Compare commits

..
42 Commits
Author SHA1 Message Date
Bram Kragten 088640642c Bumped version to 20261125.4 2026-12-02 13:44:49 +01:00
WendelinandClaude Opus 5.5 0819c80044 Fix plural forms being ignored in many languages (#56347)
* Keep the native Intl.PluralRules so plural forms work in every language

@formatjs/intl-pluralrules 7.1 and @formatjs/intl-numberformat 10.1 added a
should-polyfill check for formatting numeric strings with
trailingZeroDisplay: "stripToMinimum", which current browsers lack. Every
browser then replaced its native Intl.PluralRules with the polyfill, which
only carries English data, so languages like Russian and Polish lost their
"few" and "many" plural forms. Use our own checks without that feature, as
Home Assistant only passes numbers.

Fixes #56345

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

* Trim the Intl polyfill check comments and test

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

* Remove the unused FormatJS should-polyfill paths from tsconfig

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

---------

Co-authored-by: Claude <[email protected]>
2026-12-02 13:44:35 +01:00
Lazizbek Ergashev bb0c3bcd80 Keep visibility when an or matches despite an error in another branch (#56336) 2026-12-02 13:44:34 +01:00
Bram Kragten 0f24280606 Bumped version to 20261125.3 2026-12-02 10:11:58 +01:00
WendelinandClaude Opus 5.5 164cddaeb2 Group discovered devices by integration in the add dialog (#56315)
* Group discovered devices by integration in the add dialog

An integration with more than one discovered device now shows one row
with a count, which opens a page with all its discovered devices.
Discovered flows also show the integration's name instead of its domain
when it has no translated title.

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

* Use nextRender to focus after the discovered group changes

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

* Remove an unneeded comment

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

* Remove the count badge from discovered groups

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 10:05:25 +01:00
Paul Bottein 3fbd704245 Add capabilities to the entity selector filter (#56305)
* Add capabilities to the entity selector filter

* Test the capabilities entity filter
2026-12-02 10:05:24 +01:00
WendelinandClaude Opus 5.5 f50a0a0e6c Keep the camera stream and zoom when going full screen (#56293)
* Keep the camera zoom when entering or leaving full screen

The player refits the zoom whenever its size changes, so it keeps the part
of the picture in the middle instead of resetting it.

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

* Keep the camera stream when entering full screen in the companion apps

The Android app hides the page for a moment while it enters full screen.
The WebRTC and HLS players stop the stream right away when the page gets
hidden in the companion apps, so entering full screen restarted it, which
can take a while or stall over remote connections, and the paused video
showed the play button.

Entering full screen with the player's button now lets the first hidden
page within a second through with a short delayed clean up, and the player
plays on if the app paused the video. Leaving full screen, locking the
phone or leaving the app still stop the streams right away.

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

* Resume the camera only once after entering full screen

So a pause in the iPhone's own full screen controls stays paused.

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

* Test the full screen entering window

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 10:05:23 +01:00
WendelinandClaude Opus 5.5 24ea197e34 Always hide the camera player controls after a few seconds (#56291)
* Always hide the camera player controls after a few seconds

Hover only keeps the controls after mouse input, as a tapped button stays
hovered on touch screens. Focus only keeps them after keyboard input, as
focus moved by a script can look like keyboard focus. The hide timer also
starts again when the player is added back to the page.

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

* Capture the camera player's input listeners

The options on a listener object are ignored by addEventListener, so the
listeners didn't capture and missed key presses stopped by dialogs.

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

* Keep the camera player controls for keyboard focus on mouse moves

Moving the mouse made the player forget the keyboard input, so a control
focused with the keyboard could hide. A click still changes it.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 10:05:22 +01:00
Bram KragtenandClaude Opus 5.5 84ecc939fa Fix the remote access card title and the webhooks help link (#56290)
Fix remote access card title and webhooks help link

The remote access card used "Remote connection" while its page, the
overview row and onboarding all say "Remote access". Use the page title
for the card and its switch, and drop the unused string.

The webhooks "Learn more" link pointed to nabucasa.com/config/webhooks
without a trailing slash, which returns a 404. Only the form with the
slash redirects to the support article, like the other Nabu Casa links.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 10:05:20 +01:00
David Kennedy df40f11a14 Mark "Add user" dialog fields for password managers (#56180) 2026-12-02 10:05:19 +01:00
Bram Kragten 14034dda2d Bumped version to 20261125.2 2026-11-30 17:28:43 +01:00
Paul Bottein 47582923aa Keep the camera stream details in sync with the player (#56286) 2026-11-30 17:26:26 +01:00
WendelinandClaude Opus 5.5 75555390a1 Keep MJPEG picture in picture updating in Firefox (#56282)
Firefox only draws the first frame of an MJPEG image into a canvas, so
the picture in picture video froze. A bitmap of the image has the
current frame.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:25 +01:00
WendelinandClaude Opus 5.5 9e39b72de4 Show a placeholder instead of a broken image for cameras (#56271)
* Show a placeholder instead of a broken image for cameras

Picture cards show the camera placeholder instead of the broken image
when the camera is unavailable or its picture fails to load, and stop
requesting pictures while the camera is unavailable.

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

* Show the camera placeholder when a live MJPEG picture fails

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:24 +01:00
WendelinandClaude Opus 5.5 2ae815f1fd Simplify the camera stream badge and handle unavailable cameras (#56270)
* Simplify the camera stream badge and handle unavailable cameras

The badge only shows the state of the stream: Live, Connecting,
Unavailable or Disconnected. The protocol stays in the connection dialog.

Unavailable cameras don't start a stream. The player and the picture
cards show a camera-off placeholder instead of a broken image.

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

* Move the picture card placeholder to its own pull request

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

* Keep the unavailable placeholder while Home Assistant is disconnected

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

* Skip the camera capabilities while unavailable and explain Disconnected

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:22 +01:00
Marcin BauerandClaude Fable 5.2 92045529e2 Replace brand titles in All brands with the brand name on each card (#56262)
Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-30 17:26:21 +01:00
Jonathan DilksandClaude Opus 5.5 baaf5d1503 Fix pause button size in narrow media control card (#56256)
A missing comma in the narrow-layout selector meant the pause and stop
buttons never got the larger play-button size, so the card changed
height when switching between play and pause.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:19 +01:00
39b5f62cdb Use Marketplace icons for app install and uninstall (#56231)
The app info page now uses the same icons as the Marketplace:
mdiDownload for install and mdiDelete for uninstall. The previous
install icon filled its whole box and looked too large on the button.

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:17 +01:00
Petar Petrov 77f2230f9b Open more-info from energy meter suggestion names (#56226)
* Open more-info from energy meter suggestion names

* Type the more-info handler's current target
2026-11-30 17:26:16 +01:00
darkrain-nl 2cab493aaa Keep the startup progress in view while the list scrolls (#56213) 2026-11-30 17:26:15 +01:00
darkrain-nl c024b4594a Keep the startup details dialog at a fixed height (#56209) 2026-11-30 17:26:14 +01:00
Lazizbek Ergashev b76650cb55 Show Home Assistant Link as the title of the signed out Link page (#56205) 2026-11-30 17:26:12 +01:00
Petar Petrov eae1d81471 Show the device tooltip when hovering a name in the energy devices chart (#56200) 2026-11-30 17:26:11 +01:00
Paul Bottein 99b9f2593c Fill the mobile more info with the camera picture (#56199)
* Fill the mobile more info with the camera picture

* Use the dialog's own mode for the camera fill
2026-11-30 17:26:09 +01:00
Petar Petrov 43b6d8a0ea Add a Dismiss all button to energy meter suggestions (#56198) 2026-11-30 17:26:08 +01:00
Lazizbek Ergashev caccbf3c59 Only add the entity name to energy devices when it tells them apart (#56192)
* Only add the entity name to energy devices when it tells them apart

* Keep entity names for same-named devices with several meters

* Keep entity names when a custom name shares the device label
2026-11-30 17:26:06 +01:00
e5f408fca0 Show wake word names in the voice setup wizard (#56035)
* Show wake word names in the voice setup wizard

The migration to ha-list-item-button left the wake word phrase in the
default slot, which ha-row-item does not render, so the "Change wake
word" step showed empty rows. Put the phrase in the headline slot.

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

* Remove wake word step test

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Paul Bottein <[email protected]>
2026-11-30 17:26:05 +01:00
Bram Kragten 1c70897226 Bumped version to 20261125.1 2026-11-26 17:24:46 +01:00
WendelinandClaude Opus 5.5 3a27de8e0a Load Marketplace category icons only when they are shown (#56185)
The repository page loaded the integration category icons for every
repository, also for ones without integration categories. Load them once
a shown repository has categories, and only once per page.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:04:15 +01:00
WendelinandClaude Opus 5.5 bc21f2903d Only offer the tab's categories in the Marketplace filter (#56183)
The integration category filter offered every category on every tab, so
on the installed tab a category nothing installed is in emptied the
table. It now lists the categories of the tab's repositories, and a
category picked on another tab that this one doesn't list is left out
here but kept for that tab, like statuses.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:04:15 +01:00
WendelinandClaude Opus 5.5 b067ce5515 Remove two marketplace tests that only cover helpers (#56184)
Follow-up to #55130 review: the empty integration_category link test only
covered the query param decoder, and the filtersOfTab category test only
covered a spread.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:04:15 +01:00
Paul Bottein c95ed9f16c Swipe to open or close the tilt of tilt-only covers (#56182) 2026-11-26 17:01:38 +01:00
Paul Bottein 95eb2641e2 Fix rows value bubble cut off in the card size editor (#56181) 2026-11-26 17:01:36 +01:00
Bram KragtenandClaude Opus 5.5 4cb23b772a Draw the slats of tilt-only covers from their state (#56173)
* Draw the slats of tilt-only covers from their state

A tilt-only cover that only reports open or closed, without a tilt
position, was always drawn with half open slats. When the cover can't
move up or down, its state describes the slats, so draw them at the
closed tilt position when closed and at the open tilt position when
open. Covers that also move up and down keep the neutral slats, as
their state describes the position.

Add tilt-only blinds, open and closed, to the cover more-info gallery.

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

* Draw the slats from the state with the default tilt positions

Core only sends the open and closed tilt positions of covers that can
set their tilt position, so a tilt-only cover drawn from its state
always uses 0 and 100.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:35 +01:00
WendelinandClaude Opus 5.5 0bf5da2e09 Fix the Bluetooth adapter count on the dashboard (#56165)
* Fix the Bluetooth adapter count on the dashboard

The dashboard counted every bluetooth config entry that isn't disabled,
including ignored discoveries and entries without an adapter device, so
it could show more adapters than the adapters page lists. Move the
adapters page logic to a shared getBluetoothAdapters() helper and count
its enabled adapters on the dashboard. The count waits for the device
registry to load.

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

* Show skeletons while the Bluetooth adapters load

Don't report zero adapters and an offline network before the config
entries and the device registry have loaded. Add tests for the shared
adapter selection.

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

* Show an error with retry when the Bluetooth config entries fail to load

Otherwise the dashboard would keep showing its loading skeletons.

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

* Keep the Bluetooth adapters link named while it loads

A skeleton in the link made its accessible name only "Loading". Show
"Bluetooth adapters" until the count is known instead.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:34 +01:00
Erwin Douna c12ad32797 Restore dismissed energy meter suggestions (#56156)
* Restore dismissed energy meter suggestions

* Use a toolbar menu for dismissed meter suggestions and fix save races
2026-11-26 17:01:33 +01:00
2c03c2d74a Show Home Assistant Link label on WebRTC in camera stream info (#56153)
* Show Home Assistant Link label on WebRTC in camera stream info

The camera stream info dialog labels the WebRTC row with
"Enhanced by Home Assistant Link" when the cloud TURN servers are in
use. The dialog reads cloud/status and uses the same check as core:
logged in, active subscription, and cloud_ice_servers_enabled.

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

* Wrap the Home Assistant Link tag on narrow screens

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

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:31 +01:00
darkrain-nl 2705e6da51 2026.12 beta - Fix add integration search focus (#56151)
* Focus autofocus elements slotted into an adaptive dialog

* Test focusing autofocus elements slotted into a dialog
2026-11-26 17:01:30 +01:00
Martin Salinas e3871d47de Give the tile icon's action its whole 48px area again (#56150)
* Give the tile icon's action its whole 48px area again

The tile container pads the icon by 6px so it is a 48px target, but the action handler was bound to the 36px circle inside it. A tap on that ring, around the circle or on a badge landed on the icon's host, which had no handler, and the container stopped it before the card's handler. Bind the action handler to the host instead.

* Let taps on the tile icon's badge reach the icon

With the action handler on the host, a tap on a badge in the default slot had the badge as its target, so a double tap across the badge and the rest of the icon fired two taps.

* Show the pointer cursor over the tile icon's whole area
2026-11-26 17:01:29 +01:00
Paul Bottein ead8c01926 Fix integration names and toast overlap in startup details (#56147)
* Fix integration names and toast overlap in startup details

* Track startup details opened from the completion toast
2026-11-26 17:01:28 +01:00
Paul Bottein 258cb6f8b9 Show the connection error when logged out and the server is offline (#56139)
* Show the connection error when logged out and the server is offline

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

* Time out the server check before the login redirect

* Give the server check 10 seconds
2026-11-26 17:01:26 +01:00
Matthias de BaatandClaude Opus 5.5 72057cf504 Show when backup retention is paused for a location (#56088)
Automatic backup retention no longer deletes backups from locations
that are turned off for automatic backups (home-assistant/core#192788).
Show "Retention paused" in the locations list and an info alert on the
location page for those locations.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:25 +01:00
371 changed files with 4181 additions and 12230 deletions

No files matched your search

@@ -1,43 +0,0 @@
---
name: ha-frontend-browser-checks
description: Check a Home Assistant frontend change in a browser and show it in a pull request. Use when checking how a change looks or behaves at different screen sizes, in light and dark mode, right to left (RTL) or with long translations, or when taking before and after screenshots or recording a demo of a feature for a pull request.
---
# HA Frontend Browser Checks
Use this skill to check a visible change in a browser and to show it in a pull request. Any browser tool you already have works if it can open a page, set its size, run a script in it, take screenshots and record video. Load `ha-frontend-testing` for the dev servers, and `ha-frontend-loading` for loading states.
Screenshots and recordings help reviewers see what changed, but they don't make a large change easy to review. [Keep pull requests small](https://contributors.home-assistant.io/start/pull-requests/#keep-it-small), and make sure you have reviewed and understood the change and can explain it, as the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks.
## Check Real Devices
Check the sizes the change affects rather than one fixed size, such as a phone, a tablet in both orientations, a laptop and a large desktop monitor. Include a small phone. Take each device's viewport in CSS pixels, its pixel ratio and touch support from the device presets your tools have, rather than from memory, and check the page really has that size once it's set.
## Check Light And Dark
When the change can look different in light and dark mode, such as a colour, border, background or image, check it in both. Switch the colour scheme in your browser tool, with the profile's theme following it, or pick light and dark in the profile. A fix for one mode only needs that mode.
## Check Right To Left (RTL)
Check layout, alignment, icons and anything with a direction in RTL. In the app, set your profile language to one written right to left, then set it back: many components take their direction from the language, so setting the page to RTL in your browser tool leaves them left to right. The gallery's RTL toggle checks styling only.
## Check Long Text
When a change adds or changes text, check it in a language with long words or long translations too, so labels, descriptions and buttons don't overflow or wrap badly. When the new string isn't translated yet, try a rough translation to check its length.
## Show It In The Pull Request
- When the change alters something that exists already, capture the same screen on `dev` and on your branch, in the same state, and put them side by side. Only a new screen, with nothing before it, needs just the after.
- Keep the size of every capture fixed, screenshots as well as videos. Set the page size before you capture and don't change it in between, and capture the same area each time, so the subject sits in the same place in before and after. For a card or other part of the page, work out a fixed area around it for each size you test, and use that same area on both branches.
- Say which device, size or mode each capture shows.
- Make the change easy to see: capture the part of the screen it affects rather than a whole page where it's a few pixels.
- Save captures outside the repository, so they can't be committed by accident.
- Keep personal details out: use demo data, such as the demo or the Demo integration, and mask anything else before you capture, such as names, addresses, IP and MAC addresses, hostnames, serial numbers and tokens. Check each capture before you attach it.
Record a video when it shows the change better than a still, such as an animation, a drag, a loading sequence (hold the loading state as "Checking It" in `ha-frontend-loading` shows) or a flow across several screens. Keep each video short and small: GitHub limits upload sizes, and reviewers have to watch it. You can record it yourself with the tools you have; it doesn't need a person.
- Use the recording tools at hand: your browser tool's recorder for a page, or a desktop screen recorder for a window, such as a phone emulator, so the device frame shows.
- Don't resize, zoom or take screenshots while recording, which redraw the page at another size and make the video jump.
- Check the whole recording before you attach it. For a short clip, look at a frame every second or half second, not only the first and last, since the page can jump to another size partway through. Record again if it does. Take stills from the same frames, so they match the video.
- Keep the window drawn on a screen. A hidden or minimised window records only a frame every few seconds.
- Label each video, such as **Before** and **After**, and say what it shows and how you set it up. Say what you didn't record and why.
+1 -21
View File
@@ -10,7 +10,6 @@ Use this skill for every loading state, following the [Loading pattern](https://
## Pick The Indicator
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`, `ha-skeleton-log`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
- Use `ha-skeleton-overlay` when the content renders before its data arrives, such as a card or badge, or when content reloads over what's already shown. See [Skeleton Overlay](#skeleton-overlay).
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
@@ -28,7 +27,7 @@ Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
- Don't add your own fade to loaded content. `ha-skeleton-overlay` fades each part in over `--ha-animation-duration-fast`, which reduced motion makes instant.
- 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.
@@ -46,24 +45,6 @@ html`
`;
```
## Skeleton Overlay
`ha-skeleton-overlay` reads a skeleton from the content it wraps, so it can't drift from it: each text line, icon, image, control and drawing gets its own piece, and the real parts are hidden underneath until loading ends. Prefer it to drawing a skeleton by hand whenever the content can render before its data.
```ts
html`
<ha-skeleton-overlay .loading=${this._loading}>
<my-content></my-content>
</ha-skeleton-overlay>
`;
```
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it.
- Mark parts that shouldn't be read with `data-skeleton`: `none` leaves an element out and showing, `keep` leaves it showing but reads what's inside, and `text`, `round` or `block` force one piece of that kind. Skeletons the content draws itself are left alone.
- Put your own skeleton in the `skeleton` slot to replace the reading altogether.
- Call `refresh()` when the content changes without changing size.
- It gives the skeleton the `progressbar` role and the translated label itself.
## Checking It
Check a loading state in the browser, not only by reading the code. These work on any setup: a dev server, the demo, or the gallery.
@@ -90,6 +71,5 @@ Check a loading state in the browser, not only by reading the code. These work o
};
```
- **Compare the skeleton with the content.** It should take the same space, so nothing moves when the content arrives. Measure the wrapper's height while loading and once loaded (`element.getBoundingClientRect().height` in the console), or take a screenshot of each at the same size and flick between them. Look for pieces that are missing, extra or in the wrong place, and fix those with `data-skeleton`.
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
+1 -1
View File
@@ -20,7 +20,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
- Do not omit, reorder, or rewrite template sections.
- Check the appropriate "Type of change" box based on the actual change.
- Do not check checklist items on behalf of the user.
- If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
- If the PR includes UI changes, remind the user to add screenshots or a short video.
- Explain what the change does for users, not only implementation details.
- Use Markdown.
+8 -8
View File
@@ -18,7 +18,7 @@ workflows:
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
'.github/workflows/codeql-analysis.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
'.github/workflows/copilot-setup-steps.yml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
@@ -29,7 +29,7 @@ workflows:
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
'.github/workflows/dependency-review.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec'
- 'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294'
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
'.github/workflows/design_deployment.yaml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
@@ -101,9 +101,9 @@ dependencies:
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec':
ref: 'v5.0.1'
commit: 'sha1-bbc44d14a204704ccc493733616cd1e93a0321ec'
'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294':
ref: 'v5.0.0'
commit: 'sha1-a1d282b36b6f3519aa1f3fc636f609c47dddb294'
owner_id: 44036562
repo_id: 476372928
'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333':
@@ -151,9 +151,9 @@ dependencies:
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
owner_id: 7513068
repo_id: 113918130
'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea':
ref: 'v4.39.4'
commit: 'sha1-1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
ref: 'v4.39.3'
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
owner_id: 9919
repo_id: 259445878
'home-assistant/[email protected]':
+2 -2
View File
@@ -32,12 +32,12 @@ jobs:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
languages: javascript-typescript
build-mode: none
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
category: "/language:javascript-typescript"
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
contents: read # To compare the dependency graph between base and head
steps:
- name: Dependency review
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
with:
license-check: false # Covered by pnpm lint:licenses
fail-on-severity: high
+1 -2
View File
@@ -53,11 +53,10 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
## Pull Requests
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, remind the user to add screenshots or a short video.
## AI policy
@@ -198,7 +198,10 @@ async function fetchTranslations(currentArtifact: Artifact | null) {
console.log("Unpacking downloaded translations...");
const zip = await jszip.loadAsync(downloadResponse.data as ArrayBuffer);
await deleteCurrent;
await extract({ input: await zip.file(/.*/)[0].async("uint8array") });
const extractStream = zip.file(/.*/)[0].nodeStream().pipe(extract());
await new Promise((resolve, reject) => {
extractStream.on("close", resolve).on("error", reject);
});
// Record the artifact only after successful extraction, so a failed fetch
// is retried by the next build instead of being considered current.
+4
View File
@@ -69,6 +69,10 @@ async function copyMapPanel(staticDir) {
npmPath("leaflet/dist/leaflet.css"),
staticPath("images/leaflet/")
);
copyFileDir(
npmPath("leaflet.markercluster/dist/MarkerCluster.css"),
staticPath("images/leaflet/")
);
fs.copySync(
npmPath("leaflet/dist/images"),
staticPath("images/leaflet/images/")
+7 -1
View File
@@ -25,7 +25,13 @@ const NOTICE_FILES = [path.join(NODE_MODULES, "echarts/NOTICE")];
// that the new version's license still matches. The build will fail if
// the pinned version is no longer installed.
const LICENSE_OVERRIDES = [
// No entries currently needed.
{
// type-fest ships two license files (MIT for code, CC0 for types).
// We use the MIT license since that covers the bundled code.
packageName: "type-fest",
version: "5.10.0",
licenseFile: "license-mit",
},
];
// Locate the directory of an installed package matching an exact version.
+1 -2
View File
@@ -73,8 +73,7 @@ class HcLovelace extends LitElement {
if (index !== undefined) {
const title = getPanelTitleFromUrlPath(
this.hass.localize,
this.hass.panels,
this.hass,
this.urlPath || "lovelace"
);
+1 -2
View File
@@ -355,8 +355,7 @@ export class HcMain extends HassElement {
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
const title = getPanelTitleFromUrlPath(
this.hass!.localize,
this.hass!.panels,
this.hass!,
this._urlPath || "lovelace"
);
castContext.setApplicationState(title || "");
-1
View File
@@ -207,7 +207,6 @@ export class HaEmbedProvider extends LitElement {
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
this._applyColorScheme();
-3
View File
@@ -120,12 +120,10 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
fixed_costs: [],
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
@@ -133,7 +131,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
fixed_costs: prefs.fixed_costs.map(() => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
-10
View File
@@ -22,14 +22,6 @@ const baseRepository = {
status: "default" as const,
};
// The names of the connectivity of the demo repositories. Home Assistant
// translates them, the mocked hass has no backend translations.
export const marketplaceBackendTranslations = {
"component.homeassistant.integration_connectivity.mqtt.name": "MQTT",
"component.homeassistant.integration_connectivity.network.name":
"Local network",
};
const repositories: RepositoryBase[] = [
{
...baseRepository,
@@ -40,7 +32,6 @@ const repositories: RepositoryBase[] = [
description: "Watch camera streams with low latency through WebRTC.",
authors: ["@AlexxIT"],
domain: "webrtc",
connectivity: ["network"],
config_flow: true,
available_version: "v3.6.1",
downloads: 98000,
@@ -77,7 +68,6 @@ const repositories: RepositoryBase[] = [
description: "Use the cameras and events of a Frigate NVR.",
authors: ["@blakeblackshear", "@dermotduffy", "@NickM-27"],
domain: "frigate",
connectivity: ["network", "mqtt"],
config_flow: true,
available_version: "v5.9.0",
installed: true,
+1 -6
View File
@@ -1,7 +1,6 @@
import type { LocalizeFunc } from "../../../src/common/translations/localize";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import { connectivityBackendTranslations } from "./connectivity/fixtures";
import { marketplaceBackendTranslations } from "./marketplace";
export const mockTranslations = (
hass: MockHomeAssistant,
@@ -21,11 +20,7 @@ export const mockTranslations = (
// this merges on top of them.
(localizePromise ?? Promise.resolve()).then(() =>
hass.addTranslations(
Object.assign(
{},
...Object.values(connectivityBackendTranslations),
marketplaceBackendTranslations
)
Object.assign({}, ...Object.values(connectivityBackendTranslations))
)
);
};
-12
View File
@@ -1,8 +1,6 @@
import type { PropertyValues } from "lit";
import { html, css, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../src/components/ha-switch";
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
import type { HomeAssistant } from "../../../src/types";
import "./demo-card";
import type { DemoCardConfig } from "./demo-card";
@@ -16,16 +14,6 @@ class DemoCards extends LitElement {
@state() private _showConfig = false;
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
// Handles card actions like the app's action mixin
this.addEventListener("hass-action", (ev) => {
ev.stopPropagation();
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
});
}
render() {
return html`
<ha-demo-options>
@@ -61,6 +61,6 @@ The badge component is a small component that displays a number or status inform
**CSS Custom Properties**
- `--ha-badge-size` (default `36px`)
- `--ha-badge-border-radius` (default `calc(var(--ha-border-radius-lg) + 3px)`)
- `--ha-badge-border-radius` (default `calc(var(--ha-badge-size, 36px) / 2)`)
- `--ha-badge-font-size` (default `var(--ha-font-size-s)`)
- `--ha-badge-icon-size` (default `18px`)
@@ -22,27 +22,20 @@ export class DemoHaCircularSlider extends LitElement {
@state()
private changingHigh?: number;
// A handle that passes the other one pushes it along, like the slider does
private _lowChanged(ev) {
this.low = ev.detail.value;
this.high = Math.max(this.high, this.low);
}
private _lowChanging(ev) {
const value = ev.detail.value;
this.changingLow = value;
this.changingHigh = value != null && value > this.high ? value : undefined;
this.changingLow = ev.detail.value;
}
private _highChanged(ev) {
this.high = ev.detail.value;
this.low = Math.min(this.low, this.high);
}
private _highChanging(ev) {
const value = ev.detail.value;
this.changingHigh = value;
this.changingLow = value != null && value < this.low ? value : undefined;
this.changingHigh = ev.detail.value;
}
private _currentChanged(ev) {
@@ -462,14 +462,6 @@ const SCHEMAS: {
},
},
},
select_search: {
name: "Select (more than 12 options)",
selector: {
select: {
options: Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`),
},
},
},
select_disabled_list: {
name: "Select disabled option",
selector: {
@@ -640,10 +632,6 @@ const SCHEMAS: {
},
language: { name: "Language", selector: { language: {} } },
navigation: { name: "Navigation", selector: { navigation: {} } },
ui_condition: {
name: "Dashboard conditions",
selector: { ui_condition: {} },
},
numeric_threshold: {
name: "Numeric threshold",
selector: { numeric_threshold: {} },
@@ -22,13 +22,6 @@ const ENTITIES = [
friendly_name: "Bed Light",
},
},
{
entity_id: "light.living_room_ceiling_accent_lights",
state: "on",
attributes: {
friendly_name: "Living Room Ceiling Accent Lights",
},
},
{
entity_id: "person.paulus",
state: "home",
@@ -80,14 +73,6 @@ const CONFIGS = [
entity: "person.paulus",
},
},
{
heading: "Long name",
config: {
type: "picture-entity",
image: "/images/living_room.png",
entity: "light.living_room_ceiling_accent_lights",
},
},
{
heading: "Hidden name",
config: {
-23
View File
@@ -54,29 +54,6 @@ lorem | ipsum
`,
})
),
mdContentwithDefaults({
content: `
<p align="center">
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
</p>
- [Installation](#installation)
- [Configuration](#configuration)
## Installation
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
## Configuration
Add the integration from the integrations page.
[Back to the top](#installation)
[^marketplace]: Settings > Marketplace.
[^restart]: Only needed the first time.
`,
}),
];
@customElement("demo-misc-ha-markdown")
+40 -41
View File
@@ -40,31 +40,31 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.1.4",
"@babel/runtime": "8.1.3",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.4",
"@codemirror/commands": "6.11.2",
"@codemirror/commands": "6.11.1",
"@codemirror/lang-jinja": "6.0.1",
"@codemirror/lang-python": "6.2.1",
"@codemirror/lang-yaml": "6.1.3",
"@codemirror/language": "6.13.1",
"@codemirror/lint": "6.9.8",
"@codemirror/search": "6.7.3",
"@codemirror/search": "6.7.2",
"@codemirror/state": "6.7.6",
"@codemirror/view": "6.44.2",
"@codemirror/view": "6.43.15",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "8.2.2",
"@formatjs/intl-displaynames": "8.0.5",
"@formatjs/intl-durationformat": "0.13.2",
"@formatjs/intl-getcanonicallocales": "3.4.2",
"@formatjs/intl-listformat": "9.1.2",
"@formatjs/intl-locale": "5.5.2",
"@formatjs/intl-numberformat": "10.1.2",
"@formatjs/intl-pluralrules": "7.1.2",
"@formatjs/intl-relativetimeformat": "13.0.5",
"@formatjs/intl-datetimeformat": "8.0.3",
"@formatjs/intl-displaynames": "8.0.3",
"@formatjs/intl-durationformat": "0.13.0",
"@formatjs/intl-getcanonicallocales": "3.4.0",
"@formatjs/intl-listformat": "9.1.0",
"@formatjs/intl-locale": "5.5.0",
"@formatjs/intl-numberformat": "10.1.0",
"@formatjs/intl-pluralrules": "7.1.0",
"@formatjs/intl-relativetimeformat": "13.0.3",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.7",
"@lezer/common": "1.5.6",
"@lezer/highlight": "1.2.5",
"@lit-labs/motion": "1.1.0",
"@lit-labs/observers": "2.1.0",
@@ -79,12 +79,12 @@
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.4",
"@tsparticles/preset-links": "4.5.4",
"@versatiles/style": "9.1.3",
"@versatiles/style": "9.1.0",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.208.0",
"@vvo/tzdb": "6.204.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
"barcode-detector": "3.2.5",
"cally": "0.10.1",
"barcode-detector": "3.2.4",
"cally": "0.9.2",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
@@ -102,17 +102,15 @@
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.9.0",
"idb-keyval": "6.3.0",
"intl-messageformat": "12.2.1",
"intl-messageformat": "12.2.0",
"js-yaml": "5.5.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "2.0.0",
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.20.0",
"marked": "18.3.0",
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"memoize-one": "7.0.0",
"maplibre-gl": "6.19.0",
"marked": "18.2.1",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -138,25 +136,25 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.1.4",
"@babel/core": "8.1.3",
"@babel/helper-compilation-targets": "8.0.7",
"@babel/helper-define-polyfill-provider": "1.0.0",
"@babel/plugin-transform-class-properties": "8.0.1",
"@babel/plugin-transform-private-methods": "8.0.1",
"@babel/plugin-transform-runtime": "8.1.2",
"@babel/preset-env": "8.1.4",
"@babel/preset-env": "8.0.7",
"@bundle-stats/plugin-webpack-filter": "4.23.1",
"@eslint/js": "10.0.1",
"@gfx/zopfli": "1.0.15",
"@home-assistant/components": "workspace:*",
"@html-eslint/eslint-plugin": "0.69.0",
"@html-eslint/eslint-plugin": "0.68.0",
"@lokalise/node-api": "17.0.1",
"@octokit/auth-oauth-device": "8.0.5",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.4",
"@rspack/dev-server": "2.2.3",
"@rspack/core": "2.3.3",
"@rspack/dev-server": "2.2.2",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
"@types/chromecast-caf-sender": "1.0.11",
@@ -164,22 +162,23 @@
"@types/culori": "4.0.1",
"@types/geojson": "7946.0.16",
"@types/html-minifier-terser": "7.0.2",
"@types/leaflet": "1.9.23",
"@types/leaflet": "1.9.22",
"@types/leaflet.markercluster": "1.5.6",
"@types/lodash.merge": "4.6.9",
"@types/node": "24.19.4",
"@types/node": "24.19.2",
"@types/qrcode": "1.5.6",
"@types/sortablejs": "1.15.9",
"@types/tar": "7.0.87",
"@typescript/native": "npm:[email protected]",
"@vitest/coverage-v8": "5.1.2",
"@vitest/coverage-v8": "5.1.1",
"babel-loader": "10.1.1",
"babel-plugin-polyfill-corejs3": "1.0.0",
"browserslist": "4.29.6",
"browserslist-useragent-regexp": "4.1.4",
"core-js-compat": "3.51.0",
"del": "9.0.1",
"eslint": "10.16.0",
"eslint-config-prettier": "10.1.9",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.1",
"eslint-plugin-lit": "2.3.1",
@@ -200,7 +199,7 @@
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
"lint-staged": "17.6.3",
"lint-staged": "17.6.2",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.18.1",
@@ -211,19 +210,19 @@
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "8.0.2",
"tar": "7.5.23",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.74.0",
"vite": "8.4.0",
"typescript-eslint": "8.73.0",
"vite": "8.3.8",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.2",
"vitest": "5.1.1",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]4.0",
"packageManager": "[email protected]3.0",
"volta": {
"node": "24.22.3"
}
+1 -1
View File
@@ -53,7 +53,7 @@
},
"devDependencies": {
"@custom-elements-manifest/analyzer": "0.11.0",
"@rslib/core": "1.1.0",
"@rslib/core": "1.0.7",
"lit": "3.3.3",
"typescript": "6.0.3"
}
+1240 -1342
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -18,8 +18,6 @@ trustPolicyExclude:
- [email protected]
# Pre-release published without provenance, used by workbox-build
- "@trickfilm400/[email protected]"
# Published without the trusted-publisher record; provenance still from vvo/tzdb release.yml
- "@vvo/[email protected]"
# Dependency build scripts are denied unless listed here with true
allowBuilds:
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20261125.0"
version = "20261125.4"
license = "Apache-2.0"
license-files = ["LICENSE*"]
description = "The Home Assistant frontend"
+2 -2
View File
@@ -126,9 +126,9 @@
"matchPackageNames": ["echarts", "zrender"]
},
{
"description": "Group formatjs monorepo packages",
"description": "Group formatjs monorepo package",
"groupName": "formatjs",
"matchPackageNames": ["@formatjs/**", "intl-messageformat"]
"matchPackageNames": ["@formatjs/**"]
},
{
"description": "Group Playwright package and CI container updates",
@@ -1,74 +0,0 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ConditionContext,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
/** Pass each new hass object so client-side conditions check again. */
update(hass: HomeAssistant): void;
/** Close the subscriptions. `onChange` is not called again. */
unsubscribe(): void;
}
/**
* Live visibility of a list of dashboard visibility conditions, for code
* without a Lit host, such as custom cards and plugins. Conditions core
* evaluates are subscribed to; the rest are checked locally. Reports
* `unknown` until core replies.
*/
export const subscribeVisibility = (
hass: HomeAssistant,
conditions: VisibilityCondition[],
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
// The controller only needs a host to register with and to re-render.
const host: ReactiveControllerHost = {
addController: () => undefined,
removeController: () => undefined,
requestUpdate: () => undefined,
updateComplete: Promise.resolve(true),
};
let active = true;
const controller = new ConditionEvaluatorController(host, {
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
onChange(result, error);
}
},
});
const sanitized = dropInvalidConditions(conditions);
const { entity_id: entityId } = context;
// Core-evaluated conditions never see the context, so fold its entity in
// first, as the dashboard mixin does.
const validConditions = entityId
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
: sanitized;
const getContext = () => context;
controller.hostConnected();
controller.observe(validConditions, hass, getContext);
return {
update: (newHass) => {
if (active) {
controller.observe(validConditions, newHass, getContext);
}
},
unsubscribe: () => {
active = false;
controller.hostDisconnected();
},
};
};
+6 -13
View File
@@ -209,16 +209,6 @@ const formatDurationMinuteMem = memoizeOne((locale: FrontendLocaleData) =>
})
);
// Splits a value into whole units and whole sub-units, e.g. 1.15 h into 1 h
// and 9 min. The value is converted to sub-units and rounded before flooring,
// as floating point math puts many of them just below a whole number:
// (1.15 - 1) * 60 is 8.999999999999995.
const splitDuration = (value: number, subUnits: number): [number, number] => {
const total = Math.floor(round(value * subUnits, 6));
const units = Math.floor(total / subUnits);
return [units, total - units * subUnits];
};
export const formatDuration = (
locale: FrontendLocaleData,
duration: string,
@@ -232,7 +222,8 @@ export const formatDuration = (
switch (unit) {
case "d": {
const [days, hours] = splitDuration(value, 24);
const days = Math.floor(value);
const hours = Math.floor((value - days) * 24);
const input = {
days,
hours,
@@ -240,7 +231,8 @@ export const formatDuration = (
return formatDurationDayMem(locale)(input);
}
case "h": {
const [hours, minutes] = splitDuration(value, 60);
const hours = Math.floor(value);
const minutes = Math.floor((value - hours) * 60);
const input = {
hours,
minutes,
@@ -248,7 +240,8 @@ export const formatDuration = (
return formatDurationHourMem(locale)(input);
}
case "min": {
const [minutes, seconds] = splitDuration(value, 60);
const minutes = Math.floor(value);
const seconds = Math.floor((value - minutes) * 60);
const input = {
minutes,
seconds,
-623
View File
@@ -1,623 +0,0 @@
/**
* Read a skeleton from rendered content, such as a dashboard card: where its
* text lines, icons, images, controls and drawings are, inside shadow roots
* too. The content stays the source of truth for layout, so the skeleton
* can't drift from it.
*
* Any element can say how it's read with a `data-skeleton` attribute:
* - `text`, `round` or `block`: one piece of that kind, the size of the element
* - `none`: left out and left showing, such as a card's own chrome
* - `keep`: left showing, but what's inside it is still read
*
* Skeletons a component already draws itself (`ha-skeleton` and its
* variants) are left out and left showing, as `none`.
*/
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
const isOverride = (value: string | null): value is SkeletonOverride =>
value !== null && OVERRIDES.has(value);
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
if (element.localName.startsWith("ha-skeleton")) {
return "none";
}
const value = element.getAttribute("data-skeleton");
return isOverride(value) ? value : undefined;
};
export interface SkeletonPiece {
kind: SkeletonPieceKind;
x: number;
y: number;
width: number;
height: number;
radius?: string;
/* An SVG mask for a drawing, such as a gauge arc */
mask?: string;
/* Where that mask sits in the piece, when something cuts the drawing short:
still the drawing's whole size and place, with the piece only its part */
maskBox?: { x: number; y: number; width: number; height: number };
/* The part sits on a dark overlay, such as a picture card's name bar */
onDark?: boolean;
/* A see-through bar laid over a picture, kept as it is */
background?: string;
}
export interface ExtractedSkeleton {
pieces: SkeletonPiece[];
/* The elements the pieces stand in for, hidden while loading */
parts: (HTMLElement | SVGElement)[];
/* Elements holding text: hide only the text colour, as the same element
often draws a frame, such as a badge's pill, that has to stay */
textParts: HTMLElement[];
}
const ROUND_TAGS = new Set([
"ha-tile-icon",
"ha-state-icon",
"ha-svg-icon",
"ha-icon",
"state-badge",
]);
const BLOCK_TAGS = new Set(["img", "video", "canvas", "ha-camera-stream"]);
/* A canvas to measure fonts with, made on first use */
let measuringContext: CanvasRenderingContext2D | null | undefined;
const fontContext = (style: CSSStyleDeclaration, size: string) => {
measuringContext ??= document.createElement("canvas").getContext("2d");
if (measuringContext) {
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
}
return measuringContext;
};
/**
* Where a text bar goes on a line of this font: from the top of the
* capitals down to the baseline, measured from the font itself.
* `size` is the size as drawn, after any SVG scaling.
*/
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
const metrics = fontContext(style, `${size}px`)?.measureText("H");
// Missing before Chrome 87 and Firefox 116
if (!metrics?.fontBoundingBoxAscent || !metrics.actualBoundingBoxAscent) {
return { top: size * 0.2, height: size * 0.7 };
}
return {
// The line box holds the font's ascent, so the baseline sits that far down
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
height: metrics.actualBoundingBoxAscent,
};
};
/* How wide "…" is in this font, the room cut-off text leaves at its end */
const ellipsisWidth = (style: CSSStyleDeclaration) =>
fontContext(style, style.fontSize)?.measureText("…").width ??
parseFloat(style.fontSize);
/* The icon as drawn, not its box, which a line of text can crop */
const findGlyph = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
for (const child of [
...(element.shadowRoot?.children ?? []),
...element.children,
]) {
if (child instanceof SVGSVGElement) {
return child;
}
const found = findGlyph(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Near-white text or icons, as on a picture card's dark name bar */
const isNearWhite = (color: string): boolean => {
const channels = color
.match(/[\d.]+/g)
?.slice(0, 3)
.map(Number);
return channels?.length === 3 && channels.every((channel) => channel >= 200);
};
const isRendered = (style: CSSStyleDeclaration) =>
style.display !== "none" && style.visibility !== "hidden";
const isSeeThrough = (color: string) => {
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
return alpha > 0 && alpha < 1;
};
/* The first element, inside shadow roots too, that rounds its corners */
const findRounded = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
const children = [
...(element.shadowRoot?.children ?? []),
...element.children,
];
for (const child of children) {
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
return child;
}
const found = findRounded(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
const merged: SkeletonPiece[] = [];
for (const piece of pieces) {
const previous = merged[merged.length - 1];
// Either side, so right-to-left lines join too
const gap = previous
? Math.max(
piece.x - (previous.x + previous.width),
previous.x - (piece.x + piece.width)
)
: Infinity;
const sameLine =
previous?.kind === "text" &&
piece.kind === "text" &&
Math.abs(previous.y - piece.y) < 2 &&
Math.abs(previous.height - piece.height) < 2 &&
gap < 12;
if (sameLine) {
const left = Math.min(previous.x, piece.x);
const right = Math.max(
previous.x + previous.width,
piece.x + piece.width
);
previous.x = left;
previous.width = right - left;
continue;
}
merged.push({ ...piece });
}
return merged;
};
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
const clone = svg.cloneNode(true);
if (!(clone instanceof SVGSVGElement)) {
return undefined;
}
const originals = [svg, ...svg.querySelectorAll("*")];
const copies = [clone, ...clone.querySelectorAll("*")];
let drawnPaths = 0;
originals.forEach((original, index) => {
const copy = copies[index];
const style = getComputedStyle(original);
if (original.localName === "text" || !isRendered(style)) {
copy.setAttribute("display", "none");
return;
}
if (original !== svg && original.localName !== "g") {
drawnPaths++;
}
copy.removeAttribute("class");
copy.removeAttribute("style");
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
copy.setAttribute("stroke-width", style.strokeWidth);
copy.setAttribute("stroke-linecap", style.strokeLinecap);
// Keep what moves or cuts a shape, such as a gauge's needle and the
// dashes that draw its value arc
if (style.transform !== "none") {
copy.setAttribute(
"style",
`transform: ${style.transform}; transform-origin: ${style.transformOrigin}; transform-box: ${style.transformBox}`
);
}
if (style.strokeDasharray !== "none") {
copy.setAttribute("stroke-dasharray", style.strokeDasharray);
copy.setAttribute("stroke-dashoffset", style.strokeDashoffset);
}
});
if (drawnPaths === 0) {
return undefined;
}
clone.setAttribute("width", String(width));
clone.setAttribute("height", String(height));
const markup = new XMLSerializer().serializeToString(clone);
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
};
export const extractSkeleton = (
root: Element,
origin: DOMRect
): ExtractedSkeleton => {
const pieces: SkeletonPiece[] = [];
const parts = new Set<HTMLElement | SVGElement>();
const textParts = new Set<HTMLElement>();
/* The card's own background, the first solid one found */
let surface: string | undefined;
const box = (rect: DOMRect) => ({
x: rect.left - origin.left,
y: rect.top - origin.top,
width: rect.width,
height: rect.height,
});
/* Near-white content on a light card must sit on a dark bar */
const onDark = (style: CSSStyleDeclaration) =>
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
/* An element that cuts off its overflow, such as a scrolling list, cuts the
pieces read inside it too, as the overlay draws them on a layer of its
own where that clip doesn't reach */
const clipPieces = (from: number, rect: DOMRect) => {
const bounds = box(rect);
const clipped = pieces.splice(from).flatMap((piece): SkeletonPiece[] => {
const x = Math.max(piece.x, bounds.x);
const y = Math.max(piece.y, bounds.y);
const right = Math.min(piece.x + piece.width, bounds.x + bounds.width);
const bottom = Math.min(piece.y + piece.height, bounds.y + bounds.height);
if (right <= x || bottom <= y) {
return [];
}
const cut = { ...piece, x, y, width: right - x, height: bottom - y };
// A drawing's mask is made for its whole box, so it keeps that box
if (piece.kind === "shape") {
const mask = piece.maskBox ?? {
x: 0,
y: 0,
width: piece.width,
height: piece.height,
};
return [
{
...cut,
maskBox: {
...mask,
x: piece.x + mask.x - x,
y: piece.y + mask.y - y,
},
},
];
}
return [cut];
});
pieces.push(...clipped);
};
const addText = (element: Element | ShadowRoot) => {
const owner = element instanceof ShadowRoot ? element.host : element;
// Text cut short with an ellipsis reaches past its box, so clip to it.
// An owner with no box of its own, such as one with display: contents,
// cuts nothing off.
const clip = owner.getBoundingClientRect();
const clips = clip.width > 0 || clip.height > 0;
element.childNodes.forEach((node) => {
if (!(node instanceof Text) || !node.textContent?.trim()) {
return;
}
// Slotted text takes its font and colour from the slot it shows in,
// so that's where it's measured and hidden
const slot = node.assignedSlot;
const hideTarget = slot ?? owner;
const style = getComputedStyle(hideTarget);
const band = capitalBand(style, parseFloat(style.fontSize));
if (hideTarget instanceof HTMLElement) {
textParts.add(hideTarget);
}
const range = document.createRange();
range.selectNodeContents(node);
for (const rect of range.getClientRects()) {
// Cut-off text ends in "…", on the right or, right to left, on the
// left, so stop the bar where that starts
const left =
clips && rect.left < clip.left - 1
? clip.left + ellipsisWidth(style)
: rect.left;
const right =
clips && rect.right > clip.right + 1
? clip.right - ellipsisWidth(style)
: rect.right;
if (right <= left) {
continue;
}
pieces.push({
kind: "text",
x: left - origin.left,
width: right - left,
y: rect.top - origin.top + band.top,
height: band.height,
onDark: onDark(style),
});
}
});
};
const walk = (node: Element | ShadowRoot) => {
// Text straight inside a shadow root, as state-display renders its state
if (node instanceof ShadowRoot) {
addText(node);
}
for (const child of node.children) {
const style = getComputedStyle(child);
if (!isRendered(style)) {
continue;
}
const rect = child.getBoundingClientRect();
const tag = child.localName;
// Elements such as slots take no space but their content does
const hasSize = rect.width > 0 && rect.height > 0;
const override = skeletonOverride(child);
if (override === "none") {
continue;
}
const clipsOverflow =
hasSize &&
(style.overflowX !== "visible" || style.overflowY !== "visible");
const from = pieces.length;
// Read what's inside, cut to the child where it hides its overflow
const descend = () => {
if (child instanceof HTMLElement) {
addText(child);
}
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
if (clipsOverflow) {
clipPieces(from, rect);
}
};
if (override === "keep") {
// Its frame stays, but its own text is read like any other
descend();
continue;
}
if (override !== undefined) {
if (
hasSize &&
(child instanceof HTMLElement || child instanceof SVGElement)
) {
const size = Math.min(rect.width, rect.height);
const piece = box(rect);
pieces.push(
override === "round"
? {
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
}
: { kind: override, ...piece, radius: style.borderRadius }
);
parts.add(child);
}
continue;
}
if (
surface === undefined &&
hasSize &&
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
!isSeeThrough(style.backgroundColor)
) {
surface = style.backgroundColor;
}
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
// Use the circle itself, such as the tile icon's 36px background
const circle = (
findRounded(child) ??
findGlyph(child) ??
child
).getBoundingClientRect();
const size =
Math.min(circle.width, circle.height) ||
Math.max(circle.width, circle.height);
const piece = box(circle);
if (size > 0) {
pieces.push({
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
onDark: onDark(style),
});
parts.add(child);
}
continue;
}
// A see-through bar over a picture stays, so text keeps its contrast
if (
child instanceof HTMLElement &&
hasSize &&
style.position === "absolute" &&
isSeeThrough(style.backgroundColor)
) {
pieces.push({
kind: "scrim",
...box(rect),
radius: style.borderRadius,
background: style.backgroundColor,
});
}
// Pictures drawn as a background, as hui-image does in a fixed ratio
if (
child instanceof HTMLElement &&
hasSize &&
style.backgroundImage.startsWith("url(")
) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (
child instanceof HTMLElement &&
hasSize &&
tag.endsWith("-card-feature")
) {
const control = findRounded(child);
const radius = control
? getComputedStyle(control).borderRadius
: style.borderRadius;
pieces.push({ kind: "block", ...box(rect), radius });
parts.add(child);
continue;
}
if (child instanceof SVGSVGElement && hasSize) {
const piece = box(rect);
const mask = svgMask(child, piece.width, piece.height);
if (mask) {
pieces.push({ kind: "shape", ...piece, mask });
}
child.querySelectorAll("text").forEach((text) => {
const textRect = text.getBoundingClientRect();
if (textRect.width === 0) {
return;
}
// SVG text is scaled with its drawing, as the gauge value is
const scale = text.getScreenCTM()?.a ?? 1;
const textStyle = getComputedStyle(text);
const band = capitalBand(
textStyle,
parseFloat(textStyle.fontSize) * scale
);
pieces.push({
kind: "text",
...box(textRect),
y: textRect.top - origin.top + band.top,
height: band.height,
});
});
parts.add(child);
continue;
}
descend();
}
};
// Text straight inside the root, such as plain text in an overlay
addText(root);
walk(root);
return {
pieces: mergeLines(pieces),
parts: [...parts],
textParts: [...textParts],
};
};
+10
View File
@@ -31,6 +31,8 @@ export const setupLeafletMap = async (
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
await import("leaflet.markercluster");
const map = Leaflet.map(mapElement, {
minZoom: MAP_MIN_ZOOM,
maxZoom: MAP_MAX_ZOOM,
@@ -41,6 +43,14 @@ export const setupLeafletMap = async (
style.setAttribute("rel", "stylesheet");
mapElement.parentNode.appendChild(style);
const markerClusterStyle = document.createElement("link");
markerClusterStyle.setAttribute(
"href",
"/static/images/leaflet/MarkerCluster.css"
);
markerClusterStyle.setAttribute("rel", "stylesheet");
mapElement.parentNode.appendChild(markerClusterStyle);
if (initialView) {
map.setView(
[initialView.latitude, initialView.longitude],
+6 -10
View File
@@ -1,4 +1,3 @@
import { parseISO } from "date-fns";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
@@ -15,7 +14,6 @@ import {
getNumberFormatOptions,
isNumericFromAttributes,
} from "../number/format_number";
import { isDate } from "../string/is_date";
import { blankBeforeUnit } from "../translations/blank_before_unit";
import type { LocalizeFunc } from "../translations/localize";
import { computeDomain } from "./compute_domain";
@@ -198,9 +196,7 @@ const computeStateToPartsFromEntityAttributes = (
return [{ type: "value", value: value }];
}
const isDateSensor = isSensorDomain && attributes.device_class === "date";
if (DATE_TIME_DOMAINS.has(domain) || isDateSensor) {
if (DATE_TIME_DOMAINS.has(domain)) {
// If trying to display an explicit state, need to parse the explicit state to `Date` then format.
// Attributes aren't available, we have to use `state`.
@@ -221,15 +217,15 @@ const computeStateToPartsFromEntityAttributes = (
];
}
if (components.length === 1) {
if (isDate(state)) {
// Parse and format date-only values in UTC to preserve the calendar day.
if (state.includes("-")) {
// Date only.
return [
{
type: "value",
value: formatDate(
parseISO(`${state}T00:00:00Z`),
{ ...locale, time_zone: TimeZone.server },
{ ...config, time_zone: "UTC" }
new Date(`${state}T00:00`),
{ ...locale, time_zone: TimeZone.local },
config
),
},
];
-65
View File
@@ -1,10 +1,8 @@
import type { HassEntity } from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import type { HomeAssistant } from "../../types";
import { ensureArray } from "../array/ensure-array";
import { computeDomain } from "./compute_domain";
import { getEntityContext } from "./context/get_entity_context";
import { getEntityIds } from "./get_entity_ids";
type EntityCategory = "none" | "config" | "diagnostic";
@@ -181,66 +179,3 @@ export const findFilteredEntities = (
);
return findEntities(Object.keys(sources.states), filterFuncs);
};
export type EntityFinder = (
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
floors: HomeAssistant["floors"]
) => string[];
/**
* Finds the same entities as `findFilteredEntities`, for repeated calls.
* Of a state, the filters only read its device class, so everything else is
* matched again only when the entity ids or the registries change.
*/
export const createEntityFinder = (filters: EntityFilter[]): EntityFinder => {
const registryFilters = filters.map(
({ device_class: _deviceClass, ...filter }) => filter
);
const deviceClasses = filters.map((filter) =>
filter.device_class ? new Set(ensureArray(filter.device_class)) : undefined
);
let candidatesKey: unknown[] = [];
let candidates: string[][] = [];
return memoizeOne<EntityFinder>(
(states, entities, devices, areas, floors) => {
const entityIds = getEntityIds(states);
const key = [entityIds, entities, devices, areas, floors];
if (key.some((value, i) => value !== candidatesKey[i])) {
candidatesKey = key;
candidates = registryFilters.map((filter) =>
entityIds.filter(
generateEntityFilter(
states,
entities,
devices,
areas,
floors,
filter
)
)
);
}
const seen = new Set<string>();
const results: string[] = [];
candidates.forEach((candidateIds, i) => {
const classes = deviceClasses[i];
for (const entityId of candidateIds) {
if (
!seen.has(entityId) &&
(!classes ||
classes.has(states[entityId].attributes.device_class || "none"))
) {
seen.add(entityId);
results.push(entityId);
}
}
});
return results;
}
);
};
-22
View File
@@ -1,22 +0,0 @@
import type { HomeAssistant } from "../../types";
let lastStates: HomeAssistant["states"] | undefined;
let lastEntityIds: string[] = [];
/**
* Returns the ids of `states`, as the same array for as long as they stay the
* same, so callers can memoize on it.
*/
export const getEntityIds = (states: HomeAssistant["states"]): string[] => {
if (states !== lastStates) {
lastStates = states;
const entityIds = Object.keys(states);
if (
entityIds.length !== lastEntityIds.length ||
entityIds.some((entityId, i) => entityId !== lastEntityIds[i])
) {
lastEntityIds = entityIds;
}
}
return lastEntityIds;
};
+13 -46
View File
@@ -1,12 +1,9 @@
/// <reference types="leaflet.markercluster" />
import type {
CircleMarker,
Control,
DivIcon,
Map,
MarkerCluster,
MarkerClusterGroup,
MarkerClusterGroupOptions,
Polyline,
} from "leaflet";
import type { LeafletModuleType } from "../../dom/setup-leaflet-map";
@@ -39,18 +36,8 @@ interface HandledMarker extends DecoratedMarker {
interface LeafletMarkerHandle extends MapMarkerHandle {
marker: HandledMarker;
title?: string;
}
// v2 option the 1.x types don't know yet
interface ClusterGroupOptions extends MarkerClusterGroupOptions {
clusterLabel?(cluster: MarkerCluster): string;
}
// Stands in for getAnimations on browsers without it (Chrome before 84),
// which markercluster calls whenever the map zooms
const noAnimations = (): Animation[] => [];
/** The Leaflet engine: raster viewing fallback without WebGL2, no editing */
export class LeafletMapEngine implements MapEngine {
/** For the ha-map jsdom tests only */
@@ -62,14 +49,10 @@ export class LeafletMapEngine implements MapEngine {
private _clusterable: HandledMarker[] = [];
private _MarkerClusterGroup?: typeof MarkerClusterGroup;
private _cluster?: MarkerClusterGroup;
private _clusterOptions: MapClusterOptions | null = null;
private _animateClusters = true;
private _scaleControl?: Control.Scale;
public async init(
@@ -83,26 +66,22 @@ export class LeafletMapEngine implements MapEngine {
// eslint-disable-next-line
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
// The package's own types are for Leaflet 2; on our Leaflet 1.9,
// @types/leaflet.markercluster describes it
this._MarkerClusterGroup = (await import("leaflet.markercluster"))
.MarkerClusterGroup as unknown as typeof MarkerClusterGroup;
// Without a native getAnimations, markercluster can't cancel the
// animations a zoom interrupts, so clusters don't animate there
this._animateClusters =
"getAnimations" in Element.prototype &&
Element.prototype.getAnimations !== noAnimations;
Element.prototype.getAnimations ??= noAnimations;
await import("leaflet.markercluster");
const map = Leaflet.map(container, {
minZoom: MAP_MIN_ZOOM,
maxZoom: MAP_MAX_ZOOM,
});
map.attributionControl.setPrefix("");
const style = document.createElement("link");
style.setAttribute("href", "/static/images/leaflet/leaflet.css");
style.setAttribute("rel", "stylesheet");
root.appendChild(style);
for (const href of [
"/static/images/leaflet/leaflet.css",
"/static/images/leaflet/MarkerCluster.css",
]) {
const style = document.createElement("link");
style.setAttribute("href", href);
style.setAttribute("rel", "stylesheet");
root.appendChild(style);
}
map.setView(options.center, options.zoom);
// The base layer adds itself; a vector layer may still fall back to raster
@@ -278,7 +257,6 @@ export class LeafletMapEngine implements MapEngine {
const handle: LeafletMarkerHandle = {
marker,
location,
title: options.title,
clusterData: options.clusterData,
remove: () => {
this._cluster?.removeLayer(marker);
@@ -367,27 +345,18 @@ export class LeafletMapEngine implements MapEngine {
this._cluster = undefined;
}
this._clusterOptions = options;
if (!this.leafletMap || !this.Leaflet || !this._MarkerClusterGroup) {
if (!this.leafletMap || !this.Leaflet) {
return;
}
if (!options) {
this._clusterable.forEach((marker) => marker.addTo(this.leafletMap!));
return;
}
// markercluster groups by proximity only; groupKey is not supported here
const clusterOptions: ClusterGroupOptions = {
this._cluster = this.Leaflet.markerClusterGroup({
showCoverageOnHover: false,
removeOutsideVisibleBounds: false,
animate: this._animateClusters,
maxClusterRadius: options.radius,
// The members' names, as the MapLibre engine labels its clusters
clusterLabel: (cluster) =>
(cluster.getAllChildMarkers() as HandledMarker[])
.map((marker) => marker.engineHandle?.title)
.filter(Boolean)
.join(", "),
iconCreateFunction: (cluster) => {
const build = () => {
const members = (cluster.getAllChildMarkers() as HandledMarker[]).map(
@@ -428,9 +397,7 @@ export class LeafletMapEngine implements MapEngine {
createShadow: () => null,
} as unknown as DivIcon;
},
};
this._cluster = new this._MarkerClusterGroup(clusterOptions);
});
this._cluster.addLayers(this._clusterable);
this.leafletMap!.addLayer(this._cluster!);
}
@@ -849,9 +849,6 @@ export class MapLibreMapEngine implements MapEngine {
if (!interactive) {
// Leaflet lets input through non-interactive markers; MapLibre does not
element.style.pointerEvents = "none";
} else {
// Leaflet points at what takes a click; MapLibre leaves the map's grab
element.style.cursor = "pointer";
}
setMarkerAccessibility(element, options.title, focusable);
element.style.zIndex = options.raised ? "1" : "";
@@ -1049,8 +1046,6 @@ export class MapLibreMapEngine implements MapEngine {
setMarkerAccessibility(centerEl, options.title, !!options.onClick);
if (options.moveable) {
centerEl.style.cursor = "move";
} else if (options.onClick) {
centerEl.style.cursor = "pointer";
}
this._placedElements.add(centerEl);
const centerMarker = new maplibre.Marker({
@@ -1655,7 +1650,6 @@ export class MapLibreMapEngine implements MapEngine {
this._hideEmerging(members);
};
setMarkerAccessibility(icon.element, this._groupTitle(group), true);
icon.element.style.cursor = "pointer";
icon.element.addEventListener("click", (ev) => {
ev.stopPropagation();
zoomToMembers();
+1 -24
View File
@@ -108,32 +108,9 @@ const addAtmosphere = (style: StyleSpecification): StyleSpecification => ({
sky: { ...style.sky, "atmosphere-blend": ATMOSPHERE_BLEND },
});
// MapLibre keeps the globe until it blends into mercator between zoom 11 and
// 12, but unbuffered ocean polygons leave hairline gaps between tiles on it
// from about zoom 6. Flatten it earlier, between zoom 5 and 6.
const GLOBE_FLATTEN_ZOOM = 5;
const flattenGlobeEarly = (style: StyleSpecification): StyleSpecification =>
style.projection?.type === "globe"
? {
...style,
projection: {
type: [
"interpolate",
["linear"],
["zoom"],
GLOBE_FLATTEN_ZOOM,
"vertical-perspective",
GLOBE_FLATTEN_ZOOM + 1,
"mercator",
],
},
}
: style;
/** Everything a freshly built style needs before it is handed to MapLibre */
export const finalizeMapStyle = (
name: string,
style: StyleSpecification
): StyleSpecification =>
flattenGlobeEarly(addAtmosphere(addLatinLabels(useTileJson(name, style))));
addAtmosphere(addLatinLabels(useTileJson(name, style)));
-10
View File
@@ -5,7 +5,6 @@ import type {
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
import type { FrontendLocaleData } from "../../data/translation";
import { NumberFormat } from "../../data/translation";
import { getLocaleDataVersion } from "../../resources/polyfills/locale-data-polyfill";
import { blankBeforeUnit } from "../translations/blank_before_unit";
/**
@@ -43,20 +42,11 @@ export const numberFormatToLocale = (
// (locale, options) combinations is small and bounded in practice, so cache the
// instances instead of rebuilding them on every call.
const numberFormatCache = new Map<string, Intl.NumberFormat>();
let numberFormatCacheVersion = getLocaleDataVersion();
const getNumberFormatter = (
locale: string | string[] | undefined,
options: Intl.NumberFormatOptions
): Intl.NumberFormat => {
// The Intl polyfill falls back to another locale while the data for the
// requested one is still loading, e.g. right after a language change.
// Start over when locale data is added, so the cache doesn't keep those.
const version = getLocaleDataVersion();
if (version !== numberFormatCacheVersion) {
numberFormatCache.clear();
numberFormatCacheVersion = version;
}
const key = JSON.stringify([locale, options]);
let formatter = numberFormatCache.get(key);
if (!formatter) {
+1 -1
View File
@@ -9,7 +9,7 @@ import {
// The filters of the Marketplace tables. Search, sorting and grouping are kept
// by the data table, see data-table-query-params.
export const marketplaceFilterQueryParamConfig = {
list: ["status", "type", "source", "integration_category", "connectivity"],
list: ["status", "type", "source", "integration_category"],
} as const satisfies QueryParamConfig;
export type MarketplaceFilterQueryParams = QueryParamValues<
@@ -37,29 +37,3 @@ export const preserveUnchangedRecord = <T>(
}
return changed ? next : previous;
};
/**
* List variant of {@link preserveUnchangedRecord}: replaces each item in `next`
* with the equal `previous` item that has the same key, in place.
*/
export const preserveUnchangedItems = <T>(
previous: readonly T[] | undefined,
next: T[],
getKey: (item: T) => string,
equal: (a: T, b: T) => boolean
): T[] => {
if (!previous?.length) {
return next;
}
const previousByKey = new Map<string, T>();
for (const item of previous) {
previousByKey.set(getKey(item), item);
}
for (let i = 0; i < next.length; i++) {
const previousItem = previousByKey.get(getKey(next[i]));
if (previousItem !== undefined && equal(previousItem, next[i])) {
next[i] = previousItem;
}
}
return next;
};
+2 -3
View File
@@ -273,7 +273,7 @@ export class HaCameraPlayer extends LitElement {
const aspectRatio = this._aspectRatio();
if (aspectRatio !== this._firedAspectRatio) {
this._firedAspectRatio = aspectRatio;
fireEvent(this, "media-size-changed", { aspectRatio });
fireEvent(this, "camera-aspect-ratio-changed", { aspectRatio });
}
if (changedProps.has("keepAwake")) {
if (this.keepAwake) {
@@ -1338,7 +1338,6 @@ declare global {
"ha-camera-player": HaCameraPlayer;
}
interface HASSDomEvents {
/** The natural width limits the picture's width when it is set */
"media-size-changed": { aspectRatio: number; naturalWidth?: number };
"camera-aspect-ratio-changed": { aspectRatio: number };
}
}
+93 -267
View File
@@ -9,7 +9,6 @@ import {
import { differenceInMinutes } from "date-fns";
import type {
DataZoomComponentOption,
GridComponentOption,
MarkAreaComponentOption,
} from "echarts/components";
import type { EChartsType } from "echarts/core";
@@ -28,7 +27,6 @@ import {
eventOptions,
property,
query,
queryAll,
state,
} from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -152,9 +150,6 @@ const processSeriesTooltipFormatter = (s: HaECSeriesItem): RawSeriesOption => {
export type CustomLegendOption = ECOption["legend"] & {
type: "custom";
// "y-axis" lists the items beside the chart, each one next to its category,
// in place of the y-axis labels.
position?: "bottom" | "y-axis";
data?: {
id?: string;
secondaryIds?: string[]; // Other dataset IDs that should be controlled by this legend item.
@@ -253,9 +248,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@query(".chart") private _chartContainer?: HTMLDivElement;
@queryAll(".chart-legend button[data-id]")
private _legendButtons!: NodeListOf<HTMLElement>;
@query(".sonification-output")
private _sonificationOutput?: HTMLDivElement;
@@ -327,25 +319,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
},
});
// The axis legend takes width from the chart without resizing the host
private _chartResizeController = new ResizeController(this, {
target: null,
callback: (entries) => {
const contentRect = entries[entries.length - 1]?.contentRect;
if (
this.chart &&
contentRect &&
(Math.round(contentRect.width) !== this.chart.getWidth() ||
Math.round(contentRect.height) !== this.chart.getHeight())
) {
this._shouldResizeChart = true;
this._resizeChartIfNeeded();
}
},
});
private _focusedLegendButton?: { id: string; toggle: boolean };
private _loading = false;
private _reducedMotion = false;
@@ -468,7 +441,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!this.isConnected) {
return;
}
this._chartResizeController.observe(this._chartContainer!);
// The only measurement taken here: neither observer has reported yet, and a
// chart first rendered inside a hidden container has to defer its setup
// rather than build against a guessed width.
@@ -517,16 +489,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
public willUpdate(changedProps: PropertyValues): void {
const focused = this.shadowRoot?.activeElement as HTMLElement | null;
this._focusedLegendButton =
focused?.dataset.id &&
focused.closest(".chart-legend") &&
focused.matches(":focus-visible")
? {
id: focused.dataset.id,
toggle: focused.classList.contains("legend-toggle"),
}
: undefined;
if (!this.chart) {
return;
}
@@ -634,7 +596,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this._resizeChartIfNeeded();
}
this._renderedLegendFit = this._legendFit.fit;
this._restoreLegendFocus();
if (changedProps.has("options") || changedProps.has("data")) {
// New values keep the widest widths, but other items are fitted afresh
const legendItemsKey = JSON.stringify(
@@ -649,30 +610,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
}
// The legend reuses its buttons when items move, which would leave focus on
// whichever item now sits where the focused one was
private _restoreLegendFocus() {
const focused = this._focusedLegendButton;
const active = this.shadowRoot?.activeElement as HTMLElement | null;
if (!focused || active?.dataset.id === focused.id) {
return;
}
const className = focused.toggle ? "legend-toggle" : "label";
Array.from(this._legendButtons)
.find(
(button) =>
button.dataset.id === focused.id &&
button.classList.contains(className)
)
?.focus();
}
protected render() {
const sonifiable =
!this._sonificationUnavailable &&
canSonifyChart(this.data, this._hiddenDatasets);
const showZoomSlider = this._showZoomSlider();
const axisLegend = this._hasAxisLegend();
return html`
<div
class="container ${classMap({ "has-height": !!this.height })}"
@@ -684,14 +626,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
})}
>
<div
class="chart-container ${classMap({
"has-axis-legend": axisLegend,
})}"
class="chart-container"
style=${styleMap({
height: this.height ? undefined : `${this._getDefaultHeight()}px`,
})}
>
${axisLegend ? this._renderAxisLegend() : nothing}
<div
class="chart ${classMap({
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
@@ -717,7 +656,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
${showZoomSlider ? this._renderZoomSlider() : nothing}
</div>
<div class="sonification-output"></div>
${axisLegend ? nothing : this._renderLegend()}
${this._renderLegend()}
<div class="top-controls ${classMap({ small: this.smallControls })}">
<slot name="search"></slot>
<div
@@ -744,22 +683,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
`;
}
private _getCustomLegend() {
if (!this.options?.legend) {
private _getLegendItems() {
if (!this.options?.legend || !this.data) {
return undefined;
}
return ensureArray(this.options.legend).find(
const legend = ensureArray(this.options.legend).find(
(l) => l.show && l.type === "custom"
) as CustomLegendOption | undefined;
}
private _hasAxisLegend() {
return this._getCustomLegend()?.position === "y-axis";
}
private _getLegendItems() {
const legend = this._getCustomLegend();
if (!legend || !this.data) {
if (!legend) {
return undefined;
}
const datasets = ensureArray(this.data);
@@ -776,6 +707,20 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!items) {
return nothing;
}
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
const datasetById = new Map<unknown, (typeof datasets)[number]>();
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
for (const dataset of datasets) {
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
datasetById.set(dataset.id, dataset);
}
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
datasetByName.set(dataset.name, dataset);
}
}
const fit = this._legendFit.fit ?? items.length;
return html`<div
class=${classMap({
@@ -784,7 +729,73 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
})}
>
<ul ${this._legendFit.target()}>
${this._renderLegendItems(items, fit)}
${items.map((item, index) => {
let itemStyle: Record<string, any> = {};
let value = "";
let noLabelClick = false;
const name = typeof item === "string" ? item : (item.name ?? "");
let id: string;
if (typeof item === "string") {
id = item;
} else {
id = item.id ?? name;
value = item.value ?? "";
itemStyle = item.itemStyle ?? {};
noLabelClick = item.noLabelClick ?? false;
}
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
const dataset = datasetById.get(id) ?? datasetByName.get(id);
itemStyle = {
color: dataset?.color as string,
...(dataset?.itemStyle as { borderColor?: string }),
...itemStyle,
};
const color = itemStyle?.color as string;
return html`<li
.id=${id}
@pointerdown=${this._legendPointerDown}
@pointerup=${this._legendPointerCancel}
@pointerleave=${this._legendPointerCancel}
@pointercancel=${this._legendPointerCancel}
@contextmenu=${this._legendContextMenu}
class=${classMap({
hidden: this._hiddenDatasets.has(id),
overflow: !this.expandLegend && index >= fit,
})}
>
<button
type="button"
class="legend-toggle"
data-id=${id}
aria-pressed=${!this._hiddenDatasets.has(id)}
.title=${this._i18n.localize(
"ui.components.history_charts.toggle_visibility"
)}
@click=${this._toggleDataset}
>
<ha-svg-icon
.path=${
this._hiddenDatasets.has(id)
? mdiCircleOutline
: mdiCheckCircle
}
style=${styleMap({
color: this._hiddenDatasets.has(id) ? undefined : color,
})}
></ha-svg-icon>
</button>
<button
type="button"
class=${classMap({ label: true, clickable: labelClickable })}
data-id=${id}
.title=${name}
@click=${this._labelClick}
>
${name}
</button>
${value ? html`<div class="value">${value}</div>` : nothing}
</li>`;
})}
${
items.length
? html`<li
@@ -818,107 +829,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
</div>`;
}
private _renderAxisLegend() {
const items = this._getLegendItems() ?? [];
const grid = ensureArray(this._getGridOption()!)[0];
return html`<div class="chart-legend axis-legend">
<ul
@pointerover=${this._axisLegendPointerOver}
@pointerleave=${this._axisLegendPointerLeave}
style=${styleMap({
paddingTop: `${grid.top}px`,
paddingBottom: `${grid.bottom}px`,
})}
>
${this._renderLegendItems(items, items.length)}
</ul>
</div>`;
}
private _renderLegendItems(
items: NonNullable<ReturnType<HaChartBase["_getLegendItems"]>>,
fit: number
) {
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
const datasetById = new Map<unknown, (typeof datasets)[number]>();
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
for (const dataset of datasets) {
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
datasetById.set(dataset.id, dataset);
}
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
datasetByName.set(dataset.name, dataset);
}
}
return items.map((item, index) => {
let itemStyle: Record<string, any> = {};
let value = "";
let noLabelClick = false;
const name = typeof item === "string" ? item : (item.name ?? "");
let id: string;
if (typeof item === "string") {
id = item;
} else {
id = item.id ?? name;
value = item.value ?? "";
itemStyle = item.itemStyle ?? {};
noLabelClick = item.noLabelClick ?? false;
}
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
const dataset = datasetById.get(id) ?? datasetByName.get(id);
itemStyle = {
color: dataset?.color as string,
...(dataset?.itemStyle as { borderColor?: string }),
...itemStyle,
};
const color = itemStyle?.color as string;
return html`<li
.id=${id}
@pointerdown=${this._legendPointerDown}
@pointerup=${this._legendPointerCancel}
@pointerleave=${this._legendPointerCancel}
@pointercancel=${this._legendPointerCancel}
@contextmenu=${this._legendContextMenu}
class=${classMap({
hidden: this._hiddenDatasets.has(id),
overflow: !this.expandLegend && index >= fit,
})}
>
<button
type="button"
class="legend-toggle"
data-id=${id}
aria-pressed=${!this._hiddenDatasets.has(id)}
.title=${this._i18n.localize(
"ui.components.history_charts.toggle_visibility"
)}
@click=${this._toggleDataset}
>
<ha-svg-icon
.path=${
this._hiddenDatasets.has(id) ? mdiCircleOutline : mdiCheckCircle
}
style=${styleMap({
color: this._hiddenDatasets.has(id) ? undefined : color,
})}
></ha-svg-icon>
</button>
<button
type="button"
class=${classMap({ label: true, clickable: labelClickable })}
data-id=${id}
.title=${name}
@click=${this._labelClick}
>
${name}
</button>
${value ? html`<div class="value">${value}</div>` : nothing}
</li>`;
});
}
// Chart2Music adds ~45 kB gzipped, so it is only fetched once someone actually
// moves keyboard focus into a chart.
private async _handleChartFocus() {
@@ -1399,28 +1309,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
private _getGridOption() {
const grid = this.options?.grid;
const axisLegend = this._hasAxisLegend();
if (!axisLegend && (!grid || !this._zoomSliderRoom)) {
if (!grid || !this._zoomSliderRoom) {
return grid;
}
const [first, ...rest] = ensureArray(grid ?? {});
const result: GridComponentOption = { ...first };
if (axisLegend) {
// The legend rows are laid out from these, so labels must not move them
result.top = this._getGridTop();
result.bottom = this._getGridBottom();
result.containLabel = false;
result.outerBoundsMode = "none";
}
if (this._zoomSliderRoom) {
result.bottom = this._getGridBottom() + this._getZoomSliderSpace();
}
return [result, ...rest];
}
private _getGridTop() {
const top = this.options?.grid && ensureArray(this.options.grid)[0].top;
return typeof top === "number" ? top : 0;
const [first, ...rest] = ensureArray(grid);
return [
{ ...first, bottom: this._getGridBottom() + this._getZoomSliderSpace() },
...rest,
];
}
private _getGridBottom() {
@@ -1493,22 +1389,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
} as XAXisOption;
});
}
let yAxis = this.options?.yAxis;
if (this._hasAxisLegend()) {
const [first, ...rest] = ensureArray(yAxis ?? {});
yAxis = [
{
...first,
type: "category",
inverse: true,
data: this._getLegendItems()?.map((item) =>
typeof item === "string" ? item : (item.id ?? item.name)
),
axisLabel: { ...first.axisLabel, show: false },
} as YAXisOption,
...rest,
];
}
let legend = this.options?.legend;
if (legend) {
legend = ensureArray(legend).map((l) =>
@@ -1538,7 +1418,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
grid: this._getGridOption(),
legend,
xAxis,
yAxis,
};
if (options.tooltip) {
@@ -2002,7 +1881,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
series.option.center = null;
series.option.zoom = 1;
});
fireEvent(this, "chart-zoom-reset");
}
private _getGraphRoams(): {
@@ -2140,24 +2018,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
};
private _axisLegendPointerOver(ev: PointerEvent) {
if (ev.pointerType !== "mouse" || !this.chart) {
return;
}
const id = (ev.target as HTMLElement).closest("li")?.id;
if (!id || this._hiddenDatasets.has(id)) {
this._hideTooltip();
return;
}
this.chart.dispatchAction({ type: "showTip", seriesIndex: 0, name: id });
}
private _axisLegendPointerLeave(ev: PointerEvent) {
if (ev.pointerType === "mouse") {
this._hideTooltip();
}
}
private _hideTooltip() {
this.chart?.dispatchAction({ type: "hideTip" });
this.chart?.dispatchAction({
@@ -2462,15 +2322,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
.has-height .chart-container {
flex: 1;
}
.chart-container.has-axis-legend {
display: flex;
/* The chart is not mirrored in RTL, so its legend stays on the left */
direction: ltr;
}
.has-axis-legend .chart {
flex: 1;
min-width: 0;
}
.chart {
height: 100%;
width: 100%;
@@ -2571,29 +2422,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
position: absolute;
visibility: hidden;
}
.chart-legend.axis-legend {
flex: none;
max-width: min(200px, 40%);
max-height: none;
padding: 0;
overflow: visible;
direction: var(--direction);
}
.chart-legend.axis-legend ul {
height: 100%;
box-sizing: border-box;
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
gap: 0;
}
.chart-legend.axis-legend li,
.chart-legend.axis-legend li:has(.legend-toggle) {
flex: 1 1 0;
height: auto;
min-height: 0;
max-width: none;
}
.chart-legend .hidden {
color: var(--secondary-text-color);
}
@@ -2698,7 +2526,5 @@ declare global {
};
"chart-sankeyroam": { zoom: number };
"chart-setup": undefined;
// The user reset the zoom
"chart-zoom-reset": undefined;
}
}
+6 -188
View File
@@ -11,8 +11,6 @@ import type {
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import { reducedMotionContext } from "../../data/context";
@@ -130,25 +128,6 @@ export class HaNetworkGraph extends LitElement {
*/
@property({ attribute: false }) public selectedNode?: string;
/**
* Highlight the neighbors of a node on hover and fade the rest.
*/
@property({ attribute: false }) public hoverFocus = true;
/**
* Distance in pixels from the center of a node within which a click next to
* it still clicks the node, so small nodes are easier to hit. 0 is off.
* Such a click fires a `chart-click` with only `dataType` and `data.id`.
*/
@property({ attribute: false }) public nodeClickRadius = 0;
/**
* Names of the legend categories that are switched off. Keep it up to date
* with `network-legend-changed`, or leave it out to let the legend keep its
* own selection.
*/
@property({ attribute: false }) public hiddenCategories?: string[];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _highlightedNodes?: Set<string>;
@@ -183,8 +162,6 @@ export class HaNetworkGraph extends LitElement {
private _followedChart?: EChartsType;
private _cancelSettledHide?: () => void;
@query("ha-chart-base") private _baseChart?: HaChartBase;
constructor() {
@@ -203,10 +180,6 @@ export class HaNetworkGraph extends LitElement {
this._physicsEnabled =
this.data.nodes.length <= PHYSICS_DISABLE_THRESHOLD;
}
// Before the first render, which counts the visible nodes
if (changedProperties.has("hiddenCategories") && this.hiddenCategories) {
this._hiddenCategories = this.hiddenCategories;
}
}
protected render() {
@@ -230,19 +203,14 @@ export class HaNetworkGraph extends LitElement {
isMobile,
hasHighlightedNodes,
this.selectedNode,
this.hoverFocus,
this._nodePositions,
this._pinnedNodes,
this._fewVisibleNodes()
)}
.options=${this._createOptions(
this.data?.categories,
this.hiddenCategories
)}
.options=${this._createOptions(this.data?.categories)}
height="100%"
.extraComponents=${[GraphChart]}
@chart-setup=${this._handleChartSetup}
@chart-click=${this._handleBaseChartClick}
>
<slot name="search" slot="search"></slot>
<slot name="button" slot="button"></slot>
@@ -266,10 +234,7 @@ export class HaNetworkGraph extends LitElement {
}
private _createOptions = memoizeOne(
(
categories?: NetworkData["categories"],
hiddenCategories?: string[]
): HaECOption => ({
(categories?: NetworkData["categories"]): HaECOption => ({
tooltip: {
trigger: "item",
confine: true,
@@ -281,15 +246,6 @@ export class HaNetworkGraph extends LitElement {
...category,
icon: category.symbol,
})),
// Every category, as a category left out keeps its last selection
...(hiddenCategories && {
selected: Object.fromEntries(
(categories ?? []).map((category) => [
category.name,
!hiddenCategories.includes(category.name),
])
),
}),
bottom: 8,
},
dataZoom: {
@@ -355,7 +311,6 @@ export class HaNetworkGraph extends LitElement {
isMobile: boolean,
hasHighlightedNodes?: boolean,
selectedNode?: string,
hoverFocus = true,
nodePositions: Record<string, { x: number; y: number }> = {},
pinnedNodes: string[] = [],
fewVisibleNodes = true
@@ -390,11 +345,7 @@ export class HaNetworkGraph extends LitElement {
},
},
emphasis: {
focus: hasHighlightedNodes
? "self"
: isMobile || !hoverFocus
? "none"
: "adjacency",
focus: hasHighlightedNodes ? "self" : isMobile ? "none" : "adjacency",
},
force: {
repulsion: [400, 600],
@@ -619,23 +570,12 @@ export class HaNetworkGraph extends LitElement {
}
}
// Fired for every drawn frame, so the page can place things next to nodes
// while the graph moves, and stays idle when it does not
private _handleRendered = () => {
fireEvent(this, "network-graph-rendered", undefined, {
bubbles: false,
composed: false,
});
};
private _handleChartSetup() {
const chart = this._baseChart?.chart;
chart?.getZr().on("click", this._handleEmptyClick);
chart?.on("mousedown", this._handleNodeMouseDown);
chart?.getZr().on("dragstart", this._handleDragStart);
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
chart?.on("rendered", this._handleRendered);
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
@@ -648,22 +588,18 @@ export class HaNetworkGraph extends LitElement {
// last render
this.requestUpdate();
this._updateFollowing();
// The base chart drew the first frame before the listener was added
this._handleRendered();
}
private _handleLegendChange = (params: unknown) => {
const { selected } = params as { selected: Record<string, boolean> };
const fewVisibleNodes = this._fewVisibleNodes();
this._setHiddenCategories(selected);
this._setHiddenCategories(
(params as { selected: Record<string, boolean> }).selected
);
if (this._fewVisibleNodes() !== fewVisibleNodes) {
// The new series option lays out again from where the nodes are now
this._saveNodePositions();
this.requestUpdate();
}
fireEvent(this, "network-legend-changed", {
hidden: this._hiddenCategories,
});
};
private _setHiddenCategories(selected: Record<string, boolean>) {
@@ -672,65 +608,6 @@ export class HaNetworkGraph extends LitElement {
);
}
// A click next to a small node hits nothing, or a link that runs to its
// center, so it clicks the nearest node within nodeClickRadius instead
private _handleEmptyClick = (ev: {
target?: unknown;
offsetX: number;
offsetY: number;
}) => {
if (!ev.target) {
this._clickNearestNode(ev.offsetX, ev.offsetY);
}
};
// The base chart forwards a click on a link, which is replaced by the node
// click, so the page gets one click
private _handleBaseChartClick = (
ev: HASSDomEvent<HASSDomEvents["chart-click"]>
) => {
const { dataType, event } = ev.detail;
if (
dataType === "edge" &&
event &&
this._clickNearestNode(event.offsetX, event.offsetY)
) {
ev.stopPropagation();
}
};
// Returns whether a node was clicked
private _clickNearestNode(offsetX: number, offsetY: number): boolean {
const chart = this._baseChart?.chart;
if (!this.nodeClickRadius || !chart || chart.isDisposed()) {
return false;
}
const series = this._getGraphSeries(chart);
let nearest: { id: string; distance: number } | undefined;
series?.getGraph().eachNode((node: any) => {
const layout: number[] | undefined = node.getLayout();
if (!layout) {
return;
}
const [x, y] = chart.convertToPixel({ seriesId: "network" }, layout);
const distance = Math.hypot(x - offsetX, y - offsetY);
if (
distance <= this.nodeClickRadius &&
(!nearest || distance < nearest.distance)
) {
nearest = { id: node.id, distance };
}
});
if (!nearest) {
return false;
}
fireEvent(this, "chart-click", {
dataType: "node",
data: { id: nearest.id },
} as unknown as HASSDomEvents["chart-click"]);
return true;
}
private _handleNodeMouseDown = (params: {
dataType?: string;
data?: unknown;
@@ -858,62 +735,6 @@ export class HaNetworkGraph extends LitElement {
}
};
/**
* The position of a node in pixels within the graph, or undefined when the
* node is not drawn.
*/
public getNodePosition(id: string): { x: number; y: number } | undefined {
const chart = this._baseChart?.chart;
if (!chart || chart.isDisposed()) {
return undefined;
}
const series = this._getGraphSeries(chart);
const node = series?.getGraph().getNodeById(id);
if (!node) {
return undefined;
}
// The layout already holds where a moving node ends up, the drawn symbol
// where it is now
const transform: number[] | null | undefined = series
.getData()
.getItemGraphicEl(node.dataIndex)
?.getComputedTransform();
if (transform) {
return { x: transform[4], y: transform[5] };
}
const position: number[] | undefined = node.getLayout();
if (!position) {
return undefined;
}
const [x, y] = chart.convertToPixel({ seriesId: "network" }, position);
return { x, y };
}
public hideTooltip(): void {
const chart = this._baseChart?.chart;
if (!chart || chart.isDisposed()) {
return;
}
chart.dispatchAction({ type: "hideTip" });
this._cancelSettledHide?.();
// A resize waits for running animations and shows the tooltip again, so
// it is hidden once more when the chart has settled. Without a resize it
// would hide the next tooltip, so moving the pointer cancels it.
const zr = chart.getZr();
const hideWhenSettled = () => {
this._cancelSettledHide?.();
chart.dispatchAction({ type: "hideTip" });
};
const cancel = () => {
chart.off("finished", hideWhenSettled);
zr.off("mousemove", cancel);
this._cancelSettledHide = undefined;
};
chart.on("finished", hideWhenSettled);
zr.on("mousemove", cancel);
this._cancelSettledHide = cancel;
}
private _centerOnSelectedNode = () => {
const chart = this._followedChart;
if (!chart) {
@@ -1040,8 +861,5 @@ declare global {
}
interface HASSDomEvents {
"node-selected": { id: string };
// The names of the legend categories that are switched off
"network-legend-changed": { hidden: string[] };
"network-graph-rendered": undefined;
}
}
@@ -328,11 +328,6 @@ export function generateStatisticsChartData(
: undefined,
color: chartType === "bar" ? backgroundColor : borderColor,
};
if (chartType === "bar") {
// echarts sizes bars from the smallest gap between points, so sparse
// data (one point, or points far apart) gets huge bars without a cap
(series as BarSeriesOption).barMaxWidth = 50;
}
if (chartStacked) {
series.stack = `band-stacked`;
series.stackStrategy = "samesign";
+2 -6
View File
@@ -73,7 +73,7 @@ export class HaBadge extends LitElement {
width: auto;
border-radius: var(
--ha-badge-border-radius,
calc(var(--ha-border-radius-lg) + 3px)
calc(var(--ha-badge-size, 36px) / 2)
);
background: var(
--ha-card-background,
@@ -132,11 +132,7 @@ export class HaBadge extends LitElement {
::slotted(img[slot="icon"]) {
width: 30px;
height: 30px;
/* Concentric with the badge, the picture sits 3px inside it */
border-radius: calc(
var(--ha-badge-border-radius, calc(var(--ha-border-radius-lg) + 3px)) -
3px
);
border-radius: var(--ha-picture-border-radius);
object-fit: cover;
overflow: hidden;
margin-left: -10px;
+4 -20
View File
@@ -327,7 +327,7 @@ export class HaCodeEditor extends ReactiveElement {
transactions.push({
effects: [
this._loadedCodeMirror!.readonlyCompartment!.reconfigure(
this._readOnlyExtensions()
this._loadedCodeMirror!.EditorView!.editable.of(!this.readOnly)
),
this._loadedCodeMirror!.yamlLintCompartment!.reconfigure(
this.lint && !this.readOnly
@@ -452,7 +452,9 @@ export class HaCodeEditor extends ReactiveElement {
this._loadedCodeMirror.haSyntaxHighlighting,
this._loadedCodeMirror.yamlScalarHighlighter,
this._loadedCodeMirror.yamlScalarHighlightStyle,
this._loadedCodeMirror.readonlyCompartment.of(this._readOnlyExtensions()),
this._loadedCodeMirror.readonlyCompartment.of(
this._loadedCodeMirror.EditorView.editable.of(!this.readOnly)
),
this._loadedCodeMirror.linewrapCompartment.of(
this.linewrap ? this._loadedCodeMirror.EditorView.lineWrapping : []
),
@@ -521,20 +523,6 @@ export class HaCodeEditor extends ReactiveElement {
}
}
private _readOnlyExtensions(): Extension {
const cm = this._loadedCodeMirror!;
if (!this.readOnly) {
return cm.EditorView.editable.of(true);
}
return [
cm.EditorView.editable.of(false),
// Keeps commands like Tab from changing the content once it has focus
cm.EditorState.readOnly.of(true),
// Focusable, so the content can be scrolled with the keyboard
cm.EditorView.contentAttributes.of({ tabindex: "0" }),
];
}
private _fullscreenLabel(): string {
if (this._isFullscreen) {
return (
@@ -1951,10 +1939,6 @@ export class HaCodeEditor extends ReactiveElement {
padding-top: var(--code-editor-toolbar-height);
}
:host(.fullscreen) {
--code-mirror-min-height: 100%;
}
:host(.fullscreen) .cm-editor {
height: 100% !important;
max-height: 100% !important;
+20 -43
View File
@@ -111,11 +111,6 @@ export class HaControlCircularSlider extends LitElement {
@state() public _lastSlider?: ActiveSlider;
// Position of the other handle before the active one started pushing it
private _lowBeforePush?: number;
private _highBeforePush?: number;
private _valueToPercentage(value: number) {
return (
(clamp(value, this.min, this.max) - this.min) / (this.max - this.min)
@@ -127,31 +122,31 @@ export class HaControlCircularSlider extends LitElement {
}
private _steppedValue(value: number) {
// Rounding to the step can overshoot min/max when they aren't multiples of it
return clamp(Math.round(value / this.step) * this.step, this.min, this.max);
return Math.round(value / this.step) * this.step;
}
private _boundedValue(value: number) {
return Math.min(Math.max(value, this.min), this.max);
const min =
this._activeSlider === "high"
? Math.min(this._localLow ?? this.max)
: this.min;
const max =
this._activeSlider === "low"
? Math.max(this._localHigh ?? this.min)
: this.max;
return Math.min(Math.max(value, min), max);
}
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
const activeValue = this._getActiveValue();
if (
this._activeSlider &&
activeValue != null &&
changedProps.has(this._activeSlider) &&
this[this._activeSlider] !== this._lastChanging
) {
this._lastChanging = this._steppedValue(activeValue);
fireEvent(this, `${this._activeSlider}-changing`, {
value: this._lastChanging,
});
this._lastChanging = undefined;
}
if (!this._activeSlider) {
this._lowBeforePush = undefined;
this._highBeforePush = undefined;
if (changedProps.has("value")) {
this._localValue = this.value;
}
@@ -184,10 +179,6 @@ export class HaControlCircularSlider extends LitElement {
disconnectedCallback(): void {
super.disconnectedCallback();
this._destroyListeners();
if (this._activeSlider) {
this._cancelInteraction();
}
}
private _managers: HammerManager[] = [];
@@ -235,19 +226,9 @@ export class HaControlCircularSlider extends LitElement {
switch (this._activeSlider) {
case "high":
this._localHigh = value;
// Push the low handle along instead of stopping at it, and let it
// return to where it was if the drag comes back
if (this._localLow != null) {
this._lowBeforePush ??= this._localLow;
this._localLow = Math.min(this._lowBeforePush, value);
}
break;
case "low":
this._localLow = value;
if (this._localHigh != null) {
this._highBeforePush ??= this._localHigh;
this._localHigh = Math.max(this._highBeforePush, value);
}
break;
case "value":
this._localValue = value;
@@ -267,18 +248,6 @@ export class HaControlCircularSlider extends LitElement {
return undefined;
}
private _cancelInteraction() {
if (this._activeSlider) {
fireEvent(this, `${this._activeSlider}-changing`, {
value: undefined,
});
}
this._activeSlider = undefined;
this._localValue = this.value;
this._localLow = this.low;
this._localHigh = this.high;
}
private _setupListeners() {
if (this._interactions && this._managers.length === 0) {
this._interactions.forEach((interaction) => {
@@ -310,7 +279,15 @@ export class HaControlCircularSlider extends LitElement {
mc.add(new Tap({ event: "singletap" }));
const cancelInteraction = () => {
this._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 });
}
-9
View File
@@ -73,15 +73,6 @@ export class HaDropdown extends Dropdown {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/naming-convention
private override async showMenu() {
// Flip away from the safe areas instead of opening into them, where the
// max-height below would squeeze the menu.
const styles = getComputedStyle(this);
// @ts-ignore flipPadding is typed as a number, floating-ui accepts sides
this.popup.flipPadding = {
top: parseFloat(styles.getPropertyValue("--safe-area-inset-top")) || 0,
bottom:
parseFloat(styles.getPropertyValue("--safe-area-inset-bottom")) || 0,
};
// @ts-ignore
await super.showMenu();
const triggerElement = this.getTrigger();
@@ -83,7 +83,6 @@ const SELECTOR_FALLBACK_VALUES = {
ui_action: undefined,
ui_clock_date_format: undefined,
ui_color: undefined,
ui_condition: undefined,
ui_state_content: undefined,
ui_time_format: undefined,
unit_of_measurement: undefined,
@@ -118,7 +118,6 @@ const SELECTOR_INITIAL_VALUES = {
ui_action: undefined,
ui_clock_date_format: undefined,
ui_color: undefined,
ui_condition: () => [],
ui_state_content: undefined,
ui_time_format: undefined,
unit_of_measurement: undefined,
+1 -1
View File
@@ -45,7 +45,7 @@ function adjustRgb(
if (wv != null) {
return rgbw2rgb([...rgb, wv] as [number, number, number, number]);
}
if (cw != null && ww != null) {
if (cw != null && ww !== null) {
return rgbww2rgb(
[...rgb, cw, ww] as [number, number, number, number, number],
minKelvin,
+1 -121
View File
@@ -1,20 +1,11 @@
import type { PropertyValues } from "lit";
import { ReactiveElement, render, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property } from "lit/decorators";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import hash from "object-hash";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { rewriteHtmlUrls } from "../common/dom/rewrite-html-urls";
import { internationalizationContext } from "../data/context";
import type { FootnoteLabels } from "../resources/markdown-worker";
import {
USER_CONTENT_PREFIX,
userContentId,
} from "../resources/markdown-user-content";
import { renderMarkdown } from "../resources/render-markdown";
import type { HomeAssistantInternationalization } from "../types";
import { CacheManager } from "../util/cache-manager";
const h = (template: ReturnType<typeof unsafeHTML>) => html`${template}`;
@@ -52,35 +43,8 @@ class HaMarkdownElement extends ReactiveElement {
// For content whose relative addresses belong elsewhere, like a README
@property({ attribute: false }) public rewriteUrl?: (url: string) => string;
// Without translations, like on the auth pages, the worker uses English
@state({
hasChanged: (value?: FootnoteLabels, oldValue?: FootnoteLabels) =>
value?.heading !== oldValue?.heading ||
value?.backReference !== oldValue?.backReference,
})
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FootnoteLabels>({
transformer: ({ localize }) => {
const heading = localize("ui.components.markdown.footnotes");
const backReference = localize(
"ui.components.markdown.footnote_back_reference",
{ reference: "{0}" }
);
return heading && backReference ? { heading, backReference } : undefined;
},
})
private _footnoteLabels?: FootnoteLabels;
public connectedCallback() {
super.connectedCallback();
this.addEventListener("click", this._handleAnchorClick);
}
public disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("click", this._handleAnchorClick);
if (this.cache) {
const key = this._computeCacheKey();
markdownCache.set(key, this.innerHTML);
@@ -123,7 +87,6 @@ class HaMarkdownElement extends ReactiveElement {
allowDataUrl: this.allowDataUrl,
breaks: this.breaks,
rewriteUrl: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
});
}
@@ -138,7 +101,6 @@ class HaMarkdownElement extends ReactiveElement {
allowSvg: this.allowSvg,
allowDataUrl: this.allowDataUrl,
allowRelativeUrls: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
}
);
@@ -241,88 +203,6 @@ class HaMarkdownElement extends ReactiveElement {
}
private _resize = () => fireEvent(this, "content-resize");
// The content is in a shadow root, so the browser can't scroll to a `#` link
// in it, and the app would navigate to it instead
private _handleAnchorClick = (ev: MouseEvent) => {
// Leave opening the link in a new tab or window to the browser
if (
ev.defaultPrevented ||
ev.button !== 0 ||
ev.metaKey ||
ev.ctrlKey ||
ev.shiftKey
) {
return;
}
const anchor = ev
.composedPath()
.find((node) => node instanceof HTMLAnchorElement);
// Or one the author set to open somewhere else
if (anchor?.target && anchor.target !== "_self") {
return;
}
const href = anchor?.getAttribute("href");
if (!href?.startsWith("#") || href.length === 1) {
return;
}
const fragment = href.slice(1);
// Browsers take #top as the top of the page, READMEs use it for the top
const target =
this._findAnchorTarget(fragment) ??
(fragment.toLowerCase() === "top" ? this : undefined);
// An anchor that isn't in the content does what it did before
if (target) {
ev.preventDefault();
target.scrollIntoView({ block: "start" });
// Move focus there too, like the browser does, so Tab carries on from
// the target. -1 makes a heading focusable without adding it to Tab.
if (target instanceof HTMLElement) {
if (!target.hasAttribute("tabindex") && target.tabIndex < 0) {
target.tabIndex = -1;
}
target.focus({ preventScroll: true });
}
}
};
// Links like `#Setup` and `#%C3%BCber` still find `user-content-setup` and
// `user-content-über`, like on GitHub
private _findAnchorTarget(fragment: string) {
let decoded = fragment;
try {
decoded = decodeURIComponent(fragment);
} catch {
// Not encoded, look for it as written
}
const ids = [fragment, decoded, decoded.toLowerCase()].flatMap((id) => [
userContentId(id),
// Heading ids always get the prefix, so `## user-content-setup` has
// `user-content-user-content-setup`
`${USER_CONTENT_PREFIX}${id}`,
]);
for (const id of new Set(ids)) {
const target = this.querySelector(`[id="${CSS.escape(id)}"]`);
if (target) {
return target;
}
}
return undefined;
}
}
declare global {
-15
View File
@@ -201,21 +201,6 @@ export class HaMarkdown extends LitElement {
margin-inline: 0;
padding-inline: 1em;
}
section[data-footnotes] {
border-top: 1px solid var(--divider-color);
margin-top: var(--ha-space-4);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
/* Read out by screen readers but not shown, like on GitHub */
section[data-footnotes] > h2 {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
` as CSSResultGroup;
}
+31 -47
View File
@@ -1,23 +1,17 @@
import { mdiDelete, mdiPlayBox, mdiPlus } from "@mdi/js";
import type { HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { supportsFeature } from "../common/entity/supports-feature";
import type { LocalizeFunc } from "../common/translations/localize";
import { statesContext } from "../data/context";
import type { MediaPickedEvent } from "../data/media-player";
import {
MediaClassBrowserSettings,
MediaPlayerEntityFeature,
} from "../data/media-player";
import type { MediaSelector, MediaSelectorValue } from "../data/selector";
import type { HomeAssistant } from "../types";
import "./ha-alert";
import "./ha-form/ha-form";
import type { SchemaUnion } from "./ha-form/types";
@@ -37,6 +31,8 @@ const EMPTY_FORM = {};
@customElement("ha-media-item-picker")
export class HaMediaItemPicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: MediaSelector;
@property({ attribute: false }) public value?: MediaSelectorValue;
@@ -55,26 +51,6 @@ export class HaMediaItemPicker extends LitElement {
filter_entity?: string | string[];
};
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HassEntities | null, boolean>({
transformer: function (this: HaMediaItemPicker, states) {
const entityId = this._getActiveEntityId();
if (!entityId) {
return true;
}
const stateObj = states?.[entityId];
return (
!!stateObj &&
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA)
);
},
watch: ["value", "context"],
})
private _supportsBrowse?: boolean;
private _contextEntities: string[] | undefined;
private get _hasAccept(): boolean {
@@ -92,6 +68,13 @@ export class HaMediaItemPicker extends LitElement {
protected render() {
const entityId = this._getActiveEntityId();
const stateObj = entityId ? this.hass.states[entityId] : undefined;
const supportsBrowse =
!entityId ||
(stateObj &&
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA));
if (this.selector.media?.image_upload && !this.value) {
return html`${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-picture-upload
@@ -115,7 +98,7 @@ export class HaMediaItemPicker extends LitElement {
.value=${entityId}
.label=${
this.label ||
this._localize(
this.hass.localize(
"ui.components.selectors.media.pick_media_player"
)
}
@@ -131,19 +114,20 @@ export class HaMediaItemPicker extends LitElement {
`
}
${
this._supportsBrowse === false
!supportsBrowse
? html`
${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-alert>
${this._localize(
${this.hass.localize(
"ui.components.selectors.media.browse_not_supported"
)}
</ha-alert>
<ha-form
.hass=${this.hass}
.data=${this.value || EMPTY_FORM}
.schema=${MANUAL_SCHEMA}
.computeLabel=${this._computeLabel(this._localize)}
.computeHelper=${this._computeHelper(this._localize)}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
></ha-form>
`
: html`${this.label ? html`<label>${this.label}</label>` : nothing}
@@ -153,7 +137,9 @@ export class HaMediaItemPicker extends LitElement {
role="button"
aria-label=${
!this.value?.media_content_id
? this._localize("ui.components.selectors.media.pick_media")
? this.hass.localize(
"ui.components.selectors.media.pick_media"
)
: this.value.metadata?.title || this.value.media_content_id
}
@click=${this._pickMedia}
@@ -210,7 +196,7 @@ export class HaMediaItemPicker extends LitElement {
<div class="title">
${
!this.value?.media_content_id
? this._localize(
? this.hass.localize(
"ui.components.selectors.media.pick_media"
)
: this.value.metadata?.title ||
@@ -223,7 +209,7 @@ export class HaMediaItemPicker extends LitElement {
: html`
<div class="delete">
<ha-icon-button
.label=${this._localize("ui.common.delete")}
.label=${this.hass.localize("ui.common.delete")}
.path=${mdiDelete}
@click=${this._clearValue}
></ha-icon-button>
@@ -241,7 +227,7 @@ export class HaMediaItemPicker extends LitElement {
variant="danger"
@click=${this._clearValue}
>
${this._localize(
${this.hass.localize(
"ui.components.picture-upload.clear_picture"
)}
</ha-button>
@@ -257,17 +243,15 @@ export class HaMediaItemPicker extends LitElement {
`;
}
private _computeLabel = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}`)
);
private _computeLabelCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}`);
private _computeHelper = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}_detail`)
);
private _computeHelperCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}_detail`);
private _entityChanged(ev: CustomEvent) {
ev.stopPropagation();
@@ -4,7 +4,7 @@ import { consume } from "../../common/decorators/consume";
import { fireEvent } from "../../common/dom/fire_event";
import { transform } from "../../common/decorators/transform";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import type { ButtonToggleSelector } from "../../data/selector";
import type { ButtonToggleSelector, SelectOption } from "../../data/selector";
import { internationalizationContext } from "../../data/context";
import type { FrontendLocaleData } from "../../data/translation";
import type {
@@ -41,8 +41,8 @@ export class HaButtonToggleSelector extends LitElement {
const options =
this.selector.button_toggle?.options?.map((option) =>
typeof option === "object"
? { ...option, label: option.label ?? option.value }
: { value: option, label: option }
? (option as SelectOption)
: ({ value: option, label: option } as SelectOption)
) || [];
const translationKey = this.selector.button_toggle?.translation_key;
@@ -64,7 +64,7 @@ export class HaButtonToggleSelector extends LitElement {
);
}
const toggleButtons: ToggleButton[] = options.map((item) => ({
const toggleButtons: ToggleButton[] = options.map((item: SelectOption) => ({
label: item.label,
value: item.value,
}));
@@ -1,14 +1,10 @@
import { mdiMagnify, mdiMapSearchOutline } from "@mdi/js";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import { transform } from "../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { configContext, internationalizationContext } from "../../data/context";
import type {
LocationSelector,
LocationSelectorValue,
@@ -18,10 +14,7 @@ import {
formatOpenStreetMapPlace,
searchPlaces,
} from "../../data/openstreetmap";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../types";
import type { HomeAssistant } from "../../types";
import type { SchemaUnion } from "../ha-form/types";
import type { HaListItemButton } from "../item/ha-list-item-button";
import { searchResultsStatus } from "../list/search-results-status";
@@ -35,7 +28,6 @@ import "../ha-alert";
import "../ha-icon-button";
import "../item/ha-list-item-button";
import "../list/ha-list-base";
import "../animation/ha-fade-in";
import "../ha-spinner";
import "../ha-svg-icon";
import "../input/ha-input";
@@ -47,6 +39,8 @@ import {
@customElement("ha-selector-location")
export class HaLocationSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: LocationSelector;
@property({ type: Object }) public value?: LocationSelectorValue;
@@ -57,17 +51,6 @@ export class HaLocationSelector extends LitElement {
@property({ type: Boolean, reflect: true }) public disabled = false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig | undefined>({
transformer: ({ config }) => config ?? undefined,
})
private _hassConfig?: HassConfig;
@state() private _working = false;
@state() private _places?: OpenStreetMapPlace[] | null;
@@ -123,10 +106,10 @@ export class HaLocationSelector extends LitElement {
);
protected willUpdate() {
if (!this.value && this._hassConfig) {
if (!this.value) {
this.value = {
latitude: this._hassConfig.latitude,
longitude: this._hassConfig.longitude,
latitude: this.hass.config.latitude,
longitude: this.hass.config.longitude,
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
};
}
@@ -138,7 +121,7 @@ export class HaLocationSelector extends LitElement {
<div class="location-search" @keydown=${this._searchKeyDown}>
<ha-input
label=${this._i18n.localize(
label=${this.hass.localize(
"ui.components.selectors.location.address_label"
)}
.disabled=${this.disabled}
@@ -154,7 +137,7 @@ export class HaLocationSelector extends LitElement {
: html`<ha-icon-button
slot="end"
.path=${mdiMapSearchOutline}
.label=${this._i18n.localize("ui.common.search")}
.label=${this.hass.localize("ui.common.search")}
.disabled=${this.disabled}
@click=${this._searchButtonClicked}
></ha-icon-button>`
@@ -164,7 +147,7 @@ export class HaLocationSelector extends LitElement {
${
this._searchError
? html`<ha-alert alert-type="error">
${this._i18n.localize(
${this.hass.localize(
"ui.components.selectors.location.search_error"
)}
</ha-alert>`
@@ -182,7 +165,7 @@ export class HaLocationSelector extends LitElement {
Array.isArray(this._places) && this._places.length
? html`
<ha-list-base
aria-label=${this._i18n.localize(
aria-label=${this.hass.localize(
"ui.components.selectors.location.search_results_label"
)}
>
@@ -191,13 +174,13 @@ export class HaLocationSelector extends LitElement {
`
: this._places?.length === 0
? html`<p class="search-no-results">
${this._i18n.localize("ui.components.combo-box.no_match")}
${this.hass.localize("ui.components.combo-box.no_match")}
</p>`
: nothing
}
<p class="attribution">
${this._i18n.localize(
${this.hass.localize(
"ui.components.selectors.location.search_disclosure",
{
openstreetmap: html`<a
@@ -210,7 +193,7 @@ export class HaLocationSelector extends LitElement {
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
target="_blank"
rel="noopener noreferrer"
>${this._i18n.localize(
>${this.hass.localize(
"ui.components.selectors.location.osm_privacy_policy"
)}</a
>`,
@@ -219,27 +202,18 @@ export class HaLocationSelector extends LitElement {
</p>
</div>
${
this._hassConfig
? html`<ha-locations-editor
class="flex"
.helper=${this.helper}
.locations=${this._location(
this.selector,
this._hassConfig,
this.value
)}
@location-updated=${this._locationChanged}
@radius-updated=${this._radiusChanged}
pin-on-click
></ha-locations-editor>`
: html`<ha-fade-in .delay=${500}
><ha-spinner></ha-spinner
></ha-fade-in>`
}
<ha-locations-editor
class="flex"
.helper=${this.helper}
.locations=${this._location(this.selector, this.value)}
@location-updated=${this._locationChanged}
@radius-updated=${this._radiusChanged}
pin-on-click
></ha-locations-editor>
<ha-form
.hass=${this.hass}
.schema=${this._schema(
this._i18n.localize,
this.hass.localize,
this.selector.location?.radius,
this.selector.location?.radius_readonly
)}
@@ -254,7 +228,6 @@ export class HaLocationSelector extends LitElement {
private _location = memoizeOne(
(
selector: LocationSelector,
hassConfig: HassConfig,
value?: LocationSelectorValue
): MarkerLocation[] => {
const computedStyles = getComputedStyle(this);
@@ -267,11 +240,11 @@ export class HaLocationSelector extends LitElement {
id: "location",
latitude:
!value || isNaN(value.latitude)
? hassConfig.latitude
? this.hass.config.latitude
: value.latitude,
longitude:
!value || isNaN(value.longitude)
? hassConfig.longitude
? this.hass.config.longitude
: value.longitude,
radius: selector.location?.radius
? value?.radius || DEFAULT_RADIUS
@@ -313,7 +286,7 @@ export class HaLocationSelector extends LitElement {
entry: SchemaUnion<ReturnType<typeof this._schema>>
): string => {
if (entry.name) {
return this._i18n.localize(
return this.hass.localize(
`ui.components.selectors.location.${entry.name}`
);
}
@@ -364,17 +337,12 @@ export class HaLocationSelector extends LitElement {
this._status = undefined;
try {
this._places = await searchPlaces(
searchTerm,
this._i18n.locale.language,
true,
3
);
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
this._status = searchResultsStatus(
searchTerm,
this._places,
() => true,
this._i18n.localize
this.hass.localize
);
} catch (_err) {
this._places = undefined;
@@ -430,7 +398,7 @@ export class HaLocationSelector extends LitElement {
this._input?.focus({ preventScroll: true });
}
this._places = undefined;
this._status = this._i18n.localize(
this._status = this.hass.localize(
"ui.components.selectors.location.selected_location",
{ location: place.display_name }
);
@@ -1,12 +1,15 @@
import { html, LitElement, type TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import type { MediaSelector, MediaSelectorValue } from "../../data/selector";
import type { HomeAssistant } from "../../types";
import "../ha-media-item-picker";
import { ensureArray } from "../../common/array/ensure-array";
import { fireEvent } from "../../common/dom/fire_event";
@customElement("ha-selector-media")
export class HaMediaSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: MediaSelector;
@property({ attribute: false }) public value?:
@@ -31,6 +34,7 @@ export class HaMediaSelector extends LitElement {
changeCallback?
): TemplateResult {
return html`<ha-media-item-picker
.hass=${this.hass}
.context=${this.context}
.selector=${this.selector}
.value=${value}
@@ -4,6 +4,7 @@ import memoizeOne from "memoize-one";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { fireEvent } from "../../common/dom/fire_event";
import type { PeriodKey, PeriodSelector } from "../../data/selector";
import type { HomeAssistant } from "../../types";
import { deepEqual } from "../../common/util/deep-equal";
import type { LocalizeFunc } from "../../common/translations/localize";
import "../ha-form/ha-form";
@@ -27,6 +28,8 @@ const PERIODS = {
@customElement("ha-selector-period")
export class HaPeriodSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: PeriodSelector;
@property({ attribute: false }) public value?: unknown;
@@ -84,6 +87,7 @@ export class HaPeriodSelector extends LitElement {
return html`
<ha-form
.hass=${this.hass}
.data=${data}
.schema=${schema}
.computeHelper=${this._computeHelperCallback}
@@ -26,20 +26,6 @@ import "../ha-svg-icon";
import "../radio/ha-radio-group";
import "../radio/ha-radio-option";
const SEARCH_MIN_OPTIONS = 12;
const SEARCH_KEYS = [{ name: "primary", weight: 1 }];
// Every value gets the prefix, so "" has a non-empty ID and no value can
// collide with another value's ID.
const PICKER_ID_PREFIX = "option:";
export const toPickerId = (value: string | number) =>
`${PICKER_ID_PREFIX}${value}`;
export const findPickerOption = (options: SelectOption[], id?: string) =>
options.find((option) => toPickerId(option.value) === id);
@customElement("ha-selector-select")
export class HaSelectSelector extends LitElement {
@state()
@@ -93,12 +79,6 @@ export class HaSelectSelector extends LitElement {
if (localizedLabel) {
option.label = localizedLabel;
}
const localizedDescription = this.localizeValue!(
`${translationKey}.options_description.${option.value}`
);
if (localizedDescription) {
option.description = localizedDescription;
}
});
}
@@ -276,23 +256,6 @@ export class HaSelectSelector extends LitElement {
`;
}
if (options.length > SEARCH_MIN_OPTIONS) {
return html`
<ha-generic-picker
no-sort
.label=${this.label}
.helper=${this.helper}
.disabled=${this.disabled}
.required=${this.required}
.getItems=${this._getSearchItems(options)}
.value=${this._pickerValue(options)}
.valueRenderer=${this._valueRenderer(options)}
.searchKeys=${SEARCH_KEYS}
@value-changed=${this._searchPickerChanged}
></ha-generic-picker>
`;
}
return html`
<ha-select
.label=${this.label ?? ""}
@@ -327,8 +290,8 @@ export class HaSelectSelector extends LitElement {
(selector: SelectSelector) =>
selector.select?.options?.map((option) =>
typeof option === "object"
? { ...option, label: option.label ?? option.value }
: { value: String(option), label: option }
? (option as SelectOption)
: ({ value: String(option), label: option } as SelectOption)
) || []
);
@@ -347,37 +310,6 @@ export class HaSelectSelector extends LitElement {
}
);
private _getSearchItems = memoizeOne(
(options: SelectOption[]) => () =>
options.map((option) => ({
id: toPickerId(option.value),
primary: option.label,
sorting_label: option.label,
disabled: option.disabled,
}))
);
private _pickerValue(options: SelectOption[]): string | undefined {
const value = this.value as string | number | undefined;
if (typeof value !== "string" && typeof value !== "number") {
return undefined;
}
if (value === "" && !options.some((option) => option.value === "")) {
return undefined;
}
return toPickerId(value);
}
private _valueRenderer = memoizeOne(
(options: SelectOption[]) => (id: string) =>
html`<span slot="headline"
>${
findPickerOption(options, id)?.label ??
id.slice(PICKER_ID_PREFIX.length)
}</span
>`
);
private get _mode(): "list" | "dropdown" | "box" {
return (
this.selector.select?.mode ||
@@ -452,36 +384,6 @@ export class HaSelectSelector extends LitElement {
});
}
private _searchPickerChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (this.disabled) {
return;
}
const id: string | undefined = ev.detail.value;
if (id === undefined) {
if (this.value !== undefined) {
fireEvent(this, "value-changed", { value: undefined });
}
return;
}
// Look the pick up in the current options: the open list can be older.
const option = findPickerOption(this._getOptions(this.selector), id);
if (
!option ||
option.disabled ||
(this.value != null && String(option.value) === String(this.value))
) {
return;
}
fireEvent(this, "value-changed", { value: option.value });
}
private _comboBoxValueChanged(ev: CustomEvent): void {
ev.stopPropagation();
const newValue = ev.detail.value;
@@ -1,52 +0,0 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import type { UiConditionSelector } from "../../data/selector";
import "../../panels/lovelace/editor/conditions/ha-card-conditions-editor";
import type { VisibilityCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
@customElement("ha-selector-ui_condition")
export class HaUiConditionSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false })
public selector!: UiConditionSelector;
@property({ attribute: false }) public value?: VisibilityCondition[];
@property() public label?: string;
@property({ type: Boolean }) public disabled = false;
protected firstUpdated() {
// The editor's labels come from the dashboard translations, which only
// load with a dashboard; this selector can show anywhere.
this.hass.loadFragmentTranslation("lovelace");
}
protected render() {
return html`
${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-card-conditions-editor
.hass=${this.hass}
.conditions=${this.value ?? []}
.disabled=${this.disabled}
></ha-card-conditions-editor>
`;
}
static styles = css`
label {
display: block;
margin-bottom: var(--ha-space-1);
font-weight: var(--ha-font-weight-medium);
color: var(--secondary-text-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-selector-ui_condition": HaUiConditionSelector;
}
}
@@ -69,7 +69,6 @@ const LOAD_ELEMENTS = {
ui_action: () => import("./ha-selector-ui-action"),
ui_clock_date_format: () => import("./ha-selector-ui-clock-date-format"),
ui_color: () => import("./ha-selector-ui-color"),
ui_condition: () => import("./ha-selector-ui-condition"),
ui_state_content: () => import("./ha-selector-ui-state-content"),
ui_time_format: () => import("./ha-selector-ui-time-format"),
unit_of_measurement: () => import("./ha-selector-unit-of-measurement"),
+16 -48
View File
@@ -23,7 +23,6 @@ import {
getPanelIcon,
getPanelIconPath,
getPanelTitle,
getSelectedPanelUrlPath,
} from "../data/panel";
import type { PersistentNotification } from "../data/persistent_notification";
import { subscribeNotifications } from "../data/persistent_notification";
@@ -232,36 +231,12 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
return nothing;
}
const selectedPanel = this.hass.panelUrl;
// prettier-ignore
return html`
${this._renderHeader()}
${this._renderAllPanels()}`;
}
private _computeSidebarPanels(): [PanelInfo[], PanelInfo[]] | undefined {
if (!this._panelOrder || !this._hiddenPanels) {
return undefined;
}
return computePanels(
this.hass.panels,
getDefaultPanelUrlPath(this.hass),
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
}
private _computeSelectedPanel(
sidebarPanels: [PanelInfo[], PanelInfo[]] | undefined,
route: Route | undefined
): string {
if (!route) {
return this.hass.panelUrl;
}
const urlPaths = (sidebarPanels ?? [[], []])
.flat()
.map((panel) => panel.url_path);
return getSelectedPanelUrlPath(urlPaths, route.path);
${this._renderAllPanels(selectedPanel)}`;
}
protected shouldUpdate(changedProps: PropertyValues): boolean {
@@ -279,20 +254,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
) {
return true;
}
if (!this.hass) {
return false;
}
if (changedProps.has("route")) {
const sidebarPanels = this._computeSidebarPanels();
const oldRoute = changedProps.get("route") as Route | undefined;
if (
this._computeSelectedPanel(sidebarPanels, oldRoute) !==
this._computeSelectedPanel(sidebarPanels, this.route)
) {
return true;
}
}
if (!changedProps.has("hass")) {
if (!this.hass || !changedProps.has("hass")) {
return false;
}
const oldHass = changedProps.get("hass") as HomeAssistant;
@@ -393,9 +355,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
private _renderAllPanels() {
const sidebarPanels = this._computeSidebarPanels();
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
private _renderAllPanels(selectedPanel: string) {
const renderList = (content, cls: string, scrollable: boolean) =>
html`<ha-list-nav
class=${classMap({
@@ -405,7 +365,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
>${content}</ha-list-nav
>`;
if (!sidebarPanels) {
if (!this._panelOrder || !this._hiddenPanels) {
return html`<div class="panels-list">
<div class="wrapper">
${renderList(
@@ -430,7 +390,15 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
const [beforeSpacer, afterSpacer] = sidebarPanels;
const defaultPanel = getDefaultPanelUrlPath(this.hass);
const [beforeSpacer, afterSpacer] = computePanels(
this.hass.panels,
defaultPanel,
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
// prettier-ignore
return html`<div class="panels-list">
@@ -474,7 +442,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
}
private _renderPanel(panel: PanelInfo, isSelected: boolean) {
const title = getPanelTitle(this.hass.localize, panel);
const title = getPanelTitle(this.hass, panel);
const urlPath = panel.url_path;
const icon = getPanelIcon(panel);
const iconPath = getPanelIconPath(panel);
-1
View File
@@ -200,7 +200,6 @@ class HaEntityMarker extends LitElement {
}
.entity-picture {
background-size: cover;
background-position: center;
height: 100%;
width: 100%;
}
-14
View File
@@ -1812,20 +1812,6 @@ export class HaMap extends ReactiveElement {
#map.clickable {
cursor: pointer;
}
/* Bubble avatars open their entity; the expanded bubble around them
takes no click of its own */
.maplibregl-marker ha-entity-marker {
cursor: pointer;
}
/* A drag that starts on a marker pans the map like anywhere else;
markers that drag themselves keep their own cursor */
.maplibregl-canvas-container.maplibregl-interactive:active
.maplibregl-marker:not(.maplibregl-marker-draggable),
.maplibregl-canvas-container.maplibregl-interactive:active
.maplibregl-marker:not(.maplibregl-marker-draggable)
ha-entity-marker {
cursor: grabbing !important;
}
.maplibregl-marker {
transition:
opacity var(--ha-animation-duration-fast),
@@ -1,619 +0,0 @@
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import type {
ExtractedSkeleton,
SkeletonPiece,
} from "../../common/dom/extract-skeleton";
import { extractSkeleton } from "../../common/dom/extract-skeleton";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { parseAnimationDuration } from "../../common/util/parse-animation-duration";
import { internationalizationContext } from "../../data/context";
import type { HaSkeleton } from "./ha-skeleton";
import "./ha-skeleton";
export interface SkeletonLoadingDetail {
loading: boolean;
}
interface ArrivingParts {
/* The whole content, when it was hidden rather than its parts */
content: Element[];
opacityParts: (HTMLElement | SVGElement)[];
colorParts: HTMLElement[];
}
/* Transitions are held off too, so a part hides at once rather than easing
out from under its skeleton */
type HiddenProperty = "opacity" | "color" | "transition";
interface HiddenStyle {
/* The inline value from before anything hid it */
value: string;
/* The value it was hidden with */
hidden: string;
holders: number;
}
/* Overlays nest, as a stack card's cards each have their own, so two can
hide the same element. The first to hide one notes the value it really
had, and only the last to let go puts that back, so neither keeps the
other's hidden value as the one to restore. */
const hiddenStyles: Record<
HiddenProperty,
Map<HTMLElement | SVGElement, HiddenStyle>
> = { opacity: new Map(), color: new Map(), transition: new Map() };
const hideStyle = (
element: HTMLElement | SVGElement,
name: HiddenProperty,
hidden: string
) => {
const held = hiddenStyles[name].get(element);
if (held) {
held.holders++;
} else {
hiddenStyles[name].set(element, {
value: element.style[name],
hidden,
holders: 1,
});
}
element.style[name] = hidden;
};
const releaseStyle = (
element: HTMLElement | SVGElement,
name: HiddenProperty
) => {
const held = hiddenStyles[name].get(element);
if (!held) {
return;
}
held.holders--;
if (held.holders === 0) {
// Content that set its own value while it was hidden keeps that one
if (element.style[name] === held.hidden) {
element.style[name] = held.value;
}
hiddenStyles[name].delete(element);
}
};
const holdersOf = (element: HTMLElement | SVGElement, name: HiddenProperty) =>
hiddenStyles[name].get(element)?.holders ?? 0;
/* What's left out with data-skeleton="none" under an element, through
shadow roots, as the skeleton is read */
const leftOut = (root: Element | ShadowRoot): HTMLElement[] =>
[...root.querySelectorAll("*")].flatMap((element) => [
...(element instanceof HTMLElement && element.dataset.skeleton === "none"
? [element]
: []),
...(element.shadowRoot ? leftOut(element.shadowRoot) : []),
]);
/**
* Shows a skeleton of its content while that content loads, read from the
* content itself: each line of text, icon, image, control and drawing gets
* its own piece. When loading ends, the pieces go and each part fades in.
*
* Loading is on while `loading` is set, or while anything inside has fired
* a `skeleton-loading` event with `{ loading: true }` and not yet
* `{ loading: false }`. The event stops at the nearest overlay, so content
* doesn't need to know what wraps it.
*
* To take over:
* - put your own skeleton in the `skeleton` slot, and it's used instead of
* reading one
* - set `data-skeleton` on any element inside, as described in
* `extract-skeleton`, to change how that part is read or leave it out
* - call `refresh()` when the content changes without changing size
*
* With nothing to read yet, such as before the content's code has loaded,
* it fills itself with one plain wave. The skeleton follows the host's
* corner radius.
*
* @slot - The content.
* @slot skeleton - A skeleton of your own, used instead of reading one.
*/
@customElement("ha-skeleton-overlay")
export class HaSkeletonOverlay extends LitElement {
@property({ type: Boolean }) public loading = false;
@property() public effect: HaSkeleton["effect"] = "sheen";
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n?: ContextType<typeof internationalizationContext>;
/* What's inside that has said it's loading */
@state() private _loadingSources = new Set<EventTarget>();
@state() private _pieces?: SkeletonPiece[];
@state() private _customSkeleton = false;
@state() private _onScreen = true;
@query("slot:not([name])") private _contentSlot?: HTMLSlotElement;
/* The parts this overlay hides, through hideStyle */
private _hiddenOpacity = new Set<HTMLElement | SVGElement>();
private _hiddenColor = new Set<HTMLElement>();
private _heldTransition = new Set<HTMLElement | SVGElement>();
/* Inline colours of content left out inside hidden text, which keeps its
own colour meanwhile */
private _keptColor = new Map<HTMLElement, string>();
private _wasLoading = false;
/* What to fade in once loading has ended */
private _arriving?: ArrivingParts;
/* The fades still running from the last time loading ended */
private _fades: Animation[] = [];
private _measureFrame?: number;
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
private _intersectionObserver = new IntersectionObserver((entries) => {
this._onScreen = entries[entries.length - 1].isIntersecting;
});
constructor() {
super();
// On the host rather than the slot, so content that says it's loading
// as it connects, before the first render, is heard
this.addEventListener("skeleton-loading", this._skeletonLoading);
}
public connectedCallback() {
super.connectedCallback();
this._resizeObserver.observe(this);
this._intersectionObserver.observe(this);
this._scheduleMeasure();
}
public disconnectedCallback() {
super.disconnectedCallback();
this._resizeObserver.disconnect();
this._intersectionObserver.disconnect();
if (this._measureFrame !== undefined) {
cancelAnimationFrame(this._measureFrame);
this._measureFrame = undefined;
}
// Never leave the content hidden while it's away
this._cancelFades();
this._showParts();
}
/** Read the skeleton again, after the content changed but not its size */
public refresh() {
this._scheduleMeasure();
}
private get _isLoading() {
return this.loading || this._loadingSources.size > 0;
}
protected willUpdate(changedProperties: PropertyValues<this>) {
super.willUpdate(changedProperties);
const loading = this._isLoading;
if (loading && !this._wasLoading) {
// A fade still running would show the content over the hidden style
this._cancelFades();
this._customSkeleton = [...this.children].some(
(child) => child.slot === "skeleton"
);
}
if (!loading && this._wasLoading) {
this._endLoading();
}
this._wasLoading = loading;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
// Only when loading starts: loading events, slot changes, sizes and
// refresh() ask for their own, and measuring after every update would
// run each frame for content that animates, such as a spinner, as every
// reading comes out different and updates again
if (this._isLoading && changedProperties.has("loading")) {
this._scheduleMeasure();
}
if (this._arriving) {
this._fadeIn(this._arriving);
this._arriving = undefined;
}
}
protected render() {
const loading = this._isLoading;
// Named like ha-spinner, which falls back to English before translations
// have loaded
const label = this._i18n?.localize("ui.common.loading") || "Loading";
// The content can't be focused, used or read out while it loads, frames
// around the hidden parts included, such as a card that takes clicks
return html`
<div class="content" ?inert=${loading}>
<slot
class=${classMap({
// Before the first reading, or under a skeleton of your own
hidden:
loading && (this._customSkeleton || this._pieces === undefined),
})}
@slotchange=${this._contentChanged}
></slot>
</div>
${
loading
? html`
<div class="skeleton" role="progressbar" aria-label=${label}>
<slot
name="skeleton"
@slotchange=${this._skeletonSlotChanged}
></slot>
${this._customSkeleton ? nothing : this._renderPieces()}
</div>
`
: nothing
}
`;
}
private _renderPieces() {
// Nothing still animates off screen
const effect = this._onScreen ? this.effect : "none";
if (!this._pieces?.length) {
return html`<ha-skeleton class="fill" .effect=${effect}></ha-skeleton>`;
}
return this._pieces.map((piece) =>
piece.kind === "scrim"
? html`<div class="piece" style=${pieceStyle(piece)}></div>`
: html`<ha-skeleton
class=${classMap({
piece: true,
[piece.kind]: true,
"on-dark": Boolean(piece.onDark),
})}
.effect=${effect}
style=${pieceStyle(piece)}
></ha-skeleton>`
);
}
private _skeletonLoading = (ev: HASSDomEvent<SkeletonLoadingDetail>) => {
// The nearest overlay owns it
ev.stopPropagation();
const source = ev.composedPath()[0];
const sources = new Set(this._loadingSources);
if (ev.detail.loading) {
sources.add(source);
} else {
sources.delete(source);
}
this._loadingSources = sources;
this._scheduleMeasure();
};
private _contentChanged() {
this._resizeObserver.disconnect();
this._resizeObserver.observe(this);
this._contentSlot
?.assignedElements()
.forEach((element) => this._resizeObserver.observe(element));
this._pruneSources();
this._scheduleMeasure();
}
/* Content that went away, or moved out of this overlay, can't finish
loading here. Removing it deep inside a card fires no slotchange, so
this runs on every measure too, which any change of size starts. */
private _pruneSources() {
const sources = [...this._loadingSources].filter((source) =>
this._holds(source)
);
if (sources.length !== this._loadingSources.size) {
this._loadingSources = new Set(sources);
}
}
/* Whether a source is still inside this overlay, the way its events
travel: through the slots content shows in, and out of shadow roots */
private _holds(source: EventTarget) {
if (!(source instanceof Node)) {
return true;
}
let node: Node | null = source;
while (node) {
if (node === this) {
return true;
}
node =
node instanceof ShadowRoot
? node.host
: ((node instanceof Element || node instanceof Text
? node.assignedSlot
: null) ?? node.parentNode);
}
return false;
}
private _skeletonSlotChanged(ev: Event) {
const slot = ev.target;
if (!(slot instanceof HTMLSlotElement)) {
return;
}
this._customSkeleton = slot.assignedNodes({ flatten: true }).length > 0;
if (this._customSkeleton) {
// The whole content is hidden under it instead
this._showParts();
this._pieces = undefined;
} else {
// Read from the content again now it's gone
this._scheduleMeasure();
}
}
private _scheduleMeasure() {
if (this._measureFrame !== undefined || !this.isConnected) {
return;
}
this._measureFrame = requestAnimationFrame(() => {
this._measureFrame = undefined;
this._measure();
});
}
/* Read the skeleton from the content, and hide the parts it stands in for */
private _measure() {
this._pruneSources();
if (!this._isLoading || this._customSkeleton) {
return;
}
// Read from the content as it really looks, then hide it again before
// the next paint, so nothing flickers
this._showParts();
const skeleton = extractSkeleton(this, this.getBoundingClientRect());
this._hideParts(skeleton);
if (JSON.stringify(skeleton.pieces) !== JSON.stringify(this._pieces)) {
this._pieces = skeleton.pieces;
}
}
private _hideParts(skeleton: ExtractedSkeleton) {
skeleton.parts.forEach((part) => {
if (!this._hiddenOpacity.has(part)) {
this._hiddenOpacity.add(part);
hideStyle(part, "opacity", "0");
}
});
// What's left out with data-skeleton="none" inside text that's hidden
// keeps the colour it has now, rather than taking the transparent one.
// Read before any text is hidden.
const kept = skeleton.textParts.flatMap((part) =>
leftOut(part).map(
(element) => [element, getComputedStyle(element).color] as const
)
);
// Text goes through its colour, so a frame drawn by the same element,
// such as a badge's pill, stays
skeleton.textParts.forEach((part) => {
if (!this._hiddenColor.has(part)) {
this._hiddenColor.add(part);
hideStyle(part, "color", "transparent");
}
});
kept.forEach(([element, color]) => {
if (!this._keptColor.has(element)) {
this._keptColor.set(element, element.style.color);
}
element.style.color = color;
});
// In the same frame as the hiding, so no transition runs on it
[...skeleton.parts, ...skeleton.textParts].forEach((part) => {
if (!this._heldTransition.has(part)) {
this._heldTransition.add(part);
hideStyle(part, "transition", "none");
}
});
}
private _showParts() {
this._hiddenOpacity.forEach((part) => releaseStyle(part, "opacity"));
this._hiddenColor.forEach((part) => releaseStyle(part, "color"));
this._keptColor.forEach((color, element) => {
element.style.color = color;
});
this._heldTransition.forEach((part) => releaseStyle(part, "transition"));
this._hiddenOpacity.clear();
this._hiddenColor.clear();
this._keptColor.clear();
this._heldTransition.clear();
}
/* Show the content again before the next paint, and note what to fade in */
private _endLoading() {
// Under a skeleton of its own, or before the first reading, the whole
// content was hidden rather than its parts
const wholeContent = this._customSkeleton || this._pieces === undefined;
this._arriving = {
content: wholeContent
? (this._contentSlot?.assignedElements() ?? [])
: [],
// Only what this overlay is the last to hide shows now; a part a
// nested overlay still hides stays hidden, and fades in with that one
opacityParts: [...this._hiddenOpacity].filter(
(part) => holdersOf(part, "opacity") === 1
),
colorParts: [...this._hiddenColor].filter(
(part) => holdersOf(part, "color") === 1
),
};
this._showParts();
this._pieces = undefined;
}
/* Fade each arriving part in, instantly with reduced motion */
private _fadeIn({ content, opacityParts, colorParts }: ArrivingParts) {
// In ms or s, as the token can be either; 150ms only when it isn't set
const token = getComputedStyle(this)
.getPropertyValue("--ha-animation-duration-fast")
.trim();
const fade: KeyframeAnimationOptions = {
duration: token ? parseAnimationDuration(token) : 150,
easing: "ease-out",
};
this._fades = [
// To each part's own opacity, which isn't always 1
...[...content, ...opacityParts].map((part) => {
const opacity = getComputedStyle(part).opacity;
return part.animate([{ opacity: 0 }, { opacity }], fade);
}),
...colorParts.map((part) => {
const color = getComputedStyle(part).color;
return part.animate([{ color: "transparent" }, { color }], fade);
}),
];
}
private _cancelFades() {
this._fades.forEach((fade) => fade.cancel());
this._fades = [];
}
static readonly styles: CSSResultGroup = css`
:host {
display: block;
position: relative;
}
.content {
display: contents;
}
slot.hidden::slotted(*) {
opacity: 0;
}
.skeleton {
position: absolute;
inset: 0;
overflow: hidden;
border-radius: inherit;
pointer-events: none;
}
/* Rounded by the layer it fills, which follows the host */
.fill {
position: absolute;
inset: 0;
--ha-skeleton-border-radius: 0;
}
.piece {
position: absolute;
min-height: 0;
}
.piece.round {
--ha-skeleton-border-radius: var(--ha-border-radius-circle);
}
.piece.shape {
--ha-skeleton-border-radius: 0;
mask-size: 100% 100%;
-webkit-mask-size: 100% 100%;
mask-repeat: no-repeat;
-webkit-mask-repeat: no-repeat;
}
/* Text and icons on a dark bar over a picture */
.piece.on-dark {
--ha-skeleton-color: rgba(255, 255, 255, 0.3);
--ha-skeleton-sheen-color: rgba(255, 255, 255, 0.5);
}
`;
}
const pieceStyle = ({ maskBox, ...piece }: SkeletonPiece) => {
const maskPosition = maskBox ? `${maskBox.x}px ${maskBox.y}px` : undefined;
const maskSize = maskBox
? `${maskBox.width}px ${maskBox.height}px`
: undefined;
return styleMap({
left: `${piece.x}px`,
top: `${piece.y}px`,
width: `${piece.width}px`,
height: `${piece.height}px`,
"--ha-skeleton-border-radius": piece.radius,
"border-radius": piece.kind === "scrim" ? piece.radius : undefined,
"background-color": piece.background,
"mask-image": piece.mask,
"-webkit-mask-image": piece.mask,
"mask-position": maskPosition,
"-webkit-mask-position": maskPosition,
"mask-size": maskSize,
"-webkit-mask-size": maskSize,
});
};
declare global {
interface HTMLElementTagNameMap {
"ha-skeleton-overlay": HaSkeletonOverlay;
}
interface HASSDomEvents {
"skeleton-loading": SkeletonLoadingDetail;
}
// for add event listener
interface HTMLElementEventMap {
"skeleton-loading": HASSDomEvent<HASSDomEvents["skeleton-loading"]>;
}
}
+4
View File
@@ -4,12 +4,15 @@ import { customElement, property } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import type { LogbookEntry } from "../../data/logbook";
import type { HomeAssistant } from "../../types";
import "./hat-logbook-note";
import "../../panels/logbook/ha-logbook-renderer";
import type { TraceExtended } from "../../data/trace";
@customElement("ha-trace-logbook")
export class HaTraceLogbook extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@property({ attribute: false }) public trace!: TraceExtended;
@@ -23,6 +26,7 @@ export class HaTraceLogbook extends LitElement {
return this.logbookEntries.length
? html`
<ha-logbook-renderer
.hass=${this.hass}
.entries=${this.logbookEntries}
.narrow=${this.narrow}
no-detail
@@ -566,6 +566,7 @@ export class HaTracePathDetails extends LitElement {
return entries.length
? html`
<ha-logbook-renderer
.hass=${this.hass}
.entries=${entries}
.narrow=${this.narrow}
no-detail
+5 -8
View File
@@ -11,7 +11,6 @@ import type {
HassEntityBase,
} from "home-assistant-js-websocket";
import { supportsFeature } from "../common/entity/supports-feature";
import type { LocalizeFunc } from "../common/translations/localize";
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
import type { HomeAssistant } from "../types";
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
@@ -109,9 +108,7 @@ export const supportedAlarmModes = (stateObj: AlarmControlPanelEntity) =>
export const setProtectedAlarmControlPanelMode = async (
element: HTMLElement,
callService: HomeAssistant["callService"],
callWS: HomeAssistant["callWS"],
localize: LocalizeFunc,
hass: Pick<HomeAssistant, "callService" | "localize" | "callWS">,
stateObj: AlarmControlPanelEntity,
mode: AlarmMode
) => {
@@ -126,7 +123,7 @@ export const setProtectedAlarmControlPanelMode = async (
(mode === "disarmed" && stateObj.attributes.code_format)
) {
const entry = await getExtendedEntityRegistryEntry(
callWS,
hass.callWS,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
@@ -136,10 +133,10 @@ export const setProtectedAlarmControlPanelMode = async (
const response = await showEnterCodeDialog(element, {
codeFormat: stateObj.attributes.code_format,
title: localize(
title: hass.localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
submitText: localize(
submitText: hass.localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
});
@@ -150,7 +147,7 @@ export const setProtectedAlarmControlPanelMode = async (
}
}
await callService("alarm_control_panel", service, {
await hass.callService("alarm_control_panel", service, {
entity_id: stateObj.entity_id,
code,
});
-20
View File
@@ -103,23 +103,3 @@ export const CLIMATE_HVAC_MODE_ICONS: Record<HvacMode, string> = {
export const climateHvacModeIcon = (mode: string) =>
CLIMATE_HVAC_MODE_ICONS[mode] || mdiThermostat;
export type ClimateTarget = "value" | "low" | "high";
/**
* The targets to change when one target is set. A low or high target that
* passes the other one pushes it along, so the range never ends up inverted.
*/
export const pushTargetTemperature = (
current: Partial<Record<ClimateTarget, number>>,
target: ClimateTarget,
value: number
): Partial<Record<ClimateTarget, number>> => {
if (target === "low" && current.high != null && value > current.high) {
return { low: value, high: value };
}
if (target === "high" && current.low != null && value < current.low) {
return { low: value, high: value };
}
return { [target]: value };
};
+1 -6
View File
@@ -158,12 +158,7 @@ export const computeNavigationPathInfo = (
const isDashboard = panel?.component_name === "lovelace";
const panelInfo: NavigationPathInfo = {
label:
getPanelTitleFromUrlPath(
options.localize,
options.panels,
panelUrlPath
) || panelUrlPath,
label: getPanelTitleFromUrlPath(options, panelUrlPath) || panelUrlPath,
icon: panelIcon || (isDashboard ? "mdi:view-dashboard" : undefined),
iconPath: panelIconPath || mdiLink,
};
-74
View File
@@ -32,7 +32,6 @@ import type { EntityNameItem } from "../common/entity/entity_name_config";
import { formatNumberWithUnit } from "../common/number/format_number";
import { normalizeValueBySIPrefix } from "../common/number/normalize-by-si-prefix";
import { groupBy } from "../common/util/group-by";
import { generateUuidV4 } from "../common/util/uuid";
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
import { fileDownload } from "../util/file_download";
import type {
@@ -344,31 +343,6 @@ export interface WaterSourceTypeEnergyPreference {
name?: string;
}
export type FixedCostType = "grid" | "gas" | "water";
export type FixedCostPeriod = "day" | "month" | "year";
export interface FixedCostEnergyPreference {
id: string;
type: FixedCostType;
name: string;
// Charged at the start of each period, exactly one of these is set
number_amount: number | null;
entity_amount: string | null;
period: FixedCostPeriod;
}
export const emptyFixedCostEnergyPreference = (
type: FixedCostType
): FixedCostEnergyPreference => ({
id: generateUuidV4(),
type,
name: "",
number_amount: null,
entity_amount: null,
period: "day",
});
export type EnergySource =
| SolarSourceTypeEnergyPreference
| HomeSourceTypeEnergyPreference
@@ -382,7 +356,6 @@ export interface EnergyPreferences {
device_consumption: DeviceConsumptionEnergyPreference[];
device_consumption_water: DeviceConsumptionEnergyPreference[];
device_consumption_gas: DeviceConsumptionEnergyPreference[];
fixed_costs: FixedCostEnergyPreference[];
}
export const EMPTY_PREFERENCES: EnergyPreferences = {
@@ -390,13 +363,10 @@ export const EMPTY_PREFERENCES: EnergyPreferences = {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
export interface EnergyInfo {
cost_sensors: Record<string, string>;
// Fixed cost id to the entity ID of its cost sensor
fixed_cost_sensors: Record<string, string>;
solar_forecast_domains: string[];
}
@@ -411,7 +381,6 @@ export interface EnergyPreferencesValidation {
device_consumption: EnergyValidationIssue[][];
device_consumption_water: EnergyValidationIssue[][];
device_consumption_gas: EnergyValidationIssue[][];
fixed_costs: EnergyValidationIssue[][];
}
export const getEnergyInfo = (callWS: HomeAssistant["callWS"]) =>
@@ -474,30 +443,6 @@ export interface EnergySourceByType {
export const energySourcesByType = (prefs: EnergyPreferences) =>
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
export type FixedCostsByType = Partial<
Record<FixedCostType, FixedCostEnergyPreference[]>
>;
export const fixedCostsByType = (prefs: EnergyPreferences) =>
groupBy(prefs.fixed_costs, (item) => item.type) as FixedCostsByType;
/** Sum of the fixed costs, or undefined without cost data. */
export const calculateFixedCostTotal = (
fixedCosts: FixedCostEnergyPreference[],
info: EnergyInfo,
stats: Statistics
): number | undefined => {
let total: number | undefined;
for (const fixedCost of fixedCosts) {
const statId = info.fixed_cost_sensors[fixedCost.id];
const cost = statId ? calculateStatisticSumGrowth(stats[statId]) : null;
if (cost !== null) {
total = (total ?? 0) + cost;
}
}
return total;
};
/** Import cost minus export compensation, or undefined without cost data. */
export const calculateGridNetCost = (
sources: GridSourceTypeEnergyPreference[],
@@ -813,15 +758,6 @@ export const getReferencedStatisticIds = (
...prefs.device_consumption_gas.map((d) => d.stat_consumption)
);
}
for (const fixedCost of prefs.fixed_costs) {
if (includeTypes && !includeTypes.includes(fixedCost.type)) {
continue;
}
const costStatId = info.fixed_cost_sensors[fixedCost.id];
if (costStatId) {
statIDs.push(costStatId);
}
}
return statIDs;
};
@@ -2655,9 +2591,6 @@ export const formatFlowRateShort = (
export type WaterGasResource = "water" | "gas";
/** The device categories the device graphs can show. */
export type DeviceConsumptionResource = "electricity" | "gas";
export const getWaterGasDevicesKey = (resource: WaterGasResource) =>
`device_consumption_${resource}` as const;
@@ -3005,13 +2938,6 @@ export const downloadEnergyData = (
printCategory("device_consumption_gas", gasDevices, state.gasUnit);
}
energyData.prefs.fixed_costs.forEach((fixedCost) => {
const costId = state.info.fixed_cost_sensors[fixedCost.id];
if (costId) {
processStat(costId, `${fixedCost.type}_fixed_cost`, currency);
}
});
const { summedData } = getSummedData(state);
const { consumption } = computeConsumptionData(summedData, undefined);
-4
View File
@@ -77,10 +77,6 @@ export const filterGroupsWithListedMembers = (
): string[] => {
const listed = new Set(entityIds);
const hasListedDescendant = (groupId: string): boolean => {
const groupObj = states[groupId];
if (!groupObj || !computeGroupMemberIds(groupObj)) {
return false;
}
const seen = new Set([groupId]);
const queue = [groupId];
while (queue.length) {
+2 -30
View File
@@ -250,16 +250,13 @@ export type IconCategory =
| "services"
| "triggers"
| "conditions"
| "integration_category"
| "integration_connectivity";
| "integration_category";
export type IntegrationCategoryIcons = Record<
string,
{ default: string; subcategory?: Record<string, { default: string }> }
>;
export type IntegrationConnectivityIcons = Record<string, { default: string }>;
interface CategoryType {
entity: PlatformIcons;
entity_component: ComponentIcons;
@@ -267,7 +264,6 @@ interface CategoryType {
triggers: TriggerIcons;
conditions: ConditionIcons;
integration_category: IntegrationCategoryIcons;
integration_connectivity: IntegrationConnectivityIcons;
}
export const getHassIcons = async <T extends IconCategory>(
@@ -338,10 +334,7 @@ export const getComponentIcons = async (
export const getCategoryIcons = async <
T extends Exclude<
IconCategory,
| "entity"
| "entity_component"
| "integration_category"
| "integration_connectivity"
"entity" | "entity_component" | "integration_category"
>,
>(
connection: Connection,
@@ -782,24 +775,3 @@ export const getIntegrationCategoryIcons = async (
return undefined;
}
};
let integrationConnectivityIcons:
ReturnType<typeof getHassIcons<"integration_connectivity">> | undefined;
export const getIntegrationConnectivityIcons = async (
connection: Connection
): Promise<IntegrationConnectivityIcons | undefined> => {
// Cache the request itself, so callers while it loads share it
integrationConnectivityIcons ??= getHassIcons(
connection,
"integration_connectivity",
"homeassistant"
);
try {
const result = await integrationConnectivityIcons;
return result.resources.homeassistant;
} catch (_err) {
integrationConnectivityIcons = undefined;
return undefined;
}
};
-15
View File
@@ -1,15 +0,0 @@
import type { LocalizeFunc } from "../common/translations/localize";
import type { IntegrationConnectivityIcons } from "./icons";
// The name of a connectivity, like `zigbee`. Empty for one this Home Assistant
// doesn't know.
export const integrationConnectivityName = (
localize: LocalizeFunc,
slug: string
): string =>
localize(`component.homeassistant.integration_connectivity.${slug}.name`);
export const integrationConnectivityIcon = (
icons: IntegrationConnectivityIcons | undefined,
slug: string
): string | undefined => icons?.[slug]?.default;
+7 -17
View File
@@ -4,7 +4,7 @@ import type { TimestampStateDomain } from "../common/const";
import { computeDomain } from "../common/entity/compute_domain";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import type { LocalizeFunc } from "../common/translations/localize";
import type { HomeAssistant, HomeAssistantFormatters } from "../types";
import type { HomeAssistant } from "../types";
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
import { isNumericEntity } from "./history";
@@ -316,34 +316,24 @@ const STATE_ACTION_MESSAGES: Record<
const RESTORABLE_BUTTON_DOMAINS = new Set(["button", "input_button"]);
export type LogbookStateFormatters = Pick<
HomeAssistantFormatters,
"formatEntityState" | "formatEntityAttributeValue"
>;
export const localizeStateMessage = (
localize: LocalizeFunc,
formatters: LogbookStateFormatters,
hass: HomeAssistant,
state: string,
stateObj: HassEntity,
domain: string,
entry?: LogbookEntry
): string => {
if (state === UNKNOWN || state === UNAVAILABLE) {
return formatters.formatEntityState(stateObj, state);
return hass.formatEntityState(stateObj, state);
}
// Events show the triggered event type, falling back to a generic label when
// the type is unknown (the timestamp state is meaningless on its own).
if (domain === "event") {
const eventType = entry?.attributes?.event_type;
if (eventType != null) {
return formatters.formatEntityAttributeValue(
stateObj,
"event_type",
eventType
);
return hass.formatEntityAttributeValue(stateObj, "event_type", eventType);
}
return localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
}
const actionKey: LogbookActionMessage | undefined =
STATE_ACTION_MESSAGES[domain as keyof typeof STATE_ACTION_MESSAGES];
@@ -356,11 +346,11 @@ export const localizeStateMessage = (
actionKey &&
(!RESTORABLE_BUTTON_DOMAINS.has(domain) || matchesEntryTime)
) {
return localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
}
// Every other domain reuses the backend state translation, so the logbook
// speaks the same vocabulary as the rest of the UI.
return formatters.formatEntityState(stateObj, state);
return hass.formatEntityState(stateObj, state);
};
export const filterLogbookCompatibleEntities = (entity) => {
-3
View File
@@ -10,9 +10,6 @@ export interface RepositoryBase {
can_install: boolean;
category: RepositoryType;
config_flow: boolean;
// How an integration connects, like `zigbee` or `cloud`. Empty for other
// repositories and for integrations that don't set it.
connectivity?: string[];
custom: boolean;
description: string;
domain: string | null;
+2 -2
View File
@@ -62,14 +62,14 @@ export const formatOpenStreetMapPlace = (
export const searchPlaces = (
address: string,
language: string,
hass: HomeAssistant,
addressdetails?: boolean,
limit?: number
): Promise<OpenStreetMapPlace[]> => {
const params = new URLSearchParams({
q: address,
format: "jsonv2",
"accept-language": language,
"accept-language": hass.locale.language,
email: "[email protected]",
});
if (limit) {
+8 -27
View File
@@ -8,12 +8,9 @@ import {
mdiMap,
mdiPlayBoxMultiple,
} from "@mdi/js";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../common/translations/localize";
import type { LocalizeKeys } from "../common/translations/localize";
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
import type { HomeAssistant, PanelInfo, Panels } from "../types";
import type { HomeAssistant, PanelInfo } from "../types";
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
export const APP_PANEL = "app";
@@ -69,7 +66,7 @@ export const getPanelNameTranslationKey = (panel: PanelInfo) => {
};
export const getPanelTitle = (
localize: LocalizeFunc,
hass: Pick<HomeAssistant, "localize">,
panel: PanelInfo
): string | undefined => {
if (panel.url_path === "marketplace") {
@@ -78,19 +75,18 @@ export const getPanelTitle = (
const translationKey = getPanelNameTranslationKey(panel);
return localize(translationKey) || panel.title || undefined;
return hass.localize(translationKey) || panel.title || undefined;
};
export const getPanelTitleFromUrlPath = (
localize: LocalizeFunc,
panels: Panels,
hass: Pick<HomeAssistant, "localize" | "panels">,
urlPath: string
): string | undefined => {
if (!panels) {
if (!hass.panels) {
return undefined;
}
const panel = Object.values(panels).find(
const panel = Object.values(hass.panels).find(
(p: PanelInfo): boolean => p.url_path === urlPath
);
@@ -98,7 +94,7 @@ export const getPanelTitleFromUrlPath = (
return undefined;
}
return getPanelTitle(localize, panel);
return getPanelTitle(hass, panel);
};
/**
@@ -200,21 +196,6 @@ export const getPanelIconPath = (panel: PanelInfo): string | undefined => {
export const FIXED_PANELS = [PROFILE_PANEL, "config", NOT_FOUND_PANEL];
// A panel's url_path can span several segments (e.g. "config/logs"), so the
// most specific url_path matching the path wins over its first segment.
export const getSelectedPanelUrlPath = (
urlPaths: string[],
path: string
): string =>
urlPaths.reduce(
(selected, urlPath) =>
urlPath.length > selected.length &&
(path === `/${urlPath}` || path.startsWith(`/${urlPath}/`))
? urlPath
: selected,
path.split("/")[1] ?? ""
);
export interface PanelMutableParams {
title?: string | null;
icon?: string | null;
+1 -1
View File
@@ -57,7 +57,7 @@ const generateNavigationPanelCommands = (
.map(([_panelKey, panel]) => {
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
const primary = getPanelTitle(localize, panel) || panel.url_path;
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
+1 -7
View File
@@ -89,7 +89,6 @@ export type Selector =
| UiActionSelector
| UiClockDateFormatSelector
| UiColorSelector
| UiConditionSelector
| UiStateContentSelector
| UiTimeFormatSelector
| UnitOfMeasurementSelector
@@ -204,11 +203,6 @@ export interface ConditionSelector {
} | null;
}
/** Dashboard conditions, edited like a card's visibility tab. */
export interface UiConditionSelector {
ui_condition: {} | null;
}
export interface ConversationAgentSelector {
conversation_agent: { language?: string } | null;
}
@@ -520,7 +514,7 @@ interface SelectBoxOptionImage {
export interface SelectOption {
value: string;
label?: string;
label: string;
description?: string;
image?: string | SelectBoxOptionImage;
disabled?: boolean;
-2
View File
@@ -223,7 +223,6 @@ export const SENSOR_DEVICE_CLASS_UNITS: Record<string, (string | null)[]> = {
voltage: ["kV", "MV", "mV", "V", "μV"],
volume: ["CCF", "fl. oz.", "ft³", "gal", "L", "MCF", "mL", "m³"],
volume_flow_rate: [
"ft³/h",
"ft³/min",
"gal/d",
"gal/h",
@@ -400,7 +399,6 @@ export const SENSOR_DEVICE_CLASS_CONVERTIBLE_UNITS: Record<
voltage: ["kV", "MV", "mV", "V", "μV"],
volume: ["CCF", "fl. oz.", "ft³", "gal", "L", "MCF", "mL", "m³"],
volume_flow_rate: [
"ft³/h",
"ft³/min",
"gal/d",
"gal/h",
+2 -136
View File
@@ -1,8 +1,7 @@
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
import type { Connection } from "home-assistant-js-websocket";
import { getCollection } from "home-assistant-js-websocket";
import type { Store } from "home-assistant-js-websocket/dist/store";
import type { CallWS } from "../../types";
import type { HassioAddonDetails, HassioAddonsInfo } from "../hassio/addon";
import type { HassioAddonsInfo } from "../hassio/addon";
import type { HassioHassOSInfo, HassioHostInfo } from "../hassio/host";
import type { NetworkInfo } from "../hassio/network";
import type { HassioResolution } from "../hassio/resolution";
@@ -113,139 +112,6 @@ const subscribeSupervisorEventUpdates = (
}
);
const subscribeSupervisorEvents = (
conn: Connection,
onEvent: (event: SupervisorEvent) => void
) =>
conn.subscribeMessage<SupervisorEvent>(onEvent, {
type: "supervisor/subscribe",
});
export type SupervisorAppEvent =
// A store reload can change the latest version of any app
| { type: "store" }
| { type: "app"; slug: string; update: Partial<HassioAddonDetails> }
| {
type: "job";
slug: string;
// install, uninstall, update, rebuild or restore
operation: string;
done: boolean;
};
interface SupervisorJob {
name: string;
reference: string | null;
done: boolean;
child_jobs: SupervisorJob[];
}
// Settings in the v2 "app" status that the app info also has
const APP_SETTINGS_KEYS = [
"version_latest",
"update_available",
"boot",
"watchdog",
"ingress_panel",
"protected",
"auto_update",
] as const;
// Older Supervisors name the app manager jobs addon_manager_*
const appManagerOperation = (jobName: string | undefined) =>
/^(?:addon|app)_manager_(\w+)$/.exec(jobName ?? "")?.[1];
/**
* Parse a Supervisor event that changes the info of an app.
*/
export const parseSupervisorAppEvent = (
event: SupervisorEvent
): SupervisorAppEvent | undefined => {
// Supervisor sends "addon" with only the state, or with its v2 websocket API
// enabled "app" with the full status
if (event.event === "addon" || event.event === "app") {
const update: Partial<HassioAddonDetails> = {
// The app info never reports "stopping"; the app runs until it stops
...(event.state !== "stopping" && { state: event.state }),
// The version is null while the app is not installed
...(event.event === "app" && { version: event.version }),
// The status has no settings while the app is not installed
...(event.version &&
Object.fromEntries(APP_SETTINGS_KEYS.map((key) => [key, event[key]]))),
};
return { type: "app", slug: event.slug, update };
}
if (event.event === "store_reloaded") {
return { type: "store" };
}
const job = event.event === "job" ? event.data : undefined;
// Only manager jobs count: their child jobs share the slug, and start, stop
// and restart jobs change nothing beyond the state events. A manager job can
// itself be a child, for example of a backup restore.
// The first event of a job comes before Supervisor sets its reference.
if (!job?.reference) {
return undefined;
}
const operation = appManagerOperation(job.name);
if (!operation) {
return undefined;
}
return {
type: "job",
slug: job.reference,
operation,
done: job.done === true,
};
};
/**
* Return the app manager operations that run now, keyed by app slug.
*/
export const fetchAppOperations = async (
callWS: CallWS
): Promise<Record<string, string>> => {
const { jobs } = await callWS<{ jobs: SupervisorJob[] }>({
type: "supervisor/api",
endpoint: "/jobs/info",
method: "get",
});
const operations: Record<string, string> = {};
const addOperations = (list: SupervisorJob[]) => {
for (const job of list) {
const operation = appManagerOperation(job.name);
if (operation && job.reference && !job.done) {
operations[job.reference] = operation;
}
addOperations(job.child_jobs ?? []);
}
};
addOperations(jobs);
return operations;
};
/**
* Subscribe to Supervisor events that change app info. Events sent while the
* connection is down are lost, so `onReconnect` runs after each reconnect.
*/
export const subscribeSupervisorAppEvents = async (
conn: Connection,
onEvent: (appEvent: SupervisorAppEvent) => void,
onReconnect: () => void
): Promise<UnsubscribeFunc> => {
const unsub = await subscribeSupervisorEvents(conn, (event) => {
const appEvent = parseSupervisorAppEvent(event);
if (appEvent) {
onEvent(appEvent);
}
});
const handleReady = () => onReconnect();
conn.addEventListener("ready", handleReady);
return () => {
conn.removeEventListener("ready", handleReady);
unsub();
};
};
export const getSupervisorEventCollection = (
conn: Connection,
key: string,
+1 -2
View File
@@ -77,8 +77,7 @@ export type TranslationCategory =
| "services"
| "triggers"
| "conditions"
| "integration_category"
| "integration_connectivity";
| "integration_category";
export const subscribeTranslationPreferences = (
hass: HomeAssistant,
-11
View File
@@ -4,11 +4,9 @@ import type {
HassEntityBase,
HassEvent,
} from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import { BINARY_STATE_OFF, BINARY_STATE_ON } from "../common/const";
import { computeDomain } from "../common/entity/compute_domain";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import { getEntityIds } from "../common/entity/get_entity_ids";
import { supportsFeature } from "../common/entity/supports-feature";
import { formatNumber } from "../common/number/format_number";
import { caseInsensitiveStringCompare } from "../common/string/compare";
@@ -154,15 +152,6 @@ export const filterUpdateEntities = (
);
});
const findUpdateEntityIds = memoizeOne((entityIds: string[]) =>
entityIds.filter((entityId) => computeDomain(entityId) === "update")
);
export const countInstallableUpdates = (states: HassEntities): number =>
findUpdateEntityIds(getEntityIds(states)).filter((entityId) =>
updateCanInstall(states[entityId] as UpdateEntity)
).length;
export const filterUpdateEntitiesParameterized = (
entities: HassEntities,
formatEntityName: HomeAssistant["formatEntityName"],
-4
View File
@@ -104,10 +104,6 @@ export const DOMAINS_HIDE_DEFAULT_MORE_INFO = [
/** Domains that should have the history hidden in the more info dialog. */
export const DOMAINS_MORE_INFO_NO_HISTORY = ["camera", "configurator"];
/** Whether the info view explains why the entity isn't available instead of showing it. */
export const computeShowUnavailableInfo = (stateObj?: HassEntity) =>
!stateObj || Boolean(stateObj.attributes.restored);
export const computeShowHistoryComponent = (
hass: HomeAssistant,
entityId: string
@@ -31,9 +31,11 @@ class MoreInfoAlarmControlPanel extends LitElement {
private async _disarm() {
setProtectedAlarmControlPanelMode(
this,
this._api.callService,
this._api.callWS,
this._localize,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this.stateObj!,
"disarmed"
);
@@ -2,8 +2,6 @@ import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { transform } from "../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import { connectionContext, formattersContext } from "../../../data/context";
import type { ImageEntity } from "../../../data/image";
import { computeImageUrl } from "../../../data/image";
@@ -30,17 +28,6 @@ class MoreInfoImage extends LitElement {
@property({ attribute: false }) public stateObj?: ImageEntity;
private _size?: HASSDomEvents["media-size-changed"];
public connectedCallback() {
super.connectedCallback();
// A cached view that was detached while the picture loaded couldn't send
// its size, and the picture doesn't load again when it's shown
if (this._size) {
fireEvent(this, "media-size-changed", this._size);
}
}
protected render() {
if (!this._connection || !this.stateObj) {
return nothing;
@@ -52,28 +39,16 @@ class MoreInfoImage extends LitElement {
return html`<img
alt=${this._formatEntityName?.(this.stateObj) || this.stateObj.entity_id}
src=${this._connection.hassUrl(imageUrl)}
@load=${this._imageLoaded}
/> `;
}
private _imageLoaded(ev: HASSDomCurrentTargetEvent<HTMLImageElement>) {
const { naturalWidth, naturalHeight } = ev.currentTarget;
if (!naturalWidth || !naturalHeight) {
return;
}
this._size = { aspectRatio: naturalWidth / naturalHeight, naturalWidth };
fireEvent(this, "media-size-changed", this._size);
}
static styles = css`
:host {
display: block;
text-align: center;
}
img {
display: block;
margin: 0 auto;
max-width: 100%;
max-height: var(--more-info-media-max-height, none);
}
`;
}
@@ -1,6 +1,5 @@
import type { ContextType } from "@lit/context";
import type { HassConfig, UnsubscribeFunc } from "home-assistant-js-websocket";
import { ERR_CONNECTION_LOST } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -457,11 +456,6 @@ class MoreInfoUpdate extends LitElement {
false
);
} catch (err: any) {
// The update keeps running when the connection drops during a long install.
if (err?.error?.code === ERR_CONNECTION_LOST) {
return;
}
const message = await this._localizeInstallError(err);
if (this._isShown()) {
@@ -620,14 +620,15 @@ class MoreInfoWeather extends LitElement {
}
.temp-attribute .temp {
position: relative;
margin-right: var(--ha-space-6);
direction: ltr;
}
.temp-attribute .temp span {
position: relative;
position: absolute;
font-size: var(--ha-font-size-2xl);
top: 1px;
vertical-align: top;
}
.state,
+57 -135
View File
@@ -7,7 +7,6 @@ import {
mdiCogOutline,
mdiContentDuplicate,
mdiDevices,
mdiDirections,
mdiDotsVertical,
mdiDownload,
mdiInformationOutline,
@@ -38,8 +37,6 @@ import {
computeEntityNameParts,
type EntityNameType,
} from "../../common/entity/compute_entity_name_display";
import { getEntityLocation } from "../../common/entity/get_entity_location";
import { navigationUrl } from "../../common/map/navigation-url";
import {
getHistoryState,
navigate,
@@ -87,7 +84,6 @@ import { showConfirmationDialog } from "../generic/show-dialog-box";
import {
computeShowHistoryComponent,
computeShowLogBookComponent,
computeShowUnavailableInfo,
DOMAINS_WITH_MORE_INFO,
EDITABLE_DOMAINS_WITH_ID,
EDITABLE_DOMAINS_WITH_UNIQUE_ID,
@@ -153,12 +149,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
@property({ type: Boolean, reflect: true }) public large = false;
// The dialog grows with the camera's or image's picture, as high as there
// is room for
@state() private _mediaAspectRatio?: number;
@state() private _fill = false;
// An image is not shown larger than it is
@state() private _mediaNaturalWidth?: number;
// 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;
@@ -189,8 +183,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
@state() private _entry?: ExtEntityRegistryEntry | null;
private _entryLoadFailed = false;
@state() private _infoEditMode = false;
@state() private _detailsYamlMode = false;
@@ -204,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();
@@ -221,31 +219,22 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._detailsYamlMode = false;
this.large = params.large ?? false;
this._fill = false;
this._open = true;
this._loadEntityRegistryEntry();
}
private async _loadEntityRegistryEntry() {
const entityId = this._entityId;
if (!entityId) {
if (!this._entityId) {
return;
}
if (this._entry?.entity_id !== entityId) {
this._entry = undefined;
}
let entry: ExtEntityRegistryEntry | null | undefined;
let failed = false;
try {
entry = await getExtendedEntityRegistryEntry(this.hass.callWS, entityId);
} catch (err: any) {
// Other errors, like a lost connection, don't tell whether it's
// registered, so it loads again on reconnect
failed = err?.code !== "not_found";
entry = failed ? undefined : null;
}
if (this._entityId === entityId) {
this._entry = entry;
this._entryLoadFailed = failed;
this._entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this._entityId
);
} catch (_e) {
this._entry = null;
}
}
@@ -270,13 +259,14 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._entityId = undefined;
this._parentEntityIds = [];
this._entry = undefined;
this._entryLoadFailed = false;
this._infoEditMode = false;
this._detailsYamlMode = false;
this._initialView = DEFAULT_VIEW;
this._currView = DEFAULT_VIEW;
this._childViewStack = [];
this._returnUrl = undefined;
this._cameraAspectRatio = undefined;
this._cameraControlsHeight = undefined;
this._isEscapeEnabled = true;
window.removeEventListener("dialog-closed", this._enableEscapeKeyClose);
window.removeEventListener("show-dialog", this._disableEscapeKeyClose);
@@ -305,8 +295,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
private _shouldShowHistory(domain: string): boolean {
return (
(DOMAINS_WITH_MORE_INFO.includes(domain) ||
computeShowUnavailableInfo(this.hass.states[this._entityId!])) &&
DOMAINS_WITH_MORE_INFO.includes(domain) &&
(computeShowHistoryComponent(this.hass, this._entityId!) ||
computeShowLogBookComponent(this.hass, this._entityId!))
);
@@ -522,29 +511,11 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
case "download_snapshot":
this._downloadSnapshot();
break;
case "directions":
this._openDirections();
break;
default:
break;
}
}
private _openDirections() {
const stateObj = this._entityId
? (this.hass.states[this._entityId] as HassEntity | undefined)
: undefined;
const location = stateObj && getEntityLocation(stateObj, this.hass.states);
if (!location) {
return;
}
window.open(
navigationUrl(location.latitude, location.longitude),
"_blank",
"noreferrer"
);
}
private async _resetFavorites() {
const favoritesContext = this._getFavoritesContext();
@@ -668,16 +639,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
</ha-dropdown-item>
`
: nothing;
const hasLocation =
!!stateObj && !!getEntityLocation(stateObj, this.hass.states);
const directionsMenuItem = hasLocation
? html`
<ha-dropdown-item value="directions">
<ha-svg-icon slot="icon" .path=${mdiDirections}></ha-svg-icon>
${this.hass.localize("ui.dialogs.more_info_control.directions")}
</ha-dropdown-item>
`
: nothing;
const viewTitle = this._computeViewTitle();
const defaultTitle = breadcrumb[breadcrumb.length - 1] || entityId;
if (!viewTitle) {
@@ -730,32 +691,30 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
`
: nothing;
// Also when it was opened from a smaller entity's related view
const mediaAspectRatio =
(domain === "camera" || domain === "image") && isDefaultView
? this._mediaAspectRatio
// Also when the camera was opened from a smaller entity's related view
const cameraAspectRatio =
domain === "camera" && isDefaultView
? this._cameraAspectRatio
: undefined;
// As wide as the picture is when it's as high as there is room for
const fullHeightWidth = `var(--more-info-media-max-height) * ${mediaAspectRatio}`;
const mediaPictureWidth = this._mediaNaturalWidth
? `min(${fullHeightWidth}, ${this._mediaNaturalWidth}px)`
: fullHeightWidth;
return html`
<ha-adaptive-dialog
.open=${this._open}
.width=${this.large || mediaAspectRatio ? "large" : "medium"}
class=${classMap({
camera: domain === "camera",
image: domain === "image",
})}
.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": mediaAspectRatio
? `clamp(var(--ha-dialog-width-md, 580px), calc(${mediaPictureWidth} + var(--more-info-media-inline-padding, 0px)), 1920px)`
"--ha-dialog-width-lg": cameraAspectRatio
? `clamp(var(--ha-dialog-width-md, 580px), calc(var(--video-max-height) * ${cameraAspectRatio}), 1920px)`
: undefined,
})}
@media-size-changed=${this._mediaSizeChanged}
@camera-aspect-ratio-changed=${this._cameraAspectRatioChanged}
@camera-controls-height-changed=${this._cameraControlsHeightChanged}
.accessibleLabel=${title}
@closed=${this._dialogClosed}
@@ -788,7 +747,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
></ha-icon-button-prev>
`
}
<span slot="headerTitle" class="title">
<span slot="headerTitle" @click=${this._enlarge} class="title">
${
breadcrumb.length > 0
? !__DEMO__ && isAdmin
@@ -847,10 +806,9 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
></ha-icon-button>
${
domain === "camera" || hasLocation
domain === "camera"
? html`
${downloadSnapshotMenuItem}
${directionsMenuItem}
<wa-divider></wa-divider>
`
: nothing
@@ -987,7 +945,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
: nothing
}
${
domain === "camera" || hasLocation
domain === "camera"
? html`
<ha-dropdown
slot="headerActionItems"
@@ -1003,7 +961,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
.path=${mdiDotsVertical}
></ha-icon-button>
${downloadSnapshotMenuItem}
${directionsMenuItem}
</ha-dropdown>
`
: nothing
@@ -1114,25 +1071,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
`;
}
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
// Also when going to a related entity or back. The camera player or image
// of the same entity keeps running and doesn't send its size again.
if (changedProps.has("_entityId")) {
this._mediaAspectRatio = undefined;
this._mediaNaturalWidth = undefined;
this._cameraControlsHeight = undefined;
}
if (
this._entryLoadFailed &&
changedProps.has("hass") &&
this.hass.connected &&
!(changedProps.get("hass") as HomeAssistant | undefined)?.connected
) {
this._loadEntityRegistryEntry();
}
}
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
this.addEventListener("close-dialog", () => this.closeDialog());
@@ -1202,11 +1140,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._entry = ev.detail;
}
private _mediaSizeChanged(
ev: HASSDomEvent<HASSDomEvents["media-size-changed"]>
private _cameraAspectRatioChanged(
ev: HASSDomEvent<HASSDomEvents["camera-aspect-ratio-changed"]>
) {
this._mediaAspectRatio = ev.detail.aspectRatio;
this._mediaNaturalWidth = ev.detail.naturalWidth;
this._cameraAspectRatio = ev.detail.aspectRatio;
}
private _cameraControlsHeightChanged(
@@ -1215,6 +1152,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._cameraControlsHeight = ev.detail.height;
}
private _enlarge() {
withViewTransition(() => {
this._fill = !this._fill;
});
}
private _handleOpened() {
window.addEventListener("dialog-closed", this._enableEscapeKeyClose);
window.addEventListener("show-dialog", this._disableEscapeKeyClose);
@@ -1273,14 +1216,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
--dialog-content-padding: 0;
}
/* The dialog's margin, the safe area like the dialog's height limit,
its header of about 68px and what the info shows besides the
picture */
ha-adaptive-dialog.camera,
ha-adaptive-dialog.image {
--more-info-media-max-height: calc(
100vh - var(--ha-space-20) - var(--safe-area-inset-y, 0px) -
68px - var(--more-info-media-reserved-height, 0px)
/* 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:
@@ -1291,33 +1232,14 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
/* A custom property takes any value, so it can't fall back to the
declaration before it. svh like the height limit of the dialog. */
@supports (height: 1svh) {
ha-adaptive-dialog.camera,
ha-adaptive-dialog.image {
--more-info-media-max-height: calc(
100svh - var(--ha-space-20) - var(--safe-area-inset-y, 0px) -
68px - var(--more-info-media-reserved-height, 0px)
ha-adaptive-dialog.camera {
--video-max-height: calc(
100svh - var(--ha-space-20) -
68px - var(--more-info-camera-controls-height, 0px)
);
}
}
ha-adaptive-dialog.camera {
--more-info-media-reserved-height: var(
--more-info-camera-controls-height,
0px
);
--video-max-height: var(--more-info-media-max-height);
}
/* The info's padding around the picture and the entity's row of 40px
above it, with 16px between them */
ha-adaptive-dialog.image {
--more-info-media-reserved-height: calc(
var(--ha-space-6) +
max(var(--safe-area-inset-bottom, 0px), var(--ha-space-6)) + 56px
);
--more-info-media-inline-padding: calc(var(--ha-space-6) * 2);
}
.content-wrapper {
flex: 1 1 auto;
min-height: 0;
+34 -12
View File
@@ -1,5 +1,5 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { computeDomain } from "../../common/entity/compute_domain";
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
@@ -8,14 +8,12 @@ import {
computeShowHistoryComponent,
computeShowLogBookComponent,
computeShowNewMoreInfo,
computeShowUnavailableInfo,
DOMAINS_FULL_HEIGHT_MORE_INFO,
DOMAINS_NO_INFO,
DOMAINS_WITH_MORE_INFO,
} from "./const";
import "./ha-more-info-history";
import "./ha-more-info-logbook";
import "./ha-more-info-unavailable";
import "./more-info-content";
@customElement("ha-more-info-info")
@@ -33,21 +31,41 @@ export class MoreInfoInfo extends LitElement {
protected render() {
const entityId = this.entityId;
const stateObj = this.hass.states[entityId] as HassEntity | undefined;
if (!stateObj || computeShowUnavailableInfo(stateObj)) {
return html`<ha-more-info-unavailable
.entry=${this.entry}
.stateObj=${stateObj}
></ha-more-info-unavailable>`;
}
const entityRegObj = this.hass.entities[entityId];
const domain = computeDomain(entityId);
const isNewMoreInfo = computeShowNewMoreInfo(stateObj);
const isNewMoreInfo = stateObj && computeShowNewMoreInfo(stateObj);
const isFullHeight =
isNewMoreInfo || DOMAINS_FULL_HEIGHT_MORE_INFO.includes(domain);
return html`
<div class="container" data-domain=${domain}>
${
!stateObj
? html`<ha-alert alert-type="warning">
${
this.entry?.disabled_by
? this.hass.localize(
"ui.dialogs.entity_registry.editor.entity_disabled"
)
: this.hass.localize(
"ui.dialogs.entity_registry.editor.unavailable"
)
}
</ha-alert>`
: nothing
}
${
stateObj?.attributes.restored && entityRegObj
? html`<ha-alert alert-type="warning">
${this.hass.localize(
"ui.dialogs.more_info_control.restored.no_longer_provided",
{
integration: entityRegObj.platform,
}
)}
</ha-alert>`
: nothing
}
<div class="content">
${
DOMAINS_NO_INFO.includes(domain) || isNewMoreInfo
@@ -135,6 +153,10 @@ export class MoreInfoInfo extends LitElement {
ha-more-info-logbook {
margin-inline: calc(var(--ha-space-6) * -1);
}
ha-alert {
display: block;
}
`;
}
@@ -1,455 +0,0 @@
import {
mdiCancel,
mdiHelpCircleOutline,
mdiPowerPlugOffOutline,
} from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import "@home-assistant/components/card";
import { consume } from "../../common/decorators/consume";
import { transform } from "../../common/decorators/transform";
import { fireEvent } from "../../common/dom/fire_event";
import { navigate } from "../../common/navigate";
import {
adaptiveDialogModeContext,
type DialogSheetMode,
} from "../../components/ha-adaptive-dialog";
import "../../components/ha-alert";
import "../../components/ha-button";
import "../../components/ha-empty-state";
import "../../components/ha-relative-time";
import type { ConfigEntry } from "../../data/config_entries";
import { ERROR_STATES } from "../../data/config_entries";
import {
apiContext,
configContext,
configEntriesContext,
formattersContext,
internationalizationContext,
} from "../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { HistoryStates } from "../../data/history";
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
import { updateEntityRegistryEntry } from "../../data/entity/entity_registry";
import { domainToName } from "../../data/integration";
import { renderConfigEntryError } from "../../panels/config/integrations/render-config-entry-error";
import { showAlertDialog } from "../generic/show-dialog-box";
/**
* @element ha-more-info-unavailable
* @summary Info view of an entity that has no state or that its integration
* doesn't provide, with the reason and how to make it available again.
*/
@customElement("ha-more-info-unavailable")
export class HaMoreInfoUnavailable extends LitElement {
/** `undefined` while the entry loads, `null` when the entity isn't registered. */
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
/** The `restored` state core keeps while the integration doesn't provide the entity. */
@property({ attribute: false }) public stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
@transform<ContextType<typeof configContext>, boolean>({
transformer: ({ user }) => Boolean(user?.is_admin),
})
private _isAdmin = false;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@state()
@consume({ context: configEntriesContext, subscribe: true })
private _configEntries?: ConfigEntry[];
/** `null` when the history has no state from before. */
@state() private _lastKnown?: { state: string; until: Date } | null;
@state()
@consume({ context: adaptiveDialogModeContext, subscribe: true })
private _dialogMode?: DialogSheetMode;
@state() private _enabling = false;
private _lastKnownRequest = 0;
@state() private _error?: string;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
const platform = this.entry?.platform;
if (platform && changedProps.get("entry")?.platform !== platform) {
// Only the titles of loaded integrations are fetched by default
this._i18n.loadBackendTranslation("title", platform);
}
if (
changedProps.has("stateObj") &&
changedProps.get("stateObj")?.last_changed !== this.stateObj?.last_changed
) {
this._fetchLastKnown();
}
}
private async _fetchLastKnown() {
this._lastKnown = undefined;
const request = ++this._lastKnownRequest;
const stateObj = this.stateObj;
if (!stateObj) {
return;
}
const end = new Date(stateObj.last_changed);
// Short periods first, as a sensor can write thousands of states a day
for (const days of [1, 7, 30]) {
let history: HistoryStates;
try {
// eslint-disable-next-line no-await-in-loop
history = await this._api.callWS<HistoryStates>({
type: "history/history_during_period",
start_time: new Date(end.getTime() - days * 86400000).toISOString(),
end_time: end.toISOString(),
entity_ids: [stateObj.entity_id],
minimal_response: true,
no_attributes: true,
});
} catch (_err) {
this._lastKnown = null;
return;
}
if (request !== this._lastKnownRequest) {
return;
}
const states = history[stateObj.entity_id] ?? [];
for (let i = states.length - 1; i >= 0; i--) {
if (states[i].s !== UNAVAILABLE && states[i].s !== UNKNOWN) {
const next = states[i + 1];
this._lastKnown = {
state: states[i].s,
until: next ? new Date((next.lc ?? next.lu) * 1000) : end,
};
return;
}
}
}
this._lastKnown = null;
}
protected render() {
return html`
<div
class=${classMap({
container: true,
"bottom-sheet": this._dialogMode === "bottom-sheet",
})}
>
${this._renderContent()}
</div>
`;
}
private _renderContent() {
if (this.entry === undefined) {
return nothing;
}
const localize = this._i18n.localize;
if (this.entry === null) {
return html`
<ha-empty-state
.icon=${mdiHelpCircleOutline}
.heading=${localize(
"ui.dialogs.more_info_control.unavailable.not_found_title"
)}
.description=${localize(
"ui.dialogs.more_info_control.unavailable.not_found"
)}
></ha-empty-state>
`;
}
const entry = this.entry;
const integration = domainToName(localize, entry.platform);
if (!entry.disabled_by) {
const configEntry = entry.config_entry_id
? this._configEntries?.find(
(item) => item.entry_id === entry.config_entry_id
)
: undefined;
return html`
<ha-empty-state
.icon=${mdiPowerPlugOffOutline}
.heading=${localize(
"ui.dialogs.more_info_control.unavailable.not_provided_title"
)}
.description=${this._notProvidedDescription(integration, configEntry)}
>
${this._renderDetails(configEntry)}
${this._isAdmin ? this._renderOpenIntegration() : nothing}
</ha-empty-state>
`;
}
const canEnable =
entry.disabled_by === "user" || entry.disabled_by === "integration";
return html`
<ha-empty-state
.icon=${mdiCancel}
.heading=${localize(
"ui.dialogs.more_info_control.unavailable.disabled_title"
)}
.description=${localize(
`ui.dialogs.more_info_control.unavailable.disabled_by.${entry.disabled_by}`,
{ integration }
)}
>
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
${
!this._isAdmin
? nothing
: canEnable
? html`
<ha-button
.loading=${this._enabling}
.disabled=${this._enabling}
@click=${this._enableEntry}
>
${localize(
"ui.dialogs.more_info_control.unavailable.enable_entity"
)}
</ha-button>
`
: entry.disabled_by === "device" && entry.device_id
? html`
<ha-button appearance="plain" @click=${this._openDevice}>
${localize(
"ui.dialogs.more_info_control.unavailable.open_device"
)}
</ha-button>
`
: this._renderOpenIntegration()
}
</ha-empty-state>
`;
}
private _notProvidedDescription(
integration: string,
configEntry?: ConfigEntry
) {
const localize = this._i18n.localize;
const key = "ui.dialogs.more_info_control.unavailable.integration_state";
switch (configEntry?.state) {
case "setup_retry":
return localize(`${key}.setup_retry`, { integration });
case "setup_error":
case "migration_error":
return localize(`${key}.setup_error`, { integration });
case "setup_in_progress":
return localize(`${key}.setup_in_progress`, { integration });
case "not_loaded":
case "failed_unload":
case "unload_in_progress":
return localize(`${key}.not_loaded`, { integration });
default:
return localize(
this.stateObj
? `${key}.no_longer_provided`
: "ui.dialogs.more_info_control.unavailable.not_provided",
{ integration }
);
}
}
private _renderDetails(configEntry?: ConfigEntry) {
const localize = this._i18n.localize;
const key = "ui.dialogs.more_info_control.unavailable.details";
const reason =
this._isAdmin &&
configEntry?.reason &&
ERROR_STATES.includes(configEntry.state)
? renderConfigEntryError(this._i18n, configEntry)
: undefined;
// Only the history tells since when, the restored state's last_changed is the last restart
const lastKnown = this.stateObj ? this._lastKnown : undefined;
if (!reason && !lastKnown) {
return nothing;
}
return html`
<hac-card>
<dl>
${
reason
? html`<div class="stacked">
<dt>${localize(`${key}.reason`)}</dt>
<dd>${reason}</dd>
</div>`
: nothing
}
${
lastKnown
? html`<div>
<dt>${localize(`${key}.unavailable_since`)}</dt>
<dd>
<ha-relative-time
.datetime=${lastKnown.until}
capitalize
></ha-relative-time>
</dd>
</div>
<div>
<dt>${localize(`${key}.last_known_state`)}</dt>
<dd>
${this._formatters.formatEntityState(
this.stateObj!,
lastKnown.state
)}
</dd>
</div>`
: nothing
}
</dl>
</hac-card>
`;
}
private _renderOpenIntegration() {
return html`
<ha-button appearance="plain" @click=${this._openIntegration}>
${this._i18n.localize(
"ui.dialogs.more_info_control.unavailable.open_integration"
)}
</ha-button>
`;
}
private _openIntegration() {
navigate(`/config/integrations/integration/${this.entry!.platform}`);
}
private _openDevice() {
navigate(`/config/devices/device/${this.entry!.device_id}`);
}
private async _enableEntry() {
this._error = undefined;
this._enabling = true;
try {
const result = await updateEntityRegistryEntry(
this._api.callWS,
this.entry!.entity_id,
{ disabled_by: null }
);
fireEvent(this, "entity-entry-updated", result.entity_entry);
if (result.require_restart) {
showAlertDialog(this, {
text: this._i18n.localize(
"ui.dialogs.entity_registry.editor.enabled_restart_confirm"
),
});
}
if (result.reload_delay) {
showAlertDialog(this, {
text: this._i18n.localize(
"ui.dialogs.entity_registry.editor.enabled_delay_confirm",
{ delay: result.reload_delay }
),
});
}
} catch (err: any) {
this._error = err.message;
} finally {
this._enabling = false;
}
}
static styles = css`
:host {
display: flex;
flex: 1;
}
.container {
display: flex;
flex: 1;
min-height: 400px;
}
/* The bottom sheet has a fixed height, which is lower on a phone in landscape */
.container.bottom-sheet {
min-height: 0;
}
ha-empty-state {
flex: 1;
height: auto;
}
hac-card {
width: 100%;
--hac-card-content-padding: var(--ha-space-3) var(--ha-space-4);
}
dl {
display: flex;
flex-direction: column;
gap: var(--ha-space-2);
margin: 0;
text-align: start;
}
dl > div {
display: flex;
gap: var(--ha-space-4);
justify-content: space-between;
}
dl > div.stacked {
flex-direction: column;
gap: 0;
}
.stacked dd {
text-align: start;
}
dt {
flex: none;
color: var(--secondary-text-color);
}
dd {
margin: 0;
text-align: end;
overflow-wrap: anywhere;
}
ha-alert {
display: block;
text-align: start;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-more-info-unavailable": HaMoreInfoUnavailable;
}
}
+118 -32
View File
@@ -13,6 +13,7 @@ import { fireEvent } from "../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import "../../components/animation/ha-fade-in";
import "../../components/ha-adaptive-dialog";
import "../../components/ha-alert";
import "../../components/ha-expansion-panel";
import "../../components/ha-icon-next";
import "../../components/ha-spinner";
@@ -20,6 +21,10 @@ import "../../components/item/ha-list-item-button";
import type { HaListItemButton } from "../../components/item/ha-list-item-button";
import "../../components/list/ha-list-base";
import "../../components/progress/ha-progress-bar";
import {
getBackupState,
type BackupManagerState,
} from "../../data/backup_manager";
import {
extractApiErrorMessage,
ignoreSupervisorError,
@@ -31,14 +36,14 @@ import {
shutdownHost,
} from "../../data/hassio/host";
import { haStyle, haStyleDialog } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import type { HomeAssistant, ServiceCallRequest } from "../../types";
import { HOST_ACTION_TOAST_ID, showToast } from "../../util/toast";
import { showAlertDialog } from "../generic/show-dialog-box";
import {
confirmRestartAction,
showRestartConfirmation,
type RestartAction,
} from "./show-restart-confirmation";
showAlertDialog,
showConfirmationDialog,
} from "../generic/show-dialog-box";
import { showRestartWaitDialog } from "./show-dialog-restart";
import "./automation-restart-status";
@customElement("dialog-restart")
class DialogRestart extends LitElement {
@@ -69,6 +74,15 @@ class DialogRestart extends LitElement {
}
}
private async _loadBackupState() {
try {
return await getBackupState(this.hass);
} catch (_err) {
// Do nothing
return "idle";
}
}
private async _loadHostInfo() {
this._loadingHostInfo = true;
try {
@@ -259,16 +273,45 @@ class DialogRestart extends LitElement {
duration: 1000,
});
try {
await this.hass.callService("homeassistant", "reload_all");
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize("ui.dialogs.restart.reload.failed"),
text: err.message,
});
this._restartAction(
"homeassistant",
"reload_all",
this.hass.localize("ui.dialogs.restart.reload.failed")
)();
}
private _getBackupProgressMessage(backupState: BackupManagerState) {
switch (backupState) {
case "create_backup":
return this.hass.localize("ui.dialogs.restart.backup_in_progress");
case "receive_backup":
return this.hass.localize("ui.dialogs.restart.upload_in_progress");
case "restore_backup":
return this.hass.localize("ui.dialogs.restart.restore_in_progress");
default:
return "";
}
}
private _restartAction =
(
domain: ServiceCallRequest["domain"],
service: ServiceCallRequest["service"],
errorTitle: string,
serviceData?: ServiceCallRequest["serviceData"]
) =>
async () => {
try {
await this.hass.callService(domain, service, serviceData);
} catch (err: any) {
showAlertDialog(this, {
title: errorTitle,
text: err.message,
});
}
};
private _hostAction =
(toastMessage: string, action: "reboot" | "shutdown") => async () => {
showToast(this, {
@@ -300,32 +343,75 @@ class DialogRestart extends LitElement {
};
private async _handleAction(
ev: HASSDomCurrentTargetEvent<HaListItemButton & { action: RestartAction }>
ev: HASSDomCurrentTargetEvent<
HaListItemButton & {
action: "restart" | "reboot" | "shutdown" | "restart-safe-mode";
}
>
) {
if (this._loadingBackupInfo) {
return;
}
this._loadingBackupInfo = true;
const action = ev.currentTarget.action;
try {
const confirmed =
action === "restart" || action === "restart-safe-mode"
? await showRestartConfirmation(this, this.hass, action)
: await confirmRestartAction(
this,
this.hass,
action,
this._hostAction(
this.hass.localize(`ui.dialogs.restart.${action}.action_toast`),
action
)
);
if (confirmed) {
this._dialogOpen = false;
}
} finally {
this._loadingBackupInfo = false;
const backupState = await this._loadBackupState();
const backupProgressMessage = this._getBackupProgressMessage(backupState);
this._loadingBackupInfo = false;
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize(`ui.dialogs.restart.${action}.confirm_title`),
text: html`${this.hass.localize(
`ui.dialogs.restart.${action}.confirm_description`
)}${
backupProgressMessage
? html`<br /><br /><ha-alert>${backupProgressMessage}</ha-alert>`
: nothing
} <br /><br /><automation-restart-status></automation-restart-status>`,
confirmText: this.hass.localize(
`ui.dialogs.restart.${action}.confirm_action${backupState === "idle" ? "" : "_backup"}`
),
destructive: true,
});
if (!confirmed) {
return;
}
this._dialogOpen = false;
let actionFunc: () => Promise<void>;
if (["restart", "restart-safe-mode"].includes(action)) {
const serviceData =
action === "restart-safe-mode" ? { safe_mode: true } : undefined;
actionFunc = this._restartAction(
"homeassistant",
"restart",
this.hass.localize(`ui.dialogs.restart.${action}.failed`),
serviceData
);
} else {
actionFunc = this._hostAction(
this.hass.localize(
`ui.dialogs.restart.${action as "reboot" | "shutdown"}.action_toast`
),
action as "reboot" | "shutdown"
);
}
if (backupState !== "idle") {
showRestartWaitDialog(this, {
title: this.hass.localize(`ui.dialogs.restart.${action}.title`),
initialBackupState: backupState,
action: actionFunc,
});
return;
}
actionFunc();
}
static get styles(): CSSResultGroup {
@@ -1,96 +0,0 @@
import { html, nothing } from "lit";
import "../../components/ha-alert";
import {
getBackupState,
type BackupManagerState,
} from "../../data/backup_manager";
import type { HomeAssistant } from "../../types";
import {
showAlertDialog,
showConfirmationDialog,
} from "../generic/show-dialog-box";
import "./automation-restart-status";
import { showRestartWaitDialog } from "./show-dialog-restart";
export type RestartAction =
"restart" | "reboot" | "shutdown" | "restart-safe-mode";
type ConfirmationContext = Pick<HomeAssistant, "connection" | "localize">;
function getBackupProgressMessage(
localize: HomeAssistant["localize"],
backupState: BackupManagerState
) {
switch (backupState) {
case "create_backup":
return localize("ui.dialogs.restart.backup_in_progress");
case "receive_backup":
return localize("ui.dialogs.restart.upload_in_progress");
case "restore_backup":
return localize("ui.dialogs.restart.restore_in_progress");
default:
return "";
}
}
export async function confirmRestartAction(
element: HTMLElement,
hass: ConfirmationContext,
action: RestartAction,
run: () => Promise<void>
) {
const backupState = await getBackupState(hass).catch(() => "idle" as const);
const backupProgressMessage = getBackupProgressMessage(
hass.localize,
backupState
);
const confirmed = await showConfirmationDialog(element, {
title: hass.localize(`ui.dialogs.restart.${action}.confirm_title`),
text: html`${hass.localize(
`ui.dialogs.restart.${action}.confirm_description`
)}${
backupProgressMessage
? html`<br /><br /><ha-alert>${backupProgressMessage}</ha-alert>`
: nothing
} <br /><br /><automation-restart-status></automation-restart-status>`,
confirmText: hass.localize(
`ui.dialogs.restart.${action}.confirm_action${backupState === "idle" ? "" : "_backup"}`
),
destructive: true,
});
if (!confirmed) {
return false;
}
if (backupState !== "idle") {
showRestartWaitDialog(element, {
title: hass.localize(`ui.dialogs.restart.${action}.title`),
initialBackupState: backupState,
action: run,
});
} else {
run();
}
return true;
}
export function showRestartConfirmation(
element: HTMLElement,
hass: ConfirmationContext & Pick<HomeAssistant, "callService">,
action: "restart" | "restart-safe-mode" = "restart"
) {
return confirmRestartAction(element, hass, action, async () => {
try {
await hass.callService(
"homeassistant",
"restart",
action === "restart-safe-mode" ? { safe_mode: true } : undefined
);
} catch (err: any) {
showAlertDialog(element, {
title: hass.localize(`ui.dialogs.restart.${action}.failed`),
text: err.message,
});
}
});
}
+1 -1
View File
@@ -158,7 +158,7 @@ class DialogEditSidebar extends DirtyStateProviderMixin<SidebarState>()(
].map<DisplayItem>((panel) => ({
value: panel.url_path,
label:
(getPanelTitle(this.hass.localize, panel) || panel.url_path) +
(getPanelTitle(this.hass, panel) || panel.url_path) +
`${defaultPanel === panel.url_path ? ` (${this.hass.localize("ui.sidebar.default")})` : ""}`,
icon: getPanelIcon(panel),
iconPath: getPanelIconPath(panel),
@@ -145,9 +145,7 @@ export class HaVoiceAssistantSetupDialog extends LitElement {
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.voice_assistants.satellite_wizard.title"
)}
header-title="Voice Satellite setup"
prevent-scrim-close
@closed=${this._dialogClosed}
>
-6
View File
@@ -2,10 +2,4 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
import "../resources/scoped-registry-ready";
import "../layouts/home-assistant";
// Custom cards and plugins can reach the helpers on any page, not only once a
// dashboard has loaded.
Object.assign(window, {
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
});
import("../resources/append-ha-style");
+2
View File
@@ -11,6 +11,7 @@ import {
import { loadTokens, saveTokens } from "../common/auth/token_storage";
import { hassUrl } from "../data/auth";
import { isExternal } from "../data/external";
import { subscribeFrontendUserData } from "../data/frontend";
import { fetchConfig } from "../data/lovelace/config/types";
import { fetchResources } from "../data/lovelace/resource";
import { MAIN_WINDOW_NAME } from "../data/main_window";
@@ -187,6 +188,7 @@ window.hassConnection.then(({ conn }) => {
subscribePanels(conn, noop);
subscribeThemes(conn, noop);
subscribeUser(conn, noop);
subscribeFrontendUserData(conn, "core", noop);
subscribeRepairsIssueRegistry(conn, noop);
const preloadWindow = window as WindowWithPreloads;
+19 -14
View File
@@ -1,9 +1,21 @@
import { supportsFeatureFromAttributes } from "../../common/entity/supports-feature";
import { ClimateEntityFeature } from "../../data/climate";
import {
CLIMATE_HVAC_ACTION_TO_MODE,
ClimateEntityFeature,
} from "../../data/climate";
import type { HvacAction } from "../../data/climate";
import { MockBaseEntity } from "./base-entity";
import type { EntityAttributes } from "./types";
// Reverse mapping: mode → action (e.g. "cool" → "cooling")
const HVAC_MODE_TO_ACTION: Partial<Record<string, HvacAction>> =
Object.fromEntries(
Object.entries(CLIMATE_HVAC_ACTION_TO_MODE).map(([action, mode]) => [
mode,
action as HvacAction,
])
);
export class MockClimateEntity extends MockBaseEntity {
public async handleService(
domain: string,
@@ -231,13 +243,10 @@ export class MockClimateEntity extends MockBaseEntity {
return "off";
}
// Heat and cool get their action from the temperatures below
if (state === "dry") {
return "drying";
}
if (state === "fan_only") {
return "fan";
// Use the reverse mapping for direct mode → action (e.g. "fan_only" → "fan", "dry" → "drying")
const directAction = HVAC_MODE_TO_ACTION[state];
if (directAction && directAction !== "idle" && directAction !== "off") {
return directAction;
}
if (
@@ -267,17 +276,13 @@ export class MockClimateEntity extends MockBaseEntity {
const current = attrs.current_temperature;
const lowTarget = attrs.target_temp_low;
const highTarget = attrs.target_temp_high;
// Heat mode can only heat and cool mode only cool, while auto and
// heat_cool use both ends of the range
if (current != null) {
if (state !== "cool" && lowTarget != null && lowTarget > current) {
if (lowTarget != null && lowTarget > current) {
return "heating";
}
if (state !== "heat" && highTarget != null && highTarget < current) {
if (highTarget != null && highTarget < current) {
return "cooling";
}
return "idle";
}
}
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff. Show more