Compare commits

..
18 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
83 changed files with 4564 additions and 1594 deletions

No files matched your search

+1 -22
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}`.
- Don't add your own fade to loaded content. `ha-skeleton-overlay` fades each part in over `--ha-animation-duration-fast`, which reduced motion makes instant.
- Don't fade in the loaded content itself.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
@@ -124,24 +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.
- 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 -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>
-545
View File
@@ -1,545 +0,0 @@
/**
* Read a skeleton from rendered content, such as a dashboard card: where its
* text lines, icons, images, controls and drawings are, inside shadow roots
* too. The content stays the source of truth for layout, so the skeleton
* can't drift from it.
*
* Any element can say how it's read with a `data-skeleton` attribute:
* - `text`, `round` or `block`: one piece of that kind, the size of the element
* - `none`: left out and left showing, such as a card's own chrome
* - `keep`: left showing, but what's inside it is still read
*
* Skeletons a component already draws itself (`ha-skeleton` and its
* variants) are left out and left showing, as `none`.
*/
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
const isOverride = (value: string | null): value is SkeletonOverride =>
value !== null && OVERRIDES.has(value);
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
if (element.localName.startsWith("ha-skeleton")) {
return "none";
}
const value = element.getAttribute("data-skeleton");
return isOverride(value) ? value : undefined;
};
export interface SkeletonPiece {
kind: SkeletonPieceKind;
x: number;
y: number;
width: number;
height: number;
radius?: string;
/* An SVG mask for a drawing, such as a gauge arc */
mask?: string;
/* 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
);
+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;
+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 {
@@ -1,412 +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";
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 nothing to read yet, such as before the content's code has loaded,
* it fills itself with one plain wave. The skeleton follows the host's
* corner radius.
*
* @slot - The content.
* @slot skeleton - A skeleton of your own, used instead of reading one.
*/
@customElement("ha-skeleton-overlay")
export class HaSkeletonOverlay extends LitElement {
@property({ type: Boolean }) public loading = false;
@property() public effect: HaSkeleton["effect"] = "sheen";
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n?: ContextType<typeof internationalizationContext>;
/* What's inside that has said it's loading */
@state() private _loadingSources = new Set<EventTarget>();
@state() private _pieces?: SkeletonPiece[];
@state() private _customSkeleton = false;
@state() private _onScreen = true;
@query("slot:not([name])") private _contentSlot?: HTMLSlotElement;
/* 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;
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
private _intersectionObserver = new IntersectionObserver((entries) => {
this._onScreen = entries[entries.length - 1].isIntersecting;
});
public connectedCallback() {
super.connectedCallback();
this._resizeObserver.observe(this);
this._intersectionObserver.observe(this);
this._scheduleMeasure();
}
public disconnectedCallback() {
super.disconnectedCallback();
this._resizeObserver.disconnect();
this._intersectionObserver.disconnect();
if (this._measureFrame !== undefined) {
cancelAnimationFrame(this._measureFrame);
this._measureFrame = undefined;
}
// Never leave the content hidden while it's away
this._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"
);
}
if (!loading && this._wasLoading) {
this._endLoading();
}
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();
}
private _contentChanged() {
this._resizeObserver.disconnect();
this._resizeObserver.observe(this);
this._contentSlot
?.assignedElements()
.forEach((element) => this._resizeObserver.observe(element));
// Content that went away can't finish loading
const sources = [...this._loadingSources].filter(
(source) => !(source instanceof Node) || source.isConnected
);
if (sources.length !== this._loadingSources.size) {
this._loadingSources = new Set(sources);
}
this._scheduleMeasure();
}
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() {
if (!this._isLoading || this._customSkeleton) {
return;
}
// Read from the content as it really looks, then hide it again before
// the next paint, so nothing flickers
this._showParts();
const skeleton = extractSkeleton(this, this.getBoundingClientRect());
this._hideParts(skeleton);
if (JSON.stringify(skeleton.pieces) !== JSON.stringify(this._pieces)) {
this._pieces = skeleton.pieces;
}
}
private _hideParts(skeleton: ExtractedSkeleton) {
skeleton.parts.forEach((part) => {
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 before the first reading, the whole
// content was hidden rather than its parts
const wholeContent = this._customSkeleton || this._pieces === undefined;
this._arriving = {
content: wholeContent
? (this._contentSlot?.assignedElements() ?? [])
: [],
opacityParts: [...this._hiddenOpacity.keys()],
colorParts: [...this._hiddenColor.keys()],
};
this._showParts();
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;
}
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;
}
}
`,
];
+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
);
});
+33
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" },
+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
+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,
});
@@ -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);
}
}
}
+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",
+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
@@ -23,6 +23,7 @@ import {
} from "../../../../data/context";
import type { EnergyData, EnergySourceByType } from "../../../../data/energy";
import {
calculateGridNetCost,
energySourcesByType,
getBatteryEnergyStatIds,
getBatteryName,
@@ -362,15 +363,11 @@ export class HuiEnergySourcesTableCard
}
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 = {
@@ -477,6 +474,21 @@ export class HuiEnergySourcesTableCard
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,
costStatId: string | null
@@ -889,12 +901,6 @@ export class HuiEnergySourcesTableCard
totalGrid += energy;
totalGridCompare += energyCompare;
if (cost_stat) {
hasGridCost = true;
totalGridCost += cost;
totalGridCostCompare += costCompare;
}
if (showOnlyTotals) {
return nothing;
}
@@ -951,12 +957,6 @@ export class HuiEnergySourcesTableCard
totalGrid -= energy;
totalGridCompare -= energyCompare;
if (cost_stat) {
hasGridCost = true;
totalGridCost -= cost;
totalGridCostCompare -= costCompare;
}
if (showOnlyTotals) {
return nothing;
}
@@ -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
}
@@ -603,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(
@@ -907,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;
}
@@ -1,4 +1,5 @@
import type { PictureElementsCardConfig } from "../types";
import type { ElementPosition } from "./movable-element";
// Connects the picture-elements card editor with the card in its preview, so
// that clicks and drags on the preview edit the config. It is attached to the
@@ -15,9 +16,8 @@ const MAX_HAND_OVERS = 10;
// Positions are in percent of the image.
export interface PictureElementsEditorHandlers {
selectElement: (index: number) => void;
moveElement: (index: number, left: number, top: number) => void;
// A click on the image outside of any element.
clickImage: (x: number, y: number) => void;
// Along the sides the element is placed from, like `{ right, top }`.
moveElement: (index: number, position: ElementPosition) => void;
}
export class PictureElementsEditorBridge extends EventTarget {
@@ -4,7 +4,8 @@ import type {
LovelaceElementConfig,
} from "../../elements/types";
import type { PictureElementsEditorBridge } from "./editor-bridge";
import { isMovableElement } from "./movable-element";
import type { ElementAnchors, ElementPosition } from "./movable-element";
import { elementAnchors, isMovableElement } from "./movable-element";
// How far (px) a press has to move before it counts as a drag.
const DRAG_THRESHOLD = 4;
@@ -21,16 +22,27 @@ export interface EditorPreviewTarget {
configs?: LovelaceElementConfig[];
}
// Where a movable element is, in percent of the image: its distances from the
// sides it is placed from, and its rendered center. The card's default
// transform centers it on its left/top point only, not on its right/bottom one.
interface Placement {
anchors: ElementAnchors;
x: number;
y: number;
centerX: number;
centerY: number;
}
// A press on the preview, which ends as a click or a drag.
interface Press {
pointerId: number;
clientX: number;
clientY: number;
index?: number;
// Start position (percent) of a movable element.
start?: { left: number; top: number };
// Start position of a movable element.
start?: Placement;
// Current position (percent) once an element is dragged.
moved?: { left: number; top: number };
moved?: ElementPosition;
// The pointer left the threshold, so the press is no click.
dragged?: boolean;
}
@@ -226,15 +238,35 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
);
}
// The element's left/top in percent, as laid out.
private _position(root: HTMLElement, index: number): Press["start"] {
if (!root.offsetWidth || !root.offsetHeight) {
// Where the element is, as laid out. Undefined while it isn't rendered (like
// display: none), as it then has no layout to take it from.
private _position(root: HTMLElement, index: number): Placement | undefined {
const { elements, configs } = this._target();
const element = elements?.[index];
const anchors = configs?.[index] && elementAnchors(configs[index]);
if (!element || !anchors || !element.getClientRects().length) {
return undefined;
}
const style = getComputedStyle(this._target().elements![index]);
// The computed sides are layout px, while the rects are visual px, which
// differ under an ancestor's scale() or zoom. Both sizes are fractional,
// unlike offsetWidth/offsetHeight.
const rootStyle = getComputedStyle(root);
const width = parseFloat(rootStyle.width);
const height = parseFloat(rootStyle.height);
const rootRect = root.getBoundingClientRect();
if (!width || !height || !rootRect.width || !rootRect.height) {
return undefined;
}
const style = getComputedStyle(element);
const rect = element.getBoundingClientRect();
return {
left: (parseFloat(style.left) / root.offsetWidth) * 100,
top: (parseFloat(style.top) / root.offsetHeight) * 100,
anchors,
x: (parseFloat(style[anchors.x]) / width) * 100,
y: (parseFloat(style[anchors.y]) / height) * 100,
centerX:
((rect.left + rect.width / 2 - rootRect.left) / rootRect.width) * 100,
centerY:
((rect.top + rect.height / 2 - rootRect.top) / rootRect.height) * 100,
};
}
@@ -260,13 +292,15 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
}
const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
const wasMoved = !!press.moved;
press.moved = {
left: clampPercent(press.start.left + (dx / rect.width) * 100),
top: clampPercent(press.start.top + (dy / rect.height) * 100),
};
press.moved = movedPosition(
press.start,
(dx / rect.width) * 100,
(dy / rect.height) * 100
);
const element = this._target().elements?.[press.index];
element?.style.setProperty("left", `${press.moved.left}%`);
element?.style.setProperty("top", `${press.moved.top}%`);
for (const [prop, value] of Object.entries(press.moved)) {
element?.style.setProperty(prop, `${value}%`);
}
if (!wasMoved) {
this._host.requestUpdate();
}
@@ -278,30 +312,54 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
return;
}
const editor = this._editor;
if (!editor) {
// The visual editor went away, or the config changed the element's sides.
if (!editor || (press.moved && !this._sameAnchors(press))) {
this.pointerCancel(ev);
return;
}
this._endPress();
if (press.index !== undefined && press.moved) {
editor.handlers.moveElement(
press.index,
press.moved.left,
press.moved.top
);
editor.handlers.moveElement(press.index, press.moved);
} else if (press.dragged) {
// A drag that moved nothing is no click.
} else if (press.index !== undefined) {
editor.handlers.selectElement(press.index);
} else {
const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
editor.handlers.clickImage(
clampPercent(((ev.clientX - rect.left) / rect.width) * 100),
clampPercent(((ev.clientY - rect.top) / rect.height) * 100)
);
this._placeSelected(ev, editor);
}
};
// Whether the config places the element from the sides the press started
// from.
private _sameAnchors({ index, start }: Press): boolean {
const config =
index === undefined ? undefined : this._target().configs?.[index];
const anchors = config && elementAnchors(config);
return anchors?.x === start?.anchors.x && anchors?.y === start?.anchors.y;
}
// Moves the center of the selected element to a click on the image.
private _placeSelected(
ev: PointerEvent,
editor: PictureElementsEditorBridge
): void {
const root = ev.currentTarget as HTMLElement;
const index = editor.selectedIndex;
const start = index === undefined ? undefined : this._position(root, index);
if (index === undefined || !start) {
return;
}
const rect = root.getBoundingClientRect();
editor.handlers.moveElement(
index,
movedPosition(
start,
((ev.clientX - rect.left) / rect.width) * 100 - start.centerX,
((ev.clientY - rect.top) / rect.height) * 100 - start.centerY
)
);
}
// Also bound to lostpointercapture.
public pointerCancel = (ev: PointerEvent): void => {
const press = this._press;
@@ -316,7 +374,7 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
const { elements, configs } = this._target();
const element = elements?.[press.index];
const style = configs?.[press.index]?.style;
for (const prop of ["left", "top"]) {
for (const prop of Object.keys(press.moved)) {
if (style?.[prop] != null && style[prop] !== "") {
element?.style.setProperty(prop, style[prop]);
} else {
@@ -379,6 +437,22 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
const clampPercent = (value: number): number =>
Math.min(100, Math.max(0, value));
// The element's position once its center moved by dx/dy (percent), which is
// kept on the image.
const movedPosition = (
start: Placement,
dx: number,
dy: number
): ElementPosition => {
const moveX = clampPercent(start.centerX + dx) - start.centerX;
const moveY = clampPercent(start.centerY + dy) - start.centerY;
// Right and bottom distances shrink as the element moves right or down.
return {
[start.anchors.x]: start.x + (start.anchors.x === "left" ? moveX : -moveX),
[start.anchors.y]: start.y + (start.anchors.y === "top" ? moveY : -moveY),
};
};
const isEditable = (node: EventTarget | undefined): boolean =>
node instanceof HTMLInputElement ||
node instanceof HTMLTextAreaElement ||
@@ -3,37 +3,110 @@ import type { LovelaceElementConfig } from "../../elements/types";
// A percentage, or a unitless zero.
const POSITION = /^([+-]?(\d+(\.\d*)?|\.\d+)%|0)$/;
// Whether the editor can move the element by writing percent `left`/`top`.
// Other placements (another `position`, `right`/`bottom`/`inset*`, px or
// calc() values) are left alone rather than converted. Conditional elements
// only wrap their children.
export const isMovableElement = (config: LovelaceElementConfig): boolean => {
const SIDES = ["left", "right", "top", "bottom"];
// The sides of the image an element is placed from.
export interface ElementAnchors {
x: "left" | "right";
y: "top" | "bottom";
}
// Distances in percent of the image, keyed by the side they are taken from.
export type ElementPosition = Partial<
Record<ElementAnchors["x"] | ElementAnchors["y"], number>
>;
// The sides the editor can move the element along by writing percent values
// to them: per axis the one the style sets, else left/top. Other placements
// (another `position`, both sides of an axis, `inset*`, px or calc() values)
// are left alone rather than converted. Conditional elements only wrap their
// children.
export const elementAnchors = (
config: LovelaceElementConfig
): ElementAnchors | undefined => {
const style: unknown = config.style ?? {};
if (
config.type === "conditional" ||
typeof style !== "object" ||
Array.isArray(style)
) {
return false;
return undefined;
}
const sides = new Set<string>();
// Sides with an empty key in another case. The card applies the keys in
// order, so such a key can remove the side the lowercase key sets.
const cleared = new Set<string>();
// YAML can hold numbers or null here, and CSS ignores the key case.
for (const [key, raw] of Object.entries(style as Record<string, unknown>)) {
const prop = key.toLowerCase();
const value = raw == null ? "" : String(raw).trim().toLowerCase();
if (prop === "left" || prop === "top") {
if (key !== prop || (value && !POSITION.test(value))) {
return false;
if (SIDES.includes(prop)) {
// An empty right or bottom is ignored in any key case.
if (
(key !== prop && (value || prop === "left" || prop === "top")) ||
(value && !POSITION.test(value))
) {
return undefined;
}
if (value) {
sides.add(prop);
} else if (key !== prop) {
cleared.add(prop);
}
} else if (prop === "position") {
if (value && value !== "absolute") {
return false;
return undefined;
}
} else if (prop.startsWith("inset")) {
// The card applies the keys in order, so an empty inset removes the
// sides the keys before it set.
if (value || (prop === "inset" && sides.size)) {
return undefined;
}
} else if (
(prop === "right" || prop === "bottom" || prop.startsWith("inset")) &&
value
) {
return false;
}
}
return true;
if (
(sides.has("left") && sides.has("right")) ||
(sides.has("top") && sides.has("bottom")) ||
[...cleared].some((side) => sides.has(side))
) {
return undefined;
}
return {
x: sides.has("right") ? "right" : "left",
y: sides.has("bottom") ? "bottom" : "top",
};
};
export const isMovableElement = (config: LovelaceElementConfig): boolean =>
elementAnchors(config) !== undefined;
// The element's style with the position written to the sides it is placed
// from, rounded to 0.1 %. Undefined when it can't be moved there.
export const movedStyle = (
config: LovelaceElementConfig,
position: ElementPosition
): Record<string, string> | undefined => {
const anchors = elementAnchors(config);
const x = anchors && position[anchors.x];
const y = anchors && position[anchors.y];
if (!anchors || x === undefined || y === undefined) {
return undefined;
}
const round = (value: number) => Math.round(value * 10) / 10;
const style = { ...config.style };
const keys = Object.keys(style);
// The card applies the keys in order, so a side before an empty inset goes
// behind it, or the inset removes it again. Others keep their place.
for (const side of [anchors.x, anchors.y]) {
const later = keys.slice(keys.indexOf(side) + 1);
if (later.some((key) => key.toLowerCase() === "inset")) {
delete style[side];
}
}
return {
...style,
[anchors.x]: `${round(x)}%`,
[anchors.y]: `${round(y)}%`,
};
};
@@ -26,7 +26,11 @@ import {
PICTURE_ELEMENTS_EDITOR_BRIDGE,
PictureElementsEditorBridge,
} from "../../cards/picture-elements/editor-bridge";
import { isMovableElement } from "../../cards/picture-elements/movable-element";
import type { ElementPosition } from "../../cards/picture-elements/movable-element";
import {
isMovableElement,
movedStyle,
} from "../../cards/picture-elements/movable-element";
import type { PictureElementsCardConfig } from "../../cards/types";
import type { LovelaceCardEditor } from "../../types";
import "../hui-sub-element-editor";
@@ -81,16 +85,7 @@ export class HuiPictureElementsCardEditor
private _bridge = new PictureElementsEditorBridge({
selectElement: (index) => this._selectElement(index),
moveElement: (index, left, top) =>
this._setElementPosition(index, left, top),
clickImage: (x, y) => {
if (
this._subElementEditorConfig?.type === "element" &&
this._subElementEditorConfig.index !== undefined
) {
this._setElementPosition(this._subElementEditorConfig.index, x, y);
}
},
moveElement: (index, position) => this._setElementPosition(index, position),
});
public connectedCallback(): void {
@@ -147,21 +142,14 @@ export class HuiPictureElementsCardEditor
this._subElementEditorConfig = { index, type: "element", elementConfig };
}
// left/top are in percent of the image.
private _setElementPosition(index: number, left: number, top: number): void {
// The position is in percent of the image.
private _setElementPosition(index: number, position: ElementPosition): void {
const elementConfig = this._config?.elements[index];
if (!elementConfig || !isMovableElement(elementConfig)) {
const style = elementConfig && movedStyle(elementConfig, position);
if (!elementConfig || !style) {
return;
}
const round = (value: number) => Math.round(value * 10) / 10;
const newElement: LovelaceElementConfig = {
...elementConfig,
style: {
...elementConfig.style,
left: `${round(left)}%`,
top: `${round(top)}%`,
},
};
const newElement: LovelaceElementConfig = { ...elementConfig, style };
const elements = this._config!.elements.concat();
elements[index] = newElement;
this._config = { ...this._config!, elements };
@@ -97,6 +97,7 @@ import {
markdownWithRepositoryContext,
repositoryUrl,
} from "../tools/markdown";
import { MARKETPLACE_NAME } from "../../../common/translations/name-placeholders";
// Repository pages live at /<id> below /repository, my links at /repository itself.
const repositoryIdFromRoute = (route: Route): string => route.path.substring(1);
@@ -495,7 +496,7 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
<hass-subpage
.narrow=${this.narrow}
back-path="/marketplace"
.header=${this._i18n.localize("ui.panel.marketplace.title")}
.header=${MARKETPLACE_NAME}
>
<ha-dropdown
slot="toolbar-icon"
+67 -27
View File
@@ -17,7 +17,6 @@
"climate": "Climate",
"home": "Overview",
"maintenance": "Maintenance",
"marketplace": "Marketplace",
"notfound": "Page not found"
},
"state": {
@@ -1378,6 +1377,21 @@
"select_row": "Select {name}",
"select_row_generic": "Select row"
},
"camera-player": {
"play": "Play",
"mute": "Mute",
"unmute": "Unmute",
"picture_in_picture": "Picture in picture",
"exit_picture_in_picture": "Exit picture in picture",
"fullscreen": "Full screen",
"exit_fullscreen": "Exit full screen",
"reset_zoom": "Reset zoom",
"zoom_hint": "Use {modifier} + scroll to zoom",
"connecting": "Connecting",
"stream_info": "Streaming with {type}. Show connection details",
"stream_info_connecting": "Connecting to the camera. Show connection details",
"stream_info_upgrading": "Streaming with {type}, connecting with {upgrading} in the background. Show connection details"
},
"web-rtc-player": {
"not_supported": "WebRTC is not supported in this browser.",
"start_failed": "Failed to start the WebRTC stream: {message}",
@@ -1735,6 +1749,9 @@
"show": "Show {label}",
"hide": "Hide {label}"
},
"list-item-option": {
"partly_selected": "Partly selected"
},
"form-optional-actions": {
"add": "Add interaction"
},
@@ -2811,6 +2828,20 @@
"skip": "Skip and finish"
}
},
"camera_stream_info": {
"title": "Stream connection",
"intro": "Home Assistant starts with the connection that works most reliably and switches to a faster one as soon as it is ready.",
"still_images_only": "This camera has no video stream, so it shows a series of still images.",
"fallback_in_use": "The video streams of this camera could not be started, so still images are shown instead.",
"in_use": "In use",
"connecting": "Connecting",
"not_supported_count": "Not supported by this camera ({count})",
"description": {
"web_rtc": "Real-time video with the lowest delay, usually below a second. The video takes the most direct way from the camera to your device, which can need extra network setup when you are away from home. Needed to talk to the camera.",
"hls": "The video is sent in short pieces through Home Assistant. It works on almost every network and device, but is a few seconds behind. Used while WebRTC connects, or when WebRTC is not available.",
"mjpeg": "A series of still images, used when the camera has no video stream or the other connections failed. It has no sound."
}
},
"shortcuts": {
"title": "Shortcuts",
"enable_shortcuts_hint": "For keyboard shortcuts to work, make sure you have them enabled in your {user_profile}.",
@@ -3085,7 +3116,6 @@
"secondary": "Run extra applications next to Home Assistant"
},
"marketplace": {
"main": "Marketplace",
"secondary": "Install community integrations, dashboard content, themes, and templates"
},
"dashboards": {
@@ -8153,7 +8183,7 @@
"restart_confirm": "Restart Home Assistant to finish removing this integration",
"marketplace_uninstall": {
"title": "Also uninstall {name}?",
"text": "{name} came from the Marketplace. Its files stay on your system, and the Marketplace keeps checking for updates until you uninstall it.",
"text": "{name} came from the {marketplace}. Its files stay on your system, and the {marketplace} keeps checking for updates until you uninstall it.",
"confirm": "Uninstall",
"dismiss": "Keep",
"failed": "Uninstall failed. Check the Home Assistant logs for details."
@@ -10427,6 +10457,7 @@
"energy_usage_graph": {
"total_consumed": "Total {num} kWh",
"total_usage": "{num} kWh",
"total_cost": "Net grid cost {cost}",
"combined_from_grid": "Grid",
"consumed_solar": "Solar",
"consumed_battery": "Battery",
@@ -12785,7 +12816,17 @@
"migrate_success": "Theme settings migrated.",
"migrate_failed": "Failed to migrate theme settings.",
"theme_mode": "Theme mode",
"mode_set_by_theme": {
"light": "\"{theme}\" only has a light mode.",
"dark": "\"{theme}\" only has a dark mode.",
"none": "\"{theme}\" has fixed colors and doesn't switch between light and dark mode."
},
"colors": "Custom colors",
"colors_set_by_theme": {
"both": "Both colors are set by \"{theme}\".",
"primary": "The primary color is set by \"{theme}\".",
"accent": "The accent color is set by \"{theme}\"."
},
"dark_mode": {
"auto": "Auto",
"light": "Light",
@@ -13350,12 +13391,11 @@
"error_no_data": "You need to select some data sources first."
},
"marketplace": {
"title": "Marketplace",
"not_loaded": "The Marketplace is not available. It does not load in recovery mode or when it failed to start, check the Home Assistant logs for more information.",
"load_failed": "The Marketplace could not load its data: {error}",
"not_loaded": "The {marketplace} is not available. It does not load in recovery mode or when it failed to start, check the Home Assistant logs for more information.",
"load_failed": "The {marketplace} could not load its data: {error}",
"warning": {
"title": "Before you install from the Marketplace",
"intro": "Marketplace items are made by community contributors and are not reviewed by the Home\u00a0Assistant project. Treat them like plugins for any other software.",
"title": "Before you install from the {marketplace}",
"intro": "{marketplace} items are made by community contributors and are not reviewed by the Home\u00a0Assistant project. Treat them like plugins for any other software.",
"risks_title": "Anything you install can",
"risks": {
"access": "Access and control everything in Home\u00a0Assistant",
@@ -13391,23 +13431,23 @@
},
"dashboard": {
"search": "Search {number} {number, plural,\n one {repository}\n other {repositories}\n}",
"empty_header": "Nothing in the Marketplace yet",
"empty_text": "The Marketplace gets its list from the community catalog, which could not be reached yet. The list shows up here once it loads.",
"empty_header": "Nothing in the {marketplace} yet",
"empty_text": "The {marketplace} gets its list from the community catalog, which could not be reached yet. The list shows up here once it loads.",
"no_data": "No repositories matching search and filters",
"repository_not_found": "Repository not found"
},
"entry": {
"disabled": "The Marketplace is disabled. Enable it on the integration page to use it.",
"disabled": "The {marketplace} is disabled. Enable it on the integration page to use it.",
"open_integration": "Open integration page",
"failed": "The Marketplace could not be loaded, check the Home Assistant logs for more information.",
"failed_reason": "The Marketplace could not be loaded: {reason}",
"retrying": "The Marketplace could not start yet, retrying in a moment"
"failed": "The {marketplace} could not be loaded, check the Home Assistant logs for more information.",
"failed_reason": "The {marketplace} could not be loaded: {reason}",
"retrying": "The {marketplace} could not start yet, retrying in a moment"
},
"github": {
"connect": "Connect GitHub",
"add_repository_needs_github": "Connect GitHub to add the custom repository {repository}, then open the link again.",
"rate_limited_title": "GitHub limit reached",
"rate_limited": "GitHub limits how often the Marketplace can reach it without a GitHub connection. Try again later, or connect GitHub for a higher limit."
"rate_limited": "GitHub limits how often the {marketplace} can reach it without a GitHub connection. Try again later, or connect GitHub for a higher limit."
},
"column": {
"name": "Repository name",
@@ -13428,7 +13468,7 @@
"error": "An unknown error occurred",
"repository_not_found": "Repository {repository} not found",
"add_repository_title": "Add custom repository",
"add_repository_description": "Add the custom repository {repository} to the Marketplace?"
"add_repository_description": "Add the custom repository {repository} to the {marketplace}?"
},
"filters": {
"status": "Status",
@@ -13437,7 +13477,7 @@
},
"dialog_custom_repositories": {
"title": "Add from a GitHub link",
"intro": "Add something that is not in the Marketplace yet, straight from its page on GitHub. Like everything in the Marketplace, it is made by the community and not tested or reviewed by the Home Assistant project.",
"intro": "Add something that is not in the {marketplace} yet, straight from its page on GitHub. Like everything in the {marketplace}, it is made by the community and not tested or reviewed by the Home Assistant project.",
"link": "GitHub link",
"link_helper": "The address of its page on GitHub, like https://github.com/owner/name",
"type": "Type",
@@ -13452,10 +13492,10 @@
"github": "GitHub repository",
"no_repositories": "You have not added any repositories from a link yet.",
"remove_title": "Remove {name} from the list?",
"remove_text": "It no longer shows in the Marketplace. You can add it again later.",
"remove_text": "It no longer shows in the {marketplace}. You can add it again later.",
"remove_installed": "Uninstall it first",
"remove_selected_title": "Remove selected repositories?",
"remove_selected_text": "{count, plural,\n one {The selected repository no longer shows in the Marketplace. You can add it again later.}\n other {The {count} selected repositories no longer show in the Marketplace. You can add them again later.}\n}",
"remove_selected_text": "{count, plural,\n one {The selected repository no longer shows in the {marketplace}. You can add it again later.}\n other {The {count} selected repositories no longer show in the {marketplace}. You can add them again later.}\n}",
"remove_failed_title": "Remove failed",
"remove_failed": "Some repositories could not be removed."
},
@@ -13589,9 +13629,9 @@
},
"uninstall": {
"title": "Uninstall {name}?",
"message": "This removes the files the Marketplace installed for it.",
"message": "This removes the files the {marketplace} installed for it.",
"selected_title": "Uninstall selected repositories?",
"selected": "{count, plural,\n one {The selected repository will be uninstalled. This removes the files the Marketplace installed for it.}\n other {The {count} selected repositories will be uninstalled. This removes the files the Marketplace installed for them.}\n}",
"selected": "{count, plural,\n one {The selected repository will be uninstalled. This removes the files the {marketplace} installed for it.}\n other {The {count} selected repositories will be uninstalled. This removes the files the {marketplace} installed for them.}\n}",
"selected_in_use": "{count, plural, one {The selected repository} other {The {count} selected repositories}} will be uninstalled. {in_use, plural, one {The setup of one of them} other {The setups of # of them}} will be deleted with their devices and entities. This cannot be undone.",
"check_failed_title": "Unable to check repositories",
"check_failed": "The setups of some selected repositories could not be verified.",
@@ -13599,17 +13639,17 @@
"failed": "Some repositories could not be uninstalled."
},
"disabled": {
"title": "The Marketplace is disabled",
"title": "The {marketplace} is disabled",
"reason": {
"invalid_token": "The GitHub connection no longer works. Reconfigure the Marketplace integration to connect GitHub again.",
"rate_limit": "The GitHub API rate limit has been reached. The Marketplace works again once the limit resets.",
"removed": "The Marketplace integration has been removed.",
"unknown": "The Marketplace is unavailable, check the Home Assistant logs for more information."
"invalid_token": "The GitHub connection no longer works. Reconfigure the {marketplace} integration to connect GitHub again.",
"rate_limit": "The GitHub API rate limit has been reached. The {marketplace} works again once the limit resets.",
"removed": "The {marketplace} integration has been removed.",
"unknown": "The {marketplace} is unavailable, check the Home Assistant logs for more information."
}
},
"in_use": {
"title": "{name} is in use",
"message": "{name} is still set up, and that setup runs on the files the Marketplace installed. Without them it would fail to load and leave its devices and entities behind. Delete it first, or let the Marketplace delete it and uninstall {name} for you.",
"message": "{name} is still set up, and that setup runs on the files the {marketplace} installed. Without them it would fail to load and leave its devices and entities behind. Delete it first, or let the {marketplace} delete it and uninstall {name} for you.",
"ignored": "Ignored",
"view_integration": "View integration",
"delete_and_uninstall": "Delete and uninstall",
+20
View File
@@ -40,4 +40,24 @@ describe("dropInvalidConditions", () => {
]);
expect(nested.conditions).toEqual([screen, undefined, 5]);
});
it("wraps a single condition mapping in an array", () => {
const condition = state as unknown as VisibilityCondition;
expect(dropInvalidConditions(condition)).toEqual([state]);
});
it("drops invalid children of a single condition mapping", () => {
const condition = {
condition: "or",
conditions: [screen, null],
} as unknown as VisibilityCondition;
expect(dropInvalidConditions(condition)).toEqual([
{ condition: "or", conditions: [screen] },
]);
});
it("drops a single value that is not a condition object", () => {
const condition = "screen" as unknown as VisibilityCondition;
expect(dropInvalidConditions(condition)).toEqual([]);
});
});
@@ -0,0 +1,185 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
applyThemesOnElement,
invalidateThemeCache,
} from "../../../src/common/dom/apply_themes_on_element";
import { normalizeLuminance } from "../../../src/common/color/palette";
import type { Theme, Themes } from "../../../src/data/ws-themes";
const PICKED_PRIMARY = "#e91e63";
const PICKED_ACCENT = "#4caf50";
// Themes from YAML are partial, the `Theme` type lists keys most themes set.
const asTheme = (variables: object) => variables as Theme;
const makeThemes = (themes: Record<string, Theme>): Themes => ({
default_theme: "default",
default_dark_theme: null,
themes,
darkMode: false,
theme: "default",
});
const apply = (
themes: Themes,
theme: string,
dark = false
): CSSStyleDeclaration => {
const element = document.createElement("div");
applyThemesOnElement(
element,
themes,
theme,
{ primaryColor: PICKED_PRIMARY, accentColor: PICKED_ACCENT, dark },
true
);
return element.style;
};
describe("applyThemesOnElement user colors", () => {
beforeEach(() => {
invalidateThemeCache();
});
it("applies picked colors and the primary palette to a theme that doesn't set them", () => {
const style = apply(
makeThemes({ oled: asTheme({ "primary-background-color": "#000000" }) }),
"oled"
);
expect(style.getPropertyValue("--primary-color")).toBe(PICKED_PRIMARY);
expect(style.getPropertyValue("--accent-color")).toBe(PICKED_ACCENT);
expect(style.getPropertyValue("--ha-color-primary-50")).not.toBe("");
expect(style.getPropertyValue("--primary-background-color")).toBe(
"#000000"
);
});
it("keeps a primary color set by the theme and still applies the picked accent", () => {
const style = apply(
makeThemes({ pink: asTheme({ "primary-color": "#ff00ff" }) }),
"pink"
);
expect(style.getPropertyValue("--primary-color")).toBe("#ff00ff");
expect(style.getPropertyValue("--accent-color")).toBe(PICKED_ACCENT);
});
it("treats a theme that sets primary palette keys as setting the primary color", () => {
const style = apply(
makeThemes({ palette: asTheme({ "ha-color-primary-40": "#123456" }) }),
"palette"
);
expect(style.getPropertyValue("--primary-color")).not.toBe(PICKED_PRIMARY);
expect(style.getPropertyValue("--ha-color-primary-40")).toBe("#123456");
});
it("reads theme colors from the active mode", () => {
const themes = makeThemes({
modes: asTheme({
modes: { light: {}, dark: { "primary-color": "#ff00ff" } },
}),
});
expect(apply(themes, "modes").getPropertyValue("--primary-color")).toBe(
PICKED_PRIMARY
);
expect(
apply(themes, "modes", true).getPropertyValue("--primary-color")
).toBe("#ff00ff");
});
it("only tints the dark mode header for the default theme", () => {
const themes = makeThemes({
oled: asTheme({ modes: { light: {}, dark: {} } }),
});
expect(
apply(themes, "default", true).getPropertyValue(
"--app-header-background-color"
)
).toMatch(/^#/);
expect(
apply(themes, "oled", true).getPropertyValue(
"--app-header-background-color"
)
).toBe("var(--sidebar-background-color)");
});
});
describe("applyThemesOnElement theme palette", () => {
beforeEach(() => {
invalidateThemeCache();
});
const applyTheme = (theme: Theme): CSSStyleDeclaration => {
const element = document.createElement("div");
applyThemesOnElement(element, makeThemes({ custom: theme }), "custom");
return element.style;
};
it("generates the palette from the theme primary color", () => {
const style = applyTheme(asTheme({ "primary-color": "#ff00ff" }));
expect(style.getPropertyValue("--ha-color-primary-50")).toBe(
normalizeLuminance("#ff00ff")
);
expect(style.getPropertyValue("--ha-color-primary-05")).not.toBe("");
expect(style.getPropertyValue("--ha-color-primary-90")).not.toBe("");
expect(style.getPropertyValue("--dark-primary-color")).not.toBe("");
});
it("parses named colors", () => {
const style = applyTheme(asTheme({ "primary-color": "pink" }));
expect(style.getPropertyValue("--primary-color")).toBe("pink");
expect(style.getPropertyValue("--ha-color-primary-50")).toBe(
normalizeLuminance("#ffc0cb")
);
});
it("doesn't recolor state icons or text on primary", () => {
const style = applyTheme(asTheme({ "primary-color": "#ff00ff" }));
expect(style.getPropertyValue("--state-icon-color")).toBe("");
expect(style.getPropertyValue("--text-primary-color")).toBe("");
});
it("keeps palette keys and shades the theme sets itself", () => {
const style = applyTheme(
asTheme({
"primary-color": "#ff00ff",
"dark-primary-color": "#330033",
})
);
expect(style.getPropertyValue("--dark-primary-color")).toBe("#330033");
expect(style.getPropertyValue("--ha-color-primary-50")).not.toBe("");
});
it("keeps the palette readable for a near black theme color", () => {
const style = applyTheme(asTheme({ "primary-color": "#111111" }));
expect(style.getPropertyValue("--primary-color")).toBe("#111111");
expect(style.getPropertyValue("--ha-color-primary-50")).toBe(
normalizeLuminance("#111111")
);
expect(style.getPropertyValue("--ha-color-primary-50")).not.toBe("#111111");
});
it("doesn't generate anything when the theme sets part of the palette", () => {
const style = applyTheme(
asTheme({ "primary-color": "#ff00ff", "ha-color-primary-40": "#123456" })
);
expect(style.getPropertyValue("--ha-color-primary-40")).toBe("#123456");
expect(style.getPropertyValue("--ha-color-primary-50")).toBe("");
});
it("skips colors it can't parse", () => {
const style = applyTheme(asTheme({ "primary-color": "var(--my-color)" }));
expect(style.getPropertyValue("--primary-color")).toBe("var(--my-color)");
expect(style.getPropertyValue("--ha-color-primary-50")).toBe("");
});
});
@@ -0,0 +1,69 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { whenDocumentVisible } from "../../../src/common/dom/when-document-visible";
describe("whenDocumentVisible", () => {
let hidden: boolean;
let cancel: (() => void) | undefined;
beforeEach(() => {
vi.useFakeTimers();
hidden = true;
vi.spyOn(document, "hidden", "get").mockImplementation(() => hidden);
});
afterEach(() => {
cancel?.();
vi.restoreAllMocks();
vi.useRealTimers();
});
it("runs the callback after thaw without lifecycle events", async () => {
const recover = vi.fn();
cancel = whenDocumentVisible(recover);
await vi.advanceTimersByTimeAsync(360000);
expect(recover).not.toHaveBeenCalled();
// The WebView changes visibility but emits no event when the screen wakes.
hidden = false;
await vi.advanceTimersByTimeAsync(1000);
expect(recover).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it.each(["visibilitychange", "resume", "focus"])(
"recovers immediately on %s when visible",
(type) => {
const recover = vi.fn();
cancel = whenDocumentVisible(recover);
hidden = false;
(type === "focus" ? window : document).dispatchEvent(new Event(type));
expect(recover).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(5000);
expect(recover).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
}
);
it("keeps reconnects suspended when a lifecycle event arrives while hidden", () => {
const recover = vi.fn();
cancel = whenDocumentVisible(recover);
document.dispatchEvent(new Event("resume"));
window.dispatchEvent(new Event("focus"));
vi.advanceTimersByTime(1000);
expect(recover).not.toHaveBeenCalled();
});
it("removes timers and listeners when cancelled", () => {
const recover = vi.fn();
cancel = whenDocumentVisible(recover);
cancel();
hidden = false;
document.dispatchEvent(new Event("visibilitychange"));
document.dispatchEvent(new Event("resume"));
window.dispatchEvent(new Event("focus"));
vi.advanceTimersByTime(1000);
expect(recover).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
});
});
@@ -253,6 +253,90 @@ describe("computeAttributeValueDisplay", () => {
expect(result).toBe("Media Player Attribute Name");
});
it("should return the translation of a group member", () => {
const localize = (key: string) =>
({
"component.member_platform.entity.light.member_key.state_attributes.effect.state.candle":
"Candle",
"component.switch_platform.entity.switch.switch_key.state_attributes.effect.state.candle":
"Switch candle",
})[key] || "";
const entities = {
"light.group": { platform: "group" },
"light.plain": { platform: "plain_platform" },
"switch.member": {
platform: "switch_platform",
translation_key: "switch_key",
},
"light.member": {
platform: "member_platform",
translation_key: "member_key",
},
} as unknown as HomeAssistant["entities"];
const stateObj = {
entity_id: "light.group",
attributes: {
entity_id: ["light.plain", "switch.member", "light.member"],
},
} as unknown as HassEntityBase;
expect(
computeAttributeValueDisplay(
localize,
stateObj,
localeMock,
configMock,
entities,
"effect",
"candle"
)
).toBe("Candle");
expect(
computeAttributeValueDisplay(
localize,
stateObj,
localeMock,
configMock,
entities,
"effect",
"fire"
)
).toBe("fire");
});
it("should return the translation of a member in group_entities", () => {
const localize = (key: string) =>
({
"component.member_platform.entity.light.member_key.state_attributes.effect.state.candle":
"Candle",
})[key] || "";
const entities = {
"light.integration_group": { platform: "integration_platform" },
"light.member": {
platform: "member_platform",
translation_key: "member_key",
},
} as unknown as HomeAssistant["entities"];
const stateObj = {
entity_id: "light.integration_group",
attributes: {
group_entities: ["light.member"],
},
} as unknown as HassEntityBase;
expect(
computeAttributeValueDisplay(
localize,
stateObj,
localeMock,
configMock,
entities,
"effect",
"candle"
)
).toBe("Candle");
});
it("should return attribute value", () => {
const stateObj = {
entity_id: "media_player.test",
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { computeLocalize } from "../../../src/common/translations/localize";
const localizeWith = (strings: Record<string, string>) =>
computeLocalize<string>(document.createElement("div"), "en", {
en: strings,
});
describe("computeLocalize", () => {
it("fills product names without the caller passing them", async () => {
const localize = await localizeWith({
key: "Nothing in the {marketplace} yet",
});
expect(localize("key")).toBe("Nothing in the Marketplace yet");
});
it("keeps the names next to the caller's values", async () => {
const localize = await localizeWith({
key: "{name} came from the {marketplace}",
});
expect(localize("key", { name: "Card" })).toBe(
"Card came from the Marketplace"
);
});
});
@@ -50,4 +50,22 @@ describe("parseAspectRatio", () => {
const r = parseAspectRatio("mary:lamb");
assert.equal(r, null);
});
it("Skips non-string input", () => {
// An unquoted `aspect_ratio: 16:9` in YAML is loaded as the number 969
assert.equal(parseAspectRatio(969 as unknown as string), null);
assert.equal(parseAspectRatio(1.78 as unknown as string), null);
});
it("Parses values with surrounding whitespace", () => {
assert.deepEqual(parseAspectRatio(" 16 : 9 "), ratio16by9);
assert.deepEqual(parseAspectRatio(" 23 % "), { w: 100, h: 23 });
});
it.each(["16/9", "16X9", "16x9x4", "16:9:4", "16x", "x9", "16abc", "23%x"])(
"Skips unhandled input %s",
(input) => {
assert.equal(parseAspectRatio(input), null);
}
);
});
+91
View File
@@ -0,0 +1,91 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { throttle } from "../../../src/common/util/throttle";
describe("throttle", () => {
beforeEach(() => {
vi.useFakeTimers({
toFake: ["setTimeout", "clearTimeout", "Date"],
shouldAdvanceTime: false,
});
vi.stubGlobal("window", {
...window,
setTimeout: globalThis.setTimeout,
clearTimeout: globalThis.clearTimeout,
});
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it("calls on the leading edge and once more on the trailing edge", () => {
const fn = vi.fn();
const throttled = throttle(fn, 500);
throttled("a");
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenLastCalledWith("a");
throttled("b");
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenLastCalledWith("b");
});
it("uses the latest arguments for the trailing call", () => {
const fn = vi.fn();
const throttled = throttle(fn, 500);
throttled("a");
throttled("b");
vi.advanceTimersByTime(100);
throttled("c");
vi.advanceTimersByTime(100);
throttled("d");
vi.advanceTimersByTime(300);
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenNthCalledWith(1, "a");
expect(fn).toHaveBeenNthCalledWith(2, "d");
});
it("uses the latest arguments when leading is disabled", () => {
const fn = vi.fn();
const throttled = throttle(fn, 500, false);
throttled("a");
throttled("b");
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenLastCalledWith("b");
});
it("does not call on the trailing edge when trailing is disabled", () => {
const fn = vi.fn();
const throttled = throttle(fn, 500, true, false);
throttled("a");
throttled("b");
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenLastCalledWith("a");
});
it("drops the pending trailing call on cancel", () => {
const fn = vi.fn();
const throttled = throttle(fn, 500);
throttled("a");
throttled("b");
throttled.cancel();
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(1);
throttled("c");
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenLastCalledWith("c");
});
});
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import {
clampZoomPan,
panBy,
ZOOM_PAN_IDENTITY,
zoomAtPoint,
} from "../../../src/components/camera/zoom-pan";
const size = { width: 400, height: 300 };
// A wrong transform shows black bars next to the picture, or zooms away from
// what the user pointed at
describe("zoomAtPoint", () => {
it("keeps the point under the cursor in place", () => {
const zoomed = zoomAtPoint(ZOOM_PAN_IDENTITY, 2, { x: 100, y: 75 }, size);
expect(zoomed).toEqual({ scale: 2, x: -100, y: -75 });
// The content point under the cursor stays at the same screen position
expect((100 - zoomed.x) / zoomed.scale).toBe(100 / 1);
});
it("does not zoom out further than the whole picture", () => {
const zoomed = zoomAtPoint(
{ scale: 2, x: -100, y: -75 },
0.5,
{ x: 0, y: 0 },
size
);
expect(zoomed).toEqual(ZOOM_PAN_IDENTITY);
});
it("stops at the maximum zoom", () => {
expect(
zoomAtPoint(ZOOM_PAN_IDENTITY, 50, { x: 0, y: 0 }, size, 4).scale
).toBe(4);
});
it("keeps the picture covering the viewport at the edges", () => {
// Zooming at the bottom right corner can't move the picture past it
expect(zoomAtPoint(ZOOM_PAN_IDENTITY, 2, { x: 400, y: 300 }, size)).toEqual(
{ scale: 2, x: -400, y: -300 }
);
});
});
describe("panBy", () => {
it("pans within the zoomed in picture", () => {
expect(panBy({ scale: 2, x: -100, y: -100 }, 50, -20, size)).toEqual({
scale: 2,
x: -50,
y: -120,
});
});
it("stops at the edges", () => {
expect(panBy({ scale: 2, x: -100, y: -100 }, 500, -500, size)).toEqual({
scale: 2,
x: 0,
y: -300,
});
});
it("does not pan when not zoomed in", () => {
expect(panBy(ZOOM_PAN_IDENTITY, 50, 50, size)).toEqual(ZOOM_PAN_IDENTITY);
});
});
describe("clampZoomPan", () => {
it("resets below the original size", () => {
expect(clampZoomPan({ scale: 0.8, x: 10, y: 10 }, size)).toEqual(
ZOOM_PAN_IDENTITY
);
});
});
@@ -412,12 +412,12 @@ exports[`downSampleLineData > large scale digest is stable 1`] = `
96.917,
],
"last": [
1707066870000,
220.635,
1707067170000,
203.318,
],
"numberCount": 3336,
"numberSum": "2.84488807401e+15",
"size": 1668,
"numberCount": 3338,
"numberSum": "2.84659514118e+15",
"size": 1669,
"type": "array",
}
`;
@@ -1046,6 +1046,10 @@ exports[`downSampleLineData > min/max mode matches characterization snapshot 1`]
1704076140000,
43.606,
],
[
1704076170000,
46.641,
],
]
`;
+43 -1
View File
@@ -216,7 +216,11 @@ describe("downSampleLineData", () => {
result.forEach(([x, y]) => {
const values = framed.get(Math.floor(x / FRAME));
expect(values).toBeDefined();
expect([Math.min(...values!), Math.max(...values!)]).toContain(y);
expect([
Math.min(...values!),
Math.max(...values!),
values![values!.length - 1],
]).toContain(y);
});
});
@@ -259,6 +263,7 @@ describe("downSampleLineData", () => {
expect(downSampleLineData(points, 3)).toEqual([
[FIXED_EPOCH_MS + 1_000, 10],
[FIXED_EPOCH_MS + 2_000, 90],
[FIXED_EPOCH_MS + 3_000, 60],
[FIXED_EPOCH_MS + 30_000, 55],
[FIXED_EPOCH_MS + 31_000, 45],
]);
@@ -300,6 +305,43 @@ describe("downSampleLineData", () => {
]);
});
it("keeps a frame's last value when the next point is frames away", () => {
// Step lines hold the last value until the next point. Dropping the
// final 0 held the 5.9 peak for an hour (#56062).
const start = FIXED_EPOCH_MS - (FIXED_EPOCH_MS % 300_000);
const points: GappedPoint[] = [
[start + 2_000, 0],
[start + 7_000, 5.9],
[start + 10_000, 0],
[start + 16_000, 3.2],
[start + 46_000, 3.7],
[start + 76_000, 3.3],
[start + 106_000, 0],
[start + 3_600_000, null],
[start + 3_600_400, 0],
];
expect(downSampleLineData(points, 8)).toEqual([
[start + 2_000, 0],
[start + 7_000, 5.9],
[start + 106_000, 0],
[start + 3_600_400, 0],
]);
});
it("does not repeat a frame's minimum when it shares its x with the max", () => {
const points: GappedPoint[] = [
[FIXED_EPOCH_MS, 90],
[FIXED_EPOCH_MS, 10],
[FIXED_EPOCH_MS + 30_000, 55],
[FIXED_EPOCH_MS + 31_000, 45],
];
expect(downSampleLineData(points, 3)).toEqual([
[FIXED_EPOCH_MS, 10],
[FIXED_EPOCH_MS + 30_000, 55],
[FIXED_EPOCH_MS + 31_000, 45],
]);
});
it("keeps a gap marker whose frame holds no values", () => {
const points: GappedPoint[] = [
[FIXED_EPOCH_MS, 50],
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { computeLocationSelectorValue } from "../../../src/components/ha-selector/compute-location-selector-value";
describe("computeLocationSelectorValue", () => {
it("rounds an edited radius", () => {
expect(
computeLocationSelectorValue(
{ location: { radius: true } },
{ latitude: 1, longitude: 2, radius: 600.4 }
)
).toEqual({ latitude: 1, longitude: 2, radius: 600 });
});
it("falls back to the default radius the map shows", () => {
expect(
computeLocationSelectorValue(
{ location: { radius: true } },
{ latitude: 3, longitude: 2 }
)
).toEqual({ latitude: 3, longitude: 2, radius: 1000 });
});
it("leaves out a radius the user cleared", () => {
expect(
computeLocationSelectorValue(
{ location: { radius: true } },
{ latitude: 3, longitude: 2, radius: undefined }
)
).toEqual({ latitude: 3, longitude: 2 });
});
it("keeps a read-only radius unrounded", () => {
expect(
computeLocationSelectorValue(
{ location: { radius: true, radius_readonly: true } },
{ latitude: 3, longitude: 2, radius: 65.5 }
)
).toEqual({ latitude: 3, longitude: 2, radius: 65.5 });
});
it("leaves out the radius when the selector has none", () => {
expect(
computeLocationSelectorValue(
{ location: {} },
{ latitude: 3, longitude: 2, radius: 500 }
)
).toEqual({ latitude: 3, longitude: 2 });
});
});
+55
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
computeCameraStreamStatus,
selectCameraStreams,
type CameraStreamSelectionOptions,
} from "../../src/data/camera-streams";
@@ -43,3 +44,57 @@ describe("selectCameraStreams", () => {
expect(select({ webRtcStreams: failed, hlsStreams: failed })).toBe("mjpeg");
});
});
// The badge over the player tells the user how the stream is connected
describe("computeCameraStreamStatus", () => {
const hlsLoading = [
{ type: "hls" as const, visible: true },
{ type: "web_rtc" as const, visible: false },
];
it("connects until the shown stream plays", () => {
expect(computeCameraStreamStatus([], new Set())).toEqual({
connecting: true,
hasAudio: false,
});
expect(computeCameraStreamStatus(hlsLoading, new Set(), ok)).toEqual({
type: "hls",
connecting: true,
upgrading: undefined,
hasAudio: false,
});
});
it("shows WebRTC connecting in the background while HLS plays", () => {
expect(computeCameraStreamStatus(hlsLoading, new Set(["hls"]), ok)).toEqual(
{
type: "hls",
connecting: false,
upgrading: "web_rtc",
hasAudio: true,
}
);
});
it("takes the sound of the shown stream", () => {
expect(
computeCameraStreamStatus(
[{ type: "web_rtc", visible: true }],
new Set(["web_rtc"]),
ok,
silent
)
).toEqual({
type: "web_rtc",
connecting: false,
upgrading: undefined,
hasAudio: false,
});
expect(
computeCameraStreamStatus(
[{ type: "mjpeg", visible: true }],
new Set(["mjpeg"])
).hasAudio
).toBe(false);
});
});
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { filtersMatchUnassignedItem } from "../../src/data/data_table_filters";
describe("filtersMatchUnassignedItem", () => {
it("matches when no filter has a selection", () => {
expect(filtersMatchUnassignedItem({})).toBe(true);
expect(
filtersMatchUnassignedItem({
"ha-filter-labels": [],
"ha-filter-devices": undefined,
"ha-filter-floor-areas": {},
})
).toBe(true);
expect(
filtersMatchUnassignedItem({
"ha-filter-floor-areas": { areas: [], floors: [], no_area: false },
})
).toBe(true);
});
it("matches a No area selection, also next to selected areas", () => {
expect(
filtersMatchUnassignedItem({ "ha-filter-floor-areas": { no_area: true } })
).toBe(true);
expect(
filtersMatchUnassignedItem({
"ha-filter-floor-areas": { areas: ["kitchen"], no_area: true },
})
).toBe(true);
});
it("leaves the item out when an id is selected", () => {
expect(filtersMatchUnassignedItem({ "ha-filter-labels": ["energy"] })).toBe(
false
);
expect(
filtersMatchUnassignedItem({
"ha-filter-floor-areas": { floors: ["ground"] },
})
).toBe(false);
});
it("needs every filter to match", () => {
expect(
filtersMatchUnassignedItem({
"ha-filter-floor-areas": { no_area: true },
"ha-filter-categories": ["lights"],
})
).toBe(false);
});
});
+74
View File
@@ -12,6 +12,7 @@ import {
TimeZone,
} from "../../src/data/translation";
import {
calculateGridNetCost,
computeConsumptionSingle,
computeEnergyLabel,
computeEnergyDeviceLabels,
@@ -32,6 +33,7 @@ import {
import type {
EnergyData,
EnergyPreferences,
GridSourceTypeEnergyPreference,
EnergySource,
EnergySumData,
} from "../../src/data/energy";
@@ -2868,3 +2870,75 @@ describe("computeConsumptionData with a home meter", () => {
assert.equal(consumption.used_grid[1], baseline.used_grid[1]);
});
});
describe("calculateGridNetCost", () => {
const grid = (
overrides: Partial<GridSourceTypeEnergyPreference>
): GridSourceTypeEnergyPreference => ({
type: "grid",
stat_energy_from: "sensor.import",
stat_energy_to: "sensor.export",
stat_cost: null,
entity_energy_price: null,
number_energy_price: null,
stat_compensation: null,
entity_energy_price_export: null,
number_energy_price_export: null,
cost_adjustment_day: 0,
...overrides,
});
const series = (...changes: (number | null)[]) =>
changes.map((change, i) => ({ start: i, end: i + 1, change }));
const info = {
cost_sensors: {
"sensor.import": "sensor.import_cost",
"sensor.export": "sensor.export_compensation",
},
solar_forecast_domains: [],
};
it("subtracts export compensation from import cost", () => {
assert.equal(
calculateGridNetCost([grid({})], info, {
"sensor.import": series(2, 3),
"sensor.import_cost": series(1, 1.5),
"sensor.export": series(4),
"sensor.export_compensation": series(0.5),
}),
2
);
});
it("prefers configured cost statistics over generated cost sensors", () => {
assert.equal(
calculateGridNetCost(
[grid({ stat_cost: "sensor.my_cost", stat_energy_to: null })],
info,
{
"sensor.import": series(2),
"sensor.import_cost": series(9),
"sensor.my_cost": series(1.25),
}
),
1.25
);
});
it("returns undefined without cost statistics or period data", () => {
assert.isUndefined(
calculateGridNetCost(
[grid({})],
{ ...info, cost_sensors: {} },
{
"sensor.import": series(2),
}
)
);
assert.isUndefined(
calculateGridNetCost([grid({})], info, {
"sensor.import": series(null),
"sensor.import_cost": series(null),
})
);
});
});
+48
View File
@@ -1,9 +1,11 @@
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import { describe, expect, it } from "vitest";
import {
computeGroupMemberEntries,
computeGroupMemberIds,
filterGroupsWithListedMembers,
} from "../../src/data/group";
import type { HomeAssistant } from "../../src/types";
const entity = (
entity_id: string,
@@ -74,6 +76,52 @@ describe("computeGroupMemberIds", () => {
});
});
describe("computeGroupMemberEntries", () => {
const entities = {
"light.member": {
entity_id: "light.member",
platform: "member_platform",
translation_key: "member_key",
},
"light.no_platform": {
entity_id: "light.no_platform",
translation_key: "member_key",
},
"light.no_translation_key": {
entity_id: "light.no_translation_key",
platform: "member_platform",
},
"switch.member": {
entity_id: "switch.member",
platform: "member_platform",
translation_key: "member_key",
},
} as unknown as HomeAssistant["entities"];
it("keeps same-domain members with translations", () => {
expect(
computeGroupMemberEntries(
entity("light.group", {
entity_id: [
"light.member",
"light.no_platform",
"light.no_translation_key",
"light.unknown",
"switch.member",
],
}),
entities
)
).toEqual([entities["light.member"]]);
});
it("not a group: no members", () => {
expect(computeGroupMemberEntries(entity("light.lamp"), entities)).toEqual(
[]
);
});
});
describe("filterGroupsWithListedMembers", () => {
const lamp = entity("light.lamp");
const ceiling = entity("light.ceiling");
+136
View File
@@ -0,0 +1,136 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { describe, expect, it, vi } from "vitest";
import type { HomeAssistant } from "../../src/types";
vi.hoisted(() => {
Object.assign(globalThis, { __BACKWARDS_COMPAT__: false });
});
const { attributeIcon } = await import("../../src/data/icons");
const ICONS = {
entity: {
member_platform: {
light: {
member_key: {
state_attributes: {
effect: {
default: "mdi:member-default",
state: { candle: "mdi:candle" },
},
level: {
default: "mdi:member-default",
range: { "0": "mdi:level-low", "50": "mdi:level-high" },
},
},
},
},
},
},
entity_component: {
light: {
_: {
default: "mdi:lightbulb",
state_attributes: {
effect: { default: "mdi:circle-medium", state: {} },
},
},
},
},
};
const connection = {
haVersion: "2026.11.0",
sendMessagePromise: async (message: {
category: "entity" | "entity_component";
integration?: string;
}) => {
if (message.integration === "failing_platform") {
throw new Error("Icons not available");
}
return { resources: ICONS[message.category] };
},
} as unknown as HomeAssistant["connection"];
const config = {
components: ["light", "member_platform", "failing_platform"],
} as unknown as HomeAssistant["config"];
const entities = {
"light.group": { platform: "group" },
"light.member": {
platform: "member_platform",
translation_key: "member_key",
},
"light.failing_member": {
platform: "failing_platform",
translation_key: "failing_key",
},
} as unknown as HomeAssistant["entities"];
const groupState = {
entity_id: "light.group",
attributes: { entity_id: ["light.member"] },
} as unknown as HassEntity;
describe("attributeIcon", () => {
it("uses the icon of a group member for the value", async () => {
expect(
await attributeIcon(
config,
connection,
entities,
groupState,
"effect",
"candle"
)
).toBe("mdi:candle");
});
it("does not use the default icon of a group member", async () => {
expect(
await attributeIcon(
config,
connection,
entities,
groupState,
"effect",
"fire"
)
).toBe("mdi:circle-medium");
});
it("uses the range icon of a group member for a numeric value", async () => {
expect(
await attributeIcon(
config,
connection,
entities,
groupState,
"level",
"60"
)
).toBe("mdi:level-high");
});
it("continues when the icons of a group member fail to load", async () => {
const state = {
entity_id: "light.group",
attributes: { entity_id: ["light.failing_member", "light.member"] },
} as unknown as HassEntity;
expect(
await attributeIcon(
config,
connection,
entities,
state,
"effect",
"candle"
)
).toBe("mdi:candle");
expect(
await attributeIcon(config, connection, entities, state, "effect", "fire")
).toBe("mdi:circle-medium");
});
});
+34
View File
@@ -10,6 +10,7 @@ class TestRouter extends HassRouterPage {
routes: {
immediate: { tag: "test-immediate-panel" },
deferred: { tag: "test-deferred-panel", waitForReady: true },
redirected: { tag: "test-redirected-panel", waitForReady: true },
loaded: {
tag: "test-loaded-panel",
load: () => loadedPanelImport,
@@ -29,6 +30,10 @@ class DeferredPanel extends ReactiveElement {
@state() public loaded = false;
}
class RedirectedPanel extends HTMLElement {}
customElements.define("test-redirected-panel", RedirectedPanel);
let resolveLoadedPanelImport: () => void;
const loadedPanelImport = new Promise<void>((resolve) => {
resolveLoadedPanelImport = resolve;
@@ -237,6 +242,34 @@ describe("HassRouterPage panel readiness", () => {
panelIsReady(element.lastElementChild as HTMLElement);
await expect(element.rendered).resolves.toBeUndefined();
});
it("waits for the panel that replaces one before it was ready", async () => {
const element = await mountRouter("/deferred");
let ready = false;
element.rendered.then(() => {
ready = true;
});
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
// The panel redirects, as a dashboard can, before it is ready, so it
// never will be
element.route = { prefix: "", path: "/redirected" };
await element.updateComplete;
expect(ready).toBe(false);
const redirected = element.querySelector("test-redirected-panel");
if (!redirected) {
throw new Error("The redirected panel was not created");
}
panelIsReady(redirected);
await vi.waitFor(() => {
expect(ready).toBe(true);
});
});
});
describe("HassRouterPage update propagation during load", () => {
@@ -492,6 +525,7 @@ declare global {
"test-router": TestRouter;
"test-immediate-panel": ImmediatePanel;
"test-deferred-panel": DeferredPanel;
"test-redirected-panel": RedirectedPanel;
"test-loaded-panel": LoadedPanel;
"test-prop-router": PropRouter;
"test-prop-panel": PropPanel;
@@ -10,7 +10,6 @@ const makeBridge = () =>
new PictureElementsEditorBridge({
selectElement: vi.fn(),
moveElement: vi.fn(),
clickImage: vi.fn(),
});
describe("PictureElementsEditorBridge", () => {
@@ -7,13 +7,16 @@ import type {
} from "../../../../../src/panels/lovelace/elements/types";
// The image is 400x300 px; elements are placed by inline left/top in px, which
// is what getComputedStyle reports for them.
// is what getComputedStyle reports for them. jsdom has no layout, so the
// image's computed size comes from its inline size as well.
const setup = ({
configs = [{ type: "icon" }] as LovelaceElementConfig[],
active = true,
selectedIndex = undefined as number | undefined,
} = {}) => {
const root = document.createElement("div");
root.style.width = "400px";
root.style.height = "300px";
root.getBoundingClientRect = () => new DOMRect(0, 0, 400, 300);
Object.defineProperty(root, "offsetWidth", { value: 400 });
Object.defineProperty(root, "offsetHeight", { value: 300 });
@@ -25,6 +28,9 @@ const setup = ({
el.style.left = "100px";
el.style.top = "60px";
el.getBoundingClientRect = () => new DOMRect(88, 48, 24, 24);
// Rendered, unlike in jsdom.
el.getClientRects = () =>
[el.getBoundingClientRect()] as unknown as DOMRectList;
root.appendChild(el);
return el;
});
@@ -44,7 +50,6 @@ const setup = ({
const handlers = {
selectElement: vi.fn(),
moveElement: vi.fn(),
clickImage: vi.fn(),
};
const bridge = new PictureElementsEditorBridge(handlers);
bridge.setState(active, selectedIndex);
@@ -134,7 +139,7 @@ describe("PictureElementsEditorPreviewController", () => {
const { elements, handlers, gesture } = setup();
gesture(elements[0], [100, 60], [140, 90]);
// +40px of 400px and +30px of 300px from 25%/20%.
expect(handlers.moveElement).toHaveBeenCalledWith(0, 35, 30);
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 35, top: 30 });
expect(elements[0].style.left).toBe("35%");
expect(handlers.selectElement).not.toHaveBeenCalled();
});
@@ -142,7 +147,104 @@ describe("PictureElementsEditorPreviewController", () => {
it("keeps a dragged element on the image", () => {
const { elements, handlers, gesture } = setup();
gesture(elements[0], [100, 60], [-500, 900]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, 0, 100);
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 0, top: 100 });
});
describe("elements placed from the right or bottom", () => {
// 300px from the right and 240px from the bottom, where left/top put it.
// The card's transform centers an element on its left/top point only, so
// from the right or bottom its center is its own size further left or up.
const setupFrom = (style: Record<string, string>) => {
const test = setup({ configs: [{ type: "icon", style }] });
const element = test.elements[0];
element.style.right = "300px";
element.style.bottom = "240px";
element.getBoundingClientRect = () =>
new DOMRect(style.right ? 64 : 88, style.bottom ? 24 : 48, 24, 24);
return test;
};
it.each([
[
{ right: "75%", bottom: "80%" },
{ right: 65, bottom: 70 },
],
[
{ left: "25%", bottom: "80%" },
{ left: 35, bottom: 70 },
],
[
{ right: "75%", top: "20%" },
{ right: 65, top: 30 },
],
])("moves an element styled %j along its sides", (style, moved) => {
const { elements, handlers, gesture } = setupFrom(style);
// +40px of 400px and +30px of 300px.
gesture(elements[0], [100, 60], [140, 90]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, moved);
for (const [prop, value] of Object.entries(moved)) {
expect(elements[0].style.getPropertyValue(prop)).toBe(`${value}%`);
}
});
// The center goes from 19%/12% to the top left or bottom right corner.
it.each([
[[-500, -500], { right: 94, bottom: 92 }],
[[900, 900], { right: -6, bottom: -8 }],
])(
"keeps the center of an element dragged to %j on the image",
(to, moved) => {
const { elements, handlers, gesture } = setupFrom({
right: "75%",
bottom: "80%",
});
gesture(elements[0], [100, 60], to as [number, number]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, moved);
}
);
it("moves an element placed past a side of the image", () => {
const { elements, handlers, gesture } = setupFrom({
right: "-5%",
top: "20%",
});
// 20px past the right side, which puts its center 4px inside.
elements[0].style.right = "-20px";
elements[0].getBoundingClientRect = () => new DOMRect(384, 48, 24, 24);
gesture(elements[0], [396, 60], [388, 60]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
right: -3,
top: 20,
});
});
it("moves the element's center to a click on the image", () => {
const { root, bridge, handlers, gesture } = setupFrom({
right: "75%",
bottom: "80%",
});
bridge.setState(true, 0);
// From 19%/12% to 50%/25%.
gesture(root, [200, 75]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
right: 44,
bottom: 67,
});
});
it("puts an element back when the drag is cancelled", () => {
const { root, elements, pointer } = setupFrom({
right: "75%",
bottom: "80%",
});
pointer("pointerdown", elements[0], 100, 60);
pointer("pointermove", root, 140, 90);
pointer("pointercancel", root, 140, 90);
expect(elements[0].style.right).toBe("75%");
expect(elements[0].style.bottom).toBe("80%");
expect(elements[0].style.left).toBe("100px");
expect(elements[0].style.top).toBe("60px");
});
});
it("only drags a large overlay once it is selected", () => {
@@ -154,14 +256,14 @@ describe("PictureElementsEditorPreviewController", () => {
bridge.setState(true, 0);
gesture(elements[0], [100, 60], [140, 90]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, 35, 30);
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 35, top: 30 });
});
it("never drags elements it can't write back", () => {
const { elements, handlers, gesture } = setup({
configs: [
{ type: "conditional" },
{ type: "icon", style: { right: "5%" } },
{ type: "icon", style: { left: "5%", right: "5%" } },
{ type: "icon", style: { left: "100px" } },
],
});
@@ -196,6 +298,20 @@ describe("PictureElementsEditorPreviewController", () => {
expect(handlers.moveElement).not.toHaveBeenCalled();
});
it("puts an element back whose sides changed during the drag", () => {
const configs: LovelaceElementConfig[] = [
{ type: "icon", style: { left: "25%", top: "20%" } },
];
const { root, elements, handlers, pointer } = setup({ configs });
pointer("pointerdown", elements[0], 100, 60);
pointer("pointermove", root, 140, 90);
configs[0] = { type: "icon", style: { right: "75%", top: "20%" } };
pointer("pointerup", root, 140, 90);
expect(handlers.moveElement).not.toHaveBeenCalled();
expect(elements[0].style.left).toBe("");
expect(elements[0].style.top).toBe("20%");
});
it("puts an element placed at a YAML zero back when cancelled", () => {
const { root, elements, pointer } = setup({
configs: [{ type: "icon", style: { left: 0 as never, top: "20%" } }],
@@ -230,16 +346,117 @@ describe("PictureElementsEditorPreviewController", () => {
expect(handlers.moveElement).not.toHaveBeenCalled();
});
it("reports a click on the image in percent", () => {
const { root, handlers, gesture } = setup();
it("moves the selected element's center to a click on the image", () => {
const { root, bridge, handlers, gesture } = setup();
gesture(root, [200, 75]);
expect(handlers.clickImage).toHaveBeenCalledWith(50, 25);
expect(handlers.moveElement).not.toHaveBeenCalled();
bridge.setState(true, 0);
gesture(root, [200, 75]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 50, top: 25 });
});
describe("an image with a fractional size", () => {
// Its height is its width times the aspect ratio, while offsetWidth and
// offsetHeight stay rounded to 400x300. The element is at 25%/25%.
const setupFractional = (selectedIndex?: number) => {
const test = setup({ selectedIndex });
test.root.style.width = "399.5px";
test.root.style.height = "300.5px";
test.root.getBoundingClientRect = () => new DOMRect(0, 0, 399.5, 300.5);
const element = test.elements[0];
element.style.left = "99.875px";
element.style.top = "75.125px";
element.getBoundingClientRect = () => new DOMRect(87.875, 63.125, 24, 24);
return test;
};
it("moves the selected element's center exactly to a click", () => {
const { root, handlers, gesture } = setupFractional(0);
gesture(root, [99.875, 75.125]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
left: 25,
top: 25,
});
});
it("stops a dragged element exactly at a side of the image", () => {
const { elements, handlers, gesture } = setupFractional();
gesture(elements[0], [99.875, 75.125], [-500, 75.125]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
left: 0,
top: 25,
});
});
});
describe("an image scaled by an ancestor", () => {
// Laid out at 400x300 px but shown at 320x240 px, like under scale(0.8).
// The element's computed left/top stay in layout px (25%/20%), while its
// rect is scaled like the image's.
const setupScaled = (selectedIndex?: number) => {
const test = setup({
configs: [{ type: "icon", style: { left: "25%", top: "20%" } }],
selectedIndex,
});
test.root.getBoundingClientRect = () => new DOMRect(0, 0, 320, 240);
test.elements[0].getBoundingClientRect = () =>
new DOMRect(72, 40, 16, 16);
return test;
};
it("moves the selected element's center to a click", () => {
const { root, handlers, gesture } = setupScaled(0);
gesture(root, [160, 120]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
left: 50,
top: 50,
});
});
it("moves a dragged element by the pointer delta", () => {
const { elements, handlers, gesture } = setupScaled();
// +40 of 320 visual px.
gesture(elements[0], [80, 48], [120, 48]);
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
left: 37.5,
top: 20,
});
expect(elements[0].style.left).toBe("37.5%");
});
});
it("leaves elements alone while the image has no height", () => {
const { root, elements, handlers, gesture } = setup({ selectedIndex: 0 });
root.style.height = "0px";
root.getBoundingClientRect = () => new DOMRect(0, 0, 400, 0);
gesture(elements[0], [100, 60], [140, 90]);
gesture(root, [200, 0]);
expect(handlers.moveElement).not.toHaveBeenCalled();
expect(elements[0].style.left).toBe("100px");
});
it("leaves a selected element alone while it is hidden", () => {
const { root, elements, handlers, gesture } = setup({
configs: [{ type: "icon", style: { left: "50%", top: "50%" } }],
selectedIndex: 0,
});
// With display: none it has no layout, and its computed left/top stay in
// percent.
elements[0].style.left = "50%";
elements[0].style.top = "50%";
elements[0].getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
elements[0].getClientRects = () => [] as unknown as DOMRectList;
gesture(root, [200, 75]);
gesture(elements[0], [0, 0], [40, 30]);
expect(handlers.moveElement).not.toHaveBeenCalled();
expect(elements[0].style.left).toBe("50%");
});
it("ignores a drag across the image", () => {
const { root, handlers, gesture } = setup();
const { root, handlers, gesture } = setup({ selectedIndex: 0 });
gesture(root, [200, 75], [500, -20]);
expect(handlers.clickImage).not.toHaveBeenCalled();
expect(handlers.moveElement).not.toHaveBeenCalled();
});
it("ignores ctrl-clicks, which open the context menu on macOS", () => {
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { isMovableElement } from "../../../../../src/panels/lovelace/cards/picture-elements/movable-element";
import {
elementAnchors,
isMovableElement,
movedStyle,
} from "../../../../../src/panels/lovelace/cards/picture-elements/movable-element";
// Styles as YAML can produce them, not only strings.
const styled = (style: Record<string, unknown>) =>
@@ -13,19 +17,37 @@ describe("isMovableElement", () => {
[{ left: 0, top: null }],
[{ position: "Absolute" }],
[{ transform: "translate(-50%, -50%)" }],
[{ right: "5%" }],
[{ bottom: 0 }],
[{ left: "", right: "5%", top: null, bottom: "10%" }],
[{ Right: "", Bottom: null }],
[{ right: "", Right: "", top: "5%" }],
// The card removes the sides at the empty inset, before it sets them.
[{ inset: "" }],
[{ Inset: null, right: "5%", bottom: "10%" }],
[{ inset: "", left: "12.3%", top: "20%" }],
])("moves an element styled %j", (style) => {
expect(styled(style)).toBe(true);
});
it.each([
[{ position: "relative" }],
[{ right: "5%" }],
[{ bottom: 0 }],
[{ left: "10%", right: "5%" }],
[{ top: 0, bottom: "5%" }],
[{ right: "5px" }],
[{ Bottom: "5%" }],
[{ inset: "0" }],
[{ "inset-inline-start": "10%" }],
[{ left: "120px" }],
[{ top: "calc(50% - 10px)" }],
[{ Left: "10%" }],
[{ Top: "" }],
// Depending on the key order, the empty key removes the side again.
[{ right: "5%", Right: "" }],
[{ Bottom: null, bottom: "5%" }],
// The empty inset removes the sides again.
[{ right: "10%", bottom: "20%", inset: "" }],
[{ left: "10%", Inset: null }],
])("leaves an element styled %j alone", (style) => {
expect(styled(style)).toBe(false);
});
@@ -43,3 +65,107 @@ describe("isMovableElement", () => {
expect(isMovableElement({ type: "conditional" })).toBe(false);
});
});
describe("elementAnchors", () => {
it.each([
[{}, { x: "left", y: "top" }],
[
{ right: "5%", bottom: "10%" },
{ x: "right", y: "bottom" },
],
[
{ left: "5%", bottom: "10%" },
{ x: "left", y: "bottom" },
],
[
{ right: "5%", top: "10%" },
{ x: "right", y: "top" },
],
])("places an element styled %j from %j", (style, anchors) => {
expect(elementAnchors({ type: "icon", style })).toEqual(anchors);
});
});
describe("movedStyle", () => {
// A spot on the image, from all of its sides.
const SPOT = { left: 12.34, right: 87.66, top: 20, bottom: 80 };
it.each([
[{ color: "red" }, { color: "red", left: "12.3%", top: "20%" }],
[
{ right: "5%", bottom: "5%" },
{ right: "87.7%", bottom: "80%" },
],
[
{ left: "5%", bottom: "5%" },
{ left: "12.3%", bottom: "80%" },
],
[
{ right: "5%", top: "5%" },
{ right: "87.7%", top: "20%" },
],
])("moves an element styled %j along its sides", (style, moved) => {
expect(movedStyle({ type: "icon", style }, SPOT)).toEqual(moved);
});
const moved = (style: Record<string, unknown>) =>
movedStyle({ type: "icon", style: style as Record<string, string> }, SPOT)!;
it.each([
[
{ top: "", inset: "", right: "5%" },
{ right: "87.7%", top: "20%" },
],
[
{ left: "", inset: "", top: "5%" },
{ left: "12.3%", top: "20%" },
],
[
{ left: "", top: null, Inset: null, color: "red" },
{ left: "12.3%", top: "20%" },
],
])("keeps the sides of %j behind the empty inset", (style, sides) => {
// Set key by key like the card does.
const element = document.createElement("div");
for (const [prop, value] of Object.entries(moved(style))) {
element.style.setProperty(prop, value);
}
for (const [side, value] of Object.entries(sides)) {
expect(element.style.getPropertyValue(side)).toBe(value);
}
});
it.each([
[
{ left: "5%", color: "red", top: "5%" },
[
["left", "12.3%"],
["color", "red"],
["top", "20%"],
],
],
[
{ inset: "", bottom: "5%", color: "red", right: "5%" },
[
["inset", ""],
["bottom", "80%"],
["color", "red"],
["right", "87.7%"],
],
],
])("keeps the key order of %j", (style, entries) => {
expect(Object.entries(moved(style))).toEqual(entries);
});
it("leaves an element alone that it can't move there", () => {
const style = { left: "5%", right: "5%" };
expect(movedStyle({ type: "icon", style }, SPOT)).toBeUndefined();
// The element no longer uses the sides the position was taken from.
expect(
movedStyle(
{ type: "icon", style: { right: "5%" } },
{ left: 10, top: 20 }
)
).toBeUndefined();
});
});
@@ -809,7 +809,7 @@ describe("ha-marketplace-repository-dashboard", () => {
const subpage = page.shadowRoot!.querySelector("hass-subpage") as
(HTMLElement & { header: string }) | null;
expect(subpage!.header).toBe("ui.panel.marketplace.title");
expect(subpage!.header).toBe("Marketplace");
expect(page.shadowRoot!.querySelector(".summary h1")!.textContent).toBe(
"Repository 1"
);
+5 -1
View File
@@ -1,5 +1,6 @@
import { IntlMessageFormat } from "intl-messageformat";
import { describe, expect, it } from "vitest";
import { NAME_PLACEHOLDERS } from "../../../src/common/translations/name-placeholders";
import en from "../../../src/translations/en.json";
type TranslationNode = string | { [key: string]: TranslationNode };
@@ -13,7 +14,10 @@ const format = (key: string, values: Record<string, string | number>) => {
typeof translations === "object" ? translations[part] : undefined,
en as TranslationNode
);
return new IntlMessageFormat(message as string, "en").format(values);
return new IntlMessageFormat(message as string, "en").format({
...NAME_PLACEHOLDERS,
...values,
});
};
describe("Marketplace strings", () => {