Compare commits

..
Author SHA1 Message Date
Aidan Timson 832486a528 Read calendar card skeletons again once the calendar draws 2026-11-23 15:19:47 +00:00
Aidan Timson ff8d2af3da Redraw energy card skeletons once the energy settings arrive 2026-11-23 13:08:31 +00:00
Aidan Timson 4b34728744 Size energy card skeletons from the energy settings 2026-11-23 13:08:31 +00:00
Aidan Timson 4fbd53707b Draw logbook card skeletons as a date and entry rows 2026-11-23 13:08:31 +00:00
Aidan Timson c59f7051e0 Add data card skeleton guidance to the loading skill 2026-11-23 13:08:31 +00:00
Aidan Timson 261bfdbd91 Show energy card skeletons sized like their content 2026-11-23 13:08:31 +00:00
Aidan Timson b1ac178bf2 Show card feature skeletons while their data loads 2026-11-23 13:08:31 +00:00
Aidan Timson ba556cb1a5 Show to-do, weather and logbook skeletons while data loads 2026-11-23 13:08:31 +00:00
Aidan Timson 69230e6990 Show chart, calendar and map skeletons while data loads 2026-11-23 13:08:31 +00:00
Aidan Timson 724e4b9c3e Add a controller that tells the nearest skeleton when loading 2026-11-23 13:08:31 +00:00
Aidan Timson 179275128c Add card skeleton guidance to the loading skill 2026-11-23 13:08:31 +00:00
Aidan Timson 20ef3e4c73 Add a card skeletons gallery page 2026-11-23 13:08:30 +00:00
Aidan Timson ae80037739 Show card and badge skeletons while their code loads 2026-11-23 13:08:30 +00:00
Aidan Timson 7bb23aefce Remember how tall skeleton content was between loads 2026-11-23 13:08:30 +00:00
Aidan Timson 45d683f94f Fade in editors, onboarding and tile text after their skeletons 2026-11-23 13:08:30 +00:00
Aidan Timson 7682955a22 Use the shared skeleton and fade in the backup summary 2026-11-23 13:08:30 +00:00
Aidan Timson f8f0735ead Fade in logs after their skeletons 2026-11-23 13:08:30 +00:00
Aidan Timson de81d1edc3 Fade in data tables and device cells after their skeletons 2026-11-23 13:08:29 +00:00
Aidan Timson 532a107ab5 Add a shared fade for content that replaces a skeleton 2026-11-23 13:08:29 +00:00
Aidan Timson a3e967d915 Name the skeleton overlay before translations load 2026-11-23 13:08:29 +00:00
Aidan Timson 5adf777686 Add skeleton overlay guidance to the loading skill 2026-11-23 13:08:29 +00:00
Aidan Timson b3deb6bcd0 Add a skeleton overlay that reads its shape from the content 2026-11-23 13:08:29 +00:00
Aidan Timson 79953faee9 Move loading guidance into a loading skill 2026-11-23 13:08:25 +00:00
Aidan Timson 46ffa7b4dd Slant the skeleton wave from the top corner of the content 2026-11-23 10:05:08 +00:00
Aidan Timson 5467d41548 Run the skeleton wave across the content in one continuous loop 2026-11-23 09:20:18 +00:00
Aidan Timson 2fb86f3790 Make one shared soft wave the default skeleton effect 2026-11-23 09:20:11 +00:00
Lazizbek Ergashev ebd2842493 Sort solar forecast points by time (#56059) 2026-11-23 06:32:20 +00:00
renovate[bot]andSimon Lamon 177eaff888 Update formatjs (#56050)
* Update formatjs

* Push test

* Downgrade datetimeformat

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Simon Lamon <[email protected]>
2026-11-23 08:22:27 +02:00
renovate[bot] 02a580815b Update release-drafter/release-drafter action to v7.11.0 (#56069)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-23 08:20:19 +02:00
renovate[bot] b9c454e99b Update peter-evans/create-pull-request action to v8.1.3 (#56067)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-23 06:53:39 +01:00
renovate[bot] b5d65cd8e0 Update home-assistant/actions digest to 07f46fd (#56066)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-23 06:53:14 +01:00
renovate[bot] ec2f78471c Update dependency github/gh-actions-lock to v0.5.1 (#56065)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-23 06:52:58 +01:00
renovate[bot] 9eb51a8c06 Update dependency github/gh-actions-lock to v0.5.0 (#56057)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-22 11:34:01 +02:00
renovate[bot] d32d637ba3 Update dependency @webcomponents/scoped-custom-element-registry to v0.0.11 (#56056)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-22 08:18:19 +02:00
renovate[bot] 113f90eb8d Update vitest monorepo to v5.1.1 (#56053)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-21 14:27:02 +02:00
renovate[bot] c66d41d84b Update dependency intl-messageformat to v12.2.0 (#56049)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 17:29:35 +02:00
renovate[bot] 76d225f5ce Update dependency maplibre-gl to v6.19.0 (#56047)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 17:29:25 +02:00
WendelinandClaude Opus 5.5 6eef60dc57 Add hac-spinner and name loading spinners for screen readers (#56030)
* Give ha-spinner a translated, overridable accessible name

wa-spinner always names its progressbar with an untranslated "Loading" and ignores the host's aria-label, so every spinner was announced in English and labels set by callers never reached screen readers. Render the same template, but use the host's aria-label when given and the translated "Loading" otherwise.

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

* Translate spinner labels in the data disk and card/badge editors

These aria-labels were hard-coded English. They had no effect before, but ha-spinner now exposes them, so they must be translated.

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

* Document how to label ha-spinner in the gallery

Explain that spinners are announced as "Loading" by default, how to name what is in progress, and to use ha-button loading for button actions.

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

* Translate the loading label in the gallery

The gallery's stand-in localize echoes unknown keys, so spinners there were named "ui.common.loading".

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

* Use accessibleLabel to name ha-spinner

Match ha-input, ha-badge and the Web Awesome components, which take accessible-label. Taking aria-label put the name on the role-less host as well as on the progressbar, and overrode the native ariaLabel property.

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

* Make ha-spinner a standalone component

ha-spinner extended wa-spinner but replaced its template, so it only used the base for its styles. Make it a plain LitElement with the same template, look and API (size, accessible-label, --ha-spinner-* variables), and improve its accessibility:

- aria-hidden on the host is passed on to the progressbar, because in Chromium the host's aria-hidden alone doesn't keep "Loading" out of a parent's name.
- In forced colors mode, the track and arc use system colors so they stay visible.

Size presets now come from CSS, which also fixes removing size: it cleared --ha-progress-ring-size and left the old preset in place.

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

* Add hac-spinner and base ha-spinner on it

Move the spinner into @home-assistant/components as <hac-spinner>, with the same look and accessibility as ha-spinner: an indeterminate progressbar named with accessible-label, aria-hidden passed on to it, system colors in forced colors mode and no animation with reduced motion.

Its theme variables fall back from --hac-spinner-* to the ha-spinner variables and then the semantic tokens, like hac-card. Its default name is "Loading", which a subclass can replace.

ha-spinner stays as a subclass that only translates that default name, so existing usages keep working unchanged.

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

* Size hac-spinner without em

Resolve the size into --_size and use it directly, instead of setting it as the font size and measuring in em, which the codebase doesn't use.

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

* Fix tests and gallery build for hac-spinner

Vitest didn't use the ha-source export condition, so it resolved @home-assistant/components/spinner/scoped to the unbuilt dist and every test importing ha-spinner failed. Use the condition like tsconfig.json and the app build do.

The gallery turns markdown into a template literal, so the ${} in the spinner page's code example was evaluated and broke the gallery build and type check. Show the attribute form instead.

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

* Keep ha-spinner's sizing, hiding and legacy variables

Address review feedback on hac-spinner compatibility with ha-spinner:

- A size preset wins over --ha-spinner-size again, as when ha-spinner set it inline, so a theme-wide value can't resize a tiny spinner.
- hidden is !important, as in Web Awesome, so it still hides a spinner styled with display: block.
- --indicator-color, --track-color and --speed set on the element work again; like --track-width they are set on the host, so ancestor values don't leak in.

Also hide the ZHA add devices spinner from screen readers, since the heading above it already says the same.

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

* Keep the base part and tidy spinner docs

Expose the svg as part base too, like wa-spinner did, so ha-spinner::part(base) styles from custom cards keep matching. Fix the ha-spinner doc comment, where accessible-label isn't "as before", and drop the gallery sentence the Accessibility section already covers.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-20 15:38:19 +01:00
Clément Notin b2efa6f989 Disable Corepack download prompt in devcontainer (#56038) 2026-11-20 12:34:05 +01:00
Misha Hawthorn 98cc0046f4 Don't animate camera image spinners while off-screen (#56043)
hui-image only fetches a camera snapshot once its card scrolls into view, but it rendered the loading spinner regardless. An off-screen camera card therefore kept an infinite spinner animation running, forcing a style, layout and paint update every frame. With several cameras below the fold this pinned a CPU core in the iOS/macOS companion app's web view.
2026-11-20 09:45:13 +00:00
renovate[bot] e37bce3277 Update dependency @rspack/core to v2.3.3 (#56045)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 09:36:38 +00:00
Lex PostmaandClaude Opus 5.5 26c8e6db15 Announce the selected button in ha-button-toggle-group (#56042)
The toggle group only showed the active button through its colour, so
screen readers could not tell which option was selected.

ha-button now forwards aria-pressed to its inner button, the element that
gets focus, in the same way wa-button forwards aria-label. The toggle group
sets it on each button, inside the existing wa-button-group role="group".

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-20 09:35:24 +00:00
Lex PostmaandClaude Opus 5.5 160cfc7828 Nest the Status filter options in pairs and tick the areas of a ticked floor (#56032)
* Nest the Status filter options like floors and areas

The Status filter of the entities page lists its opposite options under a
row for each pair, like areas under their floor in the Areas filter: Available
and Unavailable under Availability, Enabled and Disabled under Activation, and
Visible and Hidden under Visibility. A pair row ticks or unticks both, and is
partly ticked while only one of them is. Every option has an icon, matching
the status column and the actions for the selected entities.

Available and Unavailable are now exact opposites: entities without a state,
which are the disabled ones, count as unavailable. The hidden Availability
column, used for grouping and sorting, matches the filter.

In the Areas filter a ticked floor shows its areas ticked. Unticking one of
them keeps the others and leaves the floor partly ticked, and ticking the last
area of a floor picks the floor again. The filter value and its links don't
change. Only the list scrolls now, instead of the list and its container.

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

* Untick listed areas of a floor and keep empty states available

Unticking an area of a ticked floor kept it ticked when an older filter
value listed the floor and that area. An entity with an empty state,
such as a cleared text helper, counted as unavailable.

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

* Match a floor and all its areas the same, and count floor targets per area

On Automations and Scripts, ticking every area of a floor picks the floor,
whose search also finds what targets the floor directly, while a search for
each of its areas doesn't. So the same ticked checkboxes could give
different results.

- The Areas filter now looks a picked floor up as its areas, so a floor and
  all its areas always match the same.
- An automation or script that targets a floor counts for each area on that
  floor, as it acts on all of them. Ticking only the Kitchen also shows the
  automations that target the whole ground floor.
- To tell what targets a floor itself, the floors of the picked areas and
  their other areas are looked up too, for automations and scripts only.
  Other tables have nothing that targets a floor directly.
- The value stays `{ floors, areas }`, so links and stored filters keep
  working.

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

* Find what targets a floor only when the whole floor is picked

Telling what targets a floor directly by taking out what its areas' searches
find missed automations and scripts that target a floor and also name one of
its areas. Search results can't tell those apart, so floors are looked up
whole again: a floor, or a floor whose areas are all picked, uses the floor
search, which also finds what targets the floor itself. Areas picked without
their whole floor use the area search.

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

* Look the floors and areas up again when they change

Whether a floor is picked whole depends on which areas it has, so when an
area is added to a floor or moved to another one, the Areas filter looks
its picks up again instead of keeping the items of the old layout.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-20 09:24:30 +00:00
renovate[bot] 46db541153 Update dependency typescript-eslint to v8.73.0 (#56036)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 08:23:46 +02:00
renovate[bot] 4d8eca2229 Update dependency marked to v18.2.1 (#56034)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-19 20:38:23 +01:00
renovate[bot] 7fff78c391 Update dependency browserslist to v4.29.6 (#56033)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-19 20:38:16 +01:00
renovate[bot] b2405df91b Update dependency home-assistant-js-websocket to v9.9.0 (#56031)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-19 20:25:43 +02:00
Petar Petrov 01dac9b1e7 Exclude states after the selected end from history export (#56024) 2026-11-19 17:30:59 +01:00
Bram KragtenandClaude Opus 5.5 ca5eed92b8 Show the energy collection key prefix in the card editors (#56025)
* Show the energy collection key prefix in the card editors

The collection key of energy cards must start with "energy_", which
users had no way of knowing. The editors now show "energy_" as a fixed
prefix in the field, so only the part after it is typed.

ha-input gets inputPrefix and inputSuffix. With a label, a prefix uses
the inset label layout of the entity ID field. The text selector, the
multi input, the dialog box and the entity ID field now use them
instead of their own slotted spans.

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

* Always add the collection key prefix

Only adding "energy_" when it was missing rewrote a valid key such as
"energy_energy_custom" to "energy_custom" whenever another field in the
editor changed.

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

* Keep an empty collection key on the default collection

An empty collection key means the default collection, but editing any
other field in the editor saved it as "energy_", a separate collection.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-19 17:26:58 +01:00
WendelinandClaude Opus 5.5 9758bcd750 Expose label menu checked state to screen readers (#56027)
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-11-19 17:07:42 +01:00
Erwin DounaandCopilot Autofix powered by AI 16103b7759 Suggest energy meters that aren't configured (#55735)
* Suggest energy meters that aren't configured

* Address review feedback

* Address review feedback

* Simplify energy meter suggestions

* Offer individual device for gas and water suggestions

* Fix grid pairing and dismiss sync

* Open the source editor from a suggestion

* Keep pending dismissals across subscription updates

* Address review feedback

* Refactor gas unit class condition for suggestions

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

* Revert "Refactor gas unit class condition for suggestions"

This reverts commit 38b26e46a2.

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-19 17:18:45 +02:00
Bram KragtenandClaude Opus 5.5 3bd7c6363b Add ha-list-item-switch for settings rows with a switch (#56023)
* Add ha-list-item-switch for settings rows with a switch

The whole row is the label of the switch, so clicking anywhere on it
toggles the switch and the row text names it for screen readers. Rows
that only had a switch at the end now use it instead of an ha-switch
with a hand-written accessibleLabel.

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

* Name switch rows by their headline only

The switch in ha-list-item-switch was named by its whole label, so the
supporting text became part of the name. Use a native switch input in
the row's own shadow root, labelled by the headline and described by
the supporting text, and keep ha-switch only to show the state.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-19 16:06:07 +01:00
WendelinandClaude 0ec07be0c5 Give dashboard and to-do controls an accessible name (#56022)
Co-authored-by: Claude <[email protected]>
2026-11-19 15:41:43 +01:00
Bram KragtenandClaude Opus 5.5 848d75c5d3 Simplify the onboarding location announcements (#56017)
* Simplify the onboarding location announcements

- Announce the selected place with its display_name instead of building
  the label in a separate helper.
- Route list and marker clicks through one _selectPlace.
- Show the plain no-match text in the empty results row, like pickers
  do, so the search term doesn't need its own state.
- Drop aria-busy on the results list.
- Don't search on Enter in an empty field.

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

* Remove unneeded comment

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-19 15:27:56 +01:00
WendelinandClaude b88233031e Give automation editor checkboxes an accessible name (#56019)
Give automation editor switches and checkboxes an accessible name

The optional field checkboxes in actions, triggers, conditions and
integer form fields, the target picker selection checkbox and the
automation state switch in the automation list had no accessible
name. Label each with the field, target or automation name.


Claude-Session: https://claude.ai/code/session_018Kv7eJ7eDkVF2sM4WjguEm

Co-authored-by: Claude <[email protected]>
2026-11-19 15:27:29 +01:00
Maarten Lakerveld 50ebbf9a49 Give dialogs an accessible name for screen readers (#56003)
* Give the more-info and Assist dialogs an accessible name

Add accessibleLabel to ha-adaptive-dialog and ha-bottom-sheet. The bottom
sheet passed aria-labelledby="ha-dialog-title" to wa-drawer, but that id
lives in another shadow root, so sheets had no name even with a header
title. Pass the title text as the drawer label instead.

Label more-info with its visible title and Assist with "Assist".

* Give the remaining dialogs an accessible name

Dialogs that put their title in a slot or a custom header now pass it as
accessibleLabel: the dashboard editors, the media dialogs, the config
flow, add automation element, the quick bar, and a few config dialogs.

ha-drawer gets accessibleLabel too, so the mobile sidebar and the
notification drawer are named.
2026-11-19 14:11:55 +00:00
Maarten Lakerveld f09e39fcbe Make the onboarding location search usable with a screen reader (#56005)
Enter on a search result or in the country picker no longer finishes
the step: the host-wide Enter listeners in onboarding-location and
onboarding-core-config are gone, so only the Next button saves.

A polite status region announces the result count, no results, and the
selected place. The visible "No results" text is localized.

The search field becomes readonly instead of disabled while searching,
so it keeps focus. Pressing the search or detect button moves focus to
the field with select(), because focus() on ha-input is a no-op while
its slotted button holds focus, and the button is replaced by a spinner.
2026-11-19 14:11:38 +00:00
WendelinandClaude 300ffc051f Give data table selection checkboxes an accessible name (#56015)
The select-all checkbox in the header and the selection checkbox in
each row had no accessible name. Label the header checkbox "Select
all" and each row "Select {name}" from the row's main column, with
"Select row" when the main column has no plain text value.


Claude-Session: https://claude.ai/code/session_018Kv7eJ7eDkVF2sM4WjguEm

Co-authored-by: Claude <[email protected]>
2026-11-19 14:10:56 +00:00
WendelinandClaude Opus 5.5 c4dfc3910f Give settings switches an accessible name (#56014)
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-11-19 14:50:42 +01:00
Maarten Lakerveld 5a528df3e3 Move header controls out of card headings (#56004) 2026-11-19 14:31:56 +01:00
Maarten Lakerveld cd87fc7ca1 Make card picker tiles keyboard and screen reader accessible (#56006) 2026-11-19 14:20:54 +01:00
Maarten Lakerveld 203bbb194f Label unlabelled icon buttons (#56007) 2026-11-19 14:18:39 +01:00
Maarten Lakerveld cdc875fc13 Put the mobile tab bar after the page content in focus order (#56002)
On narrow screens the subpage tabs sit at the bottom of the screen but
came before the content in the DOM, so keyboard and screen reader focus
jumped from the header to the bottom bar and back up. Render the bottom
bar after the content and FAB so focus follows the visual order.

Both tab bars are now a labelled nav landmark, so screen reader users
can still jump straight to the tabs without going through long lists.

fixes #14117
2026-11-19 12:49:38 +00:00
Bram KragtenandClaude Opus 5.5 3ba51a8ef2 Fix outdated demo themes (#56011)
The teachingbirds, kernehed and jimpower themes are dark themes, but
the demo applied them as light themes. Only the few variables they set
turned dark, so newer variables (text colors, inputs, dropdowns) stayed
light, giving black text on dark cards. Custom demo themes now declare
whether they are dark and are registered like a theme with only a dark
mode, so the app keeps them dark when it applies the theme again. They
also get a primary palette generated from their primary color, so
buttons, switches and checkboxes follow the theme. Variables that no
longer exist are removed, as is a black divider color that does not
show on a dark background.

Jimpower wrapped its picture elements cards in a bundled copy of the
archived card-modder, which could not load the lazy loaded card and
showed errors instead. Its styles are now ha-card theme variables, so
card-modder and card-tools are removed. The background these wrappers
set was always covered by the card images.

Arsaboo had an empty theme and now uses the default theme, like the
sections and home demos.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-19 12:17:21 +00:00
Bram KragtenandClaude Opus 5.5 52702f4a2b Make the demo dashboard editors work (#56010)
The home demo dashboard uses the custom:demo-home strategy, which did not
expose the editor of the home strategy it wraps, so its edit dialog only
offered YAML. The security page could not save because
frontend/set_system_data was not mocked.

Keep frontend system data per key for the session in the demo stub, and
notify subscribers on save. This also fixes the subscription returning the
core data for every key.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-19 12:14:37 +00:00
e31b404177 Rebrand Home Assistant Cloud to Home Assistant Link (#55231)
* Rename Home Assistant Cloud to Home Assistant Link

* Update the Nabu Casa logos to the new branding

* Use the Nabu Casa mark for Home Assistant Link icons

* Size the Nabu Casa logo by height in the voice assistant setup

* Rename the remaining Cloud integration error to Home Assistant Link

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

* Use the link icon for Home Assistant Link

* Update the Home Assistant Link description in settings

---------

Co-authored-by: Bram Kragten <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-19 12:54:50 +01:00
Paul Bottein 9338b91f18 Show the integration type in the entity type list (#55958) 2026-11-19 10:00:51 +00:00
Jan Bouwhuis b41693b8d2 Move dragged network graph nodes without layout animation (#55993)
* Move dragged network graph nodes without layout animation

* Keep the position of a node dragged without layout animation on a new layout run
2026-11-19 09:55:22 +00:00
Chanelle 407cf9e6a4 Give the onboarding welcome cards a button role (#55999) 2026-11-19 09:45:16 +00:00
Petar Petrov 02aacd0c51 Recover from a used or expired auth callback URL (#55989)
Drop a stale auth callback instead of retrying it on every reload
2026-11-19 07:03:20 +01:00
renovate[bot] f80d578deb Update dependency lint-staged to v17.6.1 (#55995)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 19:20:34 +00:00
Bram KragtenandClaude Opus 5.5 67297d7806 Add the link My redirect for Home Assistant Link (#55954)
Home Assistant Cloud becomes Home Assistant Link in 2026.12, so the My
link gets the new key link. cloud stays for existing links and badges,
and for my.home-assistant.io, which keeps sending instances to cloud for
now. link comes first so the "m" shortcut creates links with the new key.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-18 20:13:32 +01:00
renovate[bot] 46204a1955 Update dependency barcode-detector to v3.2.4 (#55992)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 17:38:27 +02:00
Jan-Philipp BeneckeandCopilot Autofix powered by AI 04ab43929e Show update release notes messages in the more info dialog (#55388)
* Show update release notes messages in the more info dialog

* Replace message display with ha-markdown component

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

* Add RTL support for message display in ha-markdown component

* Add language parameter to updateReleaseNotes function

* Fix position

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-18 06:47:54 +01:00
Erwin Douna 10b7f5ffb6 Move database analyze to the Storage page toolbar (#55982)
* Move database analyze to the Storage page toolbar

* Load the database report once recorder is available
2026-11-18 00:10:47 -05:00
Erwin Douna cce6a720f3 Show integration icons in the startup details (#55981)
* Show integration icons in the startup details

* Use ha-domain-icon in startup details
2026-11-17 14:10:45 +01:00
Maarten Lakerveld c8f6a9ef77 Revert "Let users hide entities from the maintenance page (#55610)" (#55979)
This reverts commit 49e5220634.
2026-11-17 12:27:02 +01:00
Raman GuptaandClaude Opus 5.5 94bd98d78d Call debounce immediately on the first call after cancel (#55963)
cancel() cleared the timer but kept its id, so with immediate=true the
next call saw a pending timer and was delayed by the wait instead of
firing on the leading edge.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 11:53:06 +01:00
Erwin Douna 0904c2a547 Show startup progress while Home Assistant starts (#55834)
* Show startup progress while Home Assistant starts

Replace the startup toast that named the longest running integration with a compact progress card: phase, integrations set up out of scheduled, and expandable details for active, failed and retrying integrations. Completion is only shown once Core is running.

* Address startup progress review feedback

Use a native toggle button with aria-expanded, mirror the centering in RTL, raise secondary text contrast, consume localize from context and keep listening after dismiss so the completion toast is accurate.

* Keep startup progress clear of toasts

Only offer the integrations action to admins, announce only phase and issues, lift the toast stack above the card and reattach the card after the launch screen swap.

* Move startup details into a dialog

* Handle older cores and late snapshots in startup progress

* Follow the new startup progress payload

* Make the startup toast minimal

* Add fallbacks to the startup toast
2026-11-17 11:39:36 +01:00
Raman GuptaandClaude Opus 5.5 2fd66939e7 Limit fraction digits in formatNumber to what Intl supports (#55968)
To keep trailing zeros, a numeric string's decimal places were used as
the fraction digits, and Intl.NumberFormat throws a RangeError for more
than 100. Cap them at 100.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 11:31:46 +01:00
Matthias AlphartandClaude Fable 5.2 5e340cb4e5 Fix automation editor crash when a condition row holds a service action (#55959)
Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-17 11:29:28 +01:00
Raman GuptaandClaude Opus 5.5 8b2dc28d0f Fix groupBy for keys that exist on Object.prototype (#55964)
Grouping into a plain object made `key in result` true for keys such as
constructor or toString, so push was called on the inherited function
and threw, and a __proto__ key replaced the result's prototype. Group
into a Map and convert it with Object.fromEntries instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:28:36 +01:00
Paul Bottein 8d933e85d4 Add range selection and highlight to charts (#55472)
* Add range selection and highlight to charts

* Keep range selection on release outside the chart and simplify the highlight

* Add range selection examples to the statistics chart gallery page

* Unify chart selection with a fade mask and a clear button in the gallery

* Move chart selection and highlight into ha-chart-base

* Clear stale chart masks after a data update

* Make chart selection opt-in with select-mode and cache the mask color

* Keep drag to zoom when the chart select mode is point

* Only add empty chart mask areas once a mask was shown

* Set the mask flag where the mask is applied and skip hidden statistics when snapping
2026-11-17 08:50:22 +01:00
Raman GuptaandClaude Opus 5.5 b93869e668 Fix IP address validation for leading zeros and embedded IPv4 (#55972)
IPv4 octets accepted leading zeros such as 010.1.1.1, which the backend
rejects. The IPv6 pattern also missed addresses ending in dotted IPv4
after five or six groups, such as 1:2:3:4:5:6:1.2.3.4. Build the IPv6
pattern from the RFC 3986 grammar, which covers every IPv4 suffix form
and reuses the stricter IPv4 octet.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:13:01 +02:00
Raman GuptaandClaude Opus 5.5 bfd511deaf Quote CSV values that contain line breaks (#55965)
csvSafeString only quoted values containing a comma or quote, so a
logbook message or state with a line break split its row in the
exported CSV.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:08:56 +02:00
Raman GuptaandClaude Opus 5.5 eeec2d4662 Ignore unparsable date query params (#55971)
A history or logbook URL with a start_date or end_date that couldn't be
parsed decoded to an Invalid Date, and createHistoryLogbookUrl threw a
RangeError calling toISOString on it. Leave such dates out so the panel
uses its default range.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:08:17 +02:00
renovate[bot] 500249d996 Update pnpm to v12.21.0 (#55978)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 08:31:11 +02:00
Norbert Rittel a4157a490d Change "Power sources (graph)" to "Power profile (graph)" (#55951)
Change "power sources (graph)" to "power profile (graph)"
2026-11-17 08:18:59 +02:00
Raman GuptaandClaude Opus 5.5 d24ec6d34f Parse animation duration units regardless of case (#55970)
CSS units are case-insensitive, but only lowercase s and ms were
recognized, so 3S was read as 3 ms and 300Ms as 300 seconds.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:07:54 +01:00
Thomas van TilburgandCopilot Autofix powered by AI bef72ec5da Allow selecting a sensor for battery capacity (#55713)
* Allow selecting a sensor for battery capacity

* Update accessible label for battery capacity input

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-17 08:07:40 +02:00
Raman GuptaandClaude Opus 5.5 87add82ad0 Uppercase first letters outside the BMP in capitalizeFirstLetter (#55967)
charAt(0) returns only the high surrogate of a letter outside the BMP,
which has no uppercase form, so the letter was left unchanged. Use the
first code point instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:06:27 +01:00
Raman GuptaandClaude Opus 5.5 eb70761886 Show the next unit in bytesToString when rounding reaches it (#55974)
The unit was picked before rounding, so a value just below a unit
boundary, such as 1048575 bytes, rounded to 1024 KB instead of 1 MB.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:05:05 +01:00
Raman GuptaandClaude Opus 5.5 74a2d3636b Transliterate Cyrillic х as kh in slugify (#55973)
х was also listed in the single-character map, which runs first and
replaced it with h, so its kh entry in complex_cyrillic was never used.
Remove it from the single-character map.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:03:22 +01:00
renovate[bot] f03740c446 Update Playwright (#55976)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 07:00:37 +01:00
renovate[bot] 4873df0df6 Update dependency eslint to v10.15.0 (#55977)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 07:00:21 +01:00
Erwin Douna d08b734afd Add database usage card to the storage page (#55659)
* Add database usage card to the storage page

* Address database usage card review feedback

* Open settings for disabled entities and use theme color variables

* Address review feedback on the database card

* Analyze the database on request

Follow the reworked recorder/database_usage response: separate entities and statistics, nullable tables, free and WAL bytes.

* Only make rows with entity settings clickable
2026-11-16 21:21:35 +01:00
renovate[bot] 4d1fc1225d Update dependency serve to v14.2.8 (#55956)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 20:33:48 +02:00
Dusan Cervenka 18bcddaa20 Use each light's Kelvin range in the service color temperature slider (#55947)
* Use each light's Kelvin range in the service color temperature slider

The light turn-on action advertised one 2000-6500 K slider for every
light, so a device with a different range could not be set from the
automation editor. The slider now follows the targeted lights.

* Limit the Kelvin slider to the lights an action actually calls.

The optional color temperature field now starts inside that range. The adjustment stays on light.color_temp_kelvin, and an area target no longer includes a light assigned to another area.

* Ignore secondary lights and normalize entity ids in the Kelvin range.

Service calls skip hidden and categorized lights reached only through an area or device, and legacy entity ids can be comma-separated or mixed-case.

* Use targeted entity ranges inside the color temperature selector.

The service form already supplies those entities, so the slider no longer resolves targets on its own.

* Leave the stored color temperature when the slider range changes.

The selector shows the targeted lights' Kelvin bounds, and core already clamps the value a light can produce.

* Start an optional Kelvin value inside the targeted lights' range.

Checking the field creates the stored value, so it matches the slider. Later light updates leave that value alone.

* Move the optional Kelvin default into a follow-up.

The selector change stands on its own.
2026-11-16 19:04:07 +01:00
Petar Petrov ca576fadf5 Remove unused cost_adjustment_day from grid sources (#55883) 2026-11-16 17:14:55 +02:00
Petar Petrov aea1ac4ac8 Fix history graph gaps after unavailable or inactive periods (#55908)
Keep history line after unavailable gap in downsampled charts
2026-11-16 16:12:49 +01:00
starkillerOG 6e1fe2846e Only fetch 4 thumbnails concurrently (#55952)
* Only fetch 4 thubmnails concurrently

* Restart thumbnail loading after a disconnect during a fetch
2026-11-16 15:26:03 +01:00
Paulus SchoutsenandClaude Opus 5.5 17202283b4 Count camera favorites as two slots in common controls (#55913)
* Count camera favorites as two slots in common controls

A camera favorite shows as a picture card that is two rows high, so it
fills the space of two tiles. The common controls limit counted it as
one entity. The extra suggestions then went into a new row.

The limit now counts tile-sized slots. A camera uses two of them.

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

* Count favorite slots in the home editor suggested toggle

The home editor disables the suggested entities toggle when the
favorites fill the section. It counted entities, so four camera
favorites left the toggle on although no suggestions show.

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

* Fill free slots when pinned entities do not all fit

When the pinned entities use more slots than the limit, the ones that
fit can still leave a free slot. For example, two pinned cameras with
a limit of 3. The section now checks the size of the pinned entities
that fit, and fills the free slot with a suggestion.

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

* Revert "Fill free slots when pinned entities do not all fit"

When the pinned entities that fit leave a free slot, the section asks
for suggestions. If usage prediction is not loaded, the section then
shows a message or hides itself in place of the pinned entities.

When the pinned entities fill the limit, the section now shows them
without suggestions again.

This reverts commit df676dfbe5.

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

* Always show pinned entities in common controls

The limit could drop pinned entities that did not fit. If usage
prediction was not loaded, the section showed a message or hid itself
in place of the pinned entities.

Pinned entities now always show. Predictions only fill the slots that
the pinned entities leave free.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-16 14:44:24 +01:00
Petar Petrov 0c8323c4f6 Allow theming timeline colors of custom states (#55930)
* Allow theming timeline colors of custom states

States of domains without state colors now use --state-<domain>-<state>-color (or its device class variant) when the theme defines it, before falling back to the graph palette.

* Drop device class variant for custom state colors

* Restore device class variant for custom state colors
2026-11-16 14:40:01 +01:00
Bram KragtenandClaude Opus 5.5 a2a523d5e5 Ignore outdated HLS starts and fetch a fresh stream URL on restart (#55953)
A start that was still fetching the stream URL, loading hls.js or
fetching the playlist could finish after the player was hidden or
removed, and create a player nobody stops. Count clean ups the same way
the WebRTC player does and drop starts that are outdated.

Restarting after a clean up reused the old stream URL. Core resets its
access token once the stream has been idle for 30 seconds, so the
restart got a 404 and the card fell back to MJPEG. Since the companion
apps now clean up right away when hidden, this happened every time the
app was in the background for more than 30 seconds. Fetch a new stream
URL on every restart instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-16 14:51:15 +02:00
Bram Kragten b379c0d311 Stop camera streams right away when hidden in the companion apps (#55887) 2026-11-16 14:29:33 +02:00
Julian 4dc975ec23 Keep the ha-ripple press while it is still active (#55942)
Hide a mouse or pen press when it moves off the control and show it
again when it returns while still held, since releasing it there still
clicks. Ignore the context menu during a touch press so a long press
keeps its pressed state until the touch ends.
2026-11-16 13:29:16 +01:00
Tristan Milnthorp 84294d7a8f Don't count light groups in the home summary when their lights are counted (#55903)
* Don't count light groups in the home summary when their lights are counted

* Share the group member helper with the more-info dialog

* Let the group member helper own the registry lookup too

computeGroupMemberIds now reads the registry's group_entities first, then
the state's group_entities, then the state's entity_id, so the more-info
dialog and the home summary share one definition.

For more-info, the only difference is that the state's group_entities is
now tried before entity_id when there is no registry copy. Core writes the
same capability into both, so it is the same data.

* Check nested group members for listed lights at any depth

* Keep one of two listed groups that contain each other
2026-11-16 13:08:05 +01:00
e5838446c8 Redesign the cover more-info dialog (#55614)
* Redesign the cover more-info dialog

* Refine cover drawings, handle and target edge

* Fix cover position fallback, tilt percentage and cancelled drags

* Remove speed selection from the cover dialog

* Hide the cover drawing from assistive tech without position

* Clean up the cover dialog code and rework the tilt control

* Soften the cover tilt gauge

* Use a generic drawing for doors and windows and simplify cover commands

* Update the active cover favorite when the position changes

* Drop the cover request when the position changes without moving

* Fix cover request controller typecheck

Co-authored-by: piitaya <[email protected]>

* Stop registering the cover request controller on its host

* Show the selected cover mode value in the header and hold tilt requests while moving

* Show only the state in the cover header when the value is unknown

* Follow the ARIA slider convention for cover arrow keys

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: piitaya <[email protected]>
2026-11-16 12:36:51 +01:00
Christopher Pruijsen 53f000e492 Fix more info opening when releasing outside an entity row control (#55890)
* Fix more info opening when releasing outside an entity row control

A press that starts on the control of an entity row and ends on the name
made the browser send the click to the row, which opened more info or ran
the hold action. The row now drops that click.

* Let clicks without a pointer through after an unfinished control press

A control press that ends without a click left the flag set, so the next click on the row with no pointer behind it (assistive technology or element.click()) was dropped. Only pointer clicks (detail > 0) are dropped now.
2026-11-16 13:15:57 +02:00
renovate[bot] c452e8e4ff Update formatjs (#55875)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 12:12:54 +01:00
Maarten Lakerveld e80b07893d Read formatjs locale data from the new IIFE wrapper (#55950)
The formatjs patch releases in #55875 wrap each locale-data file in an
IIFE that receives the data as its argument. The extractor matched the
__addLocaleData(...) call and captured the identifier `data`, so every
build failed while parsing locale data.

Take the IIFE's trailing argument when present and fall back to the old
inline call, so the script works before and after the bump.
2026-11-16 13:01:42 +02:00
Daniel SadilekandClaude Opus 5.5 c801a52e67 Show previous values below current ones in the energy Totals table (#55897)
* Widen the energy Totals table so comparing periods fits

With "Compare data" on, the Totals table (energy-sources-table) adds the
columns "Previous energy" and "Previous cost". On the Summary view it sat
in a one-column section, and on the Gas and Water views it had 12 of 36
grid columns, so the current Energy and Cost columns were pushed out of
view behind a horizontal scrollbar.

The Totals section on the Summary view now spans two columns and the card
fills it. On the Gas and Water views, the graph and the Totals table each
take the full width, one below the other, as on the Electricity view.

Fixes #54975

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

* Show previous values below current ones in the energy Totals table

Reverts the layout changes of the previous commit. With "Compare data" on,
the Totals table (energy-sources-table) added the columns "Previous
energy" and "Previous cost", which pushed the current Energy and Cost
columns out of view in narrow cards. The table now keeps its Source,
Energy and Cost columns and shows the previous period's value as a
secondary line in the same cell, so it fits at any card width, also on
custom dashboards.

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

* Use ha-tooltip for the previous value's label

The secondary line used a native title attribute. It now uses ha-tooltip,
as the repository does for contextual hover help.

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

* Make the previous values keyboard accessible and their IDs unique

The tooltip anchors of total rows were derived from their translated
labels, which could collide in non-Latin languages. Total rows now pass a
fixed key. The previous values are focusable, so keyboard users can open
their tooltip too.

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

* Label the previous values in the table header

The previous values were explained only by a per-cell tooltip, which touch
users could not open. The Energy and Cost headers now show "Previous
energy" / "Previous cost" as a secondary line while comparing, which
works for touch, keyboard and screen readers alike. The tooltips, their
IDs and the extra tab stops are gone.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-16 10:40:44 +00:00
WendelinandClaude Opus 5.5 8ac2712e31 Keep config navigation rows named on older Android WebViews (#55949)
* Keep config navigation rows named on older Android WebViews

Since list rows only wrap the headline and supporting text in their
button, the Companion app row became a text-only button. Android System
WebView 83 (API 30) then sometimes exposes it without a name, so the
row is missing from the accessibility tree and the Android E2E test
fails to find it.

Pass the text as headline and supporting-text properties instead of
slotting it, so it is rendered inside the button itself. The
accessibility tree in current browsers is unchanged.

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

* Remove comment from config navigation list

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-16 11:39:00 +01:00
Tim Laing f7f15ae4a8 Expose color helpers to custom cards (#55935)
* Expose color helpers to custom cards

* Remove color helper documentation from README
2026-11-16 09:37:12 +00:00
HugoPeters1024 e66733186e circular slider: disable keyboard input when disabled (#55943) 2026-11-16 09:35:38 +00:00
karwosts 1e7bdbbcc8 Restore missing mobile tooltips (#55929) 2026-11-16 09:50:32 +01:00
renovate[bot] 7292db76bf Update dependency @codemirror/lint to v6.9.8 (#55940)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 09:38:26 +01:00
renovate[bot] 9d997fbe4c Update dependency jsdom to v31.0.1 (#55941)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 10:30:01 +02:00
Jan Bouwhuis 05d11c25c2 Keep dragged nodes in place in network graphs (#55808)
* Keep dragged nodes in place in network graphs

Fix the ECharts force drag order, so a node can be dragged with physics
on when layoutAnimation is off. Pin dragged nodes where they are dropped
and keep their positions through re-renders. Count only nodes of visible
legend categories for the layoutAnimation threshold.

* Keep pins through legend changes, clicks and chart recreation

Write the pin and position of a dropped node into the ECharts item option,
so a legend re-layout keeps them. Pin a pinned node again after a click,
and render again when the chart is recreated, e.g. after a theme change.

* Move only the dragged node with reduced motion

With reduced motion, a drag no longer runs the force layout, so only the
dragged node moves. A new force option of our ECharts patch, dragAnimation,
tells this apart from layoutAnimation, which is also off above 100 nodes.

* Drop the ECharts drag patch

Restore the ECharts patch and the lockfile to dev, and remove the
dragAnimation option. Dragging with physics on and without layout
animation is an ECharts issue to fix upstream.

* Render on legend changes only when the layout animation flips

The legend lays the graph out again itself, so the hidden categories are
no longer reactive. Only a change of the layout animation threshold saves
the positions and renders. Keep the private ECharts series access in one
helper.
2026-11-16 10:02:31 +02:00
Christopher Pruijsen ec14a9fe39 Fix horizontal scroll on the backup location page on narrow screens (#55934) 2026-11-16 08:52:27 +02:00
renovate[bot] fc640e236d Update dependency fullcalendar to v7.1.5 (#55933)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 06:15:28 +01:00
renovate[bot] c2db01285c Update github/codeql-action action to v4.39.3 (#55938)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 06:14:33 +01:00
Petar Petrov f2d0da08ed Edit batteries measured per direction (#55606)
* Edit batteries measured per direction

The battery editor first asks what the battery measures: only the total
in and out, or separately for grid, solar and home. Per direction shows
an energy and an optional power sensor for each flow, offers Integral
helpers for power-only flows, and warns when a flow's source is missing.

* Hide a battery's generated power sensor from its total power pickers

Switching a battery to another power setup removes its generated net
power sensor, so it can't be picked as the new power sensor.
2026-11-15 21:22:40 +01:00
Simon LamonandPetar Petrov 502dcdc1a6 Fix getWeatherExtrema when either is 0° (#55687)
* Fix getWeatherExtrema when either is 0°

* Update src/data/weather.ts

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

* Simplify tempLow assignment conditions

Refactor temperature low assignment logic in weather.ts

* Prettier

* Apply suggestion from @MindFreeze

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

---------

Co-authored-by: Petar Petrov <[email protected]>
2026-11-15 17:19:50 +02:00
renovate[bot] 0d31ae5624 Update dependency @rslib/core to v1.0.7 (#55925)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 14:24:47 +01:00
renovate[bot] f57384a265 Update dependency glob to v14.0.6 (#55926)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 14:24:40 +01:00
Tom Carpenter 4fe20d7712 Show Day of Week on Energy Period Selector card (#55924)
Show Day of Week on energy period selector card

When a single date is displayed, include day of week in the text.
2026-11-15 14:52:25 +02:00
Yosi LevyandCopilot Autofix powered by AI 14a4c05130 Marquee RTL support (#55876)
* Marquee RTL

* Refactor _animationFactor to a getter

Refactor _animationFactor to be a getter that determines its value based on document direction.

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-15 12:49:43 +00:00
Petar Petrov 2d6ebd26d9 Use measured battery flows on the energy dashboard (#55604)
* Move energy settings from dialogs to an editor sidebar

Sources and devices on all energy configuration tabs now open in a
sidebar like automation steps, with the selected row highlighted and a
save button for unsaved changes. Cost tracking and power measurement type
use dropdowns, and the editor inputs are grouped with dividers. The energy
setup wizard keeps its dialogs, which now reuse the same editors.

* Read the energy editors' data from contexts

The energy editors, the power measurement config and the upstream device
picker consume contexts instead of hass, so the setup wizard dialog no
longer passes it. createConfigFlow, handleConfigFlowStep and
getSensorDeviceClassConvertibleUnits take callApi or callWS.

The sidebar slots the editor in, so switching to the bottom sheet keeps
unsaved changes, and the lists are inert while the editor saves.

* Confirm unsaved energy edits on the back arrow

The toolbar back arrow asks before discarding the editor's changes, like
the automation editor does, and the sidebar is inert while the editor
saves, like the lists.

* Edit energy sources and devices on pages of their own

Sources and devices open on a page with a back arrow, their name as the
title and the form in a card, instead of in a sidebar. The lists go back
to the centered column, and the energy setup wizard keeps its dialogs.

* Keep energy page saves and deletes apart

Save and Delete are disabled while the other runs, since both write all
preferences, and a page that was left no longer navigates when its save
or delete finishes.

* Use measured battery flows on the energy dashboard

A battery can report its energy and power per direction: grid to
battery, solar to battery, battery to home and battery to grid. The
cards now use those flows as measured and estimate only the rest, so
grid charging no longer shows up as solar charging. Batteries with
total in and out statistics work as before.

The power Sankey now shares the energy flow math, and its type links
get explicit values instead of the greedy fill.

* Describe battery totals without a destination

* Show the energy error screen when statistics fail to load

Editor pages wait for the statistics metadata, so a failed request kept
them loading forever. It now shows the panel's error screen, like a
failed preferences or validation request.

* Name unnamed per-direction batteries in the power Sankey

* Don't register removed dirty state providers again

* Keep measured flows without a meter out of the home load

A measured battery flow whose grid or solar meter isn't configured never
passed through that meter, so it no longer changes the home load. The
power Sankey passes grid and solar as unmetered when they have no power
sensor.

* Open energy items through links

The editors open on pages now, so the list rows, the add buttons and the
CO2 signal row are links that can open in a new tab. ha-automation-row
gets an optional href that wraps the icon and header in a link and keeps
the icons slot outside of it. The setup wizard still opens dialogs.

* Note that a battery needs a charge and a discharge direction
2026-11-15 09:48:14 +01:00
Adam Pyle 5ba1190cdd Use theme colours on the Cast receiver launch screen (#55879)
The launch screen hardcoded a light background and dark text, so it
stayed white when the user or the cast device used dark mode. Use the
theme variables the receiver's ThemesMixin already applies to the
document, keeping the previous colours as fallbacks.
2026-11-15 08:34:09 +00:00
Petar Petrov 81cf8050e4 Drop the hass-shaped context from the security alerts editor (#55851)
Security entity helpers take states and registries as separate values.
2026-11-15 09:23:44 +01:00
Petar Petrov 1a10982a5e Fix the category filter scope round-trip and the navigation path registries consumer (#55848)
* Keep category filter list on a quick scope round-trip

Clear the category filter only when the scope differs from the subscribed one, and consume the registries context once in NavigationPathInfoController.

* Skip navigation path re-resolves when its inputs are unchanged

Each controller compares the values it resolved with, instead of sharing a module-level areas and devices cache.

* Clear the category filter list on disconnect

A reconnect with a new scope would otherwise show the old scope's categories until the new ones arrive.
2026-11-15 09:23:07 +01:00
Petar Petrov fb8ac756ce Pass callWS to getExtendedEntityRegistryEntry (#55849)
Take callWS instead of a hass-shaped object and use the helper again in callProtectedLockService.
2026-11-15 09:19:17 +01:00
renovate[bot] 2c072ab254 Update dependency prettier to v3.10.1 (#55923)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:13:11 +00:00
renovate[bot] 31ca8c298b Update pnpm to v12.20.0 (#55922)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 09:03:19 +01:00
Jan Bouwhuis 1a5d8884ad Align MQTT subscribe card width with other cards (#55914) 2026-11-15 08:34:13 +02:00
karwosts 9a95c9dea9 Fix targetless media selector (#55921) 2026-11-15 08:34:08 +02:00
renovate[bot] 5db5f9075d Update babel monorepo to v8.1.2 (#55917)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:25:22 +02:00
renovate[bot] 6ce043a8e4 Update dependency maplibre-gl to v6.18.0 (#55920)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:25:14 +02:00
renovate[bot] d81a9f29b2 Update dependency tar to v7.5.23 (#55919)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:25:05 +02:00
renovate[bot] c39734f350 Update dependency glob to v14.0.5 (#55918)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:24:52 +02:00
renovate[bot] e65584e724 Update dependency prettier to v3.10.0 (#55910)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 19:15:42 +01:00
renovate[bot] 6641a43e43 Update tsparticles to v4.5.4 (#55909)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 19:15:17 +01:00
renovate[bot] 2706bd89a1 Update dependency vite to v8.3.8 (#55906)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 08:55:55 +02:00
renovate[bot] bd434eeb0d Update dependency @rspack/core to v2.3.2 (#55899)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 17:11:21 +02:00
Petar Petrov 16f01e1081 Fix legends fitting as narrow in the card editor preview (#55886) 2026-11-13 14:28:15 +01:00
Dan SpencerandClaude Opus 5.5 050251db23 Offer a blueprint's trigger IDs in Triggered by conditions (#55802)
* Offer a blueprint's trigger IDs in Triggered by conditions

In an automation that uses a blueprint, a Triggered by condition in one
of its inputs listed no triggers, and flagged the IDs it already used as
missing. The editor took the list from the automation's own triggers,
and a blueprint automation has only `use_blueprint`.

For a blueprint automation, fetch the blueprint with its inputs filled
in (`blueprint/substitute`) and list the IDs its triggers set, fetching
again when the inputs change. A trigger without an ID isn't offered,
since the editor can't give one to a blueprint's trigger, and an ID
shared by several triggers is listed once, as the condition matches any
of them.

The condition is in one of the blueprint's inputs, which the trigger
controller doesn't edit, so its `select` returns false there, as
`updateTriggerId` does for a trigger it doesn't own, and the condition
editor saves the pick through `value-changed` instead.

An option shows its trigger number only while trigger rows show theirs
(`showIndices`): the numbers point at trigger rows, and a blueprint
automation has none.

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

* Ignore an empty use_blueprint while editing YAML

`use_blueprint:` with no value parses to null, and requesting its
triggers threw on `.path`, aborting the editor's update.

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

* Hold back trigger warnings until a blueprint's triggers are known

While a blueprint's triggers load, or when its inputs can't be substituted
yet, a Triggered by condition can't tell a missing ID from one it hasn't
seen. The trigger context now carries optionsStatus: "loaded", "loading" or
"failed". Until it's loaded, the condition and the row's summary list the
selected IDs without the missing-trigger warning or chips. An empty
condition shows "Loading", or a hint to set the blueprint's required inputs
once substitution has failed. After a failure the last triggers stay listed.

use_blueprint is also compared by value, since YAML mode parses a new object
on every edit and an edit elsewhere fetched the triggers again.

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

* Address review: spinner, refetch warnings and index badges

- Show a delayed ha-spinner while a blueprint's triggers load, following
  the frontend's loading pattern, instead of visible "Loading" text.
- Mark every request as loading, keeping the last triggers listed, so an
  input change that renames a trigger's ID doesn't read as missing until
  the new triggers arrive.
- Publish showIndices false for a blueprint automation. Switching to YAML
  removes the manual editor's sidebar without reporting it, which left
  the blueprint's condition numbering trigger rows that don't exist.
- Drop inline comments from the blueprint trigger code.

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

* Show trigger IDs when trigger rows aren't numbered

A Triggered by condition tells options apart by description, custom ID or
index. In a blueprint automation there are no indices, so two triggers
that describe the same with generated-prefixed IDs looked identical while
selecting different IDs. Without indices, every option's ID is shown.

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

* Say when a blueprint's triggers have no IDs

A blueprint whose triggers have no IDs loads with nothing to offer, and
the condition said "Add a trigger first", which can't be done in a
blueprint automation. optionsStatus is now blueprintStatus, left out for
an automation with its own triggers, so the condition can tell the two
apart and say the blueprint's triggers have no IDs.

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

* Rename blueprint_triggers_pending to blueprint_triggers_unavailable

It's only shown once substitution has failed, not while loading.

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

* Drop controller tests that cover one-line branches

Keeps the tests for the response race, the statuses and refetching.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-13 06:26:48 +00:00
renovate[bot] 13128609de Update dependency @versatiles/style to v9.1.0 (#55893)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 08:22:31 +02:00
renovate[bot] 0f70813ada Update dependency marked to v18.2.0 (#55894)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 08:22:27 +02:00
Matthias 5762da9d22 Refresh the ingress session when the app panel becomes visible (#54863)
The ingress session is kept alive by a 60 s timer only. Timers do not run
while the device sleeps, so after the browser comes back to the foreground
the session may already be expired, and the Supervisor refuses every
request to the app until the next tick. An app that reconnects its
websocket right away stays unreachable for up to a minute.

Refresh the session on visibilitychange and resume as well. The refresh is
shared with the timer: validate the session, create a new one when that
fails, and never run twice at once. A failed refresh no longer surfaces as
an unhandled rejection, the next one retries.
2026-11-13 06:07:00 +00:00
renovate[bot] 33f709cd21 Update Node.js to v24.22.3 (#55892)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 06:54:27 +01:00
renovate[bot] 1f77e4cd59 Update dependency typescript-eslint to v8.72.2 (#55891)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 06:54:10 +01:00
Paul Bottein 77170b447f Fix favorites centering in the more info dialog (#55884) 2026-11-12 17:26:25 +02:00
c0ffeeca7 e2bb744202 MCP: change AI agent to AI app (#55885) 2026-11-12 17:25:49 +02:00
Wendelin 0eec83448a Revert camera ICE server filter and WebRTC-first memory (#55881)
* Revert camera ICE server filter and WebRTC-first memory

Follow-up to #55861 after review feedback:

- Use the full ICE server list from core again. The slow starts come from
  go2rtc, which stalls while it sets up TURN relays with the cloud ICE
  servers, so filtering in the browser does not help.
- Start HLS and WebRTC together again, remove the per-camera WebRTC-first
  memory and its 12 second HLS delay.
- Retry a WebRTC stream at most once, only after it played or on a backend
  error. A new connection that gets no answer or finds no path fails
  directly, so HLS or MJPEG takes over.

* Ignore stream URL errors of a removed HLS player

Switching cameras while the old HLS player was still fetching its stream
URL could mark HLS as failed for the new camera.
2026-11-12 14:51:53 +01:00
WendelinandClaude Sonnet 5.5 1864f6f802 Move the media browser list item to its own file (#55877)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-11-12 13:26:28 +01:00
renovate[bot] 9a19cc3bf6 Update dependency vite to v8.3.7 (#55880)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 13:24:58 +01:00
WendelinandClaude Fable 5.2 ec51fb4f8d Add attributes to wrap text in list rows (#55864)
The headline and supporting text of ha-row-item are truncated to one
line. Many pages overrode that with white-space rules on the headline
and supporting-text parts.

Add the wrap-headline and wrap-supporting-text attributes and use them
in place of those CSS overrides.

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-12 13:20:40 +02:00
Paul Bottein 6a1a9bfb1b Suggest area icons based on the area name (#55708)
* Suggest area icons from the room in the area name

* Fix stale icon list, closed dialog and AI icon override

* Keep an untouched area dialog clean after the icon prefill

* Keep the suggested section visible when a suggested icon is selected

* Move area icon keywords to the translations

* Move room keywords to a shared translation key

* Remove home cinema and gym from the room list

* Note the Lokalise draft effect of editing room keywords

* Ship room keyword drafts and group keywords under rooms.keywords

* Add more room types for area icon suggestions

* Fetch room keyword drafts through the Lokalise keys API
2026-11-12 10:51:12 +01:00
Maarten Lakerveld 16807d2765 Make "Don't show again" a checkbox on the browser warning (#55863)
As a second button it was easy to press by accident. The reminder now has a
checkbox, and "Continue anyway" applies it.
2026-11-12 09:48:17 +01:00
renovate[bot] 9caad65c91 Update dependency eslint-plugin-import-x to v4.18.1 (#55874)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 08:16:21 +02:00
Bram KragtenandClaude Opus 5.5 af523f1087 Fix Matter add device dialog stuck on the spinner (#55869)
The dialog waited for the companion app's commission finish message on
every step, but only the app's own flow sends it. Steps that commission
through core or another app now advance as soon as the device appears.
A failed finish message after the device appeared also advances now.

The new device watcher unsubscribed twice after a find, which dropped
another subscriber from the device registry collection. After a few
adds the registry stopped updating and the dialog never saw the device.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 08:12:21 +02:00
renovate[bot] 349d5f7125 Update dependency intl-messageformat to v12.1.5 (#55872)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 07:01:41 +01:00
renovate[bot] de64bd3c59 Update formatjs (#55873)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 07:01:21 +01:00
Zedas 5253eef284 Allow a few pixels of finger movement in the action handler (#55826)
* Allow a few pixels of finger movement in the action handler

* Cancel the action handler press when the browser takes over the touch

The document scroll listener only hears the page itself, not nested
scrollers. pointercancel is composed and fires when the browser starts
scrolling a touch, so it covers those as well.
2026-11-11 22:51:14 +01:00
WendelinandClaude Fable 5.2 b1164739c3 Make camera WebRTC streams connect faster and more reliably (#55861)
* Make camera WebRTC streams connect faster and more reliably

- Limit the ICE server URLs the browser uses to one STUN, one UDP TURN
  and one TCP TURN URL per host. The last retry uses the full list.
- Start WebRTC first for cameras where it worked before in this browser,
  with HLS as fallback after 12 seconds.
- Always prefer WebRTC over HLS once it plays.
- Restart a WebRTC stream up to two times when it fails, loses its
  connection or does not connect in time, then report the failure so HLS
  takes over.
- Fix the ICE candidates added to the offer.

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

* Address review and connect the microphone over the known path

- Always forget a camera when WebRTC shows no video within the deadline.
- Fall back to MJPEG when a WebRTC only camera delivers audio but no
  video.
- Keep using all ICE servers once a stream only loaded with them.
- Start the microphone connection with only the ICE servers the running
  stream needs for its path.

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

* Keep all ICE servers for a direct microphone path that needed them

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

* Improve microphone connection handling in WebRTC player

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-11 16:35:47 +01:00
Petar Petrov 80a516c673 Allow selecting values in the energy sources table (#55852) 2026-11-11 16:07:46 +01:00
Petar Petrov d5d0f45919 Move energy settings from dialogs to pages (#55410)
* Move energy settings from dialogs to an editor sidebar

Sources and devices on all energy configuration tabs now open in a
sidebar like automation steps, with the selected row highlighted and a
save button for unsaved changes. Cost tracking and power measurement type
use dropdowns, and the editor inputs are grouped with dividers. The energy
setup wizard keeps its dialogs, which now reuse the same editors.

* Read the energy editors' data from contexts

The energy editors, the power measurement config and the upstream device
picker consume contexts instead of hass, so the setup wizard dialog no
longer passes it. createConfigFlow, handleConfigFlowStep and
getSensorDeviceClassConvertibleUnits take callApi or callWS.

The sidebar slots the editor in, so switching to the bottom sheet keeps
unsaved changes, and the lists are inert while the editor saves.

* Confirm unsaved energy edits on the back arrow

The toolbar back arrow asks before discarding the editor's changes, like
the automation editor does, and the sidebar is inert while the editor
saves, like the lists.

* Edit energy sources and devices on pages of their own

Sources and devices open on a page with a back arrow, their name as the
title and the form in a card, instead of in a sidebar. The lists go back
to the centered column, and the energy setup wizard keeps its dialogs.

* Keep energy page saves and deletes apart

Save and Delete are disabled while the other runs, since both write all
preferences, and a page that was left no longer navigates when its save
or delete finishes.
2026-11-11 15:53:24 +01:00
Petar Petrov f922bc59a5 Drop hass from the state card content (#55853)
stateCardType, canToggleState and canToggleDomain take states and services; HassMediaPlayerEntity takes callService.
2026-11-11 15:36:31 +01:00
Petar Petrov a71a79b01b Drop hass from the target details dialog (#55850)
The dialog reads localize, callWS, states and entities from contexts, and resolveItemExclusions takes callWS.
2026-11-11 15:21:23 +01:00
Petar Petrov 9b8409d7ec Show model ID in the devices table when the model is missing (#55856) 2026-11-11 15:17:41 +01:00
Petar Petrov fc8d21b920 Point links in a duplicated dashboard at the copy (#55859) 2026-11-11 15:15:13 +01:00
Maarten Lakerveld fce0f4da4e Migrate the image cropper dialog to cropperjs 2 (#55570)
* Migrate the image cropper dialog to cropperjs 2

Cropper.js 2 is a rewrite built on shadow-DOM custom elements: the v1
class API (getData, getImageData, getCroppedCanvas, the ready and crop
callbacks) and the cropper.css stylesheet no longer exist, so the plain
Renovate bump (#55562) fails type checking and every rspack build.

Render the v2 elements directly from the dialog template instead of
wrapping an <img>. The canvas has no intrinsic size, so decode the file
first and give the canvas the image aspect ratio; the image then fills
it exactly. Initialise after the dialog has finished its scale-in
animation, because the elements measure themselves with
getBoundingClientRect, and refit the image and selection when the
canvas is resized.

Keep the v1 behaviour the callers rely on: the selection cannot leave
the image or the visible canvas, the image cannot be moved or zoomed out
from under it (viewMode 1), resizing stops at 50px, the rounded preview
is CSS only so the exported file stays rectangular, and the export is
rendered at the source resolution. Dirty tracking compares the crop
rectangle in source image pixels, like getData() did in v1.

* Clamp cropper drags to the edge and show image load errors

Cropper.js 2 moves the selection and image in relative steps per pointer
event. Rejecting a step that crossed the image edge dropped its movement on
both axes, so on fast drags the selection fell behind the cursor and got
stuck along an edge, mostly with portrait images. Clamp moves, resizes and
image pans to the edge instead, as v1 did. Fixed-ratio resizes shrink
around the anchored side to keep the ratio.

Show an error alert when the picture cannot be decoded instead of an empty
dialog.

* Keep the Shift-locked aspect ratio when a free crop hits the edge

With a free aspect ratio, Shift locks the ratio during a resize. The
out-of-bounds correction clipped the proposal instead of scaling it, so
the selection lost that ratio at the image or canvas edge.
2026-11-11 14:44:01 +01:00
WendelinandClaude Opus 5.5 2391c700c6 Expose action buttons in list rows to screen readers (#55831)
* Keep action controls in list rows reachable for screen readers

ha-list-item-button wrapped the whole row, including the start and end
slots, in its native button or link. Controls placed in those slots
were nested inside it and hidden from assistive technology.

Only the headline and supporting text are inside the native element now,
and its hit area is stretched over the row. Slotted controls sit above
it; icons, badges, text and empty dividers sit below, so they still
activate the row with native link behaviour.

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

* Rebind the list row ripple when the control is replaced

Switching href swaps the inner <a> and <button>, and media browser rows
drop the control when not interactive. The ripple kept listening to the
removed element, so the new control had no hover or press feedback.

Render the ripple after the control and recreate it with the control.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-11 15:26:10 +02:00
R HOCH RandCopilot Autofix powered by AI 8cd79a6776 Add button to duplicate dashboards (#55832)
* Add option to duplicate dashboards

* Add error handling for missing dashboard config

Handle config not found error when fetching dashboard.

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-11 13:25:56 +02:00
Petar Petrov b4f6e4e2ea Drop hass from the target picker (#55855)
* Drop hass from the target picker

getEntities takes an options object of separate values; ha-target-picker, ha-sources-picker, ha-selector-target and the exclusions controller consume contexts.

* Rerender the target picker only when a pending entity appears

Consume statesContext without @state and narrow a second consumer to the pending helper entity.

* Redraw target picker icons when the brands token arrives

Also refetch target selector entity sources after a reconnect, like the entity selector.
2026-11-11 11:00:13 +01:00
Lorenzo Marroccoli 50bb1cf53e Prefer model ID over firmware in integration device rows (#55845)
* Prefer model ID over firmware in integration device rows

* Include model ID in integration device search
2026-11-11 11:59:54 +02:00
Petar Petrov 70a1946874 Fix lazy context provider error and reconnect handling (#55854)
* Fix lazy context provider error and detached consumer handling

Retry failed subscriptions, drop consumers that left before the first value, and give config entry updates a new array.

* Reset config entries on a new snapshot

Replace the list when a resubscribe sends all entries again, and log failed subscriptions.

* Clear config entries on an empty snapshot

Core sends an empty list when no entries match the subscription.
2026-11-11 10:42:49 +01:00
Paul Bottein 3da9ba8119 Add default option and icons to the entity type select (#55833)
* Add default option and icons to the entity type select

* Simplify the entity type select code

* Store the device class override separately from the effective class
2026-11-11 09:57:22 +01:00
Petar Petrov eb8ac4139b Translate YAML editor error reasons (#55836)
Translate common YAML parse error reasons in the editor
2026-11-11 09:46:18 +01:00
Petar Petrov f9aae72325 Use "remove" wording when removing devices (#55835)
* Use "remove" wording when removing devices

* Keep "delete" wording for config entries
2026-11-11 09:18:30 +01:00
Christian Wiedel 81279aa6d2 Allow checking off to-do items without a name (#55847)
* Allow checking off to-do items without a name

* Keep whitespace-only names rejected by core
2026-11-11 10:08:27 +02:00
Eric RouleauandCopilot 33b8afffca Show area in ZHA device bindings and neighbors (#55812)
* Show area in ZHA device bindings and neighbors

The 2026.11 naming change means device names no longer carry
their area, but the Manage Zigbee Device panel still showed only
the device name in two places, making identically named devices
indistinguishable:

- The Bindable devices dropdown in the Bindings tab now shows
  the area as the option's secondary line.
- The Neighbors tab gains a sortable, filterable Area column.

Area resolution is shared in getZHADeviceAreaName(): it resolves
via the device registry (so child devices inherit their parent's
area, matching the ZHA network visualization) and falls back to
the area reported by ZHA itself.

* Address Copilot review: registry-authoritative area, memoize by registries

- Treat an existing device registry entry as authoritative: if it
  has no effective area, the device has no area, even if ZHA still
  reports one from its cached response. The ZHA area_id fallback
  now applies only when the device has no registry entry at all,
  so clearing a device's area no longer leaves stale area text.
- Narrow getZHADeviceAreaName() to take the area and device
  registries instead of the whole hass object, and key the
  Neighbors memo on those registries. Entity-state updates replace
  hass, which rebuilt every neighbor row and reran table
  sorting/filtering on unrelated updates.

* Use device picker for ZHA bindings

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

* Reuse getZHADeviceAreaName helper in other places that also did a similar registry lookup

---------

Co-authored-by: Copilot <[email protected]>
2026-11-11 08:46:05 +02:00
renovate[bot] b157dd174e Update dependency maplibre-gl to v6.17.0 (#55844)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-11 08:25:17 +02:00
renovate[bot] 4a0381e82d Update dependency @vvo/tzdb to v6.204.0 (#55843)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-11 08:17:15 +02:00
renovate[bot] 92e248c913 Update dependency @versatiles/style to v9 (#55846)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-11 08:15:54 +02:00
Maarten Lakerveld 5b1ecdb0b0 Let browsers below the legacy floor continue at their own risk (#55829)
* Let browsers below the legacy floor continue at their own risk

Browsers below the floor get a "Continue anyway" button on the launch
screen instead of a dead end, e.g. for a wall dashboard. The warning returns
monthly, and from the first reminder on offers "Don't show again".

* Space the launch screen without max() on Chrome below 79

The launch screen's top spacer and OHF logo margins use max() with var()
inside. Chrome below 79 drops those after the cascade, leaving no margin,
so the logo touched the bottom edge (Chrome 67 to 78 are in the legacy
floor). Plain margins now come first, the max() rules behind @supports.

* Keep the browser warning up while the app loads

Once the user continued, the launch screen went blank until the legacy
build took over, which can take a while on these devices. Keep the message
and only drop the buttons.

* Say the browser is no longer supported instead of too old

With the option to continue it does run, so "too old to run Home Assistant"
contradicted the button. The same text now reads right before and after
continuing.

* Use a plain color for the launch screen buttons

Theme variables are not set yet while the launch screen shows, so
var(--primary-color) always fell back anyway.
2026-11-10 16:53:24 +01:00
Zedas ee35dd8cf6 Send the final media player volume only once (#55828) 2026-11-10 15:04:46 +01:00
Daan VervackeandAidan Timson 42ce434a94 Add selection mode with bulk remove to the Marketplace repositories page (#55435)
* Add selection mode with bulk remove to the Marketplace repositories page

* Guard bulk remove against double clicks and drop stale selections

* Clear the table selection when a selected repository gets installed

* Restore the comments that still apply

* Use a Marketplace string for the bulk action menu

* Drop rendering-only tests

* Uncheck data table rows that can no longer be selected

* Use one Remove chip and let the table drop installed rows

---------

Co-authored-by: Aidan Timson <[email protected]>
2026-11-10 14:40:47 +01:00
Zedas 06d564dbd8 End the ZHA permit subscription when the search ends (#55822)
* End the ZHA permit subscription when the search ends

* End the ZHA search when the connection drops

* Don't send a stale ZHA search after a reconnect
2026-11-10 14:19:10 +01:00
Petar Petrov 93f0c2c45a Hold the last value across gaps in history graphs (#55817)
* Hold the last value across gaps in history graphs

* Hold values across gaps in every graph, without an opt-in

* Hold the real last state across gaps and keep their curves tight

* Only hold stretches the raw history was quiet for

* Keep the temperature forecast curving across gaps

* Decide which stretches to hold once, from the raw history

* Hold neither across unavailable states nor below the sampling frame
2026-11-10 13:53:49 +01:00
renovate[bot] fb40d07621 Update dependency @html-eslint/eslint-plugin to v0.68.0 (#55825)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-10 11:53:04 +00:00
Zedas a6073e44f7 Translate the fold markers in the code editor (#55821) 2026-11-10 11:44:59 +00:00
Paulus SchoutsenandClaude Opus 5.5 df69f3c7ee Show which integrations use an integration loaded as a dependency (#55499)
* Show which integrations use an integration loaded as a dependency

Some integrations, like Modbus, have no config flow and are loaded
because another integration lists them in its manifest dependencies.
The frontend treated these as YAML integrations. The integration page
told the user to configure it in configuration.yaml, and the dashboard
showed a YAML card for it.

The integration page now fetches the loaded manifests for integrations
without a config flow. If a loaded integration depends on the domain,
the page shows "Used by <integrations>" instead of the YAML text. The
dashboard does not show a YAML card for a domain that a loaded
integration depends on.

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

* Show the integrations that use a dependency as linked cards

Replace the "Used by" text with a "Used by" section. It lists each
loaded integration that depends on this integration, with its logo and
a link to its integration page. The entries section shows "No entries"
instead of the YAML text for such an integration.

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

* Show only the "Used by" section for a dependency

An integration that other loaded integrations depend on, and that has no
config entries, now shows only the "Used by" section. The page does not
show the empty entries section. It also does not show the "Add entry"
button, which only opens the "set up in YAML" dialog for these
integrations.

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

* Match the demo Modbus and LoRaWAN manifests to core

Modbus and LoRaWAN have no config flow, and the integrations that use
them list them as dependencies. The demo now does the same, so their
integration pages show the "Used by" section.

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

* Hide system integrations from the "Used by" section

System integrations, like Default Configuration, depend on many
integrations. Listing them in "Used by" does not help the user.

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

* Read the dependents from the manifests context

The integration page now finds the integrations that depend on it from
the shared manifests context, instead of its own manifest/list call.
It subscribes to the context only for an integration without a config
flow, so other integration pages do not make the context fetch the
manifests.

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

* Link the integration page to the integration's settings panel

The Connectivity settings panels, like Zigbee and Modbus, are not
reachable from the integration page unless the integration has a config
entry. A user that opens the integration page looks for these settings.

The integration page now shows a button that opens the panel of the
integration. The button uses the panel name from the Connectivity page.
LoRaWAN, Modbus, Radio frequency, and USB (Serial) are added to the map
of integrations with a panel.

An integration with a panel and no config flow does not show the
"Add entry" button. For these integrations, it only opens the "set up
in YAML" dialog, and the panel is where to set them up.

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

* Hide the YAML texts for integrations set up in their panel

An integration with a settings panel and no config flow, like Infrared,
is set up in that panel. Its integration page told the user to set it up
in configuration.yaml. The page now shows only the settings button for
such an integration when it has no entries.

The demo Infrared and Radio frequency manifests now match core, so these
pages show it.

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

* Make the settings button primary when it is the only action

An integration that is set up in its panel shows no "Add entry" or
"Add device" button, so the settings button is its only action.

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

* Show the settings button only when there are no entries

Each config entry row of an integration with a panel already has a
link to that panel, so the button repeats it on pages like Zigbee.

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

* Link the MCP integration pages to the AI settings

The AI settings show how to connect to the MCP server and the URL of
each of its APIs. The MCP client and MCP server integration pages now
have an "AI settings" button that opens them. The button is the
primary action when the page has no "Add entry" button.

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

* Scroll the AI settings to the MCP card from the MCP pages

The AI settings page now scrolls to the section named in the URL hash,
like the backup settings page. The "AI settings" button on the MCP
integration pages links to the MCP card, which is below the AI task
card.

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

* Keep the demo route when opening the AI settings

The demo routes with the URL hash. The AI settings page cleared the
hash even when it did not name a section, so a reload of the demo lost
the page. It now clears the hash only after it scrolls to a section.

The "AI settings" button links to the page without a section in the
demo, because a link with a hash skips the demo route conversion.

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

* Move the settings panel and MCP buttons to their own PRs

This PR keeps the "Used by" section for integrations that other
integrations depend on. The settings panel button and the MCP link to
the AI settings move to separate PRs.

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

* Load the Modbus dependents in the demo

The dashboard reads the dependencies of loaded integrations only. The
demo listed Modbus as loaded, but not Flexit, SolarEdge Modbus, and
Fronius, so it showed a YAML card for Modbus.

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

* Sort the "Used by" list and wait for it before the YAML texts

The manifests come from a set in core, so their order can change
between restarts. The "Used by" list is now sorted by name.

Until the manifests load, the page does not know the dependents. It
showed the YAML texts and "Add entry" first and then replaced them with
"Used by". The page now holds back those texts and the button for an
integration without a config flow until the manifests load.

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

* Apply review feedback

- Make the settings button primary whenever it is the only action,
  like the MCP button. Thread, or MQTT with its one entry, have no
  "Add entry" button.
- Set the demo LoRaWAN manifest to the service type, like core, so the
  demo dashboard checks its dependents.
- Fix the punctuation of the YAML text.

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

* Show the entries while the dependents load

The page waits for the manifests of the loaded integrations before it
shows the YAML texts. If that request fails, the wait never ends. Only
a page without entries can show "Used by", so only such a page waits.
A page with entries now shows them even when the manifests do not load.

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

* Clear the manifest when the integration page changes domain

The integration page is reused when you follow a "Used by" link. It
kept the previous integration's manifest until the new one loaded, so
going back to Modbus from Flexit briefly showed "Add entry" and the
empty entries section. The page now clears the manifest on a domain
change, and a page without entries waits for the manifest before it
shows the YAML texts and "Add entry".

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-10 10:55:56 +01:00
Markus TuominenandClaude Fable 5.1 95a009641f Fix integration icons being clipped into circles on the area page (#55820)
Stop rounding and distorting integration icons on the area page

The generic img rule meant for the area picture also applied to the 24px
brand icons in the device list, clipping square integration logos (for
example Awair) into circles. Scope that rule to the area picture and size
the icons with width/height attributes like the device page does.

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-10 10:17:22 +01:00
Wendelin 36f59f8495 Pass callWS to entity and device registry update helpers (#55819) 2026-11-10 11:02:12 +02:00
Stefan AgnerandClaude Opus 5.5 8a13bba521 Only match an OTBR to a Thread network it is part of (#55803)
* Only match an OTBR to a Thread network it is part of

findOTBRInfoForDataset returned the dataset's preferred border router
without checking that it is still on that network. When the border
router had moved to another network, the Thread panel offered to reset
it from the card of a network it no longer belongs to, which would
replace the border router's current network.

Require the extended PAN ID to match for the preferred border router
too, and drop the active dataset check in the network information page
that worked around the same problem.

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

* Update findOTBRInfoForDataset tests for the network check

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

* Keep findOTBRInfoForDataset fallback tests independent of key order

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-10 11:00:30 +02:00
Maarten Lakerveld cc7b1952c0 End slider and color wheel interaction when a drag is cancelled (#55804)
End slider and color wheel interaction when a pan is cancelled

ha-control-slider and ha-hs-color-picker restored their value on
pancancel without firing an event, so consumers never learned that the
interaction ended. The light color pickers then kept ignoring state
updates until the next interaction. Fire the same end-of-interaction
event as panend (and as ha-control-scrubber already does), and restore
the wheel's local value along with its cursor position.
2026-11-10 10:59:38 +02:00
karwosts 2edf6f91d0 Allow configurable time format for timer.finishes_at in state-display (#55813)
Allow custom time format for timer.finishes_at
2026-11-10 09:26:27 +01:00
jimjaeger 9d52517ae9 Retry translation fragments after a failed request (#55716)
* Retry translation fragments after a failed request

* Clear translation mock before each test
2026-11-10 08:51:58 +02:00
renovate[bot] 27a7f6335f Update dependency @vvo/tzdb to v6.203.0 (#55814)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-10 08:25:58 +02:00
renovate[bot] cd44bfcebc Update dependency eslint-plugin-import-x to v4.18.0 (#55815)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-10 08:25:55 +02:00
Elias Lecomte 8819844740 Fix single-day selection in the date range picker (#55718)
* Fix single-day selection in the date range picker

* Limit single-tap date selection to devices without hover
2026-11-10 08:23:21 +02:00
WendelinandClaude Opus 5.5 008adf1533 Move the create helper dialog and helper forms to contexts (#55794)
* Narrow helper create and area update data functions to the API they use

The create helper dialog can then pass the API context instead of the
full hass object.

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

* Consume contexts in helper forms instead of hass

The helper forms only read translations, locale and config, so they now
consume the internationalization and config contexts. This avoids
rerendering them on every unrelated hass change.

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

* Consume contexts in the create helper dialog instead of hass

The dialog reads translations, config, the API and the connection from
their contexts and no longer passes hass to the helper forms.

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

* Refactor API calls to use HomeAssistantApi for improved type safety and consistency across data handling

---------

Co-authored-by: Claude <[email protected]>
2026-11-09 20:54:31 +01:00
renovate[bot] 8c3d0f2f1e Update dependency serve to v14.2.7 (#55810)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-09 20:52:23 +01:00
renovate[bot] 3f4f89480f Update tsparticles to v4.5.3 (#55811)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-09 19:51:19 +00:00
Matthias de BaatandClaude Opus 5.5 432762a2ea Add design to the AI policy (#55795)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-09 20:45:01 +01:00
WendelinandClaude Opus 5.5 013cf8d7e6 Give automation editor rows a config path (#55801)
* Give automation editor rows a config path

Each list and row in the automation and script editor extends the path
of its ancestor with its own segment through a Lit context, e.g.
["actions", 0, "then", 1]. Rows that open in the sidebar register in a
per-editor registry by path, as groundwork to find the row a config path
belongs to, e.g. to point at an error in it.

Move the generic path type and helpers from the Lovelace editor to
common/util/config-path and use ConfigPath everywhere.

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

* Test config path helpers on their own

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-09 20:17:34 +02:00
Joost LekkerkerkerandClaude 1de489cca9 Sort device connections by type in device info card (#55797)
Claude-Session: https://claude.ai/code/session_01SLHDn4zYGvMHi4C8v3m45c

Co-authored-by: Claude <[email protected]>
2026-11-09 16:58:30 +01:00
Maarten Lakerveld 97af661779 Use the Backups menu caption as the backup page title (#55799)
The Settings > System menu said "Backups" while the page header said
"Backup". Reuse the caption key like the other system pages do, so
the two can't drift apart again.
2026-11-09 16:41:09 +01:00
Erwin Douna f702e369fc Add a health dialog to config entries (#55736)
* Add a health dialog to config entries

* Address review feedback

* Address review feedback

* Address review feedback

* Address review feedback

* Use the integration filter for the logs link
2026-11-09 16:40:04 +01:00
Maarten Lakerveld 78e0a92ddd Include disabled helpers in the helpers area filter (#55796)
The helpers table lists disabled helpers, but its area filter left them
out, so a disabled helper without an area disappeared when picking
No area, and one in an area disappeared when picking that area. Match
the entities page, which already passes include-disabled-entities.
2026-11-09 16:24:11 +01:00
Andreas d742259444 Fix stale color and slider jump after quick drag in light color pickers (#55780)
* Fix stale color sent after quick drag in light color pickers

When the color temperature slider is dragged and released within the
500 ms throttle window, the release handler skipped sending because the
picker value already equalled the final value, relying on the pending
throttled call. A state update from the leading throttled call then
reset the picker value (no longer interacting), so the trailing call
sent the stale initial value and the light ended up at the wrong color
temperature.

Cancel the pending throttled call on release and always send the final
value. Apply the same cancel to the RGB picker, where a pending trailing
call could send a stale color after the final one.

* Keep released value in light color pickers until state settles

After release, keep showing the released value for a short time and
ignore state updates in between, so that late state updates from calls
sent while dragging no longer make the slider jump back before the
final value is reported.

* Don't sync light color pickers while a new drag is active

If a new drag starts before the release hold of the previous one ends,
the hold timer must not overwrite the picker value with the reported
state, as that makes the control jump and lets a pending throttled call
send the older value. The release of the new drag starts a new hold.

* Address review: keep brightness normalization in sync, hold native input

Keep the brightness normalization of RGB-only lights in sync with the
reported state while the picker values are held (during a drag or the
release hold), as it is applied to the next color sent. Otherwise
successive color selections could dim the light repeatedly.

The native color input has no release event and sends throttled, so
refresh the release hold on every input. This keeps state updates from
calls sent while picking from overwriting the pending value.

* Use PendingValueSync in light color pickers and end interaction on release

Replace the fixed release hold timer with PendingValueSync, so state
updates are ignored only while a call is queued or in flight. Also clear
_isInteracting in the release handlers, so a keyboard adjustment or a
cancelled pan no longer stops the picker from following the state.
2026-11-09 16:22:09 +01:00
OllieandClaude Opus 5.5 623ca14356 Configure remote Bluetooth adapters from the adapters page (#55742)
* Configure remote Bluetooth adapters from the adapters page

Remote scanners such as ESPHome Bluetooth proxies have their scanning
mode and other settings in the options flow of the integration that
provides them. Show the configure button for remote adapters on the
Bluetooth adapters page and open that integration's options flow, found
through the scanner device's via device, so users no longer have to find
the device under Devices & services.

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

* Prefer the providing integration's device when finding the source entry

Other integrations may add config entries to the scanner's own device,
so look at the via device first and only fall back to the scanner's
device.

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

* Only use the via device and skip disabled source entries

Drop the fallback to the scanner's own device, which could pick up an
unrelated integration's entry, and don't offer to configure a remote
adapter whose providing config entry is disabled or has no options flow.

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

* Check for a configurable source entry in the template

Keep _getSourceConfigEntry a plain lookup, as suggested in review, and
skip the cog for disabled or non-configurable source entries where it
is rendered.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-09 16:10:41 +01:00
695 changed files with 33947 additions and 14888 deletions

No files matched your search

+2 -28
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-components
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, loading states, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
---
# HA Frontend Components
@@ -93,33 +93,7 @@ html`
## Loading States
Pick the indicator by what is loading, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/):
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`) 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-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.
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.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
```ts
html`
<ha-fade-in .duration=${300} easing="ease-in">
<div
role="progressbar"
aria-label=${this._i18n.localize("ui.common.loading")}
>
<ha-skeleton-text></ha-skeleton-text>
</div>
</ha-fade-in>
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
`;
```
Load `ha-frontend-loading` for anything that shows while content loads: skeletons, spinners, loading buttons and fades.
## Shortcuts And Tooltips
+112
View File
@@ -0,0 +1,112 @@
---
name: ha-frontend-loading
description: Home Assistant frontend loading states. Use when adding, changing or reviewing anything that shows while content loads, such as a skeleton, spinner, loading button or loading fade, or when checking how a screen looks while it loads.
---
# HA Frontend Loading
Use this skill for every loading state, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/). A loading state always ends in the content, an empty state, or an error.
## 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.
## The Wave
Every skeleton uses the same soft wave (`ha-skeleton`'s default `effect="sheen"`). It's one slanted wave across all the skeletons on the page, from the top corner of the content on the side text starts from to the opposite bottom corner, which each skeleton shows its slice of, on one shared clock. It flows from one skeleton into the next, starts its next sweep as soon as it leaves the content, and a skeleton added mid-sweep joins in rather than starting over. Reduced motion stops it.
Don't change the effect or speed (`--ha-skeleton-duration`) for one component.
## Showing A Skeleton
Make the skeleton the same shape and size as the content it stands for: one text skeleton per line of text, an icon skeleton per icon, a block per image or chart.
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}`.
- 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.
```ts
html`
<ha-fade-in .duration=${300} easing="ease-in">
<div
role="progressbar"
aria-label=${this._i18n.localize("ui.common.loading")}
>
<ha-skeleton-text></ha-skeleton-text>
</div>
</ha-fade-in>
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
`;
```
## 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. In a Lit component, add a `SkeletonLoadingController` from `src/components/skeleton/skeleton-loading-controller.ts` with a function that says whether it's loading, and it fires the events for you.
- Give the overlay a `skeleton-key` and it remembers how tall the content was once loaded, then holds that height next time. For content other than cards and badges, make one with `skeletonKey()` from `src/components/skeleton/skeleton-sizes.ts`.
- 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. From inside the content, call `refresh()` on its `SkeletonLoadingController` instead, such as after a calendar draws its month by itself.
- It gives the skeleton the `progressbar` role and the translated label itself.
## Cards And Badges
`hui-card` and `hui-badge` already wrap every card and badge in an overlay, with a `skeleton-key` from the card's config, and show a plain wave while the card's code loads. Don't add another overlay or a hand-drawn skeleton inside a card. A card that fetches data only needs a `SkeletonLoadingController`, as `hui-calendar-card` and the history and statistics charts do. Energy cards pass `loading` to `EnergyCollectionController` instead, for when they fetch more after the collection's data arrives.
## First Visit Sizes
Remembered heights only help from the second visit. For the first, render placeholders as big as the content will be, so it doesn't jump when the data arrives:
- Set `loading` on `ha-chart-base` to have the chart read as one block and its legend as one line, or as its items when the legend has them already.
- Before a chart exists, use `chartPlaceholderStyles` from `src/components/chart/chart-placeholder.ts`.
- Lists of a known length, such as the to-do list from its entity's state, draw that many hidden rows. Lists of an unknown length draw a typical few, as `ha-logbook` does with `placeholder-rows`.
- Energy cards whose layout follows the energy preferences, such as the sources table and the devices detail graph, draw it from `EnergyCollectionController.placeholderData` until their data comes. The controller updates the card when the preferences arrive. The energy dashboard itself waits for the data before it builds its cards, so check these on a regular dashboard.
## 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.
- **Hold the loading state.** Home Assistant's data comes over the WebSocket, which DevTools network throttling doesn't slow. Hold the replies back from the console instead, then open the screen from inside the app (not a reload, which drops the patch). Adjust the pattern to the messages the screen waits on:
```js
const conn = document.querySelector("home-assistant").hass.connection;
const slow = (type = "") => /^(recorder|history|logbook)\//.test(type);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const send = conn.sendMessagePromise.bind(conn);
conn.sendMessagePromise = async (msg) => {
const result = await send(msg);
if (slow(msg.type)) await wait(3000);
return result;
};
const subscribe = conn.subscribeMessage.bind(conn);
conn.subscribeMessage = (callback, msg, options) => {
if (!slow(msg.type)) return subscribe(callback, msg, options);
const due = Date.now() + 3000;
const later = (message) =>
setTimeout(() => callback(message), Math.max(0, due - Date.now()));
return subscribe(later, msg, options);
};
```
- **Cards and badges in the gallery.** The gallery's Card skeletons page (`gallery/src/pages/lovelace/card-skeletons.ts`) shows cards and badges with their skeletons, and "Simulate loading" replays the arrival. Add a card there when you change how it loads.
- **Clear remembered heights** with `localStorage.removeItem("skeletonHeights")` and reload, to see a first visit again. They're read when the page loads, so clear them before reloading, not after.
- **Check a first visit.** Clear remembered heights, reload on a screen without the content, hold the data back, then open the content from inside the app. Measure each card's height while it loads and once it has loaded: they should match. Do it at a phone width and a desktop width, as rows and legends wrap differently.
- **Compare the skeleton with the content.** It should take the same space, so nothing moves when the content arrives. Measure the wrapper's height while loading and once loaded (`element.getBoundingClientRect().height` in the console), or take a screenshot of each at the same size and flick between them. Look for pieces that are missing, extra or in the wrong place, and fix those with `data-skeleton`.
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
+1
View File
@@ -1,6 +1,7 @@
FROM mcr.microsoft.com/devcontainers/python:3.14
ENV \
COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
DEBIAN_FRONTEND=noninteractive \
DEVCONTAINER=true \
PATH=$PATH:./node_modules/.bin
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
name: Verify actions lockfile
runs-on: ubuntu-latest
env:
GH_ACTIONS_LOCK_VERSION: v0.4.1
GH_ACTIONS_LOCK_VERSION: v0.5.1
steps:
- name: Check out files from GitHub
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+17 -17
View File
@@ -18,7 +18,7 @@ workflows:
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
'.github/workflows/codeql-analysis.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
'.github/workflows/copilot-setup-steps.yml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
@@ -64,13 +64,13 @@ workflows:
'.github/workflows/relative-ci.yaml':
- 'relative-ci/agent-action@711f3a8fa1b928e6afde280011110c9b0a224a60'
'.github/workflows/release-drafter.yaml':
- 'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0'
- 'release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea'
'.github/workflows/release.yaml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
- 'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361'
- 'home-assistant/actions@07f46fd2e19967768b5fd3000f91f857452b767c'
- 'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
- 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086'
'.github/workflows/restrict-task-creation.yaml':
@@ -82,12 +82,12 @@ workflows:
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
- 'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1'
'.github/workflows/sync-sensor-entity-constants.yaml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
- 'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1'
'.github/workflows/translations.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
dependencies:
@@ -151,14 +151,14 @@ dependencies:
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
owner_id: 7513068
repo_id: 113918130
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
ref: 'v4.39.1'
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
ref: 'v4.39.3'
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
owner_id: 9919
repo_id: 259445878
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
ref: 'master'
commit: 'sha1-86d4564712fa02543c808e3a693dd04f9d3f8361'
'home-assistant/actions@07f46fd2e19967768b5fd3000f91f857452b767c':
ref: '2026.11.0'
commit: 'sha1-07f46fd2e19967768b5fd3000f91f857452b767c'
owner_id: 13844975
repo_id: 173703505
'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716':
@@ -166,9 +166,9 @@ dependencies:
commit: 'sha1-9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
owner_id: 13844975
repo_id: 184234812
'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1':
ref: 'v8.1.1'
commit: 'sha1-5f6978faf089d4d20b00c7766989d076bb2fc7f1'
'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1':
ref: 'v8.1.3'
commit: 'sha1-3ffccacd46053766916f087ce41d627c0b8cf2d1'
owner_id: 18365890
repo_id: 197176365
'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086':
@@ -183,8 +183,8 @@ dependencies:
commit: 'sha1-711f3a8fa1b928e6afde280011110c9b0a224a60'
owner_id: 43522883
repo_id: 398376354
'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0':
ref: 'v7.10.0'
commit: 'sha1-978bb0b30c5ee8cdd332ced253758157150d43f0'
'release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea':
ref: 'v7.11.0'
commit: 'sha1-d1a19e60e81a7e650d00a7de9277f87e439117ea'
owner_id: 58292376
repo_id: 139022359
+2 -2
View File
@@ -32,12 +32,12 @@ jobs:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
languages: javascript-typescript
build-mode: none
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
category: "/language:javascript-typescript"
+4 -4
View File
@@ -38,7 +38,7 @@ jobs:
name: Prepare container dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001
defaults:
run:
@@ -155,7 +155,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001 --ipc=host
defaults:
run:
@@ -207,7 +207,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001 --ipc=host
defaults:
run:
@@ -261,7 +261,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001 --ipc=host
defaults:
run:
+1 -1
View File
@@ -19,6 +19,6 @@ jobs:
pull-requests: read
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0 # v7.10.0
- uses: release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea # v7.11.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
python-version: ${{ env.PYTHON_VERSION }}
- name: Verify version
uses: home-assistant/actions/helpers/verify-version@86d4564712fa02543c808e3a693dd04f9d3f8361 # master
uses: home-assistant/actions/helpers/verify-version@07f46fd2e19967768b5fd3000f91f857452b767c # master
- name: Setup Node and install
uses: $/.github/actions/setup
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
run: pnpm exec prettier --write src/data/device_classes.ts
- name: Create pull request
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3
with:
branch: chore/sync-device-classes
commit-message: Update device class constants
@@ -37,7 +37,7 @@ jobs:
run: pnpm exec prettier --write src/data/sensor_entity_constants.ts
- name: Create pull request
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3
with:
branch: chore/sync-sensor-entity-constants
commit-message: Update sensor entity constants
+1 -1
View File
@@ -1 +1 @@
24.22.2
24.22.3
+2 -1
View File
@@ -40,7 +40,8 @@ Never run `tsc` or `pnpm lint:types` with file arguments. When `tsc` receives fi
Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching skill before detailed implementation or review. For reviews, load `ha-frontend-review` alongside all companions that apply to the changed code or behavior:
- `ha-frontend-contexts`: Lit contexts, `hass` migration, and rerender-sensitive state access.
- `ha-frontend-components`: dialogs, forms, alerts, loading states, shortcuts, tooltips, panels, and Lovelace cards.
- `ha-frontend-components`: dialogs, forms, alerts, shortcuts, tooltips, panels, and Lovelace cards.
- `ha-frontend-loading`: loading states, skeletons, spinners, loading fades, and checking how a screen looks while it loads.
- `ha-frontend-events`: event handler typing, custom event dispatch, and event-map declarations.
- `ha-frontend-types`: backend data contracts, optional schemas, shared types, assertions, and lifecycle types.
- `ha-frontend-lit`: reactive fields, DOM queries, lifecycle behavior, and render-derived state.
+8
View File
@@ -28,10 +28,18 @@ 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
+107 -42
View File
@@ -157,6 +157,99 @@ async function pollProcess(lokaliseApi, projectId, processId) {
}
/* eslint-enable no-await-in-loop */
const DRAFTS_ACCEPTED_KEYS = [
// Written per language rather than translated from English, so an English edit doesn't make them outdated
"ui.components.rooms.keywords",
];
async function exportTranslations(lokaliseApi, projectId) {
const exportProcess = await lokaliseApi.files().async_download(projectId, {
format: "json",
original_filenames: false,
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
});
const finishedProcess = await pollProcess(
lokaliseApi,
projectId,
exportProcess.process_id
);
const bundleUrl = finishedProcess.details.download_url;
console.log(`Downloading translations from: ${bundleUrl}`);
const response = await fetch(bundleUrl);
if (response.status !== 200 && response.status !== 0) {
throw new Error(response.statusText);
}
console.log(`Extracting translations...`);
const contents = await JSZip.loadAsync(await response.arrayBuffer());
const files = {};
await Promise.all(
Object.keys(contents.files).map(async (filename) => {
const file = contents.file(filename);
if (!file) {
// no file, probably a directory
return;
}
files[filename.split("/").splice(-1)[0]] = await file.async("string");
})
);
return files;
}
async function fetchDrafts(lokaliseApi, projectId) {
const english = JSON.parse(
await fs.readFile("src/translations/en.json", { encoding })
);
const keyNames = DRAFTS_ACCEPTED_KEYS.flatMap((key) => {
const keys = key.split(".");
const drafts = keys.reduce((obj, part) => obj?.[part], english) ?? {};
return Object.keys(drafts).map((name) => [...keys, name].join("::"));
});
if (!keyNames.length) {
return [];
}
const { items } = await lokaliseApi.keys().list({
project_id: projectId,
filter_keys: keyNames.join(","),
include_translations: 1,
limit: keyNames.length,
});
return items.flatMap((key) =>
key.translations
.filter(({ translation }) => translation)
.map(({ language_iso, translation }) => ({
filename: `${language_iso}.json`,
path: key.key_name.web.split("::"),
translation,
}))
);
}
function acceptDrafts(files, drafts) {
const data = {};
drafts.forEach(({ filename, path: keyPath, translation }) => {
data[filename] ??= files[filename] ? JSON.parse(files[filename]) : {};
const parent = keyPath.slice(0, -1).reduce((obj, part) => {
obj[part] ??= {};
return obj[part];
}, data[filename]);
parent[keyPath.at(-1)] = translation;
});
Object.entries(data).forEach(([filename, content]) => {
files[filename] = JSON.stringify(content, null, 2);
});
}
gulp.task("fetch-lokalise", async function () {
let apiKey;
try {
@@ -193,52 +286,24 @@ gulp.task("fetch-lokalise", async function () {
await Promise.all(
projects.map(async ([project, projectId]) => {
try {
const exportProcess = await lokaliseApi
.files()
.async_download(projectId, {
format: "json",
original_filenames: false,
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
});
const finishedProcess = await pollProcess(
lokaliseApi,
projectId,
exportProcess.process_id
);
const bundleUrl = finishedProcess.details.download_url;
console.log(`Downloading translations from: ${bundleUrl}`);
const response = await fetch(bundleUrl);
if (response.status !== 200 && response.status !== 0) {
throw new Error(response.statusText);
const [files, drafts] = await Promise.all([
exportTranslations(lokaliseApi, projectId),
project === "frontend"
? fetchDrafts(lokaliseApi, projectId)
: undefined,
]);
if (drafts) {
acceptDrafts(files, drafts);
}
console.log(`Extracting translations...`);
const contents = await JSZip.loadAsync(await response.arrayBuffer());
await mkdirPromise;
await Promise.all(
Object.keys(contents.files).map(async (filename) => {
const file = contents.file(filename);
if (!file) {
// no file, probably a directory
return;
}
const content = await file.async("nodebuffer");
await fs.writeFile(
path.join(inDir, project, filename.split("/").splice(-1)[0]),
content,
{ flag: "w", encoding }
);
})
Object.entries(files).map(([filename, content]) =>
fs.writeFile(path.join(inDir, project, filename), content, {
flag: "w",
encoding,
})
)
);
} catch (err) {
console.error(err);
+3 -1
View File
@@ -50,7 +50,9 @@ const convertToJSON = async (
const encodedData = localeData.match(
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
)?.groups?.data;
localeData = firstBlock.match(dataRegex)?.groups?.data;
localeData =
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
firstBlock.match(dataRegex)?.groups?.data;
if (!localeData && !encodedData) {
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
}
+1 -1
View File
@@ -100,7 +100,7 @@
The easiest way to get your Home Assistant installation served over
HTTPS is by signing up for
<a href="https://www.nabucasa.com" target="_blank"
>Home Assistant Cloud by Nabu Casa</a
>Home Assistant Link by Nabu Casa</a
>.
</p>
</div>
+2 -2
View File
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
:host {
display: block;
height: 100vh;
background-color: #f2f4f9;
background-color: var(--primary-background-color, #f2f4f9);
font-size: var(--ha-font-size-2xl);
}
.container {
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
object-fit: cover;
}
.status {
color: #1d2126;
color: var(--primary-text-color, #1d2126);
}
`;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

+1 -2
View File
@@ -1,7 +1,6 @@
import type { DemoConfig } from "../types";
import { demoEntitiesArsaboo } from "./entities";
import { demoLovelaceArsaboo } from "./lovelace";
import { demoThemeArsaboo } from "./theme";
export const demoArsaboo: DemoConfig = {
authorName: "Arsaboo",
@@ -9,5 +8,5 @@ export const demoArsaboo: DemoConfig = {
name: "ARS Home",
lovelace: demoLovelaceArsaboo,
entities: demoEntitiesArsaboo,
theme: demoThemeArsaboo,
theme: { theme: "default", dark: false },
};
-1
View File
@@ -1 +0,0 @@
export const demoThemeArsaboo = () => ({});
+7 -2
View File
@@ -13,8 +13,13 @@ import type { EntityInput } from "../../../src/fake_data/entities/types";
import type { DemoAutomation, DemoConfig, DemoTheme } from "./types";
export const applyDemoTheme = (hass: MockHomeAssistant, theme: DemoTheme) => {
if (typeof theme === "function") {
hass.mockTheme(theme());
if ("vars" in theme) {
// Like a theme with only one mode in core, so the app keeps that mode
// when it applies the theme again
hass.mockTheme(
{ modes: theme.dark ? { dark: theme.vars } : { light: theme.vars } },
{ theme: "fake-data", dark: theme.dark }
);
return;
}
hass.mockTheme(null, getDemoTheme(theme));
+2
View File
@@ -48,6 +48,8 @@ class DemoHomeDashboardStrategy extends ReactiveElement {
),
};
}
static getConfigElement = HomeDashboardStrategy.getConfigElement;
}
class DemoHomeOverviewViewStrategy extends ReactiveElement {
File diff suppressed because it is too large. Load diff
+33 -28
View File
@@ -1,28 +1,33 @@
export const demoThemeJimpower = () => ({
"text-primary-color": "var(--primary-text-color)",
"primary-color": "#5294E2",
"label-badge-red": "var(--accent-color)",
"light-primary-color": "var(--accent-color)",
"primary-background-color": "#383C45",
"primary-text-color": "#FFFFFF",
"secondary-background-color": "#383C45",
"disabled-text-color": "#7F848E",
"paper-grey-200": "#414A59",
"label-badge-background-color": "#2E333A",
"sidebar-icon-color": "var(--state-icon-color)",
"table-row-background-color": "#353840",
"paper-grey-50": "var(--primary-text-color)",
"switch-checked-color": "var(--accent-color)",
"secondary-text-color": "#5294E2",
"error-color": "#E45E65",
"divider-color": "rgba(0, 0, 0, .12)",
"success-color": "#39E949",
"switch-unchecked-button-color": "var(--disabled-text-color)",
"label-badge-border-color": "green",
"card-background-color": "#434954",
"label-badge-text-color": "var(--primary-text-color)",
"switch-unchecked-track-color": "var(--disabled-text-color)",
"dark-primary-color": "var(--accent-color)",
"accent-color": "#E45E65",
"table-row-alternative-background-color": "#3E424B",
});
import { generateColorPalette } from "../../../../src/common/color/palette";
import type { DemoCustomTheme } from "../types";
const primaryColor = "#5294E2";
export const demoThemeJimpower: DemoCustomTheme = {
dark: true,
vars: {
...Object.fromEntries(generateColorPalette(primaryColor, "primary")),
"text-primary-color": "var(--primary-text-color)",
"primary-color": primaryColor,
"label-badge-red": "var(--accent-color)",
"light-primary-color": "var(--accent-color)",
"primary-background-color": "#383C45",
"primary-text-color": "#FFFFFF",
"secondary-background-color": "#383C45",
"disabled-text-color": "#7F848E",
"label-badge-background-color": "#2E333A",
"sidebar-icon-color": "var(--state-icon-color)",
"table-row-background-color": "#353840",
"secondary-text-color": "#5294E2",
"error-color": "#E45E65",
"success-color": "#39E949",
"card-background-color": "#434954",
"label-badge-text-color": "var(--primary-text-color)",
"dark-primary-color": "var(--accent-color)",
"accent-color": "#E45E65",
"table-row-alternative-background-color": "#3E424B",
"ha-card-border-radius": "20px",
"ha-card-box-shadow": "3px 3px rgba(0, 0, 0, 0.4)",
"ha-card-border-color": "rgba(100, 100, 100, 0.3)",
},
};
+30 -28
View File
@@ -1,29 +1,31 @@
import { generateColorPalette } from "../../../../src/common/color/palette";
import type { DemoCustomTheme } from "../types";
const primaryColor = "#2980b9";
// https://community.home-assistant.io/t/slate-a-new-dark-theme/86410
export const demoThemeKernehed = () => ({
"text-primary-color": "var(--primary-text-color)",
"primary-color": "#2980b9",
"label-badge-red": "var(--accent-color)",
"primary-text-color": "#FFFFFF",
"light-primary-color": "var(--accent-color)",
"primary-background-color": "#222222",
"sidebar-icon-color": "#777777",
"secondary-background-color": "#222222",
"disabled-text-color": "#777777",
"paper-grey-200": "#222222",
"label-badge-background-color": "#222222",
"table-row-background-color": "#292929",
"paper-grey-50": "var(--primary-text-color)",
"switch-checked-color": "var(--accent-color)",
"secondary-text-color": "#b58e31",
"error-color": "#b58e31",
"divider-color": "rgba(0, 0, 0, .12)",
"success-color": "#2980b9",
"switch-unchecked-button-color": "var(--disabled-text-color)",
"label-badge-border-color": "green",
"card-background-color": "#292929",
"label-badge-text-color": "var(--primary-text-color)",
"switch-unchecked-track-color": "var(--disabled-text-color)",
"dark-primary-color": "var(--accent-color)",
"accent-color": "#2980b9",
"table-row-alternative-background-color": "#292929",
});
export const demoThemeKernehed: DemoCustomTheme = {
dark: true,
vars: {
...Object.fromEntries(generateColorPalette(primaryColor, "primary")),
"text-primary-color": "var(--primary-text-color)",
"primary-color": primaryColor,
"label-badge-red": "var(--accent-color)",
"primary-text-color": "#FFFFFF",
"light-primary-color": "var(--accent-color)",
"primary-background-color": "#222222",
"sidebar-icon-color": "#777777",
"secondary-background-color": "#222222",
"disabled-text-color": "#777777",
"label-badge-background-color": "#222222",
"table-row-background-color": "#292929",
"secondary-text-color": "#b58e31",
"error-color": "#b58e31",
"success-color": "#2980b9",
"card-background-color": "#292929",
"label-badge-text-color": "var(--primary-text-color)",
"dark-primary-color": "var(--accent-color)",
"accent-color": "#2980b9",
"table-row-alternative-background-color": "#292929",
},
};
+23 -18
View File
@@ -1,18 +1,23 @@
export const demoThemeTeachingbirds = () => ({
"paper-grey-50": "var(--primary-text-color)",
"divider-color": "rgba(255, 255, 255, 0.12)",
"primary-color": "#389638",
"light-primary-color": "#6f956f",
"label-badge-red": "var(--primary-color)",
"switch-unchecked-track-color": "var(--primary-text-color)",
"card-background-color": "#4e4e4e",
"label-badge-text-color": "var(--text-primary-color)",
"primary-background-color": "#303030",
"sidebar-icon-color": "#d3d3d3",
"secondary-background-color": "#2b2b2b",
"switch-checked-color": "var(--primary-color)",
"secondary-text-color": "#389638",
"disabled-text-color": "#545454",
"paper-grey-200": "#191919",
"label-badge-background-color": "var(--secondary-background-color)",
});
import { generateColorPalette } from "../../../../src/common/color/palette";
import type { DemoCustomTheme } from "../types";
const primaryColor = "#389638";
export const demoThemeTeachingbirds: DemoCustomTheme = {
dark: true,
vars: {
...Object.fromEntries(generateColorPalette(primaryColor, "primary")),
"divider-color": "rgba(255, 255, 255, 0.12)",
"primary-color": primaryColor,
"light-primary-color": "#6f956f",
"label-badge-red": "var(--primary-color)",
"card-background-color": "#4e4e4e",
"label-badge-text-color": "var(--text-primary-color)",
"primary-background-color": "#303030",
"sidebar-icon-color": "#d3d3d3",
"secondary-background-color": "#2b2b2b",
"secondary-text-color": "#389638",
"disabled-text-color": "#545454",
"label-badge-background-color": "var(--secondary-background-color)",
},
};
+7 -1
View File
@@ -7,7 +7,13 @@ import type { ThemeSettings } from "../../../src/types";
import type { DemoArea } from "../stubs/area_registry";
import type { DemoFloor } from "../stubs/floor_registry";
export type DemoTheme = ThemeSettings | (() => Record<string, string> | null);
export interface DemoCustomTheme {
/** The vars are applied on top of the default dark or light theme */
dark: boolean;
vars: Record<string, string>;
}
export type DemoTheme = ThemeSettings | DemoCustomTheme;
export interface DemoAutomation {
config: ManualAutomationConfig & { id: string; alias: string };
-88
View File
@@ -1,88 +0,0 @@
/* eslint-disable */
import { LitElement } from "lit";
import "./card-tools";
class CardModder extends LitElement {
setConfig(config) {
if (!window.cardTools)
throw new Error(
`Can't find card-tools. See https://github.com/thomasloven/lovelace-card-tools`
);
window.cardTools.checkVersion(0.2);
if (!config || !config.card) {
throw new Error("Card config incorrect");
}
if (Array.isArray(config.card)) {
throw new Error("It says 'card', not 'cardS'. Remove the dash.");
}
this._config = config;
this.card = window.cardTools.createCard(config.card);
this.templated = [];
this.attempts = 0;
}
render() {
return window.cardTools.litHtml`
<div id="root">${this.card}</div>
`;
}
firstUpdated() {
this._cardMod();
}
_cardMod() {
if (!this._config.style) return;
let target = null;
target = target || this.card.querySelector("ha-card");
target =
target ||
(this.card.shadowRoot && this.card.shadowRoot.querySelector("ha-card"));
target =
target ||
(this.card.firstChild &&
this.card.firstChild.shadowRoot &&
this.card.firstChild.shadowRoot.querySelector("ha-card"));
if (!target && !this.attempts)
// Try twice
setTimeout(() => this._cardMod(), 100);
this.attempts++;
target = target || this.card;
for (var k in this._config.style) {
if (window.cardTools.hasTemplate(this._config.style[k]))
this.templated.push(k);
this.card.style.setProperty(k, "");
target.style.setProperty(
k,
window.cardTools.parseTemplate(this._config.style[k])
);
}
this.target = target;
}
set hass(hass) {
if (this.card) this.card.hass = hass;
if (this.templated)
this.templated.forEach((k) => {
this.target.style.setProperty(
k,
window.cardTools.parseTemplate(this._config.style[k], "")
);
});
}
getCardSize() {
if (this._config && this._config.report_size)
return this._config.report_size;
if (this.card)
return typeof this.card.getCardSize === "function"
? this.card.getCardSize()
: 1;
return 1;
}
}
customElements.define("card-modder", CardModder);
-198
View File
@@ -1,198 +0,0 @@
/* eslint-disable */
import { html, LitElement } from "lit";
if (!window.cardTools) {
const version = 0.2;
const CUSTOM_TYPE_PREFIX = "custom:";
let cardTools = {};
cardTools.v = version;
cardTools.checkVersion = (v) => {
if (version < v) {
throw new Error(
`Old version of card-tools found. Get the latest version of card-tools.js from https://github.com/thomasloven/lovelace-card-tools`
);
}
};
cardTools.LitElement = LitElement;
cardTools.litHtml = html;
cardTools.hass = () => {
return document.querySelector("home-assistant").hass;
};
cardTools.fireEvent = (ev, detail) => {
ev = new Event(ev, {
bubbles: true,
cancelable: false,
composed: true,
});
ev.detail = detail || {};
document.querySelector("ha-demo").dispatchEvent(ev);
};
cardTools.createThing = (thing, config) => {
const _createThing = (tag, config) => {
const element = document.createElement(tag);
try {
element.setConfig(config);
} catch (err) {
console.error(tag, err);
return _createError(err.message, config);
}
return element;
};
const _createError = (error, config) => {
return _createThing("hui-error-card", {
type: "error",
error,
config,
});
};
if (!config || typeof config !== "object" || !config.type)
return _createError(`No ${thing} type configured`, config);
let tag = config.type;
if (config.error) {
const err = config.error;
delete config.error;
return _createError(err, config);
}
if (tag.startsWith(CUSTOM_TYPE_PREFIX))
tag = tag.substr(CUSTOM_TYPE_PREFIX.length);
else tag = `hui-${tag}-${thing}`;
if (customElements.get(tag)) return _createThing(tag, config);
// If element doesn't exist (yet) create an error
const element = _createError(
`Custom element doesn't exist: ${tag}.`,
config
);
element.style.display = "None";
const time = setTimeout(() => {
element.style.display = "";
}, 2000);
// Remove error if element is defined later
customElements.whenDefined(tag).then(() => {
clearTimeout(timer);
cardTools.fireEvent("rebuild-view");
});
return element;
};
cardTools.createCard = (config) => {
return cardTools.createThing("card", config);
};
cardTools.createElement = (config) => {
return cardTools.createThing("element", config);
};
cardTools.createEntityRow = (config) => {
const SPECIAL_TYPES = new Set([
"call-service",
"divider",
"section",
"weblink",
]);
const DEFAULT_ROWS = {
alert: "toggle",
automation: "toggle",
climate: "toggle",
cover: "cover",
fan: "toggle",
group: "group",
input_boolean: "toggle",
input_number: "input-number",
input_select: "input-select",
input_text: "input-text",
light: "toggle",
media_player: "media-player",
lock: "lock",
scene: "scene",
script: "script",
sensor: "sensor",
timer: "timer",
switch: "toggle",
vacuum: "toggle",
};
if (
!config ||
typeof config !== "object" ||
(!config.entity && !config.type)
) {
Object.assign(config, { error: "Invalid config given" });
return cardTools.createThing("", config);
}
const type = config.type || "default";
if (SPECIAL_TYPES.has(type) || type.startsWith(CUSTOM_TYPE_PREFIX))
return cardTools.createThing("row", config);
const domain = config.entity.split(".", 1)[0];
Object.assign(config, { type: DEFAULT_ROWS[domain] || "simple" });
return cardTools.createThing("entity-row", config);
};
cardTools.deviceID = (() => {
const ID_STORAGE_KEY = "lovelace-player-device-id";
if (window["fully"] && typeof fully.getDeviceId === "function")
return fully.getDeviceId();
if (!localStorage[ID_STORAGE_KEY]) {
const s4 = () => {
return Math.floor((1 + Math.random()) * 100000)
.toString(16)
.substring(1);
};
localStorage[ID_STORAGE_KEY] = `${s4()}${s4()}-${s4()}${s4()}`;
}
return localStorage[ID_STORAGE_KEY];
})();
cardTools.moreInfo = (entity) => {
cardTools.fireEvent("hass-more-info", { entityId: entity });
};
cardTools.longpress = (element) => {
customElements.whenDefined("action-handler").then(() => {
const longpress = document.body.querySelector("action-handler");
longpress.bind(element);
});
return element;
};
cardTools.hasTemplate = (text) => {
return /\[\[\s+.*\s+\]\]/.test(text);
};
cardTools.parseTemplate = (text, error) => {
const _parse = (str) => {
try {
str = str.replace(/^\[\[\s+|\s+\]\]$/g, "");
const parts = str.split(".");
let v = cardTools.hass().states[`${parts[0]}.${parts[1]}`];
parts.shift();
parts.shift();
parts.forEach((item) => (v = v[item]));
return v;
} catch (err) {
return error || `[[ Template matching failed ${str} ]]`;
}
};
text = text.replace(/(\[\[\s.*?\s\]\])/g, (str, p1, offset, s) =>
_parse(str)
);
return text;
};
window.cardTools = cardTools;
cardTools.fireEvent("rebuild-view");
}
+1 -1
View File
@@ -4,7 +4,7 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
const pipelines: AssistPipeline[] = [
{
id: "01home_assistant_cloud",
name: "Home Assistant Cloud",
name: "Home Assistant Link",
language: "en",
conversation_engine: "conversation.home_assistant",
conversation_language: "en",
+1 -1
View File
@@ -78,7 +78,7 @@ const backupConfig: BackupConfig = {
const agentsInfo: BackupAgentsInfo = {
agents: [
{ agent_id: "backup.local", name: "This device" },
{ agent_id: "cloud.cloud", name: "Home Assistant Cloud" },
{ agent_id: "cloud.cloud", name: "Home Assistant Link" },
],
};
@@ -44,14 +44,21 @@ export const lorawanFixtures: ConnectivityFixtures = {
],
commands: ["lorawan/"],
manifests: [
manifest("lorawan", "LoRaWAN", { integration_type: "helper" }),
manifest("lorawan", "LoRaWAN", {
config_flow: false,
integration_type: "service",
}),
manifest("sensecap_lorawan", "SenseCAP", {
integration_type: "device",
dependencies: ["lorawan"],
}),
manifest("chirpstack", "ChirpStack", { integration_type: "hub" }),
manifest("chirpstack", "ChirpStack", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
manifest("thethingsnetwork_lorawan", "The Things Network", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
],
configEntries: [
@@ -10,19 +10,26 @@ export const FRONIUS_ENTRY_ID = "mock-fronius";
export const RS485_PORT = "/dev/ttyUSB1";
export const modbusFixtures: ConnectivityFixtures = {
components: ["modbus"],
components: ["modbus", "flexit", "solaredge_modbus", "fronius"],
commands: ["modbus/"],
manifests: [
manifest("modbus", "Modbus", {
config_flow: false,
iot_class: "local_polling",
}),
manifest("flexit", "Flexit", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("solaredge_modbus", "SolarEdge Modbus", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("fronius", "Fronius", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
],
+24 -8
View File
@@ -8,7 +8,7 @@ import type {
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockEnergy = (hass: MockHomeAssistant) => {
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
const prefs: EnergyPreferences = {
energy_sources: [
{
type: "grid",
@@ -21,7 +21,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
entity_energy_price_export: null,
number_energy_price_export: null,
stat_rate: "sensor.power_grid",
cost_adjustment_day: 0,
},
{
type: "grid",
@@ -34,7 +33,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
entity_energy_price_export: null,
number_energy_price_export: null,
stat_rate: "sensor.power_grid_return",
cost_adjustment_day: 0,
},
{
type: "solar",
@@ -48,6 +46,23 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_energy_to: "sensor.battery_input",
stat_rate: "sensor.power_battery",
},
{
type: "battery",
name: "Powerwall",
stat_energy_from_grid: "sensor.powerwall_from_grid",
stat_energy_from_solar: "sensor.powerwall_from_solar",
stat_energy_to_home: "sensor.powerwall_to_home",
stat_energy_to_grid: "sensor.powerwall_to_grid",
stat_rate: "sensor.powerwall_power",
power_config: {
stat_rate_from_grid: "sensor.powerwall_power_from_grid",
stat_rate_from_solar: "sensor.powerwall_power_from_solar",
stat_rate_to_home: "sensor.powerwall_power_to_home",
stat_rate_to_grid: "sensor.powerwall_power_to_grid",
},
stat_soc: "sensor.powerwall_battery_level",
capacity: 13.5,
},
{
type: "gas",
stat_energy_from: "sensor.energy_gas",
@@ -105,16 +120,17 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
}));
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
energy_sources: Array.from({ length: 6 }, () => []),
device_consumption: Array.from({ length: 6 }, () => []),
device_consumption_water: Array.from({ length: 2 }, () => []),
device_consumption_gas: Array.from({ length: 2 }, () => []),
energy_sources: prefs.energy_sources.map(() => []),
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
+75
View File
@@ -1,3 +1,30 @@
// Live power of the battery measured per direction, in W
const powerwallPower = {
from_grid: 50,
from_solar: 150,
to_home: 0,
to_grid: 0,
};
const powerEntity = (entityId: string, power: number) => ({
entity_id: entityId,
state: String(power),
attributes: {
state_class: "measurement",
unit_of_measurement: "W",
},
});
const powerwallEnergyEntity = (entityId: string, friendlyName: string) => ({
entity_id: entityId,
state: "2",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
friendly_name: friendlyName,
unit_of_measurement: "kWh",
},
});
export const energyEntities = () =>
Object.values({
"sensor.grid_fossil_fuel_percentage": {
@@ -34,6 +61,31 @@ export const energyEntities = () =>
unit_of_measurement: "kWh",
},
},
"sensor.powerwall_from_grid": powerwallEnergyEntity(
"sensor.powerwall_from_grid",
"Powerwall charged from grid"
),
"sensor.powerwall_from_solar": powerwallEnergyEntity(
"sensor.powerwall_from_solar",
"Powerwall charged from solar"
),
"sensor.powerwall_to_home": powerwallEnergyEntity(
"sensor.powerwall_to_home",
"Powerwall discharged to home"
),
"sensor.powerwall_to_grid": powerwallEnergyEntity(
"sensor.powerwall_to_grid",
"Powerwall discharged to grid"
),
"sensor.powerwall_battery_level": {
entity_id: "sensor.powerwall_battery_level",
state: "62",
attributes: {
device_class: "battery",
friendly_name: "Powerwall battery level",
unit_of_measurement: "%",
},
},
"sensor.energy_consumption_tarif_1": {
entity_id: "sensor.energy_consumption_tarif_1",
state: "88.6",
@@ -134,6 +186,29 @@ export const energyEntities = () =>
unit_of_measurement: "W",
},
},
"sensor.powerwall_power_from_grid": powerEntity(
"sensor.powerwall_power_from_grid",
powerwallPower.from_grid
),
"sensor.powerwall_power_from_solar": powerEntity(
"sensor.powerwall_power_from_solar",
powerwallPower.from_solar
),
"sensor.powerwall_power_to_home": powerEntity(
"sensor.powerwall_power_to_home",
powerwallPower.to_home
),
"sensor.powerwall_power_to_grid": powerEntity(
"sensor.powerwall_power_to_grid",
powerwallPower.to_grid
),
"sensor.powerwall_power": powerEntity(
"sensor.powerwall_power",
powerwallPower.to_home +
powerwallPower.to_grid -
powerwallPower.from_grid -
powerwallPower.from_solar
),
"sensor.energy_gas_cost": {
entity_id: "sensor.energy_gas_cost",
state: "2",
+33 -7
View File
@@ -1,3 +1,4 @@
import type { ValidSystemDataKey } from "../../../src/data/frontend";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import type { ThemeSettings } from "../../../src/types";
@@ -57,14 +58,40 @@ export const mockFrontend = (hass: MockHomeAssistant) => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => {};
});
// System data saved during this session, per key. Core starts from the
// system data of the mock hass.
const systemData: Partial<Record<ValidSystemDataKey, unknown>> = {
core: hass.systemData,
};
const systemDataCallbacks: Partial<
Record<ValidSystemDataKey, Set<(data: { value: unknown }) => void>>
> = {};
hass.mockWS(
"frontend/subscribe_system_data",
(_msg, currentHass, onChange) => {
onChange?.({
value: currentHass.systemData,
});
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => {};
({ key }: { key: ValidSystemDataKey }, _currentHass, onChange) => {
onChange?.({ value: systemData[key] ?? null });
if (!onChange) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => {};
}
const callbacks = (systemDataCallbacks[key] ??= new Set());
callbacks.add(onChange);
return () => {
callbacks.delete(onChange);
};
}
);
hass.mockWS(
"frontend/get_system_data",
({ key }: { key: ValidSystemDataKey }) => ({
value: systemData[key] ?? null,
})
);
hass.mockWS(
"frontend/set_system_data",
({ key, value }: { key: ValidSystemDataKey; value: unknown }) => {
systemData[key] = value;
systemDataCallbacks[key]?.forEach((callback) => callback({ value }));
}
);
hass.mockWS("labs/subscribe", (_msg, _currentHass, onChange) => {
@@ -77,7 +104,6 @@ export const mockFrontend = (hass: MockHomeAssistant) => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => {};
});
hass.mockWS("frontend/get_system_data", () => ({ value: null }));
hass.mockWS("repairs/list_issues", () => ({ issues: [] }));
hass.mockWS("frontend/get_themes", (_msg, currentHass) => currentHass.themes);
};
+33 -6
View File
@@ -351,6 +351,26 @@ const statisticsFunctions: Record<
const derivedCosts: Record<string, { source: string; price: number }> = {
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
};
// Battery directions as a share of the meter the energy also passes, so they
// never exceed it
const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
"sensor.powerwall_from_grid": {
source: "sensor.energy_consumption_tarif_1",
share: 0.4,
},
"sensor.powerwall_from_solar": {
source: "sensor.solar_production",
share: 0.3,
},
"sensor.powerwall_to_home": {
source: "sensor.energy_consumption_tarif_2",
share: 0.5,
},
"sensor.powerwall_to_grid": {
source: "sensor.energy_production_tarif_2",
share: 0.3,
},
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
@@ -375,15 +395,22 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
return cache[id];
};
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];
let cost = 0;
statistics[id] = getStats(source).map((statistic) => {
const change = statistic.change! * price;
cost += change;
return { ...statistic, change, state: cost, sum: cost };
});
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 {
-1
View File
@@ -25,7 +25,6 @@ class DemoMoreInfo extends LitElement {
!computeShowNewMoreInfo(state)
? html`<state-card-content
.stateObj=${state}
.hass=${this.hass}
in-dialog
></state-card-content>`
: nothing
+19
View File
@@ -0,0 +1,19 @@
import type { ReactiveElement } from "lit";
import { ContextSubscriptionController } from "../../../src/common/decorators/consume";
import { uiContext } from "../../../src/data/context";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
// A demo that provides its own hass hides the gallery theme from its children,
// so pass the gallery light or dark mode on to it.
export const followGalleryTheme = (
host: ReactiveElement,
hass: MockHomeAssistant
) =>
new ContextSubscriptionController(host, uiContext, (ui) => {
if (ui) {
hass.updateHass({
themes: ui.themes,
selectedTheme: ui.selectedTheme,
});
}
});
+1
View File
@@ -86,6 +86,7 @@ const mql = matchMedia("(prefers-color-scheme: dark)");
const galleryLocalize = (key: string) =>
(
({
"ui.common.loading": "Loading",
"ui.sidebar.sidebar_toggle": "Toggle sidebar",
"ui.notification_drawer.title": "Notifications",
"ui.sidebar.external_app_configuration": "App configuration",
@@ -284,7 +284,9 @@ export class DemoHaAdaptiveDialog extends LitElement {
<p>
The header title can be set using the <code>header-title</code>
attribute or by providing custom content in the
<code>headerTitle</code> slot.
<code>headerTitle</code> slot. When you use the slot, set the
<code>accessibleLabel</code> property so screen readers announce the
dialog's name.
</p>
<h4>Header subtitle</h4>
@@ -66,13 +66,14 @@ Check the [webawesome documentation](https://webawesome.com/docs/components/butt
**Properties/Attributes**
| Name | Type | Default | Description |
| ---------- | ---------------------------------------------- | -------- | --------------------------------------------------------------------------------- |
| appearance | "accent"/"filled"/"outlined"/"plain" | "accent" | Sets the button appearance. |
| variants | "brand"/"danger"/"neutral"/"warning"/"success" | "brand" | Sets the button color variant. "brand" is default. |
| size | "xs"/"s"/"m"/"l"/"xl" | "m" | Sets the button size. |
| loading | Boolean | false | Shows a loading indicator instead of the buttons label and disable buttons click. |
| disabled | Boolean | false | Disables the button and prevents user interaction. |
| Name | Type | Default | Description |
| ------------ | ---------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| appearance | "accent"/"filled"/"outlined"/"plain" | "accent" | Sets the button appearance. |
| variants | "brand"/"danger"/"neutral"/"warning"/"success" | "brand" | Sets the button color variant. "brand" is default. |
| size | "xs"/"s"/"m"/"l"/"xl" | "m" | Sets the button size. |
| loading | Boolean | false | Shows a loading indicator instead of the buttons label and disable buttons click. |
| disabled | Boolean | false | Disables the button and prevents user interaction. |
| aria-pressed | "true"/"false" | - | Makes it a toggle button and tells screen readers whether it is pressed. Leave unset for a regular button. |
**CSS Custom Properties**
@@ -29,8 +29,8 @@ This component is based on the webawesome input component.
**Slots**
- `start`: Content placed before the input (usually for icons or prefixes).
- `end`: Content placed after the input (usually for icons or suffixes).
- `start`: Content placed before the input, usually an icon. Use `input-prefix` for text.
- `end`: Content placed after the input, usually an icon. Use `input-suffix` for text.
- `label`: Custom label content. Overrides the `label` property.
- `hint`: Custom hint content. Overrides the `hint` property.
- `clear-icon`: Custom clear icon.
@@ -56,6 +56,8 @@ This component is based on the webawesome input component.
| auto-validate | Boolean | false | Validates the input on blur instead of on form submit. |
| invalid | Boolean | false | Marks the input as invalid. |
| inset-label | Boolean | false | Uses an inset label style where the label stays inside the input. |
| input-prefix | String | - | Fixed text shown before the value. With a label, the label is inset above the prefix. |
| input-suffix | String | - | Fixed text shown after the value. |
| validation-message | String | "" | Custom validation message shown when the input is invalid. |
| input-id | String | - | Sets the native input's `id` and associated label `for` on the inner `wa-input`. Defaults to `"input"`. |
| pattern | String | - | A regular expression pattern to validate input against. |
+7 -7
View File
@@ -136,14 +136,14 @@ export class DemoHaInput extends LitElement {
></ha-input>
</div>
<h3>With slots</h3>
<h3>Prefix, suffix and slots</h3>
<div class="row">
<ha-input label="With prefix">
<span slot="start">$</span>
</ha-input>
<ha-input label="With suffix">
<span slot="end">kg</span>
</ha-input>
<ha-input
label="With prefix"
input-prefix="update."
value="living_room"
></ha-input>
<ha-input label="With suffix" input-suffix="kg"></ha-input>
<ha-input label="With icon">
<ha-svg-icon
.path=${mdiMagnify}
+69 -5
View File
@@ -117,11 +117,17 @@ shared slots/attributes below.
**Attributes**
| Name | Type | Default | Description |
| ----------------- | ------- | ------- | --------------------------------------- |
| `headline` | String | — | Primary text. Overridden by the slot. |
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
| Name | Type | Default | Description |
| ---------------------- | ------- | ------- | -------------------------------------------------- |
| `headline` | String | — | Primary text. Overridden by the slot. |
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
| `wrap-headline` | Boolean | `false` | Wrap the headline instead of truncating it. |
| `wrap-supporting-text` | Boolean | `false` | Wrap the supporting text instead of truncating it. |
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
The headline and the supporting text stay on one line and are truncated with an
ellipsis by default. Set `wrap-headline` or `wrap-supporting-text` on rows whose
text has to stay readable in full, like settings with a description.
**CSS parts**
@@ -165,6 +171,18 @@ Interactive row. Renders an inner `<a>` when `href` is set, otherwise a
roving tabindex, the host is the tab stop and the inner element carries
`tabindex="-1"`.
Only the headline and supporting text are inside the `<a>` or `<button>`; its
hit area is stretched over the whole row. The `start` and `end` slots sit next
to it, so controls placed there, like an `ha-icon-button` or `ha-dropdown`,
stay separate controls for screen readers. Slotted elements are raised above
the hit area so they can be clicked, except icons, badges, `span`s and empty
`div`s (dividers), which let clicks and hover through to the row. A focusable
element (with `tabindex`) is always raised. To keep another element clickable
on its own, like a drag handle, give it `z-index: 1` in the consumer's styles.
Subclasses customize the row by overriding `_renderStart()`,
`_renderContent()` and `_renderEnd()`. `_renderInner()` is not used.
**Attributes**
- `href` (String) — when set, renders an `<a>` instead of a `<button>`.
@@ -174,8 +192,54 @@ roving tabindex, the host is the tab stop and the inner element carries
**CSS parts**
- `control` — the inner `<a>` or `<button>`.
- `ripple` — the ripple effect element.
### `<ha-list-item-switch>`
Row with a switch at the end, for settings that turn something on or off. The
whole row is the label of the switch: clicking anywhere on it toggles the
switch. For screen readers, the headline names the switch and the supporting
text describes it, so don't set `accessibleLabel` yourself.
The switch is its own tab stop, so the row doesn't join the roving tabindex of
a parent list. The row can also be used on its own, outside a list; it then has
no role.
Everything in the row is part of the label, so there is no `end` slot, and
the `start` slot is for icons and avatars only. For a row with other controls
next to the switch or inside its text, like an `ha-icon-button` or a link, use
`ha-list-item-base` with an `ha-switch` in the `end` slot and set its
`accessibleLabel`.
The row inherits the slots and attributes of `ha-list-item-base`, except
`interactive`, which it doesn't use.
```html
<ha-list-item-switch checked>
<span slot="headline">Advanced mode</span>
<span slot="supporting-text">Shows advanced settings and options.</span>
</ha-list-item-switch>
```
**Attributes**
- `checked` (Boolean, default `false`, reflected) — whether the switch is on.
- `haptic` (Boolean, default `false`) — vibrates on toggle. Only set it when
the change is applied right away, not when the user still has to save.
**Events**
- `change` — the switch was toggled. Read the new state from `checked` on the
row.
**CSS parts**
- `switch` — the `ha-switch`. It only shows the state; the row handles
input.
- `base`, `start`, `content`, `headline`, `supporting-text` — as on
`ha-row-item`. There is no `end` part.
### `<ha-list-item-option>`
Selectable row. Host role is `option`; reflects `aria-selected`. Designed to
+146
View File
@@ -2,21 +2,28 @@ import {
mdiAccount,
mdiChevronRight,
mdiCog,
mdiDelete,
mdiHome,
mdiInformationOutline,
mdiMapMarker,
mdiOpenInNew,
mdiPencil,
mdiViewDashboard,
mdiWifi,
} from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, state } from "lit/decorators";
import type { HASSDomTargetEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-icon-button";
import "../../../../src/components/ha-icon-next";
import "../../../../src/components/ha-svg-icon";
import "../../../../src/components/item/ha-list-item-base";
import "../../../../src/components/item/ha-list-item-button";
import "../../../../src/components/item/ha-list-item-option";
import "../../../../src/components/item/ha-list-item-switch";
import type { HaListItemSwitch } from "../../../../src/components/item/ha-list-item-switch";
import "../../../../src/components/list/ha-list-base";
import "../../../../src/components/list/ha-list-nav";
import "../../../../src/components/list/ha-list-selectable";
@@ -77,6 +84,8 @@ const treeKey = (group: TreeGroup, child: TreeChild) =>
export class DemoHaList extends LitElement {
@state() private _buttonClicks = 0;
@state() private _lastAction = "none";
@state() private _single: number | Set<number> = -1;
@state() private _multiLine: number | Set<number> = new Set();
@@ -87,6 +96,12 @@ export class DemoHaList extends LitElement {
@state() private _tree = new Set<string>();
@state() private _switches: Record<string, boolean> = {
wifi: true,
advanced: false,
standalone: false,
};
private _options = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon"];
protected render(): TemplateResult {
@@ -185,6 +200,20 @@ export class DemoHaList extends LitElement {
<ha-list-item-base headline="Disabled row" disabled>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
<ha-list-item-base
headline="Truncated by default, a long headline stays on one line and ends with an ellipsis"
supporting-text="Long supporting text is truncated as well, so every row in the list keeps the same height"
>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
<ha-list-item-base
wrap-headline
wrap-supporting-text
headline="With wrap-headline, a long headline wraps onto as many lines as it needs"
supporting-text="With wrap-supporting-text, long supporting text wraps too, which suits settings with a description"
>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
</ha-list-base>
</ha-card>
@@ -220,6 +249,101 @@ export class DemoHaList extends LitElement {
</ha-list-base>
</ha-card>
<ha-card header="Row with actions in the end slot">
<p class="card-text">
Last action: <code>${this._lastAction}</code>. The action buttons are
separate controls; icons and the divider activate the row.
</p>
<ha-list-base aria-label="Rows with actions">
<ha-list-item-button data-action="row" @click=${this._onActionClick}>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
<span slot="headline">Button row</span>
<span slot="supporting-text">Click the row or an action</span>
<ha-icon-next slot="end"></ha-icon-next>
<div slot="end" class="vertical-divider"></div>
<ha-icon-button
slot="end"
data-action="edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-button
slot="end"
data-action="delete"
.path=${mdiDelete}
label="Delete"
@click=${this._onActionClick}
></ha-icon-button>
</ha-list-item-button>
<ha-list-item-button href="#components/ha-list">
<ha-svg-icon slot="start" .path=${mdiMapMarker}></ha-svg-icon>
<span slot="headline">Link row</span>
<span slot="supporting-text"
>Cmd/Ctrl-click on the icon or chevron opens a new tab</span
>
<ha-icon-button
slot="end"
data-action="link-edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
</ha-list-base>
</ha-card>
<h2>ha-list-item-switch</h2>
<p>
Row with a switch. The whole row is the label of the switch, so clicking
anywhere on it toggles the switch.
</p>
<ha-card header="In a list">
<ha-list-base aria-label="Switch items">
<ha-list-item-switch
wrap-supporting-text
.checked=${this._switches.wifi}
data-switch="wifi"
@change=${this._onSwitchChange}
>
<ha-svg-icon slot="start" .path=${mdiWifi}></ha-svg-icon>
<span slot="headline">Wi-Fi</span>
<span slot="supporting-text"
>Connect to known networks automatically.</span
>
</ha-list-item-switch>
<ha-list-item-switch
.checked=${this._switches.advanced}
data-switch="advanced"
@change=${this._onSwitchChange}
>
<span slot="headline">Advanced mode</span>
</ha-list-item-switch>
<ha-list-item-switch
disabled
checked
headline="Disabled"
supporting-text="Can't be changed"
></ha-list-item-switch>
</ha-list-base>
</ha-card>
<ha-card header="Without a list">
<ha-list-item-switch
wrap-headline
.checked=${this._switches.standalone}
data-switch="standalone"
@change=${this._onSwitchChange}
>
<span slot="headline">A row on its own, without a list role</span>
</ha-list-item-switch>
<p class="card-text">
State: <code>${JSON.stringify(this._switches)}</code>
</p>
</ha-card>
<h2>ha-list-selectable + ha-list-item-option</h2>
<p>
Selectable list (<code>role="listbox"</code>). Items must be
@@ -428,10 +552,23 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
return value instanceof Set ? [...value] : value;
}
private _onActionClick = (ev: MouseEvent) => {
ev.stopPropagation();
this._lastAction =
(ev.currentTarget as HTMLElement).dataset.action ?? "none";
};
private _onButtonClick = () => {
this._buttonClicks++;
};
private _onSwitchChange = (ev: HASSDomTargetEvent<HaListItemSwitch>) => {
this._switches = {
...this._switches,
[ev.target.dataset.switch!]: ev.target.checked,
};
};
private _withIndex(
value: number | Set<number>,
index: number,
@@ -542,6 +679,15 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
ha-card {
max-width: 560px;
}
.card-text {
margin: 0;
padding: 0 var(--ha-space-4) var(--ha-space-2);
}
.vertical-divider {
align-self: stretch;
width: 1px;
background: var(--divider-color);
}
pre {
padding: var(--ha-space-4);
background: var(--secondary-background-color);
+2 -2
View File
@@ -924,7 +924,7 @@ class DemoHaSelector extends LitElement implements ProvideHassElement {
providers: [
{
engine_id: "stt.cloud",
name: "Home Assistant Cloud",
name: "Home Assistant Link",
supported_languages: ["en-US"],
deprecated: false,
},
@@ -934,7 +934,7 @@ class DemoHaSelector extends LitElement implements ProvideHassElement {
providers: [
{
engine_id: "tts.cloud",
name: "Home Assistant Cloud",
name: "Home Assistant Link",
supported_languages: ["en-US"],
deprecated: false,
},
@@ -2,3 +2,17 @@
title: Spinner
subtitle: Can be used to indicate an ongoing task.
---
`ha-spinner` is `hac-spinner` from `@home-assistant/components`.
## Accessibility
`ha-spinner` is exposed to screen readers as a `progressbar` named with the translated "Loading". When the surrounding text does not already say what is in progress, name it with a translated `accessible-label`, like "Installing update", rather than its state.
```html
<ha-spinner accessible-label="Installing update"></ha-spinner>
```
If the spinner only decorates text that already says what is in progress, hide it with `aria-hidden="true"`.
For an action started from a button, use `ha-button` with `loading` instead of putting a spinner inside the button.
+4 -2
View File
@@ -23,8 +23,10 @@ export class DemoHaSpinner extends LitElement {
<ha-spinner size="small"></ha-spinner>
<ha-spinner size="medium"></ha-spinner>
<ha-spinner size="large"></ha-spinner>
<ha-spinner aria-label="Doing something..."></ha-spinner>
<ha-spinner .ariaLabel=${"Doing something..."}></ha-spinner>
<ha-spinner accessible-label="Doing something..."></ha-spinner>
<ha-spinner
.accessibleLabel=${"Doing something..."}
></ha-spinner>
</div>
</ha-card>
`
@@ -10,6 +10,7 @@ import type {
} from "../../../../src/data/history";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import type { HomeAssistant } from "../../../../src/types";
import { followGalleryTheme } from "../../data/follow-gallery-theme";
const HOUR = 60 * 60 * 1000;
const HOURS = 48;
@@ -166,6 +167,7 @@ export class DemoStateHistoryCharts extends LitElement {
super.firstUpdated(changedProps);
const hass = provideHass(this);
hass.updateTranslations(null, "en");
followGalleryTheme(this, hass);
hass.addEntities(ENTITIES);
}
@@ -1,7 +1,9 @@
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import type { ChartSelectMode } from "../../../../src/components/chart/ha-chart-base";
import "../../../../src/components/chart/statistics-chart";
import "../../../../src/components/ha-button";
import "../../../../src/components/ha-card";
import type {
Statistics,
@@ -11,7 +13,9 @@ import type {
} from "../../../../src/data/recorder";
import { StatisticMeanType } from "../../../../src/data/recorder";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
import type { HomeAssistant } from "../../../../src/types";
import { followGalleryTheme } from "../../data/follow-gallery-theme";
const HOUR = 60 * 60 * 1000;
const HOURS = 48;
@@ -108,6 +112,64 @@ interface Example {
height?: string;
}
interface TimeRange {
start: number;
end: number;
}
interface RangeExample {
id: string;
title: string;
description: string;
statistics: Statistics;
statTypes: StatisticType[];
chartType: "line" | "bar";
unit: string;
selectMode: ChartSelectMode;
hint: string;
}
const RANGE_EXAMPLES: RangeExample[] = [
{
id: "point",
title: "Point selection",
description:
"With select-mode set to point, a click selects the hour that contains it, and everything outside fades. Dragging still zooms.",
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
statTypes: ["change"],
chartType: "bar",
unit: "kWh",
selectMode: "point",
hint: "Click on a bar to select its hour.",
},
{
id: "range-bar",
title: "Range selection on bars",
description:
"With select-mode set to range, dragging selects a time range instead of zooming, so several bars can be selected at once. A click still selects one bar.",
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
statTypes: ["change"],
chartType: "bar",
unit: "kWh",
selectMode: "range",
hint: "Click or drag on the chart to select one or more bars.",
},
{
id: "range",
title: "Range selection on lines",
description: "The same on a line chart.",
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM },
statTypes: ["mean", "min", "max"],
chartType: "line",
unit: "°C",
selectMode: "range",
hint: "Click or drag on the chart to select a period.",
},
];
const formatRange = (range: TimeRange) =>
`${new Date(range.start).toLocaleString()} to ${new Date(range.end).toLocaleString()}`;
const EXAMPLES: Example[] = [
{
title: "Sum as bars",
@@ -159,17 +221,20 @@ const EXAMPLES: Example[] = [
export class DemoStatisticsChart extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _selections: Record<string, TimeRange | undefined> = {};
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
const hass = provideHass(this);
hass.updateTranslations(null, "en");
followGalleryTheme(this, hass);
}
protected render() {
if (!this.hass) {
return nothing;
}
return EXAMPLES.map(
return html`${EXAMPLES.map(
(example) => html`
<ha-card header=${example.title}>
<div class="card-content">
@@ -191,7 +256,66 @@ export class DemoStatisticsChart extends LitElement {
</div>
</ha-card>
`
);
)}
${RANGE_EXAMPLES.map((example) => this._renderRangeExample(example))}`;
}
private _renderRangeExample(example: RangeExample) {
const selection = this._selections[example.id];
return html`
<ha-card header=${example.title}>
<div class="card-content">
<p>${example.description}</p>
<statistics-chart
.statisticsData=${example.statistics}
.metadata=${METADATA}
.names=${NAMES}
.statTypes=${example.statTypes}
.chartType=${example.chartType}
period="hour"
.unit=${example.unit}
.startTime=${START}
.endTime=${END}
.highlight=${selection}
.clickForMoreInfo=${false}
data-example=${example.id}
.selectMode=${example.selectMode}
hide-legend
@chart-select=${this._rangeSelected}
></statistics-chart>
<div class="selection">
${
selection
? html`
<span>${formatRange(selection)}</span>
<ha-button
appearance="plain"
size="s"
data-example=${example.id}
@click=${this._clearSelection}
>
Clear
</ha-button>
`
: html`<span class="hint">${example.hint}</span>`
}
</div>
</div>
</ha-card>
`;
}
private _rangeSelected(ev: HASSDomEvent<HASSDomEvents["chart-select"]>) {
const id = (ev.currentTarget as HTMLElement).dataset.example!;
this._selections = {
...this._selections,
[id]: ev.detail,
};
}
private _clearSelection(ev: Event) {
const id = (ev.currentTarget as HTMLElement).dataset.example!;
this._selections = { ...this._selections, [id]: undefined };
}
static styles = css`
@@ -202,6 +326,20 @@ export class DemoStatisticsChart extends LitElement {
p {
margin-top: 0;
}
.selection {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--ha-space-2);
min-height: 48px;
margin-top: var(--ha-space-2);
padding: 0 var(--ha-space-2) 0 var(--ha-space-4);
border-radius: var(--ha-border-radius-lg);
background-color: var(--secondary-background-color);
}
.hint {
color: var(--secondary-text-color);
}
`;
}
@@ -0,0 +1,6 @@
---
title: Card skeletons
subtitle: How a dashboard looks while its cards and badges load
---
Each card and badge sits in an `ha-skeleton-overlay`, which reads a skeleton from what the card or badge draws: every name, state and value gets its own text skeleton, and icons, images, controls and drawings get their own pieces. When loading ends, each part fades in. Turn off **Loading** to see the real cards, or use **Simulate loading** to watch them arrive one by one.
@@ -0,0 +1,440 @@
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { mockIcons } from "../../../../demo/src/stubs/icons";
import type { HASSDomTargetEvent } from "../../../../src/common/dom/fire_event";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-button";
import "../../../../src/components/ha-switch";
import type { HaSwitch } from "../../../../src/components/ha-switch";
import { LightColorMode } from "../../../../src/data/light";
import type { LovelaceBadgeConfig } from "../../../../src/data/lovelace/config/badge";
import type { LovelaceCardConfig } from "../../../../src/data/lovelace/config/card";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import "../../../../src/panels/lovelace/badges/hui-badge";
import type { HuiBadge } from "../../../../src/panels/lovelace/badges/hui-badge";
import "../../../../src/panels/lovelace/cards/hui-card";
import type { HuiCard } from "../../../../src/panels/lovelace/cards/hui-card";
import { computeCardGridSize } from "../../../../src/panels/lovelace/common/compute-card-grid-size";
import type { HomeAssistant } from "../../../../src/types";
import "../../ha-demo-options";
const ENTITIES = [
{
entity_id: "light.bed_light",
state: "on",
attributes: {
friendly_name: "Bed light",
supported_color_modes: [LightColorMode.BRIGHTNESS],
color_mode: LightColorMode.BRIGHTNESS,
brightness: 180,
},
},
{
entity_id: "light.kitchen_lights",
state: "on",
attributes: { friendly_name: "Kitchen lights" },
},
{
entity_id: "switch.tv_outlet",
state: "off",
attributes: { friendly_name: "TV outlet", device_class: "outlet" },
},
{
entity_id: "media_player.living_room",
state: "playing",
attributes: { friendly_name: "Living room speaker" },
},
{
entity_id: "climate.thermostat",
state: "heat",
attributes: {
friendly_name: "Thermostat",
current_temperature: 21,
temperature: 22,
hvac_modes: ["heat", "off"],
hvac_action: "heating",
},
},
{
entity_id: "lock.front_door",
state: "locked",
attributes: { friendly_name: "Front door" },
},
{
entity_id: "person.paulus",
state: "home",
attributes: {
friendly_name: "Paulus",
entity_picture: "/images/paulus.jpg",
},
},
{
entity_id: "sensor.living_room_temperature",
state: "21.4",
attributes: {
friendly_name: "Living room temperature",
device_class: "temperature",
unit_of_measurement: "°C",
state_class: "measurement",
},
},
{
entity_id: "sensor.living_room_humidity",
state: "54",
attributes: {
friendly_name: "Living room humidity",
device_class: "humidity",
unit_of_measurement: "%",
state_class: "measurement",
},
},
{
entity_id: "binary_sensor.back_door",
state: "off",
attributes: { friendly_name: "Back door", device_class: "door" },
},
{
entity_id: "camera.garden",
state: "idle",
attributes: { friendly_name: "Garden" },
},
];
/* The badges row at the top of a sections view */
const BADGES: LovelaceBadgeConfig[] = [
{ type: "entity", entity: "person.paulus", show_entity_picture: true },
{ type: "entity", entity: "sensor.living_room_temperature" },
{ type: "entity", entity: "light.kitchen_lights", show_name: true },
{ type: "entity", entity: "lock.front_door", color: "green" },
{
type: "entity",
entity: "binary_sensor.back_door",
show_name: true,
show_state: false,
},
];
const SECTIONS: LovelaceCardConfig[][] = [
[
{
type: "heading",
heading: "Living room",
badges: [
{ type: "entity", entity: "sensor.living_room_temperature" },
{ type: "entity", entity: "sensor.living_room_humidity" },
],
},
{
type: "tile",
entity: "light.bed_light",
features: [{ type: "light-brightness" }],
},
{ type: "tile", entity: "switch.tv_outlet" },
{ type: "tile", entity: "media_player.living_room" },
{ type: "tile", entity: "climate.thermostat", vertical: true },
{ type: "tile", entity: "lock.front_door", vertical: true },
{ type: "entity", entity: "sensor.living_room_temperature" },
{ type: "entity", entity: "sensor.living_room_humidity" },
],
[
{ type: "heading", heading: "Cameras" },
{ type: "picture-entity", entity: "camera.garden" },
{
type: "picture-glance",
title: "Kitchen",
image: "/images/kitchen.png",
entities: [
"light.kitchen_lights",
"switch.tv_outlet",
"binary_sensor.back_door",
],
},
{
type: "picture-entity",
image: "/images/bed.png",
entity: "light.bed_light",
},
],
[
{ type: "heading", heading: "Overview" },
{ type: "tile", entity: "person.paulus" },
{ type: "tile", entity: "binary_sensor.back_door" },
{
type: "entities",
title: "Climate",
entities: [
"climate.thermostat",
"sensor.living_room_temperature",
"sensor.living_room_humidity",
],
},
{
type: "glance",
title: "Doors and lights",
entities: [
"lock.front_door",
"binary_sensor.back_door",
"light.kitchen_lights",
],
},
{ type: "gauge", entity: "sensor.living_room_humidity" },
],
];
interface DemoSlot {
key: string;
card: HuiCard;
}
interface BadgeSlot {
key: string;
badge: HuiBadge;
}
@customElement("demo-lovelace-card-skeletons")
class DemoCardSkeletons extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _loaded = new Set<string>();
@state() private _simulating = false;
private _sections: DemoSlot[][] = [];
private _badges: BadgeSlot[] = [];
private _timers: number[] = [];
/* Whether each card or badge was last told it's loading */
private _loadingShown = new WeakMap<Element, boolean>();
protected firstUpdated(changedProperties: PropertyValues<this>) {
super.firstUpdated(changedProperties);
const hass = provideHass(this);
hass.updateTranslations(null, "en");
hass.updateTranslations("lovelace", "en");
hass.addEntities(ENTITIES);
mockIcons(hass);
// Camera snapshots come from a signed path; point it at a gallery image.
hass.mockWS("auth/sign_path", () => ({
path: "/images/office.jpg?authSig=gallery",
}));
}
public disconnectedCallback() {
super.disconnectedCallback();
this._clearTimers();
}
protected willUpdate(changedProperties: PropertyValues<this>) {
if (!changedProperties.has("hass") || !this.hass) {
return;
}
if (this._sections.length === 0) {
this._sections = SECTIONS.map((cards, sectionIndex) =>
cards.map((config, cardIndex) => {
const card = document.createElement("hui-card");
card.layout = "grid";
card.config = config;
return { key: `${sectionIndex}-${cardIndex}`, card };
})
);
this._badges = BADGES.map((config, index) => {
const badge = document.createElement("hui-badge");
badge.config = config;
return { key: `badge-${index}`, badge };
});
}
this._elements().forEach(({ element }) => {
element.hass = this.hass;
});
}
/* Every card and badge, as one list to measure and reveal */
private _elements() {
return [
...this._badges.map(({ key, badge }) => ({ key, element: badge })),
...this._sections.flat().map(({ key, card }) => ({ key, element: card })),
];
}
protected render() {
if (!this.hass) {
return nothing;
}
return html`
<ha-demo-options>
<ha-switch
.checked=${this._loaded.size === 0}
.disabled=${this._simulating}
@change=${this._loadingToggled}
></ha-switch>
<span>Loading</span>
<ha-button
size="s"
appearance="filled"
.disabled=${this._simulating}
@click=${this._simulate}
>
Simulate loading
</ha-button>
</ha-demo-options>
<div class="badges">${this._badges.map(({ badge }) => badge)}</div>
<div class="view">
${this._sections.map(
(slots) => html`
<div class="section">
${slots.map((slot) => this._renderSlot(slot))}
</div>
`
)}
</div>
`;
}
private _renderSlot({ card }: DemoSlot): TemplateResult {
const { rows, columns } = computeCardGridSize(card.getGridOptions());
const fitRows = rows !== "auto";
const fullWidth = columns === "full";
return html`
<div
class="card ${classMap({
"fit-rows": fitRows,
"full-width": fullWidth,
})}"
style=${styleMap({
"--column-size": fullWidth ? undefined : columns,
"--row-size": fitRows ? rows : undefined,
})}
>
${card}
</div>
`;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
// A card or badge makes its content when it first updates
this._elements().forEach(async ({ key, element }) => {
await element.updateComplete;
this._setLoading(element, !this._loaded.has(key));
});
}
/* Each card and badge already sits in its own skeleton overlay. Say it's
loading from inside, as a card waiting on its data does. */
private _setLoading(wrapper: HuiCard | HuiBadge, loading: boolean) {
const content = wrapper.querySelector(":scope > ha-skeleton-overlay > *");
if (
!(content instanceof HTMLElement) ||
this._loadingShown.get(content) === loading
) {
return;
}
this._loadingShown.set(content, loading);
fireEvent(content, "skeleton-loading", { loading });
}
private _keys(): string[] {
return this._elements().map(({ key }) => key);
}
private _loadingToggled(ev: HASSDomTargetEvent<HaSwitch>) {
this._clearTimers();
this._loaded = ev.target.checked ? new Set() : new Set(this._keys());
}
private _simulate() {
this._clearTimers();
this._loaded = new Set();
this._simulating = true;
const keys = this._keys();
keys.forEach((key) => {
const delay = 600 + Math.random() * 2400;
this._timers.push(
window.setTimeout(() => {
this._loaded = new Set(this._loaded).add(key);
if (this._loaded.size === keys.length) {
this._simulating = false;
}
}, delay)
);
});
}
private _clearTimers() {
this._timers.forEach((timer) => clearTimeout(timer));
this._timers = [];
this._simulating = false;
}
static styles = css`
ha-demo-options {
display: flex;
align-items: center;
gap: var(--ha-space-2);
}
ha-demo-options ha-button {
margin-inline-start: var(--ha-space-4);
}
.view {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: var(--ha-space-8);
padding: var(--ha-space-4);
background-color: var(--primary-background-color);
align-items: start;
}
.section {
--row-gap: 8px;
--column-gap: 8px;
--row-height: 56px;
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
grid-auto-rows: auto;
row-gap: var(--row-gap);
column-gap: var(--column-gap);
}
.card {
grid-row: span var(--row-size, 1);
grid-column: span min(var(--column-size, 12), 12);
}
.card.fit-rows {
height: calc(
(var(--row-size, 1) * (var(--row-height) + var(--row-gap))) - var(
--row-gap
)
);
}
.card.full-width {
grid-column: 1 / -1;
}
/* As hui-view-badges lays out the badges row */
.badges {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: var(--ha-space-2);
padding: var(--ha-space-4) var(--ha-space-4) 0;
background-color: var(--primary-background-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"demo-lovelace-card-skeletons": DemoCardSkeletons;
}
}
@@ -1,8 +1,8 @@
---
title: Cloud account
title: Home Assistant Link account
---
The [Home Assistant Cloud](https://www.nabucasa.com/) account page, rendered from
mocked cloud data. The controls at the top flip the mocked subscription, remote,
The [Home Assistant Link](https://www.nabucasa.com/) account page, rendered from
mocked Home Assistant Link data. The controls at the top flip the mocked subscription, remote,
backup, onboarding, and feature state so every UI state can be previewed here
without a real cloud account.
without a real Home Assistant Link account.
+133
View File
@@ -187,6 +187,139 @@ const ENTITIES = [
current_tilt_position: 70,
},
},
{
entity_id: "cover.shade",
state: "open",
attributes: {
friendly_name: "Shade",
device_class: "shade",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 60,
},
},
{
entity_id: "cover.shutter",
state: "open",
attributes: {
friendly_name: "Shutter",
device_class: "shutter",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 40,
},
},
{
entity_id: "cover.awning",
state: "open",
attributes: {
friendly_name: "Awning",
device_class: "awning",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 70,
},
},
{
entity_id: "cover.curtain",
state: "open",
attributes: {
friendly_name: "Curtain",
device_class: "curtain",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 50,
},
},
{
entity_id: "cover.door",
state: "open",
attributes: {
friendly_name: "Door",
device_class: "door",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 30,
},
},
{
entity_id: "cover.gate",
state: "open",
attributes: {
friendly_name: "Gate",
device_class: "gate",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 30,
},
},
{
entity_id: "cover.window",
state: "open",
attributes: {
friendly_name: "Window",
device_class: "window",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 50,
},
},
{
entity_id: "cover.garage",
state: "closed",
attributes: {
friendly_name: "Garage door",
device_class: "garage",
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
},
},
{
entity_id: "cover.unknown",
state: "unknown",
attributes: {
friendly_name: "Unknown position",
device_class: "shade",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
},
},
{
entity_id: "cover.unavailable",
state: "unavailable",
attributes: {
friendly_name: "Unavailable",
device_class: "shutter",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
},
},
];
@customElement("demo-more-info-cover")
+11 -2
View File
@@ -250,7 +250,16 @@ class DemoMoreInfoUpdate extends LitElement {
"update/release_notes",
(msg: { type: string; entity_id: string }) => {
if (msg.entity_id === "update.update16") {
return LONG_TEXT;
return {
release_notes: LONG_TEXT,
messages: [
{
severity: "warning",
message:
"Do not restart, remove power from, or otherwise interrupt the device while the update is in progress.",
},
],
};
}
if (msg.entity_id === "update.update17") {
return Promise.reject({
@@ -261,7 +270,7 @@ class DemoMoreInfoUpdate extends LitElement {
if (msg.entity_id === "update.update18") {
return undefined;
}
return null;
return { release_notes: null, messages: [] };
}
);
}
+43 -43
View File
@@ -40,7 +40,7 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.1.0",
"@babel/runtime": "8.1.2",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.4",
"@codemirror/commands": "6.11.1",
@@ -48,21 +48,21 @@
"@codemirror/lang-python": "6.2.1",
"@codemirror/lang-yaml": "6.1.3",
"@codemirror/language": "6.13.1",
"@codemirror/lint": "6.9.7",
"@codemirror/lint": "6.9.8",
"@codemirror/search": "6.7.2",
"@codemirror/state": "6.7.6",
"@codemirror/view": "6.43.15",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "8.0.2",
"@formatjs/intl-displaynames": "8.0.1",
"@formatjs/intl-durationformat": "0.12.3",
"@formatjs/intl-getcanonicallocales": "3.3.0",
"@formatjs/intl-listformat": "9.0.1",
"@formatjs/intl-locale": "5.4.2",
"@formatjs/intl-numberformat": "10.0.2",
"@formatjs/intl-pluralrules": "7.0.2",
"@formatjs/intl-relativetimeformat": "13.0.1",
"@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.5",
"@lezer/highlight": "1.2.5",
@@ -77,18 +77,18 @@
"@mdi/svg": "7.4.47",
"@replit/codemirror-indentation-markers": "6.5.3",
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.2",
"@tsparticles/preset-links": "4.5.2",
"@versatiles/style": "8.1.1",
"@tsparticles/engine": "4.5.4",
"@tsparticles/preset-links": "4.5.4",
"@versatiles/style": "9.1.0",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.202.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10",
"barcode-detector": "3.2.3",
"@vvo/tzdb": "6.204.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
"barcode-detector": "3.2.4",
"cally": "0.9.2",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
"cropperjs": "1.7.0",
"cropperjs": "2.3.1",
"culori": "4.0.2",
"date-fns": "4.4.0",
"decimal.js": "10.6.0",
@@ -97,19 +97,19 @@
"echarts": "6.1.0",
"echarts-extension-chart2music": "0.1.1",
"element-internals-polyfill": "3.0.2",
"fullcalendar": "7.1.4",
"fullcalendar": "7.1.5",
"fuse.js": "7.5.0",
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.8.1",
"home-assistant-js-websocket": "9.9.0",
"idb-keyval": "6.3.0",
"intl-messageformat": "12.1.4",
"intl-messageformat": "12.2.0",
"js-yaml": "5.5.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.16.0",
"marked": "18.1.3",
"maplibre-gl": "6.19.0",
"marked": "18.2.1",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
@@ -136,24 +136,24 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.1.0",
"@babel/core": "8.1.2",
"@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.0.6",
"@babel/plugin-transform-runtime": "8.1.2",
"@babel/preset-env": "8.0.7",
"@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.67.0",
"@html-eslint/eslint-plugin": "0.68.0",
"@lokalise/node-api": "17.0.1",
"@octokit/auth-oauth-device": "8.0.5",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.0",
"@playwright/test": "1.65.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.1",
"@rspack/core": "2.3.3",
"@rspack/dev-server": "2.2.2",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
@@ -170,17 +170,17 @@
"@types/sortablejs": "1.15.9",
"@types/tar": "7.0.87",
"@typescript/native": "npm:[email protected]",
"@vitest/coverage-v8": "5.1.0",
"@vitest/coverage-v8": "5.1.1",
"babel-loader": "10.1.1",
"babel-plugin-polyfill-corejs3": "1.0.0",
"browserslist": "4.29.5",
"browserslist": "4.29.6",
"browserslist-useragent-regexp": "4.1.4",
"core-js-compat": "3.51.0",
"del": "9.0.1",
"eslint": "10.14.0",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.17.1",
"eslint-plugin-import-x": "4.18.1",
"eslint-plugin-lit": "2.3.1",
"eslint-plugin-lit-a11y": "5.1.3",
"eslint-plugin-unused-imports": "4.4.1",
@@ -188,42 +188,42 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "14.0.4",
"glob": "14.0.6",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
"gulp-rename": "2.1.0",
"html-minifier-terser": "7.2.0",
"husky": "9.1.7",
"jsdom": "31.0.0",
"jsdom": "31.0.1",
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
"lint-staged": "17.6.0",
"lint-staged": "17.6.1",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.18.1",
"map-stream": "0.0.7",
"minify-literals": "2.2.0",
"pinst": "3.0.0",
"prettier": "3.9.10",
"prettier": "3.10.1",
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.6",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "7.5.22",
"tar": "7.5.23",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.72.1",
"vite": "8.3.6",
"typescript-eslint": "8.73.0",
"vite": "8.3.8",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.0",
"vitest": "5.1.1",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]8.0",
"packageManager": "pnpm@12.21.0",
"volta": {
"node": "24.22.2"
"node": "24.22.3"
}
}
+1 -1
View File
@@ -53,7 +53,7 @@
},
"devDependencies": {
"@custom-elements-manifest/analyzer": "0.11.0",
"@rslib/core": "1.0.6",
"@rslib/core": "1.0.7",
"lit": "3.3.3",
"typescript": "6.0.3"
}
@@ -0,0 +1,8 @@
import { define } from "../../utils/registration/define";
import { HacSpinner } from "./hac-spinner";
import { TAG_NAME } from "./info";
// Registers <hac-spinner> in the global registry, as used by Home Assistant
define(TAG_NAME, HacSpinner);
export { HacSpinner };
@@ -0,0 +1,219 @@
import { css, html, LitElement, nothing } from "lit";
import { property } from "lit/decorators.js";
/**
* @element hac-spinner
*
* @summary
* Circular progress indicator for a task of unknown duration. Exposed to
* assistive technology as an indeterminate `progressbar`.
*
* Set `aria-hidden="true"` when the spinner only decorates text that already
* says what is in progress. It is passed on to the progressbar, because in
* Chromium the host's `aria-hidden` alone doesn't keep the label out of a
* 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.
*/
export class HacSpinner extends LitElement {
/** Preset diameter: 16, 28, 48 or 68 pixels. Defaults to 48 pixels. */
@property({ reflect: true }) public size?:
"tiny" | "small" | "medium" | "large";
/**
* Accessible name. Name what is in progress, like "Installing update",
* rather than its state. Defaults to "Loading".
*/
@property({ attribute: "accessible-label" })
public accessibleLabel?: string;
/** Name used without `accessibleLabel`. Subclasses can translate it. */
protected defaultLabel(): string {
return "Loading";
}
static get observedAttributes() {
return [...super.observedAttributes, "aria-hidden"];
}
public attributeChangedCallback(
name: string,
oldValue: string | null,
newValue: string | null
) {
super.attributeChangedCallback(name, oldValue, newValue);
if (name === "aria-hidden") {
this.requestUpdate();
}
}
protected render() {
return html`
<svg
part="spinner base"
role="progressbar"
aria-label=${this.accessibleLabel || this.defaultLabel()}
aria-hidden=${this.getAttribute("aria-hidden") ?? nothing}
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle class="track" />
<circle class="indicator" />
</svg>
`;
}
/*
* Fallback order: --hac-spinner-*, then the variables of ha-spinner
* (--ha-spinner-*, --primary-color, --divider-color) so existing themes and
* callers keep working, then the semantic tokens and their light values for
* use outside Home Assistant. A size preset wins over --ha-spinner-size, as
* it did in ha-spinner.
*
* --indicator-color, --track-color, --track-width and --speed are the
* variables ha-spinner inherited from wa-spinner. They are set on the host
* like they were there, so a rule on the element still overrides them but a
* value from an ancestor doesn't leak in.
*
* The ha-spinner and wa-spinner variables are temporary, see "Theming" in
* the README.
*/
static styles = css`
:host {
--indicator-color: var(
--ha-spinner-indicator-color,
var(--primary-color, var(--ha-color-fill-primary-loud-resting, #009ac7))
);
--track-color: var(
--ha-spinner-divider-color,
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
);
--track-width: 4px;
--speed: 3.5s;
--_size: var(
--hac-spinner-size,
var(--_preset-size, var(--ha-spinner-size, 48px))
);
box-sizing: border-box;
flex: none;
display: inline-flex;
width: var(--_size);
height: var(--_size);
}
:host([hidden]) {
display: none !important;
}
:host([size="tiny"]) {
--_preset-size: 16px;
}
:host([size="small"]) {
--_preset-size: 28px;
}
:host([size="medium"]) {
--_preset-size: 48px;
}
:host([size="large"]) {
--_preset-size: 68px;
}
svg {
width: 100%;
height: 100%;
aspect-ratio: 1;
animation: spin var(--speed) linear infinite;
}
.track,
.indicator {
--_width: var(--hac-spinner-track-width, var(--track-width));
--_radius: calc(var(--_size) / 2 - var(--_width) / 2);
--_circumference: calc(var(--_radius) * 2 * 3.141592654);
cx: calc(var(--_size) / 2);
cy: calc(var(--_size) / 2);
r: var(--_radius);
fill: none;
stroke-width: var(--_width);
}
.track {
stroke: var(--hac-spinner-track-color, var(--track-color));
}
.indicator {
stroke: var(--hac-spinner-indicator-color, var(--indicator-color));
stroke-linecap: round;
stroke-dasharray:
calc(0.597 * var(--_circumference)), calc(0.796 * var(--_circumference));
stroke-dashoffset: calc(-0.04 * var(--_circumference));
animation: dash 1.5s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
svg,
.indicator {
animation: none;
}
}
/* Keep the track and the arc apart in forced colors mode */
@media (forced-colors: active) {
svg {
forced-color-adjust: none;
}
.track {
stroke: GrayText;
}
.indicator {
stroke: CanvasText;
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes dash {
0% {
stroke-dasharray:
calc(0.008 * var(--_circumference)),
calc(1.194 * var(--_circumference));
stroke-dashoffset: 0;
}
50% {
stroke-dasharray:
calc(0.716 * var(--_circumference)),
calc(1.194 * var(--_circumference));
stroke-dashoffset: calc(-0.278 * var(--_circumference));
}
100% {
stroke-dasharray:
calc(0.716 * var(--_circumference)),
calc(1.194 * var(--_circumference));
stroke-dashoffset: calc(-0.987 * var(--_circumference));
}
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hac-spinner": HacSpinner;
}
}
@@ -0,0 +1,5 @@
/** Tag name of the element. */
export const TAG_NAME = "hac-spinner";
/** Version of <hac-spinner>. */
export const VERSION = "0.1.0";
@@ -0,0 +1,15 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacSpinner } from "./hac-spinner";
import { TAG_NAME } from "./info";
export { HacSpinner };
/**
* The bundled <hac-spinner> for a scoped registry:
* `ScopedElementsMixin(LitElement, [hacSpinner])` or
* `createScopedElementRegistry([hacSpinner])`.
*/
export const hacSpinner: ElementDefinition<typeof HacSpinner> = {
tagName: TAG_NAME,
element: HacSpinner,
};
+1377 -1289
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

+1 -1
View File
@@ -14,7 +14,7 @@
"minimumReleaseAge": "3 days",
"postUpdateOptions": ["pnpmDedupe"],
"constraints": {
"ghActionsLock": "v0.4.1"
"ghActionsLock": "v0.5.1"
},
"lockFileMaintenance": {
"description": ["Run after patch releases but before next beta"],
@@ -0,0 +1,55 @@
interface EntityWithColorTemp {
attributes?: Record<string, unknown>;
}
const finiteRange = (
min: unknown,
max: unknown
): { min: number; max: number } | undefined => {
if (typeof min !== "number" || typeof max !== "number") {
return undefined;
}
if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
return undefined;
}
return { min, max };
};
/**
* Kelvin bounds reported by the given entity states.
*
* Several lights use the overlap of their ranges, because one
* `color_temp_kelvin` value is sent to every target. When the ranges do not
* overlap, the result spans the widest range so it still has a valid min and
* max. Entities without a finite range are ignored. Returns undefined when
* nothing reports a range, so the caller keeps the selector min and max.
*/
export const kelvinRangeFromEntityStates = (
states: Readonly<Record<string, EntityWithColorTemp | undefined>> | undefined
): { min: number; max: number } | undefined => {
if (!states) {
return undefined;
}
const ranges: { min: number; max: number }[] = [];
for (const state of Object.values(states)) {
const range = finiteRange(
state?.attributes?.min_color_temp_kelvin,
state?.attributes?.max_color_temp_kelvin
);
if (range) {
ranges.push(range);
}
}
if (!ranges.length) {
return undefined;
}
let min = Math.max(...ranges.map((range) => range.min));
let max = Math.min(...ranges.map((range) => range.max));
if (min > max) {
min = Math.min(...ranges.map((range) => range.min));
max = Math.max(...ranges.map((range) => range.max));
}
return { min, max };
};
@@ -89,10 +89,19 @@ export class LegendFitController {
private _fit() {
const list = this._element;
const rowWidth = list?.getBoundingClientRect().width;
if (!list || !rowWidth) {
if (!list) {
return;
}
const style = getComputedStyle(list);
const rowWidth = parseFloat(style.width);
// Bounding rects include transforms, such as a dialog scaling in, which
// never resize the list, so measure in layout pixels
const scale = list.getBoundingClientRect().width / rowWidth;
if (!rowWidth || !scale) {
return;
}
const layoutWidth = (element: Element) =>
element.getBoundingClientRect().width / scale;
const children = Array.from(list.children);
const more = children.find((child) =>
child.classList.contains("legend-more")
@@ -107,9 +116,7 @@ export class LegendFitController {
}
this._more = more;
}
const widths = children
.filter((child) => child !== more)
.map((child) => child.getBoundingClientRect().width);
const widths = children.filter((child) => child !== more).map(layoutWidth);
// Values resize the items on every state update. Fitting each item at its
// widest since the last resize keeps the more button from flickering.
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
@@ -122,9 +129,9 @@ export class LegendFitController {
}
const fit = fitInRows(
this._widths,
more?.getBoundingClientRect().width ?? 0,
more ? layoutWidth(more) : 0,
rowWidth,
parseFloat(getComputedStyle(list).columnGap) || 0,
parseFloat(style.columnGap) || 0,
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
);
if (fit !== this.fit) {
+549
View File
@@ -0,0 +1,549 @@
/**
* 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 => {
// An overlay only wraps content, so what it wraps is read
if (
element.localName.startsWith("ha-skeleton") &&
element.localName !== "ha-skeleton-overlay"
) {
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;
/* 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", "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 context = fontContext(style, `${size}px`);
if (!context) {
return { top: size * 0.2, height: size * 0.7 };
}
const metrics = context.measureText("H");
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);
});
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);
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
const clip = owner.getBoundingClientRect();
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 =
rect.left < clip.left - 1
? clip.left + ellipsisWidth(style)
: rect.left;
const right =
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;
}
if (override === "keep") {
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
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;
}
if (child instanceof HTMLElement) {
addText(child);
}
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
}
};
walk(root);
return {
pieces: mergeLines(pieces),
parts: [...parts],
textParts: [...textParts],
};
};
+29
View File
@@ -0,0 +1,29 @@
const INTERACTIVE_SELECTOR = [
"a[href]",
"button",
"input",
"select",
"textarea",
"summary",
"label",
"[contenteditable]:not([contenteditable='false'])",
"[tabindex]:not([tabindex='-1'])",
"[role='button']",
"[role='link']",
"[role='checkbox']",
"[role='radio']",
"[role='switch']",
"[role='slider']",
"[role='tab']",
"[role='menuitem']",
"[role='option']",
"[role='combobox']",
"[role='textbox']",
].join(",");
/**
* Whether `node` is an element that handles clicks or keyboard input on its
* own, such as a button, link, form control or a focusable widget.
*/
export const isInteractiveElement = (node: EventTarget): boolean =>
node instanceof Element && node.matches(INTERACTIVE_SELECTOR);
+1
View File
@@ -3,6 +3,7 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
"ha-slider",
"ha-control-switch",
"ha-control-circular-slider",
"ha-state-control-cover",
"ha-hs-color-picker",
"ha-map",
// Charts pan and pinch-zoom on touch
+5 -5
View File
@@ -1,12 +1,12 @@
import type { HomeAssistant } from "../../types";
import type { HassServices } from "home-assistant-js-websocket";
import { getToggleAction } from "./get_toggle_action";
export const canToggleDomain = (hass: HomeAssistant, domain: string) => {
const services = hass.services[domain];
if (!services) {
export const canToggleDomain = (services: HassServices, domain: string) => {
const domainServices = services[domain];
if (!domainServices) {
return false;
}
const actionOn = getToggleAction(domain, true);
const actionOff = getToggleAction(domain, false);
return actionOn in services && actionOff in services;
return actionOn in domainServices && actionOff in domainServices;
};
+13 -6
View File
@@ -1,23 +1,30 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HomeAssistant } from "../../types";
import type {
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import { canToggleDomain } from "./can_toggle_domain";
import { computeStateDomain } from "./compute_state_domain";
import { supportsFeature } from "./supports-feature";
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
export const canToggleState = (
states: HassEntities,
services: HassServices,
stateObj: HassEntity
) => {
const domain = computeStateDomain(stateObj);
if (domain === "group") {
if (
stateObj.attributes?.entity_id?.some((entity) => {
const entityStateObj = hass.states[entity];
const entityStateObj = states[entity];
if (!entityStateObj) {
return false;
}
const entityDomain = computeStateDomain(entityStateObj);
return canToggleDomain(hass, entityDomain);
return canToggleDomain(services, entityDomain);
})
) {
return stateObj.state === "on" || stateObj.state === "off";
@@ -35,5 +42,5 @@ export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
);
}
return canToggleDomain(hass, domain);
return canToggleDomain(services, domain);
};
+12 -2
View File
@@ -4,16 +4,23 @@ import {
mdiArrowDown,
mdiArrowExpandHorizontal,
mdiArrowUp,
mdiDoorClosed,
mdiDoorOpen,
mdiGate,
mdiGateOpen,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
export const computeOpenIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "awning":
case "door":
return mdiDoorOpen;
case "gate":
return mdiGateOpen;
case "curtain":
return mdiArrowExpandHorizontal;
case "awning":
return mdiArrowDown;
default:
return mdiArrowUp;
}
@@ -21,11 +28,14 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
export const computeCloseIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "awning":
case "door":
return mdiDoorClosed;
case "gate":
return mdiGate;
case "curtain":
return mdiArrowCollapseHorizontal;
case "awning":
return mdiArrowUp;
default:
return mdiArrowDown;
}
+2 -17
View File
@@ -163,21 +163,9 @@ export const findEntities = (
return results;
};
export const excludeEntities = (
entityIds: string[],
excludedEntityIds?: string[]
): string[] => {
if (!excludedEntityIds?.length) {
return entityIds;
}
const excluded = new Set(excludedEntityIds);
return entityIds.filter((entityId) => !excluded.has(entityId));
};
export const findFilteredEntities = (
sources: EntityFilterSources,
filters: EntityFilter[],
excludedEntityIds?: string[]
filters: EntityFilter[]
): string[] => {
const filterFuncs = filters.map((filter) =>
generateEntityFilter(
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
filter
)
);
return excludeEntities(
findEntities(Object.keys(sources.states), filterFuncs),
excludedEntityIds
);
return findEntities(Object.keys(sources.states), filterFuncs);
};
+11 -4
View File
@@ -1,11 +1,18 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type {
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import { UNAVAILABLE } from "../../data/entity/entity";
import type { HomeAssistant } from "../../types";
import { DOMAINS_WITH_CARD } from "../const";
import { canToggleState } from "./can_toggle_state";
import { computeStateDomain } from "./compute_state_domain";
export const stateCardType = (hass: HomeAssistant, stateObj: HassEntity) => {
export const stateCardType = (
states: HassEntities,
services: HassServices,
stateObj: HassEntity
) => {
if (stateObj.state === UNAVAILABLE) {
return "display";
}
@@ -16,7 +23,7 @@ export const stateCardType = (hass: HomeAssistant, stateObj: HassEntity) => {
return domain;
}
if (
canToggleState(hass, stateObj) &&
canToggleState(states, services, stateObj) &&
stateObj.attributes.control !== "hidden"
) {
return "toggle";
+7 -1
View File
@@ -161,6 +161,9 @@ export const getNumberFormatOptions = (
return undefined;
};
// Intl.NumberFormat throws a RangeError for more fraction digits than this.
const MAX_FRACTION_DIGITS = 100;
/**
* Generates default options for Intl.NumberFormat
* @param num The number to be formatted
@@ -185,7 +188,10 @@ export const getDefaultFormatOptions = (
(options.minimumFractionDigits === undefined &&
options.maximumFractionDigits === undefined)
) {
const digits = num.indexOf(".") > -1 ? num.split(".")[1].length : 0;
const digits = Math.min(
num.indexOf(".") > -1 ? num.split(".")[1].length : 0,
MAX_FRACTION_DIGITS
);
defaultOptions.minimumFractionDigits = digits;
defaultOptions.maximumFractionDigits = digits;
}
+10 -2
View File
@@ -1,2 +1,10 @@
export const capitalizeFirstLetter = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1);
export const capitalizeFirstLetter = (str: string) => {
// Take the first code point, not code unit, so letters outside the BMP
// (stored as a surrogate pair) are uppercased too.
const first = str.codePointAt(0);
if (first === undefined) {
return str;
}
const firstLetter = String.fromCodePoint(first);
return firstLetter.toUpperCase() + str.slice(firstLetter.length);
};
+20 -4
View File
@@ -1,11 +1,27 @@
// Unanchored regex fragments, shared as the single source of truth for both
// the boolean validators below and the HTML `pattern` attribute (the browser
// anchors a pattern as `^(?:…)$`).
const IPV4 =
"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
const IPV6 =
"(?:([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))";
// Decimal octet 0-255 without leading zeros.
const DEC_OCTET = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])";
const IPV4 = `(?:${DEC_OCTET}\\.){3}${DEC_OCTET}`;
// IPv6 grammar from RFC 3986, section 3.2.2.
const H16 = "[0-9a-fA-F]{1,4}";
const LS32 = `(?:${H16}:${H16}|${IPV4})`;
const IPV6 = `(?:${[
`(?:${H16}:){6}${LS32}`,
`::(?:${H16}:){5}${LS32}`,
`(?:${H16})?::(?:${H16}:){4}${LS32}`,
`(?:(?:${H16}:){0,1}${H16})?::(?:${H16}:){3}${LS32}`,
`(?:(?:${H16}:){0,2}${H16})?::(?:${H16}:){2}${LS32}`,
`(?:(?:${H16}:){0,3}${H16})?::${H16}:${LS32}`,
`(?:(?:${H16}:){0,4}${H16})?::${LS32}`,
`(?:(?:${H16}:){0,5}${H16})?::${H16}`,
`(?:(?:${H16}:){0,6}${H16})?::`,
].join("|")})`;
// CIDR prefix lengths: 0-32 for IPv4, 0-128 for IPv6.
const IPV4_PREFIX = "(?:3[0-2]|[12]?[0-9])";
+2 -2
View File
@@ -1,8 +1,8 @@
// https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1
export const slugify = (value: string, delimiter = "_") => {
const a =
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧхîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghhiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
const p = new RegExp(a.split("").join("|"), "g");
const complex_cyrillic = {
ж: "zh",
@@ -0,0 +1,33 @@
import type { LocalizeFunc } from "./localize";
const YAML_ERROR_REASON_KEYS = new Map(
Object.entries({
"duplicated mapping key": "duplicated_mapping_key",
"bad indentation of a mapping entry": "bad_mapping_indentation",
"bad indentation of a sequence entry": "bad_sequence_indentation",
"deficient indentation": "deficient_indentation",
"tab characters must not be used in indentation": "tab_indentation",
"can not read a block mapping entry; a multiline key may not be an implicit key":
"multiline_implicit_key",
"a whitespace character is expected after the key-value separator within a block mapping":
"missing_key_value_space",
"expected ':' after a mapping key": "missing_colon",
"missed comma between flow collection entries": "missing_comma",
"unexpected end of the stream within a flow collection":
"unterminated_flow_collection",
"unexpected end of the stream within a single quoted scalar":
"unterminated_single_quote",
"unexpected end of the stream within a double quoted scalar":
"unterminated_double_quote",
"end of the stream or a document separator is expected":
"unexpected_content",
} as const)
);
export const localizeYamlErrorReason = (
localize: LocalizeFunc,
reason: string | undefined
): string | undefined => {
const key = reason ? YAML_ERROR_REASON_KEYS.get(reason) : undefined;
return key ? localize(`ui.components.yaml-editor.reasons.${key}`) : reason;
};
@@ -0,0 +1,17 @@
import {
createQueryString,
type QueryParamConfig,
type QueryParamValues,
} from "./query-params";
export const energyEditorQueryParamConfig = {
string: ["stat_energy_from", "stat_energy_to", "stat_consumption"],
} as const satisfies QueryParamConfig;
export type EnergyEditorQueryParams = QueryParamValues<
typeof energyEditorQueryParamConfig
>;
export const createEnergyEditorQueryString = (
values: EnergyEditorQueryParams
): string => createQueryString(values, energyEditorQueryParamConfig);
+5 -1
View File
@@ -82,7 +82,11 @@ export function decodeQueryParams(
for (const key of config.date ?? []) {
const value = getSearchParam(searchParams, key);
if (value) {
params[key] = new Date(value);
const date = new Date(value);
// Leave out dates that can't be parsed, like a missing value.
if (!Number.isNaN(date.getTime())) {
params[key] = date;
}
}
}
for (const { key, trueValue } of config.boolean ?? []) {
+7
View File
@@ -0,0 +1,7 @@
/** Where a value is in a config, e.g. `["actions", 0, "then", 1]`. */
export type ConfigPath = (string | number)[];
export const stringifyPath = (path: ConfigPath): string => path.join("/");
export const pathEquals = (a: ConfigPath, b: ConfigPath): boolean =>
a.length === b.length && a.every((segment, index) => segment === b[index]);
+1
View File
@@ -37,6 +37,7 @@ export const debounce = <T extends any[]>(
debouncedFunc.cancel = () => {
clearTimeout(timeout);
timeout = undefined;
trailingArgs = undefined;
};
+8 -5
View File
@@ -2,14 +2,17 @@ export const groupBy = <T>(
list: T[],
keySelector: (item: T) => string
): Record<string, T[]> => {
const result = {};
// Group in a Map so keys like `constructor` or `__proto__` don't collide
// with Object.prototype.
const groups = new Map<string, T[]>();
for (const item of list) {
const key = keySelector(item);
if (key in result) {
result[key].push(item);
const group = groups.get(key);
if (group) {
group.push(item);
} else {
result[key] = [item];
groups.set(key, [item]);
}
}
return result;
return Object.fromEntries(groups);
};
+2 -1
View File
@@ -11,7 +11,8 @@
* parseAnimationDuration("invalid") // Returns 0
*/
export const parseAnimationDuration = (duration: string): number => {
const trimmed = duration.trim();
// CSS units are case-insensitive, e.g. "3S" is the same as "3s".
const trimmed = duration.trim().toLowerCase();
let value: number;
let multiplier: number;
+66 -13
View File
@@ -1,12 +1,18 @@
import { mdiChevronUp } from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { fireEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import "../ha-icon-button";
@customElement("ha-automation-row")
export class HaAutomationRow extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@property({ attribute: "left-chevron", type: Boolean })
public leftChevron = false;
@@ -30,10 +36,40 @@ export class HaAutomationRow extends LitElement {
@property({ type: Boolean, reflect: true })
public dim = false;
/** Makes the row a link, with the icons slot outside of it */
@property() public href?: string;
@query(".row")
private _rowElement?: HTMLDivElement;
@query(".link")
private _linkElement?: HTMLAnchorElement;
protected render(): TemplateResult {
const content = html`
<div class="leading-icon-wrapper">
<slot name="leading-icon"></slot>
</div>
<div class="header">
<slot name="header"></slot>
<slot name="event"></slot>
</div>
`;
const icons = html`
<div class="icons">
<slot name="icons"></slot>
</div>
`;
if (this.href) {
return html`
<div class="row has-link">
<a class="link" href=${this.href}>${content}</a>
${icons}
</div>
`;
}
return html`
<div
class="row"
@@ -47,23 +83,16 @@ export class HaAutomationRow extends LitElement {
<ha-icon-button
class="expand-button"
.path=${mdiChevronUp}
.label=${this._localize(
this.collapsed ? "ui.common.expand" : "ui.common.collapse"
)}
@click=${this._handleExpand}
@keydown=${this._handleExpand}
></ha-icon-button>
`
: nothing
}
<div class="leading-icon-wrapper">
<slot name="leading-icon"></slot>
</div>
<div class="header">
<slot name="header"></slot>
<slot name="event"></slot>
</div>
<div class="icons">
<slot name="icons"></slot>
</div>
${content} ${icons}
</div>
`;
}
@@ -119,7 +148,7 @@ export class HaAutomationRow extends LitElement {
public focus() {
requestAnimationFrame(() => {
this._rowElement?.focus();
(this._linkElement ?? this._rowElement)?.focus();
});
}
@@ -144,6 +173,30 @@ export class HaAutomationRow extends LitElement {
outline: var(--wa-focus-ring);
outline-offset: -2px;
}
.row.has-link {
padding-left: 0;
padding-inline-start: 0;
cursor: default;
}
.link {
display: flex;
align-items: flex-start;
align-self: stretch;
flex: 1;
min-width: 0;
padding-left: var(--ha-space-3);
padding-inline-start: var(--ha-space-3);
padding-inline-end: initial;
color: inherit;
text-decoration: none;
cursor: pointer;
outline: none;
border-radius: inherit;
}
.link:focus-visible {
outline: var(--wa-focus-ring);
outline-offset: -2px;
}
.expand-button {
transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
color: var(--ha-color-on-neutral-quiet);
+22
View File
@@ -0,0 +1,22 @@
import { css } from "lit";
/* The space a chart takes while its data loads, as big as `ha-chart-base`
draws one by default: half as tall as it's wide, within the same limits,
with a line for its legend under it. Put the placeholder and its legend
in a `.placeholder-container` as wide as the chart will be. */
export const chartPlaceholderStyles = css`
.placeholder-container {
container-type: inline-size;
}
.placeholder {
display: flex;
align-items: center;
justify-content: center;
height: min(max(50cqi, 200px), var(--chart-max-height, 350px));
}
.legend-placeholder {
width: 40%;
height: 16px;
margin: 10px auto;
}
`;
+6 -5
View File
@@ -19,6 +19,7 @@ interface MinMaxFrame {
maxPoint: Point;
maxX: number;
maxY: number;
lastX: number;
gapPoint: Point | undefined;
}
@@ -68,6 +69,7 @@ function newFrame(
maxPoint: point,
maxX: x,
maxY: y,
lastX: x,
gapPoint,
};
}
@@ -174,6 +176,7 @@ export function downSampleLineData<
if (!frame) {
frames.set(frameIndex, newFrame(point, x, y, undefined));
} else if (frame.hasValue) {
frame.lastX = x;
// Match the original strict-less / strict-greater comparisons so the
// first occurrence wins on ties.
if (y < frame.minY) {
@@ -189,6 +192,7 @@ export function downSampleLineData<
} else {
// the frame held nothing but a marker so far
frame.hasValue = true;
frame.lastX = x;
frame.minPoint = point;
frame.minX = x;
frame.minY = y;
@@ -213,11 +217,8 @@ export function downSampleLineData<
if (frame.gapPoint !== undefined) {
// A marker followed by a value in its own frame is a gap that closed
// within one frame, which is about one device pixel: too narrow to show.
// The kept points are exactly min and max, so comparing against the
// later of the two catches that without any work on the ingest path. A
// marker-only frame compares against its own x and always passes.
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
// That value may be neither min nor max, so check the frame's last x.
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
result.push(frame.gapPoint as T);
}
}
+221 -5
View File
@@ -7,7 +7,10 @@ import {
mdiRestart,
} from "@mdi/js";
import { differenceInMinutes } from "date-fns";
import type { DataZoomComponentOption } from "echarts/components";
import type {
DataZoomComponentOption,
MarkAreaComponentOption,
} from "echarts/components";
import type { EChartsType } from "echarts/core";
import type {
ECElementEvent,
@@ -90,14 +93,29 @@ export const DEFAULT_CHART_WIDTH = 500;
// is short enough for a whole screenful; on a desktop that would cover the page.
const VISIBILITY_ROOT_MARGIN_NARROW = "100%";
const VISIBILITY_ROOT_MARGIN = "300px";
const CLICK_DRAG_TOLERANCE = 4;
// The selection is shown by the mask, not by the brush
const BRUSH_STYLE = {
color: "rgba(0, 0, 0, 0)",
borderColor: "rgba(0, 0, 0, 0)",
};
export type ZoomSliderMode = "auto" | "always" | "never";
export type ChartSelectMode = "none" | "point" | "range";
const DEFERRED_PROPS = [
"options",
"data",
"_hiddenDatasets",
"_isZoomed",
"highlight",
] as const;
const MASK_OPACITY = 0.7;
export interface ChartTimeRange {
start: number;
end: number;
}
type RawSeriesOption = Exclude<
NonNullable<ECOption["series"]>,
@@ -155,6 +173,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@property({ type: String }) public height?: string;
// While the data loads, the chart is read as one block and its legend as
// one line, or as its items when the legend has them already, so a
// skeleton drawn over it takes the size it will have
@property({ type: Boolean }) public loading = false;
// Lets cards that key their data on ids have display names announced
// instead when the chart is navigated with Chart2Music.
@property({ attribute: false })
@@ -176,6 +199,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@property({ attribute: "grow-for-zoom-slider", type: Boolean })
public growForZoomSlider = false;
// "point" selects on click, "range" also selects on drag instead of zooming
@property({ attribute: "select-mode" })
public selectMode: ChartSelectMode = "none";
// Everything outside this time range fades
@property({ attribute: false }) public highlight?: ChartTimeRange;
// Rounds a selection to the periods of the data, or drops it
@property({ attribute: false }) public snapSelection?: (
range: ChartTimeRange
) => ChartTimeRange | undefined;
// extraComponents is not reactive and should not trigger updates
public extraComponents?: any[];
@@ -201,6 +236,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@state() private _isZoomed = false;
private _pointerDownX?: number;
private _selectingRange?: ChartTimeRange;
private _maskColor = "";
private _maskShown = false;
// Separate from _isZoomed, whose touch handling reruns graph layouts
@state() private _isGraphRoamed = false;
@@ -454,6 +497,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!this.chart) {
return;
}
if (changedProps.has("selectMode")) {
this._updateSelectMode();
}
const themeChanged = changedProps.has("_themes") && this.hasUpdated;
if (!themeChanged && !DEFERRED_PROPS.some((p) => changedProps.has(p))) {
return;
@@ -499,6 +545,8 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
) {
this._disposeSonification();
}
} else if (changedProps.has("highlight")) {
this._updateMask();
}
if (changedProps.has("options")) {
chartOptions = { ...chartOptions, ...this._createOptions() };
@@ -592,6 +640,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
class="chart ${classMap({
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
})}"
data-skeleton=${ifDefined(this.loading ? "block" : undefined)}
role=${ifDefined(sonifiable ? "application" : undefined)}
tabindex=${ifDefined(
sonifiable ? "0" : this._sonificationFocusHeld ? "-1" : undefined
@@ -627,7 +676,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
class="zoom-reset"
.path=${mdiRestart}
@click=${this._handleZoomReset}
title=${this._i18n.localize(
.label=${this._i18n.localize(
"ui.components.history_charts.zoom_reset"
)}
></ha-icon-button>`
@@ -664,6 +713,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!items) {
return nothing;
}
// A card that knows its legend before its data shows it under the
// skeleton, so the skeleton has as many legend rows as it will
if (this.loading && !items.length) {
return html`<div class="chart-legend">
<ul>
<li>
<span class="legend-placeholder" data-skeleton="text"></span>
</li>
</ul>
</div>`;
}
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
@@ -888,6 +949,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
const style = getComputedStyle(this);
echarts.registerTheme("custom", this._createTheme(style));
this._maskColor =
style.getPropertyValue("--card-background-color").trim() ||
style.getPropertyValue("--primary-background-color").trim();
this.chart = echarts.init(this._chartContainer!, "custom");
this._dragToZoom = false;
@@ -970,6 +1034,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this._legendItemCount = this._getLegendItems()?.length;
this._updateSankeyRoam();
this._updateDragToZoom();
if (this.selectMode !== "none") {
this._updateSelectMode();
}
if (zoomStart !== 0 || zoomEnd !== 100) {
this.zoom(zoomStart, zoomEnd, true);
}
@@ -1021,7 +1088,10 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
// A chart can switch type (e.g. pie and bar) without being rebuilt
private _updateDragToZoom() {
const active = !this._touchInput && this._hasZoomableXAxis();
const active =
!this._touchInput &&
this._hasZoomableXAxis() &&
this.selectMode !== "range";
if (!this.chart || active === this._dragToZoom) {
return;
}
@@ -1033,6 +1103,130 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
});
}
private _snapRange(range: ChartTimeRange) {
return this.snapSelection ? this.snapSelection(range) : range;
}
private _getMaskArea(): MarkAreaComponentOption | undefined {
const range = this._selectingRange ?? this.highlight;
if (!range) {
return undefined;
}
return {
silent: true,
z: 10,
itemStyle: {
color: this._maskColor,
opacity: MASK_OPACITY,
},
data: [
[{ xAxis: -Infinity }, { xAxis: range.start }],
[{ xAxis: range.end }, { xAxis: Infinity }],
],
};
}
// Only the first series carries the mask, merged in without resending data
private _updateMask() {
const maskArea = this._getMaskArea();
if (maskArea) {
this._maskShown = true;
}
this.chart?.setOption({
series: [{ markArea: maskArea ?? { data: [] } }],
});
}
private _handleSelectPointerDown = (e: ECElementEvent) => {
this._pointerDownX = e.offsetX;
};
private _handleSelectClick = (e: ECElementEvent) => {
const point = [e.offsetX, e.offsetY];
// A drag that ends on the plot is not a click
const dragged =
this._pointerDownX !== undefined &&
Math.abs(e.offsetX - this._pointerDownX) > CLICK_DRAG_TOLERANCE;
if (dragged || !this.chart?.containPixel("grid", point)) {
return;
}
const [x] = this.chart.convertFromPixel("grid", point) as number[];
const selection = this._snapRange({ start: x, end: x });
if (selection) {
fireEvent(this, "chart-select", selection);
}
};
private _handleBrush = (e: any) => {
const range = e.areas?.[0]?.coordRange as number[] | undefined;
if (range) {
this._selectingRange = this._snapRange({
start: range[0],
end: range[1],
});
this._updateMask();
}
};
private _handleBrushEnd = (e: any) => {
const range = e.areas?.[0]?.coordRange as number[] | undefined;
this.chart?.dispatchAction({ type: "brush", areas: [] });
this._selectingRange = undefined;
this._updateMask();
const selection =
range && this._snapRange({ start: range[0], end: range[1] });
if (selection) {
fireEvent(this, "chart-select", selection);
}
};
private _updateSelectMode() {
if (!this.chart) {
return;
}
const zr = this.chart.getZr();
zr.off("mousedown", this._handleSelectPointerDown);
zr.off("click", this._handleSelectClick);
this.chart.off("brush", this._handleBrush);
this.chart.off("brushEnd", this._handleBrushEnd);
if (this.selectMode !== "none") {
zr.on("mousedown", this._handleSelectPointerDown);
zr.on("click", this._handleSelectClick);
}
const selectRange = this.selectMode === "range";
if (selectRange) {
this.chart.on("brush", this._handleBrush);
this.chart.on("brushEnd", this._handleBrushEnd);
this.chart.setOption({
brush: {
xAxisIndex: 0,
// Only measures the range, the mask fades what is outside
seriesIndex: [],
transformable: false,
brushStyle: BRUSH_STYLE,
},
});
}
const brushCursor = {
type: "takeGlobalCursor",
key: "brush",
brushOption: {
brushType: selectRange ? "lineX" : false,
brushMode: "single",
brushStyle: BRUSH_STYLE,
},
};
// Brush and drag to zoom share the global cursor, the last one taken wins
if (selectRange) {
this._updateDragToZoom();
this.chart.dispatchAction(brushCursor);
} else {
this.chart.dispatchAction(brushCursor);
this._dragToZoom = false;
this._updateDragToZoom();
}
}
private _hasZoomableXAxis() {
const xAxis = ensureArray(this.options?.xAxis)?.[0] as
XAXisOption | undefined;
@@ -1475,7 +1669,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
private _getSeries() {
const xAxis = (this.options?.xAxis?.[0] ?? this.options?.xAxis) as
XAXisOption | undefined;
const series = ensureArray(this.data).map((s) => {
const maskArea = this._getMaskArea();
if (maskArea) {
this._maskShown = true;
}
const series = ensureArray(this.data).map((s, index) => {
const data = this._hiddenDatasets.has(String(s.id ?? s.name))
? undefined
: s.data;
@@ -1513,6 +1711,16 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
} as HaECSeriesItem;
}
}
// ECharts merges series by id and would keep a mask left out here
if (this._maskShown && (s.type === "line" || s.type === "bar")) {
result = {
...result,
markArea:
index === 0 && maskArea
? maskArea
: ((s as LineSeriesOption).markArea ?? { data: [] }),
} as HaECSeriesItem;
}
return processSeriesTooltipFormatter(result);
});
return series as ECOption["series"];
@@ -1762,7 +1970,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
// it, so a quick drag out would lose the release and its selection
if (
ev.type === "pointerdown" &&
this._dragToZoom &&
(this._dragToZoom || this.selectMode === "range") &&
this._isZoomPress(ev)
) {
this.chart
@@ -2234,6 +2442,13 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
.chart-legend.multiple-items li {
max-width: 220px;
}
.chart-legend li:has(.legend-placeholder) {
width: 40%;
}
.legend-placeholder {
width: 100%;
height: var(--ha-font-size-s);
}
.chart-legend.multiple-items li:has(.value) {
max-width: 300px;
}
@@ -2337,6 +2552,7 @@ declare global {
"dataset-hidden": { id: string };
"dataset-unhidden": { id: string };
"chart-click": ECElementEvent;
"chart-select": ChartTimeRange;
"legend-label-click": { id: string };
"chart-zoom": {
start: number;
+217 -27
View File
@@ -76,6 +76,18 @@ export interface NetworkData {
const PHYSICS_DISABLE_THRESHOLD = 512;
const LAYOUT_ANIMATION_THRESHOLD = 100;
// Every event of a change of the legend selection, each with the whole
// selection
const LEGEND_SELECT_EVENTS = [
"legendselectchanged",
"legendselected",
"legendunselected",
"legendselectall",
"legendinverseselect",
];
const SELECTED_NODE_MAX_ZOOM = 2;
// Keeps neighbors clear of the search field, buttons and legend
@@ -83,6 +95,10 @@ const SELECTED_NODE_FIT_MARGIN = 72;
const FOLLOW_ROAM = "follow-selected-node";
type Displayable = ReturnType<
ReturnType<EChartsType["getZr"]>["storage"]["getDisplayList"]
>[number];
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/consistent-type-imports
let GraphChart: typeof import("echarts/lib/chart/graph/install");
@@ -124,8 +140,24 @@ export class HaNetworkGraph extends LitElement {
@state() private _showLabels = true;
// Not reactive: a new series option starts the layout again, so a drop only
// reaches the option with the next render
private _nodePositions: Record<string, { x: number; y: number }> = {};
// Dragged nodes stay where they are dropped, the force layout moves the others
private _pinnedNodes: string[] = [];
// Names of the legend categories that are switched off. Not reactive: the
// legend lays the graph out itself, only the layout animation threshold
// needs a render
private _hiddenCategories: string[] = [];
private _dragNode?: string;
private _dragMoved = false;
private _dragTarget?: Displayable;
private _followSelectedNode = false;
private _followedChart?: EChartsType;
@@ -170,12 +202,15 @@ export class HaNetworkGraph extends LitElement {
this._showLabels,
isMobile,
hasHighlightedNodes,
this.selectedNode
this.selectedNode,
this._nodePositions,
this._pinnedNodes,
this._fewVisibleNodes()
)}
.options=${this._createOptions(this.data?.categories)}
height="100%"
.extraComponents=${[GraphChart]}
@chart-setup=${this._updateFollowing}
@chart-setup=${this._handleChartSetup}
>
<slot name="search" slot="search"></slot>
<slot name="button" slot="button"></slot>
@@ -273,7 +308,10 @@ export class HaNetworkGraph extends LitElement {
showLabels: boolean,
isMobile: boolean,
hasHighlightedNodes?: boolean,
selectedNode?: string
selectedNode?: string,
nodePositions: Record<string, { x: number; y: number }> = {},
pinnedNodes: string[] = [],
fewVisibleNodes = true
) => ({
id: "network",
type: "graph",
@@ -311,14 +349,15 @@ export class HaNetworkGraph extends LitElement {
repulsion: [400, 600],
edgeLength: [200, 350],
gravity: 0.05,
layoutAnimation: !reducedMotion && data.nodes.length < 100,
layoutAnimation: !reducedMotion && fewVisibleNodes,
},
edgeSymbol: ["none", "arrow"],
edgeSymbolSize: 10,
data: this._getSeriesData(
data.nodes,
data.links,
this._nodePositions,
nodePositions,
pinnedNodes,
selectedNode
),
links: data.links.map((link) => ({
@@ -334,11 +373,25 @@ export class HaNetworkGraph extends LitElement {
deepEqual
);
// The legend leaves the nodes of hidden categories out of the layout
private _fewVisibleNodes() {
const hidden = this._hiddenCategories;
const visibleNodes = hidden.length
? this.data.nodes.filter(
(node) =>
node.category === undefined ||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
).length
: this.data.nodes.length;
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
}
private _getSeriesData = memoizeOne(
(
nodes: NetworkNode[],
links: NetworkLink[],
nodePositions: Record<string, { x: number; y: number }>,
pinnedNodes: string[],
selectedNode?: string
) =>
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
@@ -355,7 +408,7 @@ export class HaNetworkGraph extends LitElement {
? { ...node.itemStyle, borderWidth: 3 }
: node.itemStyle || {},
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
fixed: node.fixed,
fixed: node.fixed || pinnedNodes.includes(node.id),
x: node.x,
y: node.y,
} as NonNullable<GraphSeriesOption["data"]>[number];
@@ -515,6 +568,141 @@ export class HaNetworkGraph extends LitElement {
}
}
private _handleChartSetup() {
const chart = this._baseChart?.chart;
chart?.on("mousedown", this._handleNodeMouseDown);
chart?.getZr().on("dragstart", this._handleDragStart);
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
const legend = (
chart?.getOption() as
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
)?.legend?.[0];
this._setHiddenCategories(legend?.selected ?? {});
// A recreated chart, e.g. after a theme change, lacks the drops since the
// last render
this.requestUpdate();
this._updateFollowing();
}
private _handleLegendChange = (params: unknown) => {
const fewVisibleNodes = this._fewVisibleNodes();
this._setHiddenCategories(
(params as { selected: Record<string, boolean> }).selected
);
if (this._fewVisibleNodes() !== fewVisibleNodes) {
// The new series option lays out again from where the nodes are now
this._saveNodePositions();
this.requestUpdate();
}
};
private _setHiddenCategories(selected: Record<string, boolean>) {
this._hiddenCategories = Object.keys(selected).filter(
(name) => !selected[name]
);
}
private _handleNodeMouseDown = (params: {
dataType?: string;
data?: unknown;
}) => {
this._dragNode =
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
this._dragMoved = false;
};
// The dragged element gets the drag before the ECharts handler of its node
private _handleDragStart = (ev: { target?: Displayable }) => {
this._dragTarget?.off("drag", this._handleNodeDrag);
this._dragTarget = ev.target;
this._dragTarget?.on("drag", this._handleNodeDrag);
};
// Without layout animation, the ECharts handler runs the whole force layout
// on every move, which puts the node back before it reads its position. So
// the node moves here, and the other nodes stay where they are.
private _handleNodeDrag = (ev: { cancelBubble?: boolean }) => {
const chart = this._baseChart?.chart;
const series = this._getGraphSeries(chart);
const node =
this._dragNode === undefined
? undefined
: series?.getGraph().getNodeById(this._dragNode);
if (
!chart ||
!node ||
!series.forceLayout ||
series.get(["force", "layoutAnimation"])
) {
return;
}
ev.cancelBubble = true;
const data = series.getData();
const el = data.getItemGraphicEl(node.dataIndex);
data.setItemLayout(node.dataIndex, [el.x, el.y]);
// A new layout run starts from here, e.g. after a legend change
if (series.preservedPoints) {
series.preservedPoints[node.id] = [el.x, el.y];
}
series.forceLayout.setFixed(node.dataIndex);
for (const edge of node.edges) {
const source: number[] | undefined = edge.node1.getLayout();
const target: number[] | undefined = edge.node2.getLayout();
// The nodes of hidden legend categories have no layout
if (source && target) {
edge.setLayout([[...source], [...target]]);
}
}
// @ts-ignore private method but no other way to draw the new layout
chart.getViewOfSeriesModel(series).updateLayout(series);
// The handlers of the chart miss the drag now
chart.getZr().handler.trigger("drag", ev);
};
private _handleDrag = () => {
this._dragMoved = true;
};
private _handleDragEnd = () => {
const id = this._dragNode;
const moved = this._dragMoved;
this._dragNode = undefined;
this._dragMoved = false;
this._dragTarget?.off("drag", this._handleNodeDrag);
this._dragTarget = undefined;
// A click also ends a drag, which releases a pinned node in ECharts
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
return;
}
this._pinNodeInChart(id);
if (!this._pinnedNodes.includes(id)) {
this._pinnedNodes = [...this._pinnedNodes, id];
}
this._saveNodePositions();
};
// A new series option would start the layout again, so the pin goes into
// the running force layout, and into the item option that ECharts lays out
// from again, e.g. on a legend change
private _pinNodeInChart(id: string) {
const series = this._getGraphSeries();
const node = series?.getGraph().getNodeById(id);
if (!node) {
return;
}
series.forceLayout?.setFixed(node.dataIndex);
const [x, y] = node.getLayout();
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
fixed: true,
x,
y,
});
}
private _updateFollowing() {
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
if (chart !== this._followedChart) {
@@ -550,10 +738,7 @@ export class HaNetworkGraph extends LitElement {
if (!chart) {
return;
}
const series: any = chart
// @ts-ignore private method but no other way to get the graph positions
.getModel()
.getSeriesByIndex(0);
const series = this._getGraphSeries(chart);
const node = series?.getGraph().getNodeById(this.selectedNode);
const position: number[] | undefined = node?.getLayout();
if (!position) {
@@ -614,6 +799,7 @@ export class HaNetworkGraph extends LitElement {
private _togglePhysics() {
this._saveNodePositions();
this._pinnedNodes = [];
this._physicsEnabled = !this._physicsEnabled;
}
@@ -622,26 +808,30 @@ export class HaNetworkGraph extends LitElement {
}
private _saveNodePositions() {
const positions = {};
if (this._baseChart?.chart) {
this._baseChart.chart
// @ts-ignore private method but no other way to get the graph positions
.getModel()
.getSeriesByIndex(0)
.getGraph()
.eachNode((node: any) => {
const layout = node.getLayout();
if (layout) {
positions[node.id] = {
x: layout[0],
y: layout[1],
};
}
});
}
// Nodes that are not drawn keep their earlier position
const positions = { ...this._nodePositions };
this._getGraphSeries()
?.getGraph()
.eachNode((node: any) => {
const layout = node.getLayout();
if (layout) {
positions[node.id] = {
x: layout[0],
y: layout[1],
};
}
});
this._nodePositions = positions;
}
private _getGraphSeries(chart = this._baseChart?.chart): any {
if (!chart || chart.isDisposed()) {
return undefined;
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
}
static styles = css`
:host {
display: block;
@@ -36,6 +36,10 @@ const ROW_HEIGHT = 30;
const ROW_HEIGHT_INSIDE_LABELS = 64;
const GRID_BOTTOM = 30;
/* How tall a timeline with this many rows is drawn */
export const timelineHeight = (rows: number, tallRows: boolean) =>
rows * (tallRows ? ROW_HEIGHT_INSIDE_LABELS : ROW_HEIGHT) + GRID_BOTTOM;
@customElement("state-history-chart-timeline")
export class StateHistoryChartTimeline extends LitElement {
@property({ attribute: false }) public data: TimelineEntity[] = [];
@@ -94,13 +98,10 @@ export class StateHistoryChartTimeline extends LitElement {
return html`
<ha-chart-base
.options=${this._chartOptions}
.height=${`${
this.data.length *
(this.insideLabels && (this.chunked || this.showNames)
? ROW_HEIGHT_INSIDE_LABELS
: ROW_HEIGHT) +
GRID_BOTTOM
}px`}
.height=${`${timelineHeight(
this.data.length,
this.insideLabels && (this.chunked || this.showNames)
)}px`}
.data=${this._chartData as HaECSeries}
small-controls
grow-for-zoom-slider
+85 -7
View File
@@ -1,7 +1,7 @@
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import type { HassConfig } from "home-assistant-js-websocket";
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement } from "lit";
import { css, html, LitElement, nothing } from "lit";
import {
customElement,
eventOptions,
@@ -9,6 +9,7 @@ import {
queryAll,
state,
} from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { consume } from "../../common/decorators/consume";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
@@ -20,18 +21,24 @@ import type {
HASSDomTargetEvent,
} from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { configContext } from "../../data/context";
import { configContext, statesContext } from "../../data/context";
import type {
HistoryResult,
LineChartUnit,
TimelineEntity,
} from "../../data/history";
import { expectedHistoryCharts } from "../../data/history";
import { loadVirtualizer } from "../../resources/virtualizer";
import type { HomeAssistantConfig } from "../../types";
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
import { chartPlaceholderStyles } from "./chart-placeholder";
import "./state-history-chart-line";
import type { StateHistoryChartLine } from "./state-history-chart-line";
import "./state-history-chart-timeline";
import type { StateHistoryChartTimeline } from "./state-history-chart-timeline";
import {
timelineHeight,
type StateHistoryChartTimeline,
} from "./state-history-chart-timeline";
const CANVAS_TIMELINE_ROWS_CHUNK = 10; // Split up the canvases to avoid hitting the render limit
@@ -93,6 +100,21 @@ export class StateHistoryCharts extends LitElement {
@property({ attribute: "is-loading-data", type: Boolean })
public isLoadingData = false;
/** The entities being loaded, so their charts' space can be held */
@property({ attribute: false }) public loadingEntityIds?: string[];
/** Whether those entities' charts are split by device class */
@property({ attribute: "split-device-classes", type: Boolean })
public splitDeviceClasses = false;
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
isComponentLoaded(this._hassConfig, "history") &&
this.isLoadingData &&
!this.historyData
);
@property({ attribute: "logarithmic-scale", type: Boolean })
public logarithmicScale = false;
@@ -129,6 +151,9 @@ export class StateHistoryCharts extends LitElement {
})
private _hassConfig!: HassConfig;
@consume({ context: statesContext, subscribe: true })
private _states?: HassEntities;
@queryAll("state-history-chart-line, state-history-chart-timeline")
private _chartComponents!: NodeListOf<
StateHistoryChartLine | StateHistoryChartTimeline
@@ -147,9 +172,7 @@ export class StateHistoryCharts extends LitElement {
}
if (this.isLoadingData && !this.historyData) {
return html`<div class="info">
${this._localize("ui.components.history_charts.loading_history")}
</div>`;
return this._renderLoading();
}
if (this._isHistoryEmpty()) {
@@ -189,6 +212,59 @@ export class StateHistoryCharts extends LitElement {
`;
}
/* Takes the space the charts will, so nothing moves when they arrive */
private _renderLoading() {
const label = this._localize(
"ui.components.history_charts.loading_history"
);
const expected =
this.loadingEntityIds && this._states && !this.height && !this.virtualize
? expectedHistoryCharts(
this.loadingEntityIds,
this._states,
this._hassConfig.unit_system.temperature,
this.splitDeviceClasses
)
: undefined;
if (!expected || (!expected.lines && !expected.timelineRows)) {
return html`<div class="info" data-skeleton="block">${label}</div>`;
}
// Only the first chart says what's happening, for where no skeleton is
// drawn
const timeline = expected.timelineRows
? html`<div class="entry-container timeline">
<div
class="info"
data-skeleton="block"
style=${styleMap({
height: `${timelineHeight(
expected.timelineRows,
this.insideLabels && this.showNames
)}px`,
})}
>
${label}
</div>
</div>`
: nothing;
const lines = Array.from(
{ length: expected.lines },
(_, index) =>
html`<div class="entry-container line placeholder-container">
<div class="info placeholder" data-skeleton="block">
${index === 0 && !expected.timelineRows ? label : nothing}
</div>
<div class="legend-placeholder" data-skeleton="text"></div>
</div>`
);
return html`${timeline}${lines}`;
}
private _renderHistoryItem: RenderItemFunction<
TimelineEntity[] | LineChartUnit
> = (item, index) => {
@@ -472,6 +548,8 @@ export class StateHistoryCharts extends LitElement {
state-history-chart-line {
width: 100%;
}
${chartPlaceholderStyles}
`;
}
+83 -6
View File
@@ -5,7 +5,7 @@ import type {
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
@@ -49,12 +49,20 @@ import type {
HomeAssistantUI,
} from "../../types";
import { getPeriodicAxisLabelConfig } from "./axis-label";
import type { CustomLegendOption } from "./ha-chart-base";
import type {
ChartSelectMode,
ChartTimeRange,
CustomLegendOption,
HaChartBase,
ZoomSliderMode,
} from "./ha-chart-base";
import "./ha-chart-base";
import { chartPlaceholderStyles } from "./chart-placeholder";
import { sideTooltipPosition } from "./chart-tooltip-position";
import "./ha-chart-tooltip-marker";
import { generateStatisticsChartData } from "./statistics-chart-data";
import { createYAxisPrecisionBounds } from "./y-axis-fraction-digits";
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
export const supportedStatTypeMap: Record<StatisticType, StatisticType> = {
mean: "mean",
@@ -115,6 +123,14 @@ export class StatisticsChart extends LitElement {
@property({ attribute: "is-loading-data", type: Boolean })
public isLoadingData = false;
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
isComponentLoaded(this._hassConfig, "history") &&
this.isLoadingData &&
!this.statisticsData
);
@property({ attribute: "click-for-more-info", type: Boolean })
public clickForMoreInfo = true;
@@ -128,6 +144,16 @@ export class StatisticsChart extends LitElement {
@property({ attribute: "expand-legend", type: Boolean })
public expandLegend?: boolean;
@property({ attribute: "select-mode" })
public selectMode: ChartSelectMode = "none";
@property({ attribute: "zoom-slider" })
public zoomSlider: ZoomSliderMode = "auto";
@property({ attribute: false }) public highlight?: ChartTimeRange;
@query("ha-chart-base") private _chartBase?: HaChartBase;
@state() private _chartData: (LineSeriesOption | BarSeriesOption)[] = [];
@state() private _legendData: CustomLegendOption["data"];
@@ -226,10 +252,23 @@ export class StatisticsChart extends LitElement {
}
if (this.isLoadingData && !this.statisticsData) {
return html`<div class="info">
${this._i18n.localize(
"ui.components.statistics_charts.loading_statistics"
)}
const label = this._i18n.localize(
"ui.components.statistics_charts.loading_statistics"
);
// A chart given a height holds its space already
if (this.height) {
return html`<div class="info" data-skeleton="block">${label}</div>`;
}
// Takes the space the chart will, so nothing moves when it arrives
return html`<div class="placeholder-container">
<div class="info placeholder" data-skeleton="block">${label}</div>
${
this.hideLegend
? nothing
: html`<div class="legend-placeholder" data-skeleton="text"></div>`
}
</div>`;
}
@@ -244,8 +283,12 @@ export class StatisticsChart extends LitElement {
return html`
<ha-chart-base
.data=${this._chartData}
.highlight=${this.highlight}
.snapSelection=${this._snapSelection}
.options=${this._chartOptions}
.height=${this.height}
.selectMode=${this.selectMode}
.zoomSlider=${this.zoomSlider}
style=${styleMap({ height: this.height })}
@dataset-hidden=${this._datasetHidden}
@dataset-unhidden=${this._datasetUnhidden}
@@ -259,6 +302,39 @@ export class StatisticsChart extends LitElement {
`;
}
public resetZoom() {
this._chartBase?.zoom(0, 100);
}
// A click selects the period that contains it, a drag every period it
// touches
private _snapSelection = (
range: ChartTimeRange
): ChartTimeRange | undefined => {
let start: number | undefined;
let end: number | undefined;
Object.entries(this.statisticsData ?? {}).forEach(
([statisticId, values]) => {
if (this._hiddenStats.has(statisticId)) {
return;
}
values.forEach((value) => {
const touched =
range.start === range.end
? value.start <= range.start && range.start < value.end
: value.start < range.end && value.end > range.start;
if (touched) {
start = Math.min(start ?? value.start, value.start);
end = Math.max(end ?? value.end, value.end);
}
});
}
);
return start === undefined || end === undefined
? undefined
: { start, end };
};
private _datasetHidden(ev: HASSDomEvent<HASSDomEvents["dataset-hidden"]>) {
this._hiddenStats.add(ev.detail.id);
this.requestUpdate("_hiddenStats");
@@ -644,6 +720,7 @@ export class StatisticsChart extends LitElement {
line-height: 60px;
color: var(--secondary-text-color);
}
${chartPlaceholderStyles}
`;
}
+18 -15
View File
@@ -35,24 +35,27 @@ function computeTimelineStateColor(
const domain = computeDomain(stateObj.entity_id);
// Zone states for person/device_tracker don't have specific CSS color variables,
// so they all fall back to the same --state-person-active-color.
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
// otherwise return undefined to get unique colors from the generic color handler.
if (
// Zone states would all share --state-person-active-color, so only an
// exact state variable may color them, like states of uncolored domains.
const isZoneState =
(domain === "person" || domain === "device_tracker") &&
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
) {
return computeCssValue(
`--state-${domain}-${slugify(state, "_")}-color`,
computedStyles
);
}
const properties = stateColorProperties(stateObj, state);
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
const properties = isZoneState
? undefined
: stateColorProperties(stateObj, state);
if (!properties) {
return undefined;
const stateKey = slugify(state, "_");
const deviceClass = stateObj.attributes.device_class;
return computeCssValue(
[
...(deviceClass
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
: []),
`--state-${domain}-${stateKey}-color`,
],
computedStyles
);
}
const rgb = computeCssValue(properties, computedStyles);
+36 -4
View File
@@ -45,6 +45,7 @@ import "../ha-checkbox";
import type { HaCheckbox } from "../ha-checkbox";
import "../skeleton/ha-skeleton-icon";
import "../skeleton/ha-skeleton-text";
import { skeletonArrivalStyles } from "../skeleton/skeleton-arrival";
import "../ha-svg-icon";
import "../input/ha-input-search";
import { filterData, sortData } from "./sort-filter";
@@ -401,9 +402,13 @@ export class HaDataTable extends LitElement {
}
if (properties.has("data")) {
// Clean up checked rows that no longer exist in the data
// Clean up checked rows that no longer exist or can no longer be selected
if (this._checkedRows.length) {
const validIds = new Set(this.data.map((row) => String(row[this.id])));
const validIds = new Set(
this.data
.filter((row) => row.selectable !== false)
.map((row) => String(row[this.id]))
);
const validCheckedRows = this._checkedRows.filter((id) =>
validIds.has(id)
);
@@ -568,6 +573,11 @@ export class HaDataTable extends LitElement {
>
<ha-checkbox
class="mdc-data-table__row-checkbox"
.accessibleLabel=${
this._i18n?.localize?.(
"ui.components.data-table.select_all"
) ?? ""
}
@change=${this._handleHeaderRowCheckboxClick}
.indeterminate=${
!!this._checkedRows.length &&
@@ -791,9 +801,11 @@ export class HaDataTable extends LitElement {
</div>`
: nothing
}
<!-- The list fades in once as it takes the skeleton rows'
place; rows made later as it scrolls show at once -->
<lit-virtualizer
scroller
class="mdc-data-table__content scroller ha-scrollbar ${classMap(
class="mdc-data-table__content scroller ha-scrollbar arriving ${classMap(
{ grouped: Boolean(this.groupColumn) && !this.autoHeight }
)}"
tabindex=${ifDefined(!this.autoHeight ? "0" : undefined)}
@@ -894,6 +906,7 @@ export class HaDataTable extends LitElement {
>
<ha-checkbox
class="mdc-data-table__row-checkbox"
.accessibleLabel=${this._rowCheckboxLabel(columns, row)}
@click=${this._handleRowCheckboxClicked}
.rowId=${row[this.id]}
.disabled=${row.selectable === false}
@@ -963,6 +976,23 @@ export class HaDataTable extends LitElement {
`;
};
private _rowCheckboxLabel(
columns: DataTableColumnContainer,
row: DataTableRowData
): string {
const mainKey = Object.keys(columns).find((key) => columns[key].main);
const name = mainKey ? row[mainKey] : undefined;
return (
(typeof name === "string" && name
? this._i18n?.localize?.("ui.components.data-table.select_row", {
name,
})
: this._i18n?.localize?.(
"ui.components.data-table.select_row_generic"
)) ?? ""
);
}
private _isColumnVisible(key: string, column: DataTableColumnData): boolean {
if (column.hidden) {
return false;
@@ -1601,6 +1631,7 @@ export class HaDataTable extends LitElement {
static get styles(): CSSResultGroup {
return [
haStyleScrollbar,
skeletonArrivalStyles,
css`
/* default mdc styles, colors changed, without checkbox styles */
:host {
@@ -1659,7 +1690,8 @@ export class HaDataTable extends LitElement {
}
.mdc-data-table__row ~ .mdc-data-table__row {
border-top: 1px solid var(--divider-color);
border-top: var(--data-table-row-border-width, 1px) solid
var(--divider-color);
}
.mdc-data-table__row.clickable:not(
@@ -97,6 +97,8 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
@state() private _dateValue?: string;
@state() private _rangeIncomplete = false;
@state() private _timeValue = {
from: { hours: 0, minutes: 0 },
to: { hours: 23, minutes: 59 },
@@ -195,6 +197,7 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
.locale=${this._i18n.locale.language}
.focusedDate=${this._focusDate}
@focusday=${this._focusChanged}
@rangestart=${this._handleRangeStart}
@change=${this._handleChange}
show-outside-days
.firstDayOfWeek=${firstWeekdayIndex(this._i18n.locale)}
@@ -253,7 +256,9 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
<ha-button appearance="plain" @click=${this._cancel}
>${this._i18n.localize("ui.common.cancel")}</ha-button
>
<ha-button .disabled=${!this._dateValue} @click=${this._save}
<ha-button
.disabled=${!this._dateValue || this._rangeIncomplete}
@click=${this._save}
>${this._i18n.localize(
"ui.components.date-range-picker.select"
)}</ha-button
@@ -280,7 +285,7 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
}
private _save() {
if (!this._dateValue) {
if (!this._dateValue || this._rangeIncomplete) {
return;
}
@@ -331,9 +336,21 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
this._focusDate = ev.target.focusedDate;
}
private _handleRangeStart(
ev: HASSDomTargetEvent<HTMLElementTagNameMap["calendar-range"]>
) {
this._rangeIncomplete = matchMedia("(hover: hover)").matches;
if (this._rangeIncomplete) {
return;
}
const day = ev.target.tentative;
this._dateValue = `${day}/${day}`;
}
private _handleChange(
ev: HASSDomTargetEvent<HTMLElementTagNameMap["calendar-range"]>
) {
this._rangeIncomplete = false;
const dateElement = ev.target as HTMLElementTagNameMap["calendar-range"];
this._dateValue = dateElement.value;
this._focusDate = dateElement.focusedDate;
+18 -19
View File
@@ -371,25 +371,24 @@ export class HaEntityPicker extends LitElement {
excludeEntities?: string[],
value?: string
) =>
getEntities(
{
states,
...registries,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
localize: i18n.localize,
},
{
includeDomains,
excludeDomains,
entityFilter,
includeDeviceClasses,
includeUnitOfMeasurement,
includeEntities,
excludeEntities,
value,
}
)
getEntities({
states,
entities: registries.entities,
devices: registries.devices,
areas: registries.areas,
floors: registries.floors,
localize: i18n.localize,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
includeDomains,
excludeDomains,
entityFilter,
includeDeviceClasses,
includeUnitOfMeasurement,
includeEntities,
excludeEntities,
value,
})
);
private _sortByRelatedContext = memoizeOne(
Loaded 100 of 695 files, more files were not shown because too many files have changed in this diff. Show more