Compare commits

..
Author SHA1 Message Date
Raphael HehlandYosi Levy f08e3b299e Drag picture elements placed from the right or bottom (#55871)
* Drag picture elements placed from the right or bottom

* Keep moved sides behind an empty inset

---------

Co-authored-by: Yosi Levy <[email protected]>
2026-11-23 15:17:34 +02:00
WendelinandClaude Opus 5.5 089ddb9ade Add a camera player with its own controls to the more info (#56013)
* Add a camera player with its own controls to the camera more info

Prototype of a live view that looks and behaves the same in every
browser, instead of each browser's native video controls:

- Controls fade out after a few seconds and come back on hover, tap or
  focus: sound on the bottom start, picture in picture and full screen on
  the bottom end, reset zoom on the top end once zoomed in.
- Zooms with the scroll wheel, a pinch or a double click and pans by
  dragging. With wheel-zoom="modifier" the wheel only zooms while ctrl or
  cmd is held, so a dashboard around the player keeps scrolling.
- A badge on the top start shows the stream protocol, while it connects,
  and when WebRTC still connects in the background while HLS plays. It
  opens a dialog that explains WebRTC, HLS and MJPEG.
- MJPEG streams play in a video through a canvas, so they can also be
  shown picture in picture.

WebRTC streams now always keep their audio track, so a muted stream can
be unmuted again.

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

* Clean up the camera player when it is removed

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

* Only zoom the camera player with ctrl or cmd and the scroll wheel

The scroll wheel alone now always scrolls the page around the player,
in the more info dialog just like on a dashboard. A hint over the player
shows which key zooms.

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

* Drop the info icon from the camera stream badge

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

* Show the camera zoom hint as a small pill at the top end

It takes the place where the reset zoom button comes once zoomed in,
instead of covering the whole picture.

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

* Keep the bottom sheet still while panning a zoomed in camera

Dragging a zoomed in camera picture pans it, but the more info bottom
sheet also took the drag and moved or closed. The zoomed in picture now
locks the sheet's swipe, like other controls that drag on touch.

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

* Keep the stream badge and the muted button over the camera picture

The connection badge now always shows, and so does the sound button
while a stream with sound is muted, so it is clear there is sound to
turn on. The other controls still fade out.

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

* Fix MJPEG in the camera player, open stream info at the top

- An MJPEG stream never finishes loading, so some browsers never report
  the image as complete and the player kept connecting. It now only
  waits for a first frame, and shows the image itself when no frame
  could be copied within a few seconds.
- The stream badge fades with the other controls again once connected,
  only the muted sound button stays.
- The stream info dialog opens at the top like the more info dialog,
  and as a bottom sheet on small screens.

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

* Keep the bottom sheet still while pinching in it

A pinch starts with one finger, which the bottom sheet already took as a
swipe, so zooming a camera picture with two fingers also moved the
sheet. A second finger now stops the swipe and puts the sheet back.

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

* Show MJPEG streams as an image again, fold away unsupported streams

- The MJPEG player now shows the image itself, like before, which
  works in every browser. Only a hidden video plays a copy of it, for
  picture in picture. Until the first frame it keeps the room of a
  picture, with the camera's preview if there is one, so nothing
  jumps. The player also no longer looked at the wrong image and kept
  connecting.
- The stream info dialog lists the streams the camera can't use below
  the others, folded away.

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

* Give the unsupported streams in the stream info more room

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

* Keep the screen on while the camera more info is open

A live camera view shouldn't turn dark while watching it, and an image,
like an MJPEG stream, never keeps the screen on. The player now holds a
screen wake lock with keep-awake, and requests it again when the page
shows again, as browsers release it when the page is hidden.

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

* Fix MJPEG loading, panning it with a mouse and full screen layout

- The MJPEG stream image now shows over the camera's preview while it
  loads, instead of loading hidden, which some browsers never do. Where
  a browser doesn't tell when the first frame arrived, it counts as
  connected after a few seconds.
- Dragging the MJPEG image with a mouse started the browser's image
  drag instead of panning the zoomed in picture.
- Full screen centers the picture and keeps it and the controls clear
  of notches and rounded corners.

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

* Load only the MJPEG stream, like before, not also its preview

Showing the camera's preview while an MJPEG stream loaded also fetched
a snapshot at the same time. For cameras whose MJPEG stream Home
Assistant makes from snapshots, this kept the stream from loading. The
player now only requests the stream, like before, with an empty space
of a picture's size until its first frame.

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

* Load MJPEG streams from the Home Assistant URL

The MJPEG stream path was used as is, so it loaded from wherever the
frontend is served instead of from Home Assistant, unlike HLS. With
the frontend served on its own, like with script/develop_and_serve,
the stream never loaded.

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

* Only play the MJPEG video for picture in picture, fix its state

- The hidden video that copies an MJPEG stream now only plays while
  picture in picture is open, instead of all the time. It costs no
  battery otherwise, and browsers don't offer picture in picture for it
  on their own. Streams from another origin, which can't be copied,
  have no picture in picture button.
- document.pictureInPictureElement only gives the outermost shadow host,
  so the player never knew picture in picture was open. It now follows
  the events of the video.

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

* Drop the MJPEG loaded timeout, it only hid the wrong stream URL

The stream did load in every browser, it only came from the wrong URL
with the frontend served on its own. The player now only counts a
stream as connected once its first frame arrived.

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

* Only explain MJPEG in the stream info while it shows

MJPEG is only the fallback of a camera's video streams, so the stream
info now only lists it while it shows: with a note when the video
streams failed, or as all there is for a camera without a video stream,
without listing the video streams it doesn't have.

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

* Add a zoom minimap and a play button, fix review findings

- While zoomed in, a minimap next to the reset zoom button shows the
  whole picture and the part in view, so it is clear the zoom is
  digital. It fades with the other controls.
- A play button shows while the stream was paused from outside, like
  in the picture in picture window or the iPhone's own full screen
  player, which had no way back before.
- While the Android app plays an HEVC stream in its own player, the
  camera player only shows the stream, as its controls and zoom can't
  reach the app's player.
- A failed MJPEG picture in picture stops copying frames again.
- The controls stay while one of them has keyboard focus.
- A mouse released outside of the player no longer keeps its press,
  pinching stays under the fingers, and a resize keeps the same part
  of a zoomed in picture in view.

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

* Keep an MJPEG stream connected when the more info comes back

When coming back from the history, the camera stream started over
while the MJPEG player kept its picture and never told it again, so
it stayed connecting.

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

* Use theme tokens for the camera overlay colors and timings

The overlay uses the white color and focus ring tokens. The tokens need
no fallback, and their durations already turn off motion when reduced
motion is preferred.

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

* Use the list components in the stream info dialog

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

* Show the play button when autoplay is blocked, reconnect MJPEG streams

- When a browser blocks playing even muted, the play button shows, as
  it is the only way left to start the stream.
- Lifting one finger of a quick pinch no longer counts as a tap that
  toggles the controls.
- While Home Assistant is disconnected, the stream shows as connecting.
  An MJPEG stream loads again once it is back, after a restart, or when
  the more info comes back, and counts as connected at its first frame.

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

* Load an MJPEG stream again also before its first frame

When the connection came back before the first frame, nothing changed
for the player, so it never set the stream's source again.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-23 14:16:10 +01:00
50c911fe2f Add dynamic period cost indicator chip to Energy Usage Graph (#53992)
* Add dynamic period cost indicator chip to Energy Usage Graph

- Evaluates configured grid energy sources to compute period net cost from cost statistics or fixed rates.
- Factors in export compensation (stat_energy_to / stat_compensation / number_energy_price_export) matching hui-energy-sources-table-card.
- Displays a dedicated <hui-energy-graph-chip> in the card header formatted with user's currency.
- Gracefully omitted when no cost data or fixed prices are configured.

* Share grid net cost with the sources table and address review

Use the cost statistics for the period only, so the chip matches the
sources table total. Drop the fixed-price fallback and the English
fallback string, format the cost once, and label the tooltip as net grid
cost.

---------

Co-authored-by: kdvlr <[email protected]>
Co-authored-by: Petar Petrov <[email protected]>
2026-11-23 12:52:25 +00:00
Lex PostmaandClaude Opus 5.5 bf16d4e5a1 Refresh related filters after an edit and keep broken helpers in filters (#56039)
Refresh related filters on return and keep unassigned helper entries

The config list pages are kept by the router while an item is edited, so
the device, area, entity and blueprint filters kept the related items they
found before the edit. Look them up again when the page is shown again.

Helper config entries that failed or are still setting up have no entity,
so any filter hid them. They now count as items with nothing assigned:
"No area" keeps them, a selected id leaves them out.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 13:46:31 +01:00
g2ti98fl6zs023is 608ad23071 Resume suspended reconnects when WebView wake events are missing (#55975)
* Resume reconnects when WebView wake events are missing

* Create when-document-visible.ts

* Create when-document-visible.test.ts

* Prevent detached app instances from restarting reconnect suspension

* Remove unnecessary app-root detach handling

* Test visibility recovery callback directly
2026-11-23 12:41:09 +00:00
WendelinandClaude Opus 5.5 0d84bb01ec Make switches and buttons follow custom theme colors (#56077)
* Apply picked colors to custom themes that don't set them

Primary and accent colors picked in the profile only applied to the
default theme. A custom theme that only changes a few variables, like
the background, fell back to the default blue palette with no way to
pick another color. Picked colors now also apply to custom themes that
don't set that color in the active mode. Colors and palette keys the
theme sets itself still win.

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

* Explain theme mode and colors set by the theme instead of hiding them

The theme mode selector and the color pickers were hidden for themes
that don't support them, so users couldn't tell why the options were
missing. Both now stay visible. When the theme fixes the mode or a
color, the control is disabled, shows the value the theme uses, and a
line of text names the theme as the reason.

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

* Show theme explanations and palette-only primary in theme settings

The explanation text was rendered into the supporting-text slot after
the first render, which the list item doesn't pick up, so it never
showed. Use the supportingText property and let it wrap. A theme that
only sets the primary palette now shows its base palette color in the
disabled primary picker instead of the default blue.

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

* Fix theme casts in the apply themes test

The test theme literals don't have the keys the Theme type lists, so
the type check rejected the direct casts.

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

* Color the set by theme explanation as a warning

Make the text that explains why theme mode or colors can't be changed
stand out from the regular description, using the semantic warning
text color so it stays readable in light and dark mode.

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

* Generate the primary palette from a custom theme's primary color

A custom theme that set primary-color without the palette kept the
default blue palette, so switches, buttons and other components using
the palette ignored the theme color. Generate the palette and the
light, dark and darker primary shades from the theme's primary color
when the theme doesn't set any palette key. Keys the theme sets itself
still win. State icons and text on primary are left alone, so existing
themes don't get their entity icons recolored. Colors that can't be
parsed, like var() references, are skipped.

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

* Normalize the luminance of theme primary colors for the palette

A theme with a near black primary color, common in older themes that
used it for the header, got a near black palette, so switches, buttons
and links became hard to see in dark mode. Normalize the color before
generating the palette, the same as colors picked by the user. The
theme's own primary-color stays as it is.

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

* Name the darkest generated palette shade 05

The generated palette named its darkest shade ha-color-primary-5, but
components use ha-color-primary-05, so that shade kept the default blue.
Quiet primary fills in dark mode didn't follow the picked or theme color.

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

* Reword the set by theme explanations and use secondary text color

Start the explanations with the theme name, so names that end in
"theme" don't read as "the ... theme theme". Show them in the semantic
secondary text color instead of warning orange, since they explain
rather than warn.

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

* Quote the theme name in the set by theme explanations

Quoting the name marks it as a name, so theme names that end in "theme"
read fine, and keeps the wording consistent with other strings.

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

* Drop "the ... theme" around the quoted theme name

The quotes already mark the name, so the extra words only made names
that end in "theme" read twice.

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

* Trim comments and reuse existing color and localize helpers

Use cssColorToHex instead of a local formatHex wrapper, consume
localize directly instead of the whole internationalization context,
and drop comments that only restate the code.

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

* Only tint the dark mode header for the default theme

Picked colors now also apply to custom themes, which also tinted their
dark mode header. Keep that tint on the default theme, so custom themes
keep the header they had before.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-23 13:32:45 +01:00
Raman GuptaandClaude Opus 5.5 ff95b531b7 Use the latest arguments for throttle's trailing call (#55962)
The trailing call captured the arguments of the call that scheduled the
timer, so calls made later in the same window were dropped. Keep the
latest arguments and use them when the timer fires.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 13:21:00 +01:00
Maarten Lakerveld 921b7362a5 Keep the Marketplace name out of translations (#55882)
* Keep the Marketplace name out of translations

Marketplace is a product name, so translators should not change it. The
name now lives in MARKETPLACE_NAME: titles use it directly and sentences
get it through a {marketplace} placeholder. The panel title, Settings
entry, and repository page header no longer have translation keys.

* Fill the Marketplace name inside localize

Every string with {marketplace} needed its caller to pass the name, and a
forgotten caller turns the string into a translation error. localize now
merges NAME_PLACEHOLDERS under the caller's values, so the callers only
pass what varies.
2026-11-23 12:01:18 +00:00
Luca Félix fb20d72938 Keep the radius when editing a location selector's coordinates (#55765)
* Keep the radius when editing a location selector's coordinates

The form handler emitted radius: NaN when the value had no radius yet,
and dropped a read-only radius.

* Test the location selector's form value as a pure function

Rendering tests are out of scope for the frontend tests, so building the
value moves to computeLocationFormValue and is tested directly.

* Address location selector review feedback

Keep a read-only radius unrounded, fall back to the default radius the
map shows, and move the helper into its own module as
computeLocationSelectorValue.

* Keep a cleared location selector radius empty

Apply the default radius only when the value never had one, so clearing
the field no longer snaps it back to the default. Share the default
radius constant with the selector.
2026-11-23 13:13:39 +02:00
4a1328970f Return null from parseAspectRatio for unhandled formats (#55969)
* Return null from parseAspectRatio for unhandled formats

parseFloat stops at the first character it can't parse, so input such as
16/9 or 16X9 was read as 16 and returned a 16:1 ratio instead of null.
Match the supported formats in full instead.

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

* Return null from parseAspectRatio for non-string input

YAML loads an unquoted aspect_ratio: 16:9 as the base-60 number 969.
The regex coerced it to "969" and returned a 969:1 ratio, where the
previous code threw on it and returned null.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: MindFreeze <[email protected]>
2026-11-23 12:10:41 +01:00
Raman GuptaandClaude Opus 5.5 f441726c3c Accept a single visibility condition mapping in dropInvalidConditions (#55966)
A visibility written as a single mapping instead of a list reached the
for...of loop as a plain object and threw a TypeError. Wrap it in an
array, as nested conditions already are.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 12:53:39 +02:00
BenV 731fd30b07 Stop the user badge from updating on every state change (#56029)
* Stop the user badge from updating on every state change

* Derive the person picture in render and handle a loading registry
2026-11-23 11:53:07 +01:00
Aidan TimsonandCopilot Autofix powered by AI b6660a23ed Don't hold the launch screen when the first panel redirects (#56072)
* Wait for the panel that replaces one before it was ready

* Modify event listener for 'hass-panel-ready'

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-23 11:41:52 +01:00
Lex PostmaandClaude Opus 5.5 f3990796ba Announce partly selected list options to screen readers (#56041)
* Announce partly selected list options to screen readers

A list option with `indeterminate` set draws a mixed checkbox, but the
row (role `option`) only exposed `aria-selected` and the checkbox sits in
an inert wrapper, so screen readers read the row as not selected. Add a
localized "Partly selected" `aria-description` while the row is
indeterminate, and remove it again when it no longer is.

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

* Remove the rendering test for the partly selected description

The frontend testing guidance rules out rendering tests for components
that only put context data into their output.

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

* Document the indeterminate option in the list gallery page

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 11:07:13 +01:00
Jan Čermák 4fb7eefb27 Pin home-assistant/actions to the 2026.11.0 tag (#56075)
Switch the home-assistant/actions steps in release.yaml from the master
SHA pin to the 2026.11.0 release tag. The tag points to the same commit
(07f46fd), and actions.lock pins it there.
2026-11-23 11:05:40 +01:00
renovate[bot] 214762a052 Update dependency @lezer/common to v1.5.6 (#56074)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-23 11:26:37 +02:00
Petar Petrov a75f7265ff Fix history graph holding a stale value after a burst of readings (#56073)
* Keep the last reading of a downsampled frame before a long hold

* Avoid Array.at in the down-sample test
2026-11-23 10:12:11 +01:00
G JohanssonandClaude Opus 5.5 3a5c534def Translate attribute values of groups with their members (#56051)
* Translate attribute values of groups with their members

A group entity, such as a light group, has no translations or icons for
the attribute values of its members, for example light effects. When a
group has no translation or icon for a value, use the one of a member of
the same domain that has it. A member's default icon is not used.

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

* Skip group members without a platform for attribute icons

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

* Use group_entities for the members of a group

Find the members with computeGroupMemberIds, which also reads the
group_entities attribute of groups from integrations.

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

* Use the range icons of group members

A member can define icons for numeric attribute values with ranges.
Use them in the member fallback too, without the default icon of the
member.

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

* Continue the group icon lookup when a member's icons fail to load

A failed request for the icons of a member stopped the whole lookup, so
the other members and the domain fallback were not tried.

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

* Share the group member filter of attribute translations and icons

Move the filter of group members with translations into
computeGroupMemberEntries next to computeGroupMemberIds, so the attribute
value translation and the attribute icon use the same rule. The
translation lookup now also skips members without a platform.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 11:09:00 +02:00
145 changed files with 5089 additions and 3846 deletions

No files matched your search

+1 -25
View File
@@ -96,17 +96,14 @@ html`
Pick the indicator by what is loading, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/):
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
- Use `ha-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 below.
- 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.
Every skeleton uses the same soft wave (`ha-skeleton`'s default `effect="sheen"`). It's one slanted wave across all the skeletons on the page, from the top corner of the content on the side text starts from to the opposite bottom corner, which each skeleton shows its slice of, on one shared clock. It flows from one skeleton into the next, starts its next sweep as soon as it leaves the content, and a skeleton added mid-sweep joins in rather than starting over. Don't change the effect or speed (`--ha-skeleton-duration`) for one component.
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
- Content that takes a skeleton's place fades in over `--ha-animation-duration-fast`, which reduced motion makes instant. `ha-skeleton-overlay` does this for you. Elsewhere, use `skeletonOr(loading, skeleton, () => content)` from `src/components/skeleton/skeleton-arrival.ts`: it shows the skeleton while loading and fades the content in once when it replaces it, but not where no skeleton showed, such as table rows made as the table scrolls. Put text in an element of its own inside the content, as only elements fade. For content that fills in where it already is, such as a log, call `fadeInArrival(element)` once when its skeleton goes. Don't add any other fade to loaded content.
- Don't fade in the loaded content itself.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
@@ -124,27 +121,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.
```ts
html`
<ha-skeleton-overlay .loading=${this._loading}>
<my-content></my-content>
</ha-skeleton-overlay>
`;
```
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it. In a Lit component, add a `SkeletonLoadingController` from `src/components/skeleton/skeleton-loading-controller.ts` with a function that says whether it's loading, and it fires the events for you.
- `hui-card` and `hui-badge` already wrap every card and badge in an overlay, and show a plain wave while the card's code loads. A card that fetches data only needs a `SkeletonLoadingController`, as `hui-calendar-card` and the history and statistics charts do. Energy cards pass `loading` to `EnergyCollectionController` instead, for when they fetch more after the collection's data arrives.
- Give the overlay a `skeleton-key` and it remembers how tall the content was once loaded, then holds that height next time. `hui-card` sets one from the card's config. For other content, make one with `skeletonKey()` from `src/components/skeleton/skeleton-sizes.ts`.
- For the first visit, render placeholders as big as the content will be, so it doesn't jump when the data arrives. Set `loading` on `ha-chart-base` to have the chart read as one block and its legend as one line, or as its items when the legend has them already. Before a chart exists, use `chartPlaceholderStyles` from `src/components/chart/chart-placeholder.ts`. Lists of a known length, such as the to-do list from its entity's state, draw that many hidden rows. Energy cards whose layout follows the energy preferences, such as the sources table and the devices detail graph, can draw it from `EnergyCollectionController.placeholderData` until their data comes.
- 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.
## Shortcuts And Tooltips
Use `ShortcutManager` from `src/common/keyboard/shortcuts.ts` for keyboard shortcuts. It blocks shortcuts in input fields, can prevent shortcuts during text selection, and supports character and KeyCode shortcuts for non-latin keyboards. See `src/state/quick-bar-mixin.ts` for global shortcut examples.
+2 -2
View File
@@ -70,7 +70,7 @@ workflows:
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
- 'home-assistant/actions@07f46fd2e19967768b5fd3000f91f857452b767c'
- 'home-assistant/actions@2026.11.0'
- 'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
- 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086'
'.github/workflows/restrict-task-creation.yaml':
@@ -156,7 +156,7 @@ dependencies:
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
owner_id: 9919
repo_id: 259445878
'home-assistant/actions@07f46fd2e19967768b5fd3000f91f857452b767c':
'home-assistant/actions@2026.11.0':
ref: '2026.11.0'
commit: 'sha1-07f46fd2e19967768b5fd3000f91f857452b767c'
owner_id: 13844975
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
python-version: ${{ env.PYTHON_VERSION }}
- name: Verify version
uses: home-assistant/actions/helpers/verify-version@07f46fd2e19967768b5fd3000f91f857452b767c # master
uses: home-assistant/actions/helpers/verify-version@2026.11.0
- name: Setup Node and install
uses: $/.github/actions/setup
@@ -250,6 +250,9 @@ sit inside `<ha-list-selectable>`, which owns selection state and toggles
- `selected` (Boolean, default `false`, reflected) — set by the parent
`ha-list-selectable`.
- `indeterminate` (Boolean, default `false`, reflected) — draws the checkbox
as mixed, for a row that stands for a partly selected set. Screen readers
hear it as "Partly selected" through `aria-description`.
- `value` (String) — value identifying the option.
- `appearance` (`"line"` | `"checkbox"`, default `"line"`) — `"line"`
highlights the row; `"checkbox"` renders a decorative `<ha-checkbox>`.
@@ -1,6 +0,0 @@
---
title: Card skeletons
subtitle: How a dashboard looks while its cards and badges load
---
Each card and badge sits in an `ha-skeleton-overlay`, which reads a skeleton from what the card or badge draws: every name, state and value gets its own text skeleton, and icons, images, controls and drawings get their own pieces. When loading ends, each part fades in. Turn off **Loading** to see the real cards, or use **Simulate loading** to watch them arrive one by one.
@@ -1,440 +0,0 @@
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { mockIcons } from "../../../../demo/src/stubs/icons";
import type { HASSDomTargetEvent } from "../../../../src/common/dom/fire_event";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-button";
import "../../../../src/components/ha-switch";
import type { HaSwitch } from "../../../../src/components/ha-switch";
import { LightColorMode } from "../../../../src/data/light";
import type { LovelaceBadgeConfig } from "../../../../src/data/lovelace/config/badge";
import type { LovelaceCardConfig } from "../../../../src/data/lovelace/config/card";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import "../../../../src/panels/lovelace/badges/hui-badge";
import type { HuiBadge } from "../../../../src/panels/lovelace/badges/hui-badge";
import "../../../../src/panels/lovelace/cards/hui-card";
import type { HuiCard } from "../../../../src/panels/lovelace/cards/hui-card";
import { computeCardGridSize } from "../../../../src/panels/lovelace/common/compute-card-grid-size";
import type { HomeAssistant } from "../../../../src/types";
import "../../ha-demo-options";
const ENTITIES = [
{
entity_id: "light.bed_light",
state: "on",
attributes: {
friendly_name: "Bed light",
supported_color_modes: [LightColorMode.BRIGHTNESS],
color_mode: LightColorMode.BRIGHTNESS,
brightness: 180,
},
},
{
entity_id: "light.kitchen_lights",
state: "on",
attributes: { friendly_name: "Kitchen lights" },
},
{
entity_id: "switch.tv_outlet",
state: "off",
attributes: { friendly_name: "TV outlet", device_class: "outlet" },
},
{
entity_id: "media_player.living_room",
state: "playing",
attributes: { friendly_name: "Living room speaker" },
},
{
entity_id: "climate.thermostat",
state: "heat",
attributes: {
friendly_name: "Thermostat",
current_temperature: 21,
temperature: 22,
hvac_modes: ["heat", "off"],
hvac_action: "heating",
},
},
{
entity_id: "lock.front_door",
state: "locked",
attributes: { friendly_name: "Front door" },
},
{
entity_id: "person.paulus",
state: "home",
attributes: {
friendly_name: "Paulus",
entity_picture: "/images/paulus.jpg",
},
},
{
entity_id: "sensor.living_room_temperature",
state: "21.4",
attributes: {
friendly_name: "Living room temperature",
device_class: "temperature",
unit_of_measurement: "°C",
state_class: "measurement",
},
},
{
entity_id: "sensor.living_room_humidity",
state: "54",
attributes: {
friendly_name: "Living room humidity",
device_class: "humidity",
unit_of_measurement: "%",
state_class: "measurement",
},
},
{
entity_id: "binary_sensor.back_door",
state: "off",
attributes: { friendly_name: "Back door", device_class: "door" },
},
{
entity_id: "camera.garden",
state: "idle",
attributes: { friendly_name: "Garden" },
},
];
/* The badges row at the top of a sections view */
const BADGES: LovelaceBadgeConfig[] = [
{ type: "entity", entity: "person.paulus", show_entity_picture: true },
{ type: "entity", entity: "sensor.living_room_temperature" },
{ type: "entity", entity: "light.kitchen_lights", show_name: true },
{ type: "entity", entity: "lock.front_door", color: "green" },
{
type: "entity",
entity: "binary_sensor.back_door",
show_name: true,
show_state: false,
},
];
const SECTIONS: LovelaceCardConfig[][] = [
[
{
type: "heading",
heading: "Living room",
badges: [
{ type: "entity", entity: "sensor.living_room_temperature" },
{ type: "entity", entity: "sensor.living_room_humidity" },
],
},
{
type: "tile",
entity: "light.bed_light",
features: [{ type: "light-brightness" }],
},
{ type: "tile", entity: "switch.tv_outlet" },
{ type: "tile", entity: "media_player.living_room" },
{ type: "tile", entity: "climate.thermostat", vertical: true },
{ type: "tile", entity: "lock.front_door", vertical: true },
{ type: "entity", entity: "sensor.living_room_temperature" },
{ type: "entity", entity: "sensor.living_room_humidity" },
],
[
{ type: "heading", heading: "Cameras" },
{ type: "picture-entity", entity: "camera.garden" },
{
type: "picture-glance",
title: "Kitchen",
image: "/images/kitchen.png",
entities: [
"light.kitchen_lights",
"switch.tv_outlet",
"binary_sensor.back_door",
],
},
{
type: "picture-entity",
image: "/images/bed.png",
entity: "light.bed_light",
},
],
[
{ type: "heading", heading: "Overview" },
{ type: "tile", entity: "person.paulus" },
{ type: "tile", entity: "binary_sensor.back_door" },
{
type: "entities",
title: "Climate",
entities: [
"climate.thermostat",
"sensor.living_room_temperature",
"sensor.living_room_humidity",
],
},
{
type: "glance",
title: "Doors and lights",
entities: [
"lock.front_door",
"binary_sensor.back_door",
"light.kitchen_lights",
],
},
{ type: "gauge", entity: "sensor.living_room_humidity" },
],
];
interface DemoSlot {
key: string;
card: HuiCard;
}
interface BadgeSlot {
key: string;
badge: HuiBadge;
}
@customElement("demo-lovelace-card-skeletons")
class DemoCardSkeletons extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _loaded = new Set<string>();
@state() private _simulating = false;
private _sections: DemoSlot[][] = [];
private _badges: BadgeSlot[] = [];
private _timers: number[] = [];
/* Whether each card or badge was last told it's loading */
private _loadingShown = new WeakMap<Element, boolean>();
protected firstUpdated(changedProperties: PropertyValues<this>) {
super.firstUpdated(changedProperties);
const hass = provideHass(this);
hass.updateTranslations(null, "en");
hass.updateTranslations("lovelace", "en");
hass.addEntities(ENTITIES);
mockIcons(hass);
// Camera snapshots come from a signed path; point it at a gallery image.
hass.mockWS("auth/sign_path", () => ({
path: "/images/office.jpg?authSig=gallery",
}));
}
public disconnectedCallback() {
super.disconnectedCallback();
this._clearTimers();
}
protected willUpdate(changedProperties: PropertyValues<this>) {
if (!changedProperties.has("hass") || !this.hass) {
return;
}
if (this._sections.length === 0) {
this._sections = SECTIONS.map((cards, sectionIndex) =>
cards.map((config, cardIndex) => {
const card = document.createElement("hui-card");
card.layout = "grid";
card.config = config;
return { key: `${sectionIndex}-${cardIndex}`, card };
})
);
this._badges = BADGES.map((config, index) => {
const badge = document.createElement("hui-badge");
badge.config = config;
return { key: `badge-${index}`, badge };
});
}
this._elements().forEach(({ element }) => {
element.hass = this.hass;
});
}
/* Every card and badge, as one list to measure and reveal */
private _elements() {
return [
...this._badges.map(({ key, badge }) => ({ key, element: badge })),
...this._sections.flat().map(({ key, card }) => ({ key, element: card })),
];
}
protected render() {
if (!this.hass) {
return nothing;
}
return html`
<ha-demo-options>
<ha-switch
.checked=${this._loaded.size === 0}
.disabled=${this._simulating}
@change=${this._loadingToggled}
></ha-switch>
<span>Loading</span>
<ha-button
size="s"
appearance="filled"
.disabled=${this._simulating}
@click=${this._simulate}
>
Simulate loading
</ha-button>
</ha-demo-options>
<div class="badges">${this._badges.map(({ badge }) => badge)}</div>
<div class="view">
${this._sections.map(
(slots) => html`
<div class="section">
${slots.map((slot) => this._renderSlot(slot))}
</div>
`
)}
</div>
`;
}
private _renderSlot({ card }: DemoSlot): TemplateResult {
const { rows, columns } = computeCardGridSize(card.getGridOptions());
const fitRows = rows !== "auto";
const fullWidth = columns === "full";
return html`
<div
class="card ${classMap({
"fit-rows": fitRows,
"full-width": fullWidth,
})}"
style=${styleMap({
"--column-size": fullWidth ? undefined : columns,
"--row-size": fitRows ? rows : undefined,
})}
>
${card}
</div>
`;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
// A card or badge makes its content when it first updates
this._elements().forEach(async ({ key, element }) => {
await element.updateComplete;
this._setLoading(element, !this._loaded.has(key));
});
}
/* Each card and badge already sits in its own skeleton overlay. Say it's
loading from inside, as a card waiting on its data does. */
private _setLoading(wrapper: HuiCard | HuiBadge, loading: boolean) {
const content = wrapper.querySelector(":scope > ha-skeleton-overlay > *");
if (
!(content instanceof HTMLElement) ||
this._loadingShown.get(content) === loading
) {
return;
}
this._loadingShown.set(content, loading);
fireEvent(content, "skeleton-loading", { loading });
}
private _keys(): string[] {
return this._elements().map(({ key }) => key);
}
private _loadingToggled(ev: HASSDomTargetEvent<HaSwitch>) {
this._clearTimers();
this._loaded = ev.target.checked ? new Set() : new Set(this._keys());
}
private _simulate() {
this._clearTimers();
this._loaded = new Set();
this._simulating = true;
const keys = this._keys();
keys.forEach((key) => {
const delay = 600 + Math.random() * 2400;
this._timers.push(
window.setTimeout(() => {
this._loaded = new Set(this._loaded).add(key);
if (this._loaded.size === keys.length) {
this._simulating = false;
}
}, delay)
);
});
}
private _clearTimers() {
this._timers.forEach((timer) => clearTimeout(timer));
this._timers = [];
this._simulating = false;
}
static styles = css`
ha-demo-options {
display: flex;
align-items: center;
gap: var(--ha-space-2);
}
ha-demo-options ha-button {
margin-inline-start: var(--ha-space-4);
}
.view {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: var(--ha-space-8);
padding: var(--ha-space-4);
background-color: var(--primary-background-color);
align-items: start;
}
.section {
--row-gap: 8px;
--column-gap: 8px;
--row-height: 56px;
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
grid-auto-rows: auto;
row-gap: var(--row-gap);
column-gap: var(--column-gap);
}
.card {
grid-row: span var(--row-size, 1);
grid-column: span min(var(--column-size, 12), 12);
}
.card.fit-rows {
height: calc(
(var(--row-size, 1) * (var(--row-height) + var(--row-gap))) - var(
--row-gap
)
);
}
.card.full-width {
grid-column: 1 / -1;
}
/* As hui-view-badges lays out the badges row */
.badges {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: var(--ha-space-2);
padding: var(--ha-space-4) var(--ha-space-4) 0;
background-color: var(--primary-background-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"demo-lovelace-card-skeletons": DemoCardSkeletons;
}
}
+1 -1
View File
@@ -64,7 +64,7 @@
"@formatjs/intl-pluralrules": "7.1.0",
"@formatjs/intl-relativetimeformat": "13.0.3",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.5",
"@lezer/common": "1.5.6",
"@lezer/highlight": "1.2.5",
"@lit-labs/motion": "1.1.0",
"@lit-labs/observers": "2.1.0",
+21 -21
View File
@@ -261,8 +261,8 @@ importers:
specifier: 3.14.0-ha.2
version: 3.14.0-ha.2(@floating-ui/[email protected])(@types/[email protected])
'@lezer/common':
specifier: 1.5.5
version: 1.5.5
specifier: 1.5.6
version: 1.5.6
'@lezer/highlight':
specifier: 1.2.5
version: 1.2.5
@@ -2251,8 +2251,8 @@ packages:
'@konnorr/[email protected]':
resolution: {integrity: sha512-6Ae3AfG45MOqF9Qde+1YxIxKf/GUsRmcriV7iCb/HaR+Mk1YDFYP3RINDRMI8z8YMWW3BnSthOujX9RoOex/Kw==}
'@lezer/[email protected].5':
resolution: {integrity: sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==}
'@lezer/[email protected].6':
resolution: {integrity: sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==}
'@lezer/[email protected]':
resolution: {integrity: sha512-YJE78Wcg+zX8f10hiHWQ4Az48Qr/c13eId0VtRQYLBpxHDmDeSrXIlkbl+fJGW42rWC/uoUco9mhBZeVWP/A1g==}
@@ -9486,21 +9486,21 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.15
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.15
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@codemirror/[email protected]':
dependencies:
'@codemirror/autocomplete': 6.20.4
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/css': 1.3.6
'@codemirror/[email protected]':
@@ -9511,7 +9511,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.15
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/css': 1.3.6
'@lezer/html': 1.3.13
@@ -9522,7 +9522,7 @@ snapshots:
'@codemirror/lint': 6.9.8
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.15
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/javascript': 1.5.4
'@codemirror/[email protected]':
@@ -9532,7 +9532,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.15
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
@@ -9541,7 +9541,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.4
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/python': 1.1.19
'@codemirror/[email protected]':
@@ -9549,7 +9549,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.4
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/yaml': 1.0.4
@@ -9559,7 +9559,7 @@ snapshots:
'@codemirror/state': 6.7.6
'@codemirror/streamparser': 6.0.0
'@codemirror/view': 6.43.15
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
style-mod: 4.1.3
@@ -10097,43 +10097,43 @@ snapshots:
'@konnorr/[email protected]': {}
'@lezer/[email protected].5': {}
'@lezer/[email protected].6': {}
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.5
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
+1 -1
View File
@@ -79,7 +79,7 @@ export const generateColorPalette = (
}
return steps.map((step) => {
const name = `ha-color-${label}-${step}`;
const name = `ha-color-${label}-${String(step).padStart(2, "0")}`;
// Base color at 50%
if (step === 50) {
+8 -6
View File
@@ -6,15 +6,17 @@ const isConditionObject = (c: unknown): c is VisibilityCondition =>
typeof c === "object" && c !== null;
/**
* Drop entries that are not condition objects, at any depth. Returns the
* same array when every entry is valid.
* Drop entries that are not condition objects, at any depth. A single
* condition mapping is wrapped in an array. Returns the same array when it
* is an array and every entry is valid.
*/
export const dropInvalidConditions = (
conditions: VisibilityCondition[]
conditions: VisibilityCondition | VisibilityCondition[]
): VisibilityCondition[] => {
let changed = false;
const list = ensureArray(conditions);
let changed = list !== conditions;
const valid: VisibilityCondition[] = [];
for (const c of conditions) {
for (const c of list) {
if (!isConditionObject(c)) {
changed = true;
continue;
@@ -30,5 +32,5 @@ export const dropInvalidConditions = (
}
valid.push(c);
}
return changed ? valid : conditions;
return changed ? valid : list;
};
+102 -68
View File
@@ -1,4 +1,9 @@
import type { ThemeVars } from "../../data/ws-themes";
import {
getThemeVariables,
themeDefinesColor,
themeDefinesPrimaryPalette,
} from "../../data/ws-themes";
import { darkColorVariables } from "../../resources/theme/color";
import { darkSemanticVariables } from "../../resources/theme/semantic.globals";
import { derivedStyles } from "../../resources/theme/theme";
@@ -10,9 +15,9 @@ import {
rgb2hex,
rgb2lab,
} from "../color/convert-color";
import { hexBlend } from "../color/hex";
import { cssColorToHex, hexBlend } from "../color/hex";
import { labBrighten, labDarken } from "../color/lab";
import { generateColorPalette } from "../color/palette";
import { generateColorPalette, normalizeLuminance } from "../color/palette";
import { rgbContrast } from "../color/rgb";
interface ProcessedTheme {
@@ -56,78 +61,56 @@ export const applyThemesOnElement = (
themeRules = { ...darkSemanticVariables, ...darkColorVariables };
}
if (themeToApply === "default") {
// Determine the primary and accent colors from the current settings.
// Fallbacks are implicitly the HA default blue and orange or the
// derived "darkStyles" values, depending on the light vs dark mode.
const primaryColor = themeSettings?.primaryColor;
const accentColor = themeSettings?.accentColor;
const isDefaultTheme = themeToApply === "default";
const customTheme =
themeToApply && !isDefaultTheme ? themes.themes[themeToApply] : undefined;
const customThemeRules = customTheme
? getThemeVariables(customTheme, darkMode)
: undefined;
if (darkMode && primaryColor) {
themeRules["app-header-background-color"] = hexBlend(
primaryColor,
"#121212",
8
);
}
const primaryColor =
isDefaultTheme ||
(customThemeRules && !themeDefinesColor(customThemeRules, "primary"))
? themeSettings?.primaryColor
: undefined;
const accentColor =
isDefaultTheme ||
(customThemeRules && !themeDefinesColor(customThemeRules, "accent"))
? themeSettings?.accentColor
: undefined;
if (primaryColor) {
cacheKey = `${cacheKey}__primary_${primaryColor}`;
const rgbPrimaryColor = hex2rgb(primaryColor);
const labPrimaryColor = rgb2lab(rgbPrimaryColor);
themeRules["primary-color"] = primaryColor;
const rgbLightPrimaryColor = lab2rgb(labBrighten(labPrimaryColor));
if (primaryColor) {
cacheKey = `${cacheKey}__primary_${primaryColor}`;
}
if (accentColor) {
cacheKey = `${cacheKey}__accent_${accentColor}`;
}
themeRules = {
...themeRules,
...getUserColorRules(primaryColor, accentColor, isDefaultTheme && darkMode),
};
generateColorPalette(primaryColor, "primary").forEach(([key, color]) => {
themeRules[key] = color;
});
themeRules["light-primary-color"] = rgb2hex(rgbLightPrimaryColor);
themeRules["dark-primary-color"] = lab2hex(labDarken(labPrimaryColor));
themeRules["darker-primary-color"] = lab2hex(
labDarken(labPrimaryColor, 2)
);
themeRules["text-primary-color"] =
rgbContrast(rgbPrimaryColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
themeRules["text-light-primary-color"] =
rgbContrast(rgbLightPrimaryColor, [33, 33, 33]) < 6
? "#fff"
: "#212121";
themeRules["state-icon-color"] = themeRules["dark-primary-color"];
}
if (accentColor) {
cacheKey = `${cacheKey}__accent_${accentColor}`;
themeRules["accent-color"] = accentColor;
const rgbAccentColor = hex2rgb(accentColor);
themeRules["text-accent-color"] =
rgbContrast(rgbAccentColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
}
// Nothing was changed
if (element.__themes?.cacheKey === cacheKey) {
return;
}
// Nothing was changed
if (isDefaultTheme && element.__themes?.cacheKey === cacheKey) {
return;
}
// Custom theme logic (not relevant for default theme, since it would override
// the derived calculations from above)
if (
themeToApply &&
themeToApply !== "default" &&
themes.themes[themeToApply]
) {
// Apply theme vars that are relevant for all modes (but extract the "modes" section first)
const { modes, ...baseThemeRules } = themes.themes[themeToApply];
themeRules = { ...themeRules, ...baseThemeRules };
// Unparseable colors like `var(--x)` are skipped.
const themePrimaryColor =
customThemeRules?.["primary-color"] &&
!themeDefinesPrimaryPalette(customThemeRules)
? cssColorToHex(customThemeRules["primary-color"])
: undefined;
if (themePrimaryColor) {
// Older themes often use a near black primary color for the header.
themeRules = {
...themeRules,
...getPrimaryPaletteRules(normalizeLuminance(themePrimaryColor)),
};
}
// Apply theme vars for the specific mode if available
if (modes) {
if (darkMode) {
themeRules = { ...themeRules, ...modes.dark };
} else {
themeRules = { ...themeRules, ...modes.light };
}
}
if (customThemeRules) {
themeRules = { ...themeRules, ...customThemeRules };
}
if (!element.__themes?.keys && !Object.keys(themeRules).length) {
@@ -154,6 +137,57 @@ export const applyThemesOnElement = (
}
};
const getPrimaryPaletteRules = (primaryColor: string): Partial<ThemeVars> => {
const rules: Partial<ThemeVars> = {};
const labPrimaryColor = rgb2lab(hex2rgb(primaryColor));
generateColorPalette(primaryColor, "primary").forEach(([key, color]) => {
rules[key] = color;
});
rules["light-primary-color"] = rgb2hex(lab2rgb(labBrighten(labPrimaryColor)));
rules["dark-primary-color"] = lab2hex(labDarken(labPrimaryColor));
rules["darker-primary-color"] = lab2hex(labDarken(labPrimaryColor, 2));
return rules;
};
const getUserColorRules = (
primaryColor: string | undefined,
accentColor: string | undefined,
tintHeader: boolean
): Partial<ThemeVars> => {
const rules: Partial<ThemeVars> = {};
if (primaryColor) {
if (tintHeader) {
rules["app-header-background-color"] = hexBlend(
primaryColor,
"#121212",
8
);
}
Object.assign(rules, getPrimaryPaletteRules(primaryColor));
rules["primary-color"] = primaryColor;
rules["text-primary-color"] =
rgbContrast(hex2rgb(primaryColor), [33, 33, 33]) < 6 ? "#fff" : "#212121";
rules["text-light-primary-color"] =
rgbContrast(hex2rgb(rules["light-primary-color"]!), [33, 33, 33]) < 6
? "#fff"
: "#212121";
rules["state-icon-color"] = rules["dark-primary-color"];
}
if (accentColor) {
rules["accent-color"] = accentColor;
const rgbAccentColor = hex2rgb(accentColor);
rules["text-accent-color"] =
rgbContrast(rgbAccentColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
}
return rules;
};
const processTheme = (
cacheKey: string,
theme: Partial<ThemeVars>
-549
View File
@@ -1,549 +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 => {
// An overlay only wraps content, so what it wraps is read
if (
element.localName.startsWith("ha-skeleton") &&
element.localName !== "ha-skeleton-overlay"
) {
return "none";
}
const value = element.getAttribute("data-skeleton");
return isOverride(value) ? value : undefined;
};
export interface SkeletonPiece {
kind: SkeletonPieceKind;
x: number;
y: number;
width: number;
height: number;
radius?: string;
/* An SVG mask for a drawing, such as a gauge arc */
mask?: string;
/* The part sits on a dark overlay, such as a picture card's name bar */
onDark?: boolean;
/* A see-through bar laid over a picture, kept as it is */
background?: string;
}
export interface ExtractedSkeleton {
pieces: SkeletonPiece[];
/* The elements the pieces stand in for, hidden while loading */
parts: (HTMLElement | SVGElement)[];
/* Elements holding text: hide only the text colour, as the same element
often draws a frame, such as a badge's pill, that has to stay */
textParts: HTMLElement[];
}
const ROUND_TAGS = new Set([
"ha-tile-icon",
"ha-state-icon",
"ha-svg-icon",
"ha-icon",
"state-badge",
]);
const BLOCK_TAGS = new Set(["img", "video", "ha-camera-stream"]);
/* A canvas to measure fonts with, made on first use */
let measuringContext: CanvasRenderingContext2D | null | undefined;
const fontContext = (style: CSSStyleDeclaration, size: string) => {
measuringContext ??= document.createElement("canvas").getContext("2d");
if (measuringContext) {
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
}
return measuringContext;
};
/**
* Where a text bar goes on a line of this font: from the top of the
* capitals down to the baseline, measured from the font itself.
* `size` is the size as drawn, after any SVG scaling.
*/
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
const context = fontContext(style, `${size}px`);
if (!context) {
return { top: size * 0.2, height: size * 0.7 };
}
const metrics = context.measureText("H");
return {
// The line box holds the font's ascent, so the baseline sits that far down
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
height: metrics.actualBoundingBoxAscent,
};
};
/* How wide "…" is in this font, the room cut-off text leaves at its end */
const ellipsisWidth = (style: CSSStyleDeclaration) =>
fontContext(style, style.fontSize)?.measureText("…").width ??
parseFloat(style.fontSize);
/* The icon as drawn, not its box, which a line of text can crop */
const findGlyph = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
for (const child of [
...(element.shadowRoot?.children ?? []),
...element.children,
]) {
if (child instanceof SVGSVGElement) {
return child;
}
const found = findGlyph(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Near-white text or icons, as on a picture card's dark name bar */
const isNearWhite = (color: string): boolean => {
const channels = color
.match(/[\d.]+/g)
?.slice(0, 3)
.map(Number);
return channels?.length === 3 && channels.every((channel) => channel >= 200);
};
const isRendered = (style: CSSStyleDeclaration) =>
style.display !== "none" && style.visibility !== "hidden";
const isSeeThrough = (color: string) => {
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
return alpha > 0 && alpha < 1;
};
/* The first element, inside shadow roots too, that rounds its corners */
const findRounded = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
const children = [
...(element.shadowRoot?.children ?? []),
...element.children,
];
for (const child of children) {
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
return child;
}
const found = findRounded(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
const merged: SkeletonPiece[] = [];
for (const piece of pieces) {
const previous = merged[merged.length - 1];
// Either side, so right-to-left lines join too
const gap = previous
? Math.max(
piece.x - (previous.x + previous.width),
previous.x - (piece.x + piece.width)
)
: Infinity;
const sameLine =
previous?.kind === "text" &&
piece.kind === "text" &&
Math.abs(previous.y - piece.y) < 2 &&
Math.abs(previous.height - piece.height) < 2 &&
gap < 12;
if (sameLine) {
const left = Math.min(previous.x, piece.x);
const right = Math.max(
previous.x + previous.width,
piece.x + piece.width
);
previous.x = left;
previous.width = right - left;
continue;
}
merged.push({ ...piece });
}
return merged;
};
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
const clone = svg.cloneNode(true);
if (!(clone instanceof SVGSVGElement)) {
return undefined;
}
const originals = [svg, ...svg.querySelectorAll("*")];
const copies = [clone, ...clone.querySelectorAll("*")];
let drawnPaths = 0;
originals.forEach((original, index) => {
const copy = copies[index];
const style = getComputedStyle(original);
if (original.localName === "text" || !isRendered(style)) {
copy.setAttribute("display", "none");
return;
}
if (original !== svg && original.localName !== "g") {
drawnPaths++;
}
copy.removeAttribute("class");
copy.removeAttribute("style");
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
copy.setAttribute("stroke-width", style.strokeWidth);
copy.setAttribute("stroke-linecap", style.strokeLinecap);
});
if (drawnPaths === 0) {
return undefined;
}
clone.setAttribute("width", String(width));
clone.setAttribute("height", String(height));
const markup = new XMLSerializer().serializeToString(clone);
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
};
export const extractSkeleton = (
root: Element,
origin: DOMRect
): ExtractedSkeleton => {
const pieces: SkeletonPiece[] = [];
const parts = new Set<HTMLElement | SVGElement>();
const textParts = new Set<HTMLElement>();
/* The card's own background, the first solid one found */
let surface: string | undefined;
const box = (rect: DOMRect) => ({
x: rect.left - origin.left,
y: rect.top - origin.top,
width: rect.width,
height: rect.height,
});
/* Near-white content on a light card must sit on a dark bar */
const onDark = (style: CSSStyleDeclaration) =>
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
const addText = (element: Element | ShadowRoot) => {
const owner = element instanceof ShadowRoot ? element.host : element;
// Text cut short with an ellipsis reaches past its box, so clip to it
const clip = owner.getBoundingClientRect();
element.childNodes.forEach((node) => {
if (!(node instanceof Text) || !node.textContent?.trim()) {
return;
}
// Slotted text takes its font and colour from the slot it shows in,
// so that's where it's measured and hidden
const slot = node.assignedSlot;
const hideTarget = slot ?? owner;
const style = getComputedStyle(hideTarget);
const band = capitalBand(style, parseFloat(style.fontSize));
if (hideTarget instanceof HTMLElement) {
textParts.add(hideTarget);
}
const range = document.createRange();
range.selectNodeContents(node);
for (const rect of range.getClientRects()) {
// Cut-off text ends in "…", on the right or, right to left, on the
// left, so stop the bar where that starts
const left =
rect.left < clip.left - 1
? clip.left + ellipsisWidth(style)
: rect.left;
const right =
rect.right > clip.right + 1
? clip.right - ellipsisWidth(style)
: rect.right;
if (right <= left) {
continue;
}
pieces.push({
kind: "text",
x: left - origin.left,
width: right - left,
y: rect.top - origin.top + band.top,
height: band.height,
onDark: onDark(style),
});
}
});
};
const walk = (node: Element | ShadowRoot) => {
// Text straight inside a shadow root, as state-display renders its state
if (node instanceof ShadowRoot) {
addText(node);
}
for (const child of node.children) {
const style = getComputedStyle(child);
if (!isRendered(style)) {
continue;
}
const rect = child.getBoundingClientRect();
const tag = child.localName;
// Elements such as slots take no space but their content does
const hasSize = rect.width > 0 && rect.height > 0;
const override = skeletonOverride(child);
if (override === "none") {
continue;
}
if (override === "keep") {
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
continue;
}
if (override !== undefined) {
if (
hasSize &&
(child instanceof HTMLElement || child instanceof SVGElement)
) {
const size = Math.min(rect.width, rect.height);
const piece = box(rect);
pieces.push(
override === "round"
? {
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
}
: { kind: override, ...piece, radius: style.borderRadius }
);
parts.add(child);
}
continue;
}
if (
surface === undefined &&
hasSize &&
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
!isSeeThrough(style.backgroundColor)
) {
surface = style.backgroundColor;
}
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
// Use the circle itself, such as the tile icon's 36px background
const circle = (
findRounded(child) ??
findGlyph(child) ??
child
).getBoundingClientRect();
const size =
Math.min(circle.width, circle.height) ||
Math.max(circle.width, circle.height);
const piece = box(circle);
if (size > 0) {
pieces.push({
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
onDark: onDark(style),
});
parts.add(child);
}
continue;
}
// A see-through bar over a picture stays, so text keeps its contrast
if (
child instanceof HTMLElement &&
hasSize &&
style.position === "absolute" &&
isSeeThrough(style.backgroundColor)
) {
pieces.push({
kind: "scrim",
...box(rect),
radius: style.borderRadius,
background: style.backgroundColor,
});
}
// Pictures drawn as a background, as hui-image does in a fixed ratio
if (
child instanceof HTMLElement &&
hasSize &&
style.backgroundImage.startsWith("url(")
) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (
child instanceof HTMLElement &&
hasSize &&
tag.endsWith("-card-feature")
) {
const control = findRounded(child);
const radius = control
? getComputedStyle(control).borderRadius
: style.borderRadius;
pieces.push({ kind: "block", ...box(rect), radius });
parts.add(child);
continue;
}
if (child instanceof SVGSVGElement && hasSize) {
const piece = box(rect);
const mask = svgMask(child, piece.width, piece.height);
if (mask) {
pieces.push({ kind: "shape", ...piece, mask });
}
child.querySelectorAll("text").forEach((text) => {
const textRect = text.getBoundingClientRect();
if (textRect.width === 0) {
return;
}
// SVG text is scaled with its drawing, as the gauge value is
const scale = text.getScreenCTM()?.a ?? 1;
const textStyle = getComputedStyle(text);
const band = capitalBand(
textStyle,
parseFloat(textStyle.fontSize) * scale
);
pieces.push({
kind: "text",
...box(textRect),
y: textRect.top - origin.top + band.top,
height: band.height,
});
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement) {
addText(child);
}
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
}
};
walk(root);
return {
pieces: mergeLines(pieces),
parts: [...parts],
textParts: [...textParts],
};
};
+6 -1
View File
@@ -12,7 +12,12 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
"ha-filter-chip",
]);
const SWIPE_LOCKED_CLASSES = new Set(["volume-slider-container", "forecast"]);
const SWIPE_LOCKED_CLASSES = new Set([
"volume-slider-container",
"forecast",
// A zoomed in camera picture pans on touch
"camera-player-zoomed",
]);
/**
* Whether a touch inside a bottom sheet belongs to its content rather than to
+21
View File
@@ -0,0 +1,21 @@
// Some WebViews become visible after thawing without dispatching visibilitychange,
// resume, or focus. Check visibility while waiting so reconnects cannot stay blocked.
export const whenDocumentVisible = (callback: () => void): (() => void) => {
const check = () => {
if (!document.hidden) {
cancel();
callback();
}
};
const interval = window.setInterval(check, 1000);
const cancel = () => {
window.clearInterval(interval);
document.removeEventListener("visibilitychange", check);
document.removeEventListener("resume", check);
window.removeEventListener("focus", check);
};
document.addEventListener("visibilitychange", check);
document.addEventListener("resume", check);
window.addEventListener("focus", check);
return cancel;
};
@@ -5,6 +5,7 @@ import {
TEMPERATURE_ATTRIBUTES,
} from "../../data/entity/entity_attributes";
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
import { computeGroupMemberEntries } from "../../data/group";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import type { WeatherEntity } from "../../data/weather";
@@ -182,6 +183,13 @@ export const computeAttributeValueToParts = (
localize(
`component.${registryEntry.platform}.entity.${domain}.${translationKey}.state_attributes.${attribute}.state.${attributeValue}`
)) ||
computeMemberAttributeValueDisplay(
localize,
stateObj,
entities,
attribute,
attributeValue
) ||
(deviceClass &&
localize(
`component.${domain}.entity_component.${deviceClass}.state_attributes.${attribute}.state.${attributeValue}`
@@ -193,6 +201,27 @@ export const computeAttributeValueToParts = (
return [{ type: "value", value: formattedValue }];
};
// A group has no translations for the values of its members, for example the
// effects of a light group, so use the translation of a member.
const computeMemberAttributeValueDisplay = (
localize: LocalizeFunc,
stateObj: HassEntity,
entities: HomeAssistant["entities"],
attribute: string,
attributeValue: string
): string | undefined => {
const domain = computeStateDomain(stateObj);
for (const member of computeGroupMemberEntries(stateObj, entities)) {
const translation = localize(
`component.${member.platform}.entity.${domain}.${member.translation_key}.state_attributes.${attribute}.state.${attributeValue}`
);
if (translation) {
return translation;
}
}
return undefined;
};
export const computeAttributeNameDisplay = (
localize: LocalizeFunc,
stateObj: HassEntity,
+5 -1
View File
@@ -3,6 +3,7 @@ import type { HTMLTemplateResult } from "lit";
import { polyfillLocaleData } from "../../resources/polyfills/locale-data-polyfill";
import type { Resources, TranslationDict } from "../../types";
import { fireEvent } from "../dom/fire_event";
import { NAME_PLACEHOLDERS } from "./name-placeholders";
// Exclude some patterns from key type checking for now
// These are intended to be removed as errors are fixed
@@ -140,7 +141,10 @@ export const computeLocalize = async <Keys extends string = LocalizeKeys>(
}
try {
return translatedMessage.format<string>(argObject) as string;
return translatedMessage.format<string>({
...NAME_PLACEHOLDERS,
...argObject,
}) as string;
} catch (err: any) {
// eslint-disable-next-line no-console
console.error("Translation error", key, language, err);
@@ -0,0 +1,5 @@
export const MARKETPLACE_NAME = "Marketplace";
export const NAME_PLACEHOLDERS = {
marketplace: MARKETPLACE_NAME,
};
+21 -24
View File
@@ -1,32 +1,29 @@
// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78
// Ignore everything else
const parseOrThrow = (num) => {
const parsed = parseFloat(num);
if (isNaN(parsed)) {
throw new Error(`${num} is not a number`);
}
return parsed;
};
// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78 and 23%
// Return null for everything else
const NUMBER = String.raw`(\d+(?:\.\d*)?|\.\d+)`;
const RATIO_REGEX = new RegExp(
String.raw`^\s*${NUMBER}\s*(?:[x:]\s*${NUMBER}\s*)?$`
);
const PERCENTAGE_REGEX = new RegExp(String.raw`^\s*${NUMBER}\s*%\s*$`);
export default function parseAspectRatio(input: string) {
if (!input) {
// YAML loads an unquoted 16:9 as the base-60 number 969, so skip non-strings
if (!input || typeof input !== "string") {
return null;
}
try {
if (input.endsWith("%")) {
return { w: 100, h: parseOrThrow(input.slice(0, -1)) };
}
const arr = input.replace(":", "x").split("x");
if (arr.length === 0) {
return null;
}
return arr.length === 1
? { w: parseOrThrow(arr[0]), h: 1 }
: { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[1]) };
} catch (_err: any) {
// Ignore the error
const percentage = PERCENTAGE_REGEX.exec(input);
if (percentage) {
return { w: 100, h: parseFloat(percentage[1]) };
}
const ratio = RATIO_REGEX.exec(input);
if (ratio) {
return {
w: parseFloat(ratio[1]),
h: ratio[2] === undefined ? 1 : parseFloat(ratio[2]),
};
}
return null;
}
+18 -7
View File
@@ -5,6 +5,7 @@
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `false for leading`. To disable execution on the trailing edge, ditto.
// The trailing call uses the arguments of the latest call.
export const throttle = <T extends any[]>(
func: (...args: T) => void,
wait: number,
@@ -13,12 +14,17 @@ export const throttle = <T extends any[]>(
) => {
let timeout: number | undefined;
let previous = 0;
const throttledFunc = (...args: T): void => {
const later = () => {
previous = leading === false ? 0 : Date.now();
timeout = undefined;
let pendingArgs: T | undefined;
const later = () => {
previous = leading === false ? 0 : Date.now();
timeout = undefined;
const args = pendingArgs;
pendingArgs = undefined;
if (args) {
func(...args);
};
}
};
const throttledFunc = (...args: T): void => {
const now = Date.now();
if (!previous && leading === false) {
previous = now;
@@ -30,15 +36,20 @@ export const throttle = <T extends any[]>(
timeout = undefined;
}
previous = now;
pendingArgs = undefined;
func(...args);
} else if (!timeout && trailing !== false) {
timeout = window.setTimeout(later, remaining);
} else if (trailing !== false) {
pendingArgs = args;
if (!timeout) {
timeout = window.setTimeout(later, remaining);
}
}
};
throttledFunc.cancel = () => {
clearTimeout(timeout);
timeout = undefined;
previous = 0;
pendingArgs = undefined;
};
return throttledFunc;
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,153 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import type {
CameraStreamStatus,
CameraStreamType,
} from "../../data/camera-streams";
import "../ha-spinner";
/** Names of the protocols, the same in every language. */
export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
web_rtc: "WebRTC",
hls: "HLS",
mjpeg: "MJPEG",
};
/**
* Shows over a camera stream how it is connected. A faster stream that still
* connects in the background is shown next to the current one.
*/
@customElement("ha-camera-stream-badge")
export class HaCameraStreamBadge extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@property({ attribute: false }) public status?: CameraStreamStatus;
protected render() {
const status = this.status;
if (!status) {
return nothing;
}
const connecting = status.connecting || !status.type;
const label = connecting
? this._localize("ui.components.camera-player.connecting")
: CAMERA_STREAM_TYPE_NAMES[status.type!];
return html`
<button
type="button"
aria-label=${this._ariaLabel(status)}
class=${connecting ? "connecting" : "live"}
>
<span class="dot"></span>
<span class="label">${label}</span>
${
status.upgrading
? html`<span class="upgrading" aria-hidden="true">
<ha-spinner></ha-spinner>
${CAMERA_STREAM_TYPE_NAMES[status.upgrading]}
</span>`
: nothing
}
</button>
`;
}
private _ariaLabel(status: CameraStreamStatus): string {
if (status.connecting || !status.type) {
return this._localize(
"ui.components.camera-player.stream_info_connecting"
);
}
if (status.upgrading) {
return this._localize(
"ui.components.camera-player.stream_info_upgrading",
{
type: CAMERA_STREAM_TYPE_NAMES[status.type],
upgrading: CAMERA_STREAM_TYPE_NAMES[status.upgrading],
}
);
}
return this._localize("ui.components.camera-player.stream_info", {
type: CAMERA_STREAM_TYPE_NAMES[status.type],
});
}
static styles = css`
:host {
display: inline-flex;
}
/* Readable on a dark and on a bright picture */
button {
display: inline-flex;
align-items: center;
gap: var(--ha-space-1);
height: 28px;
padding-inline: var(--ha-space-2);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: var(--ha-border-radius-pill);
background-color: rgba(0, 0, 0, 0.45);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
color: var(--ha-color-white);
font-family: inherit;
font-size: var(--ha-font-size-s);
font-weight: var(--ha-font-weight-medium);
line-height: 1;
cursor: pointer;
}
button:focus-visible {
outline: var(--wa-focus-ring-style) var(--wa-focus-ring-width)
var(--ha-color-white);
outline-offset: var(--wa-focus-ring-offset);
}
.dot {
width: 8px;
height: 8px;
border-radius: var(--ha-border-radius-circle);
background-color: var(--ha-color-green-60);
}
.connecting .dot {
background-color: rgba(255, 255, 255, 0.8);
animation: pulse 1.2s ease-in-out infinite;
}
.upgrading {
display: inline-flex;
align-items: center;
gap: var(--ha-space-1);
padding-inline-start: var(--ha-space-1);
border-inline-start: 1px solid rgba(255, 255, 255, 0.3);
opacity: 0.7;
--ha-spinner-indicator-color: var(--ha-color-white);
--ha-spinner-size: 10px;
--ha-spinner-divider-color: rgba(255, 255, 255, 0.3);
}
@keyframes pulse {
50% {
opacity: 0.3;
}
}
@media (prefers-reduced-motion: reduce) {
.connecting .dot {
animation: none;
}
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-camera-stream-badge": HaCameraStreamBadge;
}
}
+76
View File
@@ -0,0 +1,76 @@
/**
* Zoom and pan of content that fills a viewport, applied as
* `translate(x, y) scale(scale)` with the transform origin at the top left.
*/
export interface ZoomPan {
scale: number;
x: number;
y: number;
}
export interface ZoomPanSize {
width: number;
height: number;
}
export const ZOOM_PAN_IDENTITY: ZoomPan = { scale: 1, x: 0, y: 0 };
export const MAX_ZOOM = 5;
export const isZoomed = (zoomPan: ZoomPan): boolean => zoomPan.scale > 1;
/** Keeps the scale in range and the content covering the whole viewport. */
export const clampZoomPan = (
{ scale, x, y }: ZoomPan,
{ width, height }: ZoomPanSize,
maxScale = MAX_ZOOM
): ZoomPan => {
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
if (clampedScale === 1) {
return ZOOM_PAN_IDENTITY;
}
const minX = width - width * clampedScale;
const minY = height - height * clampedScale;
return {
scale: clampedScale,
x: Math.min(0, Math.max(minX, x)),
y: Math.min(0, Math.max(minY, y)),
};
};
/**
* Zooms to a new scale while the point under the cursor or between the
* fingers stays where it is. The point is relative to the viewport.
*/
export const zoomAtPoint = (
zoomPan: ZoomPan,
scale: number,
point: { x: number; y: number },
size: ZoomPanSize,
maxScale = MAX_ZOOM
): ZoomPan => {
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
const ratio = clampedScale / zoomPan.scale;
return clampZoomPan(
{
scale: clampedScale,
x: point.x - (point.x - zoomPan.x) * ratio,
y: point.y - (point.y - zoomPan.y) * ratio,
},
size,
maxScale
);
};
export const panBy = (
zoomPan: ZoomPan,
dx: number,
dy: number,
size: ZoomPanSize,
maxScale = MAX_ZOOM
): ZoomPan =>
clampZoomPan(
{ ...zoomPan, x: zoomPan.x + dx, y: zoomPan.y + dy },
size,
maxScale
);
-22
View File
@@ -1,22 +0,0 @@
import { css } from "lit";
/* The space a chart takes while its data loads, as big as `ha-chart-base`
draws one by default: half as tall as it's wide, within the same limits,
with a line for its legend under it. Put the placeholder and its legend
in a `.placeholder-container` as wide as the chart will be. */
export const chartPlaceholderStyles = css`
.placeholder-container {
container-type: inline-size;
}
.placeholder {
display: flex;
align-items: center;
justify-content: center;
height: min(max(50cqi, 200px), var(--chart-max-height, 350px));
}
.legend-placeholder {
width: 40%;
height: 16px;
margin: 10px auto;
}
`;
+26 -8
View File
@@ -19,7 +19,9 @@ interface MinMaxFrame {
maxPoint: Point;
maxX: number;
maxY: number;
lastPoint: Point;
lastX: number;
lastY: number;
gapPoint: Point | undefined;
}
@@ -69,7 +71,9 @@ function newFrame(
maxPoint: point,
maxX: x,
maxY: y,
lastPoint: point,
lastX: x,
lastY: y,
gapPoint,
};
}
@@ -176,7 +180,9 @@ export function downSampleLineData<
if (!frame) {
frames.set(frameIndex, newFrame(point, x, y, undefined));
} else if (frame.hasValue) {
frame.lastPoint = point;
frame.lastX = x;
frame.lastY = y;
// Match the original strict-less / strict-greater comparisons so the
// first occurrence wins on ties.
if (y < frame.minY) {
@@ -192,7 +198,9 @@ export function downSampleLineData<
} else {
// the frame held nothing but a marker so far
frame.hasValue = true;
frame.lastPoint = point;
frame.lastX = x;
frame.lastY = y;
frame.minPoint = point;
frame.minX = x;
frame.minY = y;
@@ -203,7 +211,13 @@ export function downSampleLineData<
}
const result: T[] = [];
for (const frame of frames.values()) {
for (const [frameIndex, frame] of frames) {
// A marker followed by a value in its own frame is a gap that closed
// within one frame, which is about one device pixel: too narrow to show.
// That value may be neither min nor max, so check the frame's last x.
const keepGap =
frame.gapPoint !== undefined &&
Number(getPointData(frame.gapPoint)[0]) >= frame.lastX;
if (frame.hasValue) {
// The order of the data must be preserved so max may be before min
if (frame.minX > frame.maxX) {
@@ -213,15 +227,19 @@ export function downSampleLineData<
if (frame.minX < frame.maxX) {
result.push(frame.maxPoint as T);
}
}
if (frame.gapPoint !== undefined) {
// A marker followed by a value in its own frame is a gap that closed
// within one frame, which is about one device pixel: too narrow to show.
// That value may be neither min nor max, so check the frame's last x.
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
result.push(frame.gapPoint as T);
// Step lines hold the last value until the next point, so it must
// survive when that point is more than a frame away.
if (
!keepGap &&
!frames.has(frameIndex + 1) &&
frame.lastY !== (frame.minX < frame.maxX ? frame.maxY : frame.minY)
) {
result.push(frame.lastPoint as T);
}
}
if (keepGap) {
result.push(frame.gapPoint as T);
}
}
return result;
-25
View File
@@ -173,11 +173,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@property({ type: String }) public height?: string;
// While the data loads, the chart is read as one block and its legend as
// one line, or as its items when the legend has them already, so a
// skeleton drawn over it takes the size it will have
@property({ type: Boolean }) public loading = false;
// Lets cards that key their data on ids have display names announced
// instead when the chart is navigated with Chart2Music.
@property({ attribute: false })
@@ -640,7 +635,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
class="chart ${classMap({
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
})}"
data-skeleton=${ifDefined(this.loading ? "block" : undefined)}
role=${ifDefined(sonifiable ? "application" : undefined)}
tabindex=${ifDefined(
sonifiable ? "0" : this._sonificationFocusHeld ? "-1" : undefined
@@ -713,18 +707,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!items) {
return nothing;
}
// A card that knows its legend before its data shows it under the
// skeleton, so the skeleton has as many legend rows as it will
if (this.loading && !items.length) {
return html`<div class="chart-legend">
<ul>
<li>
<span class="legend-placeholder" data-skeleton="text"></span>
</li>
</ul>
</div>`;
}
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
@@ -2442,13 +2424,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
.chart-legend.multiple-items li {
max-width: 220px;
}
.chart-legend li:has(.legend-placeholder) {
width: 40%;
}
.legend-placeholder {
width: 100%;
height: var(--ha-font-size-s);
}
.chart-legend.multiple-items li:has(.value) {
max-width: 300px;
}
@@ -36,10 +36,6 @@ const ROW_HEIGHT = 30;
const ROW_HEIGHT_INSIDE_LABELS = 64;
const GRID_BOTTOM = 30;
/* How tall a timeline with this many rows is drawn */
export const timelineHeight = (rows: number, tallRows: boolean) =>
rows * (tallRows ? ROW_HEIGHT_INSIDE_LABELS : ROW_HEIGHT) + GRID_BOTTOM;
@customElement("state-history-chart-timeline")
export class StateHistoryChartTimeline extends LitElement {
@property({ attribute: false }) public data: TimelineEntity[] = [];
@@ -98,10 +94,13 @@ export class StateHistoryChartTimeline extends LitElement {
return html`
<ha-chart-base
.options=${this._chartOptions}
.height=${`${timelineHeight(
this.data.length,
this.insideLabels && (this.chunked || this.showNames)
)}px`}
.height=${`${
this.data.length *
(this.insideLabels && (this.chunked || this.showNames)
? ROW_HEIGHT_INSIDE_LABELS
: ROW_HEIGHT) +
GRID_BOTTOM
}px`}
.data=${this._chartData as HaECSeries}
small-controls
grow-for-zoom-slider
+7 -85
View File
@@ -1,7 +1,7 @@
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
import type { HassConfig } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { css, html, LitElement } from "lit";
import {
customElement,
eventOptions,
@@ -9,7 +9,6 @@ import {
queryAll,
state,
} from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { consume } from "../../common/decorators/consume";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
@@ -21,24 +20,18 @@ import type {
HASSDomTargetEvent,
} from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { configContext, statesContext } from "../../data/context";
import { configContext } from "../../data/context";
import type {
HistoryResult,
LineChartUnit,
TimelineEntity,
} from "../../data/history";
import { expectedHistoryCharts } from "../../data/history";
import { loadVirtualizer } from "../../resources/virtualizer";
import type { HomeAssistantConfig } from "../../types";
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
import { chartPlaceholderStyles } from "./chart-placeholder";
import "./state-history-chart-line";
import type { StateHistoryChartLine } from "./state-history-chart-line";
import "./state-history-chart-timeline";
import {
timelineHeight,
type StateHistoryChartTimeline,
} from "./state-history-chart-timeline";
import type { StateHistoryChartTimeline } from "./state-history-chart-timeline";
const CANVAS_TIMELINE_ROWS_CHUNK = 10; // Split up the canvases to avoid hitting the render limit
@@ -100,21 +93,6 @@ export class StateHistoryCharts extends LitElement {
@property({ attribute: "is-loading-data", type: Boolean })
public isLoadingData = false;
/** The entities being loaded, so their charts' space can be held */
@property({ attribute: false }) public loadingEntityIds?: string[];
/** Whether those entities' charts are split by device class */
@property({ attribute: "split-device-classes", type: Boolean })
public splitDeviceClasses = false;
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
isComponentLoaded(this._hassConfig, "history") &&
this.isLoadingData &&
!this.historyData
);
@property({ attribute: "logarithmic-scale", type: Boolean })
public logarithmicScale = false;
@@ -151,9 +129,6 @@ export class StateHistoryCharts extends LitElement {
})
private _hassConfig!: HassConfig;
@consume({ context: statesContext, subscribe: true })
private _states?: HassEntities;
@queryAll("state-history-chart-line, state-history-chart-timeline")
private _chartComponents!: NodeListOf<
StateHistoryChartLine | StateHistoryChartTimeline
@@ -172,7 +147,9 @@ export class StateHistoryCharts extends LitElement {
}
if (this.isLoadingData && !this.historyData) {
return this._renderLoading();
return html`<div class="info">
${this._localize("ui.components.history_charts.loading_history")}
</div>`;
}
if (this._isHistoryEmpty()) {
@@ -212,59 +189,6 @@ export class StateHistoryCharts extends LitElement {
`;
}
/* Takes the space the charts will, so nothing moves when they arrive */
private _renderLoading() {
const label = this._localize(
"ui.components.history_charts.loading_history"
);
const expected =
this.loadingEntityIds && this._states && !this.height && !this.virtualize
? expectedHistoryCharts(
this.loadingEntityIds,
this._states,
this._hassConfig.unit_system.temperature,
this.splitDeviceClasses
)
: undefined;
if (!expected || (!expected.lines && !expected.timelineRows)) {
return html`<div class="info" data-skeleton="block">${label}</div>`;
}
// Only the first chart says what's happening, for where no skeleton is
// drawn
const timeline = expected.timelineRows
? html`<div class="entry-container timeline">
<div
class="info"
data-skeleton="block"
style=${styleMap({
height: `${timelineHeight(
expected.timelineRows,
this.insideLabels && this.showNames
)}px`,
})}
>
${label}
</div>
</div>`
: nothing;
const lines = Array.from(
{ length: expected.lines },
(_, index) =>
html`<div class="entry-container line placeholder-container">
<div class="info placeholder" data-skeleton="block">
${index === 0 && !expected.timelineRows ? label : nothing}
</div>
<div class="legend-placeholder" data-skeleton="text"></div>
</div>`
);
return html`${timeline}${lines}`;
}
private _renderHistoryItem: RenderItemFunction<
TimelineEntity[] | LineChartUnit
> = (item, index) => {
@@ -548,8 +472,6 @@ export class StateHistoryCharts extends LitElement {
state-history-chart-line {
width: 100%;
}
${chartPlaceholderStyles}
`;
}
+4 -28
View File
@@ -57,12 +57,10 @@ import type {
ZoomSliderMode,
} from "./ha-chart-base";
import "./ha-chart-base";
import { chartPlaceholderStyles } from "./chart-placeholder";
import { sideTooltipPosition } from "./chart-tooltip-position";
import "./ha-chart-tooltip-marker";
import { generateStatisticsChartData } from "./statistics-chart-data";
import { createYAxisPrecisionBounds } from "./y-axis-fraction-digits";
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
export const supportedStatTypeMap: Record<StatisticType, StatisticType> = {
mean: "mean",
@@ -123,14 +121,6 @@ export class StatisticsChart extends LitElement {
@property({ attribute: "is-loading-data", type: Boolean })
public isLoadingData = false;
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
isComponentLoaded(this._hassConfig, "history") &&
this.isLoadingData &&
!this.statisticsData
);
@property({ attribute: "click-for-more-info", type: Boolean })
public clickForMoreInfo = true;
@@ -252,23 +242,10 @@ export class StatisticsChart extends LitElement {
}
if (this.isLoadingData && !this.statisticsData) {
const label = this._i18n.localize(
"ui.components.statistics_charts.loading_statistics"
);
// A chart given a height holds its space already
if (this.height) {
return html`<div class="info" data-skeleton="block">${label}</div>`;
}
// Takes the space the chart will, so nothing moves when it arrives
return html`<div class="placeholder-container">
<div class="info placeholder" data-skeleton="block">${label}</div>
${
this.hideLegend
? nothing
: html`<div class="legend-placeholder" data-skeleton="text"></div>`
}
return html`<div class="info">
${this._i18n.localize(
"ui.components.statistics_charts.loading_statistics"
)}
</div>`;
}
@@ -720,7 +697,6 @@ export class StatisticsChart extends LitElement {
line-height: 60px;
color: var(--secondary-text-color);
}
${chartPlaceholderStyles}
`;
}
+1 -5
View File
@@ -45,7 +45,6 @@ import "../ha-checkbox";
import type { HaCheckbox } from "../ha-checkbox";
import "../skeleton/ha-skeleton-icon";
import "../skeleton/ha-skeleton-text";
import { skeletonArrivalStyles } from "../skeleton/skeleton-arrival";
import "../ha-svg-icon";
import "../input/ha-input-search";
import { filterData, sortData } from "./sort-filter";
@@ -801,11 +800,9 @@ export class HaDataTable extends LitElement {
</div>`
: nothing
}
<!-- The list fades in once as it takes the skeleton rows'
place; rows made later as it scrolls show at once -->
<lit-virtualizer
scroller
class="mdc-data-table__content scroller ha-scrollbar arriving ${classMap(
class="mdc-data-table__content scroller ha-scrollbar ${classMap(
{ grouped: Boolean(this.groupColumn) && !this.autoHeight }
)}"
tabindex=${ifDefined(!this.autoHeight ? "0" : undefined)}
@@ -1631,7 +1628,6 @@ export class HaDataTable extends LitElement {
static get styles(): CSSResultGroup {
return [
haStyleScrollbar,
skeletonArrivalStyles,
css`
/* default mdc styles, colors changed, without checkbox styles */
:host {
+20
View File
@@ -243,6 +243,10 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
}
private _handleTouchStart = (ev: TouchEvent) => {
if (ev.touches.length > 1) {
this._cancelResizing();
return;
}
if (this.preventScrimClose) {
return;
}
@@ -269,6 +273,10 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
}
private _handleTouchMove = (ev: TouchEvent) => {
if (ev.touches.length > 1) {
this._cancelResizing();
return;
}
const currentY = ev.touches[0].clientY;
const delta = this._gestureRecognizer.move(currentY);
@@ -341,6 +349,18 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
}
};
/**
* A second finger makes it a pinch, like zooming a camera picture, which
* never moves the sheet. Puts the sheet back where it was.
*/
private _cancelResizing() {
this._unregisterResizeHandlers();
if (this._isDragging) {
this._isDragging = false;
this._animateSnapBack();
}
}
private _unregisterResizeHandlers = () => {
document.removeEventListener("touchmove", this._handleTouchMove);
document.removeEventListener("touchend", this._handleTouchEnd);
+144 -3
View File
@@ -19,9 +19,11 @@ import {
type CameraEntity,
} from "../data/camera";
import {
computeCameraStreamStatus,
MJPEG_STREAM,
selectCameraStreams,
type CameraStream,
type CameraStreamStatus,
type CameraStreamTracks,
type CameraStreamType,
} from "../data/camera-streams";
@@ -32,10 +34,16 @@ import {
formattersContext,
} from "../data/context";
import "./ha-hls-player";
import type { HaHLSPlayer } from "./ha-hls-player";
import "./ha-mjpeg-player";
import type { HaMjpegPlayer } from "./ha-mjpeg-player";
import "./ha-web-rtc-player";
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
export type { CameraStreamType } from "../data/camera-streams";
export type {
CameraStreamStatus,
CameraStreamType,
} from "../data/camera-streams";
@customElement("ha-camera-stream")
export class HaCameraStream extends LitElement {
@@ -70,6 +78,13 @@ export class HaCameraStream extends LitElement {
@property({ type: Boolean, attribute: "allow-exoplayer" })
public allowExoPlayer = false;
/**
* Shows an MJPEG stream in a player that can also open it picture in
* picture, which copies its frames into a video while open.
*/
@property({ type: Boolean, attribute: "mjpeg-video" })
public mjpegVideo = false;
// Video background image before its loaded
@state() private _posterUrl?: string;
@@ -81,10 +96,25 @@ export class HaCameraStream extends LitElement {
@state() private _webRtcStreams?: CameraStreamTracks;
// Streams that played their first frame
@state() private _loadedStreams: ReadonlySet<CameraStreamType> = new Set();
// The app plays the HLS stream in its own player, over the page
@state() private _hlsInApp = false;
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
@query("ha-mjpeg-player") private _mjpegPlayer?: HaMjpegPlayer;
@query(
"ha-hls-player:not(.hidden), ha-web-rtc-player:not(.hidden), ha-mjpeg-player"
)
private _visiblePlayer?: HaHLSPlayer | HaWebRtcPlayer | HaMjpegPlayer;
private _visibleStreamType?: CameraStreamType;
private _status?: CameraStreamStatus;
private _capabilitiesRequest = 0;
private _thumbnailApi = memoizeOne(
@@ -118,6 +148,17 @@ export class HaCameraStream extends LitElement {
this._getCapabilities();
this._getPosterUrl();
}
const oldConnection = changedProps.get("_connection") as
ContextType<typeof connectionContext> | undefined;
if (
oldConnection &&
!oldConnection.connected &&
this._connection.connected
) {
// An MJPEG stream doesn't come back on its own
this._restartMjpeg();
}
}
/** The microphone track sent to the camera, only on WebRTC streams. */
@@ -125,6 +166,22 @@ export class HaCameraStream extends LitElement {
return this._webRtcPlayer?.microphoneTrack;
}
/** The video of the shown stream. */
public get videoElement(): HTMLVideoElement | undefined {
return this._visiblePlayer?.videoElement;
}
/** Opens the video of the shown stream picture in picture. */
public async requestPictureInPicture() {
const player = this._visiblePlayer;
// An MJPEG stream first has to start copying its image into the video
if (player && "requestPictureInPicture" in player) {
await player.requestPictureInPicture();
return;
}
await this.videoElement?.requestPictureInPicture();
}
/** Toggles sending the microphone to the camera, only on WebRTC streams. */
public async toggleMicrophone() {
await this._webRtcPlayer?.toggleMicrophone();
@@ -157,6 +214,27 @@ export class HaCameraStream extends LitElement {
this._visibleStreamType = visibleStreamType;
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
}
const status: CameraStreamStatus = {
...computeCameraStreamStatus(
streams,
// Nothing plays while Home Assistant is disconnected
this._connection.connected ? this._loadedStreams : new Set(),
this._hlsStreams,
this._webRtcStreams
),
inApp: visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp,
};
if (
!this._status ||
status.type !== this._status.type ||
status.connecting !== this._status.connecting ||
status.upgrading !== this._status.upgrading ||
status.hasAudio !== this._status.hasAudio ||
status.inApp !== this._status.inApp
) {
this._status = status;
fireEvent(this, "camera-stream-status-changed", status);
}
}
protected render() {
@@ -176,14 +254,25 @@ export class HaCameraStream extends LitElement {
return nothing;
}
if (stream.type === MJPEG_STREAM) {
const mjpegPath = computeMJPEGStreamUrl(this.stateObj);
const streamUrl = __DEMO__
? this.stateObj.attributes.entity_picture
: this._connected
? computeMJPEGStreamUrl(this.stateObj)
? // Like the other streams, as the frontend can be served elsewhere
mjpegPath && this._connection.hassUrl(mjpegPath)
: this._posterUrl;
if (!streamUrl) {
return nothing;
}
if (this.mjpegVideo) {
return html`<ha-mjpeg-player
.src=${streamUrl}
.alt=${`Preview of the ${this._formatters?.formatEntityName(this.stateObj) ?? ""} camera.`}
.aspectRatio=${this.aspectRatio}
.fitMode=${this.fitMode}
@load=${this._handleMjpegLoad}
></ha-mjpeg-player>`;
}
return html`<img
.src=${streamUrl}
style=${styleMap({
@@ -205,6 +294,8 @@ export class HaCameraStream extends LitElement {
.entityid=${this.stateObj.entity_id}
.posterUrl=${this._posterUrl}
@streams=${this._handleHlsStreams}
@load=${this._handleHlsLoad}
@exoplayer-changed=${this._handleExoPlayerChanged}
class=${stream.visible ? "" : "hidden"}
.aspectRatio=${this.aspectRatio}
.fitMode=${this.fitMode}
@@ -220,6 +311,7 @@ export class HaCameraStream extends LitElement {
.entityid=${this.stateObj.entity_id}
.posterUrl=${this._posterUrl}
@streams=${this._handleWebRtcStreams}
@load=${this._handleWebRtcLoad}
class=${stream.visible ? "" : "hidden"}
.aspectRatio=${this.aspectRatio}
.fitMode=${this.fitMode}
@@ -261,6 +353,27 @@ export class HaCameraStream extends LitElement {
private _resetStreams() {
this._hlsStreams = undefined;
this._webRtcStreams = undefined;
this._loadedStreams = new Set();
this._hlsInApp = false;
this._mjpegPlayer?.restart();
}
private _restartMjpeg() {
this._setLoaded(MJPEG_STREAM, false);
this._mjpegPlayer?.restart();
}
private _setLoaded(type: CameraStreamType, loaded: boolean) {
if (this._loadedStreams.has(type) === loaded) {
return;
}
const loadedStreams = new Set(this._loadedStreams);
if (loaded) {
loadedStreams.add(type);
} else {
loadedStreams.delete(type);
}
this._loadedStreams = loadedStreams;
}
private async _getPosterUrl(): Promise<void> {
@@ -278,11 +391,33 @@ export class HaCameraStream extends LitElement {
}
private _handleImageLoad() {
this._setLoaded(MJPEG_STREAM, true);
fireEvent(this, "load");
}
private _handleMjpegLoad() {
this._setLoaded(MJPEG_STREAM, true);
}
private _handleHlsLoad() {
this._setLoaded(STREAM_TYPE_HLS, true);
}
private _handleExoPlayerChanged(
ev: HASSDomEvent<HASSDomEvents["exoplayer-changed"]>
) {
this._hlsInApp = ev.detail.active;
}
private _handleWebRtcLoad() {
this._setLoaded(STREAM_TYPE_WEB_RTC, true);
}
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
this._hlsStreams = ev.detail;
if (!ev.detail.hasVideo) {
this._setLoaded(STREAM_TYPE_HLS, false);
}
}
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
@@ -294,9 +429,13 @@ export class HaCameraStream extends LitElement {
) {
// Without another stream type, keep the player to show why it failed.
// Only a browser without WebRTC falls back to MJPEG.
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
return;
}
this._webRtcStreams = ev.detail;
if (!ev.detail.hasVideo) {
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
}
}
private _streams = memoizeOne(
@@ -318,7 +457,8 @@ export class HaCameraStream extends LitElement {
static styles = css`
:host,
img {
img,
ha-mjpeg-player {
display: block;
}
@@ -350,6 +490,7 @@ declare global {
load: undefined;
"stream-type-changed": { type?: CameraStreamType };
"camera-capabilities-changed": { capabilities?: CameraCapabilities };
"camera-stream-status-changed": CameraStreamStatus;
streams: {
hasAudio: boolean;
hasVideo: boolean;
+9
View File
@@ -55,6 +55,15 @@ export class HaFilterBlueprints extends LitElement {
private _relatedRequestId = 0;
public connectedCallback() {
super.connectedCallback();
// The config pages are cached, so an item may have been edited while this
// filter was not on screen
if (this.hasUpdated && this.value?.length) {
this._findRelated();
}
}
public willUpdate(properties: PropertyValues<this>) {
super.willUpdate(properties);
+9
View File
@@ -74,6 +74,15 @@ export class HaFilterDevices extends LitElement {
private _relatedRequestId = 0;
public connectedCallback() {
super.connectedCallback();
// The config pages are cached, so an item may have been edited while this
// filter was not on screen
if (this.hasUpdated && this.value?.length) {
this._findRelated();
}
}
public willUpdate(properties: PropertyValues<this>) {
super.willUpdate(properties);
+9
View File
@@ -80,6 +80,15 @@ export class HaFilterEntities extends LitElement {
private _relatedRequestId = 0;
public connectedCallback() {
super.connectedCallback();
// The config pages are cached, so an item may have been edited while this
// filter was not on screen
if (this.hasUpdated && this.value?.length) {
this._findRelated();
}
}
public willUpdate(properties: PropertyValues<this>) {
super.willUpdate(properties);
+15
View File
@@ -110,6 +110,21 @@ export class HaFilterFloorAreas extends LitElement {
private _relatedRequestId = 0;
public connectedCallback() {
super.connectedCallback();
// The config pages are cached, so an item may have been edited while this
// filter was not on screen
if (
this.hasUpdated &&
this.value &&
(this.value.areas?.length ||
this.value.floors?.length ||
this.value.no_area)
) {
this._findRelated();
}
}
public willUpdate(properties: PropertyValues) {
super.willUpdate(properties);
+12 -1
View File
@@ -23,7 +23,7 @@ type HlsLite = Omit<
const HIDDEN_CLEANUP_DELAY = 60000;
@customElement("ha-hls-player")
class HaHLSPlayer extends LitElement {
export class HaHLSPlayer extends LitElement {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@@ -111,6 +111,11 @@ class HaHLSPlayer extends LitElement {
}
};
/** The video that plays the stream, undefined while the app plays it. */
public get videoElement(): HTMLVideoElement | undefined {
return this._exoPlayer ? undefined : (this._videoEl ?? undefined);
}
public connectedCallback() {
super.connectedCallback();
HaHLSPlayer.streamCount += 1;
@@ -309,6 +314,7 @@ class HaHLSPlayer extends LitElement {
private async _renderHLSExoPlayer(url: string) {
this._exoPlayer = true;
fireEvent(this, "exoplayer-changed", { active: true });
window.addEventListener("resize", this._resizeExoPlayer);
this.updateComplete.then(() => nextRender()).then(this._resizeExoPlayer);
this._videoEl.style.visibility = "hidden";
@@ -444,6 +450,7 @@ class HaHLSPlayer extends LitElement {
window.removeEventListener("resize", this._resizeExoPlayer);
this._config.auth.external!.fireMessage({ type: "exoplayer/stop" });
this._exoPlayer = false;
fireEvent(this, "exoplayer-changed", { active: false });
}
if (this._videoEl) {
this._videoEl.removeAttribute("src");
@@ -505,6 +512,10 @@ class HaHLSPlayer extends LitElement {
}
declare global {
interface HASSDomEvents {
"exoplayer-changed": { active: boolean };
}
interface HTMLElementTagNameMap {
"ha-hls-player": HaHLSPlayer;
}
+257
View File
@@ -0,0 +1,257 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { live } from "lit/directives/live";
import { styleMap } from "lit/directives/style-map";
import { fireEvent } from "../common/dom/fire_event";
const LOAD_CHECK_INTERVAL = 250;
// Limits the copying, MJPEG streams rarely send more frames than this
const PICTURE_IN_PICTURE_FRAME_RATE = 15;
/**
* Shows an MJPEG stream as an image, like any browser can. Picture in
* picture only works with a video, so while it is open, the image is copied
* into a canvas that a hidden video plays. The video only plays then, so
* browsers don't offer picture in picture on their own.
*/
@customElement("ha-mjpeg-player")
export class HaMjpegPlayer extends LitElement {
@property() public src?: string;
@property() public alt?: string;
@property({ attribute: false }) public aspectRatio?: number;
@property({ attribute: false }) public fitMode?: "cover" | "contain" | "fill";
@state() private _loaded = false;
// The image can be copied, it is not from another origin
@state() private _canCopy = false;
@query("#stream") private _imageEl?: HTMLImageElement;
@query("video") private _videoEl?: HTMLVideoElement;
private _canvas?: HTMLCanvasElement;
private _stream?: MediaStream;
private _loadCheckInterval?: number;
private _drawInterval?: number;
/** The video for picture in picture, undefined when it can't be shown. */
public get videoElement(): HTMLVideoElement | undefined {
return this._canCopy ? this._videoEl : undefined;
}
/**
* Starts copying the image into the video and opens it picture in
* picture. Stops copying again when it can't be opened.
*/
public async requestPictureInPicture(): Promise<void> {
const video = this._videoEl;
if (!this._canCopy || !video) {
return;
}
try {
if (!this._stream) {
this._drawFrame();
// Captures a frame whenever the canvas is drawn
this._stream = this._canvas!.captureStream();
video.srcObject = this._stream;
this._drawInterval = window.setInterval(
() => this._drawFrame(),
1000 / PICTURE_IN_PICTURE_FRAME_RATE
);
}
// Picture in picture needs the video to play first
await video.play();
await video.requestPictureInPicture();
} catch (err: unknown) {
this._stopVideo();
throw err;
}
}
/** Loads the stream again and waits for its first frame. */
public restart() {
if (!this.hasUpdated) {
return;
}
// Without a source, the image drops its last frame, so the next one
// really is from the new stream
this._imageEl?.removeAttribute("src");
this._loaded = false;
this._canCopy = false;
// Sets the source again, also when nothing else changed
this.requestUpdate();
this._startLoadCheck();
}
public connectedCallback() {
super.connectedCallback();
if (this.hasUpdated && !this._loaded) {
this._startLoadCheck();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
this._stopLoadCheck();
this._stopVideo();
}
protected firstUpdated() {
this._startLoadCheck();
}
protected render() {
if (!this.src) {
return nothing;
}
const style = styleMap({
aspectRatio: this.aspectRatio,
objectFit: this.fitMode,
});
return html`
${this._loaded ? nothing : html`<div class="placeholder"></div>`}
<img
id="stream"
class=${this._loaded ? "" : "loading"}
.src=${live(this.src)}
alt=${this.alt ?? ""}
style=${style}
draggable="false"
@load=${this._checkLoaded}
@error=${this._stopLoadCheck}
/>
<video
muted
playsinline
disableremoteplayback
aria-hidden="true"
@leavepictureinpicture=${this._stopVideo}
></video>
`;
}
private _startLoadCheck() {
this._stopLoadCheck();
this._loadCheckInterval = window.setInterval(
() => this._checkLoaded(),
LOAD_CHECK_INTERVAL
);
}
private _stopLoadCheck() {
clearInterval(this._loadCheckInterval);
this._loadCheckInterval = undefined;
}
// An MJPEG stream never completes loading, so only wait for a first frame
private _checkLoaded() {
if (!this._imageEl?.naturalWidth) {
return;
}
this._canCopy = this._testCopy();
this._setLoaded();
}
private _setLoaded() {
this._stopLoadCheck();
if (!this._loaded) {
this._loaded = true;
fireEvent(this, "load");
}
}
/** An image from another origin can't be copied out of a canvas. */
private _testCopy(): boolean {
try {
this._drawFrame();
this._canvas?.getContext("2d")?.getImageData(0, 0, 1, 1);
return Boolean(this._canvas);
} catch (_err: unknown) {
return false;
}
}
private _drawFrame() {
const image = this._imageEl;
if (!image?.naturalWidth) {
return;
}
if (!this._canvas) {
this._canvas = document.createElement("canvas");
}
const canvas = this._canvas;
if (
canvas.width !== image.naturalWidth ||
canvas.height !== image.naturalHeight
) {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
}
canvas.getContext("2d")?.drawImage(image, 0, 0);
}
private _stopVideo = () => {
clearInterval(this._drawInterval);
this._drawInterval = undefined;
this._stream?.getTracks().forEach((track) => track.stop());
this._stream = undefined;
if (this._videoEl) {
this._videoEl.srcObject = null;
}
};
static styles = css`
:host {
display: block;
position: relative;
}
img {
display: block;
width: 100%;
max-height: var(--video-max-height, calc(100vh - 97px));
object-fit: contain;
user-select: none;
-webkit-user-select: none;
}
/* Keeps the room of a picture until the first frame, so nothing jumps */
.placeholder {
aspect-ratio: 16 / 9;
max-height: var(--video-max-height, calc(100vh - 97px));
}
/* Shows over the placeholder as soon as the browser draws a frame, some
browsers don't load a stream they don't show */
img.loading {
position: absolute;
inset: 0;
height: 100%;
}
/* Only plays for picture in picture, kept rendered so it can play */
video {
position: absolute;
top: 0;
left: 0;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-mjpeg-player": HaMjpegPlayer;
}
}
@@ -0,0 +1,30 @@
import type {
LocationSelector,
LocationSelectorValue,
} from "../../data/selector";
export const DEFAULT_RADIUS = 1000;
/**
* The selector's value from its form's value. A value that never had a radius
* falls back to the default the map draws, while a radius the user cleared is
* left out so the field stays empty. A read-only radius is kept as is because
* core stores it as a float.
*/
export const computeLocationSelectorValue = (
selector: LocationSelector,
value: LocationSelectorValue
): LocationSelectorValue => {
if (!selector.location?.radius) {
return { latitude: value.latitude, longitude: value.longitude };
}
const radius = "radius" in value ? value.radius : DEFAULT_RADIUS;
if (radius === undefined || radius === null) {
return { latitude: value.latitude, longitude: value.longitude };
}
return {
latitude: value.latitude,
longitude: value.longitude,
radius: selector.location.radius_readonly ? radius : Math.round(radius),
};
};
@@ -12,6 +12,10 @@ import type { MarkerLocation } from "../map/ha-locations-editor";
import "../map/ha-locations-editor";
import "../ha-form/ha-form";
import type { LocalizeFunc } from "../../common/translations/localize";
import {
computeLocationSelectorValue,
DEFAULT_RADIUS,
} from "./compute-location-selector-value";
@customElement("ha-selector-location")
export class HaLocationSelector extends LitElement {
@@ -51,7 +55,7 @@ export class HaLocationSelector extends LitElement {
{
name: "radius",
required: true,
default: 1000,
default: DEFAULT_RADIUS,
disabled: !!radius_readonly,
selector: {
number: {
@@ -74,7 +78,7 @@ export class HaLocationSelector extends LitElement {
this.value = {
latitude: this.hass.config.latitude,
longitude: this.hass.config.longitude,
radius: this.selector.location?.radius ? 1000 : undefined,
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
};
}
}
@@ -126,7 +130,9 @@ export class HaLocationSelector extends LitElement {
!value || isNaN(value.longitude)
? this.hass.config.longitude
: value.longitude,
radius: selector.location?.radius ? value?.radius || 1000 : undefined,
radius: selector.location?.radius
? value?.radius || DEFAULT_RADIUS
: undefined,
radius_color: selector.location?.color || zoneRadiusColor,
name: selector.location?.name,
icon:
@@ -155,20 +161,8 @@ export class HaLocationSelector extends LitElement {
private _valueChanged(ev: CustomEvent) {
ev.stopPropagation();
const value = ev.detail.value;
const radius = Math.round(ev.detail.value.radius);
fireEvent(this, "value-changed", {
value: {
latitude: value.latitude,
longitude: value.longitude,
...(this.selector.location?.radius &&
!this.selector.location?.radius_readonly
? {
radius,
}
: {}),
},
value: computeLocationSelectorValue(this.selector, ev.detail.value),
});
}
+125 -24
View File
@@ -2,10 +2,21 @@ import type { ContextType } from "@lit/context";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { cssColorToHex } from "../common/color/hex";
import { normalizeLuminance } from "../common/color/palette";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import type { LocalizeFunc } from "../common/translations/localize";
import { uiContext } from "../data/context";
import {
getThemeModeSupport,
getThemeVariables,
themeDefinesColor,
type Theme,
type ThemeModeSupport,
} from "../data/ws-themes";
import {
DefaultAccentColor,
DefaultPrimaryColor,
@@ -41,6 +52,10 @@ export class HaThemeSettings extends LitElement {
@consume({ context: uiContext, subscribe: true })
private _ui!: ContextType<typeof uiContext>;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@property({ attribute: false }) public selectedTheme?: ThemeSettings | null;
@property({ attribute: false }) public labels?: ThemeSettingsLabels;
@@ -69,12 +84,30 @@ export class HaThemeSettings extends LitElement {
? this._ui.themes.default_dark_theme || this._ui.themes.default_theme
: this._ui.themes.default_theme;
const showDarkMode =
curTheme === HOME_ASSISTANT_THEME ||
const customTheme =
curTheme && curTheme !== HOME_ASSISTANT_THEME
? this._ui.themes.themes[curTheme]
: undefined;
const showThemeOptions = curTheme === HOME_ASSISTANT_THEME || !!customTheme;
// With "use default theme", the mode picks the default light or dark theme.
const modeSupport: ThemeModeSupport =
!customTheme ||
(curThemeIsUseDefault &&
this._ui.themes.default_dark_theme &&
this._ui.themes.default_theme) ||
this._supportsModeSelection(curTheme);
this._ui.themes.default_theme)
? "both"
: getThemeModeSupport(customTheme);
const themeColors = this._themeColors(
customTheme,
this._ui.themes.darkMode
);
const primaryColorLocked = themeColors.primary !== undefined;
const accentColorLocked = themeColors.accent !== undefined;
const showReset =
(!!themeSettings?.primaryColor && !primaryColorLocked) ||
(!!themeSettings?.accentColor && !accentColorLocked);
return html`
<ha-list-base>
@@ -108,9 +141,20 @@ export class HaThemeSettings extends LitElement {
: nothing
}
${
showDarkMode
showThemeOptions
? html`
<ha-list-item-base>
<ha-list-item-base
class="set-by-theme"
wrap-supporting-text
.supportingText=${
modeSupport !== "both"
? this._localize(
`ui.panel.profile.themes.mode_set_by_theme.${modeSupport}`,
{ theme: curTheme }
)
: undefined
}
>
<span slot="headline"
>${this.labels?.mode ?? "Theme mode"}</span
>
@@ -118,13 +162,8 @@ export class HaThemeSettings extends LitElement {
slot="end"
@change=${this._handleDarkMode}
name="dark_mode"
.value=${
themeSettings?.dark === undefined
? "auto"
: themeSettings.dark
? "dark"
: "light"
}
.value=${this._modeValue(modeSupport, themeSettings?.dark)}
.disabled=${modeSupport !== "both"}
orientation="horizontal"
>
<ha-radio-option value="auto">
@@ -142,31 +181,56 @@ export class HaThemeSettings extends LitElement {
: nothing
}
${
curTheme === HOME_ASSISTANT_THEME
showThemeOptions
? html`
<ha-list-item-base>
<ha-list-item-base
class="set-by-theme"
wrap-supporting-text
.supportingText=${
primaryColorLocked || accentColorLocked
? this._localize(
`ui.panel.profile.themes.colors_set_by_theme.${
primaryColorLocked && accentColorLocked
? "both"
: primaryColorLocked
? "primary"
: "accent"
}`,
{ theme: curTheme }
)
: undefined
}
>
<span slot="headline"
>${this.labels?.colors ?? "Custom colors"}</span
>
<div slot="end" class="color-pickers">
<ha-input
.value=${themeSettings?.primaryColor || DefaultPrimaryColor}
.value=${
themeColors.primary ??
(themeSettings?.primaryColor || DefaultPrimaryColor)
}
type="color"
.label=${this.labels?.primaryColor ?? "Primary color"}
.name=${"primaryColor"}
.disabled=${primaryColorLocked}
@change=${this._handleColorChange}
></ha-input>
<ha-input
.value=${themeSettings?.accentColor || DefaultAccentColor}
.value=${
themeColors.accent ??
(themeSettings?.accentColor || DefaultAccentColor)
}
type="color"
.label=${this.labels?.accentColor ?? "Accent color"}
.name=${"accentColor"}
.disabled=${accentColorLocked}
@change=${this._handleColorChange}
></ha-input>
</div>
</ha-list-item-base>
${
themeSettings?.primaryColor || themeSettings?.accentColor
showReset
? html`
<div class="reset-row">
<ha-button
@@ -207,15 +271,49 @@ export class HaThemeSettings extends LitElement {
});
}
private _supportsModeSelection(themeName: string): boolean {
const theme = this._ui.themes.themes[themeName];
if (!theme) {
return false;
private _modeValue(
modeSupport: ThemeModeSupport,
dark: boolean | undefined
): string {
switch (modeSupport) {
case "light":
case "dark":
return modeSupport;
case "none":
// The theme has fixed colors, so neither light nor dark is accurate.
return "";
default:
return dark === undefined ? "auto" : dark ? "dark" : "light";
}
return !!(theme.modes && "light" in theme.modes && "dark" in theme.modes);
}
/** Colors the theme sets itself, `undefined` when the user can pick them. */
private _themeColors = memoizeOne(
(
theme: Theme | undefined,
darkMode: boolean
): { primary?: string; accent?: string } => {
if (!theme) {
return {};
}
const variables = getThemeVariables(theme, darkMode);
const toHex = (value: string | undefined, fallback: string) =>
(value && cssColorToHex(value)) || fallback;
return {
primary: themeDefinesColor(variables, "primary")
? toHex(
// A theme that only sets the palette uses its base step as primary
variables["primary-color"] ?? variables["ha-color-primary-40"],
DefaultPrimaryColor
)
: undefined,
accent: themeDefinesColor(variables, "accent")
? toHex(variables["accent-color"], DefaultAccentColor)
: undefined,
};
}
);
private _handleDarkMode(ev: Event) {
let dark: boolean | undefined;
switch ((ev.currentTarget as HaRadioGroup).value) {
@@ -267,6 +365,9 @@ export class HaThemeSettings extends LitElement {
ha-theme-picker {
min-width: 150px;
}
.set-by-theme::part(supporting-text) {
color: var(--ha-color-text-secondary);
}
.color-pickers {
display: flex;
gap: var(--ha-space-2);
+6 -4
View File
@@ -121,6 +121,11 @@ export class HaWebRtcPlayer extends LitElement {
return this._localReturnAudioTrack ? "on" : "off";
}
/** The video that plays the stream, undefined while showing an error. */
public get videoElement(): HTMLVideoElement | undefined {
return this._videoEl ?? undefined;
}
public get microphoneTrack(): MediaStreamTrack | undefined {
return this._localReturnAudioTrack;
}
@@ -631,10 +636,7 @@ export class HaWebRtcPlayer extends LitElement {
if (!this._remoteStream) {
return;
}
// If the track is audio and the player is muted, we do not add it to the stream.
if (event.track.kind === "audio" && this.muted) {
return;
}
// Audio is always added, even when muted, so it can be unmuted later
this._remoteStream.addTrack(event.track);
if (!this.hasUpdated) {
await this.updateComplete;
+21 -2
View File
@@ -1,6 +1,8 @@
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import "../ha-checkbox";
import "../ha-ripple";
import { HaListItemBase } from "./ha-list-item-base";
@@ -15,7 +17,8 @@ export type HaListItemOptionSelectionPosition = "start" | "end";
*
* @summary
* Selectable list row (role `option`). Selection state is driven by the parent
* `ha-list-selectable`; reflects `aria-selected`. When `appearance="checkbox"`, renders
* `ha-list-selectable`; reflects `aria-selected`, and describes an `indeterminate` row
* as partly selected through `aria-description`. When `appearance="checkbox"`, renders
* a decorative `<ha-checkbox>` (clicks on the row are handled by the listbox).
*
* @csspart checkbox - Wrapper around the `<ha-checkbox>` when `appearance="checkbox"`.
@@ -47,6 +50,10 @@ export class HaListItemOption extends HaListItemBase {
public override interactive = true;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
public update(changed: Map<string, unknown>) {
super.update(changed);
if (changed.has("selected")) {
@@ -55,6 +62,18 @@ export class HaListItemOption extends HaListItemBase {
if (changed.has("disabled")) {
this.setAttribute("aria-disabled", this.disabled ? "true" : "false");
}
if (changed.has("indeterminate") || changed.has("_localize")) {
// `option` has no mixed selection state, so describe it instead of
// letting the row read as unselected
const description = this.indeterminate
? this._localize?.("ui.components.list-item-option.partly_selected")
: undefined;
if (description) {
this.setAttribute("aria-description", description);
} else {
this.removeAttribute("aria-description");
}
}
}
protected _renderBase(inner: TemplateResult): TemplateResult {
-8
View File
@@ -73,7 +73,6 @@ import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { EntityRegistryEntry } from "../../data/entity/entity_registry";
import { ensureMapTilesToken } from "../../data/map_tiles";
import "../ha-tooltip";
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
import type {
HomeAssistantConfig,
HomeAssistantConnection,
@@ -716,12 +715,6 @@ export class HaMap extends ReactiveElement {
private _drawnFallback?: number;
// Until the first frame, which the map fades in with
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() => this.isConnected && !this._mapDrawn
);
private _markDrawn(attempt: number): void {
if (attempt !== this._setupAttempt || this._mapDrawn) {
return;
@@ -729,7 +722,6 @@ export class HaMap extends ReactiveElement {
clearTimeout(this._drawnFallback);
this._mapDrawn = true;
this._updateMapAppearance();
this.requestUpdate();
}
private _loading = false;
@@ -1,543 +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 { internationalizationContext } from "../../data/context";
import type { HaSkeleton } from "./ha-skeleton";
import "./ha-skeleton";
import {
rememberedSkeletonHeight,
rememberSkeletonHeight,
} from "./skeleton-sizes";
/* How long after loading the content can still settle into its size */
const SETTLE_TIME = 2000;
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[];
}
/**
* 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 a `skeleton-key`, it remembers how big the content was once loaded,
* and next time holds that size while it loads, stretching the content to
* fill it. Give each piece of content its own key, such as one made with
* `skeletonKey()` from its config.
*
* 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";
/** Remember the loaded size under this key, and hold it next time */
@property({ attribute: "skeleton-key" }) public skeletonKey?: string;
@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;
/* Inline values the parts had before they were hidden */
private _hiddenOpacity = new Map<HTMLElement | SVGElement, string>();
private _hiddenColor = new Map<HTMLElement, string>();
private _wasLoading = false;
/* What to fade in once loading has ended */
private _arriving?: ArrivingParts;
private _measureFrame?: number;
/* Whether the remembered size was looked at for this load */
private _reserveChecked = false;
private _settleObserver?: ResizeObserver;
private _settleTimeout?: number;
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
private _intersectionObserver = new IntersectionObserver((entries) => {
this._onScreen = entries[entries.length - 1].isIntersecting;
});
public connectedCallback() {
super.connectedCallback();
if (this._wasLoading) {
this._observe();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
this._unobserve();
this._stopRemembering();
if (this._measureFrame !== undefined) {
cancelAnimationFrame(this._measureFrame);
this._measureFrame = undefined;
}
// Never leave the content hidden while it's away
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) {
this._customSkeleton = [...this.children].some(
(child) => child.slot === "skeleton"
);
this._reserveChecked = false;
this._stopRemembering();
this._observe();
}
if (!loading && this._wasLoading) {
this._unobserve();
this._endLoading();
this._rememberWhenSettled();
}
this._wasLoading = loading;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
if (this._isLoading) {
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";
return html`
<slot
class=${classMap({
// Before the first reading, or under a skeleton of your own
hidden:
loading && (this._customSkeleton || this._pieces === undefined),
})}
@slotchange=${this._contentChanged}
@skeleton-loading=${this._skeletonLoading}
></slot>
${
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();
}
/* Sizes and visibility only matter while loading, so an overlay around
content that has loaded costs nothing */
private _observe() {
this._resizeObserver.disconnect();
this._resizeObserver.observe(this);
this._contentSlot
?.assignedElements()
.forEach((element) => this._resizeObserver.observe(element));
this._intersectionObserver.observe(this);
this._scheduleMeasure();
}
private _unobserve() {
this._resizeObserver.disconnect();
this._intersectionObserver.disconnect();
}
private _contentChanged() {
if (!this._isLoading) {
return;
}
this._observe();
this._pruneSources();
}
/* Content that went away can't finish loading */
private _pruneSources() {
const sources = [...this._loadingSources].filter(
(source) => !(source instanceof Node) || source.isConnected
);
if (sources.length !== this._loadingSources.size) {
this._loadingSources = new Set(sources);
}
}
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;
}
}
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() {
// A part that said it was loading may have gone without saying it's done
this._pruneSources();
if (!this._isLoading) {
return;
}
this._reserve();
if (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;
}
}
/* Hold the height the content had last time it loaded at this width */
private _reserve() {
if (this._reserveChecked || !this.skeletonKey) {
return;
}
const width = this.getBoundingClientRect().width;
// Not laid out yet
if (!width) {
return;
}
this._reserveChecked = true;
const height = rememberedSkeletonHeight(this.skeletonKey, width);
if (height === undefined) {
return;
}
this.style.setProperty(
"--ha-skeleton-overlay-reserved-height",
`${height}px`
);
this.toggleAttribute("reserved", true);
}
private _release() {
this.removeAttribute("reserved");
this.style.removeProperty("--ha-skeleton-overlay-reserved-height");
}
/* Remember the size the content settles into once it has loaded */
private _rememberWhenSettled() {
const key = this.skeletonKey;
if (!key) {
return;
}
this._settleObserver = new ResizeObserver(() => {
const { width, height } = this.getBoundingClientRect();
if (width && height) {
rememberSkeletonHeight(key, width, height);
}
});
this._settleObserver.observe(this);
this._settleTimeout = window.setTimeout(
() => this._stopRemembering(),
SETTLE_TIME
);
}
private _stopRemembering() {
this._settleObserver?.disconnect();
this._settleObserver = undefined;
clearTimeout(this._settleTimeout);
this._settleTimeout = undefined;
}
private _hideParts(skeleton: ExtractedSkeleton) {
skeleton.parts.forEach((part) => {
this._hiddenOpacity.set(part, part.style.opacity);
part.style.opacity = "0";
});
// Text goes through its colour, so a frame drawn by the same element,
// such as a badge's pill, stays
skeleton.textParts.forEach((part) => {
this._hiddenColor.set(part, part.style.color);
part.style.color = "transparent";
});
}
private _showParts() {
this._hiddenOpacity.forEach((opacity, part) => {
part.style.opacity = opacity;
});
this._hiddenColor.forEach((color, part) => {
part.style.color = color;
});
this._hiddenOpacity.clear();
this._hiddenColor.clear();
}
/* Show the content again before the next paint, and note what to fade in */
private _endLoading() {
// Under a skeleton of its own, or with nothing read from it, the whole
// content was hidden or not there yet, rather than its parts
const wholeContent = this._customSkeleton || !this._pieces?.length;
this._arriving = {
content: wholeContent
? (this._contentSlot?.assignedElements() ?? [])
: [],
opacityParts: [...this._hiddenOpacity.keys()],
colorParts: [...this._hiddenColor.keys()],
};
this._showParts();
this._release();
this._pieces = undefined;
}
/* Fade each arriving part in, instantly with reduced motion */
private _fadeIn({ content, opacityParts, colorParts }: ArrivingParts) {
const fade: KeyframeAnimationOptions = {
duration:
parseFloat(
getComputedStyle(this).getPropertyValue(
"--ha-animation-duration-fast"
)
) || 150,
easing: "ease-out",
};
[...content, ...opacityParts].forEach((part) =>
part.animate([{ opacity: 0 }, { opacity: 1 }], fade)
);
colorParts.forEach((part) => {
const color = getComputedStyle(part).color;
part.animate([{ color: "transparent" }, { color }], fade);
});
}
static readonly styles: CSSResultGroup = css`
:host {
display: block;
position: relative;
}
/* Holds the size the content had last time, and stretches the content
to fill it */
:host([reserved]) {
display: grid;
grid-template-columns: minmax(0, 1fr);
}
:host([reserved])::before {
content: "";
grid-area: 1 / 1;
height: var(--ha-skeleton-overlay-reserved-height);
}
:host([reserved]) ::slotted(*) {
grid-area: 1 / 1;
}
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%;
}
/* 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 = (piece: SkeletonPiece) =>
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,
});
declare global {
interface HTMLElementTagNameMap {
"ha-skeleton-overlay": HaSkeletonOverlay;
}
interface HASSDomEvents {
"skeleton-loading": SkeletonLoadingDetail;
}
}
+3 -9
View File
@@ -5,9 +5,8 @@ import { HaSkeleton } from "./ha-skeleton";
/**
* Placeholder for a line of text, matching the tile secondary text skeleton.
* It takes the height of the surrounding line, so swapping it for the text
* doesn't move anything, and draws a thinner bar in the middle of it. Set
* `width` in CSS to fit the expected text.
* Its height follows the surrounding font size. Set `width` in CSS to fit the
* expected text.
*
* @cssprop --ha-skeleton-text-width - The width of the placeholder. Defaults to `140px`.
*/
@@ -20,16 +19,11 @@ export class HaSkeletonText extends HaSkeleton {
:host {
display: inline-flex;
vertical-align: middle;
align-items: center;
width: var(--ha-skeleton-text-width, 140px);
max-width: 100%;
height: 1.2em;
height: 1lh;
height: 1em;
min-height: 0;
}
.indicator {
height: 0.75em;
}
`,
];
}
+7 -189
View File
@@ -1,152 +1,19 @@
import WaSkeleton from "@home-assistant/webawesome/dist/components/skeleton/skeleton";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html } from "lit";
import { customElement, query } from "lit/decorators";
/* How far the wave leans from upright, so it starts at the top corner of the
content and finishes at the opposite bottom corner */
const WAVE_SLANT_DEG = 20;
const WAVE_SLANT = Math.tan((WAVE_SLANT_DEG * Math.PI) / 180);
import type { CSSResultGroup } from "lit";
import { css } from "lit";
import { customElement } from "lit/decorators";
/**
* Placeholder shown while content loads. Sized by its container unless a
* more specific variant such as `ha-skeleton-text` or `ha-skeleton-icon` is used.
*
* A soft wave sweeps across it by default. It's one slanted wave across all
* the skeletons on the page, from the top corner of the content on the side
* text starts from to the opposite bottom corner: each skeleton shows its
* own slice of it, and all of them run in step, so the wave flows from one
* skeleton into the next, and a skeleton added later joins mid-sweep instead
* of starting over. Each sweep starts as the last one leaves the content.
*
* @cssprop --ha-skeleton-color - The fill color. Defaults to `var(--ha-color-fill-neutral-normal-resting)`.
* @cssprop --ha-skeleton-sheen-color - The sheen color when `effect="sheen"`. Defaults to `var(--ha-color-fill-neutral-normal-hover)`.
* @cssprop --ha-skeleton-sheen-color - The sheen color when `effect="sheen"`. Defaults to `var(--ha-color-fill-neutral-loud-resting)`.
* @cssprop --ha-skeleton-border-radius - The corner radius. Defaults to `var(--ha-border-radius-sm)`.
* @cssprop --ha-skeleton-duration - How long one sweep across the skeletons takes when `effect="sheen"`. Defaults to `3s`.
*/
@customElement("ha-skeleton")
export class HaSkeleton extends WaSkeleton {
override effect: WaSkeleton["effect"] = "sheen";
/* Every skeleton showing the wave, which share one track */
private static _waving = new Set<HaSkeleton>();
private static _trackFrame?: number;
@query(".wave") private _wave?: HTMLDivElement;
private _resizeObserver?: ResizeObserver;
/**
* Lay the one track the wave runs along over the content: the box around
* all the skeletons, so no time goes on empty space around them. The wave
* leans, so it enters at the box's top corner and has to travel further,
* by the box's height times the slant, to clear the opposite bottom
* corner. It's measured again whenever a skeleton comes, goes or changes
* size, and at the end of each sweep, so it follows the layout as it moves.
*/
private static _scheduleTrack() {
if (HaSkeleton._trackFrame !== undefined) {
return;
}
HaSkeleton._trackFrame = requestAnimationFrame(() => {
HaSkeleton._trackFrame = undefined;
// Read every skeleton before writing any, so layout runs once
const boxes = [...HaSkeleton._waving].flatMap((skeleton) => {
const rect = skeleton.getBoundingClientRect();
const rtl = getComputedStyle(skeleton).direction === "rtl";
return rect.width > 0 ? [{ skeleton, rect, rtl }] : [];
});
if (boxes.length === 0) {
return;
}
const left = Math.min(...boxes.map(({ rect }) => rect.left));
const right = Math.max(...boxes.map(({ rect }) => rect.right));
const top = Math.min(...boxes.map(({ rect }) => rect.top));
const bottom = Math.max(...boxes.map(({ rect }) => rect.bottom));
const trackLength = right - left + (bottom - top) * WAVE_SLANT;
boxes.forEach(({ skeleton, rect, rtl }) => {
// Right to left, the wave is drawn mirrored, so it's placed from the
// right edge instead
const start = rtl ? rect.right - right : left - rect.left;
// Lower down, the slanted wave arrives later
skeleton._placeWave(start - (rect.top - top) * WAVE_SLANT, trackLength);
});
});
}
public connectedCallback() {
super.connectedCallback();
this._resizeObserver ??= new ResizeObserver(() =>
HaSkeleton._scheduleTrack()
);
this._resizeObserver.observe(this);
if (this.effect === "sheen") {
HaSkeleton._waving.add(this);
HaSkeleton._scheduleTrack();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
this._resizeObserver?.disconnect();
HaSkeleton._waving.delete(this);
HaSkeleton._scheduleTrack();
}
public override render() {
return html`
<div part="indicator" class="indicator">
<div
class="wave"
@animationiteration=${HaSkeleton._scheduleTrack}
></div>
</div>
`;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
if (changedProperties.has("effect")) {
if (this.effect === "sheen") {
HaSkeleton._waving.add(this);
} else {
HaSkeleton._waving.delete(this);
}
HaSkeleton._scheduleTrack();
}
}
/* Put this skeleton's slice of the wave in its place on the track */
private _placeWave(trackStart: number, trackLength: number) {
const wave = this._wave;
if (!wave) {
return;
}
wave.style.left = `${trackStart}px`;
wave.style.setProperty("--ha-skeleton-track-width", `${trackLength}px`);
wave.style.setProperty("--ha-skeleton-slant", `${-WAVE_SLANT_DEG}deg`);
// All waves count from the same moment, so they stay in step
wave.getAnimations().forEach((animation) => {
if (animation.startTime !== 0) {
animation.startTime = 0;
}
});
}
override effect: WaSkeleton["effect"] = "pulse";
static get styles(): CSSResultGroup {
return [
@@ -159,59 +26,13 @@ export class HaSkeleton extends WaSkeleton {
);
--sheen-color: var(
--ha-skeleton-sheen-color,
var(--ha-color-fill-neutral-normal-hover)
var(--ha-color-fill-neutral-loud-resting)
);
--wa-border-radius-pill: var(
--ha-skeleton-border-radius,
var(--ha-border-radius-sm)
);
}
.wave {
display: none;
}
:host([effect="sheen"]) .indicator {
position: relative;
overflow: hidden;
background: var(--color);
animation: none;
}
/* Right to left, the wave is drawn mirrored, so it starts from the
top right corner */
:host([effect="sheen"]:dir(rtl)) .indicator {
transform: scaleX(-1);
}
/* The wave crosses the track over all the skeletons, placed from its
start and leaning back from its top edge, and moves with transform
so it stays cheap */
:host([effect="sheen"]) .wave {
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 400px;
background: linear-gradient(
90deg,
transparent,
var(--sheen-color),
transparent
);
transform-origin: top left;
transform: translateX(-100%) skewX(var(--ha-skeleton-slant, 0deg));
/* An even pace with no hold, so the next sweep enters as soon as
the last one leaves */
animation: ha-skeleton-sheen var(--ha-skeleton-duration, 3s) linear
infinite;
}
@keyframes ha-skeleton-sheen {
from {
transform: translateX(-100%) skewX(var(--ha-skeleton-slant, 0deg));
}
to {
transform: translateX(var(--ha-skeleton-track-width, 100vw))
skewX(var(--ha-skeleton-slant, 0deg));
}
}
@media (forced-colors: active) {
:host {
--color: GrayText;
@@ -219,12 +40,9 @@ export class HaSkeleton extends WaSkeleton {
}
@media (prefers-reduced-motion: reduce) {
:host([effect="pulse"]) .indicator,
:host([effect="sheen"]) .wave {
:host([effect="sheen"]) .indicator {
animation: none;
}
:host([effect="sheen"]) .wave {
display: none;
}
}
`,
];
-128
View File
@@ -1,128 +0,0 @@
import type { nothing, TemplateResult } from "lit";
import { css, html } from "lit";
import type {
ChildPart,
DirectiveParameters,
DirectiveResult,
PartInfo,
} from "lit/directive";
import { Directive, directive, PartType } from "lit/directive";
/* What a skeleton or its content can be rendered as */
type SkeletonOrValue =
| TemplateResult
| DirectiveResult
| string
| number
| typeof nothing
| null
| undefined;
/**
* Content that takes a skeleton's place fades in, so it doesn't pop in. It
* runs at the same pace as `ha-skeleton-overlay`, `--ha-animation-duration-fast`,
* which reduced motion makes instant.
*/
const ARRIVAL_KEYFRAMES: Keyframe[] = [{ opacity: 0 }, { opacity: 1 }];
/**
* Fade in an element that takes a skeleton's place but was already on the
* page, such as a log that fills in while its skeleton shows.
*/
export const fadeInArrival = (element: Element) => {
const duration =
parseFloat(
getComputedStyle(element).getPropertyValue("--ha-animation-duration-fast")
) || 150;
element.animate(ARRIVAL_KEYFRAMES, { duration, easing: "ease-out" });
};
/**
* For a whole block that replaces a skeleton: put the `arriving` class on it,
* and it fades in once, when it first appears. Where it can appear again
* without a skeleton before it, use `skeletonOr` instead.
*/
export const skeletonArrivalStyles = css`
.arriving {
animation: ha-skeleton-arrival var(--ha-animation-duration-fast, 150ms)
ease-out;
}
@keyframes ha-skeleton-arrival {
from {
opacity: 0;
}
}
`;
class SkeletonOrDirective extends Directive {
/* What this spot showed last time */
private _showedSkeleton = false;
/* Text needs an element to fade, so it's wrapped once it has arrived */
private _wrapText = false;
constructor(partInfo: PartInfo) {
super(partInfo);
if (partInfo.type !== PartType.CHILD) {
throw new Error("skeletonOr can only be used in content bindings");
}
}
public render(
loading: boolean,
skeleton: SkeletonOrValue,
content: () => SkeletonOrValue
): SkeletonOrValue {
if (loading) {
return skeleton;
}
const value = content();
return this._wrapText &&
(typeof value === "string" || typeof value === "number")
? html`<span>${value}</span>`
: value;
}
public update(
part: ChildPart,
[loading, skeleton, content]: DirectiveParameters<this>
) {
const arriving = !loading && this._showedSkeleton;
this._showedSkeleton = loading;
if (arriving) {
this._wrapText = true;
// Fade in what was rendered, once it's on the page
requestAnimationFrame(() => {
let node = part.startNode?.nextSibling;
while (node && node !== part.endNode) {
if (node instanceof Element) {
fadeInArrival(node);
}
node = node.nextSibling;
}
});
}
return this.render(loading, skeleton, content);
}
}
/**
* Shows `skeleton` while `loading`, then `content`. When this spot switches
* from the skeleton to the content, the content fades in. A spot that never
* showed a skeleton, such as a table row made as the table scrolls, shows its
* content at once.
*
* Content that's only text is wrapped so it can fade. In a template, put text
* in an element of its own, as only elements fade.
*/
export const skeletonOr = directive(SkeletonOrDirective);
@@ -1,43 +0,0 @@
import type { ReactiveController, ReactiveControllerHost } from "lit";
import { fireEvent } from "../../common/dom/fire_event";
/**
* Tells the nearest `ha-skeleton-overlay` around a component when it starts
* and stops loading, through `skeleton-loading` events. The component
* doesn't need to know whether anything wraps it: without an overlay, the
* events go nowhere.
*
* `isLoading` is read after every update of the host.
*/
export class SkeletonLoadingController implements ReactiveController {
private _host: ReactiveControllerHost & HTMLElement;
private _isLoading: () => boolean;
private _loading = false;
constructor(
host: ReactiveControllerHost & HTMLElement,
isLoading: () => boolean
) {
this._host = host;
this._isLoading = isLoading;
host.addController(this);
}
public hostConnected() {
// A new overlay may be around it now
if (this._loading) {
fireEvent(this._host, "skeleton-loading", { loading: true });
}
}
public hostUpdated() {
const loading = this._isLoading();
if (loading !== this._loading) {
this._loading = loading;
fireEvent(this._host, "skeleton-loading", { loading });
}
}
}
-99
View File
@@ -1,99 +0,0 @@
/* How tall content was once loaded last time, so its skeleton can hold the
same space while it loads again. Content wraps differently at other
widths, so each width is remembered on its own. */
const STORAGE_KEY = "skeletonHeights";
/* Widths this close together share a height */
const WIDTH_STEP = 16;
/* The most recently loaded ones are kept, the oldest dropped: about 20 bytes
each */
const MAX_HEIGHTS = 500;
let heights: Map<string, number> | undefined;
let saveTimeout: number | undefined;
const readHeights = (): Map<string, number> => {
const read = new Map<string, number>();
try {
const stored: unknown = JSON.parse(
window.localStorage.getItem(STORAGE_KEY) ?? "{}"
);
if (stored instanceof Object && !Array.isArray(stored)) {
Object.entries(stored).forEach(([key, height]) => {
if (Number.isFinite(height)) {
read.set(key, Number(height));
}
});
}
} catch {
// Unreadable heights are only lost hints
}
return read;
};
const loadHeights = (): Map<string, number> => {
heights ??= readHeights();
return heights;
};
const saveHeights = () => {
saveTimeout = undefined;
try {
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify(Object.fromEntries(loadHeights()))
);
} catch {
// Private mode or full storage: the skeleton just won't hold the space
}
};
const widthKey = (key: string, width: number) =>
`${key}@${Math.round(width / WIDTH_STEP)}`;
export const rememberedSkeletonHeight = (
key: string,
width: number
): number | undefined => loadHeights().get(widthKey(key, width));
export const rememberSkeletonHeight = (
key: string,
width: number,
height: number
) => {
const stored = loadHeights();
const entryKey = widthKey(key, width);
// Moved to the end, as the most recently loaded
stored.delete(entryKey);
stored.set(entryKey, Math.round(height));
while (stored.size > MAX_HEIGHTS) {
const [oldest] = stored.keys();
stored.delete(oldest);
}
// A view loads many at once, so they're saved together
if (saveTimeout === undefined) {
saveTimeout = window.setTimeout(saveHeights, 1000);
}
};
/* A short, stable key for a longer text, such as a card's config as JSON */
export const skeletonKey = (text: string): string => {
let hash = 5381;
for (let i = 0; i < text.length; i++) {
hash = (hash * 33 + text.charCodeAt(i)) % 2147483647;
}
return `${hash.toString(36)}${text.length.toString(36)}`;
};
+9 -11
View File
@@ -1,7 +1,6 @@
import "../skeleton/ha-skeleton-text";
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { skeletonOr } from "../skeleton/skeleton-arrival";
/**
* Home Assistant tile info component
@@ -47,16 +46,15 @@ export class HaTileInfo extends LitElement {
<slot name="primary" class="primary">
<span part="primary">${this.primary}</span>
</slot>
${skeletonOr(
this.secondaryLoading,
html`<div class="secondary">
<ha-skeleton-text></ha-skeleton-text>
</div>`,
() =>
html`<slot name="secondary" class="secondary">
<span>${this.secondary}</span>
</slot>`
)}
${
this.secondaryLoading
? html`<div class="secondary">
<ha-skeleton-text></ha-skeleton-text>
</div>`
: html`<slot name="secondary" class="secondary">
<span>${this.secondary}</span>
</slot>`
}
</div>
`;
}
+20 -45
View File
@@ -1,16 +1,16 @@
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import type { HassEntity } from "home-assistant-js-websocket";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import { computeStateDomain } from "../../common/entity/compute_state_domain";
import { consumeEntityState } from "../../common/decorators/consume-context-entry";
import { consumeEntityStates } from "../../common/decorators/consume-context-entry";
import { transform } from "../../common/decorators/transform";
import { computeDomain } from "../../common/entity/compute_domain";
import type { User } from "../../data/user";
import { computeUserInitials } from "../../data/user";
import { connectionContext, statesContext } from "../../data/context";
import { connectionContext, entitiesContext } from "../../data/context";
import type { CurrentUser } from "../../types";
@customElement("ha-user-badge")
@@ -21,38 +21,29 @@ class UserBadge extends LitElement {
@consume({ context: connectionContext, subscribe: true })
private _connection?: ContextType<typeof connectionContext>;
// Read by the @consumeEntityStates decorator below.
@state()
@consume({ context: statesContext, subscribe: true })
private _states?: HassEntities;
@state() private _personEntityId?: string;
@consume({ context: entitiesContext, subscribe: true })
@transform<ContextType<typeof entitiesContext>, string[]>({
transformer: (entities) =>
Object.keys(entities ?? {}).filter(
(entityId) => computeDomain(entityId) === "person"
),
})
protected _personEntityIds?: string[];
@state()
@consumeEntityState({ entityIdPath: ["_personEntityId"] })
private _personState?: HassEntity;
public willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
// Re-scan for the user's person entity when the user changes, or when the
// states change while we don't have a (still-present) person entity. Once
// resolved, `_personState` keeps the picture up to date via
// `consumeEntityState`, so there's no need to rescan on every state update.
if (
changedProps.has("user") ||
(changedProps.has("_states") &&
(!this._personEntityId || !this._states?.[this._personEntityId]))
) {
this._updatePersonEntityId();
}
}
@consumeEntityStates({ entityIdPath: ["_personEntityIds"] })
private _personStates?: Record<string, HassEntity>;
protected render() {
if (!this.user) {
return nothing;
}
const picture =
this._personEntityId &&
(this._personState?.attributes.entity_picture as string | undefined);
const userId = this.user.id;
const picture = Object.values(this._personStates ?? {}).find(
(entity) => entity.attributes.user_id === userId
)?.attributes.entity_picture as string | undefined;
if (picture && this._connection) {
return html`<div
@@ -70,22 +61,6 @@ class UserBadge extends LitElement {
</div>`;
}
private _updatePersonEntityId() {
this._personEntityId = undefined;
if (!this.user || !this._states) {
return;
}
for (const entity of Object.values(this._states)) {
if (
entity.attributes.user_id === this.user.id &&
computeStateDomain(entity) === "person"
) {
this._personEntityId = entity.entity_id;
return;
}
}
}
static styles = css`
:host {
display: block;
+42
View File
@@ -78,3 +78,45 @@ export const selectCameraStreams = ({
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
};
/** What the player tells the user about the connection of its stream. */
export interface CameraStreamStatus {
/** The stream that is shown, undefined until the camera's types are known */
type?: CameraStreamType;
/** The shown stream has not played its first frame yet */
connecting: boolean;
/** A faster stream that connects in the background to replace the shown one */
upgrading?: CameraStreamType;
/** The shown stream has sound */
hasAudio: boolean;
/** The app plays the shown stream in its own player, over the page */
inApp?: boolean;
}
export const computeCameraStreamStatus = (
streams: CameraStream[],
loaded: ReadonlySet<CameraStreamType>,
hlsStreams?: CameraStreamTracks,
webRtcStreams?: CameraStreamTracks
): CameraStreamStatus => {
const visible = streams.find((stream) => stream.visible);
if (!visible) {
return { connecting: true, hasAudio: false };
}
const hidden = streams.find((stream) => !stream.visible);
const tracks =
visible.type === STREAM_TYPE_HLS
? hlsStreams
: visible.type === STREAM_TYPE_WEB_RTC
? webRtcStreams
: undefined;
const connecting = !loaded.has(visible.type);
return {
type: visible.type,
connecting,
// Only worth mentioning once the shown stream plays, before that the
// whole player is connecting
upgrading: hidden && !connecting ? hidden.type : undefined,
hasAudio: !connecting && (tracks?.hasAudio ?? false),
};
};
+23
View File
@@ -179,3 +179,26 @@ export const isRelatedItemsFilterUsed = (
(key === filterName || filterName.includes(key)) && filter.items;
return isUsed;
};
/**
* Whether an item with nothing assigned (no area, device, label, category or
* assistant) passes the filters: only a "No area" selection keeps it, any
* selected id leaves it out.
*/
export const filtersMatchUnassignedItem = (
filters: DataTableFiltersValues
): boolean =>
Object.values(filters).every((value) => {
if (!value) {
return true;
}
if (Array.isArray(value)) {
return !value.length;
}
if ((value as FloorAreasFilterValue).no_area) {
return true;
}
return Object.values(value).every(
(selected) => !Array.isArray(selected) || !selected.length
);
});
+2 -73
View File
@@ -9,7 +9,6 @@ import {
consumeContext,
ContextController,
} from "../common/decorators/consume";
import { SkeletonLoadingController } from "../components/skeleton/skeleton-loading-controller";
import {
apiContext,
configContext,
@@ -20,7 +19,7 @@ import {
uiContext,
} from "./context";
import type { EnergyCollection, EnergyData } from "./energy";
import { getEnergyDataCollection, hasCombinableEnergySources } from "./energy";
import { getEnergyDataCollection } from "./energy";
import type { FrontendLocaleData } from "./translation";
import type { HomeAssistant } from "../types";
@@ -29,9 +28,6 @@ export interface EnergyCollectionControllerOptions {
config: () => { collection_key?: string } | undefined;
beforeSubscribe?: (collection: EnergyCollection) => void;
onData: (data: EnergyData) => void;
/** Whether the host still loads once the data came, such as while it
fetches more for it. The host shows a skeleton until it's done. */
loading?: () => boolean;
}
/**
@@ -91,73 +87,18 @@ export class EnergyCollectionController extends ContextController {
private _collection?: EnergyCollection;
/* Whether data has come since subscribing, so the host can show a
skeleton until it does */
private _hasData = false;
private _placeholderData?: EnergyData;
constructor(
host: ReactiveControllerHost & HTMLElement,
options: EnergyCollectionControllerOptions
) {
super(host);
this._options = options;
new SkeletonLoadingController(
host,
() =>
this._unsub !== undefined &&
(!this._hasData || this._options.loading?.() === true)
);
}
get collection(): EnergyCollection | undefined {
return this._collection;
}
/**
* The data the host is about to get, without its statistics, once the
* collection knows the energy preferences. A host can draw its real layout
* from it under its skeleton, so the skeleton has the size of what comes.
* The energy dashboard builds its cards from the preferences, so they are
* known there before the first card renders.
*/
get placeholderData(): EnergyData | undefined {
const collection = this._collection;
const prefs = collection?.prefs;
if (!collection || !prefs || this._hasData) {
return undefined;
}
// The same object each time, so hosts don't redraw for nothing
const cached = this._placeholderData;
if (
cached?.prefs === prefs &&
cached.start === collection.start &&
cached.end === collection.end
) {
return cached;
}
this._placeholderData = {
start: collection.start,
end: collection.end,
prefs,
combineSources: hasCombinableEnergySources(prefs)
? collection.combineSources
: undefined,
info: { cost_sensors: {}, solar_forecast_domains: [] },
stats: {},
statsMetadata: {},
waterUnit: "",
gasUnit: "",
};
return this._placeholderData;
}
hostConnected(): void {
this._connected = true;
this._subscribe();
@@ -201,7 +142,6 @@ export class EnergyCollectionController extends ContextController {
}
this._unsubscribe();
this._key = key;
this._hasData = false;
this._collection = getEnergyDataCollection(this._connection, {
callWS: this._callWS,
entities: this._entities,
@@ -212,18 +152,7 @@ export class EnergyCollectionController extends ContextController {
key,
});
this._options.beforeSubscribe?.(this._collection);
this._unsub = this._collection.subscribe((data) => {
this._hasData = true;
this._options.onData(data);
// So the skeleton goes even if the host keeps nothing new
this.host.requestUpdate();
});
// So the host shows a skeleton until the data comes
if (!this._hasData) {
this.host.requestUpdate();
}
this._unsub = this._collection.subscribe(this._options.onData);
}
private _unsubscribe(): void {
+35 -3
View File
@@ -42,6 +42,7 @@ import type {
StatisticValue,
} from "./recorder";
import {
calculateStatisticSumGrowth,
fetchStatistics,
getDisplayUnit,
getStatisticLabel,
@@ -442,6 +443,38 @@ export interface EnergySourceByType {
export const energySourcesByType = (prefs: EnergyPreferences) =>
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
/** Import cost minus export compensation, or undefined without cost data. */
export const calculateGridNetCost = (
sources: GridSourceTypeEnergyPreference[],
info: EnergyInfo,
stats: Statistics
): number | undefined => {
let total: number | undefined;
const add = (
energyStatId: string | null,
costStatId: string | null,
sign: 1 | -1
) => {
if (!energyStatId) {
return;
}
const statId = costStatId || info.cost_sensors[energyStatId];
if (!statId) {
return;
}
const cost = calculateStatisticSumGrowth(stats[statId]);
if (calculateStatisticSumGrowth(stats[energyStatId]) === null && !cost) {
return;
}
total = (total ?? 0) + sign * (cost ?? 0);
};
for (const source of sources) {
add(source.stat_energy_from, source.stat_cost, 1);
add(source.stat_energy_to, source.stat_compensation, -1);
}
return total;
};
const ENERGY_DEVICE_NAME = [
{ type: "parent_device" },
{ type: "device" },
@@ -632,8 +665,7 @@ export interface EnergyData {
info: EnergyInfo;
stats: Statistics;
statsMetadata: Record<string, StatisticsMetaData>;
// Only while comparing with an earlier period
statsCompare?: Statistics;
statsCompare: Statistics;
co2SignalEntity?: string;
fossilEnergyConsumption?: FossilEnergyConsumption;
fossilEnergyConsumptionCompare?: FossilEnergyConsumption;
@@ -1975,7 +2007,7 @@ const getSummedDataPartial = (
const totalStats: Record<number, number> = {};
let sum = 0;
subStatIds!.forEach((id) => {
const stats = compare ? data.statsCompare?.[id] : data.stats[id];
const stats = compare ? data.statsCompare[id] : data.stats[id];
if (!stats) {
return;
}
+27 -1
View File
@@ -5,7 +5,12 @@ import type {
HassEntityBase,
} from "home-assistant-js-websocket";
import { computeDomain } from "../common/entity/compute_domain";
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import type { HomeAssistant } from "../types";
import type {
EntityRegistryDisplayEntry,
ExtEntityRegistryEntry,
} from "./entity/entity_registry";
interface GroupEntityAttributes extends HassEntityAttributeBase {
entity_id: string[];
@@ -40,6 +45,27 @@ export const computeGroupMemberIds = (
return Array.isArray(ids) ? ids : undefined;
};
export type GroupMemberEntry = EntityRegistryDisplayEntry &
Required<Pick<EntityRegistryDisplayEntry, "platform" | "translation_key">>;
/**
* Registry entries of the members of a group in the domain of the group that
* have translations, or an empty list if it is not a group.
*/
export const computeGroupMemberEntries = (
stateObj: HassEntity,
entities: HomeAssistant["entities"]
): GroupMemberEntry[] => {
const domain = computeStateDomain(stateObj);
return (computeGroupMemberIds(stateObj) ?? [])
.filter((id) => computeDomain(id) === domain)
.map((id) => entities[id] as EntityRegistryDisplayEntry | undefined)
.filter(
(entry): entry is GroupMemberEntry =>
!!entry?.translation_key && !!entry.platform
);
};
/**
* Drops groups that have a member in `entityIds`, at any depth (a hidden
* group in between still counts). A group with no listed member stays, so
-47
View File
@@ -1,6 +1,5 @@
import type {
HassConfig,
HassEntities,
HassEntity,
HassEntityAttributeBase,
MessageBase,
@@ -745,52 +744,6 @@ export const isTimelineEntity = (
!isNumericEntity(domain, currentState, undefined) &&
!LINE_CHART_DOMAINS.includes(domain);
export interface ExpectedHistoryCharts {
lines: number;
timelineRows: number;
}
/* How many line charts and timeline rows `computeHistory` will draw these
entities' history in, guessed from their current states, so their space
can be held while it loads */
export const expectedHistoryCharts = (
entityIds: string[],
states: HassEntities,
temperatureUnit: string,
splitDeviceClasses = false
): ExpectedHistoryCharts => {
const lineGroups = new Set<string | undefined>();
let timelineRows = 0;
entityIds.forEach((entityId) => {
const domain = computeDomain(entityId);
const stateObj: HassEntity | undefined = states[entityId];
if (isTimelineEntity(domain, stateObj)) {
timelineRows++;
return;
}
const unit = isNumericEntity(domain, stateObj, undefined)
? stateObj?.attributes.unit_of_measurement || BLANK_UNIT
: ({
climate: temperatureUnit,
humidifier: "%",
water_heater: temperatureUnit,
}[domain] ?? domain);
const deviceClass =
SPECIAL_DOMAIN_CLASSES[domain] || stateObj?.attributes.device_class;
lineGroups.add(computeGroupKey(unit, deviceClass, splitDeviceClasses));
});
return { lines: lineGroups.size, timelineRows };
};
export const mergeHistoryResults = (
historyResult: HistoryResult,
ltsResult?: HistoryResult,
+33
View File
@@ -75,6 +75,7 @@ import type {
import { mdiHomeAssistant } from "../resources/home-assistant-logo-svg";
import { callWS } from "../util/websocket";
import { getConditionDomain, getConditionObjectId } from "./condition";
import { computeGroupMemberEntries } from "./group";
import { getTriggerDomain, getTriggerObjectId } from "./trigger";
/** Icon to use when no icon specified for service. */
@@ -576,6 +577,38 @@ export const attributeIcon = async (
);
}
}
// A group has no icons for the values of its members, for example the
// effects of a light group, so use the icon of a member for that value.
if (!icon && value !== undefined) {
for (const member of computeGroupMemberEntries(state, entities)) {
let memberIcons: PlatformIcons | undefined;
try {
// eslint-disable-next-line no-await-in-loop
memberIcons = await getPlatformIcons(
hassConfig,
hassConnection,
member.platform
);
} catch {
// The icons of a member are optional, so try the other fallbacks
continue;
}
const memberTranslations =
memberIcons?.[domain]?.[member.translation_key]?.state_attributes?.[
attribute
];
// The default icon of a member is not an icon for this value
icon =
memberTranslations &&
getIconFromTranslations(value, {
...memberTranslations,
default: undefined,
});
if (icon) {
break;
}
}
}
if (!icon) {
const entityComponentIcons = await getComponentIcons(
hassConnection,
+5
View File
@@ -11,6 +11,7 @@ import {
import type { LocalizeKeys } from "../common/translations/localize";
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
import type { HomeAssistant, PanelInfo } from "../types";
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
export const APP_PANEL = "app";
export const HOME_PANEL = "home";
@@ -68,6 +69,10 @@ export const getPanelTitle = (
hass: Pick<HomeAssistant, "localize">,
panel: PanelInfo
): string | undefined => {
if (panel.url_path === "marketplace") {
return MARKETPLACE_NAME;
}
const translationKey = getPanelNameTranslationKey(panel);
return hass.localize(translationKey) || panel.title || undefined;
+2 -7
View File
@@ -18,11 +18,7 @@ import type { FuseWeightedKey } from "../resources/fuseMultiTerm";
import type { HomeAssistant } from "../types";
import type { HassioAddonInfo } from "./hassio/addon";
import { domainToName } from "./integration";
import {
getPanelIcon,
getPanelNameTranslationKey,
SYSTEM_PANELS,
} from "./panel";
import { getPanelIcon, getPanelTitle, SYSTEM_PANELS } from "./panel";
export interface NavigationComboBoxItem extends PickerComboBoxItem {
path: string;
@@ -59,10 +55,9 @@ const generateNavigationPanelCommands = (
Object.entries(panels)
.filter(([panelKey]) => !SYSTEM_PANELS.includes(panelKey))
.map(([_panelKey, panel]) => {
const translationKey = getPanelNameTranslationKey(panel);
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
const primary = localize(translationKey) || panel.title || panel.url_path;
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
+51
View File
@@ -50,3 +50,54 @@ export const subscribeThemes = (
conn,
onChange
);
/** `none`: the theme has no modes and fixed colors, applied on the light base. */
export type ThemeModeSupport = "both" | "light" | "dark" | "none";
export const getThemeModeSupport = (theme: Theme): ThemeModeSupport => {
const modes = theme.modes;
const hasLight = !!modes && "light" in modes;
const hasDark = !!modes && "dark" in modes;
if (hasLight && hasDark) {
return "both";
}
if (hasDark) {
return "dark";
}
if (hasLight) {
return "light";
}
return "none";
};
export const getThemeVariables = (
theme: Theme,
darkMode: boolean
): Partial<ThemeVars> => {
const { modes, ...baseVariables } = theme;
return {
...baseVariables,
...(darkMode ? modes?.dark : modes?.light),
};
};
/** Setting any primary palette key counts as setting the primary color. */
export const themeDefinesColor = (
themeVariables: Partial<ThemeVars>,
color: "primary" | "accent"
): boolean => {
if (color === "accent") {
return "accent-color" in themeVariables;
}
return (
"primary-color" in themeVariables ||
themeDefinesPrimaryPalette(themeVariables)
);
};
export const themeDefinesPrimaryPalette = (
themeVariables: Partial<ThemeVars>
): boolean =>
Object.keys(themeVariables).some((key) =>
key.startsWith("ha-color-primary-")
);
@@ -0,0 +1,203 @@
import {
mdiFilmstrip,
mdiImageMultipleOutline,
mdiLightningBolt,
} from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import { CAMERA_STREAM_TYPE_NAMES } from "../../components/camera/ha-camera-stream-badge";
import "../../components/ha-adaptive-dialog";
import "../../components/ha-alert";
import "../../components/ha-expansion-panel";
import "../../components/ha-svg-icon";
import "../../components/item/ha-list-item-base";
import "../../components/list/ha-list-base";
import {
MJPEG_STREAM,
STREAM_TYPE_HLS,
STREAM_TYPE_WEB_RTC,
type CameraStreamType,
type StreamType,
} from "../../data/camera-streams";
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
// Ordered from the fastest to the most compatible
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
{ type: STREAM_TYPE_WEB_RTC, icon: mdiLightningBolt },
{ type: STREAM_TYPE_HLS, icon: mdiFilmstrip },
{ type: MJPEG_STREAM, icon: mdiImageMultipleOutline },
];
@customElement("dialog-camera-stream-info")
class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
LitElement
) {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
protected render() {
if (!this.params) {
return nothing;
}
const { status, supportedTypes } = this.params;
// Without a video stream, still images are all the camera has
const stillImagesOnly = supportedTypes?.length === 0;
// MJPEG is only the fallback, only worth explaining while it shows
const mjpegInUse = status.type === MJPEG_STREAM;
const videoTypes = STREAM_TYPES.filter(({ type }) => type !== MJPEG_STREAM);
const isSupported = (type: CameraStreamType) =>
!supportedTypes || supportedTypes.includes(type as StreamType);
const supported = stillImagesOnly
? []
: videoTypes.filter(({ type }) => isSupported(type));
const unsupported = stillImagesOnly
? []
: videoTypes.filter(({ type }) => !isSupported(type));
const mjpeg = STREAM_TYPES.find(({ type }) => type === MJPEG_STREAM)!;
return html`
<ha-adaptive-dialog
open
width="medium"
.headerTitle=${this._localize("ui.dialogs.camera_stream_info.title")}
>
<p>
${this._localize(
stillImagesOnly
? "ui.dialogs.camera_stream_info.still_images_only"
: "ui.dialogs.camera_stream_info.intro"
)}
</p>
${
mjpegInUse && !stillImagesOnly
? html`<ha-alert alert-type="info">
${this._localize("ui.dialogs.camera_stream_info.fallback_in_use")}
</ha-alert>`
: nothing
}
<ha-list-base>
${mjpegInUse ? this._renderType(mjpeg) : nothing}
${supported.map((item) => this._renderType(item))}
</ha-list-base>
${
unsupported.length
? html`
<ha-expansion-panel
outlined
.header=${this._localize(
"ui.dialogs.camera_stream_info.not_supported_count",
{ count: unsupported.length }
)}
>
<ha-list-base>
${unsupported.map((item) => this._renderType(item))}
</ha-list-base>
</ha-expansion-panel>
`
: nothing
}
</ha-adaptive-dialog>
`;
}
private _renderType({
type,
icon,
}: {
type: CameraStreamType;
icon: string;
}) {
const { status } = this.params!;
const current = !status.connecting && status.type === type;
const upgrading = status.upgrading === type;
return html`
<ha-list-item-base
.headline=${CAMERA_STREAM_TYPE_NAMES[type]}
.supportingText=${this._localize(
`ui.dialogs.camera_stream_info.description.${type}`
)}
wrap-supporting-text
>
<ha-svg-icon slot="start" .path=${icon}></ha-svg-icon>
${
current
? html`<span slot="end" class="tag current"
>${this._localize("ui.dialogs.camera_stream_info.in_use")}</span
>`
: upgrading
? html`<span slot="end" class="tag"
>${this._localize(
"ui.dialogs.camera_stream_info.connecting"
)}</span
>`
: nothing
}
</ha-list-item-base>
`;
}
static styles = [
haStyleDialog,
// At the top like the more info dialog it opens from
haStyleDialogFixedTop,
css`
p {
margin: 0;
color: var(--secondary-text-color);
}
ha-alert {
display: block;
margin-top: var(--ha-space-4);
}
ha-list-base {
margin-top: var(--ha-space-2);
}
ha-list-item-base {
--ha-row-item-padding-inline: 0;
}
ha-expansion-panel {
display: block;
margin-top: var(--ha-space-6);
--expansion-panel-summary-padding: 0 var(--ha-space-4);
--expansion-panel-content-padding: 0 var(--ha-space-4);
}
ha-list-item-base ha-svg-icon {
flex: none;
padding: var(--ha-space-2);
border-radius: var(--ha-border-radius-circle);
background-color: var(--ha-color-fill-neutral-quiet-resting);
color: var(--primary-text-color);
}
.tag {
font-size: var(--ha-font-size-xs);
font-weight: var(--ha-font-weight-medium);
padding: 2px var(--ha-space-2);
border-radius: var(--ha-border-radius-pill);
background-color: var(--ha-color-fill-neutral-quiet-resting);
color: var(--secondary-text-color);
}
.tag.current {
background-color: var(--ha-color-fill-success-quiet-resting);
color: var(--ha-color-on-success-quiet);
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"dialog-camera-stream-info": DialogCameraStreamInfo;
}
}
@@ -0,0 +1,18 @@
import { fireEvent } from "../../common/dom/fire_event";
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
export interface CameraStreamInfoDialogParams {
status: CameraStreamStatus;
/** The stream types the camera supports, undefined while unknown */
supportedTypes?: StreamType[];
}
export const showCameraStreamInfoDialog = (
element: HTMLElement,
params: CameraStreamInfoDialogParams
) =>
fireEvent(element, "show-dialog", {
dialogTag: "dialog-camera-stream-info",
dialogImport: () => import("./dialog-camera-stream-info"),
dialogParams: params,
});
@@ -1,13 +1,8 @@
import "../../../../components/skeleton/ha-skeleton";
import "../../../../components/skeleton/ha-skeleton-text";
import type { HassConfig } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import {
fadeInArrival,
skeletonOr,
} from "../../../../components/skeleton/skeleton-arrival";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import { isComponentLoaded } from "../../../../common/config/is_component_loaded";
import { relativeTime } from "../../../../common/datetime/relative_time";
@@ -70,8 +65,6 @@ export class HaMoreInfoUpdateBackup extends LitElement {
@state() private _entitySources?: EntitySources;
@query("ha-row-item") private _rowItem?: HTMLElement;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@@ -98,19 +91,6 @@ export class HaMoreInfoUpdateBackup extends LitElement {
this._setupBackup();
}
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
// The row's text takes its skeleton's place
if (
changedProps.get("_backupConfigLoading") === true &&
!this._backupConfigLoading &&
this._rowItem
) {
fadeInArrival(this._rowItem);
}
}
protected render() {
if (
!this.stateObj ||
@@ -139,20 +119,19 @@ export class HaMoreInfoUpdateBackup extends LitElement {
></ha-fade-in>`
: nothing
}
${skeletonOr(
this._createBackupLoading,
html`<ha-fade-in class="skeleton-end" slot="end" .delay=${500}
><ha-skeleton></ha-skeleton
></ha-fade-in>`,
() =>
html`<ha-switch
slot="end"
.accessibleLabel=${createBackupTexts?.title ?? ""}
.checked=${this._createBackup}
@change=${this._createBackupChanged}
.disabled=${this.disabled || updateIsInstalling(this.stateObj!)}
></ha-switch>`
)}
${
this._createBackupLoading
? html`<ha-fade-in class="skeleton-end" slot="end" .delay=${500}
><ha-skeleton></ha-skeleton
></ha-fade-in>`
: html`<ha-switch
slot="end"
.accessibleLabel=${createBackupTexts?.title ?? ""}
.checked=${this._createBackup}
@change=${this._createBackupChanged}
.disabled=${this.disabled || updateIsInstalling(this.stateObj)}
></ha-switch>`
}
</ha-row-item>
`;
}
@@ -9,11 +9,9 @@ import { consumeLocalize } from "../../../common/decorators/consume-context-entr
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import "../../../components/ha-camera-stream";
import type {
CameraStreamType,
HaCameraStream,
} from "../../../components/ha-camera-stream";
import "../../../components/camera/ha-camera-player";
import type { HaCameraPlayer } from "../../../components/camera/ha-camera-player";
import type { CameraStreamType } from "../../../components/ha-camera-stream";
import "../../../components/ha-spinner";
import "../../../components/ha-svg-icon";
import "../../../components/ha-tooltip";
@@ -54,7 +52,7 @@ class MoreInfoCamera extends LitElement {
@state() private _supportsTwoWayAudio = false;
@query("ha-camera-stream") private _cameraStream?: HaCameraStream;
@query("ha-camera-player") private _cameraStream?: HaCameraPlayer;
@query(".microphone-meter") private _microphoneMeter?: HTMLElement;
@@ -122,14 +120,14 @@ class MoreInfoCamera extends LitElement {
}
return html`
<ha-camera-stream
<ha-camera-player
.stateObj=${this.stateObj}
allow-exoplayer
controls
keep-awake
@microphone-changed=${this._microphoneChanged}
@stream-type-changed=${this._streamTypeChanged}
@camera-capabilities-changed=${this._capabilitiesChanged}
></ha-camera-stream>
></ha-camera-player>
${this._supportsTwoWayAudio ? this._renderMicrophoneButton() : nothing}
`;
}
+8 -1
View File
@@ -4,6 +4,7 @@ import { html } from "lit";
import { customElement, state } from "lit/decorators";
import { storage } from "../common/decorators/storage";
import { isNavigationClick } from "../common/dom/is-navigation-click";
import { whenDocumentVisible } from "../common/dom/when-document-visible";
import { handleHistoryPop, navigate } from "../common/navigate";
import type { LocalizeFunc } from "../common/translations/localize";
import { decodeMoreInfoUrl } from "../common/url/more-info-query-params";
@@ -78,6 +79,8 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
private _visiblePromiseResolve?: () => void;
private _cancelVisibilityRecovery?: () => void;
constructor() {
super();
const path = redirectLegacyToolsPath(curPath());
@@ -426,7 +429,9 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
}
}, 300000);
}
window.addEventListener("focus", () => this._onVisible(), { once: true });
this._cancelVisibilityRecovery = whenDocumentVisible(() =>
this._onVisible()
);
}
private _suspendApp() {
@@ -438,6 +443,8 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
}
private _onVisible() {
this._cancelVisibilityRecovery?.();
this._cancelVisibilityRecovery = undefined;
// Clear timer to close the connection
if (this._hiddenTimeout) {
clearTimeout(this._hiddenTimeout);
+31 -7
View File
@@ -75,13 +75,37 @@ export class ChildPanelReady implements ReactiveController {
export class PanelReady {
public ready?: Promise<void>;
private _resolveReady?: () => void;
public track(element: HTMLElement, waitForReady = false) {
this.ready = waitForReady
? new Promise((resolve) => {
element.addEventListener("hass-panel-ready", () => resolve(), {
once: true,
});
})
: undefined;
// A panel replaced before it was ready, such as a dashboard that redirects
// to another, would never get there. Whoever waits on it waits for the
// panel that took its place instead.
const resolveReplaced = this._resolveReady;
this._resolveReady = undefined;
if (!waitForReady) {
this.ready = undefined;
resolveReplaced?.();
return;
}
this.ready = new Promise((resolve) => {
this._resolveReady = resolve;
element.addEventListener(
"hass-panel-ready",
() => {
if (this._resolveReady === resolve) {
resolve();
}
},
{ once: true }
);
});
if (resolveReplaced) {
void this.ready.then(resolveReplaced);
}
}
}
+1 -6
View File
@@ -6,7 +6,6 @@ import { consume } from "../common/decorators/consume";
import "../components/ha-card";
import "../components/ha-ripple";
import "../components/ha-svg-icon";
import { skeletonOr } from "../components/skeleton/skeleton-arrival";
import { translationsReadyContext } from "../mixins/lit-localize-lite-mixin";
import { renderSkeleton, skeletonStyles } from "./render-skeleton";
@@ -30,11 +29,7 @@ class OnboardingWelcomeLink extends LitElement {
@keydown=${this._handleKeyDown}
>
<ha-svg-icon .path=${this.iconPath}></ha-svg-icon>
${skeletonOr(
this._translationsReady === false,
renderSkeleton("label"),
() => this.label
)}
${this._translationsReady === false ? renderSkeleton("label") : this.label}
<ha-ripple></ha-ripple>
</ha-card>
`;
+42 -31
View File
@@ -10,7 +10,6 @@ import "../components/ha-button";
import "../components/ha-icon-next";
import "../components/item/ha-list-item-button";
import "../components/list/ha-list-base";
import { skeletonOr } from "../components/skeleton/skeleton-arrival";
import { translationsReadyContext } from "../mixins/lit-localize-lite-mixin";
import { renderSkeleton, skeletonStyles } from "./render-skeleton";
import { onBoardingStyles } from "./styles";
@@ -29,29 +28,37 @@ class OnboardingWelcome extends LitElement {
const ready = this._translationsReady;
return html`
<h1>
${skeletonOr(!ready, renderSkeleton("title"), () =>
this._localize("ui.panel.page-onboarding.welcome.header")
)}
${
ready
? this._localize("ui.panel.page-onboarding.welcome.header")
: renderSkeleton("title")
}
</h1>
<p>
${skeletonOr(!ready, renderSkeleton("line"), () =>
this._localize("ui.panel.page-onboarding.intro")
)}
${
ready
? this._localize("ui.panel.page-onboarding.intro")
: renderSkeleton("line")
}
</p>
<ha-button @click=${this._start} class="start" .disabled=${!ready}>
${skeletonOr(!ready, renderSkeleton("button"), () =>
this._localize("ui.panel.page-onboarding.welcome.start")
)}
${
ready
? this._localize("ui.panel.page-onboarding.welcome.start")
: renderSkeleton("button")
}
</ha-button>
<div class="divider">
<wa-divider></wa-divider>
<div>
<span>
${skeletonOr(!ready, renderSkeleton("chip"), () =>
this._localize("ui.panel.page-onboarding.welcome.or_restore")
)}
${
ready
? this._localize("ui.panel.page-onboarding.welcome.or_restore")
: renderSkeleton("chip")
}
</span>
</div>
</div>
@@ -62,16 +69,22 @@ class OnboardingWelcome extends LitElement {
.disabled=${!ready}
>
<div slot="headline">
${skeletonOr(!ready, renderSkeleton("headline"), () =>
this._localize("ui.panel.page-onboarding.restore.upload_backup")
)}
${
ready
? this._localize(
"ui.panel.page-onboarding.restore.upload_backup"
)
: renderSkeleton("headline")
}
</div>
<div slot="supporting-text">
${skeletonOr(!ready, renderSkeleton("line"), () =>
this._localize(
"ui.panel.page-onboarding.restore.options.upload_description"
)
)}
${
ready
? this._localize(
"ui.panel.page-onboarding.restore.options.upload_description"
)
: renderSkeleton("line")
}
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
@@ -80,18 +93,16 @@ class OnboardingWelcome extends LitElement {
.disabled=${!ready}
>
<div slot="headline">
${skeletonOr(
!ready,
renderSkeleton("headline"),
() => "Home Assistant Link"
)}
${ready ? "Home Assistant Link" : renderSkeleton("headline")}
</div>
<div slot="supporting-text">
${skeletonOr(!ready, renderSkeleton("line"), () =>
this._localize(
"ui.panel.page-onboarding.restore.ha-cloud.description"
)
)}
${
ready
? this._localize(
"ui.panel.page-onboarding.restore.ha-cloud.description"
)
: renderSkeleton("line")
}
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
@@ -14,7 +14,6 @@ import {
state,
} from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
@@ -28,7 +27,6 @@ import "../../../../components/item/ha-list-item-button";
import "../../../../components/list/ha-list-base";
import "../../../../components/skeleton/ha-skeleton";
import "../../../../components/skeleton/ha-skeleton-text";
import { skeletonOr } from "../../../../components/skeleton/skeleton-arrival";
import type { ConfigEntry } from "../../../../data/config_entries";
import {
configEntriesContext,
@@ -137,39 +135,39 @@ export class HaAutomationAddItems extends LitElement {
})}
@scroll=${this._onItemsScroll}
>
${skeletonOr(
Boolean(this.loadingLabel),
html`<ha-fade-in .duration=${300} easing="ease-in">
<div
class="skeletons"
role="progressbar"
aria-label=${ifDefined(this.loadingLabel)}
>
<ha-skeleton-text></ha-skeleton-text>
<ha-skeleton></ha-skeleton>
<ha-skeleton></ha-skeleton>
<ha-skeleton></ha-skeleton>
</div>
</ha-fade-in>`,
() =>
!this.items && !this.error
${
this.loadingLabel
? html`<ha-fade-in .duration=${300} easing="ease-in">
<div
class="skeletons"
role="progressbar"
aria-label=${this.loadingLabel}
>
<ha-skeleton-text></ha-skeleton-text>
<ha-skeleton></ha-skeleton>
<ha-skeleton></ha-skeleton>
<ha-skeleton></ha-skeleton>
</div>
</ha-fade-in>`
: !this.items && !this.error
? this.selectLabel
: this.error
? html`<span>${this.error}</span>
? html`${this.error}
<div>${this._renderCurrentTarget()}</div>`
: this.items && !this.items.length
? html`<span>${this.emptyLabel}</span> ${
this.target
? html`<div>${this._renderCurrentTarget()}</div>`
: nothing
}`
? html`${this.emptyLabel}
${
this.target
? html`<div>${this._renderCurrentTarget()}</div>`
: nothing
}`
: repeat(
this.items,
(_, index) => `item-group-${index}`,
(itemGroup) =>
this._renderItemList(itemGroup.title, itemGroup.items)
)
)}
}
</div>
<slot></slot>`;
}
@@ -16,8 +16,6 @@ import "../../../../../components/ha-icon-button";
import "../../../../../components/ha-svg-icon";
import "../../../../../components/item/ha-list-item-base";
import "../../../../../components/list/ha-list-base";
import "../../../../../components/skeleton/ha-skeleton-text";
import { skeletonOr } from "../../../../../components/skeleton/skeleton-arrival";
import type { BackupConfig, BackupContent } from "../../../../../data/backup";
import {
BACKUP_OVERDUE_MARGIN_HOURS,
@@ -69,11 +67,9 @@ class HaBackupOverviewBackups extends LitElement {
<ha-list-base>
<ha-list-item-base wrap-headline>
<ha-svg-icon slot="start" .path=${mdiBackupRestore}></ha-svg-icon>
${skeletonOr(
headline === null,
html`<ha-skeleton-text slot="headline"></ha-skeleton-text>`,
() => html`<span slot="headline">${headline}</span>`
)}
<span slot="headline" class=${headline === null ? "skeleton" : ""}
>${headline}</span
>
</ha-list-item-base>
${
description || description === null
@@ -83,13 +79,12 @@ class HaBackupOverviewBackups extends LitElement {
slot="start"
.path=${mdiCalendar}
></ha-svg-icon>
${skeletonOr(
description === null,
html`<ha-skeleton-text
slot="headline"
></ha-skeleton-text>`,
() => html`<span slot="headline">${description}</span>`
)}
<span
slot="headline"
class=${description === null ? "skeleton" : ""}
>${description}</span
>
${
lastCompletedDate
? html`
@@ -375,8 +370,34 @@ class HaBackupOverviewBackups extends LitElement {
ha-list-item-base::part(start) {
color: var(--ha-color-text-secondary);
}
ha-skeleton-text {
--ha-skeleton-text-width: 160px;
span.skeleton {
position: relative;
display: block;
width: 160px;
animation-fill-mode: forwards;
animation-iteration-count: infinite;
animation-name: loading;
animation-timing-function: linear;
animation-duration: 1.2s;
border-radius: var(--ha-border-radius-sm);
height: 16px;
margin: 2px 0;
background: linear-gradient(
to right,
var(--card-background-color) 8%,
var(--secondary-background-color) 18%,
var(--card-background-color) 33%
)
0% 0% / 936px 104px;
}
@keyframes loading {
0% {
background-position: -468px 0;
}
100% {
background-position: 468px 0;
}
}
`,
];
+2
View File
@@ -42,6 +42,7 @@ import {
} from "@mdi/js";
import memoizeOne from "memoize-one";
import { haLora } from "../../resources/ha-icons";
import { MARKETPLACE_NAME } from "../../common/translations/name-placeholders";
import type { PageNavigation } from "../../layouts/hass-tabs-subpage";
import type { HomeAssistant } from "../../types";
import { mdiMqttLogo } from "../../resources/mqtt-logo-svg";
@@ -92,6 +93,7 @@ export const configSections: Record<string, PageNavigation[]> = {
},
{
path: "/marketplace",
name: MARKETPLACE_NAME,
translationKey: "marketplace",
iconPath: mdiStore,
iconColor: "#7C4DFF",
@@ -59,7 +59,6 @@ import "../../../components/ha-filter-states";
import "../../../components/ha-icon-button";
import "../../../components/skeleton/ha-skeleton-icon";
import "../../../components/skeleton/ha-skeleton-text";
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
import { createAreaRegistryEntry } from "../../../data/area/area_registry";
import type { ConfigEntry, SubEntry } from "../../../data/config_entries";
import { getSubEntries, sortConfigEntries } from "../../../data/config_entries";
@@ -548,26 +547,23 @@ export class HaConfigDeviceDashboard extends LitElement {
moveable: false,
showNarrow: true,
template: (device) =>
skeletonOr(
!this.entries,
html`<ha-skeleton-icon></ha-skeleton-icon>`,
() =>
device.domains.length
? html`<img
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: device.domains[0],
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>`
: ""
),
!this.entries
? html`<ha-skeleton-icon></ha-skeleton-icon>`
: device.domains.length
? html`<img
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: device.domains[0],
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>`
: "",
},
name: {
title: localize("ui.panel.config.devices.data_table.device"),
@@ -589,20 +585,17 @@ export class HaConfigDeviceDashboard extends LitElement {
</div>`
: nothing
}
${skeletonOr(
!device.label_entries.length &&
device.labels.length > 0 &&
!this._labels,
html`<ha-skeleton-text></ha-skeleton-text>`,
() =>
device.label_entries.length
? html`
<ha-data-table-labels
.labels=${device.label_entries}
></ha-data-table-labels>
`
${
device.label_entries.length
? html`
<ha-data-table-labels
.labels=${device.label_entries}
></ha-data-table-labels>
`
: device.labels.length && !this._labels
? html`<ha-skeleton-text></ha-skeleton-text>`
: nothing
)}
}
`,
},
area: getAreaTableColumn(localize),
@@ -615,11 +608,9 @@ export class HaConfigDeviceDashboard extends LitElement {
urlName: "integration",
minWidth: "120px",
template: (device) =>
skeletonOr(
!this.entries,
html`<ha-skeleton-text></ha-skeleton-text>`,
() => device.integration
),
!this.entries
? html`<ha-skeleton-text></ha-skeleton-text>`
: device.integration,
},
device_family_name: {
title: localize("ui.panel.config.devices.data_table.parent_device"),
@@ -673,46 +664,38 @@ export class HaConfigDeviceDashboard extends LitElement {
maxWidth: "101px",
minWidth: "101px",
valueColumn: "battery_level",
template: (device) =>
skeletonOr(
!this.entities,
html`<ha-skeleton-text></ha-skeleton-text>`,
() => {
const batteryEntityPair = device.battery_entity;
template: (device) => {
if (!this.entities) {
return html`<ha-skeleton-text></ha-skeleton-text>`;
}
const batteryEntityPair = device.battery_entity;
const battery =
batteryEntityPair && batteryEntityPair[0]
? this.hass.states[batteryEntityPair[0]]
: undefined;
const batteryDomain = battery
? computeStateDomain(battery)
: undefined;
const batteryCharging =
batteryEntityPair && batteryEntityPair[1]
? this.hass.states[batteryEntityPair[1]]
: undefined;
const battery =
batteryEntityPair && batteryEntityPair[0]
? this.hass.states[batteryEntityPair[0]]
: undefined;
const batteryDomain = battery
? computeStateDomain(battery)
: undefined;
const batteryCharging =
batteryEntityPair && batteryEntityPair[1]
? this.hass.states[batteryEntityPair[1]]
: undefined;
return battery &&
(batteryDomain === "binary_sensor" ||
!isNaN(Number(battery.state)))
? html`
${
batteryDomain === "sensor"
? html`<span
>${this.hass.formatEntityState(battery)}</span
>`
: nothing
}
<ha-battery-icon
.batteryStateObj=${battery}
.batteryChargingStateObj=${batteryCharging}
></ha-battery-icon>
`
: "—";
}
),
return battery &&
(batteryDomain === "binary_sensor" || !isNaN(battery.state as any))
? html`
${
batteryDomain === "sensor"
? this.hass.formatEntityState(battery)
: nothing
}
<ha-battery-icon
.batteryStateObj=${battery}
.batteryChargingStateObj=${batteryCharging}
></ha-battery-icon>
`
: "—";
},
},
created_at: getCreatedAtTableColumn(localize, this.hass),
modified_at: getModifiedAtTableColumn(localize, this.hass),
@@ -897,15 +880,15 @@ export class HaConfigDeviceDashboard extends LitElement {
${this.hass.localize(
"ui.panel.config.devices.filtering_by_config_entry"
)}
${skeletonOr(
!this.entries,
html`<ha-skeleton-text></ha-skeleton-text>`,
() =>
this.entries?.find(
(entry) =>
entry.entry_id === this._filters.config_entry!.value![0]
)?.title || this._filters.config_entry!.value![0]
)}${
${
!this.entries
? html`<ha-skeleton-text></ha-skeleton-text>`
: this.entries.find(
(entry) =>
entry.entry_id ===
this._filters.config_entry!.value![0]
)?.title || this._filters.config_entry.value[0]
}${
this._filters.config_entry.value.length === 1 &&
Array.isArray(this._filters.sub_entry?.value) &&
this._filters.sub_entry.value.length
+14 -7
View File
@@ -85,6 +85,7 @@ import type {
DataTableFiltersValue,
DataTableFiltersValues,
} from "../../../data/data_table_filters";
import { filtersMatchUnassignedItem } from "../../../data/data_table_filters";
import {
fetchDiagnosticHandlers,
getConfigEntryDiagnosticsDownloadUrl,
@@ -540,7 +541,8 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
entityReg: EntityRegistryEntry[],
categoryReg?: CategoryRegistryEntry[],
labelReg?: LabelRegistryEntry[],
filteredStateItems?: string[] | null
filteredStateItems?: string[] | null,
includeUnassigned = true
): HelperItem[] => {
if (filteredStateItems === null) {
return [];
@@ -613,11 +615,15 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
}));
return [...states, ...entries, ...disabledItems]
.filter((item) =>
filteredStateItems
? filteredStateItems?.includes(item.entity_id)
: true
)
.filter((item) => {
if (!filteredStateItems) {
return true;
}
// A config entry that has no entity yet has nothing assigned
return item.entity_id
? filteredStateItems.includes(item.entity_id)
: includeUnassigned;
})
.map((item) => {
const entityRegEntry =
entityRegistryByEntityId(entityReg)[item.entity_id];
@@ -688,7 +694,8 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
this._entityReg,
this._categories,
this._labels,
this._filteredHelperEntityIds
this._filteredHelperEntityIds,
filtersMatchUnassignedItem(this._filters)
);
return html`
<hass-tabs-subpage-data-table
@@ -3,7 +3,7 @@ import {
ERR_CONNECTION_LOST,
type UnsubscribeFunc,
} from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues } from "lit";
import type { CSSResultGroup } from "lit";
import { mdiCircle, mdiWrap, mdiWrapDisabled } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, query, state } from "lit/decorators";
@@ -20,10 +20,6 @@ import "../../../components/ha-svg-icon";
import "../../../components/input/ha-input-search";
import type { HaInputSearch } from "../../../components/input/ha-input-search";
import "../../../components/skeleton/ha-skeleton-log";
import {
fadeInArrival,
skeletonOr,
} from "../../../components/skeleton/skeleton-arrival";
import {
connectionContext,
internationalizationContext,
@@ -69,29 +65,6 @@ class DialogLiveLog extends DialogMixin<LiveLogDialogParams>(LitElement) {
private _resubscribeOnReady = false;
// Whether the skeleton showed last render, so the log fades in once its
// first lines take the skeleton's place
private _showedSkeleton = false;
private _linesArriving = false;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
const showSkeleton = !this._lineCount && this._loading;
this._linesArriving =
this._showedSkeleton && !showSkeleton && this._lineCount > 0;
this._showedSkeleton = showSkeleton;
}
protected updated(changedProps: PropertyValues<this>) {
super.updated(changedProps);
if (this._linesArriving && this._logViewer) {
this._linesArriving = false;
fadeInArrival(this._logViewer);
}
}
connectedCallback() {
super.connectedCallback();
const connection = this._connection.connection;
@@ -244,21 +217,18 @@ class DialogLiveLog extends DialogMixin<LiveLogDialogParams>(LitElement) {
${
this._lineCount
? nothing
: skeletonOr(
this._loading,
html`<ha-skeleton-log
: this._loading
? html`<ha-skeleton-log
.label=${this._i18n.localize(
"ui.panel.config.logs.loading_log"
)}
></ha-skeleton-log>`,
() =>
html`<div class="waiting">
${this._i18n.localize(
"ui.panel.config.integrations.config_entry.live_log.waiting",
{ integration: this.params!.name }
)}
</div>`
)
></ha-skeleton-log>`
: html`<div class="waiting">
${this._i18n.localize(
"ui.panel.config.integrations.config_entry.live_log.waiting",
{ integration: this.params.name }
)}
</div>`
}
</ha-log-viewer>
${
@@ -5,7 +5,6 @@ import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
import { consume } from "../../../common/decorators/consume";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { fireEvent } from "../../../common/dom/fire_event";
@@ -191,58 +190,62 @@ class DialogSystemLogDetail extends LitElement {
.label=${this._i18n.localize("ui.panel.config.logs.copy")}
.path=${mdiContentCopy}
></ha-icon-button>
<ha-alert alert-type=${this.isCustomIntegration ? "warning" : "info"}>
${skeletonOr(
Boolean(integration) &&
this._manifest === undefined &&
reportTarget !== "frontend",
html`<ha-skeleton-text></ha-skeleton-text>`,
() => html`
<p>
${this._i18n.localize(
`ui.panel.config.logs.detail.report_issue.${reportMessage}.introduction`,
{
integration:
this._manifest?.name ??
(integration
? domainToName(this._i18n.localize, integration)
: new URL(reportUrl).hostname),
}
)}
</p>
<p>
${this._i18n.localize(
`ui.panel.config.logs.detail.report_issue.${reportMessage}.report`,
{
report_link: html`<a
href=${reportUrl}
target="_blank"
rel="noopener noreferrer"
>${this._i18n.localize(`ui.panel.config.logs.detail.report_issue.${reportTarget}.link_text`)}</a
>`,
}
)}
</p>
${
reportMessage !== "custom"
? html`<p>
${this._i18n.localize(
`ui.panel.config.logs.detail.report_issue.${reportMessage}.guidance`,
{
guide_link: html`<a
href=${`${DOCUMENTATION_URL}/help/reporting_issues/`}
target="_blank"
rel="noopener noreferrer"
>${this._i18n.localize("ui.panel.config.logs.detail.report_issue.guide_link_text")}</a
>`,
}
)}
</p>`
: nothing
}
`
)}
</ha-alert>
${
integration &&
this._manifest === undefined &&
reportTarget !== "frontend"
? html`<ha-alert
alert-type=${this.isCustomIntegration ? "warning" : "info"}
>
<ha-skeleton-text></ha-skeleton-text>
</ha-alert>`
: html`<ha-alert
alert-type=${this.isCustomIntegration ? "warning" : "info"}
>
<p>
${this._i18n.localize(
`ui.panel.config.logs.detail.report_issue.${reportMessage}.introduction`,
{
integration:
this._manifest?.name ??
(integration
? domainToName(this._i18n.localize, integration)
: new URL(reportUrl).hostname),
}
)}
</p>
<p>
${this._i18n.localize(
`ui.panel.config.logs.detail.report_issue.${reportMessage}.report`,
{
report_link: html`<a
href=${reportUrl}
target="_blank"
rel="noopener noreferrer"
>${this._i18n.localize(`ui.panel.config.logs.detail.report_issue.${reportTarget}.link_text`)}</a
>`,
}
)}
</p>
${
reportMessage !== "custom"
? html`<p>
${this._i18n.localize(
`ui.panel.config.logs.detail.report_issue.${reportMessage}.guidance`,
{
guide_link: html`<a
href=${`${DOCUMENTATION_URL}/help/reporting_issues/`}
target="_blank"
rel="noopener noreferrer"
>${this._i18n.localize("ui.panel.config.logs.detail.report_issue.guide_link_text")}</a
>`,
}
)}
</p>`
: nothing
}
</ha-alert>`
}
<div class="contents">
<p>
${this._i18n.localize("ui.panel.config.logs.detail.logger")}:
+1 -29
View File
@@ -37,10 +37,6 @@ import "../../../components/ha-dropdown-item";
import "../../../components/ha-icon-button";
import "../../../components/ha-svg-icon";
import "../../../components/skeleton/ha-skeleton-log";
import {
fadeInArrival,
skeletonArrivalStyles,
} from "../../../components/skeleton/skeleton-arrival";
import { getSignedPath } from "../../../data/auth";
@@ -163,12 +159,6 @@ class ErrorLogCard extends LitElement {
@state() private _loadingPrevState?: "loading" | "end" | "loaded";
// Whether the skeleton showed last render, so the log fades in once it
// takes the skeleton's place
private _showedSkeleton = false;
private _logArriving = false;
@state() private _noSearchResults = false;
@state() private _numberOfLines?: number;
@@ -369,7 +359,7 @@ class ErrorLogCard extends LitElement {
.label=${localize("ui.panel.config.logs.loading_log")}
></ha-skeleton-log>`
: this._loadingState === "empty"
? html`<div class="arriving">
? html`<div>
${
integrationLog
? localize(
@@ -461,18 +451,6 @@ class ErrorLogCard extends LitElement {
this._boot = 0;
this._loadLogs();
}
// As render decides: lines kept while reconnecting show instead
const showSkeleton =
this._loadingState === "loading" &&
!(
this._ansiToHtmlElement?.hasLines &&
!(this.filter && this._noSearchResults)
);
this._logArriving =
this._showedSkeleton && !showSkeleton && this._loadingState === "loaded";
this._showedSkeleton = showSkeleton;
}
protected firstUpdated(changedProps: PropertyValues<this>) {
@@ -487,11 +465,6 @@ class ErrorLogCard extends LitElement {
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
if (this._logArriving && this._ansiToHtmlElement) {
this._logArriving = false;
fadeInArrival(this._ansiToHtmlElement);
}
if (this._newLogsIndicator && this._scrolledToBottomController.value) {
this._newLogsIndicator = false;
}
@@ -1068,7 +1041,6 @@ class ErrorLogCard extends LitElement {
static styles: CSSResultGroup = css`
${haStyleScrollbar}
${skeletonArrivalStyles}
:host {
direction: var(--direction);
+43 -46
View File
@@ -18,7 +18,6 @@ import "../../../components/ha-icon-button";
import "../../../components/item/ha-list-item-button";
import "../../../components/list/ha-list-base";
import "../../../components/skeleton/ha-skeleton-text";
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
import { getSignedPath } from "../../../data/auth";
import {
getCoreLogFileDownloadUnavailableReason,
@@ -183,38 +182,37 @@ export class SystemLogCard extends LitElement {
</ha-alert>`
: nothing
}
${skeletonOr(
this._items === undefined,
html`<ha-fade-in .duration=${300} easing="ease-in">
<div
class="skeleton"
role="progressbar"
aria-label=${this.hass.localize(
"ui.panel.config.logs.loading_log"
)}
>
${SKELETON_ROW_WIDTHS.map(
([primary, secondary]) => html`
<div class="skeleton-row">
<ha-skeleton-text
class="primary"
style=${styleMap({
"--ha-skeleton-text-width": `${primary}%`,
})}
></ha-skeleton-text>
<ha-skeleton-text
class="secondary"
style=${styleMap({
"--ha-skeleton-text-width": `${secondary}%`,
})}
></ha-skeleton-text>
</div>
`
)}
</div>
</ha-fade-in>`,
() =>
this._items!.length === 0
${
this._items === undefined
? html`<ha-fade-in .duration=${300} easing="ease-in">
<div
class="skeleton"
role="progressbar"
aria-label=${this.hass.localize(
"ui.panel.config.logs.loading_log"
)}
>
${SKELETON_ROW_WIDTHS.map(
([primary, secondary]) => html`
<div class="skeleton-row">
<ha-skeleton-text
class="primary"
style=${styleMap({
"--ha-skeleton-text-width": `${primary}%`,
})}
></ha-skeleton-text>
<ha-skeleton-text
class="secondary"
style=${styleMap({
"--ha-skeleton-text-width": `${secondary}%`,
})}
></ha-skeleton-text>
</div>
`
)}
</div>
</ha-fade-in>`
: this._items.length === 0
? html`
<div class="card-content empty-content">
${this.hass.localize("ui.panel.config.logs.no_issues")}
@@ -291,19 +289,18 @@ export class SystemLogCard extends LitElement {
`
)}</ha-list-base
>`
)}
${skeletonOr(
this._items === undefined,
nothing,
() =>
html`<div class="card-actions">
<ha-call-service-button domain="system_log" service="clear"
>${this.hass.localize(
"ui.panel.config.logs.clear"
)}</ha-call-service-button
>
</div>`
)}
}
${
this._items === undefined
? nothing
: html`<div class="card-actions">
<ha-call-service-button domain="system_log" service="clear"
>${this.hass.localize(
"ui.panel.config.logs.clear"
)}</ha-call-service-button
>
</div>`
}
</ha-card>
</div>
`;
+1 -78
View File
@@ -7,7 +7,6 @@ import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { computeStateDomain } from "../../common/entity/compute_state_domain";
import { throttle } from "../../common/util/throttle";
import "../../components/ha-spinner";
import { SkeletonLoadingController } from "../../components/skeleton/skeleton-loading-controller";
import type { LogbookEntry, LogbookStreamMessage } from "../../data/logbook";
import { subscribeLogbook } from "../../data/logbook";
import type { TraceContexts } from "../../data/trace";
@@ -86,14 +85,6 @@ export class HaLogbook extends LitElement {
@property({ type: Number, attribute: "max-entries" })
public maxEntries?: number;
/**
* While loading, draw a date line and this many entry rows for a skeleton
* overlay to read, instead of a spinner. Only for a logbook inside an
* overlay, such as a card's.
*/
@property({ type: Number, attribute: "placeholder-rows" })
public placeholderRows = 0;
@state() private _logbookEntries?: LogbookEntry[];
@state() private _traceContexts: TraceContexts = {};
@@ -106,15 +97,6 @@ export class HaLogbook extends LitElement {
@state() private _error?: string;
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
this.hass !== undefined &&
isComponentLoaded(this.hass.config, "logbook") &&
!this._error &&
this._logbookEntries === undefined
);
private _unsubLogbook?: Promise<UnsubscribeFunc>;
private _liveUpdatesEnabled = true;
@@ -150,27 +132,8 @@ export class HaLogbook extends LitElement {
const entries = this._shownEntries();
if (entries === undefined) {
if (this.placeholderRows > 0) {
// Shaped like the list that replaces it: a date, then entries
return html`
<div class="placeholder">
<div class="placeholder-date" data-skeleton="text"></div>
${Array.from(
{ length: this.placeholderRows },
() => html`
<div class="placeholder-entry">
<span class="placeholder-dot" data-skeleton="round"></span>
<span class="placeholder-message" data-skeleton="text"></span>
<span class="placeholder-time" data-skeleton="text"></span>
</div>
`
)}
</div>
`;
}
return html`
<div class="progress-wrapper" data-skeleton="block">
<div class="progress-wrapper">
<ha-spinner></ha-spinner>
</div>
`;
@@ -624,46 +587,6 @@ export class HaLogbook extends LitElement {
justify-content: center;
height: 100%;
align-items: center;
/* Inset like the entries, for the skeleton a card draws over it */
margin: 0 var(--ha-space-4);
}
/* Sized like the renderer's date heading and list entries */
.placeholder {
padding: var(--ha-space-2)
var(--logbook-horizontal-padding, var(--ha-space-4)) 0;
}
.placeholder-date {
width: 40%;
height: calc(var(--ha-font-size-m) * var(--ha-line-height-normal));
margin-bottom: var(--ha-space-2);
}
.placeholder-entry {
display: flex;
align-items: center;
gap: var(--ha-space-3);
height: 40px;
}
.placeholder-dot {
flex: none;
width: 10px;
height: 10px;
}
.placeholder-message {
flex: 1;
max-width: 50%;
height: var(--ha-font-size-m);
}
.placeholder-time {
flex: none;
width: 72px;
height: var(--ha-font-size-s);
margin-inline-start: auto;
}
`,
];
+4 -39
View File
@@ -3,16 +3,12 @@ import { ReactiveElement } from "lit";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon";
import "../../../components/skeleton/ha-skeleton-overlay";
import type { LovelaceBadgeConfig } from "../../../data/lovelace/config/badge";
import type { HomeAssistant } from "../../../types";
import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
import { getConfigEntityId } from "../common/get-config-entity-id";
import { createBadgeElement } from "../create-element/create-badge-element";
import {
createErrorBadgeConfig,
lovelaceElementPending,
} from "../create-element/create-element-base";
import { createErrorBadgeConfig } from "../create-element/create-element-base";
import type { LovelaceBadge } from "../types";
declare global {
@@ -43,15 +39,6 @@ export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
private _element?: LovelaceBadge;
/* Holds the badge, and draws its skeleton while its code loads */
private _overlay = document.createElement("ha-skeleton-overlay");
constructor() {
super();
this._overlay.style.borderRadius =
"var(--ha-badge-border-radius, var(--ha-border-radius-pill))";
}
protected createRenderRoot() {
return this;
}
@@ -109,28 +96,6 @@ export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
while (this.lastChild) {
this.removeChild(this.lastChild);
}
this._overlay.replaceChildren();
this.appendChild(this._overlay);
// A badge whose code is still loading has nothing to show yet, so it
// holds a badge's size for the wave until it does
const element = this._element;
const pending = lovelaceElementPending(element, config.type);
this._overlay.loading = pending !== undefined;
this._overlay.style.minHeight = pending ? "var(--ha-badge-size, 36px)" : "";
this._overlay.style.minWidth = pending
? "calc(var(--ha-badge-size, 36px) * 3)"
: "";
pending?.then(() => {
if (this._element === element) {
this._overlay.loading = false;
this._overlay.style.minHeight = "";
this._overlay.style.minWidth = "";
}
});
this._updateVisibility();
}
@@ -216,12 +181,12 @@ export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
if (this._element.connectedWhileHidden === true) {
if (!this._element.parentElement) {
this._overlay.appendChild(this._element);
this.appendChild(this._element);
}
} else if (!visible && this._element.parentElement) {
this._overlay.removeChild(this._element);
this.removeChild(this._element);
} else if (visible && !this._element.parentElement) {
this._overlay.appendChild(this._element);
this.appendChild(this._element);
}
}
}
@@ -15,7 +15,6 @@ import {
import { transform } from "../../../common/decorators/transform";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
import { apiContext, connectionContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import {
@@ -98,12 +97,6 @@ class HuiLightColorFavoritesCardFeature
private _unsubEntityRegistry?: UnsubscribeFunc;
// The favourites are read from the entity's settings
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() => this._unsubEntityRegistry !== undefined && this._entry === undefined
);
private _resizeController = new ResizeController(this, {
callback: (entries) => {
const width = entries[0]?.contentRect.width;
@@ -138,8 +131,10 @@ class HuiLightColorFavoritesCardFeature
this._unsubEntityRegistry = subscribeEntityRegistry(
this._connection,
(entries) => {
// Without an entry, there are no favourites to wait for
this._entry = entries.find((e) => e.entity_id === id) ?? null;
const entry = entries.find((e) => e.entity_id === id);
if (entry) {
this._entry = entry;
}
}
);
} catch (_e) {
@@ -152,7 +147,12 @@ class HuiLightColorFavoritesCardFeature
return this._resizeController.value ?? 0;
}
protected willUpdate(changedProps: PropertyValues): void {
protected updated(changedProps: PropertyValues): void {
if (changedProps.has("context") || changedProps.has("_connection")) {
this._unsubscribeEntityRegistry();
this._subscribeEntityEntry();
}
if (changedProps.has("_entry")) {
if (this._entry?.options?.light?.favorite_colors) {
this._favoriteColors = this._entry.options.light.favorite_colors;
@@ -164,13 +164,6 @@ class HuiLightColorFavoritesCardFeature
}
}
protected updated(changedProps: PropertyValues): void {
if (changedProps.has("context") || changedProps.has("_connection")) {
this._unsubscribeEntityRegistry();
this._subscribeEntityEntry();
}
}
static getStubConfig(): LightColorFavoritesCardFeatureConfig {
return {
type: "light-color-favorites",
@@ -23,7 +23,6 @@ import type {
LocalizeKeys,
} from "../../../common/translations/localize";
import "../../../components/ha-control-select";
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
import { apiContext, connectionContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { ExtEntityRegistryEntry } from "../../../data/entity/entity_registry";
@@ -138,12 +137,6 @@ export abstract class HuiNumericFavoriteCardFeatureBase<
private _subscribedConnection?: HomeAssistant["connection"];
// The favourites are read from the entity's settings
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() => this._subscribedEntityId !== undefined && this._entry === undefined
);
private _resizeController = new ResizeController<number | undefined>(this, {
callback: (entries: { contentRect?: { width: number } }[]) => {
const width = entries[0]?.contentRect?.width;
@@ -17,7 +17,6 @@ import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { FrontendLocaleData } from "../../../data/translation";
import "../../../components/ha-spinner";
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
import {
configContext,
connectionContext,
@@ -124,16 +123,6 @@ class HuiPrecipitationForecastCardFeature
@state() private _error?: string;
// Only while there's a forecast to wait for
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
!this._forecast &&
!this._error &&
supportsForecast(this._stateObj) &&
this._resolvedForecastType() !== undefined
);
private _subscribed?: Promise<UnsubscribeFunc | undefined>;
private _subscribedType?: ForecastResolution;
@@ -251,7 +240,7 @@ class HuiPrecipitationForecastCardFeature
}
if (!this._forecast) {
return html`
<div class="container loading" data-skeleton="block">
<div class="container loading">
<ha-spinner size="small"></ha-spinner>
</div>
`;
@@ -18,7 +18,6 @@ import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { FrontendLocaleData } from "../../../data/translation";
import "../../../components/ha-spinner";
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
import {
configContext,
connectionContext,
@@ -119,16 +118,6 @@ class HuiTemperatureForecastCardFeature
@state() private _error?: string;
// Only while there's a forecast to wait for
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() =>
!this._forecast &&
!this._error &&
supportsForecast(this._stateObj) &&
this._resolvedForecastType() !== undefined
);
private _subscribed?: Promise<UnsubscribeFunc | undefined>;
private _subscribedType?: ForecastResolution;
@@ -237,7 +226,7 @@ class HuiTemperatureForecastCardFeature
}
if (!this._forecast) {
return html`
<div class="container loading" data-skeleton="block">
<div class="container loading">
<ha-spinner size="small"></ha-spinner>
</div>
`;
@@ -21,7 +21,6 @@ import type { HaControlButton } from "../../../components/ha-control-button";
import "../../../components/ha-control-button-group";
import "../../../components/ha-control-select-menu";
import "../../../components/ha-svg-icon";
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
import {
apiContext,
connectionContext,
@@ -102,12 +101,6 @@ class HuiTimerPresetsCardFeature
private _unsubEntityRegistry?: UnsubscribeFunc;
// The presets are read from the entity's settings
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() => this._unsubEntityRegistry !== undefined && this._entry === undefined
);
public connectedCallback() {
super.connectedCallback();
this._subscribeEntityEntry();
@@ -141,19 +134,17 @@ class HuiTimerPresetsCardFeature
}
}
protected willUpdate(changedProps: PropertyValues): void {
if (changedProps.has("_entry")) {
this._presets = normalizeTimerPresets(
this._entry?.options?.timer?.presets
);
}
}
protected updated(changedProps: PropertyValues): void {
if (changedProps.has("context") || changedProps.has("_connection")) {
this._unsubscribeEntityRegistry();
this._subscribeEntityEntry();
}
if (changedProps.has("_entry")) {
this._presets = normalizeTimerPresets(
this._entry?.options?.timer?.presets
);
}
}
public static async getConfigElement(): Promise<LovelaceCardFeatureEditor> {
@@ -187,11 +178,6 @@ class HuiTimerPresetsCardFeature
const presets = this._presets;
// Keep the row while the presets load, so the card keeps its height
if (this._entry === undefined && this._unsubEntityRegistry) {
return html`<ha-control-button-group></ha-control-button-group>`;
}
if (!presets.length) {
return nothing;
}
@@ -19,7 +19,6 @@ import { transform } from "../../../common/decorators/transform";
import { computeDomain } from "../../../common/entity/compute_domain";
import { isNumericFromAttributes } from "../../../common/number/format_number";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
import {
configContext,
connectionContext,
@@ -104,24 +103,6 @@ class HuiHistoryChartCardFeature
@state() private _error?: { code: string; message: string };
protected readonly _skeletonLoading = new SkeletonLoadingController(
this,
() => {
const stateObj = this._stateObj;
const hassConfig = this._hassConfig;
// Only while there's history to wait for
return (
this._loading &&
!this._error &&
stateObj !== undefined &&
supportsTrendGraphCardFeatureFromState(stateObj) &&
hassConfig !== undefined &&
isComponentLoaded(hassConfig, "history")
);
}
);
private _subscribed?: Promise<UnsubscribeFunc | undefined>;
private _interval?: number;
@@ -1,22 +0,0 @@
import { html } from "lit";
import "../../../../../components/ha-gauge";
import type { FrontendLocaleData } from "../../../../../data/translation";
/**
* Holds the place of an energy gauge card's gauge and name while its data
* loads. The gauge is hidden, as it has no value yet, but a skeleton drawn
* over the card still takes its shape.
*/
export const renderEnergyGaugeLoading = (
locale: FrontendLocaleData,
loadingText: string
) => html`
<ha-gauge
style="opacity: 0"
aria-hidden="true"
.value=${0}
label="%"
.locale=${locale}
></ha-gauge>
<div class="name">${loadingText}</div>
`;
@@ -13,7 +13,6 @@ import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import {
configContext,
entitiesContext,
internationalizationContext,
} from "../../../../data/context";
import type { EnergyData } from "../../../../data/energy";
@@ -31,7 +30,6 @@ import { createEntityNotFoundWarning } from "../../components/hui-warning";
import type { LovelaceCard } from "../../types";
import { severityMap } from "../hui-gauge-card";
import type { EnergyCarbonGaugeCardConfig } from "../types";
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
const FORMAT_OPTIONS = {
maximumFractionDigits: 0,
@@ -73,10 +71,6 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: entitiesContext, subscribe: true })
private _entities?: HomeAssistant["entities"];
constructor() {
super();
new EnergyCollectionController(this, {
@@ -104,23 +98,7 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
}
if (!this._data) {
// Without a CO2 Signal sensor the card shows nothing, so it doesn't
// stand in for anything while the data loads
if (
this._entities &&
!Object.values(this._entities).some(
(entity) => entity.platform === "co2signal"
)
) {
return nothing;
}
return html`<ha-card>
${renderEnergyGaugeLoading(
this._i18n.locale,
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
)}
</ha-card>`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
if (!this._data.co2SignalEntity) {
@@ -122,12 +122,15 @@ export class HuiEnergyDevicesDetailGraphCard
@consume({ context: uiContext, subscribe: true })
private _ui!: HomeAssistantUI;
private _energy = new EnergyCollectionController(this, {
config: () => this._config,
onData: (data) => {
this._data = data;
},
});
constructor() {
super();
new EnergyCollectionController(this, {
config: () => this._config,
onData: (data) => {
this._data = data;
},
});
}
public getCardSize(): Promise<number> | number {
return 3;
@@ -181,7 +184,6 @@ export class HuiEnergyDevicesDetailGraphCard
this._legendData
)}
.expandLegend=${this._config.expand_legend}
?loading=${!this._data}
click-label-for-more-info
@dataset-hidden=${this._datasetHidden}
@dataset-unhidden=${this._datasetUnhidden}
@@ -309,13 +311,10 @@ export class HuiEnergyDevicesDetailGraphCard
);
private _processStatistics() {
// Until the data comes, the legend lists the configured devices so the
// skeleton has as many legend rows as the chart will
const energyData = this._data ?? this._energy.placeholderData;
if (!energyData) {
if (!this._data) {
return;
}
const energyData = this._data;
const {
chartData,
@@ -205,7 +205,6 @@ export class HuiEnergyDevicesGraphCard
.sonificationLabelFormatter=${this._sonificationLabel}
.extraComponents=${[PieChart]}
.expandLegend=${this._config.expand_legend}
?loading=${!this._data}
click-label-for-more-info
@chart-click=${this._handleChartClick}
@dataset-hidden=${this._datasetHidden}
@@ -212,13 +212,7 @@ class HuiEnergyDistrubutionCard extends LitElement implements LovelaceCard {
}
if (!this._data) {
return html`<ha-card .header=${this._config.title}>
<div class="card-content">
<div class="loading" data-skeleton="block">
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
</div>
</div>
</ha-card>`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
const prefs = this._data.prefs;
@@ -975,11 +969,6 @@ class HuiEnergyDistrubutionCard extends LitElement implements LovelaceCard {
position: relative;
direction: ltr;
}
/* The usual layout: a row of sources over the grid and home. Others are
remembered once seen. */
.loading {
height: 230px;
}
.lines {
position: absolute;
bottom: 0;
@@ -242,10 +242,9 @@ export class HuiEnergyGasGraphCard extends LitElement implements LovelaceCard {
this._displayPrecision ?? this._yAxisFractionDigits
)}
chart-type="bar"
?loading=${!this._data}
></ha-chart-base>
${
this._data && !this._chartData.length
!this._chartData.length
? html`<div class="no-data">
${
isToday(this._start)
@@ -77,30 +77,8 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
return nothing;
}
const title =
this._config.title ||
this._i18n.localize("ui.panel.lovelace.cards.energy.grid_balance.title");
if (!this._data) {
return html`
<ha-card>
<div class="content">
<ha-tile-icon>
<ha-svg-icon
slot="icon"
.path=${mdiTransmissionTower}
></ha-svg-icon>
</ha-tile-icon>
<ha-tile-info>
<span slot="primary">${title}</span>
<span slot="secondary">
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
</span>
</ha-tile-info>
</div>
<div class="bar loading" data-skeleton="block"></div>
</ha-card>
`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
const { summedData } = getSummedData(this._data);
@@ -139,7 +117,14 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
></ha-svg-icon>
</ha-tile-icon>
<ha-tile-info>
<span slot="primary">${title}</span>
<span slot="primary">
${
this._config.title ||
this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.title"
)
}
</span>
<span slot="secondary" class="equation">
<span class="imported" id="eq-imported">
${fmtEnergy(imported)}
@@ -325,10 +310,6 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
overflow: visible;
}
.bar.loading {
border-radius: var(--ha-border-radius-lg);
}
.bar-half {
position: relative;
display: flex;
@@ -21,7 +21,6 @@ import type {
} from "../../../../types";
import type { LovelaceCard } from "../../types";
import type { EnergyGridNeutralityGaugeCardConfig } from "../types";
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
const LEVELS: LevelDefinition[] = [
{ level: -1, stroke: "var(--energy-grid-return-color)" },
@@ -80,12 +79,7 @@ class HuiEnergyGridGaugeCard extends LitElement implements LovelaceCard {
}
if (!this._data) {
return html`<ha-card>
${renderEnergyGaugeLoading(
this._i18n.locale,
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
)}
</ha-card>`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
const { summedData, compareSummedData: _ } = getSummedData(this._data);
@@ -165,26 +165,8 @@ class HuiEnergySankeyCard
return nothing;
}
const vertical =
this._config.layout === "vertical" ||
(this._config.layout !== "horizontal" && this._isMobileSize);
const cardClasses = classMap({
"is-grid": this.layout === "grid",
"is-panel": this.layout === "panel",
"is-vertical": vertical,
});
if (!this._data) {
return html`
<ha-card .header=${this._config.title} class=${cardClasses}>
<div class="card-content">
<div class="loading" data-skeleton="block">
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
</div>
</div>
</ha-card>
`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
const prefs = this._data.prefs;
@@ -425,8 +407,19 @@ class HuiEnergySankeyCard
const hasData = nodes.some((node) => node.value > 0);
const vertical =
this._config.layout === "vertical" ||
(this._config.layout !== "horizontal" && this._isMobileSize);
return html`
<ha-card .header=${this._config.title} class=${cardClasses}>
<ha-card
.header=${this._config.title}
class=${classMap({
"is-grid": this.layout === "grid",
"is-panel": this.layout === "panel",
"is-vertical": vertical,
})}
>
<div class="card-content">
${
hasData
@@ -733,9 +726,6 @@ class HuiEnergySankeyCard
flex: 1;
display: flex;
}
.loading {
flex: 1;
}
`;
}
@@ -22,7 +22,6 @@ import type {
import type { LovelaceCard } from "../../types";
import { severityMap } from "../hui-gauge-card";
import type { EnergySelfSufficiencyGaugeCardConfig } from "../types";
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
const FORMAT_OPTIONS = {
maximumFractionDigits: 0,
@@ -83,12 +82,7 @@ class HuiEnergySelfSufficiencyGaugeCard
}
if (!this._data) {
return html`<ha-card>
${renderEnergyGaugeLoading(
this._i18n.locale,
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
)}
</ha-card>`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
// The strategy only includes this card if we have a grid.
@@ -21,7 +21,6 @@ import type {
import type { LovelaceCard } from "../../types";
import { severityMap } from "../hui-gauge-card";
import type { EnergySolarGaugeCardConfig } from "../types";
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
const FORMAT_OPTIONS = {
maximumFractionDigits: 0,
@@ -79,12 +78,7 @@ class HuiEnergySolarGaugeCard extends LitElement implements LovelaceCard {
}
if (!this._data) {
return html`<ha-card>
${renderEnergyGaugeLoading(
this._i18n.locale,
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
)}
</ha-card>`;
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
const { summedData, compareSummedData: _ } = getSummedData(this._data);
@@ -120,7 +120,6 @@ export class HuiEnergySolarGraphCard
new EnergyCollectionController(this, {
config: () => this._config,
onData: (data) => this._fetchForecasts(data),
loading: () => !this._data,
});
}
@@ -185,10 +184,9 @@ export class HuiEnergySolarGraphCard
this._yAxisFractionDigits
)}
chart-type="bar"
?loading=${!this._data}
></ha-chart-base>
${
this._data && !this._chartData.length
!this._chartData.length
? html`<div class="no-data">
${
isToday(this._start)
@@ -23,6 +23,7 @@ import {
} from "../../../../data/context";
import type { EnergyData, EnergySourceByType } from "../../../../data/energy";
import {
calculateGridNetCost,
energySourcesByType,
getBatteryEnergyStatIds,
getBatteryName,
@@ -151,12 +152,15 @@ export class HuiEnergySourcesTableCard
})
private _gasDisplayPrecisions?: Record<string, number | undefined>;
private _energy = new EnergyCollectionController(this, {
config: () => this._config,
onData: (data) => {
this._data = data;
},
});
constructor() {
super();
new EnergyCollectionController(this, {
config: () => this._config,
onData: (data) => {
this._data = data;
},
});
}
public getCardSize(): Promise<number> | number {
return 3;
@@ -354,34 +358,16 @@ export class HuiEnergySourcesTableCard
return nothing;
}
// Until the data comes, the table has a row for every configured source,
// so the skeleton has as many rows as the table will
const data = this._data ?? this._energy.placeholderData;
const placeholder = !this._data;
if (!data) {
return html`<ha-card>
${
this._config.title
? html`<h1 class="card-header">${this._config.title}</h1>`
: ""
}
<div class="loading" data-skeleton="block">
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
</div>
</ha-card>`;
if (!this._data) {
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
}
let totalGrid = 0;
let totalGridCost = 0;
let gridImportIdx = 0;
let gridExportIdx = 0;
let totalBattery = 0;
let hasGridCost = false;
let totalGridCompare = 0;
let totalGridCostCompare = 0;
let totalBatteryCompare = 0;
const totals = {
@@ -407,7 +393,7 @@ export class HuiEnergySourcesTableCard
water: false,
};
const allTypes = energySourcesByType(data.prefs);
const allTypes = energySourcesByType(this._data.prefs);
const pickedTypes = this._config?.types;
const types = pickedTypes
? Object.fromEntries(
@@ -463,8 +449,8 @@ export class HuiEnergySourcesTableCard
const units = {
solar: "kWh",
gas: data.gasUnit,
water: data.waterUnit,
gas: this._data.gasUnit,
water: this._data.waterUnit,
};
const gasDisplayPrecisions = types.gas
@@ -486,7 +472,22 @@ export class HuiEnergySourcesTableCard
}
: undefined;
const compare = data.statsCompare !== undefined;
const compare = this._data.statsCompare !== undefined;
const gridCost = types.grid
? calculateGridNetCost(types.grid, this._data.info, this._data.stats)
: undefined;
const gridCostCompare =
compare && types.grid
? calculateGridNetCost(
types.grid,
this._data.info,
this._data.statsCompare
)
: undefined;
const hasGridCost = gridCost !== undefined || gridCostCompare !== undefined;
const totalGridCost = gridCost ?? 0;
const totalGridCostCompare = gridCostCompare ?? 0;
const _extractStatData = (
statId: string,
@@ -498,26 +499,24 @@ export class HuiEnergySourcesTableCard
cost: number;
costCompare: number;
} => {
const energy = calculateStatisticSumGrowth(data.stats[statId]);
const energy = calculateStatisticSumGrowth(this._data!.stats[statId]);
const compareEnergy =
compare && calculateStatisticSumGrowth(data.statsCompare?.[statId]);
compare &&
calculateStatisticSumGrowth(this._data!.statsCompare[statId]);
const cost =
(costStatId && calculateStatisticSumGrowth(data.stats[costStatId])) ||
(costStatId &&
calculateStatisticSumGrowth(this._data!.stats[costStatId])) ||
0;
const costCompare =
(compare &&
costStatId &&
calculateStatisticSumGrowth(data.statsCompare?.[costStatId])) ||
calculateStatisticSumGrowth(this._data!.statsCompare[costStatId])) ||
0;
if (
!placeholder &&
energy === null &&
(!compare || compareEnergy === null)
) {
if (energy === null && (!compare || compareEnergy === null)) {
return {
hasData: false,
energy: energy || 0,
@@ -539,11 +538,11 @@ export class HuiEnergySourcesTableCard
const _sumStatData = (statIds: string[]) =>
statIds.reduce(
(sum, statId) => {
const statData = _extractStatData(statId, null);
const data = _extractStatData(statId, null);
return {
hasData: sum.hasData || statData.hasData,
energy: sum.energy + statData.energy,
energyCompare: sum.energyCompare + statData.energyCompare,
hasData: sum.hasData || data.hasData,
energy: sum.energy + data.energy,
energyCompare: sum.energyCompare + data.energyCompare,
};
},
{ hasData: false, energy: 0, energyCompare: 0 }
@@ -552,7 +551,7 @@ export class HuiEnergySourcesTableCard
const showOnlyTotals = this._config.show_only_totals;
const combine =
!showOnlyTotals &&
(this._config.combine_sources ?? data.combineSources ?? false);
(this._config.combine_sources ?? this._data.combineSources ?? false);
const combineType = (type: keyof EnergySourceByType) =>
combine && (types[type]?.length ?? 0) > 1;
@@ -622,7 +621,8 @@ export class HuiEnergySourcesTableCard
html` ${types[type]?.map((source, idx) => {
const cost_stat =
type in hasCosts &&
(source.stat_cost || data.info.cost_sensors[source.stat_energy_from]);
(source.stat_cost ||
this._data!.info.cost_sensors[source.stat_energy_from]);
const { hasData, energy, energyCompare, cost, costCompare } =
_extractStatData(source.stat_energy_from, cost_stat || null);
@@ -805,7 +805,7 @@ export class HuiEnergySourcesTableCard
this._states,
this._formatEntityName,
source,
data.statsMetadata
this._data!.statsMetadata
);
return html` ${this._renderRow(
computedStyles,
@@ -887,7 +887,7 @@ export class HuiEnergySourcesTableCard
const cost_stat =
source.stat_cost ||
data.info.cost_sensors[source.stat_energy_from];
this._data!.info.cost_sensors[source.stat_energy_from];
const { hasData, energy, energyCompare, cost, costCompare } =
_extractStatData(
source.stat_energy_from,
@@ -901,12 +901,6 @@ export class HuiEnergySourcesTableCard
totalGrid += energy;
totalGridCompare += energyCompare;
if (cost_stat) {
hasGridCost = true;
totalGridCost += cost;
totalGridCostCompare += costCompare;
}
if (showOnlyTotals) {
return nothing;
}
@@ -953,7 +947,7 @@ export class HuiEnergySourcesTableCard
const cost_stat =
source.stat_compensation ||
data.info.cost_sensors[source.stat_energy_to];
this._data!.info.cost_sensors[source.stat_energy_to];
const { hasData, energy, energyCompare, cost, costCompare } =
_extractStatData(source.stat_energy_to, cost_stat || null);
@@ -963,12 +957,6 @@ export class HuiEnergySourcesTableCard
totalGrid -= energy;
totalGridCompare -= energyCompare;
if (cost_stat) {
hasGridCost = true;
totalGridCost -= cost;
totalGridCostCompare -= costCompare;
}
if (showOnlyTotals) {
return nothing;
}
@@ -1183,12 +1171,6 @@ export class HuiEnergySourcesTableCard
.card-header {
padding-bottom: 0;
}
/* Before the energy preferences are known: as tall as the header row
and three sources (212px). Others are remembered once seen. */
.loading {
height: 180px;
margin: 16px;
}
.content {
padding: 16px;
}
@@ -30,6 +30,7 @@ import type {
GridSourceTypeEnergyPreference,
} from "../../../../data/energy";
import {
calculateGridNetCost,
computeConsumptionData,
energySourcesByType,
getBatteryEnergyStatIds,
@@ -131,6 +132,8 @@ export class HuiEnergyUsageGraphCard
@state() private _total?: number;
@state() private _totalCost?: number;
private _data?: EnergyData;
@state()
@@ -186,24 +189,48 @@ export class HuiEnergyUsageGraphCard
return nothing;
}
const totalCost =
this._totalCost !== undefined && this._hassConfig.currency
? formatNumber(this._totalCost, this._i18n.locale, {
style: "currency",
currency: this._hassConfig.currency,
})
: undefined;
return html`
<ha-card>
${
this._config.title
? html` <div class="card-header">
<span>${this._config.title}</span>
${
this._total
? html`<hui-energy-graph-chip
.tooltip=${this._formatTotal(this._total)}
>
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_usage",
{ num: formatNumber(this._total, this._i18n.locale) }
)}
</hui-energy-graph-chip>`
: nothing
}
<div class="chips">
${
this._total
? html`<hui-energy-graph-chip
.tooltip=${this._formatTotal(this._total)}
>
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_usage",
{
num: formatNumber(this._total, this._i18n.locale),
}
)}
</hui-energy-graph-chip>`
: nothing
}
${
totalCost
? html`<hui-energy-graph-chip
.tooltip=${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_cost",
{ cost: totalCost }
)}
>
${totalCost}
</hui-energy-graph-chip>`
: nothing
}
</div>
</div>`
: nothing
}
@@ -226,10 +253,8 @@ export class HuiEnergyUsageGraphCard
)}
chart-type="bar"
.expandLegend=${this._config.expand_legend}
?loading=${!this._data}
></ha-chart-base>
${
this._data &&
!this._chartData.some((dataset) => dataset.data!.length)
? html`<div class="no-data">
${
@@ -605,6 +630,11 @@ export class HuiEnergyUsageGraphCard
this._chartData = datasets;
this._legendData = this._getLegendData(datasets);
this._total = this._processTotal(consumption);
this._totalCost = calculateGridNetCost(
energySourcesByType(energyData.prefs).grid ?? [],
energyData.info,
energyData.stats
);
}
private _getLegendData(
@@ -909,6 +939,12 @@ export class HuiEnergyUsageGraphCard
align-items: center;
padding-bottom: 0;
}
.chips {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: var(--ha-space-2);
}
.content {
padding: 16px;
}
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more