Compare commits

..
Author SHA1 Message Date
Matthias de BaatandClaude Opus 5.5 25307e427d Show when backup retention is paused for a location (#56088)
Automatic backup retention no longer deletes backups from locations
that are turned off for automatic backups (home-assistant/core#192788).
Show "Retention paused" in the locations list and an info alert on the
location page for those locations.

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

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

* Time out the server check before the login redirect

* Give the server check 10 seconds
2026-11-25 19:44:23 +02:00
Bram KragtenandClaude Opus 5.5 77a4af6adf Bumped version to 20261125.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 16:09:42 +01:00
Bram KragtenandClaude Opus 5.5 94bb00d591 Merge branch 'rc' into dev
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 16:09:39 +01:00
c925ed1a9f Show integration categories in the Marketplace (#55130)
* Browse integrations by category in the add integration dialog

* Match the subcategory row height to the categories

* Address review feedback on the category browsing

* Show integration categories in the Marketplace

* Load the category names again after a language change

* Keep the focus and the manage link in the category browsing

* Keep the category filter and pass it through My links

Remember a picked category like the other filters, take the category
along in My Home Assistant links, and drop the casts on its translation
keys.

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

* Look up category names and icons in one place

The add integration dialog and the Marketplace now share the helpers for
the name, icon and matching of a category.

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

---------

Co-authored-by: Wendelin <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 16:07:12 +01:00
renovate[bot] 81579b321c Update pnpm to v12.23.0 (#56138)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-25 15:57:17 +01:00
0d4554a032 Add address search to location selector (#54351)
* Implement location search functionality in location selector with Lat and Long based place addition

* Improve places search handling and address encoding

Updated places search to handle undefined and null values, and encoded the address before searching.

* Fix HTML syntax in ha-selector-location.ts

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

* Add location address and search error translations; update HaLocationSelector for improved error handling

* Refactor HaLocationSelector: import HaLocationsEditor type and enhance _placeSelected method with async handling

* Refactor location selector and OpenStreetMap integration

- Introduced formatOpenStreetMapPlace function for consistent place formatting.
- Updated ha-selector-location to utilize new formatting function.
- Enhanced searchPlaces to build URL parameters more cleanly.
- Improved onboarding-location to use the new formatting function.
- Added tests for formatOpenStreetMapPlace and searchPlaces.
- Updated translations for location-related labels and messages.

amend email

* Fix location search results and queued submissions

Address review feedback on result slots, localized address details, loading controls, and realistic formatter fixtures. Cover queued searches and keyboard selection on desktop and mobile.

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

* Prevent location search Enter from submitting parent flows

Stop Enter propagation for result activation and IME confirmation while preserving composition defaults and keyboard selection. Extend the existing browser workflow to guard both event boundaries.

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

* Restore focus after selecting a location search result

Move focus to the existing search input before removing a focused result. Leave focus alone when the selected row is not focused, and extend the existing keyboard regression test.

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

* Align location search with onboarding review feedback

Use read-only loading and shared search status messages instead of queued searches. Preserve keyboard focus and Enter boundaries, announce selections, deduplicate place names, and simplify disclosure and list styling.

Move the focused keyboard regression into the Config panel suite and remove the queued-search success/failure loop.

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Copilot <[email protected]>
2026-11-25 15:49:55 +01:00
WendelinandClaude Opus 5.5 e04c342bce Keep the startup toast usable while a dialog is open (#56134)
* Show the startup toast through the notification manager

The "Home Assistant is starting" toast was its own element outside the
notification manager, so a modal dialog made its buttons inert and the
fix from #56063 did not apply to it. It now goes through showToast().

Toasts can now show a supporting text line, and toast actions can be
icon buttons that leave the toast open. The startup toast uses both to
keep its look and its info button.

The startup details are only offered to admins, on the starting toast
and on the completion toast.

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

* Show the startup toast once translations have loaded

The toast no longer needs English fallbacks for its texts and labels.
It passes translation keys, so the notification manager localizes it.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 15:33:42 +01:00
Paul Bottein fe89425698 Save the add dialog's Browse by choice only from its chip (#56140) 2026-11-25 15:31:23 +01:00
Paulus SchoutsenandClaude Opus 5.5 2ae1c2c92b Add timer list card and more info dialog (#56099)
* Add timer list card and more info control

Core has a timer_list entity domain. An entity holds many independent
countdown timers, and the frontend showed only the number of active ones.

Add a shared ha-timer-list component that subscribes to the timers of an
entity. It shows each timer with a live countdown and a progress bar, and
it offers the actions the entity supports: start, pause, resume, add one
minute and cancel. It shows active and paused timers only.

Use the component in a new timer-list card and in the more info dialog of
timer_list entities. Add gallery pages for both, backed by an in-memory
stub so the actions work there.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Show finished timers in the timer list for 5 minutes

A finished timer vanished from the list the moment it ended, so a glance
at the card could miss it. Keep a finished timer visible for 5 minutes
after it ends, marked as finished. Offer a remove button when the entity
supports removal. Cancelled timers stay hidden.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Start timer list timers from a dialog

The name and duration fields took a large part of the timer list card
and of the more info dialog. Replace them with a "Start timer" button
that opens a dialog with the same fields.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Put the start timer button below the list in more info

The more info dialogs of scripts, timers and automations put their action
buttons below the content. Follow that for timer lists. The card keeps the
button above the list, as the to-do list card does for its add field.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Drop the leading zero from timer list countdowns

The timer entity shows its countdown as "9:53". The timer list showed
"09:53". Format the countdown without a leading zero on the first unit.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Treat timer lists like timers in state color and area dashboards

A timer entity colors its icon while it runs, and the areas dashboard
lists it with the other helpers of an area. Do the same for timer list
entities. A timer list is active when it has at least one active timer.

Add the two timer list gallery pages to the gallery smoke tests.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Fix starting a timer on an empty list in the timer list demo stub

The stub read the timers of an entity that had no seed data, so starting
the first timer on the empty gallery example failed.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Fix timer list subscription timing and a demo interval leak

The timer list decided whether to subscribe before the entity state of a
changed entity was current, so a switch from an unavailable list to an
available one stayed unsubscribed. Decide after the update instead.

An update queued before removal could subscribe again on the removed
element. Skip the work when the element is not connected.

The demo stub never stopped its one-second interval. Return a stop
function and call it when the gallery page is removed.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EzDS5KtV4V6RNqNdajC65v

* Add screenshots for the pull request description

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

* Remove the pull request screenshots

They are only referenced from the pull request description.

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

* Show unavailable timer lists and label the duration field

An unavailable timer list rendered no content, so a card without a title
and without the start button was blank. Show that the list is
unavailable.

The duration field in the start timer dialog showed only the unit
abbreviations and had no accessible name. Give it the Duration label
that the timer helper settings use.

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

* Rename the timer list button, sort timers, and clarify adding time

Design review feedback on the timer list:
- "Start timer" read as starting an existing timer. Call it "Add timer".
- Show finished timers first, then running and paused timers with the
  soonest to finish first.
- The timer-plus icon did not say what it adds. Show "+1:00" as text.

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

* Add screenshots for a pull request comment

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

* Remove the pull request comment screenshots

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

* Fix the timer list add time label and leftover start timer wording

The add time button had an accessible name that did not contain its
visible "+1:00" text, so voice control users could not say what they
see. Use the visible text as its name and keep "Add 1 minute" as the
tooltip.

The card editor and the gallery still said "start a timer" after the
button became "Add timer".

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-25 15:29:56 +01:00
WendelinandClaude Opus 5.5 2b903846d2 Move the camera microphone row height to its more info (#56137)
The more info dialog listened to camera-capabilities-changed from the
stream and reserved 72px for the microphone row of the camera's info.
more-info-camera now reports the height of its row itself, so the value
lives next to the row it describes.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 15:10:18 +01:00
af8d129871 Add device or integration dialog with categories, brands and search (#55125)
* Browse integrations by category in the add integration dialog

* Match the subcategory row height to the categories

* Address review feedback on the category browsing

* Keep the focus and the manage link in the category browsing

* Prototype the add device or integration dialog

Coded prototype on top of the category browsing: one global search, Browse
by/Connection/Type filter chips, Featured and Works with Home Assistant
collections, Discovered grouped with adding a device, cards with a plus or
a chevron, a phone drill-down like the automation editor, and a floating
manage footer for discovered devices.

Includes a temporary demo panel (demo-add-integration.ts and the // DEMO
lines) and copied placeholder data (featured, Works with Home Assistant,
category icons) that core does not send yet.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Refine the add device or integration prototype

- Mark YAML-only integrations with a YAML label and a chevron instead of
  a code icon, so a card ends with a plus or a chevron only
- In a category, list a brand's integrations in it instead of the brand,
  like the website (Google is Google Gemini in AI models), and count them
  the same way in the sidebar
- Drop the fake demo integrations from the list
- Hide the demo panel on Marketplace pages

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

* Remove the type filter from the add device or integration dialog

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

* Keep the filter row of the add device or integration dialog from scrolling vertically

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

* Suggest integrations from the apps on the phone in the add dialog prototype

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

* Leave discovered integrations out of the phone suggestions

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

* Remove the phone suggestions from the add device or integration prototype

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

* Remove the demo panel from the add device or integration prototype

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

* Address review findings on the add device or integration dialog

- Open a passed category on phones, and keep Enter from picking a row
  that isn't on screen
- Move the focus along when drilling in and out on a phone
- Make the tree's chevrons clickable, mirror them in RTL, and use
  logical margins and paddings
- Complete the tree's arrow keys: into an open category, and back from
  a subcategory
- List brands that only have protocol devices, like Aqara
- Leave the YAML label off categories and "show more" in search results
- Browse everything when the connection filter empties what was browsed
- Drop the category icon fallback, core sends them now
- Remove leftover comments, styles and an unused translation

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

* Leave the Featured and Works with Home Assistant collections out for now

Only the website has these lists. They come back in a follow-up, once
core sends them.

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

* Keep the add dialog's sheet below a large top safe area

The bottom sheet caps its height below the top safe area, so the lists
are sized from that same height.

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

* End the add dialog's panes and lists on one line

The sheet now fills its height with flex like the dialog, instead of
heights worked out by hand. The browse pane, the list and the search
results share one bottom margin, and the cards get room after the last
one.

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

* Let the add dialog's lists scroll to the edge again

The room goes after the last card instead of under the list, as much
as the browse pane has below it.

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

* Give the last discovered card room below it

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

* Simplify the add device or integration dialog

- One helper for what a browse pick or search result shows, and one for
  dropping a selection that has nothing to show
- Pass the connection itself instead of a memoized filters object
- Drop the size snapshots and minimum sizes, the dialog has a fixed size
- Render only the subcategories shown while collapsed, instead of
  clipping the rest to a calculated height, so the keyboard can't reach
  hidden rows
- Drop the unused integration_type on the rows
- Focus the back button after drilling in; ha-icon-button-prev now
  forwards focus to its button

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

* Trim comments in the add device or integration dialog

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

* Use wa-tree for the add dialog's categories, like the automation editor

The category tree was rebuilt from list rows with its own chevrons,
ARIA roles and arrow key handling. wa-tree brings all of that, so the
dialog now uses it on wide screens, and keeps the list to drill into
on a phone, the same split as the automation editor's targets.

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

* Follow the frontend standards in the add device or integration dialog

- Import ha-adaptive-dialog instead of relying on another chunk
- Count an integration of more than one brand once, like the results
- Type the new event handlers instead of casting to any
- Drop the any casts on translation keys
- Use new translation keys where the meaning changed
- Use spacing tokens and logical padding

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

* Center the category icons in the add dialog's browse pane

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

* Center the counts in the add dialog's browse pane

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

* Use async/await for the integration category icons

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

* Clarify the categories comments

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

* Inset the add dialog's titles like the automation editor's

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

* Move the add dialog's brand titles into their own component

The rows render in the virtualized list's shadow root, so the titles
were styled inline, and the same style was repeated as .items-title.

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

* Move the add dialog's list types and helpers into their own file

The list item imported its type from the dialog. Both import it from
add-integration-list.ts now, with the constants and pure helpers. The
test covers inCategory, which must not match energy_storage for energy.

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

* Name the raw integrations and helpers in the add dialog's memos

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

* Name the search's integrations by domain in the add dialog

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

* Render nothing instead of empty strings in the discovered list

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

* Clarify the add dialog's category param comment

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

* Address Copilot's review of the add dialog

- Set the dvh heights only where dvh works: a custom property doesn't
  fall back to an earlier vh one, so older browsers lost the height
- Move the focus after drilling a frame later, once the back button
  and the browse rows have rendered

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

* Keep the discovered count visible on the selected row

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

* Scroll the browse pane to what was picked by searching

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

* Center the brand icons in the add dialog's browse pane

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

* Center what was picked by searching in the browse pane

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

* Show a custom integration's details under the brand it replaces

A custom integration replacing a core one listed under a brand kept the
core details there, and search and categories only show that row.

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

* Filter a category by the brand's rows, like its count

A custom integration replacing one under a brand brings its own
categories, so the brand's core categories could hide it from a
category that counted it.

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

---------

Co-authored-by: Wendelin <[email protected]>
Co-authored-by: marcinbauer85 <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-11-25 15:05:32 +01:00
Bram Kragten 1ea5f1ab4f Bumped version to 20261028.8 2026-11-20 15:42:39 +01:00
Bram Kragten bbd745d901 Stop camera streams right away when hidden in the companion apps (#55887) 2026-11-20 15:41:02 +01:00
Bram Kragten 5d481a77b9 Bumped version to 20261028.7 2026-11-20 14:08:00 +01:00
Jan Bouwhuis ccc750b5a9 Align MQTT subscribe card width with other cards (#55914) 2026-11-20 14:07:42 +01:00
Simon LamonandPetar Petrov 3a31fdca87 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-20 14:07:40 +01:00
Bram Kragten 92bcd97390 Bumped version to 20261028.6 2026-11-13 15:46:23 +01:00
Petar Petrov f06678a30a Fix legends fitting as narrow in the card editor preview (#55886) 2026-11-13 15:45:45 +01:00
Paul Bottein 6dc3df4ba5 Fix favorites centering in the more info dialog (#55884) 2026-11-13 15:45:44 +01:00
Bram KragtenandClaude Opus 5.5 36b17a4c47 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-13 15:45:42 +01:00
Maarten Lakerveld ed6e25f0ab 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-13 15:45:41 +01:00
Maarten Lakerveld 9b0a034bab 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-13 15:44:02 +01:00
Christian Wiedel 3c61ed2a9d Keep the demo launch screen from pushing the app down while it fades out (#55707) 2026-11-13 15:44:02 +01:00
Bram KragtenandClaude Opus 5.5 d5c17054a2 Add missing HASSDomEvent import to hui-root
The backport of #55640 uses HASSDomEvent in hui-root, but on dev the
import came from #55565, which is not on rc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 15:39:24 +01:00
Petar Petrov 3ddd98b585 Name energy devices after their entity when a device has several meters (#55778)
* Name energy devices after their entity when a device has several meters

* Keep the device name as placeholder until an energy statistic is picked

* Compute the picker ambiguity set from the memoized arguments

* Count user-set energy device names towards a label collision
2026-11-13 15:37:14 +01:00
Christian Wiedel 3a388453ea Fix grouped data tables stuttering when scrolling in Safari (#55702)
* Fix grouped data tables stuttering when scrolling in Safari

Group header actions are rendered by a callback instead of a slot per group
header. The virtualizer adds and removes header rows while scrolling, and
WebKit is slow to add and remove slots.

Fixes #55636

* Keep group header actions when the data or the pinned group changes

Group header rows are keyed by their group, so an open category menu stays open when the data refreshes. The sticky header is keyed by the pinned group, so its actions don't act on the next group's category.

* Keep group header keys apart from row keys

A group named like a row's id gave the header and the row the same virtualizer key. Prefix the keys so they can't collide.

* Don't call the group header actions slotted in the styles
2026-11-13 14:45:59 +01:00
Bram Kragten e32bc0696e Bumped version to 20261028.5 2026-11-06 15:14:00 +01:00
WendelinandClaude Opus 5.5 6327304f4d Fix bright card outlines on Shelly Wall Display (#55704)
* Keep rgba() colors in the legacy CSS build

Raising the legacy floor to Chrome 67 lets lightningcss rewrite rgba()
to 8-digit hex (#rrggbbaa), since Chrome 62 supports it. Kiosk webviews
like the Shelly Wall Display get the legacy build but can't parse that,
so var(--divider-color) borders on cards, toggles and buttons fell back
to currentColor and showed as bright outlines, the same symptom as
#52986. Always compile hex alpha colors to rgba() in legacy builds, for
both css`` templates and imported stylesheets. Modern builds are
unchanged.

Also drop the loader's redundant /* global */ header, which ESLint now
rejects because module and require are already built-in globals in
.cjs files.

Fixes #55699

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

* Also keep rgba() colors in the legacy service worker build

The template loader runs with the legacy-sw browserslist env for the
service worker layer, which an exact match on legacy missed.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-06 15:12:17 +01:00
Petar Petrov 11c79e09e9 Fit narrow chart legends to three rows instead of two (#55697) 2026-11-06 15:12:16 +01:00
Paul Bottein 5060b37381 Fix truncated buttons in the voice assistant setup (#55677) 2026-11-06 15:12:14 +01:00
Aidan Timson 63e3a04f15 Fix the max-age of the demo and cast cache headers (#55676) 2026-11-06 15:12:13 +01:00
Aidan Timson 818de1da8e Render full dashboards with their tabs in the demo embed (#55640)
* Add an embedded mode to hui-root that leaves the page's URL alone

* Add a dashboard component to the demo embed

* Keep embedded dashboards' back navigation, height and sidebar tabs inside the embed

* Follow anchors, replacements and new configs in embedded dashboards

* Go back past a followed back_path in embedded dashboards

* Isolate embedded view containers so view backgrounds show

* Match decoded and aliased views and skip empty embedded dashboards

* Read the sidebar tab once sections views have their dashboard

* Declare the navigate events in HTMLElementEventMap

* Skip the Lovelace info fetch and its mock in embedded dashboards
2026-11-06 15:12:11 +01:00
Aidan Timson 70897feab1 Render views and dashboard strategies in the demo embed (#55639)
* Add a view component to the demo embed

* Show only the latest generated dashboard in the demo embed

* Stop stale and repeated strategy results in embedded views

* Draw view themes and backgrounds in embedded views
2026-11-06 15:12:10 +01:00
Aidan Timson f827c09e72 Let embed entities set their entity registry options (#55675) 2026-11-06 15:09:48 +01:00
Aidan Timson a4bb97b71c Render sections in the demo embed, with a device registry (#55638)
* Share embed provider lookup and theme in a base element

* Add devices to the demo embed provider

* Add a section component to the demo embed

* Draw section backgrounds and accept more section configs in the demo embed
2026-11-06 15:09:43 +01:00
puddly 509561aabe Allow the ESPHome serial proxy URL to be null (#55665)
* Allow the ESPHome serial proxy URL to be None

* Clarify comment
2026-11-06 14:58:14 +01:00
Christian Wiedel 0446eb5a62 Fix wrapped flow dialog titles overlapping the subtitle (#55661) 2026-11-06 14:58:13 +01:00
Paul Bottein e815c44a42 Fix area controls freezing large dashboards (#55650) 2026-11-06 14:58:11 +01:00
Joost LekkerkerkerandClaude Opus 5.5 4551a87a7a Label marketplace open issue count as issues and pull requests (#55635)
* Label marketplace open issue count as issues and pull requests

The GitHub open issues count includes pull requests. Rename the
translation keys and update the English strings so the label matches
the number shown.

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

* Update marketplace tests for the renamed open issues keys

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-06 14:58:10 +01:00
Alexander Hass 23e376c7b4 Resolve external statistics in the History panel (#55521)
* Resolve external statistics in the History panel

The History panel plots external statistics (`<domain>:<object_id>`), for example when the statistics graph card links to it, but treated them as entities everywhere else.

- The sources picker looks up an external statistic in the statistics metadata and shows its name instead of "Entity not found".
- Statistics without an entity take name and unit from their metadata, so the legend and tooltip no longer show the prettified ID without a unit.
- External statistic IDs are no longer sent to `history/stream`. Core rejects the whole subscription for an ID that is not an entity ID, which dropped the state history of every other picked entity.

* Use statistic metadata only for external statistics

The statistics of a removed entity got the unit from their metadata, but no device class. Its recent state history has the same unit and a device class, so both ended up in separate charts and the overlap was no longer trimmed. Other statistics keep a blank unit again and merge into the history line of their entity. The metadata is only fetched for external statistics.

* Reset the zoom when only external statistics remain

Removing the last entity from a zoomed view returned before the zoom was reset. The chart was rebuilt at full range, but the zoom slider kept the previous range.

* Reset the chart zoom when only external statistics are shown

Charts of external statistics stay mounted when the date range changes, because there is no state history to load. Resetting only the zoom range left the chart zoomed while the reset button was disabled. The zoom is now reset on the charts as well, and the normal path is unchanged again.

* Keep the statistics when the metadata lookup fails

A failed metadata lookup rejected the whole request, so the fetched statistics were dropped and the panel could stay on the loading spinner. External statistics are now shown under their ID instead.

* End the loading when the statistics request fails

With only external statistics selected there is no state history, so a failed statistics request left the panel on the loading spinner. A failed request now sets an empty result, guarded by the fetch ID so that an older request cannot overwrite newer data.

* Show external statistics like the statistic picker and inline the stream filter

The sources picker row of an external statistic gets the chart line icon and the source integration as context, as in ha-statistic-picker, instead of the default entity icon. The filter for the history stream has a single caller, so it is inlined in the History panel and its export and test are dropped. The comment on the blank unit of other statistics moves to the isExternalStatistic check it describes.

* Clear the previous statistics before fetching new ones in the History panel

Switching from one external statistic to another kept the chart of the previous one on screen and in the download until the new request was done, as no state history shows the loading then. The statistics are now cleared before the request, so the panel shows its loading state instead.
2026-11-06 14:58:09 +01:00
Bram Kragten a67b691a45 Bumped version to 20261028.4 2026-11-04 12:05:25 +01:00
Franck Nijhof fc0f86e46d Add Marketplace download source menu item for the China mirrors (#55615) 2026-11-04 12:04:21 +01:00
Aidan Timson ef6438a77d Fix the demo embed for the contributors site (#55596) 2026-11-04 12:03:30 +01:00
WendelinandClaude Opus 5.5 7b4981e850 Add descriptive aria-labels to picker filter chips (#55592)
* Give picker section filter chips a descriptive aria-label

Screen readers announced the section chips in quick search and the
target picker only by their visible text (e.g. "Navigate"), which gives
no hint that the button filters the results. Label them as
"Filter: <section>" instead.

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

* Fix fallback for section label localization in ha-picker-combo-box

---------

Co-authored-by: Claude <[email protected]>
2026-11-04 11:53:19 +01:00
Maarten Lakerveld a46e90de67 Stop recomputing active system domains on every state change in the add element dialog (#55586) 2026-11-04 11:31:19 +01:00
3dfadb7fdf Let core work out what target exclusions take out (#55585)
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-04 11:25:33 +01:00
Paul Bottein 6f3ef16d20 Add an option to include pre-releases in Marketplace repositories (#55567) 2026-11-04 11:01:42 +01:00
17d08d26f6 Wrap long descriptions in the entity settings (#55590)
* Wrap supporting text of entity settings rows

Long explanations such as the visibility description were truncated
with an ellipsis, especially in languages with longer translations.

Fixes #55584

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

* Update supporting-text styles for row and list items

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

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-03 14:34:40 +01:00
Alexander Hass aa06e8ce25 Fix README images and links with a relative path in the Marketplace (#55525)
* Keep relative README addresses for the Marketplace rewrite

Images and links in a README with a plain relative path, such as `images/logo.png`, were broken on the Marketplace repository page. xss empties every `src` and `href` that does not start with a scheme, `/`, `./`, `../` or `#`, so the path was gone before `rewriteHtmlUrls` could point it at the repository.

`renderMarkdown` takes `allowRelativeUrls`, which `ha-markdown-element` sets when it rewrites the addresses afterwards. Such an address of a link, image or source is kept as a path below the current one, so it can never carry a scheme, and xss checks it like any other address.

* Trim a relative README address before it gets the ./ prefix

xss trims the spaces written around an attribute value, but not encoded ones. A relative path such as `&#32;images/logo.png` therefore got the space inside the path after the ./ prefix, and the image stayed broken. The value is now decoded and trimmed first, as the browser trims the address.

* Decode a relative README address once and keep data links first

The relative address was decoded before `safeAttrValue` decoded it again, so `&#38;#105;mages` was checked and shown as `images` while the browser reads `&#105;mages`. Like `srcset`, it is now decoded once with `&amp;` for query strings, dropped when entities are left over, and written back escaped, so the browser reads the path that was checked.

Links to data URLs allowed with `allowDataUrl` are handled before relative addresses again, so they are no longer turned into paths.

* Escape a kept relative README address only once

`safeAttrValue` returns the value escaped already, so escaping its result again turned a quote in a path into `&amp;quot;`, and the browser requested another file. It is now only the check, and the decoded path is escaped once, like `srcset`.

The comments of the change are cut down to the one above the new function, as the code around has few.

* Drop relative README addresses with a scheme and reuse URL_ATTRIBUTES

A relative path never has a scheme, so an address xss empties that still has one after decoding (HTTPS://..., j:alert(1) from &#0000106avascript:) or is empty is dropped instead of being kept below ./, where it would request a path in the repository that does not exist. The worker imports URL_ATTRIBUTES from rewrite-html-urls, so the attributes it keeps and the ones the rewrite touches cannot drift apart.
2026-11-03 14:34:39 +01:00
Bram Kragten 122877cdf5 Bumped version to 20261028.3 2026-11-02 16:42:17 +01:00
Josef Zweck a103eac243 Add access risk to the Marketplace warning (#55559) 2026-11-02 16:41:33 +01:00
Paul Bottein a9a8a9aad9 Show the area first in integration device rows (#55557) 2026-11-02 16:41:32 +01:00
WendelinandClaude Opus 5.5 35a054c1ba Fix picker rows missing the first click after scrolling (#55556)
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-11-02 16:41:31 +01:00
960e99ed66 Refactor bulk delete labels (#55555)
Co-authored-by: Bram Kragten <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-11-02 16:41:29 +01:00
Paul Bottein 232375befb Limit the more info activity to the 100 most recent entries (#55553) 2026-11-02 16:41:28 +01:00
Aidan Timson 91ee29a2e6 Use generic picker for install another version (#55552) 2026-11-02 16:41:26 +01:00
Aidan Timson a6dc5d0008 Shorten the Marketplace description on the settings page (#55549) 2026-11-02 16:41:25 +01:00
Thomas Mueller 7a66de362e Seek on slider change in the media control card (#55542)
* Seek on slider change in the media control card

A touch drag ends without a click, so the card never seeked after a
drag. Use the slider's change event, which fires when a drag or tap
ends and on arrow keys.

* Remove media control card rendering test

The frontend testing guidance asks for tests of code that computes
something, not rendering tests.
2026-11-02 16:41:23 +01:00
Thomas Mueller 36500e5b19 Fix media progress slider on Chromium < 125 (#55539)
matches(":state(dragging)") throws before Chromium 125. Use
customStates.has("dragging") instead.
2026-11-02 16:41:22 +01:00
karwosts df88136147 Fix date-only attribute formatting to not shift into other days (#55536) 2026-11-02 16:41:21 +01:00
jimjaeger 2f1d738c2c Fix onboarding using US customary units when the location is detected (#55535)
Keep the detected unit system in onboarding
2026-11-02 16:41:19 +01:00
Paulus SchoutsenandClaude bfeb26b47d Link the MCP integration pages to the AI settings (#55515)
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 the MCP card on that page. The
button is the primary action when the page has no "Add entry" button.

The AI settings page scrolls to the section named in the URL hash, like
the backup settings page, and clears the hash after. In the demo, the
hash is the route of the page, so the button links to the page without
a section and the page keeps a hash that names no section.


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

Co-authored-by: Claude <[email protected]>
2026-11-02 16:41:18 +01:00
Joost LekkerkerkerandClaude 8de5bfee89 Stretch chip container to fill host so outline matches host shape (#55510)
Co-authored-by: Claude <[email protected]>
2026-11-02 16:41:17 +01:00
Jan-Philipp BeneckeandCopilot Autofix powered by AI 1efc7f8a95 Fix network graph button spacing (#55501)
* Fix zoom reset button spacing

* Replace margin-right with margin-inline-end

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

* Align with chart-base

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-02 16:41:15 +01:00
Erwin DounaandAidan Timson 9e0d38fba8 Show a skeleton while the live log loads (#55443)
Co-authored-by: Aidan Timson <[email protected]>
2026-11-02 16:41:13 +01:00
2932f8f528 Add embeddable dashboard card components to the demo (#54348)
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Aidan Timson <[email protected]>
2026-11-02 16:41:12 +01:00
Bram Kragten 6a0902d18c Bumped version to 20261028.2 2026-10-30 23:57:41 +01:00
Paul Bottein 4424f98eb6 Add translation for the Marketplace panel title (#55486) 2026-10-30 23:57:29 +01:00
Maarten Lakerveld ea13594fb0 Move the panel background stacking context off partial-panel-resolver (#55485)
Since #54801 the resolver creates a stacking context (isolation: isolate) so
its fixed ::before background sits behind the panel. The resolver is rendered
conditionally, once the startup data is available, and isolating it can
intermittently leave the Android WebView accessibility tree (Chromium
109-124) with an empty panel subtree while the page paints normally. UI
automation then never sees the dashboard; the companion app nightly E2E has
hit this on the legacy build (API 32/33/35) since the change landed.

Move the isolation to home-assistant-main's host, which exists before the
resolver is rendered. The pseudo-element and the Lovelace view background
both stay at z-index -1 in that context, in the same order as before, so the
themed background behaves exactly as #54801 intended. Measured with Maestro
on a Chrome 109 emulator: 0 stale trees in 62 cold loads, against 11 in 100
with the isolation on the resolver.
2026-10-30 23:57:28 +01:00
Daan Vervacke ce726a8a3f Wrap long title in YAML-only integration dialog (#55481) 2026-10-30 23:57:26 +01:00
Paul Bottein d67479da6d Replace hide-zoom-controls with a zoom slider mode on charts (#55468) 2026-10-30 23:57:25 +01:00
Bram Kragten 275e30879c Bumped version to 20261028.1 2026-10-29 16:44:20 +01:00
Maarten Lakerveld 7b53005865 Load the legacy Intl polyfills once per page and bundle PluralRules with its data (#55452)
Each legacy entry bundle carries its own copy of intl-polyfill.ts, so the
module-level guard only stopped re-runs within one bundle. With the bundles
loading in parallel, the second bundle could probe Intl.PluralRules after the
first had installed the polyfill but before its locale data chunk arrived. The
FormatJS should-polyfill probe calls select(), which throws on a data-less
polyfill, rejecting the top-level await so the entry never evaluated. On the
companion app this surfaces as ExternalBusTimeout on old WebViews.

Share one promise per page on globalThis so every bundle waits for the same
run, and import the PluralRules polyfill and its English data from one module
so Intl.PluralRules is never installed without data.
2026-10-29 16:43:58 +01:00
Paul Bottein 94950fcacd Show a toast with a link to the dashboard after adding to it (#55444) 2026-10-29 16:43:56 +01:00
Petar Petrov 4214fe46c6 Name new disk mounts after the partition's volume label (#55441) 2026-10-29 16:43:55 +01:00
Aidan Timson d6325eef7d Fix the Marketplace search field overlapping the top bar icons on narrow screens (#55439)
Let the narrow data table search field shrink to fit
2026-10-29 16:43:54 +01:00
WendelinandClaude Opus 5.5 12e722f122 Wrap long text in debug tool and network discovery rows (#55438)
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-10-29 16:43:53 +01:00
Paul Bottein 83eb3ca13a Use the state color by default in alert cards and badges (#55436) 2026-10-29 16:43:51 +01:00
Petar Petrov 0532b1f5f6 Ignore YAML dashboard update event on first load (#55430) 2026-10-29 16:43:50 +01:00
Tristan Cartledge 970afb588d Fix duplicated hidden areas when reordering areas in the areas dashboard editor (#55424) 2026-10-29 16:43:49 +01:00
Maarten Lakerveld 23137ce6d2 Name maintenance problem tiles after the device and the entity (#55420)
Problem binary sensors were added to the maintenance view using the
battery tile builder, which names every tile after its device. A device
with several problem sensors (overheating, overvoltage, ...) then showed
identical tiles. Problem tiles now use a device plus entity name; the
entity part is dropped automatically when the sensor has no name of its
own, so single-sensor devices still read as just the device name.
Battery tiles keep the device-only name.

Fixes home-assistant/frontend#55413
2026-10-29 16:43:48 +01:00
JonathanandXyolyp 6b022d63e8 Preselect the only allowed unit also in an optional unit selector (#55417)
Co-authored-by: Xyolyp <[email protected]>
2026-10-29 16:43:46 +01:00
Paul Bottein d3c6e132b7 Show multi-select chips in a field with an inline add button (#55416) 2026-10-29 16:43:45 +01:00
Paul Bottein c08b261d4b Keep the section row divider under the entities card header (#55415) 2026-10-29 16:43:44 +01:00
Bram KragtenandClaude Opus 5.5 0721b22036 Keep the device and area page headers fixed while scrolling (#55409)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-29 16:43:43 +01:00
71 changed files with 5170 additions and 834 deletions

No files matched your search

@@ -1,43 +0,0 @@
---
name: ha-frontend-browser-checks
description: Check a Home Assistant frontend change in a browser and show it in a pull request. Use when checking how a change looks or behaves at different screen sizes, in light and dark mode, right to left (RTL) or with long translations, or when taking before and after screenshots or recording a demo of a feature for a pull request.
---
# HA Frontend Browser Checks
Use this skill to check a visible change in a browser and to show it in a pull request. Any browser tool you already have works if it can open a page, set its size, run a script in it, take screenshots and record video. Load `ha-frontend-testing` for the dev servers, and `ha-frontend-loading` for loading states.
Screenshots and recordings help reviewers see what changed, but they don't make a large change easy to review. [Keep pull requests small](https://contributors.home-assistant.io/start/pull-requests/#keep-it-small), and make sure you have reviewed and understood the change and can explain it, as the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks.
## Check Real Devices
Check the sizes the change affects rather than one fixed size, such as a phone, a tablet in both orientations, a laptop and a large desktop monitor. Include a small phone. Take each device's viewport in CSS pixels, its pixel ratio and touch support from the device presets your tools have, rather than from memory, and check the page really has that size once it's set.
## Check Light And Dark
When the change can look different in light and dark mode, such as a colour, border, background or image, check it in both. Switch the colour scheme in your browser tool, with the profile's theme following it, or pick light and dark in the profile. A fix for one mode only needs that mode.
## Check Right To Left (RTL)
Check layout, alignment, icons and anything with a direction in RTL. In the app, set your profile language to one written right to left, then set it back: many components take their direction from the language, so setting the page to RTL in your browser tool leaves them left to right. The gallery's RTL toggle checks styling only.
## Check Long Text
When a change adds or changes text, check it in a language with long words or long translations too, so labels, descriptions and buttons don't overflow or wrap badly. When the new string isn't translated yet, try a rough translation to check its length.
## Show It In The Pull Request
- When the change alters something that exists already, capture the same screen on `dev` and on your branch, in the same state, and put them side by side. A new screen, or a small change that's easy to see, needs only the after.
- Keep the size of every capture fixed, screenshots as well as videos. Set the page size before you capture and don't change it in between, and capture the same area each time, so the subject sits in the same place in before and after. For a card or other part of the page, work out a fixed area around it for each size you test, and use that same area on both branches.
- Say which device, size or mode each capture shows.
- Make the change easy to see: capture the part of the screen it affects rather than a whole page where it's a few pixels.
- Save captures outside the repository, so they can't be committed by accident.
- Keep personal details out: use demo data, such as the demo or the Demo integration, and mask anything else before you capture, such as names, addresses, IP and MAC addresses, hostnames, serial numbers and tokens. Check each capture before you attach it.
Record a video when it shows the change better than a still, such as an animation, a drag, a loading sequence (hold the loading state as "Checking It" in `ha-frontend-loading` shows) or a flow across several screens. Keep each video short and small: GitHub limits upload sizes, and reviewers have to watch it. You can record it yourself with the tools you have; it doesn't need a person.
- Use the recording tools at hand: your browser tool's recorder for a page, or a desktop screen recorder for a window, such as a phone emulator, so the device frame shows.
- Don't resize, zoom or take screenshots while recording, which redraw the page at another size and make the video jump.
- Check the whole recording before you attach it. For a short clip, look at a frame every second or half second, not only the first and last, since the page can jump to another size partway through. Record again if it does. Take stills from the same frames, so they match the video.
- Keep the window drawn on a screen. A hidden or minimised window records only a frame every few seconds.
- Label each video, such as **Before** and **After**, and say what it shows and how you set it up. Say what you didn't record and why.
+1 -1
View File
@@ -20,7 +20,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
- Do not omit, reorder, or rewrite template sections.
- Check the appropriate "Type of change" box based on the actual change.
- Do not check checklist items on behalf of the user.
- If the PR includes UI changes, remind the user to add screenshots or a short video, taken as `ha-frontend-browser-checks` describes.
- If the PR includes UI changes, remind the user to add screenshots or a short video.
- Explain what the change does for users, not only implementation details.
- Use Markdown.
-1
View File
@@ -53,7 +53,6 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
## Pull Requests
+217
View File
@@ -0,0 +1,217 @@
import { durationDataToSeconds } from "../../../src/common/datetime/duration_to_seconds";
import type {
TimerListMessage,
TimerListTimer,
} from "../../../src/data/timer_list";
import { timerListTimerRemaining } from "../../../src/data/timer_list";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export interface MockTimerListTimer {
name?: string;
// Seconds
duration: number;
remaining?: number;
paused?: boolean;
finished?: boolean;
}
type ChangeEventType = Extract<
TimerListMessage,
{ type: "change" }
>["event_type"];
// Keeps the timers in memory, so the timer list actions work in demos.
// Returns a function that stops the mock.
export const mockTimerList = (
hass: MockHomeAssistant,
lists: Record<string, MockTimerListTimer[]>
) => {
let nextId = 0;
const listeners: Record<
string,
Set<(message: TimerListMessage) => void>
> = {};
const createTimer = (
duration: number,
name?: string,
remaining = duration,
paused = false
): TimerListTimer => ({
timer_id: `timer-${nextId++}`,
name: name ?? null,
status: paused ? "paused" : "active",
created_duration: duration,
total_duration: duration,
created_at: new Date().toISOString(),
finishes_at: paused
? null
: new Date(Date.now() + remaining * 1000).toISOString(),
paused_remaining: paused ? remaining : null,
ended_at: null,
remaining,
});
const timers: Record<string, TimerListTimer[]> = Object.fromEntries(
Object.entries(lists).map(([entityId, seeds]) => [
entityId,
seeds.map((seed) => {
const timer = createTimer(
seed.duration,
seed.name,
seed.remaining,
seed.paused
);
return seed.finished
? {
...timer,
status: "finished" as const,
finishes_at: null,
ended_at: timer.created_at,
remaining: 0,
}
: timer;
}),
])
);
const change = (
entityId: string,
timer: TimerListTimer,
eventType: ChangeEventType
) => {
timers[entityId] = (timers[entityId] ?? []).filter(
(item) => item.timer_id !== timer.timer_id
);
if (eventType !== "removed") {
timers[entityId].push(timer);
}
listeners[entityId]?.forEach((listener) =>
listener({ type: "change", event_type: eventType, timer })
);
hass.mockEntities[entityId].update({
state: String(
timers[entityId].filter((item) => item.status === "active").length
),
});
};
const end = (
entityId: string,
timer: TimerListTimer,
status: "finished" | "cancelled"
) =>
change(
entityId,
{
...timer,
status,
finishes_at: null,
paused_remaining: null,
ended_at: new Date().toISOString(),
remaining: 0,
},
status
);
const setRemaining = (
entityId: string,
timer: TimerListTimer,
remaining: number,
paused: boolean,
eventType: ChangeEventType
) =>
change(
entityId,
{
...timer,
status: paused ? "paused" : "active",
finishes_at: paused
? null
: new Date(Date.now() + remaining * 1000).toISOString(),
paused_remaining: paused ? remaining : null,
total_duration: Math.max(timer.total_duration, Math.ceil(remaining)),
remaining,
},
eventType
);
const mockTimerService = (
service: string,
handler: (
entityId: string,
timer: TimerListTimer,
data: Record<string, any>
) => void
) =>
hass.mockService("timer_list", service, (data, target) => {
const entityId: string = target!.entity_id;
const timer = timers[entityId].find(
(item) => item.timer_id === data!.timer_id
);
if (timer) {
handler(entityId, timer, data!);
}
});
hass.mockService("timer_list", "create_timer", (data, target) =>
change(
target!.entity_id,
createTimer(durationDataToSeconds(data!.duration), data!.name),
"created"
)
);
mockTimerService("pause_timer", (entityId, timer) =>
setRemaining(
entityId,
timer,
timerListTimerRemaining(timer),
true,
"paused"
)
);
mockTimerService("unpause_timer", (entityId, timer) =>
setRemaining(
entityId,
timer,
timerListTimerRemaining(timer),
false,
"unpaused"
)
);
mockTimerService("cancel_timer", (entityId, timer) =>
end(entityId, timer, "cancelled")
);
mockTimerService("remove_timer", (entityId, timer) =>
change(entityId, timer, "removed")
);
mockTimerService("add_time", (entityId, timer, data) =>
setRemaining(
entityId,
timer,
timerListTimerRemaining(timer) + durationDataToSeconds(data.duration),
timer.status === "paused",
"time_changed"
)
);
hass.mockWS("timer_list/item/subscribe", (msg, _hass, onChange) => {
const entityId: string = msg.entity_id;
listeners[entityId] ??= new Set();
listeners[entityId].add(onChange!);
onChange!({ type: "timers", timers: timers[entityId] ?? [] });
return () => listeners[entityId].delete(onChange!);
});
const interval = window.setInterval(() => {
for (const [entityId, items] of Object.entries(timers)) {
for (const timer of items) {
if (timer.status === "active" && !timerListTimerRemaining(timer)) {
end(entityId, timer, "finished");
}
}
}
}, 1000);
return () => window.clearInterval(interval);
};
+2 -1
View File
@@ -144,6 +144,7 @@ export default [
"iframe-card",
"markdown-card",
"todo-list-card",
"timer-list-card",
],
},
],
@@ -171,7 +172,7 @@ export default [
},
{
header: "Inputs and values",
pages: ["input-number", "input-text", "number", "timer"],
pages: ["input-number", "input-text", "number", "timer", "timer-list"],
},
{
header: "Time and schedules",
+48
View File
@@ -0,0 +1,48 @@
import type { MockTimerListTimer } from "../../../demo/src/stubs/timer_list";
export const TIMER_LIST_ENTITIES = [
{
entity_id: "timer_list.kitchen",
state: "2",
attributes: {
friendly_name: "Kitchen timers",
supported_features: 63,
},
},
{
entity_id: "timer_list.empty",
state: "0",
attributes: {
friendly_name: "Empty timer list",
supported_features: 63,
},
},
{
entity_id: "timer_list.read_only",
state: "1",
attributes: {
friendly_name: "Read-only timers",
supported_features: 0,
},
},
{
entity_id: "timer_list.unavailable",
state: "unavailable",
attributes: {
friendly_name: "Unavailable timer list",
supported_features: 63,
},
},
];
export const TIMER_LIST_TIMERS: Record<string, MockTimerListTimer[]> = {
"timer_list.kitchen": [
{ name: "Eggs", duration: 360, finished: true },
{ name: "Pasta", duration: 600, remaining: 425 },
{ duration: 300, remaining: 40 },
{ name: "Bread", duration: 2700, remaining: 1310, paused: true },
],
"timer_list.read_only": [
{ name: "Laundry", duration: 5400, remaining: 3725 },
],
};
@@ -0,0 +1,3 @@
---
title: Timer list card
---
@@ -0,0 +1,117 @@
import type { PropertyValues, TemplateResult } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
import type { ShowDialogParams } from "../../../../src/dialogs/make-dialog-manager";
import { showDialog } from "../../../../src/dialogs/make-dialog-manager";
import { mockIcons } from "../../../../demo/src/stubs/icons";
import { mockTimerList } from "../../../../demo/src/stubs/timer_list";
import type { MockHomeAssistant } from "../../../../src/fake_data/provide_hass";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import type { TimerListCardConfig } from "../../../../src/panels/lovelace/cards/types";
import type { DemoCardConfig } from "../../components/demo-card";
import "../../components/demo-cards";
import { TIMER_LIST_ENTITIES, TIMER_LIST_TIMERS } from "../../data/timer_list";
const CONFIGS = [
{
heading: "Timers",
config: {
type: "timer-list",
entity: "timer_list.kitchen",
},
},
{
heading: "With title, without the add timer button",
config: {
type: "timer-list",
title: "Kitchen",
entity: "timer_list.kitchen",
hide_create: true,
},
},
{
heading: "No timers",
config: {
type: "timer-list",
entity: "timer_list.empty",
},
},
{
heading: "No supported actions",
config: {
type: "timer-list",
entity: "timer_list.read_only",
},
},
{
heading: "Unavailable",
config: {
type: "timer-list",
entity: "timer_list.unavailable",
},
},
] satisfies DemoCardConfig<TimerListCardConfig>[];
@customElement("demo-lovelace-timer-list-card")
class DemoTimerListCard extends LitElement {
@property({ attribute: false }) public hass?: MockHomeAssistant;
private _stopTimerList?: () => void;
public provideHass(el) {
el.hass = this.hass;
}
public connectedCallback() {
super.connectedCallback();
this.addEventListener("show-dialog", this._dialogManager);
}
public disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("show-dialog", this._dialogManager);
this._stopTimerList?.();
}
// Opens the dialog to start a timer
private _dialogManager = (e: HASSDomEvent<ShowDialogParams<unknown>>) => {
const { dialogTag, dialogImport, dialogParams, addHistory, parentElement } =
e.detail;
showDialog(
this,
dialogTag,
dialogParams,
dialogImport,
parentElement,
addHistory
);
};
protected render(): TemplateResult | typeof nothing {
if (!this.hass) {
return nothing;
}
return html`<demo-cards
.hass=${this.hass}
.configs=${CONFIGS}
></demo-cards>`;
}
protected firstUpdated(changedProperties: PropertyValues<this>) {
super.firstUpdated(changedProperties);
// Provided on this element, so the dialog it opens gets the mocks too
const hass = provideHass(this);
hass.updateTranslations(null, "en");
hass.updateTranslations("lovelace", "en");
hass.addEntities(TIMER_LIST_ENTITIES);
mockIcons(hass);
this._stopTimerList = mockTimerList(hass, TIMER_LIST_TIMERS);
}
}
declare global {
interface HTMLElementTagNameMap {
"demo-lovelace-timer-list-card": DemoTimerListCard;
}
}
@@ -0,0 +1,3 @@
---
title: Timer list
---
+76
View File
@@ -0,0 +1,76 @@
import type { PropertyValues, TemplateResult } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
import type { ShowDialogParams } from "../../../../src/dialogs/make-dialog-manager";
import { showDialog } from "../../../../src/dialogs/make-dialog-manager";
import { mockTimerList } from "../../../../demo/src/stubs/timer_list";
import "../../../../src/components/ha-card";
import "../../../../src/dialogs/more-info/more-info-content";
import type { MockHomeAssistant } from "../../../../src/fake_data/provide_hass";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import "../../components/demo-more-infos";
import { TIMER_LIST_ENTITIES, TIMER_LIST_TIMERS } from "../../data/timer_list";
@customElement("demo-more-info-timer-list")
class DemoMoreInfoTimerList extends LitElement {
@property({ attribute: false }) public hass!: MockHomeAssistant;
private _stopTimerList?: () => void;
public provideHass(el) {
el.hass = this.hass;
}
public connectedCallback() {
super.connectedCallback();
this.addEventListener("show-dialog", this._dialogManager);
}
public disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("show-dialog", this._dialogManager);
this._stopTimerList?.();
}
// Opens the dialog to start a timer
private _dialogManager = (e: HASSDomEvent<ShowDialogParams<unknown>>) => {
const { dialogTag, dialogImport, dialogParams, addHistory, parentElement } =
e.detail;
showDialog(
this,
dialogTag,
dialogParams,
dialogImport,
parentElement,
addHistory
);
};
protected render(): TemplateResult | typeof nothing {
if (!this.hass) {
return nothing;
}
return html`
<demo-more-infos
.hass=${this.hass}
.entities=${TIMER_LIST_ENTITIES.map((ent) => ent.entity_id)}
></demo-more-infos>
`;
}
protected firstUpdated(changedProperties: PropertyValues<this>) {
super.firstUpdated(changedProperties);
// Provided on this element, so the dialog it opens gets the mocks too
const hass = provideHass(this);
hass.updateTranslations(null, "en");
hass.addEntities(TIMER_LIST_ENTITIES);
this._stopTimerList = mockTimerList(hass, TIMER_LIST_TIMERS);
}
}
declare global {
interface HTMLElementTagNameMap {
"demo-more-info-timer-list": DemoMoreInfoTimerList;
}
}
+1 -1
View File
@@ -222,7 +222,7 @@
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]2.0",
"packageManager": "[email protected]3.0",
"volta": {
"node": "24.22.3"
}
+75 -65
View File
@@ -7,162 +7,172 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.22.0
version: 12.22.0
specifier: 12.23.0
version: 12.23.0
packages:
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-n0kwk3uOtWGaSMJWUuxG8fLefRonw8jR27dhGzMcDz79Um37QKPLEGZAZF37iASbb2yBBQFl4hue6/SfQnmIdA==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-oqZu9yFInENTRA9BKiOnEqOcpr5dNMDbquxq9zKFKJy0nEC385Vw0e4wlsOAlDh90iX94GND6Fc22FVL2O2SmQ==}
cpu: [arm64]
os: [android]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-1HERYEdvJEjU5p/lyI8g3YNEVdvVz6+omaqI1pKotZB9w92BlSXr0xTqur8X/8GAiE4B/pwZi8+eAi4v+KQVHg==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-fQRjE4Wno8ye0lxhYGmyqdcc6tv+tDGktEmgFzffZ7flp4BG/84VtdXn3i/O4BazgMbNuPdbM75aj7uDZwL7GQ==}
cpu: [x64]
os: [android]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-CU0m1tFFVW2QD2PDVTsdejYGoPzhMq04l/MnwhpCuM2iBXkMXqV52kH24U5A2SYULV4Y/TTYsKL5InKZblVNvw==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-ny5+L92frsfyV3/B3zadYQuU5kBV8o2TXB5WnhBUoJ/9Mz32FVglMr8g1HmUc01yfKkjopZ4rmF1G7vs68JxIg==}
cpu: [arm64]
os: [darwin]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-XjVoliuAZjcyQJVymR+n3xmkw3SBME3Sg7wjKBTNbOaTGe3RLIkXt8D9YXOoSnET8gyhQrY8fwThFT+Ki6IVNw==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-+MNmpJSAzb9yc80d5l4VbZ/3Teh8xtlacATUyTAx6fELUK0xwmgFi05hqzg1sXLdAPij5gcIp82VvrqY5tzPrQ==}
cpu: [x64]
os: [darwin]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-BefdhvM+nrLXHCRVFmNv5yp4Zhwz29nEP+UPhsvGRRp4YRzgmyxT9r0lVts3Lg0FzcKOtPbM3o0Hyb2y0JF3yw==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-AGfkooje58I9hh4xdSDyZCPLKvjrjuvlkKTK2gsTtj6wfhVTw1jz33wB1XbERt2/0odJdEfgnBPUIdalRnb7Fw==}
cpu: [x64]
os: [freebsd]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-72fwiRonMxFAY4Fb611eTaR+8bYwH91SnWCg3aODjhigCMURFe5Pom+TtYM/GMrme2yirGkHbpzU2u0lMMCwTQ==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-C09Z3tFnPz7CYiae326dGlJcRUNCBtlJvMc04S9M8YKACebHHyamxCItLAisvGdHVf1BawtU9shV0FngjYxMwA==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-1MZ3GfFCFckquAJP6WZ985Lrd5MP5YNA7vPZH79W+1QVzwl55fVMdsAOczdGnFeU4jqMwERnk129/1g9zYxhDw==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-RLby8T0CIWAbljrbmjaX6S3PYhMHnLbUp+IDcOmZIY1/+wy8hJoQpjMPZlV4VJIGl8lZKUXtxJcLJ2XZ1z2SVw==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-ppc[email protected]2.0':
resolution: {integrity: sha512-JOmNBnncDB+9pa8ddtIp9qrLrKwvgzV92xWEFAXSBrDcPIIAdD7imtk3kZnoiApdRzPbQHHj6JJKKVmOUXN0Bw==}
'@pnpm/exe.linux-loong[email protected]3.0':
resolution: {integrity: sha512-XytxNoKD9/PcugxRHmBptRNDxUYwBtQZwBauJ3lKXFJ3sqHPZSjjFxIMX4HTWQn7FqCVnQlF+tbewjUnvQz0dQ==}
cpu: [loong64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]':
resolution: {integrity: sha512-1h9+mBpdmlFA5LW6fAfd5UnLgHakNkEsS1R67mEXY1J6WLLnZcWFJs7Cbde0BD034CRTUa99MaILAuSs2ERf7Q==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-4oJ2VAuzpEnySBxZ9uz9dwIZYqOcgJ7FWIFdPDf9QbkYo8NbskZ2ySgHwlDVnvQYGhTM45kFRDwjfhKYZJJ9PQ==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-SlPz2UxUshIxgyBRKT0PHncYr2pIoFOxf6WR68HCkhGmASGljYlYYwRVfefgoIPM603x4Fcge9/B1Z3aIq1bSQ==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-wLbmg1e+9qAUbqZ29/BUvAQwiZtvgzKg3kjDIN4tkxrCATnneM2G0agFpD9yLHD3FT5J8bUB8RWSur5vqm4Vnw==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-Hk8jKY0i9sjyKPJFYC71lu7Mq5ahb5sWT2zCqNxzzBCrivvCqv5GVfZurLETC5TsSusE9TRWFpynLgG+iaXmSA==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-ODMJgTVHvs/WOqQKE9Am5u7RztsNjXZpkn73z9z4SsU7Dtrr/3IQkjvsF1MGM9hbhMdGwl2BHAW91eCCipIsHQ==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-7+9bD4LBQ5r+7nLnIhDgMnvMm7a7cfc28NogU3NY1sM0+0Jz7K+IwxZb4BJDY/AN1s3F26TgZ3az/bjeCshmXA==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-iBAZAYCYoow6g0aObKmprKkIBGO72mK4KFfqIrY7jIdHRkAbN67tcN0zgaPE39UAEdMcrkLhLwEml+VMxf8h8Q==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-vu/N1nUJxLA0IIumbxL/rR6leGA+++SQY0XL+5KPJ1O2kyvzJoLQYL1ibLGO7TRqsZ90wclboEdhIIWvr3Qsig==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-5y9seaGcEL2OH5p9PG1cZRnSQKENvzK8hTsTjkFxUxXM84OCDvSlaSLr4ABrjrxWKlo4k8bjnmW7NEwznlowGA==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-c85UPtAJfPR5+ghXS8UGRQlgxwqvz2PFaPaEzIVwUdBU+5DB4X2iuMAMlMXWS6hJ/OjqhKM6tpwyEc4Kkz40Fg==}
cpu: [x64]
os: [netbsd]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-eMJWsyECSWxhGDQwPokhES8dJX0dsu7E0tUfhxAaUnFxX7oBKKNS7kBY9yY75sNq4CmMNLjhOtBwrVjd3bQ1Hg==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-lx0B8HPaUEG/ovIC0PmA6HhMhXh6ud0pAWVTDNxZvAfAzuGm0RM78SCT/oBY80lbJnwA9al4sTUroqozZK9hVA==}
cpu: [arm64]
os: [win32]
'@pnpm/[email protected]2.0':
resolution: {integrity: sha512-d0D0GIiDkdiUiENlz3sMOR3arSsApaXtBZl2+rDwbwtQJ5IIBopf4KVTSZDPr09yl2NUVglCS5roveGKpYCWOg==}
'@pnpm/[email protected]3.0':
resolution: {integrity: sha512-OnbBaQWQcw31m5APFNKcM8kdmM6H7k8MoaOnA2m1LsWAHX7AZKB5cdJfNwhHGBfkURcwWk1bnMXBdllujMiCFw==}
cpu: [x64]
os: [win32]
[email protected]2.0:
resolution: {integrity: sha512-iUlAo9mlffpv03OZD7TkHgnC8tdtmC7R11J105Jn+Yj7Ti1AkAy+mSHGjZfGeqGhCW0nZjPbJI97NJJ6yd23pA==}
[email protected]3.0:
resolution: {integrity: sha512-AtqU/68TP0YHQyKv5VL5DUC19xriWa77zNrMUIWx1hfpjWXgEx9XSLm2dEWXjuUFXX1ZpHPx7vDVBIVP781ZdQ==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/[email protected]3.0':
optional: true
'@pnpm/exe.linux-ppc[email protected]2.0':
'@pnpm/exe.linux-loong[email protected]3.0':
optional: true
'@pnpm/exe.linux-riscv[email protected]2.0':
'@pnpm/exe.linux-ppc[email protected]3.0':
optional: true
'@pnpm/exe.linux-s390x@12.22.0':
'@pnpm/exe.linux-riscv64@12.23.0':
optional: true
'@pnpm/exe.linux-x64-musl@12.22.0':
'@pnpm/exe.linux-s390x@12.23.0':
optional: true
'@pnpm/[email protected]2.0':
'@pnpm/exe.linux-x64-musl@12.23.0':
optional: true
'@pnpm/exe.netbsd[email protected]2.0':
'@pnpm/exe.linux[email protected]3.0':
optional: true
'@pnpm/exe.win32-arm[email protected]2.0':
'@pnpm/exe.netbsd-x[email protected]3.0':
optional: true
'@pnpm/exe.win32-x[email protected]2.0':
'@pnpm/exe.win32-arm[email protected]3.0':
optional: true
[email protected]2.0:
'@pnpm/exe.win32-x64@12.23.0':
optional: true
[email protected]:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.22.0
'@pnpm/exe.android-x64': 12.22.0
'@pnpm/exe.darwin-arm64': 12.22.0
'@pnpm/exe.darwin-x64': 12.22.0
'@pnpm/exe.freebsd-x64': 12.22.0
'@pnpm/exe.linux-arm64': 12.22.0
'@pnpm/exe.linux-arm64-musl': 12.22.0
'@pnpm/exe.linux-ppc64': 12.22.0
'@pnpm/exe.linux-riscv64': 12.22.0
'@pnpm/exe.linux-s390x': 12.22.0
'@pnpm/exe.linux-x64': 12.22.0
'@pnpm/exe.linux-x64-musl': 12.22.0
'@pnpm/exe.netbsd-x64': 12.22.0
'@pnpm/exe.win32-arm64': 12.22.0
'@pnpm/exe.win32-x64': 12.22.0
'@pnpm/exe.android-arm64': 12.23.0
'@pnpm/exe.android-x64': 12.23.0
'@pnpm/exe.darwin-arm64': 12.23.0
'@pnpm/exe.darwin-x64': 12.23.0
'@pnpm/exe.freebsd-x64': 12.23.0
'@pnpm/exe.linux-arm64': 12.23.0
'@pnpm/exe.linux-arm64-musl': 12.23.0
'@pnpm/exe.linux-loong64': 12.23.0
'@pnpm/exe.linux-ppc64': 12.23.0
'@pnpm/exe.linux-riscv64': 12.23.0
'@pnpm/exe.linux-s390x': 12.23.0
'@pnpm/exe.linux-x64': 12.23.0
'@pnpm/exe.linux-x64-musl': 12.23.0
'@pnpm/exe.netbsd-x64': 12.23.0
'@pnpm/exe.win32-arm64': 12.23.0
'@pnpm/exe.win32-x64': 12.23.0
---
lockfileVersion: '9.0'
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20261028.0"
version = "20261125.0"
license = "Apache-2.0"
license-files = ["LICENSE*"]
description = "The Home Assistant frontend"
+2
View File
@@ -15,6 +15,7 @@ import { MediaPlayerEntityFeature } from "../../data/feature/media-player_entity
import { NotifyEntityFeature } from "../../data/notify";
import { RemoteEntityFeature } from "../../data/remote";
import { SirenEntityFeature } from "../../data/feature/siren_entity_feature";
import { TimerListEntityFeature } from "../../data/timer_list";
import { TodoListEntityFeature } from "../../data/todo";
import { UpdateEntityFeature } from "../../data/update";
import { VacuumEntityFeature } from "../../data/vacuum";
@@ -42,6 +43,7 @@ const DOMAIN_ENUMS = {
notify: NotifyEntityFeature,
remote: RemoteEntityFeature,
siren: SirenEntityFeature,
timer_list: TimerListEntityFeature,
todo: TodoListEntityFeature,
update: UpdateEntityFeature,
vacuum: VacuumEntityFeature,
+3
View File
@@ -51,6 +51,9 @@ export function stateActive(stateObj: HassEntity, state?: string): boolean {
return ["on", "home", "open", "locked", "problem"].includes(compareState);
case "timer":
return compareState === "active";
case "timer_list":
// The state is the number of active timers
return compareState !== "0";
case "camera":
return ["streaming", "recording"].includes(compareState);
}
+1
View File
@@ -36,6 +36,7 @@ const STATE_COLORED_DOMAIN = new Set([
"sun",
"switch",
"timer",
"timer_list",
"update",
"vacuum",
"valve",
+1 -1
View File
@@ -9,7 +9,7 @@ import {
// The filters of the Marketplace tables. Search, sorting and grouping are kept
// by the data table, see data-table-query-params.
export const marketplaceFilterQueryParamConfig = {
list: ["status", "type", "source"],
list: ["status", "type", "source", "integration_category"],
} as const satisfies QueryParamConfig;
export type MarketplaceFilterQueryParams = QueryParamValues<
+5
View File
@@ -21,6 +21,11 @@ export class HaIconButtonPrev extends LitElement {
@property() download?: string;
static shadowRootOptions: ShadowRootInit = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
@state() private _icon =
mainWindow.document.dir === "rtl" ? mdiChevronRight : mdiChevronLeft;
@@ -1,17 +1,37 @@
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { mdiMagnify, mdiMapSearchOutline } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import type {
LocationSelector,
LocationSelectorValue,
} from "../../data/selector";
import type { OpenStreetMapPlace } from "../../data/openstreetmap";
import {
formatOpenStreetMapPlace,
searchPlaces,
} from "../../data/openstreetmap";
import type { HomeAssistant } from "../../types";
import type { SchemaUnion } from "../ha-form/types";
import type { MarkerLocation } from "../map/ha-locations-editor";
import type { HaListItemButton } from "../item/ha-list-item-button";
import { searchResultsStatus } from "../list/search-results-status";
import type {
HaLocationsEditor,
MarkerLocation,
} from "../map/ha-locations-editor";
import "../map/ha-locations-editor";
import "../ha-form/ha-form";
import type { LocalizeFunc } from "../../common/translations/localize";
import "../ha-alert";
import "../ha-icon-button";
import "../item/ha-list-item-button";
import "../list/ha-list-base";
import "../ha-spinner";
import "../ha-svg-icon";
import "../input/ha-input";
import type { HaInput } from "../input/ha-input";
import {
computeLocationSelectorValue,
DEFAULT_RADIUS,
@@ -31,6 +51,18 @@ export class HaLocationSelector extends LitElement {
@property({ type: Boolean, reflect: true }) public disabled = false;
@state() private _working = false;
@state() private _places?: OpenStreetMapPlace[] | null;
@state() private _searchError = false;
@state() private _status?: string;
@query("ha-input") private _input?: HaInput;
@query("ha-locations-editor") private _map!: HaLocationsEditor;
private _schema = memoizeOne(
(localize: LocalizeFunc, radius?: boolean, radius_readonly?: boolean) =>
[
@@ -86,6 +118,90 @@ export class HaLocationSelector extends LitElement {
protected render() {
return html`
<p>${this.label ? this.label : ""}</p>
<div class="location-search" @keydown=${this._searchKeyDown}>
<ha-input
label=${this.hass.localize(
"ui.components.selectors.location.address_label"
)}
.disabled=${this.disabled}
.readonly=${this._working}
@input=${this._inputChanged}
@keydown=${this._addressSearch}
>
<ha-svg-icon slot="start" .path=${mdiMagnify}></ha-svg-icon>
${
this._working
? html`<ha-spinner slot="end" size="small"></ha-spinner>`
: html`<ha-icon-button
slot="end"
.path=${mdiMapSearchOutline}
.label=${this.hass.localize("ui.common.search")}
.disabled=${this.disabled}
@click=${this._searchButtonClicked}
></ha-icon-button>`
}
</ha-input>
${
this._searchError
? html`<ha-alert alert-type="error">
${this.hass.localize(
"ui.components.selectors.location.search_error"
)}
</ha-alert>`
: nothing
}
<div
class="visually-hidden"
role="status"
aria-live="polite"
aria-atomic="true"
>
${this._status}
</div>
${
Array.isArray(this._places) && this._places.length
? html`
<ha-list-base
aria-label=${this.hass.localize(
"ui.components.selectors.location.search_results_label"
)}
>
${this._places.map(this._renderPlace)}
</ha-list-base>
`
: this._places?.length === 0
? html`<p class="search-no-results">
${this.hass.localize("ui.components.combo-box.no_match")}
</p>`
: nothing
}
<p class="attribution">
${this.hass.localize(
"ui.components.selectors.location.search_disclosure",
{
openstreetmap: html`<a
href="https://www.openstreetmap.org/"
target="_blank"
rel="noopener noreferrer"
>OpenStreetMap</a
>`,
osm_privacy_policy: html`<a
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
target="_blank"
rel="noopener noreferrer"
>${this.hass.localize(
"ui.components.selectors.location.osm_privacy_policy"
)}</a
>`,
}
)}
</p>
</div>
<ha-locations-editor
class="flex"
.helper=${this.helper}
@@ -177,11 +293,163 @@ export class HaLocationSelector extends LitElement {
return "";
};
private _addressSearch(ev: KeyboardEvent) {
if (ev.key !== "Enter") {
return;
}
ev.stopPropagation();
if (ev.isComposing || ev.target !== ev.currentTarget) {
return;
}
ev.preventDefault();
this._searchPlaces(this._input?.value ?? "");
}
private _searchKeyDown(ev: KeyboardEvent) {
if (ev.key === "Enter") {
ev.stopPropagation();
}
}
private _inputChanged(): void {
this._places = undefined;
this._searchError = false;
this._status = undefined;
}
private _searchButtonClicked() {
this._input?.select();
this._searchPlaces(this._input?.value ?? "");
}
private async _searchPlaces(address: string) {
const searchTerm = address.trim();
if (!searchTerm || this.disabled || this._working) {
return;
}
this._working = true;
this._places = null;
this._searchError = false;
this._status = undefined;
try {
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
this._status = searchResultsStatus(
searchTerm,
this._places,
() => true,
this.hass.localize
);
} catch (_err) {
this._places = undefined;
this._searchError = true;
} finally {
this._working = false;
}
}
private _renderPlace = (place: OpenStreetMapPlace) => {
const { primary, secondary } = formatOpenStreetMapPlace(place);
return html`
<ha-list-item-button
@click=${this._placeSelected}
.disabled=${this.disabled}
.placeId=${place.place_id}
>
<span slot="headline">${primary || secondary}</span>
${
primary && secondary
? html`<span slot="supporting-text">${secondary}</span>`
: nothing
}
</ha-list-item-button>
`;
};
private async _placeSelected(
ev: HASSDomCurrentTargetEvent<HaListItemButton & { placeId: number }>
) {
if (this.disabled) {
return;
}
const place = this._places?.find(
(item) => item.place_id === ev.currentTarget.placeId
);
if (!place) {
return;
}
fireEvent(this, "value-changed", {
value: {
...this.value,
latitude: Number(place.lat),
longitude: Number(place.lon),
},
});
if (ev.currentTarget.matches(":focus-within")) {
this._input?.focus({ preventScroll: true });
}
this._places = undefined;
this._status = this.hass.localize(
"ui.components.selectors.location.selected_location",
{ location: place.display_name }
);
await this.updateComplete;
await this._map.fitMarker("location");
}
static styles = css`
.location-search {
margin-bottom: var(--ha-space-4);
}
.attribution {
margin: var(--ha-space-2) 0 0;
color: var(--secondary-text-color);
font-size: var(--ha-font-size-xs);
}
.attribution a {
color: inherit;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.search-no-results {
margin: 0;
padding: var(--ha-space-2) var(--ha-space-4);
color: var(--secondary-text-color);
}
ha-list-base {
width: 100%;
border: 1px solid var(--divider-color);
box-sizing: border-box;
border-radius: var(--ha-border-radius-sm);
}
ha-locations-editor {
display: block;
--ha-locations-editor-map-height: 400px;
margin-bottom: 16px;
margin-bottom: var(--ha-space-4);
}
p {
margin-top: 0;
-117
View File
@@ -1,117 +0,0 @@
import { mdiClose, mdiInformationOutline } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, 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 { showStartupProgressDialog } from "../dialogs/startup-progress/show-dialog-startup-progress";
import "./ha-icon-button";
@customElement("ha-startup-progress")
export class HaStartupProgress extends LitElement {
// The launch screen render swap would remove a dialog opened before it.
@property({ attribute: false }) public detailsAvailable = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
// Fallbacks cover the first render, before the core translations have loaded.
protected render() {
const localize = this._localize;
return html`
<div class="card">
<div class="text" role="status">
<span class="title">
${
localize("ui.startup_progress.starting") ||
"Home Assistant is starting"
}
</span>
<span class="secondary">
${
localize("ui.startup_progress.starting_secondary") ||
"Some features may not be available yet"
}
</span>
</div>
${
this.detailsAvailable
? html`<ha-icon-button
.label=${
localize("ui.startup_progress.details") || "Startup details"
}
.path=${mdiInformationOutline}
@click=${this._showDetails}
></ha-icon-button>`
: nothing
}
<ha-icon-button
.label=${localize("ui.notification_toast.dismiss") || "Dismiss"}
.path=${mdiClose}
@click=${this._dismiss}
></ha-icon-button>
</div>
`;
}
private _showDetails() {
showStartupProgressDialog(this);
}
private _dismiss() {
fireEvent(this, "startup-progress-dismissed");
}
static styles = css`
:host {
position: fixed;
inset-inline-start: 50%;
inset-block-end: calc(
var(--safe-area-inset-bottom, 0px) + var(--ha-space-4)
);
transform: translateX(calc(-50% * var(--scale-direction, 1)));
/* Above the launch screen, which can still be fading out. */
z-index: 101;
width: min(420px, calc(100vw - var(--ha-space-8)));
}
.card {
display: flex;
align-items: center;
gap: var(--ha-space-2);
padding: var(--ha-space-3) var(--ha-space-2) var(--ha-space-3)
var(--ha-space-4);
color: var(--ha-color-on-neutral-loud);
background-color: var(--ha-color-neutral-10);
border-radius: var(--ha-border-radius-sm);
box-shadow: var(--wa-shadow-l);
}
.text {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
}
.title {
font-weight: var(--ha-font-weight-medium);
}
.secondary {
/* The card is dark in both themes, so the themed quiet color lacks contrast. */
color: var(--ha-color-neutral-70);
font-size: var(--ha-font-size-s);
}
ha-icon-button {
--mdc-icon-button-size: 36px;
color: var(--ha-color-on-neutral-loud);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-startup-progress": HaStartupProgress;
}
interface HASSDomEvents {
"startup-progress-dismissed": undefined;
}
}
+39 -4
View File
@@ -1,4 +1,4 @@
import { css, html, LitElement } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { classMap } from "lit/directives/class-map";
import {
customElement,
@@ -24,6 +24,8 @@ export interface ToastClosedEventDetail {
export class HaToast extends LitElement {
@property({ attribute: "label-text" }) public labelText = "";
@property({ attribute: "supporting-text" }) public supportingText?: string;
@property({ attribute: "announce-text" }) public announceText?: string;
@property({ type: Number, attribute: "timeout-ms" }) public timeoutMs = 4000;
@@ -234,7 +236,22 @@ export class HaToast extends LitElement {
popoverSupported && !this.stacked ? "manual" : undefined
)}
>
<span class="message">${this.labelText}</span>
<div class="text">
<span
class=${classMap({
message: true,
"has-supporting-text": !!this.supportingText,
})}
>${this.labelText}</span
>
${
this.supportingText
? html`<span class="supporting-text"
>${this.supportingText}</span
>`
: nothing
}
</div>
<div class=${classMap({ actions: true, "has-action": hasAction })}>
<slot name="action"></slot>
<slot name="dismiss"></slot>
@@ -246,7 +263,10 @@ export class HaToast extends LitElement {
aria-live=${this._active ? "polite" : "off"}
aria-atomic="true"
>
${this.announceText ?? this.labelText}
${
this.announceText ??
[this.labelText, this.supportingText].filter(Boolean).join(" ")
}
</span>
`;
}
@@ -306,11 +326,22 @@ export class HaToast extends LitElement {
display: none;
}
.message {
.text {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
}
.supporting-text {
color: var(--ha-color-neutral-70);
font-size: var(--ha-font-size-s);
}
.message.has-supporting-text {
font-weight: var(--ha-font-weight-medium);
}
.assistive-message {
position: absolute;
width: 1px;
@@ -330,6 +361,10 @@ export class HaToast extends LitElement {
color: var(--ha-color-on-neutral-loud);
}
::slotted(ha-icon-button) {
margin-inline: calc(var(--ha-space-1) * -1);
}
.actions:not(.has-action) {
display: none;
}
@@ -0,0 +1,137 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { durationDataToSeconds } from "../../common/datetime/duration_to_seconds";
import { consume } from "../../common/decorators/consume";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { apiContext } from "../../data/context";
import { createTimerListTimer } from "../../data/timer_list";
import { DialogMixin } from "../../dialogs/dialog-mixin";
import { haStyleDialog } from "../../resources/styles";
import type { HomeAssistantApi, ValueChangedEvent } from "../../types";
import "../ha-alert";
import "../ha-button";
import "../ha-dialog";
import "../ha-dialog-footer";
import "../ha-duration-input";
import type { HaDurationData } from "../ha-duration-input";
import "../input/ha-input";
import type { HaInput } from "../input/ha-input";
import type { TimerListCreateDialogParams } from "./show-dialog-timer-list-create";
@customElement("dialog-timer-list-create")
class DialogTimerListCreate extends DialogMixin<TimerListCreateDialogParams>(
LitElement
) {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@state() private _name = "";
@state() private _duration: HaDurationData = { minutes: 5 };
@state() private _error?: string;
@state() private _submitting = false;
protected render() {
if (!this.params || !this._localize) {
return nothing;
}
return html`
<ha-dialog
open
width="small"
header-title=${this._localize("ui.components.timer-list.add_timer")}
>
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="form">
<ha-duration-input
autofocus
required
.label=${this._localize("ui.components.timer-list.duration")}
.data=${this._duration}
@value-changed=${this._durationChanged}
></ha-duration-input>
<ha-input
.label=${this._localize("ui.components.timer-list.name")}
.value=${this._name}
@input=${this._nameChanged}
></ha-input>
</div>
<ha-dialog-footer slot="footer">
<ha-button
slot="secondaryAction"
appearance="plain"
@click=${this.closeDialog}
>
${this._localize("ui.common.cancel")}
</ha-button>
<ha-button
slot="primaryAction"
.disabled=${
this._submitting || !durationDataToSeconds(this._duration)
}
@click=${this._start}
>
${this._localize("ui.components.timer-list.start")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private _nameChanged(ev: HASSDomCurrentTargetEvent<HaInput>): void {
this._name = ev.currentTarget.value ?? "";
}
private _durationChanged(
ev: ValueChangedEvent<HaDurationData | undefined>
): void {
this._duration = ev.detail.value ?? {};
}
private async _start(): Promise<void> {
this._submitting = true;
this._error = undefined;
try {
await createTimerListTimer(
this._api.callService,
this.params!.entityId,
this._duration,
this._name.trim()
);
this.closeDialog();
} catch (err: any) {
this._error = err.message;
} finally {
this._submitting = false;
}
}
static styles = [
haStyleDialog,
css`
.form {
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"dialog-timer-list-create": DialogTimerListCreate;
}
}
+409
View File
@@ -0,0 +1,409 @@
import { mdiClose, mdiPause, mdiPlay, mdiPlus } from "@mdi/js";
import type {
Connection,
HassEntity,
UnsubscribeFunc,
} from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { repeat } from "lit/directives/repeat";
import { formatDurationLong } from "../../common/datetime/format_duration";
import { consume } from "../../common/decorators/consume";
import { consumeEntityState } from "../../common/decorators/consume-context-entry";
import { transform } from "../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import { supportsFeature } from "../../common/entity/supports-feature";
import {
apiContext,
connectionContext,
internationalizationContext,
} from "../../data/context";
import { UNAVAILABLE } from "../../data/entity/entity";
import { normalizeTimerDuration } from "../../data/timer";
import type { TimerListTimer } from "../../data/timer_list";
import {
addTimerListTimerTime,
callTimerListTimerAction,
formatTimerListRemaining,
subscribeTimerListTimers,
TimerListEntityFeature,
timerListTimerRemaining,
sortTimerListTimers,
timerListTimerVisible,
} from "../../data/timer_list";
import type {
HomeAssistantApi,
HomeAssistantConnection,
HomeAssistantInternationalization,
} from "../../types";
import "../ha-button";
import "../ha-icon-button";
import "../ha-svg-icon";
import "../progress/ha-progress-bar";
import { showTimerListCreateDialog } from "./show-dialog-timer-list-create";
type TimerButtonEvent = HASSDomCurrentTargetEvent<
HTMLElement & { timer: TimerListTimer }
>;
@customElement("ha-timer-list")
export class HaTimerList extends LitElement {
@property({ attribute: false }) public entityId?: string;
@property({ attribute: "hide-create", type: Boolean })
public hideCreate = false;
@property({ attribute: "create-at-end", type: Boolean, reflect: true })
public createAtEnd = false;
@state()
@consumeEntityState({ entityIdPath: ["entityId"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@consume({ context: connectionContext, subscribe: true })
@transform<HomeAssistantConnection, Connection>({
transformer: ({ connection }) => connection,
})
private _connection!: Connection;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@state() private _timers?: TimerListTimer[];
private _subscribedEntityId?: string;
private _unsubTimers?: Promise<UnsubscribeFunc>;
private _interval?: number;
public connectedCallback(): void {
super.connectedCallback();
if (this.hasUpdated) {
this.requestUpdate();
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
this._unsubscribe();
this._subscribedEntityId = undefined;
this._clearInterval();
}
// Runs from updated(), because the entity state of a new entityId is only
// current after willUpdate().
private _updateSubscription(): void {
// The backend refuses a subscription to an unavailable entity, and drops
// the subscription when the entity is reloaded.
const entityId =
this._stateObj && this._stateObj.state !== UNAVAILABLE
? this.entityId
: undefined;
if (entityId === this._subscribedEntityId) {
return;
}
this._subscribedEntityId = entityId;
this._unsubscribe();
this._timers = undefined;
if (entityId && this._connection) {
this._unsubTimers = subscribeTimerListTimers(
this._connection,
entityId,
(timers) => {
this._timers = timers;
}
);
}
}
protected updated(): void {
// An update that was queued before the element was removed still runs
if (!this.isConnected) {
return;
}
this._updateSubscription();
// Finished timers need the tick too, to hide them when their time is up.
const ticking = this._timers?.some(
(timer) => timer.status !== "paused" && timerListTimerVisible(timer)
);
if (ticking && !this._interval) {
this._interval = window.setInterval(() => this.requestUpdate(), 1000);
} else if (!ticking) {
this._clearInterval();
}
}
private _unsubscribe(): void {
this._unsubTimers?.then((unsub) => unsub());
this._unsubTimers = undefined;
}
private _clearInterval(): void {
window.clearInterval(this._interval);
this._interval = undefined;
}
protected render() {
if (!this._stateObj || !this._i18n) {
return nothing;
}
const stateObj = this._stateObj;
const unavailable = stateObj.state === UNAVAILABLE;
const timers =
this._timers &&
sortTimerListTimers(
this._timers.filter((timer) => timerListTimerVisible(timer))
);
const canPause = supportsFeature(
stateObj,
TimerListEntityFeature.PAUSE_TIMER
);
const canCancel = supportsFeature(
stateObj,
TimerListEntityFeature.CANCEL_TIMER
);
const canAddTime = supportsFeature(
stateObj,
TimerListEntityFeature.ADD_TIME
);
const canRemove = supportsFeature(
stateObj,
TimerListEntityFeature.REMOVE_TIMER
);
const createButton =
!this.hideCreate &&
supportsFeature(stateObj, TimerListEntityFeature.CREATE_TIMER)
? html`
<ha-button
class="create"
appearance="filled"
.disabled=${unavailable}
@click=${this._showCreateDialog}
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this._i18n.localize("ui.components.timer-list.add_timer")}
</ha-button>
`
: nothing;
return html`
${this.createAtEnd ? nothing : createButton}
${
unavailable
? html`<p class="empty">
${this._i18n.localize("state.default.unavailable")}
</p>`
: !timers
? nothing
: !timers.length
? html`<p class="empty">
${this._i18n.localize("ui.components.timer-list.no_timers")}
</p>`
: html`
<ul>
${repeat(
timers,
(timer) => timer.timer_id,
(timer) => {
const paused = timer.status === "paused";
const finished = timer.status === "finished";
const remaining = timerListTimerRemaining(timer);
const name =
timer.name ||
formatDurationLong(
this._i18n.locale,
normalizeTimerDuration({
seconds: timer.created_duration,
})
);
return html`
<li class=${classMap({ paused, finished })}>
<div class="row">
<div class="info">
<span class="remaining">
${formatTimerListRemaining(remaining)}
</span>
<span class="name">
${
paused || finished
? this._i18n.localize(
finished
? "ui.components.timer-list.finished_name"
: "ui.components.timer-list.paused_name",
{ name }
)
: name
}
</span>
</div>
${
canAddTime && !finished
? html`<ha-button
class="add-time"
appearance="plain"
size="s"
.timer=${timer}
title=${this._i18n.localize(
"ui.components.timer-list.add_minute"
)}
@click=${this._addMinute}
>
${this._i18n.localize(
"ui.components.timer-list.add_minute_short"
)}
</ha-button>`
: nothing
}
${
canPause && !finished
? html`<ha-icon-button
.timer=${timer}
.path=${paused ? mdiPlay : mdiPause}
.label=${this._i18n.localize(
paused
? "ui.components.timer-list.resume"
: "ui.components.timer-list.pause"
)}
@click=${this._togglePause}
></ha-icon-button>`
: nothing
}
${
(finished ? canRemove : canCancel)
? html`<ha-icon-button
.timer=${timer}
.path=${mdiClose}
.label=${this._i18n.localize(
finished
? "ui.components.timer-list.remove"
: "ui.components.timer-list.cancel"
)}
@click=${this._cancelOrRemove}
></ha-icon-button>`
: nothing
}
</div>
<ha-progress-bar
.label=${name}
.value=${
timer.total_duration
? (remaining / timer.total_duration) * 100
: 0
}
></ha-progress-bar>
</li>
`;
}
)}
</ul>
`
}
${this.createAtEnd ? createButton : nothing}
`;
}
private _showCreateDialog(): void {
showTimerListCreateDialog(this, { entityId: this.entityId! });
}
private _addMinute(ev: TimerButtonEvent): void {
addTimerListTimerTime(
this._api.callService,
this.entityId!,
ev.currentTarget.timer.timer_id,
{ minutes: 1 }
);
}
private _togglePause(ev: TimerButtonEvent): void {
const { timer } = ev.currentTarget;
callTimerListTimerAction(
this._api.callService,
this.entityId!,
timer.status === "paused" ? "unpause_timer" : "pause_timer",
timer.timer_id
);
}
private _cancelOrRemove(ev: TimerButtonEvent): void {
const { timer } = ev.currentTarget;
callTimerListTimerAction(
this._api.callService,
this.entityId!,
timer.status === "finished" ? "remove_timer" : "cancel_timer",
timer.timer_id
);
}
static styles = css`
:host {
display: block;
}
.create {
width: 100%;
margin-bottom: var(--ha-space-4);
}
:host([create-at-end]) .create {
margin-top: var(--ha-space-4);
margin-bottom: 0;
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
}
.row {
display: flex;
align-items: center;
}
.info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.remaining {
font-size: var(--ha-font-size-2xl);
line-height: var(--ha-line-height-condensed);
font-variant-numeric: tabular-nums;
}
.name {
color: var(--secondary-text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.paused .remaining {
color: var(--secondary-text-color);
}
.finished .remaining {
color: var(--error-color);
}
ha-progress-bar {
--ha-progress-bar-track-height: 4px;
margin-top: var(--ha-space-1);
}
.empty {
margin: 0;
padding: var(--ha-space-4) 0;
color: var(--secondary-text-color);
text-align: center;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-timer-list": HaTimerList;
}
}
@@ -0,0 +1,16 @@
import { fireEvent } from "../../common/dom/fire_event";
export interface TimerListCreateDialogParams {
entityId: string;
}
export const showTimerListCreateDialog = (
element: HTMLElement,
dialogParams: TimerListCreateDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-timer-list-create",
dialogImport: () => import("./dialog-timer-list-create"),
dialogParams,
});
};
+37 -2
View File
@@ -245,7 +245,17 @@ type ConditionIcons = Record<
>;
export type IconCategory =
"entity" | "entity_component" | "services" | "triggers" | "conditions";
| "entity"
| "entity_component"
| "services"
| "triggers"
| "conditions"
| "integration_category";
export type IntegrationCategoryIcons = Record<
string,
{ default: string; subcategory?: Record<string, { default: string }> }
>;
interface CategoryType {
entity: PlatformIcons;
@@ -253,6 +263,7 @@ interface CategoryType {
services: ServiceIcons;
triggers: TriggerIcons;
conditions: ConditionIcons;
integration_category: IntegrationCategoryIcons;
}
export const getHassIcons = async <T extends IconCategory>(
@@ -321,7 +332,10 @@ export const getComponentIcons = async (
};
export const getCategoryIcons = async <
T extends Exclude<IconCategory, "entity" | "entity_component">,
T extends Exclude<
IconCategory,
"entity" | "entity_component" | "integration_category"
>,
>(
connection: Connection,
hassConfig: HomeAssistant["config"],
@@ -740,3 +754,24 @@ export const domainIcon = async (
return undefined;
};
let integrationCategoryIcons:
ReturnType<typeof getHassIcons<"integration_category">> | undefined;
export const getIntegrationCategoryIcons = async (
connection: Connection
): Promise<IntegrationCategoryIcons | undefined> => {
// Cache the request itself, so callers while it loads share it
integrationCategoryIcons ??= getHassIcons(
connection,
"integration_category",
"homeassistant"
);
try {
const result = await integrationCategoryIcons;
return result.resources.homeassistant;
} catch (_err) {
integrationCategoryIcons = undefined;
return undefined;
}
};
+2
View File
@@ -78,6 +78,8 @@ export interface IntegrationManifest {
)[];
homekit?: { models?: string[] };
integration_type?: IntegrationType;
// Categories like `energy` or subcategories like `energy.ev_charging`
categories?: string[];
loggers?: string[];
quality_scale?:
| "bronze"
+36
View File
@@ -0,0 +1,36 @@
import type { LocalizeFunc } from "../common/translations/localize";
import type { IntegrationCategoryIcons } from "./icons";
const TRANSLATION_KEY = "component.homeassistant.integration_category";
// The name of a category, like `energy`, or of a subcategory, like
// `energy.solar`. Empty for one this Home Assistant doesn't know.
export const integrationCategoryName = (
localize: LocalizeFunc,
slug: string
): string => {
const [category, subcategory] = slug.split(".");
return subcategory
? localize(`${TRANSLATION_KEY}.${category}.subcategory.${subcategory}.name`)
: localize(`${TRANSLATION_KEY}.${category}.name`);
};
export const integrationCategoryIcon = (
icons: IntegrationCategoryIcons | undefined,
slug: string
): string | undefined => {
const [category, subcategory] = slug.split(".");
return subcategory
? icons?.[category]?.subcategory?.[subcategory]?.default
: icons?.[category]?.default;
};
// In a category when it lists the category itself, or one of its
// subcategories. A subcategory only matches itself.
export const inIntegrationCategory = (
categories: string[] | undefined,
slug: string
): boolean =>
(categories ?? []).some(
(category) => category === slug || category.startsWith(`${slug}.`)
);
+2
View File
@@ -13,6 +13,8 @@ export interface Integration {
is_built_in?: boolean;
overwrites_built_in?: boolean;
single_config_entry?: boolean;
// Categories like `energy` or subcategories like `energy.ev_charging`
categories?: string[];
}
export type Integrations = Record<string, Integration>;
+3
View File
@@ -21,6 +21,9 @@ export interface RepositoryBase {
id: string;
installed_version: string;
installed: boolean;
// Categories like `energy` or subcategories like `energy.solar`. Only
// integrations have them, and not every one sets them yet.
integration_categories?: string[];
last_updated: string | number;
local_path: string;
name: string;
+48 -7
View File
@@ -29,24 +29,65 @@ export interface OpenStreetMapPlace {
boundingbox: number[];
}
export const formatOpenStreetMapPlace = (
place: OpenStreetMapPlace
): { primary: string; secondary: string } => {
const primary = [
...new Set([
place.name || place.address[place.category],
place.address.house_number,
place.address.road || place.address.waterway,
place.address.village || place.address.town,
place.address.suburb || place.address.subdivision,
place.address.city || place.address.municipality,
]),
]
.filter(Boolean)
.join(", ");
const secondary = [
...new Set([
place.address.county ||
place.address.state_district ||
place.address.region,
place.address.state,
place.address.country,
]),
]
.filter(Boolean)
.join(", ");
return { primary, secondary };
};
export const searchPlaces = (
address: string,
hass: HomeAssistant,
addressdetails?: boolean,
limit?: number
): Promise<OpenStreetMapPlace[]> =>
fetch(
`https://nominatim.openstreetmap.org/search.php?q=${address}&format=jsonv2${
limit ? `&limit=${limit}` : ""
}${addressdetails ? "&addressdetails=1" : ""}&accept-language=${
hass.locale.language
}&[email protected]`
): Promise<OpenStreetMapPlace[]> => {
const params = new URLSearchParams({
q: address,
format: "jsonv2",
"accept-language": hass.locale.language,
email: "[email protected]",
});
if (limit) {
params.set("limit", String(limit));
}
if (addressdetails) {
params.set("addressdetails", "1");
}
return fetch(
`https://nominatim.openstreetmap.org/search.php?${params.toString()}`
).then((res) => {
if (res.ok) {
return res.json();
}
throw new Error(res.statusText);
});
};
export const reverseGeocode = (
location: [number, number],
+163
View File
@@ -0,0 +1,163 @@
import type { Connection } from "home-assistant-js-websocket";
import type { HaDurationData } from "../components/ha-duration-input";
import type { HomeAssistant, ServiceCallResponse } from "../types";
export type TimerListTimerStatus =
"active" | "paused" | "finished" | "cancelled";
export interface TimerListTimer {
timer_id: string;
name: string | null;
status: TimerListTimerStatus;
created_duration: number;
total_duration: number;
created_at: string;
finishes_at: string | null;
paused_remaining: number | null;
ended_at: string | null;
remaining: number;
}
export enum TimerListEntityFeature {
CREATE_TIMER = 1,
PAUSE_TIMER = 2,
CANCEL_TIMER = 4,
ADD_TIME = 8,
REMOVE_TIMER = 16,
FINISH_TIMER = 32,
}
export type TimerListMessage =
| { type: "timers"; timers: TimerListTimer[] }
| {
type: "change";
event_type:
| "created"
| "paused"
| "unpaused"
| "time_changed"
| "finished"
| "cancelled"
| "removed";
timer: TimerListTimer;
delta?: number;
};
export const applyTimerListMessage = (
timers: TimerListTimer[],
message: TimerListMessage
): TimerListTimer[] => {
if (message.type === "timers") {
return message.timers;
}
const { timer } = message;
if (message.event_type === "removed") {
return timers.filter((item) => item.timer_id !== timer.timer_id);
}
return timers.some((item) => item.timer_id === timer.timer_id)
? timers.map((item) => (item.timer_id === timer.timer_id ? timer : item))
: [...timers, timer];
};
export const subscribeTimerListTimers = (
connection: Connection,
entity_id: string,
callback: (timers: TimerListTimer[]) => void
) => {
let timers: TimerListTimer[] = [];
return connection.subscribeMessage<TimerListMessage>(
(message) => {
timers = applyTimerListMessage(timers, message);
callback(timers);
},
{ type: "timer_list/item/subscribe", entity_id }
);
};
// Seconds left, from the browser clock for an active timer.
export const timerListTimerRemaining = (
timer: TimerListTimer,
now = Date.now()
): number => {
if (timer.status === "active" && timer.finishes_at) {
return Math.max(0, (new Date(timer.finishes_at).getTime() - now) / 1000);
}
if (timer.status === "paused") {
return timer.paused_remaining ?? 0;
}
return 0;
};
// "9:53" or "1:02:05", without a leading zero on the first unit, as the timer
// entity shows its countdown. Minutes always show, so a short time reads "0:35".
export const formatTimerListRemaining = (remaining: number): string => {
const total = Math.ceil(remaining);
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const seconds = String(total % 60).padStart(2, "0");
return hours
? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}`
: `${minutes}:${seconds}`;
};
const FINISHED_VISIBLE_MS = 5 * 60 * 1000;
// Active and paused timers, and timers that finished in the last 5 minutes.
// The backend keeps ended timers much longer than is useful to show.
export const timerListTimerVisible = (
timer: TimerListTimer,
now = Date.now()
): boolean =>
timer.status === "active" ||
timer.status === "paused" ||
(timer.status === "finished" &&
timer.ended_at !== null &&
now - new Date(timer.ended_at).getTime() < FINISHED_VISIBLE_MS);
const STATUS_ORDER: Record<TimerListTimerStatus, number> = {
finished: 0,
active: 1,
paused: 2,
cancelled: 3,
};
// Finished timers first, as they need attention. Then running and paused
// timers, each with the soonest to finish first.
export const sortTimerListTimers = (
timers: TimerListTimer[],
now = Date.now()
): TimerListTimer[] =>
[...timers].sort(
(a, b) =>
STATUS_ORDER[a.status] - STATUS_ORDER[b.status] ||
timerListTimerRemaining(a, now) - timerListTimerRemaining(b, now)
);
export const createTimerListTimer = (
callService: HomeAssistant["callService"],
entity_id: string,
duration: HaDurationData,
name?: string
): Promise<ServiceCallResponse> =>
callService(
"timer_list",
"create_timer",
{ duration, name: name || undefined },
{ entity_id }
);
export const addTimerListTimerTime = (
callService: HomeAssistant["callService"],
entity_id: string,
timer_id: string,
duration: HaDurationData
): Promise<ServiceCallResponse> =>
callService("timer_list", "add_time", { timer_id, duration }, { entity_id });
export const callTimerListTimerAction = (
callService: HomeAssistant["callService"],
entity_id: string,
action: "pause_timer" | "unpause_timer" | "cancel_timer" | "remove_timer",
timer_id: string
): Promise<ServiceCallResponse> =>
callService("timer_list", action, { timer_id }, { entity_id });
+2 -1
View File
@@ -76,7 +76,8 @@ export type TranslationCategory =
| "selector"
| "services"
| "triggers"
| "conditions";
| "conditions"
| "integration_category";
export const subscribeTranslationPreferences = (
hass: HomeAssistant,
+1
View File
@@ -80,6 +80,7 @@ export const DOMAINS_WITH_MORE_INFO = [
"switch",
"time",
"timer",
"timer_list",
"update",
"vacuum",
"valve",
@@ -7,6 +7,7 @@ import { watchAudioLevel } from "../../../common/audio/watch-audio-level";
import { consume } from "../../../common/decorators/consume";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import "../../../components/camera/ha-camera-player";
@@ -32,6 +33,9 @@ import type {
} from "../../../external_app/external_messaging";
import { showToast } from "../../../util/toast";
// The padding of the microphone row around its 40px button
const MICROPHONE_ROW_HEIGHT = "calc(var(--ha-space-4) * 2 + 40px)";
@customElement("more-info-camera")
class MoreInfoCamera extends LitElement {
@state()
@@ -93,6 +97,11 @@ class MoreInfoCamera extends LitElement {
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
if (changedProps.has("_supportsTwoWayAudio")) {
fireEvent(this, "camera-controls-height-changed", {
height: this._supportsTwoWayAudio ? MICROPHONE_ROW_HEIGHT : undefined,
});
}
if (changedProps.has("_microphoneState")) {
this._stopMicrophoneMeter();
const track = this._cameraStream?.microphoneTrack;
@@ -390,4 +399,7 @@ declare global {
interface HTMLElementTagNameMap {
"more-info-camera": MoreInfoCamera;
}
interface HASSDomEvents {
"camera-controls-height-changed": { height?: string };
}
}
@@ -0,0 +1,27 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import "../../../components/timer-list/ha-timer-list";
@customElement("more-info-timer_list")
class MoreInfoTimerList extends LitElement {
@property({ attribute: false }) public stateObj?: HassEntity;
protected render() {
if (!this.stateObj) {
return nothing;
}
return html`
<ha-timer-list
create-at-end
.entityId=${this.stateObj.entity_id}
></ha-timer-list>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"more-info-timer_list": MoreInfoTimerList;
}
}
+11 -13
View File
@@ -154,8 +154,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
// The dialog grows with the camera's picture, as high as there is room for
@state() private _cameraAspectRatio?: number;
// The camera's info shows microphone controls below the picture then
@state() private _cameraTwoWayAudio = false;
// Height of the controls the camera's info shows below the picture
@state() private _cameraControlsHeight?: string;
@state() private _open = false;
@@ -200,7 +200,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
// its size again
if (params.entityId !== this._entityId) {
this._cameraAspectRatio = undefined;
this._cameraTwoWayAudio = false;
this._cameraControlsHeight = undefined;
}
this._entityId = params.entityId;
if (!this._entityId) {
@@ -266,7 +266,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._childViewStack = [];
this._returnUrl = undefined;
this._cameraAspectRatio = undefined;
this._cameraTwoWayAudio = false;
this._cameraControlsHeight = undefined;
this._isEscapeEnabled = true;
window.removeEventListener("dialog-closed", this._enableEscapeKeyClose);
window.removeEventListener("show-dialog", this._disableEscapeKeyClose);
@@ -709,15 +709,13 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
}
class=${classMap({ camera: domain === "camera" })}
style=${styleMap({
"--more-info-camera-controls-height": this._cameraTwoWayAudio
? "72px"
: undefined,
"--more-info-camera-controls-height": this._cameraControlsHeight,
"--ha-dialog-width-lg": cameraAspectRatio
? `clamp(var(--ha-dialog-width-md, 580px), calc(var(--video-max-height) * ${cameraAspectRatio}), 1920px)`
: undefined,
})}
@camera-aspect-ratio-changed=${this._cameraAspectRatioChanged}
@camera-capabilities-changed=${this._cameraCapabilitiesChanged}
@camera-controls-height-changed=${this._cameraControlsHeightChanged}
.accessibleLabel=${title}
@closed=${this._dialogClosed}
@opened=${this._handleOpened}
@@ -1148,10 +1146,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._cameraAspectRatio = ev.detail.aspectRatio;
}
private _cameraCapabilitiesChanged(
ev: HASSDomEvent<HASSDomEvents["camera-capabilities-changed"]>
private _cameraControlsHeightChanged(
ev: HASSDomEvent<HASSDomEvents["camera-controls-height-changed"]>
) {
this._cameraTwoWayAudio = ev.detail.capabilities?.two_way_audio ?? false;
this._cameraControlsHeight = ev.detail.height;
}
private _enlarge() {
@@ -1218,8 +1216,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
--dialog-content-padding: 0;
}
/* The dialog's margin, its header of about 68px and the microphone
controls of about 72px when the camera has them */
/* The dialog's margin, its header of about 68px and the controls
below the picture */
ha-adaptive-dialog.camera {
--video-max-height: calc(
100vh - var(--ha-space-20) -
@@ -35,6 +35,7 @@ const LAZY_LOADED_MORE_INFO_CONTROL = {
switch: () => import("./controls/more-info-switch"),
time: () => import("./controls/more-info-time"),
timer: () => import("./controls/more-info-timer"),
timer_list: () => import("./controls/more-info-timer_list"),
update: () => import("./controls/more-info-update"),
vacuum: () => import("./controls/more-info-vacuum"),
valve: () => import("./controls/more-info-valve"),
+29 -1
View File
@@ -75,11 +75,39 @@ const clearUrlParams = () => {
}
};
const SERVER_CHECK_TIMEOUT = 10_000;
const checkServer = async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), SERVER_CHECK_TIMEOUT);
try {
const response = await fetch(`${hassUrl}/manifest.json`, {
mode: "no-cors",
cache: "no-store",
signal: controller.signal,
});
if (response.status >= 500) {
throw new Error(`Home Assistant responded with ${response.status}`);
}
} finally {
clearTimeout(timeout);
}
};
// The login page is never cached, so check the server is up before getAuth redirects to it.
const loadTokensOrCheckServer = async () => {
const tokens = loadTokens();
if (!tokens || tokens.hassUrl !== hassUrl) {
await checkServer();
}
return tokens;
};
const authOptions = {
hassUrl,
limitHassInstance: true,
saveTokens,
loadTokens: () => Promise.resolve(loadTokens()),
loadTokens: loadTokensOrCheckServer,
};
const getAuthDroppingStaleCallback = async () => {
+5
View File
@@ -279,6 +279,11 @@ export const ENTITY_COMPONENT_ICONS: Record<string, ComponentIcons> = {
default: "mdi:clipboard-list",
},
},
timer_list: {
_: {
default: "mdi:timer-outline",
},
},
cover: {
_: {
default: "mdi:window-open",
+55 -46
View File
@@ -24,15 +24,16 @@ import "../components/ha-toast";
import type { ToastClosedEventDetail } from "../components/ha-toast";
import type { HomeAssistant } from "../types";
export type ToastText =
| string
| { translationKey: LocalizeKeys; args?: Record<string, string | number> };
export interface ShowToastParams {
// Unique ID for updating or closing a specific toast without flickering.
id?: string;
message:
| string
| { translationKey: LocalizeKeys; args?: Record<string, string | number> };
announceMessage?:
| string
| { translationKey: LocalizeKeys; args?: Record<string, string | number> };
message: ToastText;
supportingText?: ToastText;
announceMessage?: ToastText;
action?: ToastActionParams;
secondaryAction?: ToastActionParams;
dismiss?: () => void;
@@ -44,9 +45,9 @@ export interface ShowToastParams {
export interface ToastActionParams {
action: () => void;
primary?: boolean;
text:
| string
| { translationKey: LocalizeKeys; args?: Record<string, string | number> };
icon?: string;
keepOpen?: boolean;
text: ToastText;
}
interface Notification {
@@ -181,24 +182,9 @@ class NotificationManager extends LitElement {
({ key, parameters }) => html`
<ha-toast
data-notification-key=${key}
.labelText=${
typeof parameters.message !== "string"
? this.hass.localize(
parameters.message.translationKey,
parameters.message.args
)
: parameters.message
}
.announceText=${
parameters.announceMessage
? typeof parameters.announceMessage !== "string"
? this.hass.localize(
parameters.announceMessage.translationKey,
parameters.announceMessage.args
)
: parameters.announceMessage
: undefined
}
.labelText=${this._localizeText(parameters.message)}
.supportingText=${this._localizeText(parameters.supportingText)}
.announceText=${this._localizeText(parameters.announceMessage)}
.timeoutMs=${parameters.duration!}
.stacked=${true}
@toast-closed=${this._toastClosed}
@@ -233,37 +219,61 @@ class NotificationManager extends LitElement {
if (!action) {
return nothing;
}
const onClick = secondary
? this._secondaryButtonClicked
: this._buttonClicked;
if (action.icon) {
return html`
<ha-icon-button
data-notification-key=${key}
.label=${this._localizeText(action.text)}
.path=${action.icon}
slot="action"
@click=${onClick}
></ha-icon-button>
`;
}
return html`
<ha-button
data-notification-key=${key}
appearance=${action.primary ? "filled" : "plain"}
size="s"
slot="action"
@click=${secondary ? this._secondaryButtonClicked : this._buttonClicked}
@click=${onClick}
>
${
typeof action.text !== "string"
? this.hass.localize(action.text.translationKey, action.text.args)
: action.text
}
${this._localizeText(action.text)}
</ha-button>
`;
}
private _buttonClicked(
ev: HASSDomCurrentTargetEvent<HTMLElementTagNameMap["ha-button"]>
) {
const key = ev.currentTarget.dataset.notificationKey!;
this._getToast(key)?.hide("action");
this._getNotification(key)?.parameters.action?.action();
private _localizeText(text: ToastText): string;
private _localizeText(text: ToastText | undefined): string | undefined;
private _localizeText(text: ToastText | undefined) {
return typeof text === "object"
? this.hass.localize(text.translationKey, text.args)
: text;
}
private _secondaryButtonClicked(
ev: HASSDomCurrentTargetEvent<HTMLElementTagNameMap["ha-button"]>
) {
private _buttonClicked(ev: HASSDomCurrentTargetEvent<HTMLElement>) {
const key = ev.currentTarget.dataset.notificationKey!;
this._getToast(key)?.hide("action");
this._getNotification(key)?.parameters.secondaryAction?.action();
this._runAction(key, this._getNotification(key)?.parameters.action);
}
private _secondaryButtonClicked(ev: HASSDomCurrentTargetEvent<HTMLElement>) {
const key = ev.currentTarget.dataset.notificationKey!;
this._runAction(
key,
this._getNotification(key)?.parameters.secondaryAction
);
}
private _runAction(key: string, action: ToastActionParams | undefined) {
if (!action?.keepOpen) {
this._getToast(key)?.hide("action");
}
action?.action();
}
private _dismissClicked(
@@ -332,8 +342,7 @@ class NotificationManager extends LitElement {
inset-inline-end: auto;
inset-block-end: calc(
var(--safe-area-inset-bottom, 0px) + var(--ha-space-4) +
var(--notification-stack-bottom-offset, 0px) +
var(--ha-startup-progress-offset, 0px)
var(--notification-stack-bottom-offset, 0px)
);
inset-inline-start: 50%;
margin: 0;
+7 -20
View File
@@ -34,7 +34,11 @@ import type {
import type { ConfigUpdateValues } from "../data/core";
import { detectCoreConfig } from "../data/core";
import type { OpenStreetMapPlace } from "../data/openstreetmap";
import { reverseGeocode, searchPlaces } from "../data/openstreetmap";
import {
formatOpenStreetMapPlace,
reverseGeocode,
searchPlaces,
} from "../data/openstreetmap";
import { showConfirmationDialog } from "../dialogs/generic/show-dialog-box";
import type { HomeAssistant } from "../types";
import { onBoardingStyles } from "./styles";
@@ -154,25 +158,8 @@ class OnboardingLocation extends LitElement {
${
this._places?.length
? this._places.map((place) => {
const primary = [
place.name || place.address[place.category],
place.address.house_number,
place.address.road || place.address.waterway,
place.address.village || place.address.town,
place.address.suburb || place.address.subdivision,
place.address.city || place.address.municipality,
]
.filter(Boolean)
.join(", ");
const secondary = [
place.address.county ||
place.address.state_district ||
place.address.region,
place.address.state,
place.address.country,
]
.filter(Boolean)
.join(", ");
const { primary, secondary } =
formatOpenStreetMapPlace(place);
return html`<ha-list-item-button
@click=${this._itemClicked}
.placeId=${place.place_id}
@@ -89,7 +89,11 @@ class HaBackupConfigAgents extends LitElement {
const retention = this.agentsConfig?.[agentId]?.retention;
if (retention) {
if (retention && !this._value.includes(agentId)) {
texts.push(
this.hass.localize("ui.panel.config.backup.agents.retention_inactive")
);
} else if (retention) {
if (retention.copies === null && retention.days === null) {
texts.push(
this.hass.localize("ui.panel.config.backup.agents.retention_all")
@@ -120,21 +120,34 @@ class HaConfigBackupDetails extends LitElement {
</p>
</div>
`
: html`<ha-backup-config-retention
location-specific
.headline=${this.hass.localize(
`ui.panel.config.backup.location.retention_for_${isLocalAgent(this.agentId) ? "this_system" : "location"}`,
{ location: agentName }
)}
.hass=${this.hass}
.retention=${
!this.config
? undefined
: this.config.agents[this.agentId]
?.retention || null
}
@value-changed=${this._retentionChanged}
></ha-backup-config-retention>`
: html`${
this.config &&
!this.config.create_backup.agent_ids.includes(
this.agentId
)
? html`<div class="card-content">
<ha-alert alert-type="info">
${this.hass.localize(
"ui.panel.config.backup.location.retention_inactive"
)}
</ha-alert>
</div>`
: nothing
}<ha-backup-config-retention
location-specific
.headline=${this.hass.localize(
`ui.panel.config.backup.location.retention_for_${isLocalAgent(this.agentId) ? "this_system" : "location"}`,
{ location: agentName }
)}
.hass=${this.hass}
.retention=${
!this.config
? undefined
: this.config.agents[this.agentId]
?.retention || null
}
@value-changed=${this._retentionChanged}
></ha-backup-config-retention>`
}
</ha-card>
<ha-card>
@@ -0,0 +1,84 @@
import type { IFuseOptions } from "fuse.js";
import type { HaListVirtualizedItem } from "../../../components/list/ha-list-virtualized";
import { inIntegrationCategory } from "../../../data/integration_category";
export interface IntegrationListItem extends HaListVirtualizedItem {
name: string;
domain: string;
config_flow?: boolean;
is_helper?: boolean;
integrations?: string[];
domains?: string[];
iot_standards?: string[];
supported_by?: string;
cloud?: boolean;
is_built_in?: boolean;
overwrites_built_in?: boolean;
is_add?: boolean;
single_config_entry?: boolean;
// A brand title row, not pickable
is_header?: boolean;
is_end_space?: boolean;
result?: "brand" | "category" | "more";
category?: string;
subcategory?: string;
section?: SearchSection;
icon?: string;
description?: string;
categories?: string[];
}
export type BrowseBy = "category" | "brand";
export type Connection = "local" | "cloud";
export const CONNECTIONS: Connection[] = ["local", "cloud"];
export const ofConnection = (
item: IntegrationListItem,
connection?: Connection
) => !connection || (connection === "cloud") === !!item.cloud;
export type SearchSection = "brand" | "category" | "integration" | "helper";
export const SEARCH_SECTIONS: SearchSection[] = [
"brand",
"category",
"integration",
"helper",
];
export const MAX_SEARCH_ITEMS_PER_SECTION = 5;
export const searchOptions = (
filter: string
): IFuseOptions<IntegrationListItem> => ({
keys: [
{ name: "name", weight: 5 },
{ name: "domain", weight: 5 },
{ name: "integrations", weight: 2 },
"supported_by",
"iot_standards",
],
isCaseSensitive: false,
minMatchCharLength: Math.min(filter.length, 2),
threshold: 0.2,
ignoreDiacritics: true,
});
export interface IntegrationCategory {
slug: string;
name: string;
subcategories: { slug: string; name: string }[];
}
export const inCategory = (
categories: string[] | undefined,
category?: string,
subcategory?: string
) =>
!category ||
inIntegrationCategory(
categories,
subcategory ? `${category}.${subcategory}` : category
);
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import { mdiPlus } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
@@ -11,6 +12,8 @@ import {
} from "../../../common/integrations/protocolIntegrationPicked";
import { navigate } from "../../../common/navigate";
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
import "../../../components/ha-button";
import "../../../components/ha-svg-icon";
import "../../../components/item/ha-list-item-button";
import "../../../components/list/ha-list-base";
import { localizeConfigFlowTitle } from "../../../data/config_flow";
@@ -27,7 +30,7 @@ import { brandsUrl } from "../../../util/brands-url";
import "./ha-integration-list-item";
import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
const standardToDomain = { zigbee: "zha", zwave: "zwave_js" } as const;
export const standardToDomain = { zigbee: "zha", zwave: "zwave_js" } as const;
@customElement("ha-domain-integrations")
class HaDomainIntegrations extends LitElement {
@@ -46,26 +49,86 @@ class HaDomainIntegrations extends LitElement {
@property({ attribute: false })
public showManageLink = false;
@property({ type: Boolean, reflect: true }) public boxed = false;
protected render() {
return html`<ha-list-base>
${
this.flowsInProgress?.length
? html`<h3>
${this.hass.localize("ui.panel.config.integrations.discovered")}
</h3>
${this.flowsInProgress.map(
(flow) =>
html`<ha-list-item-button
.flow=${flow}
@click=${this._flowInProgressPicked}
// Only show manage link if not already on the integrations dashboard
const manage =
this.showManageLink &&
!location.pathname.startsWith("/config/integrations");
return html`<div class="box">
<ha-list-base>
${
this.flowsInProgress?.length
? html`<h3>
${this.hass.localize("ui.panel.config.integrations.discovered")}
</h3>
${this.flowsInProgress.map(
(flow) =>
html`<ha-list-item-button
.flow=${flow}
@click=${this._flowInProgressPicked}
>
<img
alt=""
slot="start"
loading="lazy"
src=${brandsUrl(
{
domain: flow.handler,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
>
<span slot="supporting-text"
>${domainToName(this.hass.localize, flow.handler)}</span
>
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
</ha-list-item-button>`
)}
<wa-divider></wa-divider>
${
this.integration &&
"integrations" in this.integration &&
this.integration.integrations
? html`<h3>
${this.hass.localize(
"ui.panel.config.integrations.available_integrations"
)}
</h3>`
: nothing
}`
: nothing
}
${
this.integration?.iot_standards
? this.integration.iot_standards
.filter((standard) =>
(PROTOCOL_INTEGRATIONS as readonly string[]).includes(
standardToDomain[standard] || standard
)
)
.map((standard) => {
const domain: (typeof PROTOCOL_INTEGRATIONS)[number] =
standardToDomain[standard] || standard;
return html`<ha-list-item-button
.domain=${domain}
@click=${this._standardPicked}
>
<img
alt=""
slot="start"
loading="lazy"
alt=""
src=${brandsUrl(
{
domain: flow.handler,
domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
@@ -75,204 +138,169 @@ class HaDomainIntegrations extends LitElement {
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
>
<span slot="supporting-text"
>${domainToName(this.hass.localize, flow.handler)}</span
>${this.hass.localize(
`ui.panel.config.integrations.add_${domain}_device`
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
)}
<wa-divider></wa-divider>
${
this.integration &&
"integrations" in this.integration &&
this.integration.integrations
? html`<h3>
${this.hass.localize(
"ui.panel.config.integrations.available_integrations"
)}
</h3>`
: nothing
}`
: nothing
}
${
this.integration?.iot_standards
? this.integration.iot_standards
.filter((standard) =>
(PROTOCOL_INTEGRATIONS as readonly string[]).includes(
standardToDomain[standard] || standard
</ha-list-item-button>`;
})
: nothing
}
${
this.integration &&
"integrations" in this.integration &&
this.integration.integrations
? Object.entries(this.integration.integrations)
.filter(([, val]) => val.integration_type !== "hardware")
.sort((a, b) => {
if (a[1].config_flow && !b[1].config_flow) {
return -1;
}
if (b[1].config_flow && !a[1].config_flow) {
return 0;
}
return caseInsensitiveStringCompare(
a[1].name || domainToName(this.hass.localize, a[0]),
b[1].name || domainToName(this.hass.localize, b[0]),
this.hass.locale.language
);
})
.map(
([dom, val]) =>
html`<ha-integration-list-item
.domain=${dom}
.integration=${{
...val,
domain: dom,
name: val.name || domainToName(this.hass.localize, dom),
is_built_in: val.is_built_in !== false,
cloud: val.iot_class?.startsWith("cloud_"),
}}
.opensFlow=${!val.iot_standards}
@click=${this._integrationPicked}
>
</ha-integration-list-item>`
)
)
.map((standard) => {
const domain: (typeof PROTOCOL_INTEGRATIONS)[number] =
standardToDomain[standard] || standard;
return html`<ha-list-item-button
.domain=${domain}
@click=${this._standardPicked}
: nothing
}
${
(PROTOCOL_INTEGRATIONS as readonly string[]).includes(this.domain)
? html`<ha-list-item-button
.domain=${this.domain}
@click=${this._standardPicked}
>
<img
slot="start"
loading="lazy"
alt=""
src=${brandsUrl(
{
domain: this.domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${this.hass.localize(
`ui.panel.config.integrations.add_${
this.domain as (typeof PROTOCOL_INTEGRATIONS)[number]
}_device`
)}</span
>
<img
slot="start"
loading="lazy"
alt=""
src=${brandsUrl(
{
domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${this.hass.localize(
`ui.panel.config.integrations.add_${domain}_device`
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`;
})
: ""
}
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
: nothing
}
${
this.integration &&
"config_flow" in this.integration &&
this.integration.config_flow
? html`${
this.flowsInProgress?.length
? html`<ha-list-item-button
.domain=${this.domain}
@click=${this._integrationPicked}
.integration=${{
...this.integration,
domain: this.domain,
name:
this.integration.name ||
domainToName(this.hass.localize, this.domain),
is_built_in: this.integration.is_built_in !== false,
cloud: this.integration.iot_class?.startsWith("cloud_"),
}}
>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.integrations.new_flow",
{
integration:
this.integration.name ||
domainToName(this.hass.localize, this.domain),
}
)}
</span>
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
</ha-list-item-button>`
: html`<ha-integration-list-item
.domain=${this.domain}
.integration=${{
...this.integration,
domain: this.domain,
name:
this.integration.name ||
domainToName(this.hass.localize, this.domain),
is_built_in: this.integration.is_built_in !== false,
cloud: this.integration.iot_class?.startsWith("cloud_"),
}}
opens-flow
@click=${this._integrationPicked}
>
</ha-integration-list-item>`
}`
: nothing
}
${
manage && !this.boxed
? html`<ha-list-item-button @click=${this._manageDiscovered}>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.integrations.manage_discovered"
)}</span
>
<span slot="supporting-text"
>${this.hass.localize(
"ui.panel.config.integrations.manage_discovered_description"
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
: nothing
}
</ha-list-base>
${
this.integration &&
"integrations" in this.integration &&
this.integration.integrations
? Object.entries(this.integration.integrations)
.filter(([, val]) => val.integration_type !== "hardware")
.sort((a, b) => {
if (a[1].config_flow && !b[1].config_flow) {
return -1;
}
if (b[1].config_flow && !a[1].config_flow) {
return 0;
}
return caseInsensitiveStringCompare(
a[1].name || domainToName(this.hass.localize, a[0]),
b[1].name || domainToName(this.hass.localize, b[0]),
this.hass.locale.language
);
})
.map(
([dom, val]) =>
html`<ha-integration-list-item
.domain=${dom}
.integration=${{
...val,
domain: dom,
name: val.name || domainToName(this.hass.localize, dom),
is_built_in: val.is_built_in !== false,
cloud: val.iot_class?.startsWith("cloud_"),
}}
@click=${this._integrationPicked}
>
</ha-integration-list-item>`
)
: ""
}
${
(PROTOCOL_INTEGRATIONS as readonly string[]).includes(this.domain)
? html`<ha-list-item-button
.domain=${this.domain}
@click=${this._standardPicked}
>
<img
slot="start"
loading="lazy"
alt=""
src=${brandsUrl(
{
domain: this.domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${this.hass.localize(
`ui.panel.config.integrations.add_${
this.domain as (typeof PROTOCOL_INTEGRATIONS)[number]
}_device`
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
: ""
}
${
this.integration &&
"config_flow" in this.integration &&
this.integration.config_flow
? html`${
this.flowsInProgress?.length
? html`<ha-list-item-button
.domain=${this.domain}
@click=${this._integrationPicked}
.integration=${{
...this.integration,
domain: this.domain,
name:
this.integration.name ||
domainToName(this.hass.localize, this.domain),
is_built_in: this.integration.is_built_in !== false,
cloud: this.integration.iot_class?.startsWith("cloud_"),
}}
>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.integrations.new_flow",
{
integration:
this.integration.name ||
domainToName(this.hass.localize, this.domain),
}
)}
</span>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
: html`<ha-integration-list-item
.domain=${this.domain}
.integration=${{
...this.integration,
domain: this.domain,
name:
this.integration.name ||
domainToName(this.hass.localize, this.domain),
is_built_in: this.integration.is_built_in !== false,
cloud: this.integration.iot_class?.startsWith("cloud_"),
}}
@click=${this._integrationPicked}
>
</ha-integration-list-item>`
}`
: ""
}
${
this.showManageLink &&
// Only show manage link if not already on the integrations dashboard
!location.pathname.startsWith("/config/integrations")
? html`<ha-list-item-button @click=${this._manageDiscovered}>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.integrations.manage_discovered"
)}</span
>
<span slot="supporting-text"
>${this.hass.localize(
"ui.panel.config.integrations.manage_discovered_description"
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
manage && this.boxed
? html`<div class="footer">
<div class="footer-bar">
<ha-button
appearance="plain"
size="s"
@click=${this._manageDiscovered}
>
${this.hass.localize(
"ui.panel.config.integrations.manage_discovered"
)}
</ha-button>
</div>
</div>`
: nothing
}
</ha-list-base> `;
</div>`;
}
private async _integrationPicked(
@@ -380,6 +408,86 @@ class HaDomainIntegrations extends LitElement {
ha-icon-next {
color: var(--ha-color-text-secondary);
}
ha-svg-icon[slot="end"] {
color: var(--primary-color);
}
.box {
display: contents;
}
:host([boxed]) {
--ha-row-item-padding-inline: var(--ha-space-3);
display: flex;
flex-direction: column;
flex: 1;
height: 100%;
min-height: 0;
}
:host([boxed]) .box {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: auto;
/* Bouncing would move the sticky footer */
overscroll-behavior: none;
}
:host([boxed]) ha-list-base {
flex-shrink: 0;
padding-block-end: var(--ha-space-2);
}
/* hidden would make it a scroll container and break the sticky title */
:host([boxed]) ha-list-base::part(base) {
overflow-x: clip;
}
:host([boxed]) h3 {
position: sticky;
top: 0;
z-index: 1;
display: flex;
align-items: center;
box-sizing: border-box;
min-height: var(--ha-space-10);
margin: 0;
padding-block: var(--ha-space-2);
padding-inline: var(--ha-space-8) var(--ha-space-3);
background-color: var(--card-background-color);
color: var(--primary-text-color);
font-weight: var(--ha-font-weight-medium);
}
:host([boxed]) ha-list-item-button {
padding: 0 var(--ha-space-4) var(--ha-space-2);
box-sizing: border-box;
--ha-list-item-focus-radius: var(--ha-border-radius-lg);
}
:host([boxed]) ha-list-item-button::part(base) {
border: 1px solid var(--ha-color-border-neutral-quiet);
border-radius: var(--ha-border-radius-lg);
overflow: hidden;
}
:host([boxed]) wa-divider {
display: none;
}
.footer {
position: sticky;
bottom: 0;
z-index: 1;
margin-top: auto;
padding: var(--ha-space-6) var(--ha-space-4) var(--ha-space-3);
background: linear-gradient(
to bottom,
transparent,
var(--card-background-color) var(--ha-space-6)
);
pointer-events: none;
}
.footer-bar {
display: flex;
justify-content: center;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-xl);
background-color: var(--ha-color-surface-low);
pointer-events: auto;
}
`,
];
}
@@ -1,26 +1,31 @@
import {
mdiDevices,
mdiFileCodeOutline,
mdiPackageVariant,
mdiWeb,
} from "@mdi/js";
import { mdiPackageVariant, mdiPlus, mdiWeb } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-domain-icon";
import "../../../components/ha-icon";
import "../../../components/ha-icon-next";
import "../../../components/ha-label";
import "../../../components/ha-svg-icon";
import "../../../components/ha-tooltip";
import { HaListItemButton } from "../../../components/item/ha-list-item-button";
import { domainToName } from "../../../data/integration";
import type { IntegrationListItem } from "./dialog-add-integration";
import type { IntegrationListItem } from "./add-integration-list";
@customElement("ha-integration-list-item")
export class HaIntegrationListItem extends HaListItemButton {
@property({ attribute: false }) public integration!: IntegrationListItem;
// Padding, not margin, so the virtualized list measures it
@property({ type: Boolean, reflect: true }) public card = false;
@property({ type: Boolean, attribute: "opens-flow" }) public opensFlow =
false;
@property({ type: Boolean }) public discovered = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@@ -30,11 +35,8 @@ export class HaIntegrationListItem extends HaListItemButton {
return html`
<div part="start" class="start">
${
integration.is_discovered
? html`<ha-svg-icon
class="discovered-icon"
.path=${mdiDevices}
></ha-svg-icon>`
integration.icon
? html`<ha-icon .icon=${integration.icon}></ha-icon>`
: html`<ha-domain-icon
brand-fallback
.domain=${integration.domain}
@@ -58,6 +60,13 @@ export class HaIntegrationListItem extends HaListItemButton {
: nothing
}
</div>
${
integration.description
? html`<div part="supporting-text" class="supporting">
${integration.description}
</div>`
: nothing
}
</div>
`;
}
@@ -65,14 +74,26 @@ export class HaIntegrationListItem extends HaListItemButton {
protected override _renderEnd(): TemplateResult {
const integration = this.integration;
const yamlOnly =
!integration.result &&
!integration.config_flow &&
!integration.integrations &&
!integration.iot_standards;
return html`
<div part="end" class="end">
${
this.discovered
? html`<ha-label dense>
${this._localize("ui.panel.config.integrations.discovered")}
</ha-label>`
: nothing
}
${
integration.cloud
? html`<ha-svg-icon id="icon-cloud" .path=${mdiWeb}></ha-svg-icon>
? html`<ha-svg-icon
id="icon-cloud"
class="status"
.path=${mdiWeb}
></ha-svg-icon>
<ha-tooltip for="icon-cloud" placement="left">
${this._localize(
"ui.panel.config.integrations.config_entry.depends_on_cloud"
@@ -84,9 +105,9 @@ export class HaIntegrationListItem extends HaListItemButton {
!integration.is_built_in
? html`<ha-svg-icon
id="icon-custom"
class=${
class=${`status ${
integration.overwrites_built_in ? "overwrites" : "custom"
}
}`}
.path=${mdiPackageVariant}
></ha-svg-icon>
<ha-tooltip for="icon-custom" placement="left">
@@ -100,17 +121,25 @@ export class HaIntegrationListItem extends HaListItemButton {
}
${
yamlOnly
? html`<ha-svg-icon
id="icon-yaml"
.path=${mdiFileCodeOutline}
class="open-in-new"
></ha-svg-icon>
<ha-tooltip for="icon-yaml" placement="left">
? html`<ha-label id="label-yaml" class="yaml" dense>
${this._localize(
"ui.panel.config.integrations.config_entry.yaml_label"
)}
</ha-label>
<ha-tooltip for="label-yaml" placement="left">
${this._localize(
"ui.panel.config.integrations.config_entry.yaml_only"
)}
</ha-tooltip>`
: html`<ha-icon-next></ha-icon-next>`
: nothing
}
${
this.opensFlow && !yamlOnly
? html`<ha-svg-icon
class="add action"
.path=${mdiPlus}
></ha-svg-icon>`
: html`<ha-icon-next class="action"></ha-icon-next>`
}
</div>
`;
@@ -119,31 +148,61 @@ export class HaIntegrationListItem extends HaListItemButton {
static styles: CSSResultGroup = [
HaListItemButton.styles,
css`
:host([card]) {
padding: 0 var(--ha-space-4) var(--ha-space-2);
box-sizing: border-box;
--ha-list-item-focus-radius: var(--ha-border-radius-lg);
}
:host([card]) .base {
border: 1px solid var(--ha-color-border-neutral-quiet);
border-radius: var(--ha-border-radius-lg);
overflow: hidden;
}
.start {
--mdc-icon-size: 32px;
height: 32px;
}
/* The inline image's line box pushes it off center */
.start ha-domain-icon {
display: flex;
}
.end {
color: var(--ha-color-text-secondary);
display: flex;
align-items: center;
gap: var(--ha-space-2);
gap: var(--ha-space-1);
}
/* Raise the icons above the row's hit area so their tooltips open */
.end ha-svg-icon {
position: relative;
z-index: 1;
}
/* The chevron is decorative, keep it below the row's hit area */
.end .status {
--mdc-icon-size: 20px;
}
.end .action {
margin-inline-start: var(--ha-space-2);
}
/* Below the row's hit area */
.end ha-icon-next {
z-index: -1;
color: var(--ha-color-on-neutral-quiet);
}
.discovered-icon {
.end ha-label {
border: none;
--ha-label-background-color: var(
--ha-color-fill-primary-normal-resting
);
--ha-label-text-color: var(--ha-color-on-primary-normal);
}
.end .add {
color: var(--primary-color);
}
.open-in-new {
--mdc-icon-size: 22px;
padding: 1px;
.end ha-label.yaml {
--ha-label-background-color: var(
--ha-color-fill-neutral-normal-resting
);
--ha-label-text-color: var(--ha-color-on-neutral-normal);
}
.end .custom {
color: var(--warning-color);
@@ -0,0 +1,33 @@
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators";
/**
* @element ha-integration-list-title
* @summary Title above a group of integration cards, like a brand's name.
* @slot - The title text.
*/
@customElement("ha-integration-list-title")
export class HaIntegrationListTitle extends LitElement {
protected render() {
return html`<slot></slot>`;
}
static styles = css`
:host {
display: flex;
align-items: center;
box-sizing: border-box;
min-height: var(--ha-space-10);
padding-block: var(--ha-space-2);
padding-inline: var(--ha-space-8) var(--ha-space-3);
font-weight: var(--ha-font-weight-medium);
background-color: var(--card-background-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-integration-list-title": HaIntegrationListTitle;
}
}
@@ -8,6 +8,8 @@ export interface AddIntegrationDialogParams {
initialFilter?: string;
integrationFilter?: IntegrationFilter;
navigateToResult?: boolean;
// Opens on a category like `ai_voice`, or a subcategory like `ai_voice.ai_models`
category?: string;
}
export interface YamlIntegrationDialogParams {
@@ -0,0 +1,135 @@
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { applyThemesOnElement } from "../../../common/dom/apply_themes_on_element";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-card";
import "../../../components/timer-list/ha-timer-list";
import { configContext, uiContext } from "../../../data/context";
import type { Themes } from "../../../data/ws-themes";
import type {
HomeAssistant,
HomeAssistantConfig,
HomeAssistantUI,
} from "../../../types";
import { findEntities } from "../common/find-entities";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { LovelaceCard } from "../types";
import type { TimerListCardConfig } from "./types";
@customElement("hui-timer-list-card")
export class HuiTimerListCard extends LitElement implements LovelaceCard {
public static async getConfigForm() {
return (
await import("../editor/config-elements/hui-timer-list-card-editor")
).default;
}
public static getStubConfig(
hass: HomeAssistant,
entities: string[],
entitiesFallback: string[]
): TimerListCardConfig {
const foundEntities = findEntities(hass, 1, entities, entitiesFallback, [
"timer_list",
]);
return { type: "timer-list", entity: foundEntities[0] || "" };
}
@state() private _config?: TimerListCardConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, Themes>({
transformer: ({ themes }) => themes,
})
private _themes!: Themes;
public getCardSize(): number {
return (this._config?.title ? 1 : 0) + 3;
}
public setConfig(config: TimerListCardConfig): void {
if (!config.entity || computeDomain(config.entity) !== "timer_list") {
throw new Error("Specify an entity from within the timer_list domain");
}
this._config = config;
}
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
if (!this._config || !this._themes) {
return;
}
const oldConfig = changedProps.get("_config") as
TimerListCardConfig | undefined;
if (
changedProps.has("_themes") ||
(changedProps.has("_config") && oldConfig?.theme !== this._config.theme)
) {
applyThemesOnElement(this, this._themes, this._config.theme);
}
}
protected render() {
if (!this._config || !this._localize) {
return nothing;
}
if (!this._stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
return html`
<ha-card .header=${this._config.title}>
<ha-timer-list
.entityId=${this._config.entity}
.hideCreate=${this._config.hide_create ?? false}
></ha-timer-list>
</ha-card>
`;
}
static styles = css`
ha-card {
height: 100%;
box-sizing: border-box;
}
ha-timer-list {
padding: var(--ha-space-4);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-timer-list-card": HuiTimerListCard;
}
}
+7
View File
@@ -692,6 +692,13 @@ export interface TodoListCardConfig extends LovelaceCardConfig {
};
}
export interface TimerListCardConfig extends LovelaceCardConfig {
title?: string;
theme?: string;
entity?: string;
hide_create?: boolean;
}
export interface StackCardConfig extends LovelaceCardConfig {
cards: LovelaceCardConfig[];
title?: string;
@@ -105,6 +105,7 @@ const LAZY_LOAD_TYPES = {
"recovery-mode": () => import("../cards/hui-recovery-mode-card"),
"toggle-group": () => import("../cards/hui-toggle-group-card"),
"todo-list": () => import("../cards/hui-todo-list-card"),
"timer-list": () => import("../cards/hui-timer-list-card"),
"shopping-list": () => import("../cards/hui-shopping-list-card"),
starting: () => import("../cards/hui-starting-card"),
"statistics-graph": () => import("../cards/hui-statistics-graph-card"),
@@ -0,0 +1,37 @@
import { assert, assign, boolean, object, optional, string } from "superstruct";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type { HaFormSchema } from "../../../../components/ha-form/types";
import type { LovelaceConfigForm } from "../../types";
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
const struct = assign(
baseLovelaceCardConfig,
object({
entity: optional(string()),
title: optional(string()),
theme: optional(string()),
hide_create: optional(boolean()),
})
);
const SCHEMA: HaFormSchema[] = [
{
name: "entity",
required: true,
selector: { entity: { domain: "timer_list" } },
},
{ name: "title", selector: { text: {} } },
{ name: "theme", selector: { theme: {} } },
{ name: "hide_create", selector: { boolean: {} } },
];
const timerListCardConfigForm: LovelaceConfigForm = {
schema: SCHEMA,
assertConfig: (config) => assert(config, struct),
computeLabel: (schema: HaFormSchema, localize: LocalizeFunc) =>
schema.name === "hide_create"
? localize("ui.panel.lovelace.editor.card.timer-list.hide_create")
: undefined,
};
export default timerListCardConfigForm;
@@ -137,6 +137,9 @@ export const coreCards: Card[] = [
{
type: "todo-list",
},
{
type: "timer-list",
},
{
type: "heading",
showElement: true,
+1 -1
View File
@@ -280,7 +280,7 @@ class HUIRoot extends KeyboardShortcutMixin(LitElement) {
subItems: [
{
icon: mdiDevices,
key: "ui.panel.lovelace.menu.add_device",
key: "ui.panel.lovelace.menu.add_device_or_integration",
visible: true,
action: this._addDevice,
overflowAction: this._addDevice,
@@ -291,6 +291,7 @@ export const getAreaGroupedEntities = (
"input_number",
"counter",
"timer",
"timer_list",
],
area: area,
entity_category: "none",
@@ -14,6 +14,10 @@ import {
type SearchParamsSource,
} from "../../../common/url/query-params";
import type { DataTableRowData } from "../../../components/data-table/ha-data-table";
import {
inIntegrationCategory,
integrationCategoryName,
} from "../../../data/integration_category";
import type { RepositoryBase } from "../../../data/marketplace/repository";
import type { HomeAssistant } from "../../../types";
import type { MarketplaceTab } from "./ha-marketplace-dashboard";
@@ -38,6 +42,9 @@ export const TYPE_FILTER = "type";
export const SOURCE_FILTER = "source";
// Like `energy`, which takes in its subcategories, or `energy.solar`
export const INTEGRATION_CATEGORY_FILTER = "integration_category";
// Where a repository comes from, the community catalog or added from a link
export const SOURCE_ORDER = ["catalog", "custom"] as const;
@@ -49,7 +56,10 @@ const repositorySource = (repository: RepositoryBase): RepositorySource =>
// What the filter panes picked, nothing picked in a pane shows everything
export type RepositoryFilters = Partial<
Record<
typeof STATUS_FILTER | typeof TYPE_FILTER | typeof SOURCE_FILTER,
| typeof STATUS_FILTER
| typeof TYPE_FILTER
| typeof SOURCE_FILTER
| typeof INTEGRATION_CATEGORY_FILTER,
string[]
>
>;
@@ -185,6 +195,17 @@ const matchesFilters = (
return false;
}
const integrationCategories = filters[INTEGRATION_CATEGORY_FILTER];
if (
integrationCategories?.length &&
!integrationCategories.some((slug) =>
inIntegrationCategory(repository.integration_categories, slug)
)
) {
return false;
}
return true;
};
@@ -226,6 +247,13 @@ export const filterRepositories = (
translated_source: localize(
`ui.panel.marketplace.repository_source.${repositorySource(repository)}`
),
// Ones this Home Assistant doesn't know are left out
translated_integration_categories: (
repository.integration_categories ?? []
)
.map((slug) => integrationCategoryName(localize, slug))
.filter(Boolean)
.join(", "),
// A date as text or 0 without one, only numbers sort among each other
last_updated_timestamp: timestamp(repository.last_updated),
}));
@@ -289,6 +317,8 @@ export const browseLinkFromUrl = (
[STATUS_FILTER]: lists.status?.filter(Boolean),
[TYPE_FILTER]: lists.type?.filter(Boolean),
[SOURCE_FILTER]: lists.source?.filter(Boolean),
[INTEGRATION_CATEGORY_FILTER]:
lists.integration_category?.filter(Boolean),
},
};
};
@@ -77,6 +77,7 @@ import {
apiContext,
brandsAccessTokenContext,
configContext,
connectionContext,
devicesContext,
entitiesContext,
internationalizationContext,
@@ -95,6 +96,7 @@ import { haStyle } from "../../../resources/styles";
import {
applySkippedUpdates,
browseLinkFromUrl,
INTEGRATION_CATEGORY_FILTER,
filterRepositories,
filtersOfTab,
marketplaceUpdateEntityIds,
@@ -113,6 +115,12 @@ import type {
} from "./dashboard-repositories";
import { documentationUrl } from "../../../util/documentation-url";
import { renderRepositoryIcon } from "../tools/repository-icon";
import type { IntegrationCategoryIcons } from "../../../data/icons";
import { getIntegrationCategoryIcons } from "../../../data/icons";
import {
integrationCategoryIcon,
integrationCategoryName,
} from "../../../data/integration_category";
import {
showAlertDialog,
showConfirmationDialog,
@@ -198,6 +206,11 @@ export class HaMarketplaceDashboard extends LitElement {
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@consume({ context: connectionContext, subscribe: true })
private _connection!: ContextType<typeof connectionContext>;
@state() private _integrationCategoryIcons?: IntegrationCategoryIcons;
@state()
@consumeEntityStates({ entityIdPath: ["_marketplaceUpdateEntityIds"] })
private _states?: HassEntities;
@@ -284,6 +297,9 @@ export class HaMarketplaceDashboard extends LitElement {
if (!this.hasUpdated) {
this._filters = this._storageFilters;
this._applyLink();
getIntegrationCategoryIcons(this._connection.connection).then((icons) => {
this._integrationCategoryIcons = icons;
});
}
// The states of these are only selected after this runs, so the skipped
@@ -365,6 +381,12 @@ export class HaMarketplaceDashboard extends LitElement {
filters
);
const integrationCategoryStates = this._integrationCategoryStates(
this.marketplace.repositories,
this._i18n.localize,
this._integrationCategoryIcons
);
return html`<hass-tabs-subpage-data-table
.tabs=${tabs}
.columns=${this._columns(
@@ -477,6 +499,20 @@ export class HaMarketplaceDashboard extends LitElement {
.narrow=${this.narrow}
@data-table-filter-changed=${this._sourceFilterChanged}
></ha-filter-states>
${
integrationCategoryStates.length
? html`<ha-filter-states
slot="filter-pane"
.label=${this._i18n.localize(
"ui.panel.marketplace.filters.integration_category"
)}
.value=${this._filters[INTEGRATION_CATEGORY_FILTER]}
.states=${integrationCategoryStates}
.narrow=${this.narrow}
@data-table-filter-changed=${this._integrationCategoryFilterChanged}
></ha-filter-states>`
: nothing
}
</hass-tabs-subpage-data-table>
<ha-dropdown
id="repository-overflow-menu"
@@ -712,6 +748,15 @@ export class HaMarketplaceDashboard extends LitElement {
hidden: false,
defaultHidden: true,
},
// Few custom integrations set their categories yet, so it starts hidden
translated_integration_categories: {
...defaultKeyData,
title: localizeFunc(
"ui.panel.marketplace.column.integration_categories"
),
hidden: false,
defaultHidden: true,
},
description: defaultKeyData,
authors: defaultKeyData,
domain: defaultKeyData,
@@ -1041,6 +1086,43 @@ export class HaMarketplaceDashboard extends LitElement {
}))
);
// The categories the repositories are in, each subcategory after its
// category. Only what can be found, the list of all of them is long.
private _integrationCategoryStates = memoize(
(
repositories: RepositoryBase[],
localize: LocalizeFunc,
icons: IntegrationCategoryIcons | undefined
) => {
const slugs = new Set<string>();
repositories.forEach((repository) =>
repository.integration_categories?.forEach((slug) => {
slugs.add(slug.split(".")[0]);
slugs.add(slug);
})
);
const options = [...slugs]
.map((slug) => ({
value: slug,
label: integrationCategoryName(localize, slug),
icon: integrationCategoryIcon(icons, slug),
category: integrationCategoryName(localize, slug.split(".")[0]),
}))
// Ones this Home Assistant doesn't know are left out
.filter((option) => option.label && option.category);
return options
.sort(
(a, b) =>
a.category.localeCompare(b.category) ||
Number(a.value.includes(".")) - Number(b.value.includes(".")) ||
a.label.localeCompare(b.label)
)
.map(({ value, label, icon }) => ({ value, label, icon }));
}
);
private _sourceStates = memoize((localize: LocalizeFunc) =>
SOURCE_ORDER.map((source) => ({
value: source,
@@ -1134,6 +1216,25 @@ export class HaMarketplaceDashboard extends LitElement {
this._writeFilters();
}
private _integrationCategoryFilterChanged(
ev: CustomEvent<{ value: string[] }>
) {
const filters = {
...this._filters,
[INTEGRATION_CATEGORY_FILTER]: ev.detail.value,
};
if (this._isUserChange(filters)) {
this._storageFilters = {
...this._storageFilters,
[INTEGRATION_CATEGORY_FILTER]: ev.detail.value,
};
}
this._filters = filters;
this._writeFilters();
}
private _handleCollapseChanged(
ev: HASSDomEvent<HASSDomEvents["collapsed-changed"]>
) {
@@ -26,6 +26,8 @@ import { fireEvent } from "../../../common/dom/fire_event";
import { formatNumber } from "../../../common/number/format_number";
import { extractSearchParamsObject } from "../../../common/url/search-params";
import { deepEqual } from "../../../common/util/deep-equal";
import "../../../components/chips/ha-assist-chip";
import "../../../components/chips/ha-chip-set";
import "../../../components/ha-alert";
import "../../../components/ha-card";
import "../../../components/ha-button";
@@ -34,13 +36,21 @@ import "@home-assistant/webawesome/dist/components/divider/divider";
import "../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
import "../../../components/ha-dropdown-item";
import "../../../components/ha-icon";
import "../../../components/ha-icon-button";
import "../../../components/ha-svg-icon";
import { getConfigEntries } from "../../../data/config_entries";
import type { IntegrationCategoryIcons } from "../../../data/icons";
import { getIntegrationCategoryIcons } from "../../../data/icons";
import {
integrationCategoryIcon,
integrationCategoryName,
} from "../../../data/integration_category";
import {
apiContext,
brandsAccessTokenContext,
configContext,
connectionContext,
internationalizationContext,
uiContext,
} from "../../../data/context";
@@ -92,6 +102,10 @@ import { marketplaceBrandsUrl } from "../../../util/brands-url";
import { generateFrontendResourceURL } from "../tools/frontend-resource";
import { installBlockedReason } from "../tools/install-blocked-reason";
import { typeIcon } from "../tools/type-icon";
import {
browseUrl,
INTEGRATION_CATEGORY_FILTER,
} from "./dashboard-repositories";
import { isCommunityOrganization, repositoryAuthors } from "../tools/authors";
import {
markdownWithRepositoryContext,
@@ -158,6 +172,11 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@consume({ context: connectionContext, subscribe: true })
private _connection!: ContextType<typeof connectionContext>;
@state() private _integrationCategoryIcons?: IntegrationCategoryIcons;
@state()
@consumeEntityState({ entityIdPath: ["_repository", "update_entity_id"] })
private _updateEntity?: UpdateEntity;
@@ -182,6 +201,9 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
changedProperties: PropertyValues<this>
): Promise<void> {
super.firstUpdated(changedProperties);
getIntegrationCategoryIcons(this._connection.connection).then((icons) => {
this._integrationCategoryIcons = icons;
});
await this._loadRepository();
}
@@ -596,11 +618,46 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
? html`<p class="description">${repository.description}</p>`
: nothing
}
${this._renderIntegrationCategories(repository)}
</div>
${this._renderStatus(repository)}
</ha-card>`;
}
// Each links to the other integrations in that category
private _renderIntegrationCategories(repository: RepositoryInfo) {
const categories = (repository.integration_categories ?? [])
.map((slug) => ({
slug,
name: integrationCategoryName(this._i18n.localize, slug),
icon: integrationCategoryIcon(this._integrationCategoryIcons, slug),
}))
// Ones this Home Assistant doesn't know are left out
.filter((category) => category.name);
if (!categories.length) {
return nothing;
}
return html`<ha-chip-set class="categories">
${categories.map(
(category) =>
html`<ha-assist-chip
.label=${category.name}
.href=${browseUrl({
filters: { [INTEGRATION_CATEGORY_FILTER]: [category.slug] },
})}
>
${
category.icon
? html`<ha-icon slot="icon" .icon=${category.icon}></ha-icon>`
: nothing
}
</ha-assist-chip>`
)}
</ha-chip-set>`;
}
// Where it stands, and the one thing to do next
private _renderStatus(repository: RepositoryInfo) {
const status = this._status(repository);
@@ -1082,6 +1139,9 @@ type: module</pre>`,
.description {
margin-block: var(--ha-space-4) 0;
}
.categories {
margin-block-start: var(--ha-space-4);
}
.status {
display: flex;
flex-wrap: wrap;
+20 -3
View File
@@ -131,11 +131,22 @@ class HaPanelMarketplace extends SubscribeMixin(LitElement) {
protected willUpdate(changedProperties: PropertyValues<this>): void {
super.willUpdate(changedProperties);
const previousHass = changedProperties.get("hass");
// Another language drops the translations of integrations, they don't
// come back by themselves
if (
this._entryLoaded &&
previousHass &&
previousHass.language !== this.hass.language
) {
this._loadBackendTranslations();
}
if (this._integrationLoaded || !this.hass) {
return;
}
const previousHass = changedProperties.get("hass");
const componentsChanged =
previousHass?.config.components !== this.hass.config.components;
@@ -281,13 +292,19 @@ class HaPanelMarketplace extends SubscribeMixin(LitElement) {
}
this._loadError = undefined;
// The panel translates the errors of the backend itself
this.hass.loadBackendTranslation("exceptions", "marketplace");
this._loadBackendTranslations();
this._subscribeMarketplace();
this._refreshInfo();
this._refreshRepositories();
};
private _loadBackendTranslations() {
// The panel translates the errors of the backend itself
this.hass.loadBackendTranslation("exceptions", "marketplace");
// The categories of custom integrations, the names come with Home Assistant
this.hass.loadBackendTranslation("integration_category", "homeassistant");
}
private _subscribeMarketplace(): void {
const signals: [MarketplaceDispatchEvent, () => void][] = [
[MarketplaceDispatchEvent.CONFIG, this._refreshInfo],
+1
View File
@@ -51,6 +51,7 @@ const marketplaceTableParams = {
type: "string?",
status: "string?",
source: "string?",
integration_category: "string?",
sort: "string?",
direction: "string?",
group: "string?",
+43 -39
View File
@@ -1,3 +1,4 @@
import { mdiInformationOutline } from "@mdi/js";
import type { PropertyValues } from "lit";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { BootstrapProgress } from "../data/bootstrap_integrations";
@@ -25,9 +26,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
private _startupFinishPending = false;
private _startupProgressEl?: HTMLElementTagNameMap["ha-startup-progress"];
private _startupProgressResize?: ResizeObserver;
private _startupToastKey?: string;
private _disconnectedTimeout?: number;
@@ -35,7 +34,6 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
super.firstUpdated(changedProps);
// Need to load in advance because when disconnected, can't dynamically load code.
setTimeout(() => import("../managers/notification-manager"), 5000);
setTimeout(() => import("../components/ha-startup-progress"), 5000);
}
updated(changedProperties: PropertyValues<this>) {
@@ -120,6 +118,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
this._startupProgress = undefined;
this._startupFinishPending = false;
this._startupProgressVisible = true;
this._startupToastKey = undefined;
this._subscribedBootstrapProgress = subscribeBootstrapProgress(
this.hass!.connection,
(message) => {
@@ -132,46 +131,49 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
this._updateStartupProgress();
}
private async _updateStartupProgress() {
if (!this._startupProgressVisible) {
private _updateStartupProgress() {
// Wait until the translations are available.
if (
!this._startupProgressVisible ||
!this.hass!.localize("ui.startup_progress.starting")
) {
return;
}
await import("../components/ha-startup-progress");
// Hidden or finished while the component was loading.
if (!this._startupProgressVisible) {
// The launch screen render swap clears the root, which detaches the
// notification manager and would remove a dialog opened before it.
const mainRendered = !!this.renderRoot.querySelector(
"home-assistant-main"
);
const detailsAvailable = mainRendered && !!this.hass!.user?.is_admin;
const key = `${mainRendered}|${detailsAvailable}`;
if (key === this._startupToastKey) {
return;
}
if (!this._startupProgressEl) {
this._startupProgressEl = document.createElement("ha-startup-progress");
this._startupProgressEl.addEventListener(
"startup-progress-dismissed",
() => this._hideStartupProgress()
);
// Lifts the toast stack above the card so neither covers the other.
this._startupProgressResize = new ResizeObserver(() =>
this.style.setProperty(
"--ha-startup-progress-offset",
`calc(${this._startupProgressEl?.offsetHeight ?? 0}px + var(--ha-space-2))`
)
);
this._startupProgressResize.observe(this._startupProgressEl);
}
// The launch screen render swap clears the root, detaching the card.
if (!this._startupProgressEl.isConnected) {
this.renderRoot.appendChild(this._startupProgressEl);
}
this._startupProgressEl.detailsAvailable =
!!this.renderRoot.querySelector("home-assistant-main");
this._startupToastKey = key;
showToast(this, {
id: SERVER_STARTUP_TOAST_ID,
message: { translationKey: "ui.startup_progress.starting" },
supportingText: {
translationKey: "ui.startup_progress.starting_secondary",
},
duration: -1,
dismissable: true,
dismiss: () => this._hideStartupProgress(),
action: detailsAvailable
? {
text: { translationKey: "ui.startup_progress.details" },
icon: mdiInformationOutline,
keepOpen: true,
action: () => showStartupProgressDialog(this),
}
: undefined,
});
}
// Keeps the subscription, so the completion toast still reflects late failures.
private _hideStartupProgress() {
this._startupProgressVisible = false;
this._startupProgressResize?.disconnect();
this._startupProgressResize = undefined;
this.style.removeProperty("--ha-startup-progress-offset");
this._startupProgressEl?.remove();
this._startupProgressEl = undefined;
this._startupToastKey = undefined;
}
// Core can reach RUNNING before its final snapshot with the failures arrives.
@@ -200,10 +202,12 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
})
: this.hass!.localize("ui.notification_toast.started"),
duration: issues ? 10000 : 5000,
action: {
text: this.hass!.localize("ui.notification_toast.details"),
action: () => showStartupProgressDialog(this),
},
action: this.hass!.user?.is_admin
? {
text: this.hass!.localize("ui.notification_toast.details"),
action: () => showStartupProgressDialog(this),
}
: undefined,
});
}
+62 -9
View File
@@ -628,7 +628,13 @@
"latitude": "[%key:ui::panel::config::zone::detail::latitude%]",
"longitude": "[%key:ui::panel::config::zone::detail::longitude%]",
"radius": "[%key:ui::panel::config::zone::detail::radius%]",
"radius_meters": "[%key:ui::panel::config::core::section::core::core_config::elevation_meters%]"
"radius_meters": "[%key:ui::panel::config::core::section::core::core_config::elevation_meters%]",
"address_label": "[%key:ui::panel::page-onboarding::core-config::address_label%]",
"search_disclosure": "Searches are sent directly to {openstreetmap}, which may receive your IP address. See its {osm_privacy_policy}.",
"osm_privacy_policy": "privacy policy",
"search_error": "Unable to search for this location. Try again.",
"search_results_label": "Search results",
"selected_location": "[%key:ui::panel::page-onboarding::core-config::selected_location%]"
},
"period": {
"periods": {
@@ -1494,6 +1500,21 @@
"grid": "Grid",
"list": "List"
},
"timer-list": {
"name": "Name",
"start": "Start",
"add_timer": "Add timer",
"duration": "[%key:ui::dialogs::helper_settings::timer::duration%]",
"pause": "Pause",
"resume": "Resume",
"cancel": "Cancel",
"add_minute": "Add 1 minute",
"add_minute_short": "+1:00",
"remove": "Remove",
"paused_name": "{name} (paused)",
"finished_name": "{name} (finished)",
"no_timers": "No active timers"
},
"todo": {
"item": {
"summary": "Task name",
@@ -2972,7 +2993,6 @@
"started_with_issues": "Home Assistant has started. {count, plural,\n one {# integration needs}\n other {# integrations need}\n} attention.",
"details": "Details",
"triggered": "Triggered {name}",
"dismiss": "Dismiss",
"no_matching_link_found": "No matching My link found for {path}",
"new_version_available": "A new version of the frontend is available. This page will update in {seconds, plural, one {# second} other {# seconds}}.",
"new_version_available_reload": "A new version of the frontend is available. It will be applied once you have finished what you are working on.",
@@ -3973,7 +3993,8 @@
"location_settings": "Location settings",
"retention_all": "Keep all backups",
"retention_backups": "Keep {count} {count, plural,\n one {backup}\n other {backups}\n}",
"retention_days": "Keep {count} {count, plural,\n one {day}\n other {days}\n}"
"retention_days": "Keep {count} {count, plural,\n one {day}\n other {days}\n}",
"retention_inactive": "Retention paused"
},
"data": {
"ha_settings": "Home Assistant settings",
@@ -4029,7 +4050,7 @@
"retention": "Retention",
"custom_retention": "Custom retention",
"custom_retention_label": "Keep only",
"retention_description": "Based on the maximum number of backups or how many days they should be kept.",
"retention_description": "Based on the maximum number of backups or how many days they should be kept. Only applies to automatic backups, in the locations they are stored in.",
"retention_presets": {
"global": "Use global settings",
"copies_3": "3 backups",
@@ -4304,6 +4325,7 @@
"save_error": "Error saving configuration: {error}",
"retention_for_this_system": "Retention for this system",
"retention_for_location": "Retention for {location}",
"retention_inactive": "Automatic backups aren't stored in this location, so its retention settings are paused. Backups already in this location are kept until you delete them. Retention applies again when you turn the location back on for automatic backups.",
"not_found": "Not found",
"not_found_description": "Location matching ''{backupId}'' not found",
"error": "Could not fetch location details",
@@ -8089,7 +8111,6 @@
"description": "Manage integrations with services or devices",
"integration": "integration",
"discovered": "Discovered",
"discovered_devices": "{count, plural,\n one {# discovered device}\n other {# discovered devices}\n}",
"manage_discovered": "Manage discovered devices",
"manage_discovered_description": "Ignore or configure previously discovered devices",
"disabled": "Disabled",
@@ -8097,7 +8118,7 @@
"new_flow": "Set up another instance of {integration}",
"attention": "Attention required",
"configured": "Configured",
"new": "Select brand",
"add_device_or_integration": "Add device or integration",
"confirm_new": "Do you want to set up {integration}?",
"add_integration": "Add integration",
"no_integrations": "Seems like you don't have any integrations configured yet. Press the button below to add your first integration!",
@@ -8118,7 +8139,31 @@
"search": "Search integrations",
"filters": "[%key:ui::components::subpage-data-table::filters%]",
"filters_disabled_hidden": "Filters, {number} disabled {number, plural,\n one {integration}\n other {integrations}\n} hidden",
"search_brand": "Search for a brand name",
"all_integrations": "All integrations",
"add_a_device": "Add a device",
"browse": "Browse",
"browse_by": {
"label": "Browse by: {value}",
"brand": "Brand",
"category": "Category"
},
"all_brands": "All brands",
"search_all": "Search all brands and integrations",
"search_section": {
"brand": "Brands",
"category": "Categories",
"integration": "Integrations",
"helper": "Helpers"
},
"search_show_more": "Show {count} more",
"subcategories": "Subcategories",
"connection": {
"label": "Connection: {value}",
"all": "All",
"local": "Local",
"cloud": "Cloud"
},
"search_no_results": "No results for “{term}”",
"search_helper": "Search for a helper",
"add_zwave_js_device": "Add Z-Wave device",
"add_zha_device": "Add Zigbee device",
@@ -8274,6 +8319,7 @@
"custom_overwrites_core": "Custom integration that replaces a Core component",
"depends_on_cloud": "Requires Internet",
"yaml_only": "This integration cannot be set up from the UI",
"yaml_label": "YAML",
"no_config_flow": "This integration was not set up from the UI",
"disabled_polling": "Automatic polling for updated data disabled",
"debug_logging_enabled": "Debug logging enabled",
@@ -10704,7 +10750,7 @@
"exit_edit_mode": "Done",
"close": "Close",
"add": "Add to Home Assistant",
"add_device": "Add device",
"add_device_or_integration": "Add device or integration",
"create_automation": "Create automation",
"create_area": "Create area",
"create_area_success": "Area created",
@@ -12037,6 +12083,11 @@
"limit_min": "Minimum value",
"limit_max": "Maximum value"
},
"timer-list": {
"name": "Timer list",
"description": "This card allows you to start, pause, and cancel the timers in a timer list.",
"hide_create": "Hide the add timer button"
},
"todo-list": {
"name": "To-do list",
"description": "This card allows you to add, edit, check-off, and remove items from your to-do list.",
@@ -13546,6 +13597,7 @@
"status": "Status",
"type": "Type",
"source": "Source",
"integration_categories": "Categories",
"last_updated": "Activity",
"actions": "Actions"
},
@@ -13560,7 +13612,8 @@
"filters": {
"status": "Status",
"type": "Type",
"source": "Source"
"source": "Source",
"integration_category": "Category"
},
"dialog_custom_repositories": {
"title": "Add from a GitHub link",
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import type { LocalizeFunc } from "../../src/common/translations/localize";
import {
inIntegrationCategory,
integrationCategoryIcon,
integrationCategoryName,
} from "../../src/data/integration_category";
describe("integrationCategoryName", () => {
const localize = ((key: string) => key) as LocalizeFunc;
it("names a category and a subcategory", () => {
expect(integrationCategoryName(localize, "energy")).toBe(
"component.homeassistant.integration_category.energy.name"
);
expect(integrationCategoryName(localize, "energy.solar_batteries")).toBe(
"component.homeassistant.integration_category.energy.subcategory.solar_batteries.name"
);
});
});
describe("integrationCategoryIcon", () => {
const icons = {
energy: {
default: "mdi:lightning-bolt",
subcategory: { solar_batteries: { default: "mdi:solar-power" } },
},
};
it("finds the icon of a category and of a subcategory", () => {
expect(integrationCategoryIcon(icons, "energy")).toBe("mdi:lightning-bolt");
expect(integrationCategoryIcon(icons, "energy.solar_batteries")).toBe(
"mdi:solar-power"
);
});
it("has none for an unknown category, or without icons", () => {
expect(integrationCategoryIcon(icons, "water")).toBeUndefined();
expect(integrationCategoryIcon(icons, "energy.unknown")).toBeUndefined();
expect(integrationCategoryIcon(undefined, "energy")).toBeUndefined();
});
});
describe("inIntegrationCategory", () => {
it.each([
[["energy.solar_batteries"], "energy", true],
[["energy.solar_batteries"], "energy.solar_batteries", true],
[["energy"], "energy.solar_batteries", false],
// Only a whole slug matches, not one that starts the same
[["energy_storage"], "energy", false],
[undefined, "energy", false],
])("%j is in %s: %s", (categories, slug, expected) => {
expect(inIntegrationCategory(categories, slug)).toBe(expected);
});
});
+94
View File
@@ -0,0 +1,94 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
formatOpenStreetMapPlace,
searchPlaces,
type OpenStreetMapPlace,
} from "../../src/data/openstreetmap";
import type { HomeAssistant } from "../../src/types";
const hass = { locale: { language: "en" } } as HomeAssistant;
afterEach(() => {
vi.unstubAllGlobals();
});
describe("searchPlaces", () => {
it("encodes raw search queries as URL parameters", async () => {
const fetchMock = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response("[]"));
vi.stubGlobal("fetch", fetchMock);
await searchPlaces("10 Downing Street & London", hass, true, 3);
const url = new URL(String(fetchMock.mock.calls[0][0]));
expect(url.searchParams.get("q")).toBe("10 Downing Street & London");
expect(url.searchParams.get("addressdetails")).toBe("1");
expect(url.searchParams.get("limit")).toBe("3");
expect(url.searchParams.get("accept-language")).toBe("en");
});
});
describe("formatOpenStreetMapPlace", () => {
it("formats a street address and its regional details", () => {
const place = {
place_id: 1,
licence: "",
osm_type: "way",
osm_id: 1,
lat: "51.5034",
lon: "-0.1276",
place_rank: 30,
category: "building",
type: "house",
importance: 1,
addresstype: "building",
name: null,
display_name: "10, Downing Street, London, England, United Kingdom",
address: {
house_number: "10",
road: "Downing Street",
city: "London",
state: "England",
country: "United Kingdom",
country_code: "gb",
},
boundingbox: [],
} satisfies OpenStreetMapPlace;
expect(formatOpenStreetMapPlace(place)).toEqual({
primary: "10, Downing Street, London",
secondary: "England, United Kingdom",
});
});
it("omits duplicate city names", () => {
const place = {
place_id: 2,
licence: "",
osm_type: "relation",
osm_id: 2,
lat: "51.5074",
lon: "-0.1278",
place_rank: 16,
category: "place",
type: "city",
importance: 1,
addresstype: "city",
name: "London",
display_name: "London, England, United Kingdom",
address: {
city: "London",
state: "England",
country: "United Kingdom",
country_code: "gb",
},
boundingbox: [],
} satisfies OpenStreetMapPlace;
expect(formatOpenStreetMapPlace(place)).toEqual({
primary: "London",
secondary: "England, United Kingdom",
});
});
});
+141
View File
@@ -0,0 +1,141 @@
import { describe, expect, it } from "vitest";
import type { TimerListTimer } from "../../src/data/timer_list";
import {
applyTimerListMessage,
formatTimerListRemaining,
sortTimerListTimers,
timerListTimerVisible,
} from "../../src/data/timer_list";
const timer = (
timer_id: string,
status: TimerListTimer["status"] = "active"
): TimerListTimer => ({
timer_id,
name: null,
status,
created_duration: 60,
total_duration: 60,
created_at: "2026-01-01T00:00:00+00:00",
finishes_at: null,
paused_remaining: null,
ended_at: null,
remaining: 60,
});
// The subscription sends one snapshot and then single-timer changes, so the
// list shown in the UI depends on these being merged correctly.
describe("applyTimerListMessage", () => {
const timers = [timer("a"), timer("b")];
it("replaces the list with a snapshot", () => {
expect(
applyTimerListMessage(timers, { type: "timers", timers: [timer("c")] })
).toEqual([timer("c")]);
});
it("appends a created timer", () => {
expect(
applyTimerListMessage(timers, {
type: "change",
event_type: "created",
timer: timer("c"),
})
).toEqual([timer("a"), timer("b"), timer("c")]);
});
it("updates a changed timer in place", () => {
expect(
applyTimerListMessage(timers, {
type: "change",
event_type: "paused",
timer: timer("a", "paused"),
})
).toEqual([timer("a", "paused"), timer("b")]);
});
it("drops a removed timer", () => {
expect(
applyTimerListMessage(timers, {
type: "change",
event_type: "removed",
timer: timer("a"),
})
).toEqual([timer("b")]);
});
});
// Ended timers stay in the backend list, so this decides what the UI shows.
describe("timerListTimerVisible", () => {
const now = new Date("2026-01-01T00:10:00+00:00").getTime();
const ended = (status: TimerListTimer["status"], ended_at: string) => ({
...timer("a", status),
ended_at,
});
it.each([
["active", timer("a"), true],
["paused", timer("a", "paused"), true],
[
"finished 4 minutes ago",
ended("finished", "2026-01-01T00:06:00+00:00"),
true,
],
[
"finished 5 minutes ago",
ended("finished", "2026-01-01T00:05:00+00:00"),
false,
],
[
"cancelled just now",
ended("cancelled", "2026-01-01T00:10:00+00:00"),
false,
],
])("%s", (_name, item, visible) => {
expect(timerListTimerVisible(item, now)).toBe(visible);
});
});
describe("formatTimerListRemaining", () => {
it.each([
[0, "0:00"],
[34.2, "0:35"],
[593, "9:53"],
[3725, "1:02:05"],
])("%s seconds", (seconds, text) => {
expect(formatTimerListRemaining(seconds)).toBe(text);
});
});
// The list order decides which timer people see first.
describe("sortTimerListTimers", () => {
const now = new Date("2026-01-01T00:00:00+00:00").getTime();
const running = (timer_id: string, seconds: number): TimerListTimer => ({
...timer(timer_id),
finishes_at: new Date(now + seconds * 1000).toISOString(),
});
const paused = (timer_id: string, seconds: number): TimerListTimer => ({
...timer(timer_id, "paused"),
paused_remaining: seconds,
});
it("puts finished first, then running and paused by time left", () => {
const sorted = sortTimerListTimers(
[
paused("p-long", 600),
running("r-long", 300),
timer("done", "finished"),
paused("p-short", 60),
running("r-short", 30),
],
now
);
expect(sorted.map((item) => item.timer_id)).toEqual([
"done",
"r-short",
"r-long",
"p-short",
"p-long",
]);
});
});
+114
View File
@@ -841,6 +841,120 @@ test.describe("Theming", () => {
// ---------------------------------------------------------------------------
test.describe("Config panel", () => {
test("searches for a zone with the keyboard without leaking Enter", async ({
page,
}) => {
const response = Promise.withResolvers<undefined>();
let searches = 0;
await page.route(
"https://nominatim.openstreetmap.org/search.php**",
async (route) => {
searches++;
await response.promise;
await route.fulfill({
json: [
{
place_id: 1,
name: "Paris",
display_name: "Paris, Ile-de-France, France",
category: "place",
type: "city",
lat: "48.8566",
lon: "2.3522",
address: { state: "Ile-de-France", country: "France" },
},
],
});
}
);
await goToPanel(page, "/config/zone/new");
const selector = page.locator("ha-selector-location");
await selector.evaluate((element) => {
element.addEventListener("keydown", (event) => {
if (event instanceof KeyboardEvent && event.key === "Enter") {
element.setAttribute("data-enter-bubbled", "");
}
});
});
const input = selector.getByRole("textbox", { name: "Search address" });
await input.fill("Paris");
const compositionPrevented = await input.evaluate((element) => {
const event = new KeyboardEvent("keydown", {
key: "Enter",
code: "Enter",
isComposing: true,
bubbles: true,
composed: true,
cancelable: true,
});
element.dispatchEvent(event);
return event.defaultPrevented;
});
expect(compositionPrevented).toBe(false);
await expect(selector).not.toHaveAttribute("data-enter-bubbled");
expect(searches).toBe(0);
await input.press("Enter");
await expect(input).toBeFocused();
await expect(input).toBeEnabled();
await expect(input).not.toBeEditable();
await input.press("x");
await input.press("Enter");
await expect(input).toHaveValue("Paris");
response.resolve(undefined);
const result = selector.getByRole("button", {
name: "Paris Ile-de-France, France",
exact: true,
});
const status = selector.getByRole("status");
await expect(result).toBeVisible();
await expect(input).toBeEditable();
await expect(status).toHaveText("1 result for ‘Paris’");
expect(searches).toBe(1);
await selector.locator("ha-list-item-button").focus();
await page.keyboard.press("Enter");
await expect(
selector.getByRole("spinbutton", { name: "Latitude*", exact: true })
).toHaveValue("48.8566");
await expect(
selector.getByRole("spinbutton", { name: "Longitude*", exact: true })
).toHaveValue("2.3522");
await expect(result).not.toBeAttached();
await expect(input).toBeFocused();
await expect(status).toHaveText("Selected Paris, Ile-de-France, France");
const searchFromButton = async (key: "Enter" | "Space") => {
await selector
.getByRole("button", { name: "Search", exact: true })
.press(key);
await expect(result).toBeVisible();
await expect(input).toBeFocused();
await selector.locator("ha-list-item-button").focus();
await page.keyboard.press(key);
await expect(result).not.toBeAttached();
await expect(input).toBeFocused();
};
await searchFromButton("Enter");
await searchFromButton("Space");
expect(searches).toBe(3);
await page
.context()
.route("https://www.openstreetmap.org/", (route) =>
route.fulfill({ body: "" })
);
const popupPromise = page.waitForEvent("popup");
await selector
.getByRole("link", { name: "OpenStreetMap", exact: true })
.press("Enter");
const popup = await popupPromise;
await popup.close();
await expect(selector).not.toHaveAttribute("data-enter-bubbled");
});
test("config panel loads without JS errors", async ({ page }) => {
const errors = trackPageErrors(page);
+2
View File
@@ -79,6 +79,7 @@ export const moreInfoPages: GalleryPageSmokeCase[] = [
{ name: "number", selector: "demo-more-info-number" },
{ name: "scene", selector: "demo-more-info-scene" },
{ name: "timer", selector: "demo-more-info-timer" },
{ name: "timer-list", selector: "demo-more-info-timer-list" },
{ name: "update", selector: "demo-more-info-update" },
{ name: "vacuum", selector: "demo-more-info-vacuum" },
{ name: "water-heater", selector: "demo-more-info-water-heater" },
@@ -117,5 +118,6 @@ export const lovelacePages: GalleryPageSmokeCase[] = [
},
{ name: "thermostat-card", selector: "demo-lovelace-thermostat-card" },
{ name: "tile-card", selector: "demo-lovelace-tile-card" },
{ name: "timer-list-card", selector: "demo-lovelace-timer-list-card" },
{ name: "todo-list-card", selector: "demo-lovelace-todo-list-card" },
];
@@ -144,6 +144,26 @@ describe("notification-manager", () => {
expect(primary).toHaveBeenCalledOnce();
});
it("keeps the toast open after a keepOpen icon action", async () => {
const manager = await mountManager();
const action = vi.fn();
await manager.showDialog({
message: "Starting",
action: { action, icon: "M0 0", keepOpen: true, text: "Details" },
duration: -1,
});
const toast = manager.shadowRoot!.querySelector("ha-toast")!;
const button = manager.shadowRoot!.querySelector(
"ha-icon-button[slot='action']"
) as HTMLElement;
button.click();
expect(action).toHaveBeenCalledOnce();
expect(toast.hide).not.toHaveBeenCalled();
});
it("invokes the action belonging to the selected stacked toast", async () => {
const manager = await mountManager();
const firstAction = vi.fn();
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import {
inCategory,
ofConnection,
} from "../../../../src/panels/config/integrations/add-integration-list";
describe("inCategory", () => {
it("matches a category, its subcategories, and only those", () => {
const categories = ["energy.ev_charging", "climate"];
expect(inCategory(categories)).toBe(true);
expect(inCategory(categories, "energy")).toBe(true);
expect(inCategory(categories, "energy", "ev_charging")).toBe(true);
expect(inCategory(categories, "energy", "solar")).toBe(false);
expect(inCategory(categories, "climate")).toBe(true);
expect(inCategory(categories, "climate", "thermostats")).toBe(false);
expect(inCategory(["energy_storage"], "energy")).toBe(false);
expect(inCategory(undefined, "energy")).toBe(false);
});
});
describe("ofConnection", () => {
it("keeps everything without a connection, else local or cloud", () => {
const local = { id: "a", domain: "a", name: "A" };
const cloud = { ...local, cloud: true };
expect(ofConnection(local)).toBe(true);
expect(ofConnection(cloud)).toBe(true);
expect(ofConnection(local, "local")).toBe(true);
expect(ofConnection(cloud, "local")).toBe(false);
expect(ofConnection(local, "cloud")).toBe(false);
expect(ofConnection(cloud, "cloud")).toBe(true);
});
});
@@ -91,6 +91,68 @@ describe("filterRepositories", () => {
).toEqual(expected);
});
it.each([
// A category takes in its subcategories, a subcategory only itself
[{ integration_category: ["energy"] }, ["Prices", "Solar"]],
[{ integration_category: ["energy.solar_batteries"] }, ["Solar"]],
[
{ integration_category: ["energy", "lighting"] },
["Lamps", "Prices", "Solar"],
],
[{ integration_category: ["water"] }, []],
[{ integration_category: [] }, ["Lamps", "Plain", "Prices", "Solar"]],
])(
"keeps the integration category that matches %j",
(activeFilters, expected) => {
expect(
names(
filterRepositories(
[
repository("Plain"),
repository("Lamps", { integration_categories: ["lighting"] }),
repository("Prices", {
integration_categories: ["energy.energy_prices"],
}),
repository("Solar", {
integration_categories: [
"energy.solar_batteries",
"weather_alerts",
],
}),
],
localize,
activeFilters
)
)
).toEqual(expected);
}
);
it("adds the names of the integration categories, without unknown ones", () => {
const categoryNames = {
"component.homeassistant.integration_category.energy.subcategory.solar_batteries.name":
"Solar & batteries",
"component.homeassistant.integration_category.weather_alerts.name":
"Weather & alerts",
};
const [row] = filterRepositories(
[
repository("Solar", {
integration_categories: [
"energy.solar_batteries",
"weather_alerts",
"unknown",
],
}),
],
((key: string) => categoryNames[key] ?? "") as unknown as LocalizeFunc
);
expect(row.translated_integration_categories).toBe(
"Solar & batteries, Weather & alerts"
);
});
it("puts installed first, then new, then the most starred, then by name", () => {
const sorted = filterRepositories(
[
@@ -174,7 +236,12 @@ describe("browseUrl", () => {
browseUrl({
search: "mushroom card",
sorting: { column: "stars", direction: "desc" },
filters: { status: ["new"], type: ["theme"], source: ["custom"] },
filters: {
status: ["new"],
type: ["theme"],
source: ["custom"],
integration_category: ["energy.solar_batteries"],
},
}),
"http://localhost"
);
@@ -184,7 +251,12 @@ describe("browseUrl", () => {
expect(url.searchParams.get("direction")).toBe("desc");
expect(browseLinkFromUrl(url.search)).toEqual({
search: "mushroom card",
filters: { status: ["new"], type: ["theme"], source: ["custom"] },
filters: {
status: ["new"],
type: ["theme"],
source: ["custom"],
integration_category: ["energy.solar_batteries"],
},
});
});
@@ -203,6 +275,22 @@ describe("browseLinkFromUrl", () => {
});
});
it("reads a link that only filters on an integration category", () => {
expect(
browseLinkFromUrl("?integration_category=energy.solar_batteries")
).toEqual({
search: "",
filters: { integration_category: ["energy.solar_batteries"] },
});
});
it("filters on no integration category for an empty one", () => {
expect(
browseLinkFromUrl("?integration_category=")?.filters
.integration_category ?? []
).toEqual([]);
});
it("keeps what was picked for a link that says nothing about browsing", () => {
expect(
browseLinkFromUrl("?owner=hacs&repository=integration")
@@ -211,6 +299,13 @@ describe("browseLinkFromUrl", () => {
});
describe("filtersOfTab", () => {
it("keeps the integration category on every tab", () => {
expect(
filtersOfTab({ integration_category: ["energy"] }, "installed")
.integration_category
).toEqual(["energy"]);
});
it("only offers statuses something installed can have on the installed tab", () => {
expect(statusesOfTab("installed")).toEqual([
"pending-restart",