Compare commits

...
Author SHA1 Message Date
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
Martin Salinas c4c84361cb Send slider keyboard changes when focus leaves before the key is released (#56132) 2026-11-25 14:57:07 +01:00
G JohanssonandClaude Opus 5.5 aedc5f1e7e Show the debug logging option on the page of an integration that is not set up (#56124)
* Add debug logging to the integration setup dialog

Users can enable debug logging from a menu in the config flow dialog.
This also works for integrations that are not set up yet, so the log
covers the initial setup without YAML or an action call.

A banner shows while debug logging is on. Disabling it offers the log
for download. On the success step, one button disables debug logging
and downloads the log.

The integration page now shows the debug logging menu item when the
integration is not listed by logger/log_info yet. The enable, disable
and download logic moves to a shared helper.

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

* Keep the debug logging button label on one line

The alert action area is only as wide as its content allows, so the
"Disable and download log" label wrapped one word per line.

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

* Mock the log info subscription in the config flow dialog tests

The dialog subscribes to log info for config flows. The fake connection
in the tests does not support collection subscriptions, so opening the
dialog failed.

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

* Keep the integration page debug logging state in sync with core

Core leaves out an integration that is not loaded once its custom log
level is removed. The page kept the old debug level, so disabling debug
logging did not offer the log for download.

Wait for the first log info before showing the debug logging menu item,
so it does not offer to enable debug logging when it is already on.

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

* Keep debug logging controls visible while a setup step loads

The dialog keeps the current step while the next step loads, so the
debug logging menu and banner can stay. Before, they disappeared during
a slow setup request.

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

* Limit debug logging changes to the integration page

Remove the debug logging menu and banners from the setup dialog, as
requested in review, to keep setup flows minimal. Debug logging for an
integration that is not set up yet starts from its integration page.

The shared helper is no longer needed, so its code moves back into the
integration page.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 13:10:04 +00:00
Maarten Lakerveld d1952af771 Pick the automation sidebar from the row that opened it (#55986)
* Pick the automation sidebar from the row that opened it

The sidebar guessed its type from the shape of the row's config. Rows
accept any YAML, so a condition row holding a service action such as
{ action: "number.set_value" } opened the action sidebar, which then
threw on the string action and rendered nothing.

Each row now tags its sidebar config with a type, and the sidebar uses
that. Such a condition row opens the condition sidebar with its YAML,
where it can be fixed.

* Read the sidebar type when showing trigger indices

The check worked out the row from the shape of its config, like the
sidebar did. Now it switches on the type the row sets, so a trigger
condition entered as YAML in a trigger row no longer shows the indices.

* Guard sidebar header lookups against non-string types

Rows now pick the sidebar, so YAML like `condition: false` or
`trigger: false` reaches the header lookups, which call .includes on
the value and threw during render. Only look up the domain and name
for string types so the YAML editor stays reachable.
2026-11-25 12:52:12 +00:00
WendelinandClaude Opus 5.5 3471667bd5 Translate automation validation errors and show them at more fields (#56111)
* Translate validation errors and show them at more fields

Core sends a translation key with the generic validation errors, like
`required` or `value_one_of`, so the frontend translates those and keeps
core's message for the rest. The remaining ha-form editors and the delay
action show their errors at the field instead of in the sidebar alert.

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

* Show only the repeat options' own errors in the repeat form

Errors of nested rows in while, until and sequence stay on those rows.

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

* Name fields without the colon of their label in errors

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 11:15:00 +00:00
WendelinandClaude Opus 5.5 22c6f16ecb Show automation validation errors on the rows they belong to (#55830)
* Show automation validation errors on the rows they belong to

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

* Follow error rows through moves and saves

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

* Keep errors on duplicate rows and rows changed while saving

Identical rows keep their own errors after the YAML is parsed again, and
a save whose config changed meanwhile checks the current config in full,
so rows renamed and moved during the save stay marked.

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

* Adapt error rows to core's structured validation errors

Core now reports paths as written in the config, so the mapping of
flattened trigger lists and the parallel shorthand is gone. Only blocks
written as a single item still need the list index the editor shows.

Match the error type to core's contract, show the save failed toast
before revalidating so a later successful save closes it, and render
error alerts with one shared template.

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

* Move errors with their rows and fix review findings

Follow the shown errors through moves and deletes right away instead of
waiting for revalidation, resolve the first row of a single item block
when tracking error items, close the save failed toast also when no
errors are left, and don't expand trigger rows that open in the sidebar.

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

* Track single item blocks through moves and fix review findings

Blocks written as a single item, like `default: { delay: … }`, are now
indexed at the row path the editor uses, so their errors move with them.
Pending validations no longer apply after the editor is left, and the
problem count uses a plural form.

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

* Track template conditions written as a string and keep errors of missing sections

A template condition written as a string is a row, so its errors stay on it
and follow it when the visual editor turns it into an object. Sections that
are missing aren't validated by core, so their errors stay while editing.

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

* Keep errors on rows edited to match another and of nested service data

Only lists of rows hold rows, so objects in service data belong to their
action. A row edited to the content of another row that is still there keeps
its errors. Errors of the first check of an unavailable automation follow the
config when the editor changed it meanwhile.

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

* Track template conditions written as a single string

A condition block like `if: "{{ … }}"` is its first row, so its errors stay
on it when the visual editor turns it into a list.

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

* Revalidate when rows shift instead of following errors

Replace the follow and known item tracking with a simpler rule: errors
keep their paths while typing, and when rows move, are inserted or
deleted, they are hidden and checked again right away. Revalidation now
shows everything core returns, except new errors on the row open in the
sidebar.

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

* Show errors of hidden rows on their collapsed block

Collapsed rows keep the rows inside rendered but hidden, so a collapsed
row on an error's path now owns it. Field errors use a map without a
prototype, so data keys like `constructor` keep their errors.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 11:08:48 +01:00
WendelinandClaude Opus 5.5 f1e0084648 Make the camera more info as wide as its picture fits (#56109)
* Make the camera more info as wide as its picture fits

The more info of a camera was always 1024px wide, which left an ultra
wide camera with little height while there was room for more. In the info
view, the dialog now takes the width the picture needs to be as high as
there is room for, between 580px and 1920px, and changes it with a
transition. Dialogs get a --ha-dialog-width-transition for that.

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

* Size a camera's more info by its picture also from a related view

A camera opened from a smaller entity's related view kept that entity's
medium dialog width, which doesn't use the picture's width.

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

* Keep the camera's size when its more info opens again

Opening the more info of the camera that is already open reset the size
the player sent, and the player doesn't send it again. The height of the
picture now uses svh like the height limit of the dialog, because dvh can
be larger while the browser's toolbars are hidden.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 10:48:34 +01:00
Javier Torres 4db2b58687 Allow requiring client certificates in Link remote connection (#56093)
* Add client certificate toggle to cloud remote access

Add a Require client certificates switch to the remote access security
options. It is disabled unless the HTTP integration has an SSL peer
certificate configured.

* Confirm the remote access restart when toggling client certificates

* Handle ssl client context error

* Allow turning off client certificates when they can't be enforced

* Change approach: move config toggle to network page

* New changes in http integration
2026-11-25 10:45:19 +01:00
Petar Petrov ca3da4d3ca Keep short timeline state changes from merging into neighbours of the same state (#56131) 2026-11-25 09:42:43 +01:00
Petar Petrov 4485fc4ab3 Draw the power sources graph zero line above all series (#56000)
* Stop drawing idle power sources on the power graph axis

* Draw the power graph zero line above all series instead of hiding zeros

* Leave silent decoration series out of chart sonification
2026-11-25 09:39:57 +01:00
Maarten Lakerveld 688b310549 Read localize from the filters' i18n context (#56118)
The filter components consumed internationalizationContext twice: once
through consumeLocalize for _localize and once in full for _i18n. Use
_i18n.localize instead and drop the second subscription. HaFilterStates
now provides _i18n, so ha-filter-device-classes reuses it instead of
consuming the context again next to the inherited _localize.
2026-11-25 09:33:40 +01:00
Martin Salinas 976352c5c6 Fix light card errors when dragging the slider of an unknown light (#56129) 2026-11-25 09:22:14 +01:00
Martin Salinas baec09d83a Reset the circular slider when a touch is cancelled after a press (#56127)
* Reset the circular slider when a touch is cancelled after a press

* Put the circular slider's handle back when a touch is cancelled
2026-11-25 08:08:03 +00:00
Erwin Douna 8b6de6c38a Move database calculate into card (#56082)
* Move database calculate into card

* Drop duplicate spinner on database calculate button
2026-11-25 09:52:16 +02:00
Aidan TimsonandCopilot Autofix powered by AI 0b8ec5ee62 Make one slanted wave the default skeleton effect (#56089)
* Make one shared soft wave the default skeleton effect

* Run the skeleton wave across the content in one continuous loop

* Slant the skeleton wave from the top corner of the content

* Move loading guidance into a loading skill

* Place skeleton waves by the same direction they're drawn in

* Add optional chaining for getAnimations method

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

* Measure the skeleton indicator and keep detached skeletons out of the wave

* Align text skeletons to the top of their line

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-25 08:49:22 +01:00
renovate[bot] ba40d539cf Update dependency lint-staged to v17.6.2 (#56128)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-25 07:39:31 +00:00
Paul Bottein 1fc36ed56b Use the open tilt position and slat angles of covers (#56090)
* Use the open tilt position and slat angles of covers

* Read the closed tilt positions of covers
2026-11-25 09:30:16 +02:00
Aidan Timson 369adba1e5 Flatten the Status filter on the entities page (#56114) 2026-11-25 08:50:07 +02:00
Martin Salinas 2aa6217cc0 Only fire circular slider changing events when the stepped value changes (#56122)
* Only fire circular slider changing events when the stepped value changes

During a pan, value-changing was fired on every move even when the stepped
value hadn't changed, so consumers like the climate temperature control
re-rendered for nothing.

* Keep the light card's brightness visible until the drag ends

The readout hid 500 ms after the last value-changing event, so with
repeated values no longer fired it disappeared while still dragging
against the end of the slider. It now hides once the drag ends, and the
slider also signals the end when a pan is cancelled.

* Resend the slider value after a mid-drag update and clear the light card's hide timer before rescheduling it

* Only hide the light card's brightness once the drag ends

* Hide the light card's brightness when the slider loses focus
2026-11-25 06:47:54 +00:00
Franck Nijhof a212a3343b Add bulk delete to the automations and scripts lists (#56121) 2026-11-25 08:46:35 +02:00
Franck Nijhof fa4f3ce1b6 Add a serial number column to the devices table (#56123) 2026-11-25 08:42:19 +02:00
karwosts 3d18e7b9a2 Fix area card memoization perf (#56120) 2026-11-25 07:41:03 +02:00
WendelinandClaude Opus 5.5 1d76a22ba5 Keep the sidebar from shifting after closing notifications (#56116)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 07:39:50 +02:00
WendelinandClaude Opus 5.5 e6d0a00c55 Keep the camera picture in view when zooming and loading (#56108)
* Keep the camera picture in view when zooming and while it loads

Zoom and pan now stop at the edges of the picture instead of the viewport,
so a camera with another aspect ratio than the player no longer shows its
black bars when zoomed in. The minimap shows the part of the picture in
view.

While the stream connects, the player keeps the room of the snapshot's
aspect ratio, or 16:9 until the snapshot loads, instead of the height of
an empty video. It changes to the stream's aspect ratio with a transition.

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

* Open the camera player at the size of its last picture

The aspect ratio of each camera's picture is kept in the local storage,
so the player opens at the right size before the snapshot or the stream
loads. It is only written when the picture has another aspect ratio than
last time.

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

* Keep dashboards' camera posters as before and follow resizes in the app

Only the camera player loads the poster first to tell its size, so
camera cards don't load an MJPEG camera's snapshot they don't show. An
error message taller than the player's picture scrolls instead of being
cut off. The app's own HLS player follows the video when it changes size
without the window, like while the player changes its aspect ratio.

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

* Center the camera picture when the player's height limits it

With a limited height, the aspect ratio also limits the width of the
picture, which then showed on the left of a wider player.

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

* Zoom the camera picture into the bars next to it

When the player's height limits the picture, it keeps the player's whole
width with the picture in the middle, instead of being only as wide as
the picture. Zooming in fills the bars next to it, and zooming and
panning work there too.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-24 16:17:54 +01:00
135 changed files with 6491 additions and 1273 deletions

No files matched your search

+2 -28
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-components
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, loading states, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
---
# HA Frontend Components
@@ -93,33 +93,7 @@ html`
## Loading States
Pick the indicator by what is loading, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/):
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
- Don't fade in the loaded content itself.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
```ts
html`
<ha-fade-in .duration=${300} easing="ease-in">
<div
role="progressbar"
aria-label=${this._i18n.localize("ui.common.loading")}
>
<ha-skeleton-text></ha-skeleton-text>
</div>
</ha-fade-in>
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
`;
```
Load `ha-frontend-loading` for anything that shows while content loads: skeletons, spinners, loading buttons and fades.
## Shortcuts And Tooltips
@@ -0,0 +1,75 @@
---
name: ha-frontend-loading
description: Home Assistant frontend loading states. Use when adding, changing or reviewing anything that shows while content loads, such as a skeleton, spinner, loading button or loading fade, or when checking how a screen looks while it loads.
---
# HA Frontend Loading
Use this skill for every loading state, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/). A loading state always ends in the content, an empty state, or an error.
## Pick The Indicator
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`, `ha-skeleton-log`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
## The Wave
Every skeleton uses the same soft wave (`ha-skeleton`'s default `effect="sheen"`). It's one slanted wave across all the skeletons on the page, from the top corner of the content on the side text starts from to the opposite bottom corner, which each skeleton shows its slice of, on one shared clock. It flows from one skeleton into the next, starts its next sweep as soon as it leaves the content, and a skeleton added mid-sweep joins in rather than starting over. Reduced motion stops it.
Don't change the effect or speed (`--ha-skeleton-duration`) for one component.
## Showing A Skeleton
Make the skeleton the same shape and size as the content it stands for: one text skeleton per line of text, an icon skeleton per icon, a block per image or chart.
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
- Don't fade in the loaded content itself.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text.
```ts
html`
<ha-fade-in .duration=${300} easing="ease-in">
<div
role="progressbar"
aria-label=${this._i18n.localize("ui.common.loading")}
>
<ha-skeleton-text></ha-skeleton-text>
</div>
</ha-fade-in>
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
`;
```
## Checking It
Check a loading state in the browser, not only by reading the code. These work on any setup: a dev server, the demo, or the gallery.
- **Hold the loading state.** Home Assistant's data comes over the WebSocket, which DevTools network throttling doesn't slow. Hold the replies back from the console instead, then open the screen from inside the app (not a reload, which drops the patch). Adjust the pattern to the messages the screen waits on:
```js
const conn = document.querySelector("home-assistant").hass.connection;
const slow = (type = "") => /^(recorder|history|logbook)\//.test(type);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const send = conn.sendMessagePromise.bind(conn);
conn.sendMessagePromise = async (msg) => {
const result = await send(msg);
if (slow(msg.type)) await wait(3000);
return result;
};
const subscribe = conn.subscribeMessage.bind(conn);
conn.subscribeMessage = (callback, msg, options) => {
if (!slow(msg.type)) return subscribe(callback, msg, options);
const due = Date.now() + 3000;
const later = (message) =>
setTimeout(() => callback(message), Math.max(0, due - Date.now()));
return subscribe(later, msg, options);
};
```
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
+2 -1
View File
@@ -40,7 +40,8 @@ Never run `tsc` or `pnpm lint:types` with file arguments. When `tsc` receives fi
Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching skill before detailed implementation or review. For reviews, load `ha-frontend-review` alongside all companions that apply to the changed code or behavior:
- `ha-frontend-contexts`: Lit contexts, `hass` migration, and rerender-sensitive state access.
- `ha-frontend-components`: dialogs, forms, alerts, loading states, shortcuts, tooltips, panels, and Lovelace cards.
- `ha-frontend-components`: dialogs, forms, alerts, shortcuts, tooltips, panels, and Lovelace cards.
- `ha-frontend-loading`: loading states, skeletons, spinners, loading fades, and checking how a screen looks while it loads.
- `ha-frontend-events`: event handler typing, custom event dispatch, and event-map declarations.
- `ha-frontend-types`: backend data contracts, optional schemas, shared types, assertions, and lifecycle types.
- `ha-frontend-lit`: reactive fields, DOM queries, lifecycle behavior, and render-derived state.
+3 -3
View File
@@ -3,8 +3,8 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockConfig = (hass: MockHomeAssistant) => {
hass.mockWS<typeof validateConfig>("validate_config", () => ({
actions: { valid: true, error: null },
conditions: { valid: true, error: null },
triggers: { valid: true, error: null },
actions: { valid: true, error: null, errors: [] },
conditions: { valid: true, error: null, errors: [] },
triggers: { valid: true, error: null, errors: [] },
}));
};
+1 -1
View File
@@ -199,7 +199,7 @@
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
"lint-staged": "17.6.1",
"lint-staged": "17.6.2",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.18.1",
+5 -5
View File
@@ -661,8 +661,8 @@ importers:
specifier: 1.33.0
version: 1.33.0
lint-staged:
specifier: 17.6.1
version: 17.6.1
specifier: 17.6.2
version: 17.6.2
lit-analyzer:
specifier: 2.0.3
version: 2.0.3
@@ -6071,8 +6071,8 @@ packages:
resolution: {integrity: sha512-wM1+Z03eypVAVUCE7QdSqpVIvelbOakn1M0bPDoA4SGWPx3sNDVUiMo3L6To6WWGClB7VyXnhQ4Sn7gxiJbE6A==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
[email protected].1:
resolution: {integrity: sha512-3MXgVN7BERDR/6CXZs2fDHGc+r0+hlvGAa9wqMlVbIS6RVRuaPOnb5SnN6wMXulwfEy9DXVkMVUN/8cUlpPDnw==}
[email protected].2:
resolution: {integrity: sha512-c/JaXaXmleubmKUwwp4OAcq55RV9Z3HTUNdqdqPh2srtmP9Of3bcR6o00GoWDUye+9JhMuoYkhYqAVPIOZKcsw==}
engines: {node: '>=22.22.1'}
hasBin: true
@@ -13998,7 +13998,7 @@ snapshots:
[email protected]: {}
[email protected].1:
[email protected].2:
dependencies:
picomatch: 4.0.7
string-argv: 0.4.0
+8
View File
@@ -0,0 +1,8 @@
/** Loads an image, resolves with undefined when it can't be loaded. */
export const loadImage = (url: string): Promise<HTMLImageElement | undefined> =>
new Promise((resolve) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () => resolve(undefined);
image.src = url;
});
+16
View File
@@ -5,3 +5,19 @@ export const stringifyPath = (path: ConfigPath): string => path.join("/");
export const pathEquals = (a: ConfigPath, b: ConfigPath): boolean =>
a.length === b.length && a.every((segment, index) => segment === b[index]);
export const pathStartsWith = (path: ConfigPath, prefix: ConfigPath): boolean =>
prefix.length <= path.length &&
prefix.every((segment, index) => segment === path[index]);
/** Formats a path the way it reads in YAML, e.g. `actions[1].then[0].delay`. */
export const formatPath = (path: ConfigPath): string =>
path
.map((segment, index) =>
typeof segment === "number"
? `[${segment}]`
: index === 0
? segment
: `.${segment}`
)
.join("");
@@ -39,6 +39,9 @@ export class HaAutomationRow extends LitElement {
/** Makes the row a link, with the icons slot outside of it */
@property() public href?: string;
@property({ type: Boolean, reflect: true })
public error = false;
@query(".row")
private _rowElement?: HTMLDivElement;
@@ -285,6 +288,15 @@ export class HaAutomationRow extends LitElement {
:host([highlight]) .row:hover {
background-color: rgba(var(--rgb-primary-color), 0.16);
}
:host([error]) .row {
background-color: var(--ha-color-fill-danger-quiet-resting);
}
:host([error][selected]) .row,
:host([error][selected]) .row:focus {
outline: 2px solid var(--ha-color-border-danger-loud);
outline-offset: -2px;
background-color: var(--ha-color-fill-danger-normal-resting);
}
.icons,
.leading-icon-wrapper,
+133 -40
View File
@@ -14,8 +14,9 @@ import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { storage } from "../../common/decorators/storage";
import { deepActiveElement } from "../../common/dom/deep-active-element";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
@@ -29,13 +30,16 @@ import "../ha-spinner";
import "../ha-svg-icon";
import "./ha-camera-stream-badge";
import {
clampZoomPan,
fitPicture,
isZoomed,
panBy,
refitZoomPan,
visiblePart,
ZOOM_PAN_IDENTITY,
zoomAtPoint,
type ZoomPan,
type ZoomPanSize,
type ZoomPanViewport,
} from "./zoom-pan";
const CONTROLS_TIMEOUT = 3000;
@@ -53,6 +57,9 @@ const WHEEL_ZOOM_SPEED = 0.0025;
// The longer side of the minimap of a zoomed in picture, in pixels
const MINIMAP_SIZE = 64;
// Most cameras, for the room the player keeps until it knows the picture
const DEFAULT_ASPECT_RATIO = 16 / 9;
interface PointerInfo {
x: number;
y: number;
@@ -105,6 +112,15 @@ export class HaCameraPlayer extends LitElement {
@state() private _zoom: ZoomPan = ZOOM_PAN_IDENTITY;
@state() private _pictureSize?: ZoomPanSize;
// Known before the stream's picture, so the player can make room for it
@state() private _posterSize?: ZoomPanSize;
// Of each camera's picture last time, so the player opens at its size
@storage({ key: "cameraAspectRatios", state: true, subscribe: false })
private _storedAspectRatios?: Record<string, number>;
@state() private _gesture = false;
@state() private _fullscreen = false;
@@ -125,18 +141,20 @@ export class HaCameraPlayer extends LitElement {
@query(".overlay") private _overlay?: HTMLElement;
private _firedAspectRatio?: number;
private _pointers = new Map<number, PointerInfo>();
// More than one finger touched since all were lifted, so it is no tap
private _multiPointer = false;
// The size of the viewport the zoom was last made for
private _zoomSize: ZoomPanSize = { width: 0, height: 0 };
// The viewport and picture the zoom was last made for
private _zoomViewport: ZoomPanViewport = fitPicture({ width: 0, height: 0 });
private _viewportResize = new ResizeController(this, {
target: null,
skipInitial: true,
callback: () => this._viewportResized(),
callback: () => this._refitZoom(),
});
private _controlsTimeout?: number;
@@ -201,6 +219,8 @@ export class HaCameraPlayer extends LitElement {
const oldStateObj = changedProps.get("stateObj");
if (oldStateObj && oldStateObj.entity_id !== this.stateObj?.entity_id) {
this._zoom = ZOOM_PAN_IDENTITY;
this._pictureSize = undefined;
this._posterSize = undefined;
}
}
@@ -212,6 +232,11 @@ export class HaCameraPlayer extends LitElement {
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
const aspectRatio = this._aspectRatio();
if (aspectRatio !== this._firedAspectRatio) {
this._firedAspectRatio = aspectRatio;
fireEvent(this, "camera-aspect-ratio-changed", { aspectRatio });
}
if (changedProps.has("keepAwake")) {
if (this.keepAwake) {
this._requestWakeLock();
@@ -258,6 +283,11 @@ export class HaCameraPlayer extends LitElement {
"camera-player-zoomed": zoomed,
gesture: this._gesture,
})}
style=${styleMap({
aspectRatio: this._fullscreen
? undefined
: String(this._aspectRatio()),
})}
@pointerdown=${this._pointerDown}
@pointerup=${this._pointerUp}
@pointercancel=${this._pointerCancel}
@@ -271,6 +301,7 @@ export class HaCameraPlayer extends LitElement {
.allowExoPlayer=${this.allowExoPlayer}
.muted=${this._muted}
mjpeg-video
measure-poster
style=${styleMap({
transform: zoomed
? `translate(${this._zoom.x}px, ${this._zoom.y}px) scale(${this._zoom.scale})`
@@ -279,6 +310,7 @@ export class HaCameraPlayer extends LitElement {
@camera-stream-status-changed=${this._statusChanged}
@load=${this._updateVideo}
@camera-capabilities-changed=${this._capabilitiesChanged}
@camera-poster-size-changed=${this._posterSizeChanged}
></ha-camera-stream>
</div>
${inApp ? nothing : this._renderControls(status, zoomed, badgeVisible)}
@@ -400,12 +432,12 @@ export class HaCameraPlayer extends LitElement {
* which isn't mirrored in right to left languages.
*/
private _renderMinimap() {
const { scale, x, y } = this._zoom;
const { width, height } = this._zoomSize;
const { width, height } = this._zoomViewport.picture;
if (!width || !height) {
return nothing;
}
const longSide = Math.max(width, height);
const area = visiblePart(this._zoom, this._zoomViewport);
return html`<div
class=${classMap({ minimap: true, gesture: this._gesture })}
style=${styleMap({
@@ -417,10 +449,10 @@ export class HaCameraPlayer extends LitElement {
<div
class="area"
style=${styleMap({
left: `${(-x / (width * scale)) * 100}%`,
top: `${(-y / (height * scale)) * 100}%`,
width: `${100 / scale}%`,
height: `${100 / scale}%`,
left: `${area.x * 100}%`,
top: `${area.y * 100}%`,
width: `${area.width * 100}%`,
height: `${area.height * 100}%`,
})}
></div>
</div>`;
@@ -523,6 +555,30 @@ export class HaCameraPlayer extends LitElement {
this._capabilities = ev.detail.capabilities;
}
/**
* Of the stream's picture, until then of the camera's picture last time,
* its poster or most cameras'.
*/
private _aspectRatio(): number {
if (this._pictureSize) {
return this._pictureSize.width / this._pictureSize.height;
}
const stored =
this.stateObj && this._storedAspectRatios?.[this.stateObj.entity_id];
if (stored) {
return stored;
}
return this._posterSize
? this._posterSize.width / this._posterSize.height
: DEFAULT_ASPECT_RATIO;
}
private _posterSizeChanged(
ev: HASSDomEvent<HASSDomEvents["camera-poster-size-changed"]>
) {
this._posterSize = ev.detail.size;
}
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
status: this._status,
@@ -538,6 +594,7 @@ export class HaCameraPlayer extends LitElement {
return;
}
this._video = this._stream?.videoElement;
this._updatePictureSize();
// Binds the video first, which resets its paused state
await this.updateComplete;
if (!this._status.connecting) {
@@ -577,6 +634,7 @@ export class HaCameraPlayer extends LitElement {
for (const type of ["play", "pause", "emptied"]) {
video.addEventListener(type, this._updatePaused);
}
video.addEventListener("resize", this._updatePictureSize);
// Only a pause from outside shows the play button, not the moment before
// a new video starts playing
this._paused = false;
@@ -595,6 +653,7 @@ export class HaCameraPlayer extends LitElement {
for (const type of ["play", "pause", "emptied"]) {
video?.removeEventListener(type, this._updatePaused);
}
video?.removeEventListener("resize", this._updatePictureSize);
video?.removeEventListener(
"enterpictureinpicture",
this._pictureInPictureChanged
@@ -703,35 +762,56 @@ export class HaCameraPlayer extends LitElement {
}
}
private _viewportSize() {
private _updatePictureSize = () => {
const size = this._stream?.pictureSize;
if (
size &&
(size.width !== this._pictureSize?.width ||
size.height !== this._pictureSize.height)
) {
this._pictureSize = size;
this._storeAspectRatio(size.width / size.height);
}
// The new picture can have another size
this._refitZoom();
};
private _storeAspectRatio(aspectRatio: number) {
const entityId = this.stateObj?.entity_id;
if (!entityId || this._storedAspectRatios?.[entityId] === aspectRatio) {
return;
}
this._storedAspectRatios = {
...this._storedAspectRatios,
[entityId]: aspectRatio,
};
}
private _measureViewport() {
const rect = this._viewport!.getBoundingClientRect();
// Kept for the minimap, every zoom and pan measures it first
this._zoomSize = { width: rect.width, height: rect.height };
return { rect, size: this._zoomSize };
this._zoomViewport = fitPicture(
{ width: rect.width, height: rect.height },
this._stream?.pictureSize ?? this._pictureSize ?? this._posterSize
);
return { rect, viewport: this._zoomViewport };
}
/**
* Keeps the same part of the picture in view when the size changes, like
* when turning a phone.
* Keeps the same part of the picture in view when the viewport or the
* picture changes size.
*/
private _viewportResized() {
const oldSize = this._zoomSize;
if (!isZoomed(this._zoom) || !this._viewport || !oldSize.width) {
private _refitZoom = () => {
const oldViewport = this._zoomViewport;
if (!isZoomed(this._zoom) || !this._viewport || !oldViewport.width) {
return;
}
const { size } = this._viewportSize();
if (!size.width || !size.height) {
const { viewport } = this._measureViewport();
if (!viewport.width || !viewport.height) {
return;
}
this._zoom = clampZoomPan(
{
scale: this._zoom.scale,
x: (this._zoom.x * size.width) / oldSize.width,
y: (this._zoom.y * size.height) / oldSize.height,
},
size
);
}
this._zoom = refitZoomPan(this._zoom, oldViewport, viewport);
};
private _resetZoom() {
this._zoom = ZOOM_PAN_IDENTITY;
@@ -749,7 +829,7 @@ export class HaCameraPlayer extends LitElement {
// Also keeps the browser from zooming the whole page
ev.preventDefault();
this._hideWheelHint();
const { rect, size } = this._viewportSize();
const { rect, viewport } = this._measureViewport();
// Lines instead of pixels, like in Firefox with a mouse wheel
const delta =
ev.deltaMode === WheelEvent.DOM_DELTA_LINE ? ev.deltaY * 33 : ev.deltaY;
@@ -758,7 +838,7 @@ export class HaCameraPlayer extends LitElement {
this._zoom,
this._zoom.scale * Math.exp(-clampedDelta * WHEEL_ZOOM_SPEED),
{ x: ev.clientX - rect.left, y: ev.clientY - rect.top },
size
viewport
);
}
@@ -789,12 +869,12 @@ export class HaCameraPlayer extends LitElement {
this._resetZoom();
return;
}
const { rect, size } = this._viewportSize();
const { rect, viewport } = this._measureViewport();
this._zoom = zoomAtPoint(
this._zoom,
2,
{ x: ev.clientX - rect.left, y: ev.clientY - rect.top },
size
viewport
);
}
@@ -828,7 +908,7 @@ export class HaCameraPlayer extends LitElement {
if (!pointer || !this._viewport) {
return;
}
const { rect, size } = this._viewportSize();
const { rect, viewport } = this._measureViewport();
if (this._pointers.size === 2) {
const [a, b] = [...this._pointers.values()];
@@ -846,13 +926,13 @@ export class HaCameraPlayer extends LitElement {
this._zoom,
(this._zoom.scale * newDistance) / oldDistance,
{ x: oldCenter.x - rect.left, y: oldCenter.y - rect.top },
size
viewport
);
this._zoom = panBy(
zoomed,
newCenter.x - oldCenter.x,
newCenter.y - oldCenter.y,
size
viewport
);
return;
}
@@ -862,7 +942,7 @@ export class HaCameraPlayer extends LitElement {
pointer.x = ev.clientX;
pointer.y = ev.clientY;
if (this._pointers.size === 1 && isZoomed(this._zoom)) {
this._zoom = panBy(this._zoom, dx, dy, size);
this._zoom = panBy(this._zoom, dx, dy, viewport);
}
}
@@ -953,12 +1033,18 @@ export class HaCameraPlayer extends LitElement {
.viewport {
position: relative;
overflow: hidden;
max-height: var(--video-max-height, calc(100vh - 97px));
/* As wide as the player also when its height is limited, which the
aspect ratio would otherwise limit the width with, so the zoomed in
picture and gestures reach into the bars next to it */
width: 100%;
/* Scrolls the page until zoomed in, pinches are handled here */
touch-action: pan-x pan-y;
/* From the poster's or a default size to the stream's */
transition: aspect-ratio var(--ha-animation-duration-normal) ease-out;
}
.player.fullscreen .viewport,
.player.fullscreen ha-camera-stream {
.player.fullscreen .viewport {
width: 100%;
height: 100%;
}
@@ -972,7 +1058,11 @@ export class HaCameraPlayer extends LitElement {
cursor: grabbing;
}
/* Sized by the viewport, a video without a picture yet would be only
as high as an empty video */
ha-camera-stream {
width: 100%;
height: 100%;
transform-origin: 0 0;
transition: transform var(--ha-animation-duration-fast) ease-out;
}
@@ -1098,4 +1188,7 @@ declare global {
interface HTMLElementTagNameMap {
"ha-camera-player": HaCameraPlayer;
}
interface HASSDomEvents {
"camera-aspect-ratio-changed": { aspectRatio: number };
}
}
+130 -12
View File
@@ -1,6 +1,7 @@
/**
* Zoom and pan of content that fills a viewport, applied as
* `translate(x, y) scale(scale)` with the transform origin at the top left.
* Zoom and pan of a picture in a viewport, applied as
* `translate(x, y) scale(scale)` with the transform origin at the top left
* of the viewport.
*/
export interface ZoomPan {
scale: number;
@@ -13,28 +14,87 @@ export interface ZoomPanSize {
height: number;
}
export interface ZoomPanRect extends ZoomPanSize {
x: number;
y: number;
}
/**
* The viewport and where the picture shows in it before zooming, with bars
* next to it when their aspect ratios differ.
*/
export interface ZoomPanViewport extends ZoomPanSize {
picture: ZoomPanRect;
}
export const ZOOM_PAN_IDENTITY: ZoomPan = { scale: 1, x: 0, y: 0 };
export const MAX_ZOOM = 5;
export const isZoomed = (zoomPan: ZoomPan): boolean => zoomPan.scale > 1;
/** Keeps the scale in range and the content covering the whole viewport. */
/**
* The viewport with the picture fit in its middle, like `object-fit:
* contain`. Without the size of the picture, it fills the viewport.
*/
export const fitPicture = (
{ width, height }: ZoomPanSize,
pictureSize?: ZoomPanSize
): ZoomPanViewport => {
if (!pictureSize?.width || !pictureSize.height || !width || !height) {
return { width, height, picture: { x: 0, y: 0, width, height } };
}
const fit = Math.min(width / pictureSize.width, height / pictureSize.height);
const pictureWidth = pictureSize.width * fit;
const pictureHeight = pictureSize.height * fit;
return {
width,
height,
picture: {
x: (width - pictureWidth) / 2,
y: (height - pictureHeight) / 2,
width: pictureWidth,
height: pictureHeight,
},
};
};
/**
* The offset on one axis that keeps the zoomed picture covering the viewport,
* or in its middle while it is still smaller than the viewport.
*/
const clampOffset = (
offset: number,
scale: number,
viewportLength: number,
pictureStart: number,
pictureLength: number
): number => {
const scaledLength = pictureLength * scale;
if (scaledLength <= viewportLength) {
return (viewportLength - scaledLength) / 2 - pictureStart * scale;
}
const min = viewportLength - (pictureStart + pictureLength) * scale;
// Not -0 when the picture starts at the edge of the viewport
const max = 0 - pictureStart * scale;
return Math.min(max, Math.max(min, offset));
};
/** Keeps the scale in range and the bars next to the picture out of view. */
export const clampZoomPan = (
{ scale, x, y }: ZoomPan,
{ width, height }: ZoomPanSize,
viewport: ZoomPanViewport,
maxScale = MAX_ZOOM
): ZoomPan => {
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
if (clampedScale === 1) {
return ZOOM_PAN_IDENTITY;
}
const minX = width - width * clampedScale;
const minY = height - height * clampedScale;
const { picture } = viewport;
return {
scale: clampedScale,
x: Math.min(0, Math.max(minX, x)),
y: Math.min(0, Math.max(minY, y)),
x: clampOffset(x, clampedScale, viewport.width, picture.x, picture.width),
y: clampOffset(y, clampedScale, viewport.height, picture.y, picture.height),
};
};
@@ -46,7 +106,7 @@ export const zoomAtPoint = (
zoomPan: ZoomPan,
scale: number,
point: { x: number; y: number },
size: ZoomPanSize,
viewport: ZoomPanViewport,
maxScale = MAX_ZOOM
): ZoomPan => {
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
@@ -57,7 +117,7 @@ export const zoomAtPoint = (
x: point.x - (point.x - zoomPan.x) * ratio,
y: point.y - (point.y - zoomPan.y) * ratio,
},
size,
viewport,
maxScale
);
};
@@ -66,11 +126,69 @@ export const panBy = (
zoomPan: ZoomPan,
dx: number,
dy: number,
size: ZoomPanSize,
viewport: ZoomPanViewport,
maxScale = MAX_ZOOM
): ZoomPan =>
clampZoomPan(
{ ...zoomPan, x: zoomPan.x + dx, y: zoomPan.y + dy },
size,
viewport,
maxScale
);
/**
* Keeps the part of the picture in the middle of the viewport there when the
* viewport or the picture changes size, like when turning a phone.
*/
export const refitZoomPan = (
zoomPan: ZoomPan,
oldViewport: ZoomPanViewport,
newViewport: ZoomPanViewport,
maxScale = MAX_ZOOM
): ZoomPan => {
const { scale } = zoomPan;
const oldPicture = oldViewport.picture;
const newPicture = newViewport.picture;
if (!isZoomed(zoomPan) || !oldPicture.width || !oldPicture.height) {
return clampZoomPan(zoomPan, newViewport, maxScale);
}
const centerX =
((oldViewport.width / 2 - zoomPan.x) / scale - oldPicture.x) /
oldPicture.width;
const centerY =
((oldViewport.height / 2 - zoomPan.y) / scale - oldPicture.y) /
oldPicture.height;
return clampZoomPan(
{
scale,
x:
newViewport.width / 2 -
(newPicture.x + centerX * newPicture.width) * scale,
y:
newViewport.height / 2 -
(newPicture.y + centerY * newPicture.height) * scale,
},
newViewport,
maxScale
);
};
/**
* The part of the picture that shows, as fractions of the picture between 0
* and 1.
*/
export const visiblePart = (
{ scale, x, y }: ZoomPan,
{ width, height, picture }: ZoomPanViewport
): ZoomPanRect => {
if (!picture.width || !picture.height) {
return { x: 0, y: 0, width: 1, height: 1 };
}
const left = Math.max(0, (-x / scale - picture.x) / picture.width);
const right = Math.min(1, ((width - x) / scale - picture.x) / picture.width);
const top = Math.max(0, (-y / scale - picture.y) / picture.height);
const bottom = Math.min(
1,
((height - y) / scale - picture.y) / picture.height
);
return { x: left, y: top, width: right - left, height: bottom - top };
};
+11 -4
View File
@@ -89,6 +89,11 @@ const countNumericPoints = (data: unknown, limit: number): number => {
return found;
};
// A silent series ignores the pointer, like the power sources graph's zero
// line, so it is decoration rather than data to walk through.
const isDecoration = (s: { silent?: boolean } | undefined): boolean =>
s?.silent === true;
const countNavigablePoints = (
series: readonly ({ data?: unknown } | undefined)[]
): number => {
@@ -109,9 +114,9 @@ export const canSonifyChart = (
hiddenDatasets?: ReadonlySet<string>
): boolean => {
const series = ensureArray(data);
const visible = hiddenDatasets?.size
? series.filter((s) => !hiddenDatasets.has(String(s.id ?? s.name)))
: series;
const visible = series.filter(
(s) => !isDecoration(s) && !hiddenDatasets?.has(String(s.id ?? s.name))
);
return (
// Cards commonly push empty placeholder series, so judge the chart by the
// points the extension can actually read — but every type has to be
@@ -264,7 +269,9 @@ export const sonifyChart = async (
const allSeries = ensureArray(chartOptions.series) as (
HaECSeriesItem | undefined
)[];
const readable = allSeries.filter((s) => countNumericPoints(s?.data, 1));
const readable = allSeries.filter(
(s) => !isDecoration(s) && countNumericPoints(s?.data, 1)
);
// A single point is not navigable, so it does not earn a focus stop either.
if (countNavigablePoints(readable) < MIN_NAVIGABLE_POINTS) {
return null;
@@ -29,14 +29,21 @@ export interface TimelineSegment {
end: number;
}
/** Resolves each frame of a run to the state covering most of that frame. */
/**
* Resolves each frame of a run to the state covering most of that frame. The
* first and last frames prefer any other state over the state of the
* neighbour they touch, so a run never disappears into its neighbours.
*/
function collapseRun(
segments: TimelineSegment[],
from: number,
to: number,
frameMs: number,
before: string | undefined,
after: string | undefined,
push: (segment: TimelineSegment) => void
) {
const runStart = segments[from].start;
const runEnd = segments[to - 1].end;
const frameStates = new Map<
string,
@@ -86,6 +93,22 @@ function collapseRun(
while (index < to && segments[index].end <= frameEnd) {
index++;
}
const avoidBefore = frameStart === runStart ? before : undefined;
const avoidAfter = frameEnd === runEnd ? after : undefined;
if (bestState === avoidBefore || bestState === avoidAfter) {
let otherDuration = 0;
for (const [state, entry] of frameStates) {
if (
state !== avoidBefore &&
state !== avoidAfter &&
entry.duration > otherDuration
) {
otherDuration = entry.duration;
bestState = state;
bestLocState = entry.locState;
}
}
}
if (bestState !== null) {
push({
state: bestState,
@@ -138,7 +161,17 @@ export function downSampleTimelineSegments(
) {
index++;
}
collapseRun(segments, from, index, frameMs, push);
const last = result[result.length - 1];
const next = segments[index];
collapseRun(
segments,
from,
index,
frameMs,
last?.end === segments[from].start ? last.state : undefined,
next?.start === segments[index - 1].end ? next.state : undefined,
push
);
}
return result;
}
@@ -14,6 +14,12 @@ class HaDeviceActionPicker extends HaDeviceAutomationPicker<DeviceAction> {
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.unknown_action"
@@ -49,6 +49,10 @@ export abstract class HaDeviceAutomationPicker<
@property({ type: Object }) public value?: T;
@property({ type: Boolean }) public invalid = false;
@property({ attribute: "error-message" }) public errorMessage?: string;
@state() private _automations?: T[];
// Trigger an empty render so we start with a clean DOM.
@@ -106,6 +110,13 @@ export abstract class HaDeviceAutomationPicker<
);
}
/** Error shown when the picked device has nothing to choose from. */
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.not_supported"
);
}
private _localizeDeviceAutomation: (
localize: LocalizeFunc,
states: HassEntities,
@@ -163,6 +174,12 @@ export abstract class HaDeviceAutomationPicker<
.value=${value}
.disabled=${this._automations?.length === 0}
.loading=${this._automations === undefined}
.invalid=${this.invalid}
.errorMessage=${
this._automations?.length === 0
? this.NOT_SUPPORTED_TEXT
: this.errorMessage
}
.getItems=${this._getItems(
value,
this._automations,
@@ -14,6 +14,12 @@ class HaDeviceConditionPicker extends HaDeviceAutomationPicker<DeviceCondition>
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.conditions.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.conditions.unknown_condition"
@@ -107,6 +107,10 @@ export class HaDevicePicker extends LitElement {
@property() public helper?: string;
@property({ type: Boolean }) public invalid = false;
@property({ attribute: "error-message" }) public errorMessage?: string;
@property() public placeholder?: string;
@property({ type: String, attribute: "search-label" })
@@ -521,6 +525,8 @@ export class HaDevicePicker extends LitElement {
.autofocus=${this.autofocus}
.disabled=${this.disabled}
.helper=${this.helper}
.invalid=${this.invalid}
.errorMessage=${this.errorMessage}
.label=${this.label}
.searchLabel=${this.searchLabel}
.notFoundLabel=${this._notFoundLabel}
@@ -14,6 +14,12 @@ class HaDeviceTriggerPicker extends HaDeviceAutomationPicker<DeviceTrigger> {
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.triggers.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.triggers.unknown_trigger"
+52 -3
View File
@@ -7,6 +7,7 @@ import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
import { loadImage } from "../common/dom/load-image";
import { supportsFeature } from "../common/entity/supports-feature";
import {
CameraEntityFeature,
@@ -85,6 +86,14 @@ export class HaCameraStream extends LitElement {
@property({ type: Boolean, attribute: "mjpeg-video" })
public mjpegVideo = false;
/**
* Loads the poster first to tell its size with
* `camera-poster-size-changed`, so a player can make room for it before
* the stream loads.
*/
@property({ type: Boolean, attribute: "measure-poster" })
public measurePoster = false;
// Video background image before its loaded
@state() private _posterUrl?: string;
@@ -171,6 +180,21 @@ export class HaCameraStream extends LitElement {
return this._visiblePlayer?.videoElement;
}
/**
* The size of the shown stream's picture, before it is fit into the
* player. Undefined until it is known.
*/
public get pictureSize(): { width: number; height: number } | undefined {
const player = this._visiblePlayer;
if (player && player === this._mjpegPlayer) {
return this._mjpegPlayer.pictureSize;
}
const video = player?.videoElement;
return video?.videoWidth
? { width: video.videoWidth, height: video.videoHeight }
: undefined;
}
/** Opens the video of the shown stream picture in picture. */
public async requestPictureInPicture() {
const player = this._visiblePlayer;
@@ -377,17 +401,41 @@ export class HaCameraStream extends LitElement {
}
private async _getPosterUrl(): Promise<void> {
const entityId = this.stateObj!.entity_id;
let posterUrl: string | undefined;
try {
this._posterUrl = await fetchThumbnailUrlWithCache(
posterUrl = await fetchThumbnailUrlWithCache(
this._thumbnailApi(this._api, this._connection),
this.stateObj!.entity_id,
entityId,
this.clientWidth,
this.clientHeight
);
} catch (_err: any) {
// poster url is optional
this._posterUrl = undefined;
}
if (!this.measurePoster) {
if (this.stateObj?.entity_id === entityId) {
this._posterUrl = posterUrl;
}
return;
}
// Loaded here first for its size, the poster then uses the same image
// instead of asking the camera again
const poster = posterUrl ? await loadImage(posterUrl) : undefined;
if (this.stateObj?.entity_id !== entityId) {
return;
}
this._posterUrl = posterUrl;
fireEvent(
this,
"camera-poster-size-changed",
{
size: poster?.naturalWidth
? { width: poster.naturalWidth, height: poster.naturalHeight }
: undefined,
},
{ bubbles: false, composed: false }
);
}
private _handleImageLoad() {
@@ -491,6 +539,7 @@ declare global {
"stream-type-changed": { type?: CameraStreamType };
"camera-capabilities-changed": { capabilities?: CameraCapabilities };
"camera-stream-status-changed": CameraStreamStatus;
"camera-poster-size-changed": { size?: { width: number; height: number } };
streams: {
hasAudio: boolean;
hasVideo: boolean;
+44 -6
View File
@@ -1,5 +1,6 @@
import {
DIRECTION_ALL,
INPUT_CANCEL,
Manager,
Pan,
Press,
@@ -138,6 +139,13 @@ export class HaControlCircularSlider extends LitElement {
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
if (
this._activeSlider &&
changedProps.has(this._activeSlider) &&
this[this._activeSlider] !== this._lastChanging
) {
this._lastChanging = undefined;
}
if (!this._activeSlider) {
if (changedProps.has("value")) {
this._localValue = this.value;
@@ -175,6 +183,10 @@ export class HaControlCircularSlider extends LitElement {
private _managers: HammerManager[] = [];
private _lastChanging?: number;
private _keyboardChanging = false;
private _getPercentageFromEvent = (e: HammerInput) => {
const bound = this._slider.getBoundingClientRect();
const x = (2 * (e.center.x - bound.left - bound.width / 2)) / bound.width;
@@ -266,6 +278,21 @@ export class HaControlCircularSlider extends LitElement {
mc.add(new Tap({ event: "singletap" }));
const cancelInteraction = () => {
if (this._activeSlider) {
fireEvent(this, `${this._activeSlider}-changing`, {
value: undefined,
});
}
this._activeSlider = undefined;
this._localValue = this.value;
this._localLow = this.low;
this._localHigh = this.high;
if (pressToActivate) {
panRecognizer.set({ enable: false });
}
};
mc.on("press", (e) => {
e.srcEvent.stopPropagation();
e.srcEvent.preventDefault();
@@ -313,14 +340,12 @@ export class HaControlCircularSlider extends LitElement {
const raw = this._percentageToValue(percentage);
this._activeSlider = this._findActiveSlider(raw);
this._lastSlider = this._activeSlider;
this._lastChanging = undefined;
this.shadowRoot?.getElementById("#slider")?.focus();
});
mc.on("pancancel", () => {
if (this.disabled || this.readonly) return;
this._activeSlider = undefined;
if (pressToActivate) {
panRecognizer.set({ enable: false });
}
cancelInteraction();
});
mc.on("panmove", (e) => {
if (this.disabled || this.readonly) return;
@@ -329,7 +354,8 @@ export class HaControlCircularSlider extends LitElement {
const bounded = this._boundedValue(raw);
this._setActiveValue(bounded);
const stepped = this._steppedValue(bounded);
if (this._activeSlider) {
if (this._activeSlider && stepped !== this._lastChanging) {
this._lastChanging = stepped;
fireEvent(this, `${this._activeSlider}-changing`, {
value: stepped,
});
@@ -378,6 +404,10 @@ export class HaControlCircularSlider extends LitElement {
panRecognizer.set({ enable: false });
}
});
mc.on("hammer.input", (e) => {
if (e.eventType !== INPUT_CANCEL || !this._activeSlider) return;
cancelInteraction();
});
});
}
}
@@ -432,6 +462,7 @@ export class HaControlCircularSlider extends LitElement {
this._setActiveValue(this._boundedValue(this.max));
break;
}
this._keyboardChanging = true;
fireEvent(this, `${this._activeSlider}-changing`, {
value: this._getActiveValue(),
});
@@ -440,8 +471,14 @@ export class HaControlCircularSlider extends LitElement {
private _handleKeyUp(e: KeyboardEvent) {
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
e.preventDefault();
this._endKeyboardChange(e);
}
private _endKeyboardChange(e: Event) {
if (!this._keyboardChanging) return;
this._keyboardChanging = false;
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
fireEvent(this, `${this._activeSlider}-changing`, {
value: undefined,
});
@@ -583,6 +620,7 @@ export class HaControlCircularSlider extends LitElement {
)}
@keydown=${this._handleKeyDown}
@keyup=${this._handleKeyUp}
@blur=${this._endKeyboardChange}
/>
`
: nothing
+10
View File
@@ -82,6 +82,8 @@ export class HaControlScrubber extends LitElement {
private _mc?: HammerManager;
private _keyboardChanging = false;
private get _range() {
return this.max - this.min;
}
@@ -278,12 +280,19 @@ export class HaControlScrubber extends LitElement {
e.code === "ArrowLeft" || e.code === "ArrowDown" ? -1 : 1;
this.value = this.normalizedValue(current + this.step * multiplier);
}
this._keyboardChanging = true;
fireEvent(this, "slider-moved", { value: this.value });
}
private _handleKeyUp(e: KeyboardEvent) {
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
e.preventDefault();
this._endKeyboardChange();
}
private _endKeyboardChange() {
if (!this._keyboardChanging) return;
this._keyboardChanging = false;
fireEvent(this, "slider-moved", { value: undefined });
fireEvent(this, "value-changed", { value: this.value });
}
@@ -323,6 +332,7 @@ export class HaControlScrubber extends LitElement {
aria-orientation="horizontal"
@keydown=${this._handleKeyDown}
@keyup=${this._handleKeyUp}
@blur=${this._endKeyboardChange}
>
<div class="rail"></div>
<div class="track" @transitionend=${this._handleTransitionEnd}></div>
+10
View File
@@ -308,14 +308,23 @@ export class HaControlSlider extends LitElement {
);
}
this._showTooltip();
this._keyboardChanging = true;
fireEvent(this, "slider-moved", { value: this.value });
}
private _tooltipTimeout?: number;
private _keyboardChanging = false;
private _handleKeyUp(e: KeyboardEvent) {
if (!A11Y_KEY_CODES.has(e.code)) return;
e.preventDefault();
this._endKeyboardChange();
}
private _endKeyboardChange() {
if (!this._keyboardChanging) return;
this._keyboardChanging = false;
this._hideTooltip(500);
fireEvent(this, "value-changed", { value: this.value });
}
@@ -405,6 +414,7 @@ export class HaControlSlider extends LitElement {
aria-orientation=${this.vertical ? "vertical" : "horizontal"}
@keydown=${this._handleKeyDown}
@keyup=${this._handleKeyUp}
@blur=${this._endKeyboardChange}
>
<div class="slider-track-background"></div>
<slot name="background"></slot>
+2
View File
@@ -65,6 +65,7 @@ type DialogHideEvent = CustomEvent<{ source?: Element }>;
* @cssprop --dialog-backdrop-filter - Dialog scrim backdrop filter (legacy).
* @cssprop --mdc-dialog-scrim-color - Dialog scrim color (legacy).
* @cssprop --dialog-surface-margin-top - Top margin for the dialog surface.
* @cssprop --ha-dialog-width-transition - Transition of the dialog surface's width, like when it follows the size of its content. Defaults to none.
*
* @attr {boolean} open - Controls the dialog open state.
* @attr {("alert"|"standard")} type - Dialog type. Defaults to "standard".
@@ -412,6 +413,7 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
color: var(--primary-text-color);
min-width: var(--width, var(--full-width));
max-width: var(--width, var(--full-width));
transition: var(--ha-dialog-width-transition, none);
max-height: var(
--ha-dialog-max-height,
calc(var(--safe-height) - var(--ha-space-20))
+4 -13
View File
@@ -5,7 +5,7 @@ import { consume } from "../common/decorators/consume";
import { computeDomain } from "../common/entity/compute_domain";
import type { LocalizeFunc } from "../common/translations/localize";
import { stringCompare } from "../common/string/compare";
import { internationalizationContext, statesContext } from "../data/context";
import { statesContext } from "../data/context";
import { computeDeviceClassName } from "../data/entity/device_class";
import { HaFilterStates } from "./ha-filter-states";
@@ -15,10 +15,6 @@ export class HaFilterDeviceClasses extends HaFilterStates {
@consume({ context: statesContext, subscribe: true })
private _entityStates?: ContextType<typeof statesContext>;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n?: ContextType<typeof internationalizationContext>;
private _deviceClasses = memoizeOne(
(
states: ContextType<typeof statesContext>,
@@ -47,19 +43,14 @@ export class HaFilterDeviceClasses extends HaFilterStates {
);
protected firstUpdated() {
this._i18n?.loadBackendTranslation("entity_component");
this._i18n.loadBackendTranslation("entity_component");
}
protected willUpdate() {
if (
this._entityStates &&
this._localize &&
this._i18n &&
(this.expanded || !this.states)
) {
if (this._entityStates && this._i18n && (this.expanded || !this.states)) {
this.states = this._deviceClasses(
this._entityStates,
this._localize,
this._i18n.localize,
this._i18n.locale.language
);
}
+5 -10
View File
@@ -10,7 +10,6 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import { computeDeviceNameDisplay } from "../common/entity/compute_device_name";
import { stringCompare } from "../common/string/compare";
@@ -37,10 +36,6 @@ interface HaFilterDevicesItem extends HaListVirtualizedItem {
@customElement("ha-filter-devices")
export class HaFilterDevices extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: devicesContext, subscribe: true })
@state()
private _devicesReg!: ContextType<typeof devicesContext>;
@@ -111,13 +106,13 @@ export class HaFilterDevices extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.panel.config.devices.caption")}
${this._i18n.localize("ui.panel.config.devices.caption")}
${
this.value?.length
? html`<div class="badge">${this.value?.length}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -142,7 +137,7 @@ export class HaFilterDevices extends LitElement {
.rows=${this._devices(
this._devicesReg,
this._filter || "",
this._localize,
this._i18n.localize,
this._i18n.locale.language
)}
.rowRenderer=${this._renderItem}
@@ -174,7 +169,7 @@ export class HaFilterDevices extends LitElement {
this._devices(
this._devicesReg,
this._filter || "",
this._localize,
this._i18n.localize,
this._i18n.locale.language
)[ev.detail].id,
];
@@ -184,7 +179,7 @@ export class HaFilterDevices extends LitElement {
const id = this._devices(
this._devicesReg,
this._filter || "",
this._localize,
this._i18n.localize,
this._i18n.locale.language
)[ev.detail].id;
this.value = (this.value ?? []).filter((deviceId) => deviceId !== id);
+5 -10
View File
@@ -11,7 +11,6 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { arrayWith, arrayWithout } from "../common/array/array-with";
import type {
HASSDomCurrentTargetEvent,
@@ -34,10 +33,6 @@ import type { HaInputSearch } from "./input/ha-input-search";
@customElement("ha-filter-domains")
export class HaFilterDomains extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: statesContext, subscribe: true })
@state()
private _states!: ContextType<typeof statesContext>;
@@ -66,13 +61,13 @@ export class HaFilterDomains extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.panel.config.domains.caption")}
${this._i18n.localize("ui.panel.config.domains.caption")}
${
this.value?.length
? html`<div class="badge">${this.value?.length}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -92,14 +87,14 @@ export class HaFilterDomains extends LitElement {
</ha-input-search>
<ha-list-selectable
multi
aria-label=${this._localize("ui.panel.config.domains.caption")}
aria-label=${this._i18n.localize("ui.panel.config.domains.caption")}
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
${repeat(
this._domains(
this._states,
this._localize,
this._i18n.localize,
this._i18n.locale.language,
this._filter
),
@@ -117,7 +112,7 @@ export class HaFilterDomains extends LitElement {
brand-fallback
></ha-domain-icon>
<span slot="headline"
>${domainToName(this._localize, domain)}</span
>${domainToName(this._i18n.localize, domain)}</span
>
</ha-list-item-option>`
)}
+3 -9
View File
@@ -11,12 +11,10 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { arrayWith, arrayWithout } from "../common/array/array-with";
import { fireEvent } from "../common/dom/fire_event";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import { stringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { deepEqual } from "../common/util/deep-equal";
import {
apiContext,
@@ -42,10 +40,6 @@ interface EntityItem extends HaListVirtualizedItem {
@customElement("ha-filter-entities")
export class HaFilterEntities extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: statesContext, subscribe: true })
@state()
private _states!: ContextType<typeof statesContext>;
@@ -117,13 +111,13 @@ export class HaFilterEntities extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.panel.config.entities.caption")}
${this._i18n.localize("ui.panel.config.entities.caption")}
${
this.value?.length
? html`<div class="badge">${this.value?.length}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -144,7 +138,7 @@ export class HaFilterEntities extends LitElement {
</ha-input-search>
<ha-list-selectable-virtualized
multi
aria-label=${this._localize("ui.panel.config.entities.caption")}
aria-label=${this._i18n.localize("ui.panel.config.entities.caption")}
.rows=${this._currentEntities()}
.rowRenderer=${this._renderItem}
@ha-list-item-selected=${this._handleItemToggled}
+5 -10
View File
@@ -17,7 +17,6 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { computeRTL } from "../common/util/compute_rtl";
import { fireEvent } from "../common/dom/fire_event";
import { stringCompare } from "../common/string/compare";
@@ -56,10 +55,6 @@ interface TypeRow {
@customElement("ha-filter-entity-types")
export class HaFilterEntityTypes extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: statesContext, subscribe: true })
@state()
private _states!: ContextType<typeof statesContext>;
@@ -96,13 +91,13 @@ export class HaFilterEntityTypes extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.components.filter-entity-types.caption")}
${this._i18n.localize("ui.components.filter-entity-types.caption")}
${
count
? html`<div class="badge">${count}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -118,7 +113,7 @@ export class HaFilterEntityTypes extends LitElement {
private _renderContent() {
const rows = this._rows(
this._states,
this._localize,
this._i18n.localize,
this._i18n.locale.language,
this._filter,
this._expandedDomains
@@ -138,7 +133,7 @@ export class HaFilterEntityTypes extends LitElement {
<ha-list-selectable
multi
controlled
aria-label=${this._localize("ui.components.filter-entity-types.caption")}
aria-label=${this._i18n.localize("ui.components.filter-entity-types.caption")}
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
@@ -191,7 +186,7 @@ export class HaFilterEntityTypes extends LitElement {
slot="end"
data-domain=${row.domain}
.path=${row.expanded ? mdiChevronUp : mdiChevronDown}
.label=${this._localize(
.label=${this._i18n.localize(
row.expanded
? "ui.components.filter-entity-types.collapse"
: "ui.components.filter-entity-types.expand"
+5 -11
View File
@@ -14,11 +14,9 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import { computeRTL } from "../common/util/compute_rtl";
import { deepEqual } from "../common/util/deep-equal";
import type { LocalizeFunc } from "../common/translations/localize";
import type { AreaRegistryEntry } from "../data/area/area_registry";
import type { FloorAreasFilterValue } from "../data/data_table_filters";
import {
@@ -52,10 +50,6 @@ import type { HaListSelectable } from "./list/ha-list-selectable";
@customElement("ha-filter-floor-areas")
export class HaFilterFloorAreas extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: areasContext, subscribe: true })
@state()
private _areasReg!: ContextType<typeof areasContext>;
@@ -160,13 +154,13 @@ export class HaFilterFloorAreas extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.panel.config.areas.caption")}
${this._i18n.localize("ui.panel.config.areas.caption")}
${
count
? html`<div class="badge">${count}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -184,7 +178,7 @@ export class HaFilterFloorAreas extends LitElement {
multi
@ha-list-item-selected=${this._handleAdded}
@ha-list-item-deselected=${this._handleRemoved}
aria-label=${this._localize("ui.panel.config.areas.caption")}
aria-label=${this._i18n.localize("ui.panel.config.areas.caption")}
>
<ha-list-item-option
appearance="checkbox"
@@ -194,7 +188,7 @@ export class HaFilterFloorAreas extends LitElement {
.selected=${this.value?.no_area || false}
>
<span slot="headline">
${this._localize("ui.components.area-picker.no_area")}
${this._i18n.localize("ui.components.area-picker.no_area")}
</span>
</ha-list-item-option>
${repeat(
@@ -242,7 +236,7 @@ export class HaFilterFloorAreas extends LitElement {
.path=${mdiTextureBox}
></ha-svg-icon>
<span slot="headline">
${this._localize(
${this._i18n.localize(
"ui.panel.config.areas.picker.other_areas"
)}
</span>
+4 -8
View File
@@ -12,7 +12,6 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { arrayWith, arrayWithout } from "../common/array/array-with";
import type {
HASSDomCurrentTargetEvent,
@@ -62,9 +61,6 @@ export class HaFilterIntegrations extends LitElement {
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: manifestsContext, subscribe: true })
@state()
private _manifests?: ContextType<typeof manifestsContext>;
@@ -92,13 +88,13 @@ export class HaFilterIntegrations extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.panel.config.integrations.caption")}
${this._i18n.localize("ui.panel.config.integrations.caption")}
${
this.value?.length
? html`<div class="badge">${this.value?.length}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -120,7 +116,7 @@ export class HaFilterIntegrations extends LitElement {
</ha-input-search>
<ha-list-selectable
multi
aria-label=${this._localize(
aria-label=${this._i18n.localize(
"ui.panel.config.integrations.caption"
)}
@ha-list-item-selected=${this._handleItemToggled}
@@ -128,7 +124,7 @@ export class HaFilterIntegrations extends LitElement {
>
${repeat(
this._integrations(
this._localize,
this._i18n.localize,
manifests,
this._filter,
this._i18n.locale.language
+4 -10
View File
@@ -11,7 +11,6 @@ import {
FilterPanelController,
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { arrayWith, arrayWithout } from "../common/array/array-with";
import type {
HASSDomCurrentTargetEvent,
@@ -20,7 +19,6 @@ import type {
import { fireEvent } from "../common/dom/fire_event";
import { navigate } from "../common/navigate";
import { stringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { internationalizationContext, labelsContext } from "../data/context";
import type { LabelRegistryEntry } from "../data/label/label_registry";
import "./ha-expansion-panel";
@@ -44,10 +42,6 @@ export class HaFilterLabels extends LitElement {
@property({ type: Boolean, reflect: true }) public expanded = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: internationalizationContext, subscribe: true })
@state()
private _i18n!: ContextType<typeof internationalizationContext>;
@@ -88,13 +82,13 @@ export class HaFilterLabels extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.panel.config.labels.caption")}
${this._i18n.localize("ui.panel.config.labels.caption")}
${
this.value?.length
? html`<div class="badge">${this.value?.length}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -114,7 +108,7 @@ export class HaFilterLabels extends LitElement {
</ha-input-search>
<ha-list-selectable
multi
aria-label=${this._localize("ui.panel.config.labels.caption")}
aria-label=${this._i18n.localize("ui.panel.config.labels.caption")}
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
@@ -154,7 +148,7 @@ export class HaFilterLabels extends LitElement {
<ha-list-item-button @click=${this._manageLabels}>
<ha-svg-icon slot="start" .path=${mdiCog}></ha-svg-icon>
<span slot="headline"
>${this._localize("ui.panel.config.labels.manage_labels")}</span
>${this._i18n.localize("ui.panel.config.labels.manage_labels")}</span
>
</ha-list-item-button>
</ha-list-base>
+4 -10
View File
@@ -17,11 +17,9 @@ import {
filterPanelStyles,
} from "../common/controllers/filter-panel-controller";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import { stringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import {
formattersContext,
internationalizationContext,
@@ -53,10 +51,6 @@ const GROUP_ICONS: Record<LogbookCauseGroup, string> = {
@customElement("ha-filter-logbook-causes")
export class HaFilterLogbookCauses extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: internationalizationContext, subscribe: true })
@state()
private _i18n!: ContextType<typeof internationalizationContext>;
@@ -89,13 +83,13 @@ export class HaFilterLogbookCauses extends LitElement {
@expanded-changed=${this._expandedChanged}
>
<div slot="header" class="header">
${this._localize("ui.components.logbook.cause_filter.caption")}
${this._i18n.localize("ui.components.logbook.cause_filter.caption")}
${
count
? html`<div class="badge">${count}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -120,7 +114,7 @@ export class HaFilterLogbookCauses extends LitElement {
<ha-list-selectable
multi
controlled
aria-label=${this._localize("ui.components.logbook.cause_filter.caption")}
aria-label=${this._i18n.localize("ui.components.logbook.cause_filter.caption")}
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
@@ -153,7 +147,7 @@ export class HaFilterLogbookCauses extends LitElement {
.path=${GROUP_ICONS[group]}
></ha-svg-icon>
<span slot="headline"
>${this._localize(
>${this._i18n.localize(
`ui.components.logbook.cause_filter.${group}`
)}</span
>
+34 -106
View File
@@ -1,3 +1,4 @@
import type { ContextType } from "@lit/context";
import { mdiFilterVariantRemove } from "@mdi/js";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
@@ -14,13 +15,12 @@ import type {
HASSDomEvent,
} from "../common/dom/fire_event";
import { fireEvent } from "../common/dom/fire_event";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../common/translations/localize";
import { consume } from "../common/decorators/consume";
import { internationalizationContext } from "../data/context";
import "./ha-expansion-panel";
import "./ha-icon";
import "./ha-icon-button";
import "./ha-svg-icon";
import "./ha-tree-indicator";
import "./item/ha-list-item-option";
import type { HaListItemOption } from "./item/ha-list-item-option";
import "./list/ha-list-selectable";
@@ -35,34 +35,17 @@ export interface FilterStateOption {
iconPath?: string;
}
/**
* Two opposite options, like available and unavailable, listed under a row
* that ticks or unticks both. The row is partly ticked when one of the two is.
*/
export interface FilterStatePair {
/** Identifies the row, apart from the values of its options */
value: string;
label: string;
iconPath?: string;
options: [FilterStateOption, FilterStateOption];
}
export type FilterStateItem = FilterStateOption | FilterStatePair;
const isPair = (item: FilterStateItem): item is FilterStatePair =>
"options" in item;
@customElement("ha-filter-states")
export class HaFilterStates extends LitElement {
@state()
@consumeLocalize()
protected _localize!: LocalizeFunc;
@consume({ context: internationalizationContext, subscribe: true })
protected _i18n!: ContextType<typeof internationalizationContext>;
@property() public label?: string;
@property({ attribute: false }) public value?: string[];
@property({ attribute: false }) public states?: FilterStateItem[];
@property({ attribute: false }) public states?: FilterStateOption[];
@property({ type: Boolean }) public narrow = false;
@@ -89,7 +72,7 @@ export class HaFilterStates extends LitElement {
? html`<div class="badge">${this.value?.length}</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
.label=${this._localize(
.label=${this._i18n.localize(
"ui.components.subpage-data-table.clear_filter"
)}
@click=${this._clearFilter}
@@ -108,10 +91,29 @@ export class HaFilterStates extends LitElement {
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
${this.states.map((item) =>
isPair(item)
? this._renderPair(item)
: this._renderOption(item)
${this.states.map(
(item) =>
html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${item.value}
.selected=${this.value?.includes(item.value) ?? false}
>
${
item.iconPath
? html`<ha-svg-icon
slot="start"
.path=${item.iconPath}
></ha-svg-icon>`
: item.icon
? html`<ha-icon
slot="start"
.icon=${item.icon}
></ha-icon>`
: nothing
}
<span slot="headline">${item.label}</span>
</ha-list-item-option>`
)}
</ha-list-selectable>
</div>
@@ -121,56 +123,6 @@ export class HaFilterStates extends LitElement {
`;
}
private _renderOption(item: FilterStateOption, nested?: { last: boolean }) {
return html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
class=${nested ? "nested" : ""}
.value=${item.value}
.selected=${this.value?.includes(item.value) ?? false}
>
${
nested
? html`<ha-tree-indicator
slot="start"
.end=${nested.last}
></ha-tree-indicator>`
: nothing
}
${this._renderIcon(item)}
<span slot="headline">${item.label}</span>
</ha-list-item-option>`;
}
private _renderPair(pair: FilterStatePair) {
const picked = pair.options.filter((option) =>
this.value?.includes(option.value)
).length;
return html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${pair.value}
.selected=${picked === pair.options.length}
.indeterminate=${picked > 0 && picked < pair.options.length}
>
${this._renderIcon(pair)}
<span slot="headline">${pair.label}</span>
</ha-list-item-option>
${pair.options.map((option, index) =>
this._renderOption(option, {
last: index === pair.options.length - 1,
})
)}`;
}
private _renderIcon(item: { icon?: string; iconPath?: string }) {
return item.iconPath
? html`<ha-svg-icon slot="start" .path=${item.iconPath}></ha-svg-icon>`
: item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: nothing;
}
private _expandedChanged(ev) {
this.expanded = ev.detail.expanded;
}
@@ -185,21 +137,10 @@ export class HaFilterStates extends LitElement {
return;
}
const selected = ev.type === "ha-list-item-selected";
// A pair row ticks or unticks both of its options
const pair = this.states?.find(
(item): item is FilterStatePair =>
isPair(item) && item.value === itemValue
);
const values = pair
? pair.options.map((option) => option.value)
: [itemValue];
this.value = values.reduce(
(value, val) =>
selected ? arrayWith(value, val) : arrayWithout(value, val),
this.value
);
this.value =
ev.type === "ha-list-item-selected"
? arrayWith(this.value, itemValue)
: arrayWithout(this.value, itemValue);
fireEvent(this, "data-table-filter-changed", {
value: this.value,
@@ -229,19 +170,6 @@ export class HaFilterStates extends LitElement {
flex: 1;
min-height: 0;
}
/* Options of a pair sit under it, like areas under their floor */
.nested::part(base) {
padding-inline-start: 48px;
}
ha-tree-indicator {
width: 56px;
position: absolute;
top: 0px;
inset-inline-start: 0px;
}
ha-tree-indicator:dir(rtl) {
transform: scaleX(-1);
}
.header {
display: flex;
align-items: center;
+15
View File
@@ -1,4 +1,5 @@
import type { ContextType } from "@lit/context";
import { ResizeController } from "@lit-labs/observers/resize-controller";
import type HlsType from "hls.js";
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
@@ -78,6 +79,14 @@ export class HaHLSPlayer extends LitElement {
private _exoPlayer = false;
// The app's player only follows the video when told, also when the video
// changes size without the window, like in a dialog that grows
private _exoPlayerResize = new ResizeController(this, {
target: null,
skipInitial: true,
callback: () => this._resizeExoPlayer(),
});
private static streamCount = 0;
private _hiddenCleanupTimeout?: number;
@@ -316,6 +325,7 @@ export class HaHLSPlayer extends LitElement {
this._exoPlayer = true;
fireEvent(this, "exoplayer-changed", { active: true });
window.addEventListener("resize", this._resizeExoPlayer);
this._exoPlayerResize.observe(this._videoEl);
this.updateComplete.then(() => nextRender()).then(this._resizeExoPlayer);
this._videoEl.style.visibility = "hidden";
await this._config.auth.external!.fireMessage({
@@ -448,6 +458,7 @@ export class HaHLSPlayer extends LitElement {
}
if (this._exoPlayer) {
window.removeEventListener("resize", this._resizeExoPlayer);
this._exoPlayerResize.unobserve(this._videoEl);
this._config.auth.external!.fireMessage({ type: "exoplayer/stop" });
this._exoPlayer = false;
fireEvent(this, "exoplayer-changed", { active: false });
@@ -500,8 +511,12 @@ export class HaHLSPlayer extends LitElement {
max-height: var(--video-max-height, calc(100vh - 97px));
}
/* Scrolls in a player that is only as high as its picture */
.fatal {
display: block;
box-sizing: border-box;
max-height: 100%;
overflow: auto;
padding: 100px 16px;
}
+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;
+8
View File
@@ -47,6 +47,14 @@ export class HaMjpegPlayer extends LitElement {
return this._canCopy ? this._videoEl : undefined;
}
/** The size of the stream's frames, undefined until the first one. */
public get pictureSize(): { width: number; height: number } | undefined {
const image = this._imageEl;
return image?.naturalWidth
? { width: image.naturalWidth, height: image.naturalHeight }
: undefined;
}
/**
* Starts copying the image into the video and opens it picture in
* picture. Stops copying again when it can't be opened.
+99 -29
View File
@@ -41,6 +41,7 @@ import "./ha-selector/ha-selector";
import type { HaSelector } from "./ha-selector/ha-selector";
import "./ha-service-picker";
import "./ha-service-section-icon";
import "./ha-input-helper-text";
import "./ha-settings-row";
import "./ha-yaml-editor";
import type { HaYamlEditor } from "./ha-yaml-editor";
@@ -119,6 +120,15 @@ export class HaServiceControl extends LitElement {
@property({ attribute: "hide-description", type: Boolean })
public hideDescription = false;
/** Error shown below the target picker. */
@property({ attribute: false }) public targetError?: string;
/** Errors shown below the data fields, keyed by field. */
@property({ attribute: false }) public dataErrors?: Record<string, string>;
/** Error of the data as a whole. */
@property({ attribute: false }) public dataError?: string;
@state() private _value!: this["value"];
@state() private _checkedKeys = new Set();
@@ -558,13 +568,14 @@ export class HaServiceControl extends LitElement {
${
serviceData && "target" in serviceData
? html`<ha-selector
class="target-selector"
.hass=${this.hass}
.selector=${targetSelector}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this._value?.target}
></ha-selector>`
class="target-selector"
.hass=${this.hass}
.selector=${targetSelector}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this._value?.target}
></ha-selector>
${this._renderError(this.targetError)}`
: entityId
? html`<ha-entity-picker
.disabled=${this.disabled}
@@ -610,7 +621,10 @@ export class HaServiceControl extends LitElement {
this._hasFilteredFields(fields, targetEntities)
? html`<ha-expansion-panel
left-chevron
.expanded=${!dataField.collapsed}
.expanded=${
!dataField.collapsed ||
fields.some((field) => this.dataErrors?.[field.key])
}
.header=${
this.hass.localize(
`component.${domain}.services.${serviceName}.sections.${dataField.key}.name`,
@@ -642,7 +656,12 @@ export class HaServiceControl extends LitElement {
</ha-expansion-panel>`
: nothing;
})
} `;
}
${this._unshownErrors(
serviceData,
targetEntities,
Boolean(shouldRenderServiceDataYaml)
).map((error) => this._renderError(error))}`;
}
private _getSectionDescription(
@@ -759,30 +778,70 @@ export class HaServiceControl extends LitElement {
}
></ha-markdown>
</span>
<ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${
this.disabled ||
(showOptional &&
!this._checkedKeys.has(dataField.key) &&
(!this._value?.data ||
this._value.data[dataField.key] === undefined))
}
.hass=${this.hass}
.selector=${selector}
.key=${dataField.key}
@value-changed=${this._serviceDataChanged}
.value=${
this._value?.data ? this._value.data[dataField.key] : undefined
}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
.required=${dataField.required}
></ha-selector>
<div class="field">
<ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${
this.disabled ||
(showOptional &&
!this._checkedKeys.has(dataField.key) &&
(!this._value?.data ||
this._value.data[dataField.key] === undefined))
}
.hass=${this.hass}
.selector=${selector}
.key=${dataField.key}
@value-changed=${this._serviceDataChanged}
.value=${
this._value?.data ? this._value.data[dataField.key] : undefined
}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
.required=${dataField.required}
></ha-selector>
${this._renderError(this.dataErrors?.[dataField.key])}
</div>
</ha-settings-row>`
: "";
};
// Errors without a field to show them on, e.g. of a field no target
// supports or of a target the action doesn't have a picker for
private _unshownErrors(
serviceData: ExtHassService | undefined,
targetEntities: string[] | null,
dataYaml: boolean
): string[] {
const targetShown = Boolean(serviceData && "target" in serviceData);
const shownFields = new Set(
dataYaml
? []
: (serviceData?.flatFields ?? [])
.filter(
(field) =>
field.selector &&
(!field.filter ||
this._filterField(field.filter, targetEntities))
)
.map((field) => field.key)
);
return [
...(this.targetError && !targetShown ? [this.targetError] : []),
...(this.dataError ? [this.dataError] : []),
...Object.entries(this.dataErrors ?? {})
.filter(([key]) => !shownFields.has(key))
.map(([key, error]) => `${key}: ${error}`),
];
}
private _renderError(error: string | undefined) {
return error
? html`<ha-input-helper-text class="error"
>${error}</ha-input-helper-text
>`
: nothing;
}
private _selectorContext = memoizeOne((targetEntities: string[] | null) => ({
filter_entity: targetEntities || undefined,
}));
@@ -1022,6 +1081,17 @@ export class HaServiceControl extends LitElement {
ha-settings-row {
padding: var(--service-control-padding, 0 var(--ha-space-4));
}
/* Every field has this wrapper, so the selector isn't rebuilt when its
error comes or goes */
.field {
display: flex;
flex-direction: column;
}
ha-input-helper-text.error {
color: var(--ha-color-on-danger-quiet);
padding-top: var(--ha-space-1);
padding-bottom: var(--ha-space-2);
}
ha-settings-row[narrow] {
padding-bottom: var(--ha-space-2);
}
+3 -1
View File
@@ -775,13 +775,15 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
ha-list-item-button {
flex-shrink: 0;
margin: 0 var(--ha-space-1) var(--ha-space-1);
margin: 0 0 var(--ha-space-1);
margin-inline-start: var(--ha-space-1);
border-radius: var(--ha-border-radius-sm);
--ha-row-item-min-height: var(--ha-space-10);
--ha-row-item-padding-block: 0;
--ha-row-item-padding-inline: var(--ha-space-3);
width: var(--ha-space-12);
position: relative;
overflow: clip;
transition: width var(--ha-animation-duration-normal) ease;
}
ha-list-item-button::part(headline) {
+7
View File
@@ -852,6 +852,13 @@ export class HaWebRtcPlayer extends LitElement {
max-height: var(--video-max-height, calc(100vh - 97px));
}
/* Scrolls in a player that is only as high as its picture */
ha-alert {
display: block;
max-height: 100%;
overflow: auto;
}
.reconnecting {
position: absolute;
inset: 0;
+12 -4
View File
@@ -5,8 +5,9 @@ import { HaSkeleton } from "./ha-skeleton";
/**
* Placeholder for a line of text, matching the tile secondary text skeleton.
* Its height follows the surrounding font size. Set `width` in CSS to fit the
* expected text.
* It takes the height of the surrounding line, so swapping it for the text
* doesn't move anything, and draws a thinner bar in the middle of it. Set
* `width` in CSS to fit the expected text.
*
* @cssprop --ha-skeleton-text-width - The width of the placeholder. Defaults to `140px`.
*/
@@ -18,12 +19,19 @@ export class HaSkeletonText extends HaSkeleton {
css`
:host {
display: inline-flex;
vertical-align: middle;
/* As tall as the line, so from its top, or it can stick out of it
and make the line taller */
vertical-align: top;
align-items: center;
width: var(--ha-skeleton-text-width, 140px);
max-width: 100%;
height: 1em;
height: 1.2em;
height: 1lh;
min-height: 0;
}
.indicator {
height: 0.75em;
}
`,
];
}
+212 -7
View File
@@ -1,19 +1,175 @@
import WaSkeleton from "@home-assistant/webawesome/dist/components/skeleton/skeleton";
import type { CSSResultGroup } from "lit";
import { css } from "lit";
import { customElement } from "lit/decorators";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html } from "lit";
import { customElement, query } from "lit/decorators";
/* How far the wave leans from upright, so it starts at the top corner of the
content and finishes at the opposite bottom corner */
const WAVE_SLANT_DEG = 20;
const WAVE_SLANT = Math.tan((WAVE_SLANT_DEG * Math.PI) / 180);
/* Older browsers don't know :dir(), so they don't mirror the wave either and
it's placed left to right there */
const DIR_SELECTOR_SUPPORTED = (() => {
try {
document.documentElement.matches(":dir(rtl)");
return true;
} catch {
return false;
}
})();
/**
* Placeholder shown while content loads. Sized by its container unless a
* more specific variant such as `ha-skeleton-text` or `ha-skeleton-icon` is used.
*
* A soft wave sweeps across it by default. It's one slanted wave across all
* the skeletons on the page, from the top corner of the content on the side
* text starts from to the opposite bottom corner: each skeleton shows its
* own slice of it, and all of them run in step, so the wave flows from one
* skeleton into the next, and a skeleton added later joins mid-sweep instead
* of starting over. Each sweep starts as the last one leaves the content.
*
* @cssprop --ha-skeleton-color - The fill color. Defaults to `var(--ha-color-fill-neutral-normal-resting)`.
* @cssprop --ha-skeleton-sheen-color - The sheen color when `effect="sheen"`. Defaults to `var(--ha-color-fill-neutral-loud-resting)`.
* @cssprop --ha-skeleton-sheen-color - The sheen color when `effect="sheen"`. Defaults to `var(--ha-color-fill-neutral-normal-hover)`.
* @cssprop --ha-skeleton-border-radius - The corner radius. Defaults to `var(--ha-border-radius-sm)`.
* @cssprop --ha-skeleton-duration - How long one sweep across the skeletons takes when `effect="sheen"`. Defaults to `3s`.
*/
@customElement("ha-skeleton")
export class HaSkeleton extends WaSkeleton {
override effect: WaSkeleton["effect"] = "pulse";
override effect: WaSkeleton["effect"] = "sheen";
/* Every skeleton showing the wave, which share one track */
private static _waving = new Set<HaSkeleton>();
private static _trackFrame?: number;
@query(".indicator") private _indicator?: HTMLDivElement;
@query(".wave") private _wave?: HTMLDivElement;
private _resizeObserver?: ResizeObserver;
/**
* Lay the one track the wave runs along over the content: the box around
* all the skeletons, so no time goes on empty space around them. The wave
* leans, so it enters at the box's top corner and has to travel further,
* by the box's height times the slant, to clear the opposite bottom
* corner. It's measured again whenever a skeleton comes, goes or changes
* size, and at the end of each sweep, so it follows the layout as it moves.
*/
private static _scheduleTrack() {
if (HaSkeleton._trackFrame !== undefined) {
return;
}
HaSkeleton._trackFrame = requestAnimationFrame(() => {
HaSkeleton._trackFrame = undefined;
// Read every skeleton before writing any, so layout runs once
const boxes = [...HaSkeleton._waving].flatMap((skeleton) => {
// The wave sits in the indicator, which can be smaller than the
// host, such as a text skeleton's bar in the middle of its line
const rect = (skeleton._indicator ?? skeleton).getBoundingClientRect();
// A hidden skeleton, such as a picker's once it has loaded, stays
// out of the box so it doesn't stretch the track
const shown = getComputedStyle(skeleton).visibility === "visible";
// The same check the mirroring uses, so a left-to-right cell on a
// right-to-left page is placed the way it's drawn
const rtl = DIR_SELECTOR_SUPPORTED && skeleton.matches(":dir(rtl)");
return rect.width > 0 && shown ? [{ skeleton, rect, rtl }] : [];
});
if (boxes.length === 0) {
return;
}
const left = Math.min(...boxes.map(({ rect }) => rect.left));
const right = Math.max(...boxes.map(({ rect }) => rect.right));
const top = Math.min(...boxes.map(({ rect }) => rect.top));
const bottom = Math.max(...boxes.map(({ rect }) => rect.bottom));
const trackLength = right - left + (bottom - top) * WAVE_SLANT;
boxes.forEach(({ skeleton, rect, rtl }) => {
// Right to left, the wave is drawn mirrored, so it's placed from the
// right edge instead
const start = rtl ? rect.right - right : left - rect.left;
// Lower down, the slanted wave arrives later
skeleton._placeWave(start - (rect.top - top) * WAVE_SLANT, trackLength);
});
});
}
public connectedCallback() {
super.connectedCallback();
this._resizeObserver ??= new ResizeObserver(() =>
HaSkeleton._scheduleTrack()
);
this._resizeObserver.observe(this);
if (this.effect === "sheen") {
HaSkeleton._waving.add(this);
HaSkeleton._scheduleTrack();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
this._resizeObserver?.disconnect();
HaSkeleton._waving.delete(this);
HaSkeleton._scheduleTrack();
}
public override render() {
return html`
<div part="indicator" class="indicator">
<div
class="wave"
@animationiteration=${HaSkeleton._scheduleTrack}
></div>
</div>
`;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
if (changedProperties.has("effect")) {
// An update can finish after the skeleton has gone, and it only
// rejoins when it's connected again
if (this.effect === "sheen" && this.isConnected) {
HaSkeleton._waving.add(this);
} else {
HaSkeleton._waving.delete(this);
}
HaSkeleton._scheduleTrack();
}
}
/* Put this skeleton's slice of the wave in its place on the track */
private _placeWave(trackStart: number, trackLength: number) {
const wave = this._wave;
if (!wave) {
return;
}
wave.style.left = `${trackStart}px`;
wave.style.setProperty("--ha-skeleton-track-width", `${trackLength}px`);
wave.style.setProperty("--ha-skeleton-slant", `${-WAVE_SLANT_DEG}deg`);
// All waves count from the same moment, so they stay in step
wave.getAnimations?.().forEach((animation) => {
if (animation.startTime !== 0) {
animation.startTime = 0;
}
});
}
static get styles(): CSSResultGroup {
return [
@@ -26,13 +182,59 @@ export class HaSkeleton extends WaSkeleton {
);
--sheen-color: var(
--ha-skeleton-sheen-color,
var(--ha-color-fill-neutral-loud-resting)
var(--ha-color-fill-neutral-normal-hover)
);
--wa-border-radius-pill: var(
--ha-skeleton-border-radius,
var(--ha-border-radius-sm)
);
}
.wave {
display: none;
}
:host([effect="sheen"]) .indicator {
position: relative;
overflow: hidden;
background: var(--color);
animation: none;
}
/* Right to left, the wave is drawn mirrored, so it starts from the
top right corner */
:host([effect="sheen"]:dir(rtl)) .indicator {
transform: scaleX(-1);
}
/* The wave crosses the track over all the skeletons, placed from its
start and leaning back from its top edge, and moves with transform
so it stays cheap */
:host([effect="sheen"]) .wave {
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 400px;
background: linear-gradient(
90deg,
transparent,
var(--sheen-color),
transparent
);
transform-origin: top left;
transform: translateX(-100%) skewX(var(--ha-skeleton-slant, 0deg));
/* An even pace with no hold, so the next sweep enters as soon as
the last one leaves */
animation: ha-skeleton-sheen var(--ha-skeleton-duration, 3s) linear
infinite;
}
@keyframes ha-skeleton-sheen {
from {
transform: translateX(-100%) skewX(var(--ha-skeleton-slant, 0deg));
}
to {
transform: translateX(var(--ha-skeleton-track-width, 100vw))
skewX(var(--ha-skeleton-slant, 0deg));
}
}
@media (forced-colors: active) {
:host {
--color: GrayText;
@@ -40,9 +242,12 @@ export class HaSkeleton extends WaSkeleton {
}
@media (prefers-reduced-motion: reduce) {
:host([effect="pulse"]) .indicator,
:host([effect="sheen"]) .indicator {
:host([effect="sheen"]) .wave {
animation: none;
}
:host([effect="sheen"]) .wave {
display: none;
}
}
`,
];
+5 -8
View File
@@ -672,14 +672,6 @@ export const isCondition = (config: unknown): boolean => {
return "condition" in condition && typeof condition.condition === "string";
};
export const isScriptField = (config: unknown): boolean => {
if (!config || typeof config !== "object") {
return false;
}
const field = config as Record<string, unknown>;
return "field" in field && typeof field.field === "object";
};
export const subscribeTrigger = (
hass: HomeAssistant,
onChange: (result: {
@@ -736,6 +728,7 @@ export interface BaseSidebarConfig {
}
export interface TriggerSidebarConfig extends BaseSidebarConfig {
type: "trigger";
save: (value: Trigger) => void;
replace?: () => void;
rename: () => void;
@@ -755,6 +748,7 @@ export interface TriggerSidebarConfig extends BaseSidebarConfig {
}
export interface ConditionSidebarConfig extends BaseSidebarConfig {
type: "condition";
save: (value: Condition) => void;
replace?: () => void;
rename: () => void;
@@ -774,6 +768,7 @@ export interface ConditionSidebarConfig extends BaseSidebarConfig {
}
export interface ActionSidebarConfig extends BaseSidebarConfig {
type: "action";
save: (value: Action) => void;
replace?: () => void;
rename: () => void;
@@ -795,6 +790,7 @@ export interface ActionSidebarConfig extends BaseSidebarConfig {
}
export interface OptionSidebarConfig extends BaseSidebarConfig {
type: "option";
save: (value: unknown) => void;
rename: () => void;
duplicate: () => void;
@@ -808,6 +804,7 @@ export interface OptionSidebarConfig extends BaseSidebarConfig {
}
export interface ScriptFieldSidebarConfig extends BaseSidebarConfig {
type: "script-field";
save: (value: Field) => void;
config: {
field: Field;
+70
View File
@@ -1,17 +1,33 @@
import type { ConfigPath } from "../common/util/config-path";
import type { HomeAssistant } from "../types";
export interface ConfigValidationError {
message: string;
/** The path in the config as it was sent, `[]` when core does not know. */
path: ConfigPath;
code: string | null;
translation_key: string | null;
translation_domain: string | null;
translation_placeholders: Record<string, unknown>;
}
export interface ValidConfig {
valid: true;
error: null;
errors: [];
}
export interface InvalidConfig {
valid: false;
error: string;
/** Paths are relative to the section. */
errors: ConfigValidationError[];
}
type ValidKeys = "triggers" | "actions" | "conditions";
export type ValidationSectionKeys = Partial<Record<ValidKeys, string>>;
export const validateConfig = <T extends Partial<Record<ValidKeys, unknown>>>(
hass: HomeAssistant,
config: T
@@ -20,3 +36,57 @@ export const validateConfig = <T extends Partial<Record<ValidKeys, unknown>>>(
type: "validate_config",
...config,
});
/**
* Flattens a `validate_config` result into errors with paths from the config
* root. `sectionKeys` names the config key of a section when it differs from
* the key it is validated under, e.g. `{ actions: "sequence" }` for scripts.
*/
export const validationResultErrors = (
result: Partial<Record<ValidKeys, ValidConfig | InvalidConfig>>,
sectionKeys: ValidationSectionKeys = {}
): ConfigValidationError[] =>
(Object.keys(result) as ValidKeys[]).flatMap((key) => {
const sectionKey = sectionKeys[key] ?? key;
return (result[key]?.errors ?? []).map((error) => ({
...error,
path: [sectionKey, ...error.path],
}));
});
export const validateConfigErrors = async (
hass: HomeAssistant,
config: Partial<Record<ValidKeys, unknown>>,
sectionKeys?: ValidationSectionKeys
): Promise<ConfigValidationError[]> =>
validationResultErrors(await validateConfig(hass, config), sectionKeys);
export interface ConfigSaveError {
message: string;
errors: ConfigValidationError[];
}
/**
* Reads the errors of a failed config save. Errors that are not about the
* config, like a network error, only have a message.
*/
export const parseConfigSaveError = (err: unknown): ConfigSaveError => {
const { body, error } = (err ?? {}) as { body?: unknown; error?: unknown };
const bodyObject =
body && typeof body === "object"
? (body as { message?: unknown; errors?: unknown })
: undefined;
const message = String(
bodyObject?.message ||
error ||
(typeof body === "string" && body) ||
(err instanceof Error && err.message) ||
err
);
return {
message,
errors: Array.isArray(bodyObject?.errors)
? (bodyObject.errors as ConfigValidationError[])
: [],
};
};
+35 -2
View File
@@ -124,12 +124,41 @@ export function isFullyClosed(stateObj: CoverEntity) {
return stateObj.state === "closed";
}
export function coverOpenTiltPosition(stateObj: CoverEntity): number {
return stateObj.attributes.open_tilt_position ?? 100;
}
export function coverClosedTiltPositions(stateObj: CoverEntity): number[] {
return stateObj.attributes.closed_tilt_positions ?? [0];
}
export function coverTiltAngle(stateObj: CoverEntity, tilt: number): number {
const start = stateObj.attributes.tilt_start_angle;
const end = stateObj.attributes.tilt_end_angle;
if (start != null && end != null) {
return start + ((end - start) * tilt) / 100;
}
const open = coverOpenTiltPosition(stateObj);
if (tilt <= open) {
return open === 0 ? 0 : (-90 * (open - tilt)) / open;
}
return (90 * (tilt - open)) / (100 - open);
}
export function coverTiltOpenness(stateObj: CoverEntity, tilt: number) {
return 100 * (1 - Math.min(1, Math.abs(coverTiltAngle(stateObj, tilt)) / 90));
}
export function isFullyOpenTilt(stateObj: CoverEntity) {
return stateObj.attributes.current_tilt_position === 100;
return (
stateObj.attributes.current_tilt_position ===
coverOpenTiltPosition(stateObj)
);
}
export function isFullyClosedTilt(stateObj: CoverEntity) {
return stateObj.attributes.current_tilt_position === 0;
const tilt = stateObj.attributes.current_tilt_position;
return tilt != null && coverClosedTiltPositions(stateObj).includes(tilt);
}
export function isOpening(stateObj: CoverEntity) {
@@ -199,6 +228,10 @@ export function canStopTilt(stateObj: CoverEntity): boolean {
interface CoverEntityAttributes extends HassEntityAttributeBase {
current_position?: number;
current_tilt_position?: number;
open_tilt_position?: number;
closed_tilt_positions?: number[];
tilt_start_angle?: number;
tilt_end_angle?: number;
supported_speeds?: string[];
}
+2
View File
@@ -16,6 +16,7 @@ export interface HttpConfig {
server_port?: number;
ssl_certificate?: string;
ssl_peer_certificate?: string;
ssl_peer_certificate_remote?: boolean;
ssl_key?: string;
cors_allowed_origins?: string[];
use_x_forwarded_for?: boolean;
@@ -56,6 +57,7 @@ export const HTTP_CONFIG_FIELDS: (keyof HttpConfig)[] = [
"ssl_certificate",
"ssl_key",
"ssl_peer_certificate",
"ssl_peer_certificate_remote",
"ssl_profile",
"cors_allowed_origins",
"use_x_forwarded_for",
+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"
+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>;
+2 -1
View File
@@ -76,7 +76,8 @@ export type TranslationCategory =
| "selector"
| "services"
| "triggers"
| "conditions";
| "conditions"
| "integration_category";
export const subscribeTranslationPreferences = (
hass: HomeAssistant,
@@ -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 };
}
}
+73 -1
View File
@@ -24,6 +24,7 @@ import { customElement, property, query, state } from "lit/decorators";
import { cache } from "lit/directives/cache";
import { classMap } from "lit/directives/class-map";
import { keyed } from "lit/directives/keyed";
import { styleMap } from "lit/directives/style-map";
import { dynamicElement } from "../../common/dom/dynamic-element-directive";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
@@ -150,6 +151,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
@state() private _fill = false;
// The dialog grows with the camera's picture, as high as there is room for
@state() private _cameraAspectRatio?: number;
// Height of the controls the camera's info shows below the picture
@state() private _cameraControlsHeight?: string;
@state() private _open = false;
@state() private _parentEntityIds: string[] = [];
@@ -189,6 +196,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
}
public showDialog(params: MoreInfoDialogParams) {
// The camera player keeps running for the same entity and doesn't send
// its size again
if (params.entityId !== this._entityId) {
this._cameraAspectRatio = undefined;
this._cameraControlsHeight = undefined;
}
this._entityId = params.entityId;
if (!this._entityId) {
this.closeDialog();
@@ -252,6 +265,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._currView = DEFAULT_VIEW;
this._childViewStack = [];
this._returnUrl = undefined;
this._cameraAspectRatio = undefined;
this._cameraControlsHeight = undefined;
this._isEscapeEnabled = true;
window.removeEventListener("dialog-closed", this._enableEscapeKeyClose);
window.removeEventListener("show-dialog", this._disableEscapeKeyClose);
@@ -676,10 +691,31 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
`
: nothing;
// Also when the camera was opened from a smaller entity's related view
const cameraAspectRatio =
domain === "camera" && isDefaultView
? this._cameraAspectRatio
: undefined;
return html`
<ha-adaptive-dialog
.open=${this._open}
.width=${this._fill ? "full" : this.large ? "large" : "medium"}
.width=${
this._fill
? "full"
: this.large || cameraAspectRatio
? "large"
: "medium"
}
class=${classMap({ camera: domain === "camera" })}
style=${styleMap({
"--more-info-camera-controls-height": this._cameraControlsHeight,
"--ha-dialog-width-lg": cameraAspectRatio
? `clamp(var(--ha-dialog-width-md, 580px), calc(var(--video-max-height) * ${cameraAspectRatio}), 1920px)`
: undefined,
})}
@camera-aspect-ratio-changed=${this._cameraAspectRatioChanged}
@camera-controls-height-changed=${this._cameraControlsHeightChanged}
.accessibleLabel=${title}
@closed=${this._dialogClosed}
@opened=${this._handleOpened}
@@ -1104,6 +1140,18 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._entry = ev.detail;
}
private _cameraAspectRatioChanged(
ev: HASSDomEvent<HASSDomEvents["camera-aspect-ratio-changed"]>
) {
this._cameraAspectRatio = ev.detail.aspectRatio;
}
private _cameraControlsHeightChanged(
ev: HASSDomEvent<HASSDomEvents["camera-controls-height-changed"]>
) {
this._cameraControlsHeight = ev.detail.height;
}
private _enlarge() {
withViewTransition(() => {
this._fill = !this._fill;
@@ -1168,6 +1216,30 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
--dialog-content-padding: 0;
}
/* The dialog's margin, its header of about 68px and the controls
below the picture */
ha-adaptive-dialog.camera {
--video-max-height: calc(
100vh - var(--ha-space-20) -
68px - var(--more-info-camera-controls-height, 0px)
);
/* Along with the height of the picture */
--ha-dialog-width-transition:
min-width var(--ha-animation-duration-normal) ease-out,
max-width var(--ha-animation-duration-normal) ease-out;
}
/* A custom property takes any value, so it can't fall back to the
declaration before it. svh like the height limit of the dialog. */
@supports (height: 1svh) {
ha-adaptive-dialog.camera {
--video-max-height: calc(
100svh - var(--ha-space-20) -
68px - var(--more-info-camera-controls-height, 0px)
);
}
}
.content-wrapper {
flex: 1 1 auto;
min-height: 0;
@@ -131,8 +131,6 @@ export class MoreInfoInfo extends LitElement {
[data-domain="camera"] .content {
padding: 0;
/* max height of the video is full screen, minus the height of the header of the dialog (79px) and the max height of the dialog (mdc-dialog-max-height: calc(100% - 72px)) and the actions bar 60px */
--video-max-height: calc(100vh - 72px - 79px - 60px);
}
more-info-content {
@@ -129,6 +129,7 @@ import "./types/ha-automation-action-wait_template";
import { renderCtrlOrCmd } from "../../../../common/keyboard/ctrl-or-cmd";
import { scrollRowIntoView } from "../scroll-row-into-view";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
export interface ActionElement extends LitElement {
action: Action;
@@ -256,6 +257,10 @@ export default class HaAutomationActionRow extends LitElement {
return this._selected;
}
get collapsed() {
return this._collapsed;
}
protected firstUpdated(changedProperties: PropertyValues<this>): void {
super.firstUpdated(changedProperties);
@@ -498,6 +503,12 @@ export default class HaAutomationActionRow extends LitElement {
${this._runResult?.title}
</ha-automation-row-event-chip>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
<ha-dropdown
@@ -798,6 +809,7 @@ export default class HaAutomationActionRow extends LitElement {
...ACTION_COMBINED_BLOCKS,
].includes(blockType!)}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
.dim=${this._running}
@click=${this._toggleSidebar}
@toggle-collapsed=${this._toggleCollapse}
@@ -1269,6 +1281,7 @@ export default class HaAutomationActionRow extends LitElement {
const actionType = getAutomationActionType(sidebarAction);
fireEvent(this, "open-sidebar", {
type: "action",
save: (value) => {
this._sidebarAction = value;
fireEvent(this, "value-changed", { value });
@@ -1,18 +1,25 @@
import type { PropertyValues } from "lit";
import { html, LitElement } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { hasTemplate } from "../../../../../common/string/has-template";
import type { HaDurationData } from "../../../../../components/ha-duration-input";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-duration-input";
import type { DelayAction } from "../../../../../data/script";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { HomeAssistant } from "../../../../../types";
import type { ActionElement } from "../ha-automation-action-row";
import { createDurationData } from "../../../../../common/datetime/create_duration_data";
import { errorMessage } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-action-delay")
export class HaDelayAction extends LitElement implements ActionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["delay"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public disabled = false;
@@ -52,16 +59,25 @@ export class HaDelayAction extends LitElement implements ActionElement {
}
protected render() {
return html`<ha-duration-input
.label=${this.hass.localize(
`ui.panel.config.automation.editor.actions.type.delay.delay`
)}
.disabled=${this.disabled}
.data=${this._timeData}
enable-millisecond
required
@value-changed=${this._valueChanged}
></ha-duration-input>`;
const label = this.hass.localize(
"ui.panel.config.automation.editor.actions.type.delay.delay"
);
const error = this._fieldErrors.fieldError("delay");
return html`${
error
? html`<ha-alert own-margin alert-type="error">
${errorMessage(this.hass.localize, error, label)}
</ha-alert>`
: nothing
}
<ha-duration-input
.label=${label}
.disabled=${this.disabled}
.data=${this._timeData}
enable-millisecond
required
@value-changed=${this._valueChanged}
></ha-duration-input>`;
}
private _valueChanged(ev: CustomEvent) {
@@ -27,9 +27,18 @@ import {
} from "../../../../../data/device/device_registry";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { HomeAssistant } from "../../../../../types";
import {
deviceAutomationErrorText,
deviceErrorText,
} from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-action-device_id")
export class HaDeviceAction extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["device_id", "domain"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public disabled = false;
@@ -131,12 +140,20 @@ export class HaDeviceAction extends LitElement {
}
protected render() {
const deviceError = this._fieldErrors.fieldError("device_id");
const automationError = this._fieldErrors.fieldError("domain");
const deviceId = this._deviceId || this.action.device_id;
return html`
<ha-device-picker
.value=${deviceId}
.replacementDeviceIds=${this._replacementDeviceIds}
.invalid=${!!deviceError}
.errorMessage=${
deviceError
? deviceErrorText(this.hass.localize, deviceError)
: undefined
}
.disabled=${this.disabled}
@value-changed=${this._devicePicked}
label=${this.hass.localize(
@@ -144,6 +161,16 @@ export class HaDeviceAction extends LitElement {
)}
></ha-device-picker>
<ha-device-action-picker
.invalid=${!!automationError}
.errorMessage=${
automationError
? deviceAutomationErrorText(
this.hass.localize,
"actions",
automationError
)
: undefined
}
.value=${this.action}
.deviceId=${deviceId}
.disabled=${this.disabled}
@@ -20,15 +20,24 @@ import type {
import type { HaSelector } from "../../../../../components/ha-selector/ha-selector";
import type { HaActionSelector } from "../../../../../components/ha-selector/ha-selector-action";
import type { HaConditionSelector } from "../../../../../components/ha-selector/ha-selector-condition";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const OPTIONS = ["count", "while", "until", "for_each"] as const;
type RepeatType = (typeof OPTIONS)[number];
// The rows of `while`, `until` and `sequence` show their own errors
const INLINE_FIELDS = ["count", "for_each"];
export const getRepeatType = (action: RepeatAction["repeat"]) =>
OPTIONS.find((option) => option in action);
@customElement("ha-automation-action-repeat")
export class HaRepeatAction extends LitElement implements ActionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
key: "repeat",
inlineFields: INLINE_FIELDS,
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public disabled = false;
@@ -53,6 +62,12 @@ export class HaRepeatAction extends LitElement implements ActionElement {
return { repeat: { count: 2, sequence: [] } };
}
private _formErrors = memoizeOne((fields: Record<string, string>) =>
Object.fromEntries(
Object.entries(fields).filter(([field]) => INLINE_FIELDS.includes(field))
)
);
private _schema = memoizeOne(
(
type: RepeatType,
@@ -123,6 +138,8 @@ export class HaRepeatAction extends LitElement implements ActionElement {
const data = { ...action, type };
return html`<ha-form
.error=${this._formErrors(this._fieldErrors.fields)}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -12,6 +12,8 @@ import type { ServiceAction } from "../../../../../data/script";
import { serviceActionStruct } from "../../../../../data/script";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { HomeAssistant } from "../../../../../types";
import { errorMessage, targetErrorText } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type { ActionElement } from "../ha-automation-action-row";
@customElement("ha-automation-action-service")
@@ -28,6 +30,10 @@ export class HaServiceAction extends LitElement implements ActionElement {
@state() private _responseChecked = false;
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["target", "data"],
});
public static get defaultConfig(): ServiceAction {
return { action: "", data: {} };
}
@@ -80,6 +86,9 @@ export class HaServiceAction extends LitElement implements ActionElement {
? this._action.action.split(".", 2)
: [undefined, undefined];
const targetError = this._fieldErrors.fieldError("target");
const dataError = this._fieldErrors.ownFieldError("data");
const optionalResponse =
domain && service
? !!this.hass.services[domain]?.[service]?.response?.optional
@@ -92,6 +101,15 @@ export class HaServiceAction extends LitElement implements ActionElement {
.value=${this._action}
.disabled=${this.disabled}
.hidePicker=${!!this._action.metadata}
.targetError=${
targetError
? targetErrorText(this.hass.localize, targetError)
: undefined
}
.dataErrors=${this._fieldErrors.nestedFieldErrors("data")}
.dataError=${
dataError ? errorMessage(this.hass.localize, dataError) : undefined
}
@value-changed=${this._actionChanged}
></ha-service-control>
${
@@ -4,6 +4,7 @@ import "../../../../../components/ha-form/ha-form";
import type { SetConversationResponseAction } from "../../../../../data/script";
import type { HomeAssistant } from "../../../../../types";
import type { ActionElement } from "../ha-automation-action-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const SCHEMA = [
{
@@ -19,6 +20,10 @@ export class HaSetConversationResponseAction
extends LitElement
implements ActionElement
{
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["set_conversation_response"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public action!: SetConversationResponseAction;
@@ -32,6 +37,8 @@ export class HaSetConversationResponseAction
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${this.action}
.schema=${SCHEMA}
@@ -15,12 +15,17 @@ import "../../trigger/ha-automation-trigger";
import type { TimeoutType } from "../../types";
import type { ActionElement } from "../ha-automation-action-row";
import { handleChangeEvent } from "../ha-automation-action-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-action-wait_for_trigger")
export class HaWaitForTriggerAction
extends LitElement
implements ActionElement
{
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["timeout", "continue_on_timeout"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public action!: WaitForTriggerAction;
@@ -77,6 +82,10 @@ export class HaWaitForTriggerAction
this.inSidebar || (!this.inSidebar && !this.indent)
? html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(
this._computeLabelCallback
)}
.hass=${this.hass}
.data=${this.action}
.schema=${this._schema(timeoutType, timeout !== undefined)}
@@ -7,6 +7,7 @@ import type { WaitAction } from "../../../../../data/script";
import type { HomeAssistant } from "../../../../../types";
import type { ActionElement } from "../ha-automation-action-row";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type {
HaFormSchema,
SchemaUnion,
@@ -15,6 +16,10 @@ import type { TimeoutType } from "../../types";
@customElement("ha-automation-action-wait_template")
export class HaWaitAction extends LitElement implements ActionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["wait_template", "timeout", "continue_on_timeout"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public action!: WaitAction;
@@ -65,6 +70,8 @@ export class HaWaitAction extends LitElement implements ActionElement {
: "duration";
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${this.action}
.schema=${this._schema(timeoutType, timeout !== undefined)}
@@ -0,0 +1,48 @@
import { mdiAlertCircle } from "@mdi/js";
import { html, nothing } from "lit";
import { ifDefined } from "lit/directives/if-defined";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { ConfigPath } from "../../../common/util/config-path";
import "../../../components/ha-alert";
import "../../../components/ha-svg-icon";
import "../../../components/ha-tooltip";
import type { ConfigValidationError } from "../../../data/config";
import { errorText } from "./automation-errors";
export const renderRowErrorIcon = (
localize: LocalizeFunc,
errors: ConfigValidationError[],
path: ConfigPath,
label: string
) =>
errors.length
? html`<ha-svg-icon
id="error-icon"
slot="icons"
tabindex="0"
class="error-indicator"
.path=${mdiAlertCircle}
role="img"
aria-label=${label}
></ha-svg-icon>
<ha-tooltip for="error-icon" slot="icons">
${errors.map((error) => html`<div>${errorText(localize, error, path)}</div>`)}
</ha-tooltip>`
: nothing;
/** Lists errors with their path relative to `path`. */
export const renderErrorsAlert = (
localize: LocalizeFunc,
errors: ConfigValidationError[],
path: ConfigPath = [],
slot?: string
) =>
errors.length
? html`<ha-alert
alert-type="error"
class="errors-alert"
slot=${ifDefined(slot)}
>
${errors.map((error) => html`<div>${errorText(localize, error, path)}</div>`)}
</ha-alert>`
: nothing;
@@ -0,0 +1,299 @@
import { createContext } from "@lit/context";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../common/translations/localize";
import {
formatPath,
pathEquals,
pathStartsWith,
type ConfigPath,
} from "../../../common/util/config-path";
import type { ConfigValidationError } from "../../../data/config";
import type {
AutomationPathRow,
AutomationRowRegistry,
} from "./automation-path";
import { isConfigObject } from "./ui-support";
/** The validation errors of the config being edited, paths from its root. */
export const automationErrorsContext =
createContext<ConfigValidationError[]>("automation-errors");
export const NO_ERRORS: ConfigValidationError[] = [];
/**
* The row an error belongs to: the deepest visible row on its path. Rows
* above it only contain the error, they are expanded to show it. Collapsed
* rows keep the rows inside rendered but hidden, so they show their errors.
*/
export const errorOwner = (
registry: AutomationRowRegistry,
error: ConfigValidationError
): AutomationPathRow | undefined => {
const rows = registry.rowsAlong(error.path);
return rows.find((row) => row.collapsed) ?? rows[rows.length - 1];
};
export const ownedErrors = (
registry: AutomationRowRegistry,
errors: ConfigValidationError[],
row: AutomationPathRow
): ConfigValidationError[] => {
const owned = errors.filter((error) => errorOwner(registry, error) === row);
return owned.length ? owned : NO_ERRORS;
};
/**
* The message of an error, translated when core sent a translation key the
* frontend knows, like `required`.
*/
export const errorMessage = (
localize: LocalizeFunc,
error: ConfigValidationError,
/** The label of the field the error is about, to name it in the message */
field?: string
): string => {
if (!field) {
return translatedMessage(localize, error);
}
// Some labels end with a colon, like the repeat options
const name = field.replace(/:$/, "");
return error.translation_key === "required" && !error.translation_domain
? localize(
"ui.panel.config.automation.editor.errors.validation.required_field",
{ field: name }
)
: localize("ui.panel.config.automation.editor.errors.field_message", {
field: name,
message: translatedMessage(localize, error),
});
};
const translatedMessage = (
localize: LocalizeFunc,
error: ConfigValidationError
): string => {
if (!error.translation_key || error.translation_domain) {
return error.message;
}
const placeholders = Object.fromEntries(
Object.entries(error.translation_placeholders).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(", ") : String(value),
])
);
return (
localize(
`ui.panel.config.automation.editor.errors.validation.${error.translation_key}` as LocalizeKeys,
placeholders
) || error.message
);
};
export const fieldErrors = (
localize: LocalizeFunc,
errors: ConfigValidationError[],
path: ConfigPath
): Record<string, string> => {
// Without a prototype, so data keys like `constructor` aren't taken
const fields: Record<string, string> = Object.create(null);
errors.forEach((error) => {
const field = errorField(error, path);
if (field !== undefined && !(field in fields)) {
fields[field] = errorMessage(localize, error);
}
});
return fields;
};
/** The field of the config at `path` an error is about, if any. */
export const errorField = (
error: ConfigValidationError,
path: ConfigPath
): string | undefined =>
error.path.length > path.length && pathStartsWith(error.path, path)
? String(error.path[path.length])
: undefined;
export const errorText = (
localize: LocalizeFunc,
error: ConfigValidationError,
path: ConfigPath = []
): string => {
const relative = pathStartsWith(error.path, path)
? error.path.slice(path.length)
: error.path;
const message = errorMessage(localize, error);
return relative.length ? `${formatPath(relative)}: ${message}` : message;
};
export const errorsEqual = (
a: ConfigValidationError[],
b: ConfigValidationError[]
): boolean =>
a.length === b.length &&
a.every(
(error, index) =>
error.message === b[index].message &&
error.code === b[index].code &&
pathEquals(error.path, b[index].path)
);
// A block written as a single item, or a template condition written as a
// string, is its first row, see `configErrorPath`
const isSingleItem = (value: unknown): boolean =>
typeof value === "string" || (isConfigObject(value) && !("0" in value));
const childAt = (value: unknown, segment: string | number): unknown => {
if (segment === 0 && isSingleItem(value)) {
return value;
}
if (typeof value !== "object" || value === null) {
return undefined;
}
return (value as Record<string | number, unknown>)[segment];
};
const BLOCK_KEYS = new Set([
"triggers",
"conditions",
"actions",
"sequence",
"if",
"then",
"else",
"choose",
"default",
"parallel",
"while",
"until",
"and",
"or",
"not",
"wait_for_trigger",
]);
/**
* Core reports errors of a block written as a single item, like
* `default: { delay: … }`, without a list index, but the editor shows the
* item as the first row of the block.
*/
export const configErrorPath = (
config: unknown,
path: ConfigPath
): ConfigPath => {
const result: ConfigPath = [];
let value = config;
for (const [index, segment] of path.entries()) {
result.push(segment);
value = childAt(value, segment);
if (typeof segment !== "string") {
continue;
}
if (BLOCK_KEYS.has(segment)) {
if (
(isConfigObject(value) && typeof path[index + 1] === "string") ||
(typeof value === "string" && index === path.length - 1)
) {
result.push(0);
}
} else if (segment !== "repeat") {
// Keys inside fields like `data` are not blocks
return [...result, ...path.slice(index + 1)];
}
}
return result;
};
export const mapErrorsToConfig = (
config: unknown,
errors: ConfigValidationError[]
): ConfigValidationError[] =>
errors.map((error) => ({
...error,
path: configErrorPath(config, error.path),
}));
// Keys that hold rows. Others, like `data`, are fields of the row.
const isRowsKey = (key: string): boolean =>
BLOCK_KEYS.has(key) || key === "repeat";
/**
* Whether rows of `previous` may sit at other paths in `current`, so errors
* at their paths can point at the wrong rows. An edit replaces one item per
* list on its way down, a move, insert or delete changes more.
*/
export const rowPathsShifted = (
previous: unknown,
current: unknown
): boolean => {
if (previous === current) {
return false;
}
if (Array.isArray(previous) || Array.isArray(current)) {
if (
!Array.isArray(previous) ||
!Array.isArray(current) ||
previous.length !== current.length
) {
return true;
}
const changed = previous.flatMap((item, index) =>
item === current[index] ? [] : [index]
);
return (
changed.length > 1 ||
rowPathsShifted(previous[changed[0]], current[changed[0]])
);
}
// New blocks don't move other rows, and a template condition written as a
// string keeps its path when it becomes an object
if (!isConfigObject(previous)) {
return false;
}
if (!isConfigObject(current)) {
return true;
}
// An edit changes one block on its way down, more blocks can swap rows,
// like `then` and `else`
const changed = Object.keys(previous).filter(
(key) =>
isRowsKey(key) &&
previous[key] !== undefined &&
previous[key] !== current[key]
);
return (
changed.length > 1 ||
(changed.length === 1 &&
(current[changed[0]] === undefined ||
rowPathsShifted(previous[changed[0]], current[changed[0]])))
);
};
export const targetErrorText = (
localize: LocalizeFunc,
error: ConfigValidationError
): string =>
localize(
error.code === "required"
? "ui.panel.config.automation.editor.errors.target_required"
: "ui.panel.config.automation.editor.errors.target_invalid"
);
export const deviceErrorText = (
localize: LocalizeFunc,
error: ConfigValidationError
): string =>
error.code === "required"
? localize("ui.panel.config.automation.editor.errors.device_required")
: errorMessage(localize, error);
export const deviceAutomationErrorText = (
localize: LocalizeFunc,
kind: "triggers" | "conditions" | "actions",
error: ConfigValidationError
): string =>
error.code === "required"
? localize(`ui.panel.config.devices.automation.${kind}.required`)
: errorMessage(localize, error);
@@ -0,0 +1,257 @@
import { createContext } from "@lit/context";
import {
consumeContext,
ContextController,
} from "../../../common/decorators/consume";
import {
pathEquals,
pathStartsWith,
type ConfigPath,
} from "../../../common/util/config-path";
import type { ConfigValidationError } from "../../../data/config";
import { internationalizationContext } from "../../../data/context";
import type { HomeAssistantInternationalization } from "../../../types";
import {
automationErrorsContext,
errorField,
errorMessage,
errorsEqual,
fieldErrors,
NO_ERRORS,
ownedErrors,
} from "./automation-errors";
import {
automationPathContext,
automationRowRegistryContext,
type AutomationRowRegistry,
} from "./automation-path";
const fieldsEqual = (a: Record<string, string>, b: Record<string, string>) => {
const keys = Object.keys(a);
return (
keys.length === Object.keys(b).length &&
keys.every((key) => a[key] === b[key])
);
};
/**
* @summary The fields whose errors an editor shows next to the field, so
* the sidebar doesn't list them again.
*/
export class InlineErrorFields {
private _fields = new Map<object, ConfigPath[]>();
constructor(private readonly _onChange: () => void) {}
/** `fields` are paths relative to the row. */
public set(owner: object, fields: ConfigPath[]) {
this._fields.set(owner, fields);
this._onChange();
}
public delete(owner: object) {
if (this._fields.delete(owner)) {
this._onChange();
}
}
/** Whether an error at `path`, relative to the row, is shown inline. */
public has(path: ConfigPath): boolean {
return [...this._fields.values()].some((fields) =>
fields.some((field) => pathStartsWith(path, field))
);
}
}
export const automationInlineErrorFieldsContext =
createContext<InlineErrorFields>("automation-inline-error-fields");
interface AutomationFieldErrorsOptions {
/** Fields the host shows the error of, see `InlineErrorFields`. */
inlineFields?: string[];
/** The key below the path whose fields the host edits, like `repeat`. */
key?: string;
}
/**
* @summary Validation errors of the config at the host's path.
*
* Consumes the errors and the path of the closest ancestor and updates the
* host when the errors it exposes change.
*/
export class AutomationFieldErrorsController extends ContextController {
public fields: Record<string, string> = {};
/** Errors that belong to the row at exactly the path, see `errorOwner`. */
public rowErrors: ConfigValidationError[] = NO_ERRORS;
public path: ConfigPath = [];
@consumeContext({ context: internationalizationContext, subscribe: true })
private _i18n?: HomeAssistantInternationalization;
@consumeContext({ context: automationErrorsContext, subscribe: true })
private _errors: ConfigValidationError[] = NO_ERRORS;
@consumeContext({ context: automationPathContext, subscribe: true })
private _path: ConfigPath = [];
@consumeContext({ context: automationRowRegistryContext })
private _registry?: AutomationRowRegistry;
@consumeContext({ context: automationInlineErrorFieldsContext })
private _inlineErrorFields?: InlineErrorFields;
private _inlineFields?: string[];
private readonly _key: ConfigPath;
private _claimedIn?: InlineErrorFields;
constructor(
host: ConstructorParameters<typeof ContextController>[0],
options: AutomationFieldErrorsOptions = {}
) {
super(host);
this._inlineFields = options.inlineFields;
this._key = options.key ? [options.key] : [];
}
/** Changes the fields the host shows the error of, like when it hides some. */
public set inlineFields(fields: string[]) {
if (
this._inlineFields?.length === fields.length &&
this._inlineFields.every((field, index) => field === fields[index])
) {
return;
}
this._inlineFields = fields;
this._claimedIn?.set(this, this._claims(fields));
}
private _claims(fields: string[]): ConfigPath[] {
return fields.map((field) => [...this._key, field]);
}
private _nestedFieldErrors = new Map<string, Record<string, string>>();
/** First error message of each key inside a field, keyed by the key. */
public nestedFieldErrors(field: string): Record<string, string> {
const errors = this._fieldErrors([...this._path, field]);
const previous = this._nestedFieldErrors.get(field);
// The same object while nothing changed, so the host's child doesn't update
if (previous && fieldsEqual(previous, errors)) {
return previous;
}
this._nestedFieldErrors.set(field, errors);
return errors;
}
/** The error of a field as a whole, not of something inside it. */
public ownFieldError(field: string): ConfigValidationError | undefined {
return this._errors.find((error) =>
pathEquals(error.path, [...this._path, field])
);
}
/** The first error of a field the host edits. */
public fieldError(field: string): ConfigValidationError | undefined {
const path = [...this._path, ...this._key];
return this._errors.find((error) => errorField(error, path) === field);
}
/** The errors at or inside `path`, relative to the host's path. */
public errorsAt(path: ConfigPath): ConfigValidationError[] {
const absolute = [...this._path, ...path];
return this._errors.filter((error) => pathStartsWith(error.path, absolute));
}
private _fieldErrors(path: ConfigPath): Record<string, string> {
return this._errors.length && this._i18n
? fieldErrors(this._i18n.localize, this._errors, path)
: {};
}
private _formErrorLabel?: unknown;
private _formError?: (message: string, schema: { name: string }) => string;
/**
* An ha-form `computeError` that names the field in its error, like
* "Entity is required.", as the error is shown above the field.
*/
public formError<S extends { name: string }>(
computeLabel: (schema: S) => string,
/** The error of a form field, for forms that don't use the config keys */
errorOf: (field: string) => ConfigValidationError | undefined = (field) =>
this.fieldError(field)
): (message: string, schema: S) => string {
if (!this._formError || this._formErrorLabel !== computeLabel) {
this._formErrorLabel = computeLabel;
this._formError = (message, schema) => {
const error = schema.name ? errorOf(schema.name) : undefined;
const label = error && computeLabel(schema as S);
return error && label && this._i18n
? errorMessage(this._i18n.localize, error, label)
: message;
};
}
return this._formError;
}
private _unsubscribeRegistry?: () => void;
public hostConnected() {
this._unsubscribeRegistry ??= this._registry?.subscribe(() => this._sync());
this._claimInlineFields();
this._sync();
}
public hostDisconnected() {
this._unsubscribeRegistry?.();
this._unsubscribeRegistry = undefined;
this._claimedIn?.delete(this);
this._claimedIn = undefined;
}
protected contextUpdated() {
this._claimInlineFields();
this._sync();
}
private _claimInlineFields() {
if (
!this._inlineFields ||
!this._inlineErrorFields ||
this._claimedIn === this._inlineErrorFields
) {
return;
}
this._claimedIn?.delete(this);
this._inlineErrorFields.set(this, this._claims(this._inlineFields));
this._claimedIn = this._inlineErrorFields;
}
private _sync() {
const fields = this._fieldErrors([...this._path, ...this._key]);
const row =
this._errors.length && this._path.length
? this._registry?.rowAt(this._path)
: undefined;
const rowErrors =
row && this._registry
? ownedErrors(this._registry, this._errors, row)
: NO_ERRORS;
if (
this.path === this._path &&
fieldsEqual(fields, this.fields) &&
errorsEqual(rowErrors, this.rowErrors)
) {
return;
}
this.path = this._path;
this.fields = fields;
this.rowErrors = rowErrors;
this.host.requestUpdate();
}
}
@@ -9,12 +9,21 @@ import {
stringifyPath,
type ConfigPath,
} from "../../../common/util/config-path";
import type { ConfigValidationError } from "../../../data/config";
import {
automationErrorsContext,
errorsEqual,
NO_ERRORS,
ownedErrors,
} from "./automation-errors";
export const automationPathContext =
createContext<ConfigPath>("automation-path");
export interface AutomationPathRow extends HTMLElement {
readonly selected: boolean;
/** Whether the rows inside are hidden. */
readonly collapsed?: boolean;
openSidebar(): void;
expand(): void;
}
@@ -34,14 +43,19 @@ export class AutomationRowRegistry {
{ path: ConfigPath; rows: AutomationPathRow[] }
>();
private _listeners = new Set<() => void>();
private _notifyScheduled = false;
public register(path: ConfigPath, row: AutomationPathRow) {
const key = stringifyPath(path);
const entry = this._rows.get(key);
if (!entry) {
this._rows.set(key, { path, rows: [row] });
return;
} else {
entry.rows = [...entry.rows.filter((claimed) => claimed !== row), row];
}
entry.rows = [...entry.rows.filter((claimed) => claimed !== row), row];
this._changed();
}
public unregister(path: ConfigPath, row: AutomationPathRow) {
@@ -54,6 +68,38 @@ export class AutomationRowRegistry {
if (!entry.rows.length) {
this._rows.delete(key);
}
this._changed();
}
/**
* Calls `listener` after rows were registered, unregistered, collapsed or
* expanded, once for all changes made in the same task. Returns the
* function to unsubscribe.
*/
public subscribe(listener: () => void): () => void {
this._listeners.add(listener);
return () => {
this._listeners.delete(listener);
};
}
public rowCollapsedChanged() {
this._changed();
}
private _changed() {
if (this._notifyScheduled || !this._listeners.size) {
return;
}
this._notifyScheduled = true;
queueMicrotask(() => {
this._notifyScheduled = false;
this._listeners.forEach((listener) => listener());
});
}
public rowAt(path: ConfigPath): AutomationPathRow | undefined {
return owner(this._rows.get(stringifyPath(path))?.rows);
}
public pathOf(row: AutomationPathRow): ConfigPath | undefined {
@@ -61,6 +107,11 @@ export class AutomationRowRegistry {
?.path;
}
public selectedPath(): ConfigPath | undefined {
return [...this._rows.values()].find((entry) => owner(entry.rows)?.selected)
?.path;
}
/** The rows containing `path`, outermost first. */
public rowsAlong(path: ConfigPath): AutomationPathRow[] {
return path
@@ -83,11 +134,19 @@ interface AutomationPathControllerOptions {
/**
* Consumes the path of the closest ancestor and provides it extended by the
* host's own segment to its descendants.
* host's own segment to its descendants. For a row, also finds the validation
* errors the row owns and updates the host when they change.
*/
export class AutomationPathController extends ContextController {
public path: ConfigPath = [];
public errors: ConfigValidationError[] = NO_ERRORS;
@consumeContext({ context: automationErrorsContext, subscribe: true })
private _configErrors: ConfigValidationError[] = NO_ERRORS;
private _unsubscribeRegistry?: () => void;
@consumeContext({ context: automationPathContext, subscribe: true })
private _parentPath: ConfigPath = [];
@@ -98,6 +157,8 @@ export class AutomationPathController extends ContextController {
private _registeredRow?: AutomationPathRow;
private _collapsed?: boolean;
private readonly _provider: ContextProvider<typeof automationPathContext>;
constructor(
@@ -124,6 +185,12 @@ export class AutomationPathController extends ContextController {
public hostConnected() {
// A row moved by a drag reconnects without an update
this._sync();
if (this._options.row && this._registry && !this._unsubscribeRegistry) {
// Another row on the path of an error can take it over or give it back
this._unsubscribeRegistry = this._registry.subscribe(() =>
this._syncErrors()
);
}
}
private _sync() {
@@ -133,12 +200,35 @@ export class AutomationPathController extends ContextController {
this._provider.setValue(path);
}
this._syncRegistration();
this._syncErrors();
}
public hostUpdated() {
// A collapsed row takes over the errors of the rows it hides
const collapsed = this._registeredRow?.collapsed;
if (collapsed !== this._collapsed) {
this._collapsed = collapsed;
this._registry?.rowCollapsedChanged();
}
}
public hostDisconnected() {
this._unsubscribeRegistry?.();
this._unsubscribeRegistry = undefined;
this._unregister();
}
private _syncErrors() {
const errors =
this._registeredRow && this._registry && this._configErrors.length
? ownedErrors(this._registry, this._configErrors, this._registeredRow)
: NO_ERRORS;
if (!errorsEqual(errors, this.errors)) {
this.errors = errors;
this.host.requestUpdate();
}
}
private _syncRegistration() {
if (!this._registry || !this._options.row) {
return;
@@ -97,6 +97,7 @@ import "./types/ha-automation-condition-zone";
import { renderCtrlOrCmd } from "../../../../common/keyboard/ctrl-or-cmd";
import { scrollRowIntoView } from "../scroll-row-into-view";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
export interface ConditionElement extends LitElement {
condition: Condition;
@@ -178,6 +179,10 @@ export default class HaAutomationConditionRow extends LitElement {
return this._selected;
}
get collapsed() {
return this._collapsed;
}
private _renderOverflowLabel(label: string, shortcut?: TemplateResult) {
return html`
<div class="overflow-label">
@@ -262,6 +267,12 @@ export default class HaAutomationConditionRow extends LitElement {
)}
</ha-automation-row-event-chip>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
<ha-dropdown
@@ -529,6 +540,7 @@ export default class HaAutomationConditionRow extends LitElement {
this.condition.condition
)}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
.dim=${this._testing}
@click=${this._toggleSidebar}
@toggle-collapsed=${this._toggleCollapse}
@@ -980,6 +992,7 @@ export default class HaAutomationConditionRow extends LitElement {
const sidebarCondition = condition || this.condition;
this._sidebarCondition = sidebarCondition;
fireEvent(this, "open-sidebar", {
type: "condition",
save: (value) => {
this._sidebarCondition = value;
fireEvent(this, "value-changed", { value });
@@ -27,9 +27,18 @@ import {
} from "../../../../../data/device/device_registry";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { HomeAssistant } from "../../../../../types";
import {
deviceAutomationErrorText,
deviceErrorText,
} from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-condition-device")
export class HaDeviceCondition extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["device_id", "domain"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Object }) public condition!: DeviceCondition;
@@ -132,12 +141,20 @@ export class HaDeviceCondition extends LitElement {
}
protected render() {
const deviceError = this._fieldErrors.fieldError("device_id");
const automationError = this._fieldErrors.fieldError("domain");
const deviceId = this._deviceId || this.condition.device_id;
return html`
<ha-device-picker
.value=${deviceId}
.replacementDeviceIds=${this._replacementDeviceIds}
.invalid=${!!deviceError}
.errorMessage=${
deviceError
? deviceErrorText(this.hass.localize, deviceError)
: undefined
}
@value-changed=${this._devicePicked}
.disabled=${this.disabled}
.label=${this.hass.localize(
@@ -145,6 +162,16 @@ export class HaDeviceCondition extends LitElement {
)}
></ha-device-picker>
<ha-device-condition-picker
.invalid=${!!automationError}
.errorMessage=${
automationError
? deviceAutomationErrorText(
this.hass.localize,
"conditions",
automationError
)
: undefined
}
.value=${this.condition}
.deviceId=${deviceId}
@value-changed=${this._deviceConditionPicked}
@@ -19,6 +19,7 @@ import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { NumericStateCondition } from "../../../../../data/automation";
import { NON_NUMERIC_ATTRIBUTES } from "../../../../../data/entity/entity_attributes";
import type { HomeAssistant } from "../../../../../types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const numericStateConditionStruct = object({
alias: optional(string()),
@@ -34,6 +35,16 @@ const numericStateConditionStruct = object({
@customElement("ha-automation-condition-numeric_state")
export default class HaNumericStateCondition extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: [
"entity_id",
"attribute",
"above",
"below",
"value_template",
],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: NumericStateCondition;
@@ -227,6 +238,8 @@ export default class HaNumericStateCondition extends LitElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -34,6 +34,9 @@ import {
} from "../../../../../data/target";
import type { HomeAssistant } from "../../../../../types";
import { documentationUrl } from "../../../../../util/documentation-url";
import "../../../../../components/ha-input-helper-text";
import { targetErrorText } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import { targetExpandGroupContext } from "../../../../../components/target-picker/target-expand-group-context";
// Mirrors `MAX_HISTORY_PRIMING_LOOKBACK` in homeassistant/helpers/condition.py:
@@ -53,6 +56,10 @@ export class HaPlatformCondition extends LitElement {
@provide({ context: targetExpandGroupContext })
protected _targetExpandGroup = false;
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["target"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: PlatformCondition;
@@ -234,6 +241,7 @@ export class HaPlatformCondition extends LitElement {
></ha-selector>`
: nothing
}
${this._renderTargetError()}
${
shouldRenderDataYaml
? html`<ha-yaml-editor
@@ -258,6 +266,15 @@ export class HaPlatformCondition extends LitElement {
`;
}
private _renderTargetError() {
const error = this._fieldErrors.fieldError("target");
return error
? html`<ha-input-helper-text class="target-error">
${targetErrorText(this.hass.localize, error)}
</ha-input-helper-text>`
: nothing;
}
private _targetSelector = memoizeOne(
(targetSelector: TargetSelector["target"] | null | undefined) =>
targetSelector ? { target: { ...targetSelector } } : { target: {} }
@@ -681,6 +698,10 @@ export class HaPlatformCondition extends LitElement {
1px solid var(--divider-color)
);
}
.target-error {
color: var(--ha-color-on-danger-quiet);
padding-bottom: var(--ha-space-2);
}
ha-yaml-editor {
padding: var(--ha-space-4) 0;
}
@@ -17,6 +17,7 @@ import { ensureArray } from "../../../../../common/array/ensure-array";
import { createDurationData } from "../../../../../common/datetime/create_duration_data";
import { fireEvent } from "../../../../../common/dom/fire_event";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { StateCondition } from "../../../../../data/automation";
import { STATE_CONDITION_HIDDEN_ATTRIBUTES } from "../../../../../data/entity/entity_attributes";
@@ -71,6 +72,10 @@ const SCHEMA = memoizeOne(
@customElement("ha-automation-condition-state")
export class HaStateCondition extends LitElement implements ConditionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["entity_id", "attribute", "state", "for"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: StateCondition;
@@ -118,6 +123,8 @@ export class HaStateCondition extends LitElement implements ConditionElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA(hasAttribute)}
@@ -8,14 +8,25 @@ import type { HaSelectSelectEvent } from "../../../../../components/ha-select";
import type { SunCondition } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { ConditionElement } from "../ha-automation-condition-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
type FormType = "before" | "after" | "between";
const BEFORE_DEFAULT = "sunrise";
const AFTER_DEFAULT = "sunset";
const FORM_FIELDS: Record<FormType, string[]> = {
before: ["before", "before_offset"],
after: ["after", "after_offset"],
between: ["after", "after_offset", "before", "before_offset"],
};
@customElement("ha-automation-condition-sun")
export class HaSunCondition extends LitElement implements ConditionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: FORM_FIELDS.before,
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: SunCondition;
@@ -105,6 +116,10 @@ export class HaSunCondition extends LitElement implements ConditionElement {
] as const
);
protected willUpdate() {
this._fieldErrors.inlineFields = FORM_FIELDS[this._formType];
}
protected render() {
const schema = this._schema(this.hass.localize, this._formType);
return html`
@@ -137,6 +152,8 @@ export class HaSunCondition extends LitElement implements ConditionElement {
>
</ha-select>
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.condition}
.hass=${this.hass}
@@ -5,6 +5,7 @@ import type { HomeAssistant } from "../../../../../types";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import "../../../../../components/ha-form/ha-form";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const SCHEMA = [
{ name: "value_template", required: true, selector: { template: {} } },
@@ -12,6 +13,10 @@ const SCHEMA = [
@customElement("ha-automation-condition-template")
export class HaTemplateCondition extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["value_template"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: TemplateCondition;
@@ -25,6 +30,8 @@ export class HaTemplateCondition extends LitElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${this.condition}
.schema=${SCHEMA}
@@ -14,9 +14,14 @@ import type { TimeCondition } from "../../../../../data/automation";
import type { FrontendLocaleData } from "../../../../../data/translation";
import type { HomeAssistant } from "../../../../../types";
import type { ConditionElement } from "../ha-automation-condition-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-condition-time")
export class HaTimeCondition extends LitElement implements ConditionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["after", "before", "weekday"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: TimeCondition;
@@ -150,6 +155,8 @@ export class HaTimeCondition extends LitElement implements ConditionElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -56,7 +56,6 @@ import {
triggerAutomationActions,
} from "../../../data/automation";
import { substituteBlueprint } from "../../../data/blueprint";
import { validateConfig } from "../../../data/config";
import { UNAVAILABLE } from "../../../data/entity/entity";
import {
type EntityRegistryEntry,
@@ -71,7 +70,7 @@ import "../../../layouts/hass-subpage";
import { KeyboardShortcutMixin } from "../../../mixins/keyboard-shortcut-mixin";
import { PreventUnsavedMixin } from "../../../mixins/prevent-unsaved-mixin";
import { haStyle } from "../../../resources/styles";
import type { Entries, ValueChangedEvent } from "../../../types";
import type { ValueChangedEvent } from "../../../types";
import { isMac } from "../../../util/is_mac";
import { showEditorToast } from "./editor-toast";
import { showAssignCategoryDialog } from "../category/show-dialog-assign-category";
@@ -168,7 +167,14 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
const { id, ...rest } = normalizeAutomationConfig(config, report);
return { id, ...rest };
},
checkValidation: () => this._checkValidation(),
validationSections: (config) =>
"use_blueprint" in config
? {}
: {
triggers: config.triggers,
conditions: config.conditions,
actions: config.actions,
},
};
private _undoRedoController = new UndoRedoController<AutomationConfig>(this, {
@@ -510,16 +516,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
@value-changed=${this._valueChanged}
@save-automation=${this._handleSaveAutomation}
>
${
this.errors
? html`<ha-alert
alert-type="error"
slot="alerts"
>
${this.errors}
</ha-alert>`
: nothing
}
${this.renderConfigErrorsAlert("alerts")}
</blueprint-automation-editor>
`
: html`
@@ -531,6 +528,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
.config=${this.config}
.disabled=${this.readOnly}
.saving=${this.saving}
.configErrors=${this.configErrors}
@value-changed=${this._valueChanged}
@save-automation=${this._handleSaveAutomation}
@editor-save=${this._handleSaveAutomation}
@@ -539,26 +537,17 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
<div class="alert-wrapper" slot="alerts">
${this._renderDeprecatedMigratedAlert()}
${
this.errors || stateObj?.state === UNAVAILABLE
stateObj?.state === UNAVAILABLE
? html`<ha-alert
alert-type="error"
.title=${
stateObj?.state === UNAVAILABLE
? this.hass.localize(
"ui.panel.config.automation.editor.unavailable"
)
: undefined
}
.title=${this.hass.localize(
"ui.panel.config.automation.editor.unavailable"
)}
>
${this.errors || this.validationErrors}
${
stateObj?.state === UNAVAILABLE
? html`<ha-svg-icon
slot="icon"
.path=${mdiRobotConfused}
></ha-svg-icon>`
: nothing
}
<ha-svg-icon
slot="icon"
.path=${mdiRobotConfused}
></ha-svg-icon>
</ha-alert>`
: nothing
}
@@ -637,6 +626,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
`
: this.mode === "yaml"
? html`${this._renderDeprecatedMigratedAlert()}
${this.renderConfigErrorsAlert()}
${
stateObj?.state === "off"
? html`
@@ -756,7 +746,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
entityRegistryUpdate: this.entityRegistryUpdate,
}
);
this._checkValidation();
this.checkValidation();
});
this.currentEntityId = this.entityId;
this.readOnly = true;
@@ -784,32 +774,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this.currentEntityId = automation?.entity_id;
}
private async _checkValidation() {
this.validationErrors = undefined;
if (!this.currentEntityId || !this.config) {
return;
}
const stateObj = this.hass.states[this.currentEntityId];
if (stateObj?.state !== UNAVAILABLE) {
return;
}
const validation = await validateConfig(this.hass, {
triggers: this.config.triggers,
conditions: this.config.conditions,
actions: this.config.actions,
});
this.validationErrors = (
Object.entries(validation) as Entries<typeof validation>
).map(([key, value]) =>
value.valid
? ""
: html`${this.hass.localize(
`ui.panel.config.automation.editor.${key}.name`
)}:
${value.error}<br />`
);
}
private _valueChanged(ev: ValueChangedEvent<AutomationConfig>) {
ev.stopPropagation();
const config = ev.detail.value;
@@ -839,7 +803,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
config: this.config,
entityRegistryUpdate: this.entityRegistryUpdate,
});
this.errors = undefined;
}
private _showInfo() {
@@ -929,7 +892,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
config: this.config!,
entityRegistryUpdate: this.entityRegistryUpdate,
});
this.errors = undefined;
}
protected async confirmUnsavedChanged(addHistory = true): Promise<boolean> {
@@ -1010,9 +972,8 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this._yamlEditor?.setValue(this.config);
}
this.readOnly = true;
this.errors = undefined;
} catch (err: any) {
this.errors = err.message;
showEditorToast(this, { message: err.message });
}
}
@@ -1125,7 +1086,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
private async _saveAutomation(id): Promise<void> {
this.saving = true;
this.validationErrors = undefined;
const config = this.config!;
let entityRegPromise: Promise<EntityRegistryEntry> | undefined;
if (this.entityRegistryUpdate !== undefined && !this.currentEntityId) {
@@ -1136,7 +1097,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
}
try {
await saveAutomationConfig(this.hass, id, this.config!);
await saveAutomationConfig(this.hass, id, config);
if (this.entityRegistryUpdate !== undefined) {
let entityId = this.currentEntityId;
@@ -1183,11 +1144,9 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this._markDirtyStateClean();
this.deprecatedConfigMigrated = false;
} catch (errors: any) {
this.errors = errors.body?.message || errors.error || errors.body;
showEditorToast(this, {
message: errors.body?.message || errors.error || errors.body,
});
this.clearConfigErrors();
} catch (errors: unknown) {
this.showSaveErrors(errors, config);
throw errors;
} finally {
this.saving = false;
@@ -114,6 +114,7 @@ import {
showConfirmationDialog,
} from "../../../dialogs/generic/show-dialog-box";
import "../../../layouts/hass-tabs-subpage-data-table";
import type { HaTabsSubpageDataTable } from "../../../layouts/hass-tabs-subpage-data-table";
import { SubscribeMixin } from "../../../mixins/subscribe-mixin";
import { haStyle } from "../../../resources/styles";
import type { HomeAssistant, Route, ServiceCallResponse } from "../../../types";
@@ -263,6 +264,9 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
@query("#overflow-menu") private _overflowMenu!: HaDropdown;
@query("hass-tabs-subpage-data-table", true)
private _dataTable!: HaTabsSubpageDataTable;
private _sizeController = new ResizeController(this, {
callback: (entries) => entries[0]?.contentRect.width,
});
@@ -762,6 +766,13 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
"ui.panel.config.automation.picker.bulk_actions.disable"
)}
</ha-dropdown-item>
<wa-divider></wa-divider>
<ha-dropdown-item value="delete_selected" variant="danger">
<ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.automation.picker.bulk_actions.delete_selected.button"
)}
</ha-dropdown-item>
</ha-dropdown>
${
!this.automations.length
@@ -1175,6 +1186,50 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
}
}
private _deleteSelected = () => {
// Only rows with an entity registry entry are selectable, so every selected
// automation has an ID. The backend still refuses the ones that aren't
// stored in automations.yaml, those end up in the failure alert.
const automations = this.automations.filter((automation) =>
this._selected.includes(automation.entity_id)
);
let failedCount = 0;
showConfirmationDialog(this, {
title: this.hass.localize(
"ui.panel.config.automation.picker.bulk_actions.delete_selected.confirm_title"
),
text: this.hass.localize(
"ui.panel.config.automation.picker.bulk_actions.delete_selected.confirm_text",
{ count: automations.length }
),
confirmText: this.hass.localize("ui.common.delete"),
dismissText: this.hass.localize("ui.common.cancel"),
destructive: true,
action: async () => {
const results = await Promise.allSettled(
automations.map((automation) =>
deleteAutomation(this.hass, automation.attributes.id!)
)
);
failedCount = rejectedItems(results).length;
this._dataTable.clearSelection();
},
}).then((confirmed) => {
if (confirmed && failedCount) {
showAlertDialog(this, {
title: this.hass.localize(
"ui.panel.config.automation.picker.bulk_actions.delete_selected.failed_title"
),
text: this.hass.localize(
"ui.panel.config.automation.picker.bulk_actions.delete_selected.failed",
{ count: failedCount }
),
});
}
});
};
private _duplicate = async (automation: AutomationItem) => {
try {
const config = await fetchAutomationFileConfig(
@@ -1546,6 +1601,10 @@ ${rejected
this._handleBulkDisable();
return;
}
if (value === "delete_selected") {
this._deleteSelected();
return;
}
if (value.startsWith("category_")) {
if (value === "category_create") {
@@ -5,15 +5,23 @@ import type {
TemplateResult,
} from "lit";
import { css, html } from "lit";
import { property, state } from "lit/decorators";
import { property, query, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { transform } from "../../../common/decorators/transform";
import { goBack, navigate } from "../../../common/navigate";
import { debounce } from "../../../common/util/debounce";
import { afterNextRender } from "../../../common/util/render-status";
import "../../../components/animation/ha-fade-in";
import "../../../components/ha-spinner"; // used by renderLoading() provided to both editors
import type { AutomationMigrationReport } from "../../../data/automation";
import {
parseConfigSaveError,
validateConfigErrors,
type ConfigValidationError,
type ValidationSectionKeys,
} from "../../../data/config";
import { fireRelatedContext, fullEntitiesContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { EntityRegistryEntry } from "../../../data/entity/entity_registry";
import {
showAlertDialog,
@@ -22,7 +30,28 @@ import {
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mixin";
import type { Constructor, HomeAssistant, Route } from "../../../types";
import { showToast } from "../../../util/toast";
import {
errorMessage,
errorsEqual,
mapErrorsToConfig,
NO_ERRORS,
rowPathsShifted,
} from "./automation-errors";
import { renderErrorsAlert } from "./automation-error-templates";
import type { EntityRegistryUpdate } from "./automation-save-dialog/show-dialog-automation-save";
import { showEditorToast } from "./editor-toast";
const CONFIG_ERRORS_TOAST_ID = "config-errors";
const REVALIDATE_DELAY = 500;
// Core reports errors in the config a blueprint generates at `use_blueprint`
const BLUEPRINT_PATH = ["use_blueprint"];
interface ErrorsEditorElement extends HTMLElement {
revealErrors(): Promise<void>;
}
/** Minimum config shape shared by both AutomationConfig and ScriptConfig. */
interface BaseEditorConfig {
@@ -82,7 +111,11 @@ export const automationScriptEditorStyles: CSSResult = css`
export interface EditorDomainHooks<TConfig> {
fetchFileConfig(hass: HomeAssistant, id: string): Promise<TConfig>;
normalizeConfig(raw: TConfig, report?: AutomationMigrationReport): TConfig;
checkValidation(): Promise<void>;
/** The parts of the config `validate_config` checks, none for blueprints. */
validationSections(
config: TConfig
): Partial<Record<"triggers" | "conditions" | "actions", unknown>>;
validationSectionKeys?: ValidationSectionKeys;
domain: "automation" | "script";
}
@@ -111,8 +144,6 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
@consume({ context: fullEntitiesContext, subscribe: true })
entityRegistry?: EntityRegistryEntry[];
@state() protected errors?: string;
@state() protected yamlErrors?: string;
@state() protected currentEntityId?: string;
@@ -125,7 +156,7 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
@state() protected deprecatedConfigMigrated = false;
@state() protected validationErrors?: (string | TemplateResult)[];
@state() protected configErrors: ConfigValidationError[] = NO_ERRORS;
@state() protected config?: TConfig;
@@ -157,6 +188,16 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
private _relatedContextAreaId?: string;
@query("manual-automation-editor, manual-script-editor")
private _errorsEditor?: ErrorsEditorElement;
// Validation responses of an older run are dropped
private _validationRun = 0;
// Errors may be hidden for a moment while core checks moved rows, the
// editor keeps revalidating until they are fixed or saved
private _errorsActive = false;
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (
@@ -165,6 +206,230 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
) {
this._setRelatedContext();
}
// Errors set in the same update already belong to the current config
if (
changedProps.has("config") &&
!changedProps.has("configErrors") &&
this._errorsActive
) {
// The YAML editor lists errors with their paths, it has no rows
if (
this.mode === "gui" &&
rowPathsShifted(changedProps.get("config"), this.config)
) {
// Until core checks the new paths, errors would show on wrong rows
const kept = this.config
? this._unvalidatedErrors(this.config, this.configErrors)
: NO_ERRORS;
if (!errorsEqual(kept, this.configErrors)) {
this.configErrors = kept.length ? kept : NO_ERRORS;
}
this._validateConfig();
} else {
this._revalidate();
}
}
}
public disconnectedCallback() {
super.disconnectedCallback();
// Pending validations must not touch errors or the toast anymore
this._validationRun++;
this._revalidate.cancel();
this._closeErrorsToast();
}
/** Shows the errors of saving `submitted`, the config sent to core. */
protected async showSaveErrors(err: unknown, submitted: TConfig) {
const { message, errors } = parseConfigSaveError(err);
if (!errors.length) {
this._showSaveFailedToast(message);
return;
}
this._validationRun++;
const submittedErrors = mapErrorsToConfig(submitted, errors);
// Rows moved while saving are checked again before showing their errors
this._setConfigErrors(
rowPathsShifted(submitted, this.config)
? this._unvalidatedErrors(submitted, submittedErrors)
: submittedErrors
);
// Shown before revalidating, so a later save that succeeds closes it
this._showSaveFailedToast(
errors.length === 1
? errorMessage(this.hass.localize, errors[0])
: this.hass.localize(
"ui.panel.config.automation.editor.errors.problems_found",
{ count: errors.length }
)
);
if (submitted !== this.config) {
await this._validateConfig();
}
await this._revealErrors();
}
protected async checkValidation() {
if (!this.currentEntityId || !this.config) {
return;
}
if (this.hass.states[this.currentEntityId]?.state !== UNAVAILABLE) {
return;
}
const config = this.config;
const sections = this.domainHooks.validationSections(config);
if (!Object.keys(sections).length) {
return;
}
const run = ++this._validationRun;
let errors: ConfigValidationError[];
try {
errors = await validateConfigErrors(
this.hass,
sections,
this.domainHooks.validationSectionKeys
);
} catch (_err: unknown) {
// The unavailable alert still shows, only the rows stay unmarked
return;
}
if (run !== this._validationRun || !errors.length) {
return;
}
const mapped = mapErrorsToConfig(config, errors);
if (config === this.config) {
this._setConfigErrors(mapped);
return;
}
// The editor changed the config meanwhile, e.g. when it turned a
// condition written as a string into an object
this._setConfigErrors(
rowPathsShifted(config, this.config) ? NO_ERRORS : mapped
);
await this._validateConfig();
}
private _setConfigErrors(errors: ConfigValidationError[]) {
this._errorsActive = true;
if (!errorsEqual(errors, this.configErrors)) {
this.configErrors = errors.length ? errors : NO_ERRORS;
}
}
/** Errors revalidating doesn't update, like an invalid mode from saving. */
private _unvalidatedErrors(
config: TConfig,
errors: ConfigValidationError[]
): ConfigValidationError[] {
const sectionKeys = this.domainHooks.validationSectionKeys ?? {};
const sections = Object.entries(
this.domainHooks.validationSections(config)
).map(([key, value]) => ({ key: sectionKeys[key] ?? key, value }));
return errors.filter((error) => {
const section = sections.find(({ key }) => key === error.path[0]);
// Core skips missing sections, so errors about one stay, but errors
// of its removed rows go
return (
!section || (section.value === undefined && error.path.length === 1)
);
});
}
private async _revealErrors() {
await this.updateComplete;
if (this.mode === "gui") {
await this._errorsEditor?.revealErrors();
}
}
/** All errors, for the editors that have no rows to show them on. */
protected renderConfigErrorsAlert(slot?: string) {
return renderErrorsAlert(
this.hass.localize,
this.configErrors,
BLUEPRINT_PATH,
slot
);
}
private _showSaveFailedToast(problems: string) {
showEditorToast(this, {
id: CONFIG_ERRORS_TOAST_ID,
message: this.hass.localize(
"ui.panel.config.automation.editor.errors.save_failed",
{ problems }
),
});
}
private _closeErrorsToast() {
// A removed editor can't reach the toast manager by bubbling
const host = this.isConnected
? this
: document.querySelector<HTMLElement>("home-assistant");
if (!host) {
return;
}
showToast(host, {
id: CONFIG_ERRORS_TOAST_ID,
message: "",
duration: 0,
});
}
// While errors are shown, fixed problems clear and new ones show while
// editing. Errors outside the validated sections, like an invalid mode,
// wait for the next save.
private _revalidate = debounce(() => {
this._validateConfig();
}, REVALIDATE_DELAY);
/** Validates the sections of the current config. */
private async _validateConfig() {
this._revalidate.cancel();
const config = this.config;
if (!config || !this._errorsActive) {
return;
}
const sections = this.domainHooks.validationSections(config);
// Blueprint inputs can't be validated on their own, so their errors
// only last until the next edit
if (!Object.keys(sections).length) {
this.clearConfigErrors();
return;
}
const sectionKeys = this.domainHooks.validationSectionKeys ?? {};
const run = ++this._validationRun;
let sectionErrors: ConfigValidationError[];
try {
sectionErrors = await validateConfigErrors(
this.hass,
sections,
sectionKeys
);
} catch (_err: unknown) {
return;
}
if (run !== this._validationRun || config !== this.config) {
return;
}
const errors = [
...this._unvalidatedErrors(config, this.configErrors),
...mapErrorsToConfig(config, sectionErrors),
];
if (!errors.length) {
this.clearConfigErrors();
return;
}
this._setConfigErrors(errors);
}
protected clearConfigErrors() {
this._errorsActive = false;
this._validationRun++;
this._revalidate.cancel();
this.configErrors = NO_ERRORS;
this._closeErrorsToast();
}
private _setRelatedContext(): void {
@@ -277,6 +542,7 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
protected async loadConfig(id: string) {
const hooks = this.domainHooks;
const domain = hooks.domain;
this.clearConfigErrors();
try {
const config = await hooks.fetchFileConfig(this.hass, id);
if (!this.isConnected) {
@@ -296,7 +562,7 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
entityRegistryUpdate: this.entityRegistryUpdate,
}
);
hooks.checkValidation();
this.checkValidation();
} catch (err: any) {
if (!this.isConnected) {
return;
@@ -1,3 +1,4 @@
import { ContextProvider } from "@lit/context";
import { css, html, LitElement, nothing, type PropertyValues } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { tinykeys } from "tinykeys";
@@ -5,23 +6,21 @@ import { consume } from "../../../common/decorators/consume";
import { fireEvent } from "../../../common/dom/fire_event";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { computeRTL } from "../../../common/util/compute_rtl";
import { pathEquals } from "../../../common/util/config-path";
import "../../../components/ha-snap-bottom-sheet";
import type { HaSnapBottomSheet } from "../../../components/ha-snap-bottom-sheet";
import {
isCondition,
isScriptField,
isTrigger,
type ActionSidebarConfig,
type ConditionSidebarConfig,
type OptionSidebarConfig,
type ScriptFieldSidebarConfig,
type SidebarConfig,
type TriggerSidebarConfig,
import type {
ActionSidebarConfig,
SidebarConfig,
} from "../../../data/automation";
import { manifestsContext } from "../../../data/context";
import type { DomainManifestLookup } from "../../../data/integration";
import { isTriggerList } from "../../../data/trigger";
import type { HomeAssistant } from "../../../types";
import {
automationPathContext,
automationRowRegistryContext,
type AutomationRowRegistry,
} from "./automation-path";
import "./sidebar/ha-automation-sidebar-action";
import type HaAutomationSidebarAction from "./sidebar/ha-automation-sidebar-action";
import "./sidebar/ha-automation-sidebar-condition";
@@ -61,6 +60,17 @@ export default class HaAutomationSidebar extends LitElement {
@consume({ context: manifestsContext, subscribe: true })
private _manifests?: DomainManifestLookup;
@consume({ context: automationRowRegistryContext })
private _registry?: AutomationRowRegistry;
// Editors in the sidebar are not inside their row, so they get its path here
private readonly _pathProvider = new ContextProvider(this, {
context: automationPathContext,
initialValue: [],
});
private _unsubscribeRegistry?: () => void;
@query("ha-snap-bottom-sheet")
private _bottomSheetElement?: HaSnapBottomSheet;
@@ -83,6 +93,28 @@ export default class HaAutomationSidebar extends LitElement {
private _tinykeysUnsub?: () => void;
public connectedCallback() {
super.connectedCallback();
// A row dragged to another place while it is open changes its path
this._unsubscribeRegistry = this._registry?.subscribe(() =>
this._syncPath()
);
}
protected willUpdate(changedProperties: PropertyValues<this>) {
super.willUpdate(changedProperties);
if (changedProperties.has("config")) {
this._syncPath();
}
}
private _syncPath() {
const path = this.config ? (this._registry?.selectedPath() ?? []) : [];
if (!pathEquals(path, this._pathProvider.value)) {
this._pathProvider.setValue(path);
}
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
if (
@@ -105,6 +137,8 @@ export default class HaAutomationSidebar extends LitElement {
disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeRegistry?.();
this._unsubscribeRegistry = undefined;
this._unregisterResizeHandlers();
this._tinykeysUnsub?.();
}
@@ -251,36 +285,12 @@ export default class HaAutomationSidebar extends LitElement {
}
private _getType() {
if (
(this.config as TriggerSidebarConfig)?.config &&
(isTrigger((this.config as TriggerSidebarConfig)?.config) ||
isTriggerList((this.config as TriggerSidebarConfig)?.config))
) {
return "trigger";
}
if (isCondition((this.config as ConditionSidebarConfig)?.config)) {
return "condition";
}
if (
(this.config as ScriptFieldSidebarConfig)?.config &&
isScriptField((this.config as ScriptFieldSidebarConfig)?.config)
) {
return (this.config as ScriptFieldSidebarConfig)?.config.selector
if (this.config?.type === "script-field") {
return this.config.config.selector
? "script-field-selector"
: "script-field";
}
// option is a building block; its config only carries the option itself
const optionConfig = (this.config as OptionSidebarConfig)?.config;
if (this.config && (!optionConfig || "option" in optionConfig)) {
return "option";
}
if ((this.config as ActionSidebarConfig)?.config.action) {
return "action";
}
return undefined;
return this.config?.type;
}
public triggerCloseSidebar(ev?: CustomEvent) {
@@ -2,8 +2,8 @@ import { provide } from "@lit/context";
import { mdiContentSave } from "@mdi/js";
import {
html,
nothing,
type LitElement,
type nothing,
type PropertyValues,
type TemplateResult,
} from "lit";
@@ -16,6 +16,7 @@ import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import { replaceCurrentUrl } from "../../../common/navigate";
import { constructUrlCurrentPath } from "../../../common/url/construct-url";
import { nextRender } from "../../../common/util/render-status";
import {
extractSearchParam,
removeSearchParam,
@@ -24,6 +25,7 @@ import "../../../components/ha-button";
import "../../../components/ha-icon-button";
import "../../../components/ha-markdown";
import type { SidebarConfig } from "../../../data/automation";
import type { ConfigValidationError } from "../../../data/config";
import {
dirtyStateContext,
type DirtyStateContext,
@@ -34,10 +36,20 @@ import type {
ValueChangedEvent,
} from "../../../types";
import { showToast } from "../../../util/toast";
import {
automationErrorsContext,
errorOwner,
errorsEqual,
NO_ERRORS,
ownedErrors,
} from "./automation-errors";
import { renderErrorsAlert } from "./automation-error-templates";
import {
AutomationRowRegistry,
automationRowRegistryContext,
type AutomationPathRow,
} from "./automation-path";
import { scrollRowIntoView } from "./scroll-row-into-view";
import "./ha-automation-sidebar";
import type HaAutomationSidebar from "./ha-automation-sidebar";
@@ -90,6 +102,20 @@ export const ManualEditorMixin = <TConfig>(
@provide({ context: automationRowRegistryContext })
protected rowRegistry = new AutomationRowRegistry();
/** The validation errors of the config, paths from its root. */
@property({ attribute: false })
public configErrors: ConfigValidationError[] = NO_ERRORS;
// The errors rows show. A row the user opened without errors gets no new
// ones while it is open, so a row being filled in isn't marked yet.
@provide({ context: automationErrorsContext })
@state()
private _shownErrors: ConfigValidationError[] = NO_ERRORS;
private _sidebarRow?: AutomationPathRow;
private _sidebarRowHadErrors = false;
declare protected collapsableElements?: NodeListOf<
Element & {
expandAll(): void;
@@ -103,16 +129,78 @@ export const ManualEditorMixin = <TConfig>(
throw new Error("Not implemented");
};
private _unsubscribeRows?: () => void;
// Rows register while they render, so errors only count as without a
// row once the rows had a frame to render
@state() private _rowsRendered = false;
public connectedCallback() {
super.connectedCallback();
window.addEventListener("paste", this.handlePaste);
// Which errors have a row changes as rows render
this._unsubscribeRows = this.rowRegistry.subscribe(() => {
if (this.configErrors.length) {
this.requestUpdate();
}
});
}
public disconnectedCallback() {
window.removeEventListener("paste", this.handlePaste);
this._unsubscribeRows?.();
this._unsubscribeRows = undefined;
super.disconnectedCallback();
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
// Also runs when rows render, as they decide which row owns an error
if (
changedProps.has("sidebarConfig") ||
this.configErrors.length ||
this._shownErrors.length
) {
this._updateShownErrors();
}
}
private _updateShownErrors() {
const selectedPath = this.sidebarConfig
? this.rowRegistry.selectedPath()
: undefined;
const row = selectedPath
? this.rowRegistry.rowAt(selectedPath)
: undefined;
if (row !== this._sidebarRow) {
this._sidebarRow = row;
this._sidebarRowHadErrors =
!!row &&
ownedErrors(this.rowRegistry, this.configErrors, row).length > 0;
}
const shown =
row && !this._sidebarRowHadErrors
? this.configErrors.filter(
(error) => errorOwner(this.rowRegistry, error) !== row
)
: this.configErrors;
if (!errorsEqual(shown, this._shownErrors)) {
this._shownErrors = shown.length ? shown : NO_ERRORS;
}
}
private _renderUnownedErrors() {
if (!this._rowsRendered) {
return nothing;
}
return renderErrorsAlert(
this.hass.localize,
this._shownErrors.filter(
(error) => !errorOwner(this.rowRegistry, error)
)
);
}
protected renderContent(): TemplateResult | typeof nothing {
throw new Error("Not implemented");
}
@@ -141,7 +229,7 @@ export const ManualEditorMixin = <TConfig>(
>
<div class="content">
<slot name="alerts"></slot>
${this.renderContent()}
${this._renderUnownedErrors()} ${this.renderContent()}
</div>
<div class="fab-positioner">
<ha-button
@@ -179,6 +267,9 @@ export const ManualEditorMixin = <TConfig>(
protected firstUpdated(changedProps: PropertyValues<this>): void {
super.firstUpdated(changedProps);
nextRender().then(() => {
this._rowsRendered = true;
});
this.style.setProperty(
"--sidebar-dynamic-width",
@@ -303,6 +394,57 @@ export const ManualEditorMixin = <TConfig>(
});
}
/**
* Expands the rows along the path of every error, then scrolls to the
* first one and opens it in the sidebar. Does nothing while a row with an
* error is open, so the user stays where they are.
*/
public async revealErrors() {
// Errors to reveal also show on the open row
this._sidebarRow = undefined;
this.requestUpdate();
await this.updateComplete;
const errorRows = () =>
this.configErrors.map((error) =>
this.rowRegistry.rowsAlong(error.path)
);
const owners = (rows: AutomationPathRow[][]) =>
rows
.map((along) => along[along.length - 1])
.filter((owner) => owner !== undefined);
let rows = errorRows();
if (owners(rows).some((owner) => owner.selected)) {
return;
}
const depthOf = (along: AutomationPathRow[][]) =>
along.reduce((sum, path) => sum + path.length, 0);
// Collapsed rows don't render their children, so expand one level at a
// time until no deeper row shows up
let depth = -1;
while (depthOf(rows) > depth) {
depth = depthOf(rows);
rows.flat().forEach((row) => row.expand());
// eslint-disable-next-line no-await-in-loop
await nextRender();
rows = errorRows();
}
// Errors aren't in config order, so take the topmost row
const first = owners(rows).reduce<AutomationPathRow | undefined>(
(top, row) =>
!top ||
row.getBoundingClientRect().top < top.getBoundingClientRect().top
? row
: top,
undefined
);
if (!first) {
return;
}
first.openSidebar();
await nextRender();
scrollRowIntoView(first);
}
public expandAll() {
this.collapsableElements?.forEach((element) => {
element.expandAll();
@@ -65,6 +65,7 @@ import {
import "../trigger/ha-automation-trigger-references";
import { getUiSupportWarnings, isConfigObject } from "../ui-support";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
@customElement("ha-automation-option-row")
export default class HaAutomationOptionRow extends LitElement {
@@ -127,6 +128,10 @@ export default class HaAutomationOptionRow extends LitElement {
return this._selected;
}
get collapsed() {
return this._collapsed;
}
public static checkUiSupport(
_localize: LocalizeFunc,
option: Option
@@ -272,6 +277,12 @@ export default class HaAutomationOptionRow extends LitElement {
}
</h3>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
${
@@ -502,6 +513,7 @@ export default class HaAutomationOptionRow extends LitElement {
.collapsed=${this._collapsed}
.selected=${this._selected}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
@click=${this._toggleSidebar}
@toggle-collapsed=${this._toggleCollapse}
@delete-row=${this._removeOption}
@@ -725,6 +737,7 @@ export default class HaAutomationOptionRow extends LitElement {
const sidebarOption = option ?? this.option;
this._sidebarOption = sidebarOption;
fireEvent(this, "open-sidebar", {
type: "option",
save: (value) => {
this._saveYamlOption(value);
},
@@ -1,3 +1,4 @@
import { provide } from "@lit/context";
import { mdiClose, mdiDotsVertical } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators";
@@ -12,6 +13,12 @@ import "../../../../components/ha-icon-button";
import { ScrollableFadeMixin } from "../../../../mixins/scrollable-fade-mixin";
import { haStyleScrollbar } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { renderErrorsAlert } from "../automation-error-templates";
import {
automationInlineErrorFieldsContext,
AutomationFieldErrorsController,
InlineErrorFields,
} from "../automation-field-errors";
import "../ha-automation-editor-warning";
export interface SidebarOverflowMenuEntry {
@@ -44,11 +51,22 @@ export default class HaAutomationSidebarCard extends ScrollableFadeMixin(
@query(".card-content") private _contentElement!: HTMLDivElement;
private readonly _errors = new AutomationFieldErrorsController(this);
@provide({ context: automationInlineErrorFieldsContext })
protected inlineErrorFields = new InlineErrorFields(() =>
this.requestUpdate()
);
protected get scrollableElement(): HTMLElement | null {
return this._contentElement;
}
protected render() {
const errors = this._errors.rowErrors.filter((error) => {
const field = error.path.slice(this._errors.path.length);
return !field.length || !this.inlineErrorFields.has(field);
});
return html`
<ha-card
outlined
@@ -90,6 +108,7 @@ export default class HaAutomationSidebarCard extends ScrollableFadeMixin(
</ha-automation-editor-warning>`
: nothing
}
${renderErrorsAlert(this.hass.localize, errors, this._errors.path)}
<div class="card-content ha-scrollbar">
<slot></slot>
${this.renderScrollableFades(this.isWide)}
@@ -148,6 +167,10 @@ export default class HaAutomationSidebarCard extends ScrollableFadeMixin(
padding-bottom: max(var(--safe-area-inset-bottom, 0px), 32px);
}
.errors-alert {
margin: 0 var(--ha-space-4) var(--ha-space-4);
}
.fade-top {
top: var(--ha-space-17);
}
@@ -100,12 +100,9 @@ export default class HaAutomationSidebarCondition extends LitElement {
"ui.panel.config.automation.editor.conditions.condition"
);
const domain =
"condition" in this.config.config &&
getConditionDomain(this.config.config.condition);
const domain = typeof type === "string" && getConditionDomain(type);
const conditionName =
"condition" in this.config.config &&
getConditionObjectId(this.config.config.condition);
typeof type === "string" && getConditionObjectId(type);
const title =
this.hass.localize(
@@ -93,12 +93,12 @@ export default class HaAutomationSidebarTrigger extends LitElement {
"ui.panel.config.automation.editor.triggers.trigger"
);
const domain =
const platform =
"trigger" in this.config.config &&
getTriggerDomain(this.config.config.trigger);
const triggerName =
"trigger" in this.config.config &&
getTriggerObjectId(this.config.config.trigger);
typeof this.config.config.trigger === "string" &&
this.config.config.trigger;
const domain = platform && getTriggerDomain(platform);
const triggerName = platform && getTriggerObjectId(platform);
const title =
this.hass.localize(
+12 -1
View File
@@ -116,7 +116,8 @@ export const rowStyles = css`
.note-indicator {
color: var(--ha-color-on-neutral-normal);
}
.note-indicator + ha-tooltip::part(body) {
.note-indicator + ha-tooltip::part(body),
.error-indicator + ha-tooltip::part(body) {
cursor: default;
max-width: 300px;
}
@@ -124,6 +125,11 @@ export const rowStyles = css`
white-space: pre-wrap;
margin: 0;
}
.error-indicator {
color: var(--ha-color-on-danger-quiet);
padding: var(--ha-space-3);
}
`;
export const editorStyles = css`
@@ -280,6 +286,11 @@ export const manualEditorStyles = css`
.header a {
color: var(--secondary-text-color);
}
.errors-alert {
display: block;
margin-bottom: var(--ha-space-2);
}
`;
export const automationRowsStyles = css`
@@ -30,6 +30,7 @@ import {
type BlueprintTriggersStatus,
} from "./automation-trigger-id";
import { preserveAutomationRowKeys } from "../ha-automation-sortable-list-mixin";
import { isConfigObject } from "../ui-support";
interface AutomationTriggerControllerOptions {
/** Read the editor's current configuration, including after an awaited dialog. */
@@ -149,23 +150,18 @@ export class AutomationTriggerController implements ReactiveController {
private _isTriggerConditionSidebarActive(
sidebarConfig: SidebarConfig | undefined
): boolean {
if (!sidebarConfig || !("config" in sidebarConfig)) {
return false;
if (sidebarConfig?.type === "condition") {
return sidebarConfig.config.condition === "trigger";
}
const config = sidebarConfig.config as
{ condition?: unknown } | { action?: unknown };
if ("condition" in config && config.condition === "trigger") {
return true;
if (sidebarConfig?.type === "action") {
const action = sidebarConfig.config.action;
return (
isConfigObject(action) &&
"condition" in action &&
action.condition === "trigger"
);
}
// A row can hold any YAML, so `action` may be a service name instead of
// the wrapped action of an action sidebar.
return !!(
"action" in config &&
typeof config.action === "object" &&
config.action &&
"condition" in config.action &&
config.action.condition === "trigger"
);
return false;
}
/**
@@ -121,6 +121,7 @@ import "./types/ha-automation-trigger-zone";
import { renderCtrlOrCmd } from "../../../../common/keyboard/ctrl-or-cmd";
import { scrollRowIntoView } from "../scroll-row-into-view";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
import { targetExpandGroupContext } from "../../../../components/target-picker/target-expand-group-context";
export interface TriggerElement extends LitElement {
@@ -400,6 +401,12 @@ export default class HaAutomationTriggerRow extends LitElement {
)}
</ha-automation-row-event-chip>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
<ha-dropdown
@@ -664,6 +671,7 @@ export default class HaAutomationTriggerRow extends LitElement {
.selected=${this._selected}
.highlight=${this.highlight}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
.dim=${this._triggered}
@click=${this._toggleSidebar}
>${
@@ -846,6 +854,7 @@ export default class HaAutomationTriggerRow extends LitElement {
public openSidebar(trigger?: Trigger): void {
trigger = trigger || this.trigger;
fireEvent(this, "open-sidebar", {
type: "trigger",
save: (value) => {
fireEvent(this, "value-changed", { value });
},
@@ -1211,6 +1220,10 @@ export default class HaAutomationTriggerRow extends LitElement {
};
public expand() {
// Rows that open in the sidebar have nothing to expand
if (this.optionsInSidebar) {
return;
}
this.updateComplete.then(() => {
this.shadowRoot!.querySelector("ha-expansion-panel")!.expanded = true;
});
@@ -8,9 +8,14 @@ import type { TriggerElement } from "../ha-automation-trigger-row";
import "../../../../../components/ha-form/ha-form";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-calendar")
export class HaCalendarTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["entity_id", "event", "offset"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: CalendarTrigger;
@@ -65,6 +70,8 @@ export class HaCalendarTrigger extends LitElement implements TriggerElement {
const schema = this._schema(this.hass.localize);
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.trigger}
.hass=${this.hass}
@@ -29,9 +29,18 @@ import {
} from "../../../../../data/device/device_registry";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { HomeAssistant } from "../../../../../types";
import {
deviceAutomationErrorText,
deviceErrorText,
} from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-device")
export class HaDeviceTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["device_id", "domain"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Object }) public trigger!: DeviceTrigger;
@@ -136,12 +145,20 @@ export class HaDeviceTrigger extends LitElement {
}
protected render() {
const deviceError = this._fieldErrors.fieldError("device_id");
const automationError = this._fieldErrors.fieldError("domain");
const deviceId = this._deviceId || this.trigger.device_id;
return html`
<ha-device-picker
.value=${deviceId}
.replacementDeviceIds=${this._replacementDeviceIds}
.invalid=${!!deviceError}
.errorMessage=${
deviceError
? deviceErrorText(this.hass.localize, deviceError)
: undefined
}
@value-changed=${this._devicePicked}
.disabled=${this.disabled}
.label=${this.hass.localize(
@@ -149,6 +166,16 @@ export class HaDeviceTrigger extends LitElement {
)}
></ha-device-picker>
<ha-device-trigger-picker
.invalid=${!!automationError}
.errorMessage=${
automationError
? deviceAutomationErrorText(
this.hass.localize,
"triggers",
automationError
)
: undefined
}
.value=${this.trigger}
.deviceId=${deviceId}
@value-changed=${this._deviceTriggerPicked}
@@ -7,9 +7,14 @@ import type { GeoLocationTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-geo_location")
export class HaGeolocationTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["source", "zone", "event"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: GeoLocationTrigger;
@@ -55,6 +60,8 @@ export class HaGeolocationTrigger extends LitElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${this._schema(this.hass.localize)}
.data=${this.trigger}
.hass=${this.hass}
@@ -7,9 +7,14 @@ import type { HassTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-homeassistant")
export class HaHassTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["event"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: HassTrigger;
@@ -51,6 +56,8 @@ export class HaHassTrigger extends LitElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${this._schema(this.hass.localize)}
.data=${this.trigger}
.hass=${this.hass}
@@ -4,6 +4,7 @@ import memoizeOne from "memoize-one";
import { ensureArray } from "../../../../../common/array/ensure-array";
import { fireEvent } from "../../../../../common/dom/fire_event";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { NumericStateTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
@@ -183,6 +184,17 @@ const SCHEMA = [
@customElement("ha-automation-trigger-numeric_state")
export class HaNumericStateTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: [
"entity_id",
"attribute",
"value_template",
"above",
"below",
"for",
],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: NumericStateTrigger;
@@ -230,6 +242,8 @@ export class HaNumericStateTrigger extends LitElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA}
@@ -10,6 +10,7 @@ import "../../../../../components/ha-icon-button";
import type { PersistentNotificationTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { TriggerElement } from "../ha-automation-trigger-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const DEFAULT_UPDATE_TYPES = ["added", "removed"];
const DEFAULT_NOTIFICATION_ID = "";
@@ -19,6 +20,10 @@ export class HaPersistentNotificationTrigger
extends LitElement
implements TriggerElement
{
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["notification_id", "update_type"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false })
@@ -80,6 +85,8 @@ export class HaPersistentNotificationTrigger
const schema = this._schema(this.hass.localize);
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.trigger}
.hass=${this.hass}
@@ -23,6 +23,9 @@ import {
} from "../../../../../data/trigger";
import type { HomeAssistant } from "../../../../../types";
import { documentationUrl } from "../../../../../util/documentation-url";
import "../../../../../components/ha-input-helper-text";
import { targetErrorText } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import { targetExpandGroupContext } from "../../../../../components/target-picker/target-expand-group-context";
const showOptionalToggle = (field: TriggerDescription["fields"][string]) =>
@@ -43,6 +46,10 @@ export class HaPlatformTrigger extends LitElement {
@provide({ context: targetExpandGroupContext })
protected _targetExpandGroup = false;
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["target"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: PlatformTrigger;
@@ -226,6 +233,7 @@ export class HaPlatformTrigger extends LitElement {
></ha-selector>`
: nothing
}
${this._renderTargetError()}
${
shouldRenderDataYaml
? html`<ha-yaml-editor
@@ -250,6 +258,15 @@ export class HaPlatformTrigger extends LitElement {
`;
}
private _renderTargetError() {
const error = this._fieldErrors.fieldError("target");
return error
? html`<ha-input-helper-text class="target-error">
${targetErrorText(this.hass.localize, error)}
</ha-input-helper-text>`
: nothing;
}
private _targetSelector = memoizeOne(
(targetSelector: TargetSelector["target"] | null | undefined) =>
targetSelector ? { target: { ...targetSelector } } : { target: {} }
@@ -559,6 +576,10 @@ export class HaPlatformTrigger extends LitElement {
1px solid var(--divider-color)
);
}
.target-error {
color: var(--ha-color-on-danger-quiet);
padding-bottom: var(--ha-space-2);
}
ha-yaml-editor {
padding: var(--ha-space-4) 0;
}
@@ -20,6 +20,7 @@ import { hasTemplate } from "../../../../../common/string/has-template";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import { ANY_STATE_VALUE } from "../../../../../components/entity/const";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type {
HaFormSchema,
SchemaUnion,
@@ -57,6 +58,10 @@ const stateTriggerStruct = assign(
@customElement("ha-automation-trigger-state")
export class HaStateTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["entity_id", "attribute", "from", "to", "for"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: StateTrigger;
@@ -311,6 +316,8 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -8,9 +8,14 @@ import type { TriggerElement } from "../ha-automation-trigger-row";
import "../../../../../components/ha-form/ha-form";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-sun")
export class HaSunTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["event", "offset"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: SunTrigger;
@@ -55,6 +60,8 @@ export class HaSunTrigger extends LitElement implements TriggerElement {
const schema = this._schema(this.hass.localize);
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.trigger}
.hass=${this.hass}
@@ -3,6 +3,7 @@ import { customElement, property } from "lit/decorators";
import type { TemplateTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import { fireEvent } from "../../../../../common/dom/fire_event";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
@@ -25,6 +26,10 @@ const SCHEMA = [
@customElement("ha-automation-trigger-template")
export class HaTemplateTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["value_template", "for"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: TemplateTrigger;
@@ -54,6 +59,8 @@ export class HaTemplateTrigger extends LitElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA}
@@ -30,6 +30,9 @@ import type { FrontendLocaleData } from "../../../../../data/translation";
import type { HomeAssistant } from "../../../../../types";
import { baseTriggerStruct } from "../../structs";
import type { TriggerElement } from "../ha-automation-trigger-row";
import type { ConfigValidationError } from "../../../../../data/config";
import { errorMessage } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const MODE_TIME = "time";
const MODE_ENTITY = "entity";
@@ -53,6 +56,10 @@ const timeTriggerStruct = assign(
@customElement("ha-automation-trigger-time")
export class HaTimeTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["at", "weekday"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: TimeTrigger;
@@ -189,6 +196,42 @@ export class HaTimeTrigger extends LitElement implements TriggerElement {
}
);
// The form shows `at` as a time, or as an entity and its offset
private _formFieldError = (
field: string
): ConfigValidationError | undefined => {
if (field === "offset") {
return this._fieldErrors.errorsAt(["at", "offset"])[0];
}
if (field === "time" || field === "entity") {
return this._fieldErrors
.errorsAt(["at"])
.find(
(error) => error.path[this._fieldErrors.path.length + 1] !== "offset"
);
}
return this._fieldErrors.fieldError(field);
};
private _formErrors(mode: typeof MODE_TIME | typeof MODE_ENTITY) {
const { at, ...fields } = this._fieldErrors.fields;
if (at === undefined) {
return this._fieldErrors.fields;
}
const atField = mode === MODE_TIME ? "time" : "entity";
const atError = this._formFieldError(atField);
const offsetError = this._formFieldError("offset");
return {
...fields,
...(atError
? { [atField]: errorMessage(this.hass.localize, atError) }
: {}),
...(offsetError
? { offset: errorMessage(this.hass.localize, offsetError) }
: {}),
};
}
protected render() {
const at = this.trigger.at;
@@ -205,6 +248,11 @@ export class HaTimeTrigger extends LitElement implements TriggerElement {
return html`
<ha-form
.error=${this._formErrors(data.mode)}
.computeError=${this._fieldErrors.formError(
this._computeLabelCallback,
this._formFieldError
)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -6,6 +6,7 @@ import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { TimePatternTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { TriggerElement } from "../ha-automation-trigger-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const SCHEMA = [
{ name: "hours", selector: { text: {} } },
@@ -15,6 +16,10 @@ const SCHEMA = [
@customElement("ha-automation-trigger-time_pattern")
export class HaTimePatternTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["hours", "minutes", "seconds"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: TimePatternTrigger;
@@ -28,6 +33,8 @@ export class HaTimePatternTrigger extends LitElement implements TriggerElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.schema=${SCHEMA}
.data=${this.trigger}
@@ -514,6 +514,7 @@ export class HaConfigDeviceDashboard extends LitElement {
? computeDeviceNameDisplay(familyParentDevice, this.hass.localize)
: undefined,
firmware_version: device.sw_version || undefined,
serial_number: device.serial_number || undefined,
battery_entity: [
this._batteryEntity(device.id, deviceEntityLookup),
this._batteryChargingEntity(device.id, deviceEntityLookup),
@@ -656,6 +657,13 @@ export class HaConfigDeviceDashboard extends LitElement {
defaultHidden: true,
minWidth: "120px",
},
serial_number: {
title: localize("ui.panel.config.devices.data_table.serial_number"),
sortable: true,
filterable: true,
defaultHidden: true,
minWidth: "120px",
},
battery_entity: {
title: localize("ui.panel.config.devices.data_table.battery"),
showNarrow: true,
@@ -7,14 +7,11 @@ import {
mdiDotsVertical,
mdiEye,
mdiEyeOff,
mdiEyeOutline,
mdiMenuDown,
mdiMicrophoneMessage,
mdiMicrophoneMessageOff,
mdiPencilOff,
mdiPlus,
mdiPower,
mdiPulse,
mdiRestore,
mdiRestoreAlert,
mdiToggleSwitch,
@@ -78,7 +75,7 @@ import "../../../components/ha-filter-floor-areas";
import "../../../components/ha-filter-integrations";
import "../../../components/ha-filter-labels";
import "../../../components/ha-filter-states";
import type { FilterStateItem } from "../../../components/ha-filter-states";
import type { FilterStateOption } from "../../../components/ha-filter-states";
import "../../../components/ha-filter-voice-assistants";
import "../../../components/ha-icon";
import "../../../components/ha-icon-button";
@@ -324,59 +321,36 @@ export class HaConfigEntities extends LitElement {
// The icons of the options match the ones of the status column and of the
// actions for the selected entities
private _states = memoize((localize: LocalizeFunc): FilterStateItem[] => [
private _states = memoize((localize: LocalizeFunc): FilterStateOption[] => [
{
value: "availability",
label: localize("ui.panel.config.entities.picker.headers.availability"),
iconPath: mdiPulse,
options: [
{
value: "available",
label: localize("ui.panel.config.entities.picker.status.available"),
iconPath: mdiCheckCircle,
},
{
value: "unavailable",
label: localize("ui.panel.config.entities.picker.status.unavailable"),
iconPath: mdiAlertCircle,
},
],
value: "available",
label: localize("ui.panel.config.entities.picker.status.available"),
iconPath: mdiCheckCircle,
},
{
value: "activation",
label: localize(
"ui.panel.config.entities.picker.status_pairs.activation"
),
iconPath: mdiPower,
options: [
{
value: "enabled",
label: localize("ui.panel.config.entities.picker.status.enabled"),
iconPath: mdiToggleSwitch,
},
{
value: "disabled",
label: localize("ui.panel.config.entities.picker.status.disabled"),
iconPath: mdiToggleSwitchOffOutline,
},
],
value: "unavailable",
label: localize("ui.panel.config.entities.picker.status.unavailable"),
iconPath: mdiAlertCircle,
},
{
value: "visibility",
label: localize("ui.panel.config.entities.picker.headers.visibility"),
iconPath: mdiEyeOutline,
options: [
{
value: "visible",
label: localize("ui.panel.config.entities.picker.status.visible"),
iconPath: mdiEye,
},
{
value: "hidden",
label: localize("ui.panel.config.entities.picker.status.hidden"),
iconPath: mdiEyeOff,
},
],
value: "enabled",
label: localize("ui.panel.config.entities.picker.status.enabled"),
iconPath: mdiToggleSwitch,
},
{
value: "disabled",
label: localize("ui.panel.config.entities.picker.status.disabled"),
iconPath: mdiToggleSwitchOffOutline,
},
{
value: "visible",
label: localize("ui.panel.config.entities.picker.status.visible"),
iconPath: mdiEye,
},
{
value: "hidden",
label: localize("ui.panel.config.entities.picker.status.hidden"),
iconPath: mdiEyeOff,
},
{
value: "readonly",
@@ -0,0 +1,84 @@
import type { IFuseOptions } from "fuse.js";
import type { HaListVirtualizedItem } from "../../../components/list/ha-list-virtualized";
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 ||
(categories || []).some((slug) =>
subcategory
? slug === `${category}.${subcategory}`
: slug === category || slug.startsWith(`${category}.`)
);
File diff suppressed because it is too large. Load diff
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more