Compare commits

..
Author SHA1 Message Date
Paul Bottein ca1b3d95ee Show the integration type in the entity type list 2026-11-16 18:51:50 +01:00
Petar Petrov ca576fadf5 Remove unused cost_adjustment_day from grid sources (#55883) 2026-11-16 17:14:55 +02:00
Petar Petrov aea1ac4ac8 Fix history graph gaps after unavailable or inactive periods (#55908)
Keep history line after unavailable gap in downsampled charts
2026-11-16 16:12:49 +01:00
starkillerOG 6e1fe2846e Only fetch 4 thumbnails concurrently (#55952)
* Only fetch 4 thubmnails concurrently

* Restart thumbnail loading after a disconnect during a fetch
2026-11-16 15:26:03 +01:00
Paulus SchoutsenandClaude Opus 5.5 17202283b4 Count camera favorites as two slots in common controls (#55913)
* Count camera favorites as two slots in common controls

A camera favorite shows as a picture card that is two rows high, so it
fills the space of two tiles. The common controls limit counted it as
one entity. The extra suggestions then went into a new row.

The limit now counts tile-sized slots. A camera uses two of them.

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

* Count favorite slots in the home editor suggested toggle

The home editor disables the suggested entities toggle when the
favorites fill the section. It counted entities, so four camera
favorites left the toggle on although no suggestions show.

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

* Fill free slots when pinned entities do not all fit

When the pinned entities use more slots than the limit, the ones that
fit can still leave a free slot. For example, two pinned cameras with
a limit of 3. The section now checks the size of the pinned entities
that fit, and fills the free slot with a suggestion.

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

* Revert "Fill free slots when pinned entities do not all fit"

When the pinned entities that fit leave a free slot, the section asks
for suggestions. If usage prediction is not loaded, the section then
shows a message or hides itself in place of the pinned entities.

When the pinned entities fill the limit, the section now shows them
without suggestions again.

This reverts commit df676dfbe5.

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

* Always show pinned entities in common controls

The limit could drop pinned entities that did not fit. If usage
prediction was not loaded, the section showed a message or hid itself
in place of the pinned entities.

Pinned entities now always show. Predictions only fill the slots that
the pinned entities leave free.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-16 14:44:24 +01:00
Petar Petrov 0c8323c4f6 Allow theming timeline colors of custom states (#55930)
* Allow theming timeline colors of custom states

States of domains without state colors now use --state-<domain>-<state>-color (or its device class variant) when the theme defines it, before falling back to the graph palette.

* Drop device class variant for custom state colors

* Restore device class variant for custom state colors
2026-11-16 14:40:01 +01:00
Bram KragtenandClaude Opus 5.5 a2a523d5e5 Ignore outdated HLS starts and fetch a fresh stream URL on restart (#55953)
A start that was still fetching the stream URL, loading hls.js or
fetching the playlist could finish after the player was hidden or
removed, and create a player nobody stops. Count clean ups the same way
the WebRTC player does and drop starts that are outdated.

Restarting after a clean up reused the old stream URL. Core resets its
access token once the stream has been idle for 30 seconds, so the
restart got a 404 and the card fell back to MJPEG. Since the companion
apps now clean up right away when hidden, this happened every time the
app was in the background for more than 30 seconds. Fetch a new stream
URL on every restart instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-16 14:51:15 +02:00
Bram Kragten b379c0d311 Stop camera streams right away when hidden in the companion apps (#55887) 2026-11-16 14:29:33 +02:00
Julian 4dc975ec23 Keep the ha-ripple press while it is still active (#55942)
Hide a mouse or pen press when it moves off the control and show it
again when it returns while still held, since releasing it there still
clicks. Ignore the context menu during a touch press so a long press
keeps its pressed state until the touch ends.
2026-11-16 13:29:16 +01:00
Tristan Milnthorp 84294d7a8f Don't count light groups in the home summary when their lights are counted (#55903)
* Don't count light groups in the home summary when their lights are counted

* Share the group member helper with the more-info dialog

* Let the group member helper own the registry lookup too

computeGroupMemberIds now reads the registry's group_entities first, then
the state's group_entities, then the state's entity_id, so the more-info
dialog and the home summary share one definition.

For more-info, the only difference is that the state's group_entities is
now tried before entity_id when there is no registry copy. Core writes the
same capability into both, so it is the same data.

* Check nested group members for listed lights at any depth

* Keep one of two listed groups that contain each other
2026-11-16 13:08:05 +01:00
e5838446c8 Redesign the cover more-info dialog (#55614)
* Redesign the cover more-info dialog

* Refine cover drawings, handle and target edge

* Fix cover position fallback, tilt percentage and cancelled drags

* Remove speed selection from the cover dialog

* Hide the cover drawing from assistive tech without position

* Clean up the cover dialog code and rework the tilt control

* Soften the cover tilt gauge

* Use a generic drawing for doors and windows and simplify cover commands

* Update the active cover favorite when the position changes

* Drop the cover request when the position changes without moving

* Fix cover request controller typecheck

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

* Stop registering the cover request controller on its host

* Show the selected cover mode value in the header and hold tilt requests while moving

* Show only the state in the cover header when the value is unknown

* Follow the ARIA slider convention for cover arrow keys

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: piitaya <[email protected]>
2026-11-16 12:36:51 +01:00
Christopher Pruijsen 53f000e492 Fix more info opening when releasing outside an entity row control (#55890)
* Fix more info opening when releasing outside an entity row control

A press that starts on the control of an entity row and ends on the name
made the browser send the click to the row, which opened more info or ran
the hold action. The row now drops that click.

* Let clicks without a pointer through after an unfinished control press

A control press that ends without a click left the flag set, so the next click on the row with no pointer behind it (assistive technology or element.click()) was dropped. Only pointer clicks (detail > 0) are dropped now.
2026-11-16 13:15:57 +02:00
renovate[bot] c452e8e4ff Update formatjs (#55875)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 12:12:54 +01:00
Maarten Lakerveld e80b07893d Read formatjs locale data from the new IIFE wrapper (#55950)
The formatjs patch releases in #55875 wrap each locale-data file in an
IIFE that receives the data as its argument. The extractor matched the
__addLocaleData(...) call and captured the identifier `data`, so every
build failed while parsing locale data.

Take the IIFE's trailing argument when present and fall back to the old
inline call, so the script works before and after the bump.
2026-11-16 13:01:42 +02:00
Daniel SadilekandClaude Opus 5.5 c801a52e67 Show previous values below current ones in the energy Totals table (#55897)
* Widen the energy Totals table so comparing periods fits

With "Compare data" on, the Totals table (energy-sources-table) adds the
columns "Previous energy" and "Previous cost". On the Summary view it sat
in a one-column section, and on the Gas and Water views it had 12 of 36
grid columns, so the current Energy and Cost columns were pushed out of
view behind a horizontal scrollbar.

The Totals section on the Summary view now spans two columns and the card
fills it. On the Gas and Water views, the graph and the Totals table each
take the full width, one below the other, as on the Electricity view.

Fixes #54975

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

* Show previous values below current ones in the energy Totals table

Reverts the layout changes of the previous commit. With "Compare data" on,
the Totals table (energy-sources-table) added the columns "Previous
energy" and "Previous cost", which pushed the current Energy and Cost
columns out of view in narrow cards. The table now keeps its Source,
Energy and Cost columns and shows the previous period's value as a
secondary line in the same cell, so it fits at any card width, also on
custom dashboards.

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

* Use ha-tooltip for the previous value's label

The secondary line used a native title attribute. It now uses ha-tooltip,
as the repository does for contextual hover help.

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

* Make the previous values keyboard accessible and their IDs unique

The tooltip anchors of total rows were derived from their translated
labels, which could collide in non-Latin languages. Total rows now pass a
fixed key. The previous values are focusable, so keyboard users can open
their tooltip too.

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

* Label the previous values in the table header

The previous values were explained only by a per-cell tooltip, which touch
users could not open. The Energy and Cost headers now show "Previous
energy" / "Previous cost" as a secondary line while comparing, which
works for touch, keyboard and screen readers alike. The tooltips, their
IDs and the extra tab stops are gone.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-16 10:40:44 +00:00
WendelinandClaude Opus 5.5 8ac2712e31 Keep config navigation rows named on older Android WebViews (#55949)
* Keep config navigation rows named on older Android WebViews

Since list rows only wrap the headline and supporting text in their
button, the Companion app row became a text-only button. Android System
WebView 83 (API 30) then sometimes exposes it without a name, so the
row is missing from the accessibility tree and the Android E2E test
fails to find it.

Pass the text as headline and supporting-text properties instead of
slotting it, so it is rendered inside the button itself. The
accessibility tree in current browsers is unchanged.

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

* Remove comment from config navigation list

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-16 11:39:00 +01:00
Tim Laing f7f15ae4a8 Expose color helpers to custom cards (#55935)
* Expose color helpers to custom cards

* Remove color helper documentation from README
2026-11-16 09:37:12 +00:00
HugoPeters1024 e66733186e circular slider: disable keyboard input when disabled (#55943) 2026-11-16 09:35:38 +00:00
karwosts 1e7bdbbcc8 Restore missing mobile tooltips (#55929) 2026-11-16 09:50:32 +01:00
renovate[bot] 7292db76bf Update dependency @codemirror/lint to v6.9.8 (#55940)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 09:38:26 +01:00
renovate[bot] 9d997fbe4c Update dependency jsdom to v31.0.1 (#55941)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 10:30:01 +02:00
Jan Bouwhuis 05d11c25c2 Keep dragged nodes in place in network graphs (#55808)
* Keep dragged nodes in place in network graphs

Fix the ECharts force drag order, so a node can be dragged with physics
on when layoutAnimation is off. Pin dragged nodes where they are dropped
and keep their positions through re-renders. Count only nodes of visible
legend categories for the layoutAnimation threshold.

* Keep pins through legend changes, clicks and chart recreation

Write the pin and position of a dropped node into the ECharts item option,
so a legend re-layout keeps them. Pin a pinned node again after a click,
and render again when the chart is recreated, e.g. after a theme change.

* Move only the dragged node with reduced motion

With reduced motion, a drag no longer runs the force layout, so only the
dragged node moves. A new force option of our ECharts patch, dragAnimation,
tells this apart from layoutAnimation, which is also off above 100 nodes.

* Drop the ECharts drag patch

Restore the ECharts patch and the lockfile to dev, and remove the
dragAnimation option. Dragging with physics on and without layout
animation is an ECharts issue to fix upstream.

* Render on legend changes only when the layout animation flips

The legend lays the graph out again itself, so the hidden categories are
no longer reactive. Only a change of the layout animation threshold saves
the positions and renders. Keep the private ECharts series access in one
helper.
2026-11-16 10:02:31 +02:00
Christopher Pruijsen ec14a9fe39 Fix horizontal scroll on the backup location page on narrow screens (#55934) 2026-11-16 08:52:27 +02:00
renovate[bot] fc640e236d Update dependency fullcalendar to v7.1.5 (#55933)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 06:15:28 +01:00
renovate[bot] c2db01285c Update github/codeql-action action to v4.39.3 (#55938)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 06:14:33 +01:00
Petar Petrov f2d0da08ed Edit batteries measured per direction (#55606)
* Edit batteries measured per direction

The battery editor first asks what the battery measures: only the total
in and out, or separately for grid, solar and home. Per direction shows
an energy and an optional power sensor for each flow, offers Integral
helpers for power-only flows, and warns when a flow's source is missing.

* Hide a battery's generated power sensor from its total power pickers

Switching a battery to another power setup removes its generated net
power sensor, so it can't be picked as the new power sensor.
2026-11-15 21:22:40 +01:00
Simon LamonandPetar Petrov 502dcdc1a6 Fix getWeatherExtrema when either is 0° (#55687)
* Fix getWeatherExtrema when either is 0°

* Update src/data/weather.ts

Co-authored-by: Petar Petrov <[email protected]>

* Simplify tempLow assignment conditions

Refactor temperature low assignment logic in weather.ts

* Prettier

* Apply suggestion from @MindFreeze

Co-authored-by: Petar Petrov <[email protected]>

---------

Co-authored-by: Petar Petrov <[email protected]>
2026-11-15 17:19:50 +02:00
renovate[bot] 0d31ae5624 Update dependency @rslib/core to v1.0.7 (#55925)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 14:24:47 +01:00
renovate[bot] f57384a265 Update dependency glob to v14.0.6 (#55926)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 14:24:40 +01:00
Tom Carpenter 4fe20d7712 Show Day of Week on Energy Period Selector card (#55924)
Show Day of Week on energy period selector card

When a single date is displayed, include day of week in the text.
2026-11-15 14:52:25 +02:00
Yosi LevyandCopilot Autofix powered by AI 14a4c05130 Marquee RTL support (#55876)
* Marquee RTL

* Refactor _animationFactor to a getter

Refactor _animationFactor to be a getter that determines its value based on document direction.

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-15 12:49:43 +00:00
Petar Petrov 2d6ebd26d9 Use measured battery flows on the energy dashboard (#55604)
* Move energy settings from dialogs to an editor sidebar

Sources and devices on all energy configuration tabs now open in a
sidebar like automation steps, with the selected row highlighted and a
save button for unsaved changes. Cost tracking and power measurement type
use dropdowns, and the editor inputs are grouped with dividers. The energy
setup wizard keeps its dialogs, which now reuse the same editors.

* Read the energy editors' data from contexts

The energy editors, the power measurement config and the upstream device
picker consume contexts instead of hass, so the setup wizard dialog no
longer passes it. createConfigFlow, handleConfigFlowStep and
getSensorDeviceClassConvertibleUnits take callApi or callWS.

The sidebar slots the editor in, so switching to the bottom sheet keeps
unsaved changes, and the lists are inert while the editor saves.

* Confirm unsaved energy edits on the back arrow

The toolbar back arrow asks before discarding the editor's changes, like
the automation editor does, and the sidebar is inert while the editor
saves, like the lists.

* Edit energy sources and devices on pages of their own

Sources and devices open on a page with a back arrow, their name as the
title and the form in a card, instead of in a sidebar. The lists go back
to the centered column, and the energy setup wizard keeps its dialogs.

* Keep energy page saves and deletes apart

Save and Delete are disabled while the other runs, since both write all
preferences, and a page that was left no longer navigates when its save
or delete finishes.

* Use measured battery flows on the energy dashboard

A battery can report its energy and power per direction: grid to
battery, solar to battery, battery to home and battery to grid. The
cards now use those flows as measured and estimate only the rest, so
grid charging no longer shows up as solar charging. Batteries with
total in and out statistics work as before.

The power Sankey now shares the energy flow math, and its type links
get explicit values instead of the greedy fill.

* Describe battery totals without a destination

* Show the energy error screen when statistics fail to load

Editor pages wait for the statistics metadata, so a failed request kept
them loading forever. It now shows the panel's error screen, like a
failed preferences or validation request.

* Name unnamed per-direction batteries in the power Sankey

* Don't register removed dirty state providers again

* Keep measured flows without a meter out of the home load

A measured battery flow whose grid or solar meter isn't configured never
passed through that meter, so it no longer changes the home load. The
power Sankey passes grid and solar as unmetered when they have no power
sensor.

* Open energy items through links

The editors open on pages now, so the list rows, the add buttons and the
CO2 signal row are links that can open in a new tab. ha-automation-row
gets an optional href that wraps the icon and header in a link and keeps
the icons slot outside of it. The setup wizard still opens dialogs.

* Note that a battery needs a charge and a discharge direction
2026-11-15 09:48:14 +01:00
Adam Pyle 5ba1190cdd Use theme colours on the Cast receiver launch screen (#55879)
The launch screen hardcoded a light background and dark text, so it
stayed white when the user or the cast device used dark mode. Use the
theme variables the receiver's ThemesMixin already applies to the
document, keeping the previous colours as fallbacks.
2026-11-15 08:34:09 +00:00
Petar Petrov 81cf8050e4 Drop the hass-shaped context from the security alerts editor (#55851)
Security entity helpers take states and registries as separate values.
2026-11-15 09:23:44 +01:00
Petar Petrov 1a10982a5e Fix the category filter scope round-trip and the navigation path registries consumer (#55848)
* Keep category filter list on a quick scope round-trip

Clear the category filter only when the scope differs from the subscribed one, and consume the registries context once in NavigationPathInfoController.

* Skip navigation path re-resolves when its inputs are unchanged

Each controller compares the values it resolved with, instead of sharing a module-level areas and devices cache.

* Clear the category filter list on disconnect

A reconnect with a new scope would otherwise show the old scope's categories until the new ones arrive.
2026-11-15 09:23:07 +01:00
Petar Petrov fb8ac756ce Pass callWS to getExtendedEntityRegistryEntry (#55849)
Take callWS instead of a hass-shaped object and use the helper again in callProtectedLockService.
2026-11-15 09:19:17 +01:00
renovate[bot] 2c072ab254 Update dependency prettier to v3.10.1 (#55923)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:13:11 +00:00
renovate[bot] 31ca8c298b Update pnpm to v12.20.0 (#55922)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 09:03:19 +01:00
Jan Bouwhuis 1a5d8884ad Align MQTT subscribe card width with other cards (#55914) 2026-11-15 08:34:13 +02:00
karwosts 9a95c9dea9 Fix targetless media selector (#55921) 2026-11-15 08:34:08 +02:00
renovate[bot] 5db5f9075d Update babel monorepo to v8.1.2 (#55917)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:25:22 +02:00
renovate[bot] 6ce043a8e4 Update dependency maplibre-gl to v6.18.0 (#55920)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:25:14 +02:00
renovate[bot] d81a9f29b2 Update dependency tar to v7.5.23 (#55919)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:25:05 +02:00
renovate[bot] c39734f350 Update dependency glob to v14.0.5 (#55918)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 08:24:52 +02:00
renovate[bot] e65584e724 Update dependency prettier to v3.10.0 (#55910)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 19:15:42 +01:00
renovate[bot] 6641a43e43 Update tsparticles to v4.5.4 (#55909)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 19:15:17 +01:00
renovate[bot] 2706bd89a1 Update dependency vite to v8.3.8 (#55906)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 08:55:55 +02:00
renovate[bot] bd434eeb0d Update dependency @rspack/core to v2.3.2 (#55899)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 17:11:21 +02:00
Petar Petrov 16f01e1081 Fix legends fitting as narrow in the card editor preview (#55886) 2026-11-13 14:28:15 +01:00
Dan SpencerandClaude Opus 5.5 050251db23 Offer a blueprint's trigger IDs in Triggered by conditions (#55802)
* Offer a blueprint's trigger IDs in Triggered by conditions

In an automation that uses a blueprint, a Triggered by condition in one
of its inputs listed no triggers, and flagged the IDs it already used as
missing. The editor took the list from the automation's own triggers,
and a blueprint automation has only `use_blueprint`.

For a blueprint automation, fetch the blueprint with its inputs filled
in (`blueprint/substitute`) and list the IDs its triggers set, fetching
again when the inputs change. A trigger without an ID isn't offered,
since the editor can't give one to a blueprint's trigger, and an ID
shared by several triggers is listed once, as the condition matches any
of them.

The condition is in one of the blueprint's inputs, which the trigger
controller doesn't edit, so its `select` returns false there, as
`updateTriggerId` does for a trigger it doesn't own, and the condition
editor saves the pick through `value-changed` instead.

An option shows its trigger number only while trigger rows show theirs
(`showIndices`): the numbers point at trigger rows, and a blueprint
automation has none.

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

* Ignore an empty use_blueprint while editing YAML

`use_blueprint:` with no value parses to null, and requesting its
triggers threw on `.path`, aborting the editor's update.

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

* Hold back trigger warnings until a blueprint's triggers are known

While a blueprint's triggers load, or when its inputs can't be substituted
yet, a Triggered by condition can't tell a missing ID from one it hasn't
seen. The trigger context now carries optionsStatus: "loaded", "loading" or
"failed". Until it's loaded, the condition and the row's summary list the
selected IDs without the missing-trigger warning or chips. An empty
condition shows "Loading", or a hint to set the blueprint's required inputs
once substitution has failed. After a failure the last triggers stay listed.

use_blueprint is also compared by value, since YAML mode parses a new object
on every edit and an edit elsewhere fetched the triggers again.

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

* Address review: spinner, refetch warnings and index badges

- Show a delayed ha-spinner while a blueprint's triggers load, following
  the frontend's loading pattern, instead of visible "Loading" text.
- Mark every request as loading, keeping the last triggers listed, so an
  input change that renames a trigger's ID doesn't read as missing until
  the new triggers arrive.
- Publish showIndices false for a blueprint automation. Switching to YAML
  removes the manual editor's sidebar without reporting it, which left
  the blueprint's condition numbering trigger rows that don't exist.
- Drop inline comments from the blueprint trigger code.

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

* Show trigger IDs when trigger rows aren't numbered

A Triggered by condition tells options apart by description, custom ID or
index. In a blueprint automation there are no indices, so two triggers
that describe the same with generated-prefixed IDs looked identical while
selecting different IDs. Without indices, every option's ID is shown.

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

* Say when a blueprint's triggers have no IDs

A blueprint whose triggers have no IDs loads with nothing to offer, and
the condition said "Add a trigger first", which can't be done in a
blueprint automation. optionsStatus is now blueprintStatus, left out for
an automation with its own triggers, so the condition can tell the two
apart and say the blueprint's triggers have no IDs.

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

* Rename blueprint_triggers_pending to blueprint_triggers_unavailable

It's only shown once substitution has failed, not while loading.

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

* Drop controller tests that cover one-line branches

Keeps the tests for the response race, the statuses and refetching.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-13 06:26:48 +00:00
renovate[bot] 13128609de Update dependency @versatiles/style to v9.1.0 (#55893)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 08:22:31 +02:00
renovate[bot] 0f70813ada Update dependency marked to v18.2.0 (#55894)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 08:22:27 +02:00
Matthias 5762da9d22 Refresh the ingress session when the app panel becomes visible (#54863)
The ingress session is kept alive by a 60 s timer only. Timers do not run
while the device sleeps, so after the browser comes back to the foreground
the session may already be expired, and the Supervisor refuses every
request to the app until the next tick. An app that reconnects its
websocket right away stays unreachable for up to a minute.

Refresh the session on visibilitychange and resume as well. The refresh is
shared with the timer: validate the session, create a new one when that
fails, and never run twice at once. A failed refresh no longer surfaces as
an unhandled rejection, the next one retries.
2026-11-13 06:07:00 +00:00
renovate[bot] 33f709cd21 Update Node.js to v24.22.3 (#55892)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 06:54:27 +01:00
renovate[bot] 1f77e4cd59 Update dependency typescript-eslint to v8.72.2 (#55891)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 06:54:10 +01:00
Paul Bottein 77170b447f Fix favorites centering in the more info dialog (#55884) 2026-11-12 17:26:25 +02:00
c0ffeeca7 e2bb744202 MCP: change AI agent to AI app (#55885) 2026-11-12 17:25:49 +02:00
Wendelin 0eec83448a Revert camera ICE server filter and WebRTC-first memory (#55881)
* Revert camera ICE server filter and WebRTC-first memory

Follow-up to #55861 after review feedback:

- Use the full ICE server list from core again. The slow starts come from
  go2rtc, which stalls while it sets up TURN relays with the cloud ICE
  servers, so filtering in the browser does not help.
- Start HLS and WebRTC together again, remove the per-camera WebRTC-first
  memory and its 12 second HLS delay.
- Retry a WebRTC stream at most once, only after it played or on a backend
  error. A new connection that gets no answer or finds no path fails
  directly, so HLS or MJPEG takes over.

* Ignore stream URL errors of a removed HLS player

Switching cameras while the old HLS player was still fetching its stream
URL could mark HLS as failed for the new camera.
2026-11-12 14:51:53 +01:00
WendelinandClaude Sonnet 5.5 1864f6f802 Move the media browser list item to its own file (#55877)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-11-12 13:26:28 +01:00
renovate[bot] 9a19cc3bf6 Update dependency vite to v8.3.7 (#55880)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 13:24:58 +01:00
WendelinandClaude Fable 5.2 ec51fb4f8d Add attributes to wrap text in list rows (#55864)
The headline and supporting text of ha-row-item are truncated to one
line. Many pages overrode that with white-space rules on the headline
and supporting-text parts.

Add the wrap-headline and wrap-supporting-text attributes and use them
in place of those CSS overrides.

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-12 13:20:40 +02:00
Paul Bottein 6a1a9bfb1b Suggest area icons based on the area name (#55708)
* Suggest area icons from the room in the area name

* Fix stale icon list, closed dialog and AI icon override

* Keep an untouched area dialog clean after the icon prefill

* Keep the suggested section visible when a suggested icon is selected

* Move area icon keywords to the translations

* Move room keywords to a shared translation key

* Remove home cinema and gym from the room list

* Note the Lokalise draft effect of editing room keywords

* Ship room keyword drafts and group keywords under rooms.keywords

* Add more room types for area icon suggestions

* Fetch room keyword drafts through the Lokalise keys API
2026-11-12 10:51:12 +01:00
Maarten Lakerveld 16807d2765 Make "Don't show again" a checkbox on the browser warning (#55863)
As a second button it was easy to press by accident. The reminder now has a
checkbox, and "Continue anyway" applies it.
2026-11-12 09:48:17 +01:00
renovate[bot] 9caad65c91 Update dependency eslint-plugin-import-x to v4.18.1 (#55874)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 08:16:21 +02:00
Bram KragtenandClaude Opus 5.5 af523f1087 Fix Matter add device dialog stuck on the spinner (#55869)
The dialog waited for the companion app's commission finish message on
every step, but only the app's own flow sends it. Steps that commission
through core or another app now advance as soon as the device appears.
A failed finish message after the device appeared also advances now.

The new device watcher unsubscribed twice after a find, which dropped
another subscriber from the device registry collection. After a few
adds the registry stopped updating and the dialog never saw the device.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 08:12:21 +02:00
renovate[bot] 349d5f7125 Update dependency intl-messageformat to v12.1.5 (#55872)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 07:01:41 +01:00
renovate[bot] de64bd3c59 Update formatjs (#55873)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 07:01:21 +01:00
Zedas 5253eef284 Allow a few pixels of finger movement in the action handler (#55826)
* Allow a few pixels of finger movement in the action handler

* Cancel the action handler press when the browser takes over the touch

The document scroll listener only hears the page itself, not nested
scrollers. pointercancel is composed and fires when the browser starts
scrolling a touch, so it covers those as well.
2026-11-11 22:51:14 +01:00
WendelinandClaude Fable 5.2 b1164739c3 Make camera WebRTC streams connect faster and more reliably (#55861)
* Make camera WebRTC streams connect faster and more reliably

- Limit the ICE server URLs the browser uses to one STUN, one UDP TURN
  and one TCP TURN URL per host. The last retry uses the full list.
- Start WebRTC first for cameras where it worked before in this browser,
  with HLS as fallback after 12 seconds.
- Always prefer WebRTC over HLS once it plays.
- Restart a WebRTC stream up to two times when it fails, loses its
  connection or does not connect in time, then report the failure so HLS
  takes over.
- Fix the ICE candidates added to the offer.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Address review and connect the microphone over the known path

- Always forget a camera when WebRTC shows no video within the deadline.
- Fall back to MJPEG when a WebRTC only camera delivers audio but no
  video.
- Keep using all ICE servers once a stream only loaded with them.
- Start the microphone connection with only the ICE servers the running
  stream needs for its path.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Keep all ICE servers for a direct microphone path that needed them

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Improve microphone connection handling in WebRTC player

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-11 16:35:47 +01:00
Petar Petrov 80a516c673 Allow selecting values in the energy sources table (#55852) 2026-11-11 16:07:46 +01:00
Petar Petrov d5d0f45919 Move energy settings from dialogs to pages (#55410)
* Move energy settings from dialogs to an editor sidebar

Sources and devices on all energy configuration tabs now open in a
sidebar like automation steps, with the selected row highlighted and a
save button for unsaved changes. Cost tracking and power measurement type
use dropdowns, and the editor inputs are grouped with dividers. The energy
setup wizard keeps its dialogs, which now reuse the same editors.

* Read the energy editors' data from contexts

The energy editors, the power measurement config and the upstream device
picker consume contexts instead of hass, so the setup wizard dialog no
longer passes it. createConfigFlow, handleConfigFlowStep and
getSensorDeviceClassConvertibleUnits take callApi or callWS.

The sidebar slots the editor in, so switching to the bottom sheet keeps
unsaved changes, and the lists are inert while the editor saves.

* Confirm unsaved energy edits on the back arrow

The toolbar back arrow asks before discarding the editor's changes, like
the automation editor does, and the sidebar is inert while the editor
saves, like the lists.

* Edit energy sources and devices on pages of their own

Sources and devices open on a page with a back arrow, their name as the
title and the form in a card, instead of in a sidebar. The lists go back
to the centered column, and the energy setup wizard keeps its dialogs.

* Keep energy page saves and deletes apart

Save and Delete are disabled while the other runs, since both write all
preferences, and a page that was left no longer navigates when its save
or delete finishes.
2026-11-11 15:53:24 +01:00
Petar Petrov f922bc59a5 Drop hass from the state card content (#55853)
stateCardType, canToggleState and canToggleDomain take states and services; HassMediaPlayerEntity takes callService.
2026-11-11 15:36:31 +01:00
Petar Petrov a71a79b01b Drop hass from the target details dialog (#55850)
The dialog reads localize, callWS, states and entities from contexts, and resolveItemExclusions takes callWS.
2026-11-11 15:21:23 +01:00
Petar Petrov 9b8409d7ec Show model ID in the devices table when the model is missing (#55856) 2026-11-11 15:17:41 +01:00
Petar Petrov fc8d21b920 Point links in a duplicated dashboard at the copy (#55859) 2026-11-11 15:15:13 +01:00
Maarten Lakerveld fce0f4da4e Migrate the image cropper dialog to cropperjs 2 (#55570)
* Migrate the image cropper dialog to cropperjs 2

Cropper.js 2 is a rewrite built on shadow-DOM custom elements: the v1
class API (getData, getImageData, getCroppedCanvas, the ready and crop
callbacks) and the cropper.css stylesheet no longer exist, so the plain
Renovate bump (#55562) fails type checking and every rspack build.

Render the v2 elements directly from the dialog template instead of
wrapping an <img>. The canvas has no intrinsic size, so decode the file
first and give the canvas the image aspect ratio; the image then fills
it exactly. Initialise after the dialog has finished its scale-in
animation, because the elements measure themselves with
getBoundingClientRect, and refit the image and selection when the
canvas is resized.

Keep the v1 behaviour the callers rely on: the selection cannot leave
the image or the visible canvas, the image cannot be moved or zoomed out
from under it (viewMode 1), resizing stops at 50px, the rounded preview
is CSS only so the exported file stays rectangular, and the export is
rendered at the source resolution. Dirty tracking compares the crop
rectangle in source image pixels, like getData() did in v1.

* Clamp cropper drags to the edge and show image load errors

Cropper.js 2 moves the selection and image in relative steps per pointer
event. Rejecting a step that crossed the image edge dropped its movement on
both axes, so on fast drags the selection fell behind the cursor and got
stuck along an edge, mostly with portrait images. Clamp moves, resizes and
image pans to the edge instead, as v1 did. Fixed-ratio resizes shrink
around the anchored side to keep the ratio.

Show an error alert when the picture cannot be decoded instead of an empty
dialog.

* Keep the Shift-locked aspect ratio when a free crop hits the edge

With a free aspect ratio, Shift locks the ratio during a resize. The
out-of-bounds correction clipped the proposal instead of scaling it, so
the selection lost that ratio at the image or canvas edge.
2026-11-11 14:44:01 +01:00
WendelinandClaude Opus 5.5 2391c700c6 Expose action buttons in list rows to screen readers (#55831)
* Keep action controls in list rows reachable for screen readers

ha-list-item-button wrapped the whole row, including the start and end
slots, in its native button or link. Controls placed in those slots
were nested inside it and hidden from assistive technology.

Only the headline and supporting text are inside the native element now,
and its hit area is stretched over the row. Slotted controls sit above
it; icons, badges, text and empty dividers sit below, so they still
activate the row with native link behaviour.

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

* Rebind the list row ripple when the control is replaced

Switching href swaps the inner <a> and <button>, and media browser rows
drop the control when not interactive. The ripple kept listening to the
removed element, so the new control had no hover or press feedback.

Render the ripple after the control and recreate it with the control.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-11 15:26:10 +02:00
R HOCH RandCopilot Autofix powered by AI 8cd79a6776 Add button to duplicate dashboards (#55832)
* Add option to duplicate dashboards

* Add error handling for missing dashboard config

Handle config not found error when fetching dashboard.

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

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-11 13:25:56 +02:00
Petar Petrov b4f6e4e2ea Drop hass from the target picker (#55855)
* Drop hass from the target picker

getEntities takes an options object of separate values; ha-target-picker, ha-sources-picker, ha-selector-target and the exclusions controller consume contexts.

* Rerender the target picker only when a pending entity appears

Consume statesContext without @state and narrow a second consumer to the pending helper entity.

* Redraw target picker icons when the brands token arrives

Also refetch target selector entity sources after a reconnect, like the entity selector.
2026-11-11 11:00:13 +01:00
Lorenzo Marroccoli 50bb1cf53e Prefer model ID over firmware in integration device rows (#55845)
* Prefer model ID over firmware in integration device rows

* Include model ID in integration device search
2026-11-11 11:59:54 +02:00
Petar Petrov 70a1946874 Fix lazy context provider error and reconnect handling (#55854)
* Fix lazy context provider error and detached consumer handling

Retry failed subscriptions, drop consumers that left before the first value, and give config entry updates a new array.

* Reset config entries on a new snapshot

Replace the list when a resubscribe sends all entries again, and log failed subscriptions.

* Clear config entries on an empty snapshot

Core sends an empty list when no entries match the subscription.
2026-11-11 10:42:49 +01:00
Paul Bottein 3da9ba8119 Add default option and icons to the entity type select (#55833)
* Add default option and icons to the entity type select

* Simplify the entity type select code

* Store the device class override separately from the effective class
2026-11-11 09:57:22 +01:00
Petar Petrov eb8ac4139b Translate YAML editor error reasons (#55836)
Translate common YAML parse error reasons in the editor
2026-11-11 09:46:18 +01:00
Petar Petrov f9aae72325 Use "remove" wording when removing devices (#55835)
* Use "remove" wording when removing devices

* Keep "delete" wording for config entries
2026-11-11 09:18:30 +01:00
Christian Wiedel 81279aa6d2 Allow checking off to-do items without a name (#55847)
* Allow checking off to-do items without a name

* Keep whitespace-only names rejected by core
2026-11-11 10:08:27 +02:00
Eric RouleauandCopilot 33b8afffca Show area in ZHA device bindings and neighbors (#55812)
* Show area in ZHA device bindings and neighbors

The 2026.11 naming change means device names no longer carry
their area, but the Manage Zigbee Device panel still showed only
the device name in two places, making identically named devices
indistinguishable:

- The Bindable devices dropdown in the Bindings tab now shows
  the area as the option's secondary line.
- The Neighbors tab gains a sortable, filterable Area column.

Area resolution is shared in getZHADeviceAreaName(): it resolves
via the device registry (so child devices inherit their parent's
area, matching the ZHA network visualization) and falls back to
the area reported by ZHA itself.

* Address Copilot review: registry-authoritative area, memoize by registries

- Treat an existing device registry entry as authoritative: if it
  has no effective area, the device has no area, even if ZHA still
  reports one from its cached response. The ZHA area_id fallback
  now applies only when the device has no registry entry at all,
  so clearing a device's area no longer leaves stale area text.
- Narrow getZHADeviceAreaName() to take the area and device
  registries instead of the whole hass object, and key the
  Neighbors memo on those registries. Entity-state updates replace
  hass, which rebuilt every neighbor row and reran table
  sorting/filtering on unrelated updates.

* Use device picker for ZHA bindings

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

* Reuse getZHADeviceAreaName helper in other places that also did a similar registry lookup

---------

Co-authored-by: Copilot <[email protected]>
2026-11-11 08:46:05 +02:00
renovate[bot] b157dd174e Update dependency maplibre-gl to v6.17.0 (#55844)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-11 08:25:17 +02:00
renovate[bot] 4a0381e82d Update dependency @vvo/tzdb to v6.204.0 (#55843)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-11 08:17:15 +02:00
renovate[bot] 92e248c913 Update dependency @versatiles/style to v9 (#55846)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-11 08:15:54 +02:00
Maarten Lakerveld 5b1ecdb0b0 Let browsers below the legacy floor continue at their own risk (#55829)
* Let browsers below the legacy floor continue at their own risk

Browsers below the floor get a "Continue anyway" button on the launch
screen instead of a dead end, e.g. for a wall dashboard. The warning returns
monthly, and from the first reminder on offers "Don't show again".

* Space the launch screen without max() on Chrome below 79

The launch screen's top spacer and OHF logo margins use max() with var()
inside. Chrome below 79 drops those after the cascade, leaving no margin,
so the logo touched the bottom edge (Chrome 67 to 78 are in the legacy
floor). Plain margins now come first, the max() rules behind @supports.

* Keep the browser warning up while the app loads

Once the user continued, the launch screen went blank until the legacy
build took over, which can take a while on these devices. Keep the message
and only drop the buttons.

* Say the browser is no longer supported instead of too old

With the option to continue it does run, so "too old to run Home Assistant"
contradicted the button. The same text now reads right before and after
continuing.

* Use a plain color for the launch screen buttons

Theme variables are not set yet while the launch screen shows, so
var(--primary-color) always fell back anyway.
2026-11-10 16:53:24 +01:00
Zedas ee35dd8cf6 Send the final media player volume only once (#55828) 2026-11-10 15:04:46 +01:00
Daan VervackeandAidan Timson 42ce434a94 Add selection mode with bulk remove to the Marketplace repositories page (#55435)
* Add selection mode with bulk remove to the Marketplace repositories page

* Guard bulk remove against double clicks and drop stale selections

* Clear the table selection when a selected repository gets installed

* Restore the comments that still apply

* Use a Marketplace string for the bulk action menu

* Drop rendering-only tests

* Uncheck data table rows that can no longer be selected

* Use one Remove chip and let the table drop installed rows

---------

Co-authored-by: Aidan Timson <[email protected]>
2026-11-10 14:40:47 +01:00
Zedas 06d564dbd8 End the ZHA permit subscription when the search ends (#55822)
* End the ZHA permit subscription when the search ends

* End the ZHA search when the connection drops

* Don't send a stale ZHA search after a reconnect
2026-11-10 14:19:10 +01:00
Petar Petrov 93f0c2c45a Hold the last value across gaps in history graphs (#55817)
* Hold the last value across gaps in history graphs

* Hold values across gaps in every graph, without an opt-in

* Hold the real last state across gaps and keep their curves tight

* Only hold stretches the raw history was quiet for

* Keep the temperature forecast curving across gaps

* Decide which stretches to hold once, from the raw history

* Hold neither across unavailable states nor below the sampling frame
2026-11-10 13:53:49 +01:00
renovate[bot] fb40d07621 Update dependency @html-eslint/eslint-plugin to v0.68.0 (#55825)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-10 11:53:04 +00:00
Zedas a6073e44f7 Translate the fold markers in the code editor (#55821) 2026-11-10 11:44:59 +00:00
Paulus SchoutsenandClaude Opus 5.5 df69f3c7ee Show which integrations use an integration loaded as a dependency (#55499)
* Show which integrations use an integration loaded as a dependency

Some integrations, like Modbus, have no config flow and are loaded
because another integration lists them in its manifest dependencies.
The frontend treated these as YAML integrations. The integration page
told the user to configure it in configuration.yaml, and the dashboard
showed a YAML card for it.

The integration page now fetches the loaded manifests for integrations
without a config flow. If a loaded integration depends on the domain,
the page shows "Used by <integrations>" instead of the YAML text. The
dashboard does not show a YAML card for a domain that a loaded
integration depends on.

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

* Show the integrations that use a dependency as linked cards

Replace the "Used by" text with a "Used by" section. It lists each
loaded integration that depends on this integration, with its logo and
a link to its integration page. The entries section shows "No entries"
instead of the YAML text for such an integration.

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

* Show only the "Used by" section for a dependency

An integration that other loaded integrations depend on, and that has no
config entries, now shows only the "Used by" section. The page does not
show the empty entries section. It also does not show the "Add entry"
button, which only opens the "set up in YAML" dialog for these
integrations.

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

* Match the demo Modbus and LoRaWAN manifests to core

Modbus and LoRaWAN have no config flow, and the integrations that use
them list them as dependencies. The demo now does the same, so their
integration pages show the "Used by" section.

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

* Hide system integrations from the "Used by" section

System integrations, like Default Configuration, depend on many
integrations. Listing them in "Used by" does not help the user.

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

* Read the dependents from the manifests context

The integration page now finds the integrations that depend on it from
the shared manifests context, instead of its own manifest/list call.
It subscribes to the context only for an integration without a config
flow, so other integration pages do not make the context fetch the
manifests.

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

* Link the integration page to the integration's settings panel

The Connectivity settings panels, like Zigbee and Modbus, are not
reachable from the integration page unless the integration has a config
entry. A user that opens the integration page looks for these settings.

The integration page now shows a button that opens the panel of the
integration. The button uses the panel name from the Connectivity page.
LoRaWAN, Modbus, Radio frequency, and USB (Serial) are added to the map
of integrations with a panel.

An integration with a panel and no config flow does not show the
"Add entry" button. For these integrations, it only opens the "set up
in YAML" dialog, and the panel is where to set them up.

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

* Hide the YAML texts for integrations set up in their panel

An integration with a settings panel and no config flow, like Infrared,
is set up in that panel. Its integration page told the user to set it up
in configuration.yaml. The page now shows only the settings button for
such an integration when it has no entries.

The demo Infrared and Radio frequency manifests now match core, so these
pages show it.

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

* Make the settings button primary when it is the only action

An integration that is set up in its panel shows no "Add entry" or
"Add device" button, so the settings button is its only action.

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

* Show the settings button only when there are no entries

Each config entry row of an integration with a panel already has a
link to that panel, so the button repeats it on pages like Zigbee.

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

* Link the MCP integration pages to the AI settings

The AI settings show how to connect to the MCP server and the URL of
each of its APIs. The MCP client and MCP server integration pages now
have an "AI settings" button that opens them. The button is the
primary action when the page has no "Add entry" button.

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

* Scroll the AI settings to the MCP card from the MCP pages

The AI settings page now scrolls to the section named in the URL hash,
like the backup settings page. The "AI settings" button on the MCP
integration pages links to the MCP card, which is below the AI task
card.

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

* Keep the demo route when opening the AI settings

The demo routes with the URL hash. The AI settings page cleared the
hash even when it did not name a section, so a reload of the demo lost
the page. It now clears the hash only after it scrolls to a section.

The "AI settings" button links to the page without a section in the
demo, because a link with a hash skips the demo route conversion.

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

* Move the settings panel and MCP buttons to their own PRs

This PR keeps the "Used by" section for integrations that other
integrations depend on. The settings panel button and the MCP link to
the AI settings move to separate PRs.

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

* Load the Modbus dependents in the demo

The dashboard reads the dependencies of loaded integrations only. The
demo listed Modbus as loaded, but not Flexit, SolarEdge Modbus, and
Fronius, so it showed a YAML card for Modbus.

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

* Sort the "Used by" list and wait for it before the YAML texts

The manifests come from a set in core, so their order can change
between restarts. The "Used by" list is now sorted by name.

Until the manifests load, the page does not know the dependents. It
showed the YAML texts and "Add entry" first and then replaced them with
"Used by". The page now holds back those texts and the button for an
integration without a config flow until the manifests load.

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

* Apply review feedback

- Make the settings button primary whenever it is the only action,
  like the MCP button. Thread, or MQTT with its one entry, have no
  "Add entry" button.
- Set the demo LoRaWAN manifest to the service type, like core, so the
  demo dashboard checks its dependents.
- Fix the punctuation of the YAML text.

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

* Show the entries while the dependents load

The page waits for the manifests of the loaded integrations before it
shows the YAML texts. If that request fails, the wait never ends. Only
a page without entries can show "Used by", so only such a page waits.
A page with entries now shows them even when the manifests do not load.

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

* Clear the manifest when the integration page changes domain

The integration page is reused when you follow a "Used by" link. It
kept the previous integration's manifest until the new one loaded, so
going back to Modbus from Flexit briefly showed "Add entry" and the
empty entries section. The page now clears the manifest on a domain
change, and a page without entries waits for the manifest before it
shows the YAML texts and "Add entry".

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-10 10:55:56 +01:00
328 changed files with 19738 additions and 10705 deletions

No files matched your search

+4 -4
View File
@@ -18,7 +18,7 @@ workflows:
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
'.github/workflows/codeql-analysis.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
'.github/workflows/copilot-setup-steps.yml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
@@ -151,9 +151,9 @@ dependencies:
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
owner_id: 7513068
repo_id: 113918130
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
ref: 'v4.39.1'
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
ref: 'v4.39.3'
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
owner_id: 9919
repo_id: 259445878
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
+2 -2
View File
@@ -32,12 +32,12 @@ jobs:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
languages: javascript-typescript
build-mode: none
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
category: "/language:javascript-typescript"
+1 -1
View File
@@ -1 +1 @@
24.22.2
24.22.3
+107 -42
View File
@@ -157,6 +157,99 @@ async function pollProcess(lokaliseApi, projectId, processId) {
}
/* eslint-enable no-await-in-loop */
const DRAFTS_ACCEPTED_KEYS = [
// Written per language rather than translated from English, so an English edit doesn't make them outdated
"ui.components.rooms.keywords",
];
async function exportTranslations(lokaliseApi, projectId) {
const exportProcess = await lokaliseApi.files().async_download(projectId, {
format: "json",
original_filenames: false,
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
});
const finishedProcess = await pollProcess(
lokaliseApi,
projectId,
exportProcess.process_id
);
const bundleUrl = finishedProcess.details.download_url;
console.log(`Downloading translations from: ${bundleUrl}`);
const response = await fetch(bundleUrl);
if (response.status !== 200 && response.status !== 0) {
throw new Error(response.statusText);
}
console.log(`Extracting translations...`);
const contents = await JSZip.loadAsync(await response.arrayBuffer());
const files = {};
await Promise.all(
Object.keys(contents.files).map(async (filename) => {
const file = contents.file(filename);
if (!file) {
// no file, probably a directory
return;
}
files[filename.split("/").splice(-1)[0]] = await file.async("string");
})
);
return files;
}
async function fetchDrafts(lokaliseApi, projectId) {
const english = JSON.parse(
await fs.readFile("src/translations/en.json", { encoding })
);
const keyNames = DRAFTS_ACCEPTED_KEYS.flatMap((key) => {
const keys = key.split(".");
const drafts = keys.reduce((obj, part) => obj?.[part], english) ?? {};
return Object.keys(drafts).map((name) => [...keys, name].join("::"));
});
if (!keyNames.length) {
return [];
}
const { items } = await lokaliseApi.keys().list({
project_id: projectId,
filter_keys: keyNames.join(","),
include_translations: 1,
limit: keyNames.length,
});
return items.flatMap((key) =>
key.translations
.filter(({ translation }) => translation)
.map(({ language_iso, translation }) => ({
filename: `${language_iso}.json`,
path: key.key_name.web.split("::"),
translation,
}))
);
}
function acceptDrafts(files, drafts) {
const data = {};
drafts.forEach(({ filename, path: keyPath, translation }) => {
data[filename] ??= files[filename] ? JSON.parse(files[filename]) : {};
const parent = keyPath.slice(0, -1).reduce((obj, part) => {
obj[part] ??= {};
return obj[part];
}, data[filename]);
parent[keyPath.at(-1)] = translation;
});
Object.entries(data).forEach(([filename, content]) => {
files[filename] = JSON.stringify(content, null, 2);
});
}
gulp.task("fetch-lokalise", async function () {
let apiKey;
try {
@@ -193,52 +286,24 @@ gulp.task("fetch-lokalise", async function () {
await Promise.all(
projects.map(async ([project, projectId]) => {
try {
const exportProcess = await lokaliseApi
.files()
.async_download(projectId, {
format: "json",
original_filenames: false,
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
});
const finishedProcess = await pollProcess(
lokaliseApi,
projectId,
exportProcess.process_id
);
const bundleUrl = finishedProcess.details.download_url;
console.log(`Downloading translations from: ${bundleUrl}`);
const response = await fetch(bundleUrl);
if (response.status !== 200 && response.status !== 0) {
throw new Error(response.statusText);
const [files, drafts] = await Promise.all([
exportTranslations(lokaliseApi, projectId),
project === "frontend"
? fetchDrafts(lokaliseApi, projectId)
: undefined,
]);
if (drafts) {
acceptDrafts(files, drafts);
}
console.log(`Extracting translations...`);
const contents = await JSZip.loadAsync(await response.arrayBuffer());
await mkdirPromise;
await Promise.all(
Object.keys(contents.files).map(async (filename) => {
const file = contents.file(filename);
if (!file) {
// no file, probably a directory
return;
}
const content = await file.async("nodebuffer");
await fs.writeFile(
path.join(inDir, project, filename.split("/").splice(-1)[0]),
content,
{ flag: "w", encoding }
);
})
Object.entries(files).map(([filename, content]) =>
fs.writeFile(path.join(inDir, project, filename), content, {
flag: "w",
encoding,
})
)
);
} catch (err) {
console.error(err);
+3 -1
View File
@@ -50,7 +50,9 @@ const convertToJSON = async (
const encodedData = localeData.match(
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
)?.groups?.data;
localeData = firstBlock.match(dataRegex)?.groups?.data;
localeData =
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
firstBlock.match(dataRegex)?.groups?.data;
if (!localeData && !encodedData) {
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
}
+2 -2
View File
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
:host {
display: block;
height: 100vh;
background-color: #f2f4f9;
background-color: var(--primary-background-color, #f2f4f9);
font-size: var(--ha-font-size-2xl);
}
.container {
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
object-fit: cover;
}
.status {
color: #1d2126;
color: var(--primary-text-color, #1d2126);
}
`;
}
@@ -44,14 +44,21 @@ export const lorawanFixtures: ConnectivityFixtures = {
],
commands: ["lorawan/"],
manifests: [
manifest("lorawan", "LoRaWAN", { integration_type: "helper" }),
manifest("lorawan", "LoRaWAN", {
config_flow: false,
integration_type: "service",
}),
manifest("sensecap_lorawan", "SenseCAP", {
integration_type: "device",
dependencies: ["lorawan"],
}),
manifest("chirpstack", "ChirpStack", { integration_type: "hub" }),
manifest("chirpstack", "ChirpStack", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
manifest("thethingsnetwork_lorawan", "The Things Network", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
],
configEntries: [
@@ -10,19 +10,26 @@ export const FRONIUS_ENTRY_ID = "mock-fronius";
export const RS485_PORT = "/dev/ttyUSB1";
export const modbusFixtures: ConnectivityFixtures = {
components: ["modbus"],
components: ["modbus", "flexit", "solaredge_modbus", "fronius"],
commands: ["modbus/"],
manifests: [
manifest("modbus", "Modbus", {
config_flow: false,
iot_class: "local_polling",
}),
manifest("flexit", "Flexit", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("solaredge_modbus", "SolarEdge Modbus", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("fronius", "Fronius", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
],
+24 -8
View File
@@ -8,7 +8,7 @@ import type {
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockEnergy = (hass: MockHomeAssistant) => {
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
const prefs: EnergyPreferences = {
energy_sources: [
{
type: "grid",
@@ -21,7 +21,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
entity_energy_price_export: null,
number_energy_price_export: null,
stat_rate: "sensor.power_grid",
cost_adjustment_day: 0,
},
{
type: "grid",
@@ -34,7 +33,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
entity_energy_price_export: null,
number_energy_price_export: null,
stat_rate: "sensor.power_grid_return",
cost_adjustment_day: 0,
},
{
type: "solar",
@@ -48,6 +46,23 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_energy_to: "sensor.battery_input",
stat_rate: "sensor.power_battery",
},
{
type: "battery",
name: "Powerwall",
stat_energy_from_grid: "sensor.powerwall_from_grid",
stat_energy_from_solar: "sensor.powerwall_from_solar",
stat_energy_to_home: "sensor.powerwall_to_home",
stat_energy_to_grid: "sensor.powerwall_to_grid",
stat_rate: "sensor.powerwall_power",
power_config: {
stat_rate_from_grid: "sensor.powerwall_power_from_grid",
stat_rate_from_solar: "sensor.powerwall_power_from_solar",
stat_rate_to_home: "sensor.powerwall_power_to_home",
stat_rate_to_grid: "sensor.powerwall_power_to_grid",
},
stat_soc: "sensor.powerwall_battery_level",
capacity: 13.5,
},
{
type: "gas",
stat_energy_from: "sensor.energy_gas",
@@ -105,16 +120,17 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
}));
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
energy_sources: Array.from({ length: 6 }, () => []),
device_consumption: Array.from({ length: 6 }, () => []),
device_consumption_water: Array.from({ length: 2 }, () => []),
device_consumption_gas: Array.from({ length: 2 }, () => []),
energy_sources: prefs.energy_sources.map(() => []),
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
+75
View File
@@ -1,3 +1,30 @@
// Live power of the battery measured per direction, in W
const powerwallPower = {
from_grid: 50,
from_solar: 150,
to_home: 0,
to_grid: 0,
};
const powerEntity = (entityId: string, power: number) => ({
entity_id: entityId,
state: String(power),
attributes: {
state_class: "measurement",
unit_of_measurement: "W",
},
});
const powerwallEnergyEntity = (entityId: string, friendlyName: string) => ({
entity_id: entityId,
state: "2",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
friendly_name: friendlyName,
unit_of_measurement: "kWh",
},
});
export const energyEntities = () =>
Object.values({
"sensor.grid_fossil_fuel_percentage": {
@@ -34,6 +61,31 @@ export const energyEntities = () =>
unit_of_measurement: "kWh",
},
},
"sensor.powerwall_from_grid": powerwallEnergyEntity(
"sensor.powerwall_from_grid",
"Powerwall charged from grid"
),
"sensor.powerwall_from_solar": powerwallEnergyEntity(
"sensor.powerwall_from_solar",
"Powerwall charged from solar"
),
"sensor.powerwall_to_home": powerwallEnergyEntity(
"sensor.powerwall_to_home",
"Powerwall discharged to home"
),
"sensor.powerwall_to_grid": powerwallEnergyEntity(
"sensor.powerwall_to_grid",
"Powerwall discharged to grid"
),
"sensor.powerwall_battery_level": {
entity_id: "sensor.powerwall_battery_level",
state: "62",
attributes: {
device_class: "battery",
friendly_name: "Powerwall battery level",
unit_of_measurement: "%",
},
},
"sensor.energy_consumption_tarif_1": {
entity_id: "sensor.energy_consumption_tarif_1",
state: "88.6",
@@ -134,6 +186,29 @@ export const energyEntities = () =>
unit_of_measurement: "W",
},
},
"sensor.powerwall_power_from_grid": powerEntity(
"sensor.powerwall_power_from_grid",
powerwallPower.from_grid
),
"sensor.powerwall_power_from_solar": powerEntity(
"sensor.powerwall_power_from_solar",
powerwallPower.from_solar
),
"sensor.powerwall_power_to_home": powerEntity(
"sensor.powerwall_power_to_home",
powerwallPower.to_home
),
"sensor.powerwall_power_to_grid": powerEntity(
"sensor.powerwall_power_to_grid",
powerwallPower.to_grid
),
"sensor.powerwall_power": powerEntity(
"sensor.powerwall_power",
powerwallPower.to_home +
powerwallPower.to_grid -
powerwallPower.from_grid -
powerwallPower.from_solar
),
"sensor.energy_gas_cost": {
entity_id: "sensor.energy_gas_cost",
state: "2",
+33 -6
View File
@@ -351,6 +351,26 @@ const statisticsFunctions: Record<
const derivedCosts: Record<string, { source: string; price: number }> = {
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
};
// Battery directions as a share of the meter the energy also passes, so they
// never exceed it
const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
"sensor.powerwall_from_grid": {
source: "sensor.energy_consumption_tarif_1",
share: 0.4,
},
"sensor.powerwall_from_solar": {
source: "sensor.solar_production",
share: 0.3,
},
"sensor.powerwall_to_home": {
source: "sensor.energy_consumption_tarif_2",
share: 0.5,
},
"sensor.powerwall_to_grid": {
source: "sensor.energy_production_tarif_2",
share: 0.3,
},
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
@@ -375,15 +395,22 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
return cache[id];
};
const scaleStats = (source: string, factor: number) => {
let sum = 0;
return getStats(source).map((statistic) => {
const change = statistic.change! * factor;
sum += change;
return { ...statistic, change, state: sum, sum };
});
};
statistic_ids.forEach((id: string) => {
if (id in derivedCosts) {
const { source, price } = derivedCosts[id];
let cost = 0;
statistics[id] = getStats(source).map((statistic) => {
const change = statistic.change! * price;
cost += change;
return { ...statistic, change, state: cost, sum: cost };
});
statistics[id] = scaleStats(source, price);
} else if (id in derivedBatteryFlows) {
const { source, share } = derivedBatteryFlows[id];
statistics[id] = scaleStats(source, share);
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
-1
View File
@@ -25,7 +25,6 @@ class DemoMoreInfo extends LitElement {
!computeShowNewMoreInfo(state)
? html`<state-card-content
.stateObj=${state}
.hass=${this.hass}
in-dialog
></state-card-content>`
: nothing
+24 -5
View File
@@ -117,11 +117,17 @@ shared slots/attributes below.
**Attributes**
| Name | Type | Default | Description |
| ----------------- | ------- | ------- | --------------------------------------- |
| `headline` | String | — | Primary text. Overridden by the slot. |
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
| Name | Type | Default | Description |
| ---------------------- | ------- | ------- | -------------------------------------------------- |
| `headline` | String | — | Primary text. Overridden by the slot. |
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
| `wrap-headline` | Boolean | `false` | Wrap the headline instead of truncating it. |
| `wrap-supporting-text` | Boolean | `false` | Wrap the supporting text instead of truncating it. |
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
The headline and the supporting text stay on one line and are truncated with an
ellipsis by default. Set `wrap-headline` or `wrap-supporting-text` on rows whose
text has to stay readable in full, like settings with a description.
**CSS parts**
@@ -165,6 +171,18 @@ Interactive row. Renders an inner `<a>` when `href` is set, otherwise a
roving tabindex, the host is the tab stop and the inner element carries
`tabindex="-1"`.
Only the headline and supporting text are inside the `<a>` or `<button>`; its
hit area is stretched over the whole row. The `start` and `end` slots sit next
to it, so controls placed there, like an `ha-icon-button` or `ha-dropdown`,
stay separate controls for screen readers. Slotted elements are raised above
the hit area so they can be clicked, except icons, badges, `span`s and empty
`div`s (dividers), which let clicks and hover through to the row. A focusable
element (with `tabindex`) is always raised. To keep another element clickable
on its own, like a drag handle, give it `z-index: 1` in the consumer's styles.
Subclasses customize the row by overriding `_renderStart()`,
`_renderContent()` and `_renderEnd()`. `_renderInner()` is not used.
**Attributes**
- `href` (String) — when set, renders an `<a>` instead of a `<button>`.
@@ -174,6 +192,7 @@ roving tabindex, the host is the tab stop and the inner element carries
**CSS parts**
- `control` — the inner `<a>` or `<button>`.
- `ripple` — the ripple effect element.
### `<ha-list-item-option>`
+80
View File
@@ -2,10 +2,12 @@ import {
mdiAccount,
mdiChevronRight,
mdiCog,
mdiDelete,
mdiHome,
mdiInformationOutline,
mdiMapMarker,
mdiOpenInNew,
mdiPencil,
mdiViewDashboard,
mdiWifi,
} from "@mdi/js";
@@ -13,6 +15,8 @@ import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, state } from "lit/decorators";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-icon-button";
import "../../../../src/components/ha-icon-next";
import "../../../../src/components/ha-svg-icon";
import "../../../../src/components/item/ha-list-item-base";
import "../../../../src/components/item/ha-list-item-button";
@@ -77,6 +81,8 @@ const treeKey = (group: TreeGroup, child: TreeChild) =>
export class DemoHaList extends LitElement {
@state() private _buttonClicks = 0;
@state() private _lastAction = "none";
@state() private _single: number | Set<number> = -1;
@state() private _multiLine: number | Set<number> = new Set();
@@ -185,6 +191,20 @@ export class DemoHaList extends LitElement {
<ha-list-item-base headline="Disabled row" disabled>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
<ha-list-item-base
headline="Truncated by default, a long headline stays on one line and ends with an ellipsis"
supporting-text="Long supporting text is truncated as well, so every row in the list keeps the same height"
>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
<ha-list-item-base
wrap-headline
wrap-supporting-text
headline="With wrap-headline, a long headline wraps onto as many lines as it needs"
supporting-text="With wrap-supporting-text, long supporting text wraps too, which suits settings with a description"
>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
</ha-list-base>
</ha-card>
@@ -220,6 +240,51 @@ export class DemoHaList extends LitElement {
</ha-list-base>
</ha-card>
<ha-card header="Row with actions in the end slot">
<p class="card-text">
Last action: <code>${this._lastAction}</code>. The action buttons are
separate controls; icons and the divider activate the row.
</p>
<ha-list-base aria-label="Rows with actions">
<ha-list-item-button data-action="row" @click=${this._onActionClick}>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
<span slot="headline">Button row</span>
<span slot="supporting-text">Click the row or an action</span>
<ha-icon-next slot="end"></ha-icon-next>
<div slot="end" class="vertical-divider"></div>
<ha-icon-button
slot="end"
data-action="edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-button
slot="end"
data-action="delete"
.path=${mdiDelete}
label="Delete"
@click=${this._onActionClick}
></ha-icon-button>
</ha-list-item-button>
<ha-list-item-button href="#components/ha-list">
<ha-svg-icon slot="start" .path=${mdiMapMarker}></ha-svg-icon>
<span slot="headline">Link row</span>
<span slot="supporting-text"
>Cmd/Ctrl-click on the icon or chevron opens a new tab</span
>
<ha-icon-button
slot="end"
data-action="link-edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
</ha-list-base>
</ha-card>
<h2>ha-list-selectable + ha-list-item-option</h2>
<p>
Selectable list (<code>role="listbox"</code>). Items must be
@@ -428,6 +493,12 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
return value instanceof Set ? [...value] : value;
}
private _onActionClick = (ev: MouseEvent) => {
ev.stopPropagation();
this._lastAction =
(ev.currentTarget as HTMLElement).dataset.action ?? "none";
};
private _onButtonClick = () => {
this._buttonClicks++;
};
@@ -542,6 +613,15 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
ha-card {
max-width: 560px;
}
.card-text {
margin: 0;
padding: 0 var(--ha-space-4) var(--ha-space-2);
}
.vertical-divider {
align-self: stretch;
width: 1px;
background: var(--divider-color);
}
pre {
padding: var(--ha-space-4);
background: var(--secondary-background-color);
+133
View File
@@ -187,6 +187,139 @@ const ENTITIES = [
current_tilt_position: 70,
},
},
{
entity_id: "cover.shade",
state: "open",
attributes: {
friendly_name: "Shade",
device_class: "shade",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 60,
},
},
{
entity_id: "cover.shutter",
state: "open",
attributes: {
friendly_name: "Shutter",
device_class: "shutter",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 40,
},
},
{
entity_id: "cover.awning",
state: "open",
attributes: {
friendly_name: "Awning",
device_class: "awning",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 70,
},
},
{
entity_id: "cover.curtain",
state: "open",
attributes: {
friendly_name: "Curtain",
device_class: "curtain",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 50,
},
},
{
entity_id: "cover.door",
state: "open",
attributes: {
friendly_name: "Door",
device_class: "door",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 30,
},
},
{
entity_id: "cover.gate",
state: "open",
attributes: {
friendly_name: "Gate",
device_class: "gate",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 30,
},
},
{
entity_id: "cover.window",
state: "open",
attributes: {
friendly_name: "Window",
device_class: "window",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 50,
},
},
{
entity_id: "cover.garage",
state: "closed",
attributes: {
friendly_name: "Garage door",
device_class: "garage",
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
},
},
{
entity_id: "cover.unknown",
state: "unknown",
attributes: {
friendly_name: "Unknown position",
device_class: "shade",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
},
},
{
entity_id: "cover.unavailable",
state: "unavailable",
attributes: {
friendly_name: "Unavailable",
device_class: "shutter",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
},
},
];
@customElement("demo-more-info-cover")
+33 -33
View File
@@ -40,7 +40,7 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.1.0",
"@babel/runtime": "8.1.2",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.4",
"@codemirror/commands": "6.11.1",
@@ -48,21 +48,21 @@
"@codemirror/lang-python": "6.2.1",
"@codemirror/lang-yaml": "6.1.3",
"@codemirror/language": "6.13.1",
"@codemirror/lint": "6.9.7",
"@codemirror/lint": "6.9.8",
"@codemirror/search": "6.7.2",
"@codemirror/state": "6.7.6",
"@codemirror/view": "6.43.15",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "8.0.2",
"@formatjs/intl-displaynames": "8.0.1",
"@formatjs/intl-durationformat": "0.12.3",
"@formatjs/intl-getcanonicallocales": "3.3.0",
"@formatjs/intl-listformat": "9.0.1",
"@formatjs/intl-locale": "5.4.2",
"@formatjs/intl-numberformat": "10.0.2",
"@formatjs/intl-pluralrules": "7.0.2",
"@formatjs/intl-relativetimeformat": "13.0.1",
"@formatjs/intl-datetimeformat": "8.0.3",
"@formatjs/intl-displaynames": "8.0.3",
"@formatjs/intl-durationformat": "0.12.4",
"@formatjs/intl-getcanonicallocales": "3.3.1",
"@formatjs/intl-listformat": "9.0.3",
"@formatjs/intl-locale": "5.4.3",
"@formatjs/intl-numberformat": "10.0.4",
"@formatjs/intl-pluralrules": "7.0.4",
"@formatjs/intl-relativetimeformat": "13.0.3",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.5",
"@lezer/highlight": "1.2.5",
@@ -77,18 +77,18 @@
"@mdi/svg": "7.4.47",
"@replit/codemirror-indentation-markers": "6.5.3",
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.3",
"@tsparticles/preset-links": "4.5.3",
"@versatiles/style": "8.1.1",
"@tsparticles/engine": "4.5.4",
"@tsparticles/preset-links": "4.5.4",
"@versatiles/style": "9.1.0",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.203.0",
"@vvo/tzdb": "6.204.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10",
"barcode-detector": "3.2.3",
"cally": "0.9.2",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
"cropperjs": "1.7.0",
"cropperjs": "2.3.1",
"culori": "4.0.2",
"date-fns": "4.4.0",
"decimal.js": "10.6.0",
@@ -97,19 +97,19 @@
"echarts": "6.1.0",
"echarts-extension-chart2music": "0.1.1",
"element-internals-polyfill": "3.0.2",
"fullcalendar": "7.1.4",
"fullcalendar": "7.1.5",
"fuse.js": "7.5.0",
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.8.1",
"idb-keyval": "6.3.0",
"intl-messageformat": "12.1.4",
"intl-messageformat": "12.1.5",
"js-yaml": "5.5.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.16.0",
"marked": "18.1.3",
"maplibre-gl": "6.18.0",
"marked": "18.2.0",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
@@ -136,24 +136,24 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.1.0",
"@babel/core": "8.1.2",
"@babel/helper-compilation-targets": "8.0.7",
"@babel/helper-define-polyfill-provider": "1.0.0",
"@babel/plugin-transform-class-properties": "8.0.1",
"@babel/plugin-transform-private-methods": "8.0.1",
"@babel/plugin-transform-runtime": "8.0.6",
"@babel/plugin-transform-runtime": "8.1.2",
"@babel/preset-env": "8.0.7",
"@bundle-stats/plugin-webpack-filter": "4.23.1",
"@eslint/js": "10.0.1",
"@gfx/zopfli": "1.0.15",
"@home-assistant/components": "workspace:*",
"@html-eslint/eslint-plugin": "0.67.0",
"@html-eslint/eslint-plugin": "0.68.0",
"@lokalise/node-api": "17.0.1",
"@octokit/auth-oauth-device": "8.0.5",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.0",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.1",
"@rspack/core": "2.3.2",
"@rspack/dev-server": "2.2.2",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
@@ -180,7 +180,7 @@
"eslint": "10.14.0",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.0",
"eslint-plugin-import-x": "4.18.1",
"eslint-plugin-lit": "2.3.1",
"eslint-plugin-lit-a11y": "5.1.3",
"eslint-plugin-unused-imports": "4.4.1",
@@ -188,14 +188,14 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "14.0.4",
"glob": "14.0.6",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
"gulp-rename": "2.1.0",
"html-minifier-terser": "7.2.0",
"husky": "9.1.7",
"jsdom": "31.0.0",
"jsdom": "31.0.1",
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
@@ -206,24 +206,24 @@
"map-stream": "0.0.7",
"minify-literals": "2.2.0",
"pinst": "3.0.0",
"prettier": "3.9.10",
"prettier": "3.10.1",
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.7",
"sinon": "22.1.0",
"tar": "7.5.22",
"tar": "7.5.23",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.72.1",
"vite": "8.3.6",
"typescript-eslint": "8.72.2",
"vite": "8.3.8",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.0",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "pnpm@12.18.0",
"packageManager": "pnpm@12.20.0",
"volta": {
"node": "24.22.2"
"node": "24.22.3"
}
}
+1 -1
View File
@@ -53,7 +53,7 @@
},
"devDependencies": {
"@custom-elements-manifest/analyzer": "0.11.0",
"@rslib/core": "1.0.6",
"@rslib/core": "1.0.7",
"lit": "3.3.3",
"typescript": "6.0.3"
}
+1153 -1055
View File
File diff suppressed because it is too large. Load diff
@@ -89,10 +89,19 @@ export class LegendFitController {
private _fit() {
const list = this._element;
const rowWidth = list?.getBoundingClientRect().width;
if (!list || !rowWidth) {
if (!list) {
return;
}
const style = getComputedStyle(list);
const rowWidth = parseFloat(style.width);
// Bounding rects include transforms, such as a dialog scaling in, which
// never resize the list, so measure in layout pixels
const scale = list.getBoundingClientRect().width / rowWidth;
if (!rowWidth || !scale) {
return;
}
const layoutWidth = (element: Element) =>
element.getBoundingClientRect().width / scale;
const children = Array.from(list.children);
const more = children.find((child) =>
child.classList.contains("legend-more")
@@ -107,9 +116,7 @@ export class LegendFitController {
}
this._more = more;
}
const widths = children
.filter((child) => child !== more)
.map((child) => child.getBoundingClientRect().width);
const widths = children.filter((child) => child !== more).map(layoutWidth);
// Values resize the items on every state update. Fitting each item at its
// widest since the last resize keeps the more button from flickering.
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
@@ -122,9 +129,9 @@ export class LegendFitController {
}
const fit = fitInRows(
this._widths,
more?.getBoundingClientRect().width ?? 0,
more ? layoutWidth(more) : 0,
rowWidth,
parseFloat(getComputedStyle(list).columnGap) || 0,
parseFloat(style.columnGap) || 0,
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
);
if (fit !== this.fit) {
+29
View File
@@ -0,0 +1,29 @@
const INTERACTIVE_SELECTOR = [
"a[href]",
"button",
"input",
"select",
"textarea",
"summary",
"label",
"[contenteditable]:not([contenteditable='false'])",
"[tabindex]:not([tabindex='-1'])",
"[role='button']",
"[role='link']",
"[role='checkbox']",
"[role='radio']",
"[role='switch']",
"[role='slider']",
"[role='tab']",
"[role='menuitem']",
"[role='option']",
"[role='combobox']",
"[role='textbox']",
].join(",");
/**
* Whether `node` is an element that handles clicks or keyboard input on its
* own, such as a button, link, form control or a focusable widget.
*/
export const isInteractiveElement = (node: EventTarget): boolean =>
node instanceof Element && node.matches(INTERACTIVE_SELECTOR);
+1
View File
@@ -3,6 +3,7 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
"ha-slider",
"ha-control-switch",
"ha-control-circular-slider",
"ha-state-control-cover",
"ha-hs-color-picker",
"ha-map",
// Charts pan and pinch-zoom on touch
+5 -5
View File
@@ -1,12 +1,12 @@
import type { HomeAssistant } from "../../types";
import type { HassServices } from "home-assistant-js-websocket";
import { getToggleAction } from "./get_toggle_action";
export const canToggleDomain = (hass: HomeAssistant, domain: string) => {
const services = hass.services[domain];
if (!services) {
export const canToggleDomain = (services: HassServices, domain: string) => {
const domainServices = services[domain];
if (!domainServices) {
return false;
}
const actionOn = getToggleAction(domain, true);
const actionOff = getToggleAction(domain, false);
return actionOn in services && actionOff in services;
return actionOn in domainServices && actionOff in domainServices;
};
+13 -6
View File
@@ -1,23 +1,30 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HomeAssistant } from "../../types";
import type {
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import { canToggleDomain } from "./can_toggle_domain";
import { computeStateDomain } from "./compute_state_domain";
import { supportsFeature } from "./supports-feature";
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
export const canToggleState = (
states: HassEntities,
services: HassServices,
stateObj: HassEntity
) => {
const domain = computeStateDomain(stateObj);
if (domain === "group") {
if (
stateObj.attributes?.entity_id?.some((entity) => {
const entityStateObj = hass.states[entity];
const entityStateObj = states[entity];
if (!entityStateObj) {
return false;
}
const entityDomain = computeStateDomain(entityStateObj);
return canToggleDomain(hass, entityDomain);
return canToggleDomain(services, entityDomain);
})
) {
return stateObj.state === "on" || stateObj.state === "off";
@@ -35,5 +42,5 @@ export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
);
}
return canToggleDomain(hass, domain);
return canToggleDomain(services, domain);
};
+12 -2
View File
@@ -4,16 +4,23 @@ import {
mdiArrowDown,
mdiArrowExpandHorizontal,
mdiArrowUp,
mdiDoorClosed,
mdiDoorOpen,
mdiGate,
mdiGateOpen,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
export const computeOpenIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "awning":
case "door":
return mdiDoorOpen;
case "gate":
return mdiGateOpen;
case "curtain":
return mdiArrowExpandHorizontal;
case "awning":
return mdiArrowDown;
default:
return mdiArrowUp;
}
@@ -21,11 +28,14 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
export const computeCloseIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "awning":
case "door":
return mdiDoorClosed;
case "gate":
return mdiGate;
case "curtain":
return mdiArrowCollapseHorizontal;
case "awning":
return mdiArrowUp;
default:
return mdiArrowDown;
}
+11 -4
View File
@@ -1,11 +1,18 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type {
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import { UNAVAILABLE } from "../../data/entity/entity";
import type { HomeAssistant } from "../../types";
import { DOMAINS_WITH_CARD } from "../const";
import { canToggleState } from "./can_toggle_state";
import { computeStateDomain } from "./compute_state_domain";
export const stateCardType = (hass: HomeAssistant, stateObj: HassEntity) => {
export const stateCardType = (
states: HassEntities,
services: HassServices,
stateObj: HassEntity
) => {
if (stateObj.state === UNAVAILABLE) {
return "display";
}
@@ -16,7 +23,7 @@ export const stateCardType = (hass: HomeAssistant, stateObj: HassEntity) => {
return domain;
}
if (
canToggleState(hass, stateObj) &&
canToggleState(states, services, stateObj) &&
stateObj.attributes.control !== "hidden"
) {
return "toggle";
@@ -0,0 +1,33 @@
import type { LocalizeFunc } from "./localize";
const YAML_ERROR_REASON_KEYS = new Map(
Object.entries({
"duplicated mapping key": "duplicated_mapping_key",
"bad indentation of a mapping entry": "bad_mapping_indentation",
"bad indentation of a sequence entry": "bad_sequence_indentation",
"deficient indentation": "deficient_indentation",
"tab characters must not be used in indentation": "tab_indentation",
"can not read a block mapping entry; a multiline key may not be an implicit key":
"multiline_implicit_key",
"a whitespace character is expected after the key-value separator within a block mapping":
"missing_key_value_space",
"expected ':' after a mapping key": "missing_colon",
"missed comma between flow collection entries": "missing_comma",
"unexpected end of the stream within a flow collection":
"unterminated_flow_collection",
"unexpected end of the stream within a single quoted scalar":
"unterminated_single_quote",
"unexpected end of the stream within a double quoted scalar":
"unterminated_double_quote",
"end of the stream or a document separator is expected":
"unexpected_content",
} as const)
);
export const localizeYamlErrorReason = (
localize: LocalizeFunc,
reason: string | undefined
): string | undefined => {
const key = reason ? YAML_ERROR_REASON_KEYS.get(reason) : undefined;
return key ? localize(`ui.components.yaml-editor.reasons.${key}`) : reason;
};
-16
View File
@@ -5,19 +5,3 @@ export const stringifyPath = (path: ConfigPath): string => path.join("/");
export const pathEquals = (a: ConfigPath, b: ConfigPath): boolean =>
a.length === b.length && a.every((segment, index) => segment === b[index]);
export const pathStartsWith = (path: ConfigPath, prefix: ConfigPath): boolean =>
prefix.length <= path.length &&
prefix.every((segment, index) => segment === path[index]);
/** Formats a path the way it reads in YAML, e.g. `actions[1].then[0].delay`. */
export const formatPath = (path: ConfigPath): string =>
path
.map((segment, index) =>
typeof segment === "number"
? `[${segment}]`
: index === 0
? segment
: `.${segment}`
)
.join("");
+55 -23
View File
@@ -30,13 +30,40 @@ export class HaAutomationRow extends LitElement {
@property({ type: Boolean, reflect: true })
public dim = false;
@property({ type: Boolean, reflect: true })
public error = false;
/** Makes the row a link, with the icons slot outside of it */
@property() public href?: string;
@query(".row")
private _rowElement?: HTMLDivElement;
@query(".link")
private _linkElement?: HTMLAnchorElement;
protected render(): TemplateResult {
const content = html`
<div class="leading-icon-wrapper">
<slot name="leading-icon"></slot>
</div>
<div class="header">
<slot name="header"></slot>
<slot name="event"></slot>
</div>
`;
const icons = html`
<div class="icons">
<slot name="icons"></slot>
</div>
`;
if (this.href) {
return html`
<div class="row has-link">
<a class="link" href=${this.href}>${content}</a>
${icons}
</div>
`;
}
return html`
<div
class="row"
@@ -56,17 +83,7 @@ export class HaAutomationRow extends LitElement {
`
: nothing
}
<div class="leading-icon-wrapper">
<slot name="leading-icon"></slot>
</div>
<div class="header">
<slot name="header"></slot>
<slot name="event"></slot>
</div>
<div class="icons">
<slot name="icons"></slot>
</div>
${content} ${icons}
</div>
`;
}
@@ -122,7 +139,7 @@ export class HaAutomationRow extends LitElement {
public focus() {
requestAnimationFrame(() => {
this._rowElement?.focus();
(this._linkElement ?? this._rowElement)?.focus();
});
}
@@ -147,6 +164,30 @@ export class HaAutomationRow extends LitElement {
outline: var(--wa-focus-ring);
outline-offset: -2px;
}
.row.has-link {
padding-left: 0;
padding-inline-start: 0;
cursor: default;
}
.link {
display: flex;
align-items: flex-start;
align-self: stretch;
flex: 1;
min-width: 0;
padding-left: var(--ha-space-3);
padding-inline-start: var(--ha-space-3);
padding-inline-end: initial;
color: inherit;
text-decoration: none;
cursor: pointer;
outline: none;
border-radius: inherit;
}
.link:focus-visible {
outline: var(--wa-focus-ring);
outline-offset: -2px;
}
.expand-button {
transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
color: var(--ha-color-on-neutral-quiet);
@@ -235,15 +276,6 @@ export class HaAutomationRow extends LitElement {
:host([highlight]) .row:hover {
background-color: rgba(var(--rgb-primary-color), 0.16);
}
:host([error]) .row {
background-color: var(--ha-color-fill-danger-quiet-resting);
}
:host([error][selected]) .row,
:host([error][selected]) .row:focus {
outline: 2px solid var(--ha-color-border-danger-loud);
outline-offset: -2px;
background-color: var(--ha-color-fill-danger-normal-resting);
}
.icons,
.leading-icon-wrapper,
+6 -5
View File
@@ -19,6 +19,7 @@ interface MinMaxFrame {
maxPoint: Point;
maxX: number;
maxY: number;
lastX: number;
gapPoint: Point | undefined;
}
@@ -68,6 +69,7 @@ function newFrame(
maxPoint: point,
maxX: x,
maxY: y,
lastX: x,
gapPoint,
};
}
@@ -174,6 +176,7 @@ export function downSampleLineData<
if (!frame) {
frames.set(frameIndex, newFrame(point, x, y, undefined));
} else if (frame.hasValue) {
frame.lastX = x;
// Match the original strict-less / strict-greater comparisons so the
// first occurrence wins on ties.
if (y < frame.minY) {
@@ -189,6 +192,7 @@ export function downSampleLineData<
} else {
// the frame held nothing but a marker so far
frame.hasValue = true;
frame.lastX = x;
frame.minPoint = point;
frame.minX = x;
frame.minY = y;
@@ -213,11 +217,8 @@ export function downSampleLineData<
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.
// The kept points are exactly min and max, so comparing against the
// later of the two catches that without any work on the ingest path. A
// marker-only frame compares against its own x and always passes.
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
// 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);
}
}
+160 -27
View File
@@ -76,6 +76,18 @@ export interface NetworkData {
const PHYSICS_DISABLE_THRESHOLD = 512;
const LAYOUT_ANIMATION_THRESHOLD = 100;
// Every event of a change of the legend selection, each with the whole
// selection
const LEGEND_SELECT_EVENTS = [
"legendselectchanged",
"legendselected",
"legendunselected",
"legendselectall",
"legendinverseselect",
];
const SELECTED_NODE_MAX_ZOOM = 2;
// Keeps neighbors clear of the search field, buttons and legend
@@ -124,8 +136,22 @@ export class HaNetworkGraph extends LitElement {
@state() private _showLabels = true;
// Not reactive: a new series option starts the layout again, so a drop only
// reaches the option with the next render
private _nodePositions: Record<string, { x: number; y: number }> = {};
// Dragged nodes stay where they are dropped, the force layout moves the others
private _pinnedNodes: string[] = [];
// Names of the legend categories that are switched off. Not reactive: the
// legend lays the graph out itself, only the layout animation threshold
// needs a render
private _hiddenCategories: string[] = [];
private _dragNode?: string;
private _dragMoved = false;
private _followSelectedNode = false;
private _followedChart?: EChartsType;
@@ -170,12 +196,15 @@ export class HaNetworkGraph extends LitElement {
this._showLabels,
isMobile,
hasHighlightedNodes,
this.selectedNode
this.selectedNode,
this._nodePositions,
this._pinnedNodes,
this._fewVisibleNodes()
)}
.options=${this._createOptions(this.data?.categories)}
height="100%"
.extraComponents=${[GraphChart]}
@chart-setup=${this._updateFollowing}
@chart-setup=${this._handleChartSetup}
>
<slot name="search" slot="search"></slot>
<slot name="button" slot="button"></slot>
@@ -273,7 +302,10 @@ export class HaNetworkGraph extends LitElement {
showLabels: boolean,
isMobile: boolean,
hasHighlightedNodes?: boolean,
selectedNode?: string
selectedNode?: string,
nodePositions: Record<string, { x: number; y: number }> = {},
pinnedNodes: string[] = [],
fewVisibleNodes = true
) => ({
id: "network",
type: "graph",
@@ -311,14 +343,15 @@ export class HaNetworkGraph extends LitElement {
repulsion: [400, 600],
edgeLength: [200, 350],
gravity: 0.05,
layoutAnimation: !reducedMotion && data.nodes.length < 100,
layoutAnimation: !reducedMotion && fewVisibleNodes,
},
edgeSymbol: ["none", "arrow"],
edgeSymbolSize: 10,
data: this._getSeriesData(
data.nodes,
data.links,
this._nodePositions,
nodePositions,
pinnedNodes,
selectedNode
),
links: data.links.map((link) => ({
@@ -334,11 +367,25 @@ export class HaNetworkGraph extends LitElement {
deepEqual
);
// The legend leaves the nodes of hidden categories out of the layout
private _fewVisibleNodes() {
const hidden = this._hiddenCategories;
const visibleNodes = hidden.length
? this.data.nodes.filter(
(node) =>
node.category === undefined ||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
).length
: this.data.nodes.length;
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
}
private _getSeriesData = memoizeOne(
(
nodes: NetworkNode[],
links: NetworkLink[],
nodePositions: Record<string, { x: number; y: number }>,
pinnedNodes: string[],
selectedNode?: string
) =>
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
@@ -355,7 +402,7 @@ export class HaNetworkGraph extends LitElement {
? { ...node.itemStyle, borderWidth: 3 }
: node.itemStyle || {},
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
fixed: node.fixed,
fixed: node.fixed || pinnedNodes.includes(node.id),
x: node.x,
y: node.y,
} as NonNullable<GraphSeriesOption["data"]>[number];
@@ -515,6 +562,90 @@ export class HaNetworkGraph extends LitElement {
}
}
private _handleChartSetup() {
const chart = this._baseChart?.chart;
chart?.on("mousedown", this._handleNodeMouseDown);
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
const legend = (
chart?.getOption() as
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
)?.legend?.[0];
this._setHiddenCategories(legend?.selected ?? {});
// A recreated chart, e.g. after a theme change, lacks the drops since the
// last render
this.requestUpdate();
this._updateFollowing();
}
private _handleLegendChange = (params: unknown) => {
const fewVisibleNodes = this._fewVisibleNodes();
this._setHiddenCategories(
(params as { selected: Record<string, boolean> }).selected
);
if (this._fewVisibleNodes() !== fewVisibleNodes) {
// The new series option lays out again from where the nodes are now
this._saveNodePositions();
this.requestUpdate();
}
};
private _setHiddenCategories(selected: Record<string, boolean>) {
this._hiddenCategories = Object.keys(selected).filter(
(name) => !selected[name]
);
}
private _handleNodeMouseDown = (params: {
dataType?: string;
data?: unknown;
}) => {
this._dragNode =
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
this._dragMoved = false;
};
private _handleDrag = () => {
this._dragMoved = true;
};
private _handleDragEnd = () => {
const id = this._dragNode;
const moved = this._dragMoved;
this._dragNode = undefined;
this._dragMoved = false;
// A click also ends a drag, which releases a pinned node in ECharts
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
return;
}
this._pinNodeInChart(id);
if (!this._pinnedNodes.includes(id)) {
this._pinnedNodes = [...this._pinnedNodes, id];
}
this._saveNodePositions();
};
// A new series option would start the layout again, so the pin goes into
// the running force layout, and into the item option that ECharts lays out
// from again, e.g. on a legend change
private _pinNodeInChart(id: string) {
const series = this._getGraphSeries();
const node = series?.getGraph().getNodeById(id);
if (!node) {
return;
}
series.forceLayout?.setFixed(node.dataIndex);
const [x, y] = node.getLayout();
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
fixed: true,
x,
y,
});
}
private _updateFollowing() {
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
if (chart !== this._followedChart) {
@@ -550,10 +681,7 @@ export class HaNetworkGraph extends LitElement {
if (!chart) {
return;
}
const series: any = chart
// @ts-ignore private method but no other way to get the graph positions
.getModel()
.getSeriesByIndex(0);
const series = this._getGraphSeries(chart);
const node = series?.getGraph().getNodeById(this.selectedNode);
const position: number[] | undefined = node?.getLayout();
if (!position) {
@@ -614,6 +742,7 @@ export class HaNetworkGraph extends LitElement {
private _togglePhysics() {
this._saveNodePositions();
this._pinnedNodes = [];
this._physicsEnabled = !this._physicsEnabled;
}
@@ -622,26 +751,30 @@ export class HaNetworkGraph extends LitElement {
}
private _saveNodePositions() {
const positions = {};
if (this._baseChart?.chart) {
this._baseChart.chart
// @ts-ignore private method but no other way to get the graph positions
.getModel()
.getSeriesByIndex(0)
.getGraph()
.eachNode((node: any) => {
const layout = node.getLayout();
if (layout) {
positions[node.id] = {
x: layout[0],
y: layout[1],
};
}
});
}
// Nodes that are not drawn keep their earlier position
const positions = { ...this._nodePositions };
this._getGraphSeries()
?.getGraph()
.eachNode((node: any) => {
const layout = node.getLayout();
if (layout) {
positions[node.id] = {
x: layout[0],
y: layout[1],
};
}
});
this._nodePositions = positions;
}
private _getGraphSeries(chart = this._baseChart?.chart): any {
if (!chart || chart.isDisposed()) {
return undefined;
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
}
static styles = css`
:host {
display: block;
+18 -15
View File
@@ -35,24 +35,27 @@ function computeTimelineStateColor(
const domain = computeDomain(stateObj.entity_id);
// Zone states for person/device_tracker don't have specific CSS color variables,
// so they all fall back to the same --state-person-active-color.
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
// otherwise return undefined to get unique colors from the generic color handler.
if (
// Zone states would all share --state-person-active-color, so only an
// exact state variable may color them, like states of uncolored domains.
const isZoneState =
(domain === "person" || domain === "device_tracker") &&
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
) {
return computeCssValue(
`--state-${domain}-${slugify(state, "_")}-color`,
computedStyles
);
}
const properties = stateColorProperties(stateObj, state);
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
const properties = isZoneState
? undefined
: stateColorProperties(stateObj, state);
if (!properties) {
return undefined;
const stateKey = slugify(state, "_");
const deviceClass = stateObj.attributes.device_class;
return computeCssValue(
[
...(deviceClass
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
: []),
`--state-${domain}-${stateKey}-color`,
],
computedStyles
);
}
const rgb = computeCssValue(properties, computedStyles);
+6 -2
View File
@@ -401,9 +401,13 @@ export class HaDataTable extends LitElement {
}
if (properties.has("data")) {
// Clean up checked rows that no longer exist in the data
// Clean up checked rows that no longer exist or can no longer be selected
if (this._checkedRows.length) {
const validIds = new Set(this.data.map((row) => String(row[this.id])));
const validIds = new Set(
this.data
.filter((row) => row.selectable !== false)
.map((row) => String(row[this.id]))
);
const validCheckedRows = this._checkedRows.filter((id) =>
validIds.has(id)
);
@@ -14,12 +14,6 @@ class HaDeviceActionPicker extends HaDeviceAutomationPicker<DeviceAction> {
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.unknown_action"
@@ -49,10 +49,6 @@ export abstract class HaDeviceAutomationPicker<
@property({ type: Object }) public value?: T;
@property({ type: Boolean }) public invalid = false;
@property({ attribute: "error-message" }) public errorMessage?: string;
@state() private _automations?: T[];
// Trigger an empty render so we start with a clean DOM.
@@ -110,13 +106,6 @@ export abstract class HaDeviceAutomationPicker<
);
}
/** Error shown when the picked device has nothing to choose from. */
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.not_supported"
);
}
private _localizeDeviceAutomation: (
localize: LocalizeFunc,
states: HassEntities,
@@ -174,12 +163,6 @@ export abstract class HaDeviceAutomationPicker<
.value=${value}
.disabled=${this._automations?.length === 0}
.loading=${this._automations === undefined}
.invalid=${this.invalid}
.errorMessage=${
this._automations?.length === 0
? this.NOT_SUPPORTED_TEXT
: this.errorMessage
}
.getItems=${this._getItems(
value,
this._automations,
@@ -14,12 +14,6 @@ class HaDeviceConditionPicker extends HaDeviceAutomationPicker<DeviceCondition>
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.conditions.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.conditions.unknown_condition"
@@ -107,10 +107,6 @@ export class HaDevicePicker extends LitElement {
@property() public helper?: string;
@property({ type: Boolean }) public invalid = false;
@property({ attribute: "error-message" }) public errorMessage?: string;
@property() public placeholder?: string;
@property({ type: String, attribute: "search-label" })
@@ -525,8 +521,6 @@ export class HaDevicePicker extends LitElement {
.autofocus=${this.autofocus}
.disabled=${this.disabled}
.helper=${this.helper}
.invalid=${this.invalid}
.errorMessage=${this.errorMessage}
.label=${this.label}
.searchLabel=${this.searchLabel}
.notFoundLabel=${this._notFoundLabel}
@@ -14,12 +14,6 @@ class HaDeviceTriggerPicker extends HaDeviceAutomationPicker<DeviceTrigger> {
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.triggers.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.triggers.unknown_trigger"
+18 -19
View File
@@ -371,25 +371,24 @@ export class HaEntityPicker extends LitElement {
excludeEntities?: string[],
value?: string
) =>
getEntities(
{
states,
...registries,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
localize: i18n.localize,
},
{
includeDomains,
excludeDomains,
entityFilter,
includeDeviceClasses,
includeUnitOfMeasurement,
includeEntities,
excludeEntities,
value,
}
)
getEntities({
states,
entities: registries.entities,
devices: registries.devices,
areas: registries.areas,
floors: registries.floors,
localize: i18n.localize,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
includeDomains,
excludeDomains,
entityFilter,
includeDeviceClasses,
includeUnitOfMeasurement,
includeEntities,
excludeEntities,
value,
})
);
private _sortByRelatedContext = memoizeOne(
+1 -1
View File
@@ -52,7 +52,7 @@ class StateInfo extends LitElement {
${
this.inDialog
? html`<div class="time-ago">
<ha-tooltip for="relative-time">
<ha-tooltip for="relative-time" trigger="hover focus click">
<div class="row">
<span class="column-name">
${this._localize(
+55 -94
View File
@@ -6,7 +6,7 @@ import { repeat } from "lit/directives/repeat";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { fireEvent } from "../common/dom/fire_event";
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
import { supportsFeature } from "../common/entity/supports-feature";
import {
CameraEntityFeature,
@@ -17,8 +17,14 @@ import {
STREAM_TYPE_WEB_RTC,
type CameraCapabilities,
type CameraEntity,
type StreamType,
} from "../data/camera";
import {
MJPEG_STREAM,
selectCameraStreams,
type CameraStream,
type CameraStreamTracks,
type CameraStreamType,
} from "../data/camera-streams";
import {
apiContext,
configContext,
@@ -29,14 +35,7 @@ import "./ha-hls-player";
import "./ha-web-rtc-player";
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
const MJPEG_STREAM = "mjpeg";
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
interface Stream {
type: CameraStreamType;
visible: boolean;
}
export type { CameraStreamType } from "../data/camera-streams";
@customElement("ha-camera-stream")
export class HaCameraStream extends LitElement {
@@ -78,13 +77,15 @@ export class HaCameraStream extends LitElement {
@state() private _capabilities?: CameraCapabilities;
@state() private _hlsStreams?: { hasAudio: boolean; hasVideo: boolean };
@state() private _hlsStreams?: CameraStreamTracks;
@state() private _webRtcStreams?: { hasAudio: boolean; hasVideo: boolean };
@state() private _webRtcStreams?: CameraStreamTracks;
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
private _visibleStreamType?: Stream["type"];
private _visibleStreamType?: CameraStreamType;
private _capabilitiesRequest = 0;
private _thumbnailApi = memoizeOne(
(
@@ -132,6 +133,10 @@ export class HaCameraStream extends LitElement {
public connectedCallback() {
super.connectedCallback();
this._connected = true;
if (this.hasUpdated) {
// The players start again when reattached, so their results do as well
this._resetStreams();
}
}
public disconnectedCallback() {
@@ -146,9 +151,8 @@ export class HaCameraStream extends LitElement {
capabilities: this._capabilities,
});
}
const visibleStreamType = this._currentStreams().find(
(stream) => stream.visible
)?.type;
const streams = this._currentStreams();
const visibleStreamType = streams.find((stream) => stream.visible)?.type;
if (visibleStreamType !== this._visibleStreamType) {
this._visibleStreamType = visibleStreamType;
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
@@ -167,7 +171,7 @@ export class HaCameraStream extends LitElement {
)}`;
}
private _renderStream(stream: Stream) {
private _renderStream(stream: CameraStream) {
if (!this.stateObj) {
return nothing;
}
@@ -229,15 +233,14 @@ export class HaCameraStream extends LitElement {
return this._streams(
this._capabilities?.frontend_stream_types,
this._hlsStreams,
this._webRtcStreams,
this.muted
this._webRtcStreams
);
}
private async _getCapabilities() {
this._capabilities = undefined;
this._hlsStreams = undefined;
this._webRtcStreams = undefined;
this._resetStreams();
const request = ++this._capabilitiesRequest;
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
this._capabilities = {
frontend_stream_types: [],
@@ -245,10 +248,19 @@ export class HaCameraStream extends LitElement {
};
return;
}
this._capabilities = await fetchCameraCapabilities(
const capabilities = await fetchCameraCapabilities(
this._api,
this.stateObj!.entity_id
);
if (request !== this._capabilitiesRequest) {
return;
}
this._capabilities = capabilities;
}
private _resetStreams() {
this._hlsStreams = undefined;
this._webRtcStreams = undefined;
}
private async _getPosterUrl(): Promise<void> {
@@ -269,89 +281,38 @@ export class HaCameraStream extends LitElement {
fireEvent(this, "load");
}
private _handleHlsStreams(ev: CustomEvent) {
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
this._hlsStreams = ev.detail;
}
private _handleWebRtcStreams(ev: CustomEvent) {
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
if (
!ev.detail.hasVideo &&
!ev.detail.hasAudio &&
this._capabilities?.frontend_stream_types.length === 1 &&
typeof RTCPeerConnection !== "undefined"
) {
// Without another stream type, keep the player to show why it failed.
// Only a browser without WebRTC falls back to MJPEG.
return;
}
this._webRtcStreams = ev.detail;
}
private _streams = memoizeOne(
(
supportedTypes?: StreamType[],
hlsStreams?: { hasAudio: boolean; hasVideo: boolean },
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean },
muted?: boolean
): Stream[] => {
supportedTypes?: CameraCapabilities["frontend_stream_types"],
hlsStreams?: CameraStreamTracks,
webRtcStreams?: CameraStreamTracks
): CameraStream[] => {
if (__DEMO__) {
return [{ type: MJPEG_STREAM, visible: true }];
}
if (!supportedTypes) {
return [];
}
if (supportedTypes.length === 0) {
// doesn't support any stream type, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
if (supportedTypes.length === 1) {
// only 1 stream type, no need to choose
if (
(supportedTypes[0] === STREAM_TYPE_HLS &&
hlsStreams?.hasVideo === false) ||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
webRtcStreams?.hasVideo === false)
) {
// stream failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
return [{ type: supportedTypes[0], visible: true }];
}
if (hlsStreams && webRtcStreams) {
// fully loaded
if (
hlsStreams.hasVideo &&
hlsStreams.hasAudio &&
!webRtcStreams.hasAudio &&
!muted
) {
// webRTC stream is missing audio and audio is not muted, use HLS
return [{ type: STREAM_TYPE_HLS, visible: true }];
}
if (webRtcStreams.hasVideo) {
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
// both streams failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
if (hlsStreams?.hasVideo !== webRtcStreams?.hasVideo) {
// one of the two streams is loaded, or errored
// choose the one that has video or is still loading
if (hlsStreams?.hasVideo) {
return [
{ type: STREAM_TYPE_HLS, visible: true },
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
}
if (hlsStreams?.hasVideo === false) {
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
if (webRtcStreams?.hasVideo) {
return [
{ type: STREAM_TYPE_WEB_RTC, visible: true },
{ type: STREAM_TYPE_HLS, visible: false },
];
}
if (webRtcStreams?.hasVideo === false) {
return [{ type: STREAM_TYPE_HLS, visible: true }];
}
}
return [
{ type: STREAM_TYPE_HLS, visible: true },
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
return selectCameraStreams({
supportedTypes,
hlsStreams,
webRtcStreams,
});
}
);
+9 -19
View File
@@ -2,6 +2,7 @@ import type { ContextType } from "@lit/context";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../common/decorators/consume";
import { configContext } from "../data/context";
import "./ha-icon-next";
@@ -32,27 +33,18 @@ class HaConfigNavigationList extends LitElement {
return html`
<ha-list-item-button
.href=${externalApp ? undefined : page.path}
.headline=${page.name}
.supportingText=${this.hasSecondary ? page.description : undefined}
@click=${externalApp ? this._handleExternalApp : undefined}
>
<div
<ha-svg-icon
slot="start"
class=${page.iconColor ? "icon-background" : ""}
.style="background-color: ${page.iconColor || "undefined"}"
>
<ha-svg-icon
.path=${page.iconPath}
.secondaryPath=${page.iconSecondaryPath}
.viewBox=${page.iconViewBox}
></ha-svg-icon>
</div>
<span slot="headline">${page.name}</span>
${
this.hasSecondary
? html`<span slot="supporting-text"
>${page.description}</span
>`
: ""
}
style=${styleMap({ backgroundColor: page.iconColor })}
.path=${page.iconPath}
.secondaryPath=${page.iconSecondaryPath}
.viewBox=${page.iconViewBox}
></ha-svg-icon>
${
!this.narrow
? html`<ha-icon-next slot="end"></ha-icon-next>`
@@ -82,8 +74,6 @@ class HaConfigNavigationList extends LitElement {
}
.icon-background {
border-radius: var(--ha-border-radius-circle);
}
.icon-background ha-svg-icon {
color: #fff;
}
`;
+2 -2
View File
@@ -387,7 +387,7 @@ export class HaControlCircularSlider extends LitElement {
}
private _handleKeyDown(e: KeyboardEvent) {
if (!A11Y_KEY_CODES.has(e.code)) return;
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
e.preventDefault();
if (this._lastSlider) {
this.shadowRoot?.getElementById(this._lastSlider)?.focus();
@@ -439,7 +439,7 @@ export class HaControlCircularSlider extends LitElement {
}
private _handleKeyUp(e: KeyboardEvent) {
if (!A11Y_KEY_CODES.has(e.code)) return;
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
e.preventDefault();
fireEvent(this, `${this._activeSlider}-changing`, {
+2 -1
View File
@@ -87,11 +87,12 @@ export class HaFilterCategories extends LitElement {
public disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeCategories();
this._categories = [];
}
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (changedProps.get("scope") !== undefined) {
if (changedProps.has("scope") && this.scope !== this._categoriesScope) {
this._categories = [];
}
}
+4
View File
@@ -112,6 +112,9 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
@property({ attribute: "pin-block" })
public pinBlock?: "start" | "center" | "end" | "nearest";
// Skip the "unknown value" highlight and note for a value that is not in the
// list but that the value renderer presents on its own.
@property({ type: Boolean, attribute: "no-unknown-state" })
@@ -347,6 +350,7 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
.searchKeys=${this.searchKeys}
.customValueLabel=${this.customValueLabel}
.noSort=${this.noSort}
.pinBlock=${this.pinBlock}
></ha-picker-combo-box>
`;
}
+5 -1
View File
@@ -26,7 +26,11 @@ export class HaHelpTooltip extends LitElement {
protected render(): TemplateResult {
return html`
<ha-svg-icon id="svg-icon" .path=${mdiHelpCircleOutline}></ha-svg-icon>
<ha-tooltip for="svg-icon" .placement=${this.position}>
<ha-tooltip
trigger="hover focus click"
for="svg-icon"
.placement=${this.position}
>
${this.label}
</ha-tooltip>
`;
+58 -15
View File
@@ -12,6 +12,7 @@ import type { LocalizeFunc } from "../common/translations/localize";
import { nextRender } from "../common/util/render-status";
import { fetchStreamUrl } from "../data/camera";
import { apiContext, configContext, connectionContext } from "../data/context";
import { isExternal } from "../data/external";
import "./ha-alert";
type HlsLite = Omit<
@@ -71,7 +72,7 @@ class HaHLSPlayer extends LitElement {
@state() private _errorIsFatal = false;
@state() private _url!: string;
private _url?: string;
private _hlsPolyfillInstance?: HlsLite;
@@ -81,12 +82,22 @@ class HaHLSPlayer extends LitElement {
private _hiddenCleanupTimeout?: number;
// Increased on every clean up, so a start that is still waiting on the
// network knows it is outdated
private _cleanUpCount = 0;
private _handleVisibilityChange = () => {
if (document.pictureInPictureElement) {
// video is playing in picture-in-picture mode, don't do anything
return;
}
if (document.hidden) {
if (isExternal) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
@@ -96,8 +107,7 @@ class HaHLSPlayer extends LitElement {
clearTimeout(this._hiddenCleanupTimeout);
this._hiddenCleanupTimeout = undefined;
} else {
this._resetError();
this._startHls();
this._restartHls();
}
};
@@ -105,8 +115,7 @@ class HaHLSPlayer extends LitElement {
super.connectedCallback();
HaHLSPlayer.streamCount += 1;
if (this.hasUpdated) {
this._resetError();
this._startHls();
this._restartHls();
}
document.addEventListener("visibilitychange", this._handleVisibilityChange);
}
@@ -171,24 +180,44 @@ class HaHLSPlayer extends LitElement {
}
}
/** Starts the stream again, replacing a start that is still pending. */
private _restartHls() {
if (this.entityid) {
// The stream URL stops working once the stream has been idle for a while
this._getStreamUrlFromEntityId();
return;
}
this._cleanUp();
this._resetError();
this._startHls();
}
private async _getStreamUrlFromEntityId(): Promise<void> {
this._cleanUp();
this._resetError();
this._url = undefined;
if (!isComponentLoaded(this._config.config, "stream")) {
this._setFatalError("Streaming component is not loaded.");
return;
}
if (!this.entityid) {
const entityId = this.entityid;
if (!entityId) {
return;
}
const cleanUpCount = this._cleanUpCount;
try {
const { url } = await fetchStreamUrl(
{ callWS: this._api.callWS, hassUrl: this._connection.hassUrl },
this.entityid
entityId
);
if (cleanUpCount !== this._cleanUpCount) {
// Removed, hidden or switched camera while fetching
return;
}
this._url = this._connection.hassUrl(url);
this._cleanUp();
this._resetError();
@@ -198,18 +227,27 @@ class HaHLSPlayer extends LitElement {
// eslint-disable-next-line
console.error(err);
if (cleanUpCount !== this._cleanUpCount || entityId !== this.entityid) {
// Removed, hidden or switched camera while fetching
return;
}
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
}
}
private async _startHls(): Promise<void> {
const masterPlaylistPromise = fetch(this._url);
const url = this._url;
if (!url) {
return;
}
const cleanUpCount = this._cleanUpCount;
const masterPlaylistPromise = fetch(url);
// eslint-disable-next-line @typescript-eslint/naming-convention
const Hls: typeof HlsType = (await import("hls.js/dist/hls.light.mjs"))
.default;
if (!this.isConnected) {
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
return;
}
@@ -231,7 +269,7 @@ class HaHLSPlayer extends LitElement {
this.allowExoPlayer && this._config.auth.external?.config.hasExoPlayer;
const masterPlaylist = await (await masterPlaylistPromise).text();
if (!this.isConnected) {
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
return;
}
@@ -247,9 +285,9 @@ class HaHLSPlayer extends LitElement {
let playlist_url: string;
if (match !== null && matchTwice === null) {
// Only send the regular playlist url if we match exactly once
playlist_url = new URL(match[3], this._url).href;
playlist_url = new URL(match[3], url).href;
} else {
playlist_url = this._url;
playlist_url = url;
}
const codecs = match ? `${match[1]},${match[2]}` : undefined;
@@ -387,12 +425,17 @@ class HaHLSPlayer extends LitElement {
private async _renderHLSNative(videoEl: HTMLVideoElement, url: string) {
videoEl.src = url;
videoEl.addEventListener("loadedmetadata", () => {
videoEl.play();
});
videoEl.addEventListener(
"loadedmetadata",
() => {
videoEl.play();
},
{ once: true }
);
}
private _cleanUp() {
this._cleanUpCount++;
if (this._hlsPolyfillInstance) {
this._hlsPolyfillInstance.destroy();
this._hlsPolyfillInstance = undefined;
+62 -18
View File
@@ -1,13 +1,17 @@
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import type { TemplateResult } from "lit";
import type { PropertyValues, TemplateResult } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import { caseInsensitiveStringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { customIcons } from "../data/custom_icons";
import type { ValueChangedEvent } from "../types";
import "./ha-combo-box-item";
import "./ha-generic-picker";
import type { HaGenericPicker } from "./ha-generic-picker";
import "./ha-icon";
import type { PickerComboBoxItem } from "./ha-picker-combo-box";
@@ -50,16 +54,17 @@ const createIconItem = (icon: IconData, prefix: string): PickerComboBoxItem => {
const loadIcons = async () => {
ICONS_LOADED = true;
const iconList = await import("../../build/mdi/iconList.json");
ICONS = iconList.default.map((icon) => createIconItem(icon, "mdi"));
const sortIcons = (icons: PickerComboBoxItem[]) =>
icons.sort((a, b) => caseInsensitiveStringCompare(a.id, b.id));
const customIconLoads: Promise<PickerComboBoxItem[]>[] = [];
Object.keys(customIcons).forEach((iconSet) => {
customIconLoads.push(loadCustomIconItems(iconSet));
});
(await Promise.all(customIconLoads)).forEach((customIconItems) => {
ICONS.push(...customIconItems);
});
const iconList = await import("../../build/mdi/iconList.json");
const mdiIcons = iconList.default.map((icon) => createIconItem(icon, "mdi"));
ICONS = sortIcons([...mdiIcons]);
const customIconItems = await Promise.all(
Object.keys(customIcons).map(loadCustomIconItems)
);
ICONS = sortIcons([...mdiIcons, ...customIconItems.flat()]);
};
const loadCustomIconItems = async (
@@ -81,8 +86,8 @@ const loadCustomIconItems = async (
const rowRenderer: RenderItemFunction<PickerComboBoxItem> = (item) => html`
<ha-combo-box-item>
<ha-icon .icon=${item.id} slot="start"></ha-icon>
${item.id}
<ha-icon .icon=${item.icon ?? item.id} slot="start"></ha-icon>
${item.icon ?? item.id}
</ha-combo-box-item>
`;
@@ -104,12 +109,32 @@ export class HaIconPicker extends LitElement {
@property({ type: Boolean }) public invalid = false;
private _getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
@property({ attribute: false }) public suggestedIcons?: string[];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@query("ha-generic-picker") private _picker?: HaGenericPicker;
private _getIconPickerItems = () =>
this._itemsWithSuggestions(ICONS, this.suggestedIcons, this._localize);
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
if (changedProps.has("suggestedIcons") || changedProps.has("_localize")) {
this._picker?.refreshItems();
}
}
protected render(): TemplateResult {
return html`
<ha-generic-picker
allow-custom-value
no-sort
.pinBlock=${
this.value && this.suggestedIcons?.includes(this.value)
? "end"
: undefined
}
.getItems=${this._getIconPickerItems}
.helper=${this.helper}
.disabled=${this.disabled}
@@ -128,15 +153,35 @@ export class HaIconPicker extends LitElement {
`;
}
private _itemsWithSuggestions = memoizeOne(
(
icons: PickerComboBoxItem[],
suggestedIcons: string[] | undefined,
localize: LocalizeFunc
): (PickerComboBoxItem | string)[] => {
if (!suggestedIcons?.length) {
return icons;
}
const suggested = new Set(suggestedIcons);
return [
localize("ui.components.icon_picker.suggested"),
...suggestedIcons.map((icon) => ({ id: icon, primary: icon, icon })),
localize("ui.components.icon_picker.all_icons"),
...icons.filter((item) => !suggested.has(item.id)),
];
}
);
// Filter can take a significant chunk of frame (up to 3-5 ms)
private _filterIcons = memoizeOne(
(
filter: string,
filteredItems: PickerComboBoxItem[],
allItems: PickerComboBoxItem[]
_allItems: PickerComboBoxItem[]
): PickerComboBoxItem[] => {
const normalizedFilter = filter.toLowerCase().replace(/\s+/g, "-");
const iconItems = allItems?.length ? allItems : filteredItems;
// The full list also holds the suggestions and their section titles
const iconItems = ICONS.length ? ICONS : filteredItems;
if (!normalizedFilter.length) {
return iconItems;
@@ -175,8 +220,7 @@ export class HaIconPicker extends LitElement {
protected firstUpdated() {
if (!ICONS_LOADED) {
loadIcons().then(() => {
this._getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
this.requestUpdate();
this._picker?.refreshItems();
});
}
}
@@ -406,6 +406,8 @@ export class HaItemDisplayEditor extends LitElement {
cursor: move;
padding: 8px;
margin: -8px;
/* Keep the handle above the row's hit area so dragging can start */
z-index: 1;
}
.separator {
width: 1px;
+5 -1
View File
@@ -32,6 +32,10 @@ export class HaMarqueeText extends LitElement {
private _pauseTimeout?: number;
private get _animationFactor() {
return document.dir === "rtl" ? -1 : 1;
}
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
@@ -117,7 +121,7 @@ export class HaMarqueeText extends LitElement {
reachedEnd = true;
}
}
this._textSpan.style.transform = `translateX(${this._position}px)`;
this._textSpan.style.transform = `translateX(${this._position * this._animationFactor}px)`;
if (reachedEnd) {
this._pauseTimeout = window.setTimeout(() => {
this._pauseTimeout = undefined;
+12 -2
View File
@@ -201,6 +201,9 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
@property({ attribute: "pin-block" })
public pinBlock?: "start" | "center" | "end" | "nearest";
@query(".list") private _list?: HaListBase;
@query("ha-input-search") private _searchFieldElement?: HaInputSearch;
@@ -453,6 +456,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
this.value
)}
.pinIndex=${this.value ? this._getInitialSelectedIndex() : undefined}
.pinBlock=${this.pinBlock ?? "center"}
@mousedown=${this._preventBlur}
@focus=${this._focusList}
@blur=${this._resetSelectedItem}
@@ -685,6 +689,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
fireEvent(this, "index-selected", { index, item, newTab });
}
// Fuse indexes every row as text when the first one is a section title
private _searchableItems = memoizeOne((items: PickerComboBoxItem[]) =>
items.filter((item) => typeof item !== "string")
);
private _fuseIndex = memoizeOne(
(states: PickerComboBoxItem[], searchKeys?: FuseWeightedKey[]) =>
Fuse.createIndex(searchKeys || DEFAULT_SEARCH_KEYS, states)
@@ -708,10 +717,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
return;
}
const index = this._fuseIndex(this._allItems, this.searchKeys);
const searchableItems = this._searchableItems(this._allItems);
const index = this._fuseIndex(searchableItems, this.searchKeys);
let filteredItems = multiTermSortedSearch<PickerComboBoxItem>(
this._allItems,
searchableItems,
searchString,
(item) => item.id,
index
+28 -5
View File
@@ -50,6 +50,7 @@ const wait = (ms: number) =>
* @cssprop --ha-ripple-hover-color - Hover color.
* @cssprop --ha-ripple-pressed-color - Pressed color.
* @cssprop --ha-ripple-hover-opacity - Hover opacity. Defaults to 0.08.
* @cssprop --ha-ripple-hover-duration - Fade duration of the hover color. Defaults to 15ms.
* @cssprop --ha-ripple-pressed-opacity - Pressed opacity. Defaults to 0.12.
*/
@customElement("ha-ripple")
@@ -170,6 +171,16 @@ export class HaRipple extends LitElement {
return;
}
// A touch long press opens the context menu while the press continues,
// e.g. for a hold action. touchend or pointercancel ends it instead.
if (
ev.type === "contextmenu" &&
this._startEvent &&
isTouch(this._startEvent)
) {
return;
}
if (ev.type === "contextmenu" || ev.type === "touchend") {
this._endPress();
@@ -192,13 +203,25 @@ export class HaRipple extends LitElement {
break;
case "pointerenter":
this._hovered = true;
if (this._state === "waiting-for-click") {
if (ev.buttons === 1) {
// Back on the control with the press still held
this._pressed = true;
} else {
// The press was released off the control, so no click follows
this._endPress();
}
}
break;
case "pointerleave":
this._hovered = false;
// Release a held mouse or pen press that moves off the control
if (this._state !== "inactive") {
this._endPress();
// A mouse or pen press that moves off the control still clicks if it
// is released back on it, so only hide the press until it returns
if (this._state === "waiting-for-click") {
this._pressed = false;
}
break;
@@ -396,8 +419,8 @@ export class HaRipple extends LitElement {
var(--ha-ripple-color, var(--secondary-text-color))
);
transition:
opacity 15ms linear,
background-color 15ms linear;
opacity var(--ha-ripple-hover-duration, 15ms) linear,
background-color var(--ha-ripple-hover-duration, 15ms) linear;
}
.hovered .hover {
opacity: var(--ha-ripple-hover-opacity, 0.08);
@@ -1,9 +1,18 @@
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { ensureArray } from "../../common/array/ensure-array";
import { consume } from "../../common/decorators/consume";
import {
apiContext,
connectionContext,
devicesContext,
entitiesContext,
statesContext,
} from "../../data/context";
import type { DeviceRegistryEntry } from "../../data/device/device_registry";
import { getDeviceIntegrationLookup } from "../../data/device/device_registry";
import type { EntitySources } from "../../data/entity/entity_sources";
@@ -15,7 +24,7 @@ import {
filterSelectorEntities,
} from "../../data/selector";
import type { HassServiceTargetWithExclude } from "../../data/target";
import type { HomeAssistant } from "../../types";
import type { HomeAssistant, HomeAssistantConnection } from "../../types";
import "../ha-target-picker";
type TargetSelectorFilters = NonNullable<TargetSelector["target"]>;
@@ -28,8 +37,6 @@ const ALL_DEVICES = () => true;
@customElement("ha-selector-target")
export class HaTargetSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: TargetSelector;
@property({ type: Object }) public value?: HassServiceTargetWithExclude;
@@ -44,9 +51,27 @@ export class HaTargetSelector extends LitElement {
@state() private _createDomains: string[] | undefined;
@consume({ context: apiContext, subscribe: true })
private _api?: ContextType<typeof apiContext>;
@state()
@consume({ context: connectionContext, subscribe: true })
private _connection?: ContextType<typeof connectionContext>;
@consume({ context: statesContext, subscribe: true })
private _states?: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities?: ContextType<typeof entitiesContext>;
@consume({ context: devicesContext, subscribe: true })
private _devices?: ContextType<typeof devicesContext>;
private _fetchedEntitySources = false;
private _deviceIntegrationLookup = memoizeOne(
(entities: HomeAssistant["entities"]) =>
getDeviceIntegrationLookup(Object.values(entities))
(entities: HomeAssistant["entities"] | undefined) =>
getDeviceIntegrationLookup(Object.values(entities ?? {}))
);
private _hasIntegration(selector: TargetSelector) {
@@ -62,18 +87,31 @@ export class HaTargetSelector extends LitElement {
);
}
protected updated(changedProperties: PropertyValues<this>): void {
protected updated(changedProperties: PropertyValues): void {
super.updated(changedProperties);
const oldConnection = changedProperties.get("_connection") as
HomeAssistantConnection | undefined;
if (
changedProperties.has("selector") &&
this._hasIntegration(this.selector) &&
!this._entitySources
oldConnection &&
this._connection &&
(oldConnection.connection !== this._connection.connection ||
(!oldConnection.connected && this._connection.connected))
) {
fetchEntitySourcesWithCache(this.hass.callWS, this.hass.states).then(
(sources) => {
this._fetchedEntitySources = false;
}
if (
this._api &&
!this._fetchedEntitySources &&
this._hasIntegration(this.selector)
) {
this._fetchedEntitySources = true;
fetchEntitySourcesWithCache(this._api.callWS, this._states ?? {})
.then((sources) => {
this._entitySources = sources;
}
);
})
.catch(() => {
this._entitySources ??= {};
});
}
if (changedProperties.has("selector")) {
this._createDomains = computeCreateDomains(this.selector);
@@ -87,7 +125,6 @@ export class HaTargetSelector extends LitElement {
return html` ${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-target-picker
.hass=${this.hass}
.value=${this.value}
.helper=${this.helper}
.deviceFilter=${this._deviceFilter(this.selector.target?.device)}
@@ -118,8 +155,8 @@ export class HaTargetSelector extends LitElement {
filter,
entity,
entitySources,
this.hass.entities,
this.hass.devices
this._entities,
this._devices
)
);
}
@@ -132,7 +169,7 @@ export class HaTargetSelector extends LitElement {
}
return (device: DeviceRegistryEntry): boolean => {
const deviceIntegrations = this._hasIntegration(this.selector)
? this._deviceIntegrationLookup(this.hass.entities)
? this._deviceIntegrationLookup(this._entities)
: undefined;
return ensureArray(filters).some((filter) =>
filterSelectorDevices(filter, device, deviceIntegrations)
+36 -102
View File
@@ -41,7 +41,6 @@ import "./ha-selector/ha-selector";
import type { HaSelector } from "./ha-selector/ha-selector";
import "./ha-service-picker";
import "./ha-service-section-icon";
import "./ha-input-helper-text";
import "./ha-settings-row";
import "./ha-yaml-editor";
import type { HaYamlEditor } from "./ha-yaml-editor";
@@ -120,15 +119,6 @@ export class HaServiceControl extends LitElement {
@property({ attribute: "hide-description", type: Boolean })
public hideDescription = false;
/** Error shown below the target picker. */
@property({ attribute: false }) public targetError?: string;
/** Errors shown below the data fields, keyed by field. */
@property({ attribute: false }) public dataErrors?: Record<string, string>;
/** Error of the data as a whole. */
@property({ attribute: false }) public dataError?: string;
@state() private _value!: this["value"];
@state() private _checkedKeys = new Set();
@@ -475,10 +465,13 @@ export class HaServiceControl extends LitElement {
serviceData?.flatFields.some((field) => showOptionalToggle(field))
);
const targetEntities = this._getTargetedEntities(
serviceData?.target,
this._value
);
// Actions that can never have targets get null, like template targets
const targetEntities =
serviceData &&
("target" in serviceData ||
serviceData.flatFields.some((field) => field.key === "entity_id"))
? this._getTargetedEntities(serviceData.target, this._value)
: null;
const domain = this._value?.action
? computeDomain(this._value.action)
@@ -552,14 +545,13 @@ export class HaServiceControl extends LitElement {
${
serviceData && "target" in serviceData
? html`<ha-selector
class="target-selector"
.hass=${this.hass}
.selector=${targetSelector}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this._value?.target}
></ha-selector>
${this._renderError(this.targetError)}`
class="target-selector"
.hass=${this.hass}
.selector=${targetSelector}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this._value?.target}
></ha-selector>`
: entityId
? html`<ha-entity-picker
.disabled=${this.disabled}
@@ -605,10 +597,7 @@ export class HaServiceControl extends LitElement {
this._hasFilteredFields(fields, targetEntities)
? html`<ha-expansion-panel
left-chevron
.expanded=${
!dataField.collapsed ||
fields.some((field) => this.dataErrors?.[field.key])
}
.expanded=${!dataField.collapsed}
.header=${
this.hass.localize(
`component.${domain}.services.${serviceName}.sections.${dataField.key}.name`,
@@ -640,12 +629,7 @@ export class HaServiceControl extends LitElement {
</ha-expansion-panel>`
: nothing;
})
}
${this._unshownErrors(
serviceData,
targetEntities,
Boolean(shouldRenderServiceDataYaml)
).map((error) => this._renderError(error))}`;
} `;
}
private _getSectionDescription(
@@ -709,25 +693,6 @@ export class HaServiceControl extends LitElement {
? this.hass.services[domain][serviceName].description_placeholders
: undefined;
const fieldError = this.dataErrors?.[dataField.key];
const selectorTemplate = html`<ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${
this.disabled ||
(showOptional &&
!this._checkedKeys.has(dataField.key) &&
(!this._value?.data || this._value.data[dataField.key] === undefined))
}
.hass=${this.hass}
.selector=${selector}
.key=${dataField.key}
@value-changed=${this._serviceDataChanged}
.value=${this._value?.data ? this._value.data[dataField.key] : undefined}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
.required=${dataField.required}
></ha-selector>`;
return dataField.selector
? html`<ha-settings-row
.narrow=${
@@ -780,50 +745,30 @@ export class HaServiceControl extends LitElement {
}
></ha-markdown>
</span>
<div class="field">
${selectorTemplate}${this._renderError(fieldError)}
</div>
<ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${
this.disabled ||
(showOptional &&
!this._checkedKeys.has(dataField.key) &&
(!this._value?.data ||
this._value.data[dataField.key] === undefined))
}
.hass=${this.hass}
.selector=${selector}
.key=${dataField.key}
@value-changed=${this._serviceDataChanged}
.value=${
this._value?.data ? this._value.data[dataField.key] : undefined
}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
.required=${dataField.required}
></ha-selector>
</ha-settings-row>`
: "";
};
// Errors without a field to show them on, e.g. of a field no target
// supports or of a target the action doesn't have a picker for
private _unshownErrors(
serviceData: ExtHassService | undefined,
targetEntities: string[] | null,
dataYaml: boolean
): string[] {
const targetShown = Boolean(serviceData && "target" in serviceData);
const shownFields = new Set(
dataYaml
? []
: (serviceData?.flatFields ?? [])
.filter(
(field) =>
field.selector &&
(!field.filter ||
this._filterField(field.filter, targetEntities))
)
.map((field) => field.key)
);
return [
...(this.targetError && !targetShown ? [this.targetError] : []),
...(this.dataError ? [this.dataError] : []),
...Object.entries(this.dataErrors ?? {})
.filter(([key]) => !shownFields.has(key))
.map(([key, error]) => `${key}: ${error}`),
];
}
private _renderError(error: string | undefined) {
return error
? html`<ha-input-helper-text class="error"
>${error}</ha-input-helper-text
>`
: nothing;
}
private _selectorContext = memoizeOne((targetEntities: string[] | null) => ({
filter_entity: targetEntities || undefined,
}));
@@ -1049,17 +994,6 @@ export class HaServiceControl extends LitElement {
ha-settings-row {
padding: var(--service-control-padding, 0 var(--ha-space-4));
}
/* Every field has this wrapper, so the selector isn't rebuilt when its
error comes or goes */
.field {
display: flex;
flex-direction: column;
}
ha-input-helper-text.error {
color: var(--ha-color-on-danger-quiet);
padding-top: var(--ha-space-1);
padding-bottom: var(--ha-space-2);
}
ha-settings-row[narrow] {
padding-bottom: var(--ha-space-2);
}
+14 -6
View File
@@ -1,10 +1,13 @@
import type { ContextType } from "@lit/context";
import type { HassServiceTarget } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { ensureArray } from "../common/array/ensure-array";
import { consume } from "../common/decorators/consume";
import { fireEvent } from "../common/dom/fire_event";
import { entitiesContext, statesContext } from "../data/context";
import type { DataTableFiltersValue } from "../data/data_table_filters";
import type { HaEntityPickerEntityFilterFunc } from "../data/entity/entity";
import { entityTypeFilterFunc } from "../data/entity/entity_type";
@@ -108,8 +111,6 @@ export const applySourceFilters = (
*/
@customElement("ha-sources-picker")
export class HaSourcesPicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public value: HassServiceTarget = {};
/** The filters the page applies, so the picker counts what they keep. */
@@ -125,6 +126,14 @@ export class HaSourcesPicker extends LitElement {
@property({ type: Boolean }) public disabled = false;
@state()
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@state()
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
protected render() {
const noTargets = countTargets(this.value) === 0;
@@ -136,13 +145,12 @@ export class HaSourcesPicker extends LitElement {
}
<ha-target-picker
class=${classMap({ "no-padding-top": noTargets })}
.hass=${this.hass}
.value=${this.value}
.entityFilter=${this.entityFilter}
.activeFilter=${this._activeFilter(
this.filters,
this.hass.states,
this.hass.entities,
this._states,
this._entities,
this.entitySources
)}
.primaryEntitiesOnly=${false}
+165 -84
View File
@@ -1,3 +1,4 @@
import type { ContextType } from "@lit/context";
import "@home-assistant/webawesome/dist/components/popover/popover";
import { mdiPlaylistMinus, mdiPlus, mdiTextureBox } from "@mdi/js";
import Fuse from "fuse.js";
@@ -8,6 +9,7 @@ import { customElement, property, query, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { ensureArray } from "../common/array/ensure-array";
import type { HASSDomEvent } from "../common/dom/fire_event";
import { fireEvent } from "../common/dom/fire_event";
@@ -21,7 +23,17 @@ import {
type FloorComboBoxItem,
} from "../data/area_floor_picker";
import { getConfigEntries, type ConfigEntry } from "../data/config_entries";
import { labelsContext } from "../data/context";
import {
apiContext,
brandsAccessTokenContext,
configContext,
connectionContext,
internationalizationContext,
labelsContext,
registriesContext,
statesContext,
uiContext,
} from "../data/context";
import {
deviceComboBoxKeys,
getDevices,
@@ -47,7 +59,6 @@ import {
type TargetType,
type TargetTypeFloorless,
} from "../data/target";
import { SubscribeMixin } from "../mixins/subscribe-mixin";
import { isHelperDomain } from "../panels/config/helpers/const";
import { showHelperDetailDialog } from "../panels/config/helpers/show-dialog-helper-detail";
import {
@@ -55,7 +66,11 @@ import {
multiTermSortedSearch,
type FuseWeightedKey,
} from "../resources/fuseMultiTerm";
import type { HomeAssistant, ValueChangedEvent } from "../types";
import type {
HomeAssistant,
HomeAssistantUI,
ValueChangedEvent,
} from "../types";
import { brandsUrl } from "../util/brands-url";
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
import "./ha-button";
@@ -89,9 +104,7 @@ const isTargetType = (value: string): value is TargetType =>
value === "floor";
@customElement("ha-target-picker")
export class HaTargetPicker extends SubscribeMixin(LitElement) {
@property({ attribute: false }) public hass!: HomeAssistant;
export class HaTargetPicker extends LitElement {
@property({ attribute: false }) public value?: HassServiceTargetWithExclude;
@property() public helper?: string;
@@ -157,6 +170,47 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
@consume({ context: labelsContext, subscribe: true })
private _labelRegistry!: LabelRegistryEntry[];
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HomeAssistant["states"], boolean>({
transformer: function (this: HaTargetPicker, states) {
return !!this._pendingEntityId && !!states?.[this._pendingEntityId];
},
watch: ["_pendingEntityId"],
})
private _pendingEntityLoaded = false;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, boolean | undefined>({
transformer: (ui) => ui?.themes?.darkMode,
})
private _darkMode?: boolean;
@consume({ context: configContext, subscribe: true })
private _config?: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api?: ContextType<typeof apiContext>;
@consume({ context: connectionContext, subscribe: true })
private _connection?: ContextType<typeof connectionContext>;
@state()
@consume({ context: brandsAccessTokenContext, subscribe: true })
private _brandsAccessToken?: string;
@query("ha-generic-picker") private _picker?: HaGenericPicker;
@query("ha-generic-picker.exclude") private _excludePicker?: HaGenericPicker;
@@ -167,7 +221,9 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
private _getDevicesMemoized = memoizeOne(
(
hass: HomeAssistant,
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>,
configEntryLookup: Record<string, ConfigEntry>,
includeDomains?: string[],
includeDeviceClasses?: string[],
@@ -178,13 +234,13 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
idPrefix?: string
) =>
getDevices({
states: hass.states,
areas: hass.areas,
devices: hass.devices,
entities: hass.entities,
localize: hass.localize,
language: hass.locale.language,
translationMetadata: hass.translationMetadata,
states,
areas: registries.areas,
devices: registries.devices,
entities: registries.entities,
localize: i18n.localize,
language: i18n.locale.language,
translationMetadata: i18n.translationMetadata,
configEntryLookup,
includeDomains,
includeDeviceClasses,
@@ -201,7 +257,9 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
private _getEntitiesMemoized = memoizeOne(
(
hass: HomeAssistant,
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>,
includeDomains?: string[],
excludeDomains?: string[],
entityFilter?: HaEntityPickerEntityFilterFunc,
@@ -212,7 +270,15 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
value?: string,
idPrefix?: string
) =>
getEntities(hass, {
getEntities({
states,
entities: registries.entities,
devices: registries.devices,
areas: registries.areas,
floors: registries.floors,
localize: i18n.localize,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
includeDomains,
excludeDomains,
entityFilter,
@@ -228,7 +294,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
private _getAreasAndFloorsMemoized = memoizeOne(getAreasAndFloors);
private get _showEntityId() {
return this.hass.userData?.showEntityIdPicker;
return this._config?.userData?.showEntityIdPicker;
}
private _fuseIndexes = {
@@ -248,36 +314,34 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
@state() private _pendingEntityId?: string;
public willUpdate(changedProps: PropertyValues<this>) {
public willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this._loadConfigEntries();
}
const devices = this._registries?.devices;
const devicesChanged =
changedProps.has("hass") &&
this.hass.devices !== changedProps.get("hass")?.devices;
changedProps.has("_registries") &&
devices !==
(
changedProps.get("_registries") as
ContextType<typeof registriesContext> | undefined
)?.devices;
if (
(changedProps.has("value") || devicesChanged) &&
this.hass &&
devices &&
this._compositeSplits === undefined &&
!this._loadingCompositeSplits &&
this.value?.device_id &&
ensureArray(this.value.device_id).some(
(deviceId) => !this.hass.devices[deviceId]
)
ensureArray(this.value.device_id).some((deviceId) => !devices[deviceId])
) {
// A referenced device is missing from the registry; it might be a legacy
// composite device that was split. Fetch the split map to offer a fix.
this._loadCompositeSplits();
}
const registriesChanged =
changedProps.has("hass") &&
(devicesChanged ||
this.hass.entities !== changedProps.get("hass")?.entities ||
this.hass.areas !== changedProps.get("hass")?.areas);
if (
changedProps.has("value") ||
changedProps.has("allowExclude") ||
@@ -285,18 +349,12 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
changedProps.has("deviceFilter") ||
changedProps.has("includeDomains") ||
changedProps.has("includeDeviceClasses") ||
changedProps.has("entityFilter") ||
registriesChanged
changedProps.has("entityFilter")
) {
this._exclusions.resolve();
}
if (
this._pendingEntityId &&
changedProps.has("hass") &&
this.hass.states !== changedProps.get("hass")?.states &&
this.hass.states[this._pendingEntityId]
) {
if (this._pendingEntityId && this._pendingEntityLoaded) {
this._addTarget(this._pendingEntityId, "entity");
this._pendingEntityId = undefined;
}
@@ -453,7 +511,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
return nothing;
}
return html`
<div class="exclusion-list-label">${this.hass.localize(label)}</div>
<div class="exclusion-list-label">${this._i18n.localize(label)}</div>
<ha-list-base>
${items.map(
(item) =>
@@ -486,16 +544,16 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
.helper=${this.helper}
.sections=${sections}
.notFoundLabel=${this._noTargetFoundLabel}
.emptyLabel=${this.hass.localize(
.emptyLabel=${this._i18n.localize(
"ui.components.target-picker.no_targets"
)}
.selectedSection=${this._selectedSection}
.popoverAnchor=${this._replaceTargetAnchor}
.rowRenderer=${this._renderRow}
.rowRenderer=${this._rowRenderer(this._brandsAccessToken)}
.getItems=${this._getItems}
@value-changed=${this._targetPicked}
@picker-closed=${this._handlePickerClosed}
.addButtonLabel=${this.hass.localize(
.addButtonLabel=${this._i18n.localize(
"ui.components.target-picker.add_target"
)}
.getAdditionalItems=${this._getAdditionalItems}
@@ -510,11 +568,11 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
.disabled=${this.disabled}
.sections=${sections}
.notFoundLabel=${this._noTargetFoundLabel}
.emptyLabel=${this.hass.localize(
.emptyLabel=${this._i18n.localize(
"ui.components.target-picker.no_targets"
)}
.selectedSection=${this._excludeSection}
.rowRenderer=${this._renderRow}
.rowRenderer=${this._rowRenderer(this._brandsAccessToken)}
.getItems=${this._getExcludeItems}
@value-changed=${this._excludePicked}
>
@@ -529,7 +587,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
.path=${mdiPlaylistMinus}
slot="start"
></ha-svg-icon>
${this.hass.localize(
${this._i18n.localize(
"ui.components.target-picker.exclude_target"
)}
</ha-button>
@@ -545,20 +603,20 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
return [
{
id: "entity",
label: this.hass.localize("ui.components.target-picker.type.entities"),
label: this._i18n.localize("ui.components.target-picker.type.entities"),
},
{
id: "device",
label: this.hass.localize("ui.components.target-picker.type.devices"),
label: this._i18n.localize("ui.components.target-picker.type.devices"),
},
{
id: "area",
label: this.hass.localize("ui.components.target-picker.type.areas"),
label: this._i18n.localize("ui.components.target-picker.type.areas"),
},
"separator" as const,
{
id: "label",
label: this.hass.localize("ui.components.target-picker.type.labels"),
label: this._i18n.localize("ui.components.target-picker.type.labels"),
},
];
}
@@ -687,7 +745,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
this._excludeSection = section as TargetTypeFloorless | undefined;
return this._getItemsMemoized(
this.hass.localize,
this._i18n,
this._excludeEntityFilter(
this.entityFilter,
this._exclusions.includedEntities
@@ -699,7 +757,8 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
undefined,
searchString,
this._configEntryLookup,
this.hass.entities,
this._states,
this._registries,
this._excludeSection,
this._excludePickerIncludedDevices(this.value)
);
@@ -816,7 +875,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
domain,
dialogClosedCallback: (item) => {
if (item.entityId) {
if (this.hass.states[item.entityId]) {
if (this._states?.[item.entityId]) {
this._addTarget(item.entityId, "entity");
} else {
this._pendingEntityId = item.entityId;
@@ -903,7 +962,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
this._selectedSection = section as TargetTypeFloorless | undefined;
return this._getItemsMemoized(
this.hass.localize,
this._i18n,
this.entityFilter,
this.deviceFilter,
this.includeDomains,
@@ -912,14 +971,15 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
this._replaceTarget,
searchString,
this._configEntryLookup,
this.hass.entities,
this._states,
this._registries,
this._selectedSection
);
};
private _getItemsMemoized = memoizeOne(
(
localize: HomeAssistant["localize"],
i18n: ContextType<typeof internationalizationContext>,
entityFilter: this["entityFilter"],
deviceFilter: this["deviceFilter"],
includeDomains: this["includeDomains"],
@@ -928,11 +988,13 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
replaceTarget: TargetItem | undefined,
searchTerm: string,
configEntryLookup: Record<string, ConfigEntry>,
_entities: HomeAssistant["entities"],
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
filterType?: TargetTypeFloorless,
// Hidden without hiding their child devices.
hiddenDeviceIds?: string[]
) => {
const localize = i18n.localize;
const replacingEntityId =
replaceTarget?.type === "entity" ? replaceTarget.id : undefined;
const replacingDeviceId =
@@ -950,7 +1012,9 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
if (!filterType || filterType === "entity") {
let entityItems = this._getEntitiesMemoized(
this.hass,
states,
registries,
i18n,
includeDomains,
undefined,
entityFilter,
@@ -1004,7 +1068,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
...(hiddenDeviceIds ?? []),
...(selectedDeviceIds ?? []),
...(selectedDeviceIds
? Object.values(this.hass.devices)
? Object.values(registries.devices)
.filter(
(device) =>
device.parent_device_id !== null &&
@@ -1015,7 +1079,9 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
]
: undefined;
let deviceItems = this._getDevicesMemoized(
this.hass,
states,
registries,
i18n,
configEntryLookup,
includeDomains,
includeDeviceClasses,
@@ -1066,11 +1132,11 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
if (!filterType || filterType === "area") {
let areasAndFloors = this._getAreasAndFloorsMemoized(
this.hass.states,
this.hass.floors,
this.hass.areas,
this.hass.devices,
this.hass.entities,
states,
registries.floors,
registries.areas,
registries.devices,
registries.entities,
memoizeOne((value: AreaFloorValue): string =>
[value.type, value.id].join(SEPARATOR)
),
@@ -1131,10 +1197,10 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
if (!filterType || filterType === "label") {
let labels = this._getLabelsMemoized(
this.hass.states,
this.hass.areas,
this.hass.devices,
this.hass.entities,
states,
registries.areas,
registries.devices,
registries.entities,
this._labelRegistry,
includeDomains,
undefined,
@@ -1195,30 +1261,32 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
});
}
private _getAdditionalItems = () => this._getCreateItems(this.createDomains);
private _getAdditionalItems = () =>
this._getCreateItems(this.createDomains, this._i18n.localize);
private _getCreateItems = memoizeOne(
(createDomains: this["createDomains"]) => {
(
createDomains: this["createDomains"],
localize: ContextType<typeof internationalizationContext>["localize"]
) => {
if (!createDomains?.length) {
return [];
}
return createDomains.map((domain) => {
const primary = this.hass.localize(
const primary = localize(
"ui.components.entity.entity-picker.create_helper",
{
domain: isHelperDomain(domain)
? this.hass.localize(`ui.panel.config.helpers.types.${domain}`)
: domainToName(this.hass.localize, domain),
? localize(`ui.panel.config.helpers.types.${domain}`)
: domainToName(localize, domain),
}
);
return {
id: CREATE_ID + domain,
primary: primary,
secondary: this.hass.localize(
"ui.components.entity.entity-picker.new_entity"
),
secondary: localize("ui.components.entity.entity-picker.new_entity"),
icon_path: mdiPlus,
} satisfies EntityComboBoxItem;
});
@@ -1226,18 +1294,24 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
);
private async _loadConfigEntries() {
const configEntries = await getConfigEntries(this.hass);
if (!this._api) {
return;
}
const configEntries = await getConfigEntries(this._api);
this._configEntryLookup = Object.fromEntries(
configEntries.map((entry) => [entry.entry_id, entry])
);
}
private async _loadCompositeSplits() {
if (!this._api || !this._connection) {
return;
}
this._loadingCompositeSplits = true;
try {
this._compositeSplits = await fetchDeviceCompositeSplits(
this.hass.connection,
this.hass.callWS
this._connection.connection,
this._api.callWS
);
} catch (_err) {
this._compositeSplits = {};
@@ -1262,6 +1336,13 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
});
}
// A new renderer when the brands token arrives, so open lists redraw icons.
private _rowRenderer = memoizeOne(
(_brandsAccessToken: string | undefined) =>
(item: Parameters<HaTargetPicker["_renderRow"]>[0]) =>
this._renderRow(item)
);
private _renderRow = (
item:
| PickerComboBoxItem
@@ -1281,8 +1362,8 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
type === "device" && !!(item as DevicePickerItem).is_child;
if (type === "area" || type === "floor" || isChildDeviceRow) {
rtl = computeRTL(
this.hass.language,
this.hass.translationMetadata.translations
this._i18n.language,
this._i18n.translationMetadata.translations
);
hasFloor =
type === "area" && !!(item as FloorComboBoxItem).area?.floor_id;
@@ -1348,9 +1429,9 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
{
domain: (item as DevicePickerItem).domain!,
type: "icon",
darkOptimized: this.hass.themes.darkMode,
darkOptimized: this._darkMode,
},
this.hass.auth.data.hassUrl
this._config?.auth?.data.hassUrl
)}
/>
`
@@ -1396,7 +1477,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
};
private _noTargetFoundLabel = (search: string) =>
this.hass.localize("ui.components.target-picker.no_target_found", {
this._i18n.localize("ui.components.target-picker.no_target_found", {
term: html`<b>‘${search}’</b>`,
});
@@ -1404,7 +1485,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
caseInsensitiveStringCompare(
(entityA as PickerComboBoxItem).sorting_label!,
(entityB as PickerComboBoxItem).sorting_label!,
this.hass?.locale.language ?? navigator.language
this._i18n?.locale.language ?? navigator.language
);
static styles = css`
+136 -12
View File
@@ -18,14 +18,30 @@ import {
type WebRtcOfferEvent,
} from "../data/camera";
import { apiContext, connectionContext } from "../data/context";
import { isExternal } from "../data/external";
import "./ha-alert";
import "./ha-spinner";
import { showToast } from "../util/toast";
const HIDDEN_CLEANUP_DELAY = 60000;
// How long the backend gets to answer the offer, it has to connect to the camera
const ANSWER_TIMEOUT = 20000;
// How long finding a network path gets after the answer. Browsers can take
// minutes to give up on their own, or never do.
const ICE_TIMEOUT = 30000;
// How often a stream that lost its connection or got a backend error is
// started again. A new connection that gets no answer or finds no path is not
// retried, as a retry would most likely end the same way.
const MAX_RETRIES = 1;
// Gives the backend time to tear down the failed session before the next one
const RETRY_DELAY = 1000;
interface WebRtcPlayerError {
type: "not_supported" | "start_failed" | "connect_failed";
type: "not_supported" | "start_failed" | "connect_failed" | "no_connection";
message?: string;
}
@@ -99,7 +115,7 @@ export class HaWebRtcPlayer extends LitElement {
if (this._microphoneDenied) {
return "denied";
}
if (this._microphoneConnecting) {
if (this._microphoneConnecting || this._retryMicrophoneTrack) {
return "connecting";
}
return this._localReturnAudioTrack ? "on" : "off";
@@ -110,11 +126,17 @@ export class HaWebRtcPlayer extends LitElement {
}
public async toggleMicrophone() {
if (this._localReturnAudioTrack || this._microphoneConnecting) {
if (
this._localReturnAudioTrack ||
this._microphoneConnecting ||
this._retryMicrophoneTrack
) {
// Stop (not disable) so the browser releases the microphone, also cancels connecting
this._microphoneRequest++;
this._localReturnAudioTrack?.stop();
this._localReturnAudioTrack = undefined;
this._retryMicrophoneTrack?.stop();
this._retryMicrophoneTrack = undefined;
this._microphoneConnecting = false;
this._fireMicrophoneChanged();
await this._microphoneSender?.replaceTrack(null).catch(() => undefined);
@@ -197,12 +219,30 @@ export class HaWebRtcPlayer extends LitElement {
private _cleanUpCount = 0;
private _connectTimeout?: number;
private _retryTimeout?: number;
private _retryMicrophoneTrack?: MediaStreamTrack;
private _retries = 0;
// The stream showed video since it was started, so a lost connection is
// worth a retry
private _hasPlayed = false;
private _handleVisibilityChange = () => {
if (document.pictureInPictureElement) {
// video is playing in picture-in-picture mode, don't do anything
return;
}
if (document.hidden) {
if (isExternal) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
@@ -212,7 +252,7 @@ export class HaWebRtcPlayer extends LitElement {
clearTimeout(this._hiddenCleanupTimeout);
this._hiddenCleanupTimeout = undefined;
} else {
this._startWebRtc();
this._restartWebRtc();
}
};
@@ -253,7 +293,7 @@ export class HaWebRtcPlayer extends LitElement {
public override connectedCallback() {
super.connectedCallback();
if (this.hasUpdated && this.entityid) {
this._startWebRtc();
this._restartWebRtc();
}
document.addEventListener("visibilitychange", this._handleVisibilityChange);
}
@@ -274,6 +314,13 @@ export class HaWebRtcPlayer extends LitElement {
if (!changedProperties.has("entityid")) {
return;
}
this._restartWebRtc();
}
/** Starts a new stream, not a retry of the current one. */
private _restartWebRtc() {
this._retries = 0;
this._hasPlayed = false;
this._startWebRtc();
}
@@ -415,7 +462,7 @@ export class HaWebRtcPlayer extends LitElement {
while (this._candidatesList.length) {
const candidate = this._candidatesList.pop();
if (candidate) {
candidates += `a=${candidate}\r\n`;
candidates += `a=${candidate.candidate}\r\n`;
}
}
@@ -423,6 +470,8 @@ export class HaWebRtcPlayer extends LitElement {
this._logEvent("start webRtcOffer", offer_sdp);
this._startConnectTimeout(ANSWER_TIMEOUT);
this._unsub = webRtcOffer(
this._connection,
this.entityid,
@@ -443,11 +492,61 @@ export class HaWebRtcPlayer extends LitElement {
"ice connection state change",
this._peerConnection?.iceConnectionState
);
if (this._peerConnection?.iceConnectionState === "failed") {
this._peerConnection.restartIce();
const iceState = this._peerConnection?.iceConnectionState;
if (iceState === "connected" || iceState === "completed") {
clearTimeout(this._connectTimeout);
this._connectTimeout = undefined;
} else if (iceState === "failed") {
// An ICE restart needs a new offer, which the backend answers from a new
// peer that can't continue this connection, so start a new one instead.
this._retryOrFail({ type: "no_connection" });
}
};
private _startConnectTimeout(timeout: number) {
clearTimeout(this._connectTimeout);
this._connectTimeout = window.setTimeout(() => {
this._connectTimeout = undefined;
this._logEvent("connect timeout");
this._retryOrFail({ type: "no_connection" });
}, timeout);
}
private _retryOrFail(error: WebRtcPlayerError) {
if (
this._retries >= MAX_RETRIES ||
// No answer or no path for a stream that never played, a retry would
// most likely end the same way
(error.type === "no_connection" && !this._hasPlayed) ||
// A microphone connect the user started is handled by starting again
// without the microphone. A retry keeps the microphone of the stream.
(this._localReturnAudioTrack &&
this._microphoneConnecting &&
this._retries === 0)
) {
this._failStart(error);
return;
}
this._retries++;
this._logEvent("retry", this._retries, error);
// Keep showing the last frame instead of the poster while starting again
this._captureReconnectFrame();
// Taken out before the clean up, so a running microphone is not stopped
const microphoneTrack = this._localReturnAudioTrack;
this._localReturnAudioTrack = undefined;
this._cleanUp();
if (microphoneTrack) {
this._retryMicrophoneTrack = microphoneTrack;
this._fireMicrophoneChanged();
}
this._retryTimeout = window.setTimeout(() => {
this._retryTimeout = undefined;
const track = this._retryMicrophoneTrack;
this._retryMicrophoneTrack = undefined;
this._startWebRtc(track);
}, RETRY_DELAY);
}
private async _handleOfferEvent(
peerConnection: RTCPeerConnection,
event: WebRtcOfferEvent
@@ -470,6 +569,10 @@ export class HaWebRtcPlayer extends LitElement {
this._candidatesList = [];
}
if (event.type === "answer") {
const iceState = peerConnection.iceConnectionState;
if (iceState !== "connected" && iceState !== "completed") {
this._startConnectTimeout(ICE_TIMEOUT);
}
this._logEvent("answer", event.answer);
this._handleAnswer(peerConnection, event);
@@ -495,7 +598,8 @@ export class HaWebRtcPlayer extends LitElement {
}
}
if (event.type === "error") {
this._failStart({ type: "start_failed", message: event.message });
// Often temporary, like the backend still closing the previous session
this._retryOrFail({ type: "start_failed", message: event.message });
}
}
@@ -587,8 +691,13 @@ export class HaWebRtcPlayer extends LitElement {
}
private _failStart(error: WebRtcPlayerError) {
// The camera can reject the microphone, keep the video running without it
if (this._localReturnAudioTrack && this._microphoneConnecting) {
// The camera can reject the microphone, keep the video running without it.
// After retries it is the connection that failed, not the microphone.
if (
this._localReturnAudioTrack &&
this._microphoneConnecting &&
this._retries === 0
) {
showToast(this, {
message: this._localize(
"ui.components.web-rtc-player.microphone_connect_failed",
@@ -599,12 +708,19 @@ export class HaWebRtcPlayer extends LitElement {
return;
}
this._error = error;
this._reconnectPoster = undefined;
this._cleanUp();
// Tell the camera stream this player has no video, so it can fall back
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
}
private _cleanUp() {
this._cleanUpCount++;
this._microphoneRequest++;
clearTimeout(this._connectTimeout);
this._connectTimeout = undefined;
clearTimeout(this._retryTimeout);
this._retryTimeout = undefined;
if (this._remoteStream) {
this._remoteStream.getTracks().forEach((track) => {
track.stop();
@@ -612,9 +728,15 @@ export class HaWebRtcPlayer extends LitElement {
this._remoteStream = undefined;
}
if (this._localReturnAudioTrack || this._microphoneConnecting) {
if (
this._localReturnAudioTrack ||
this._microphoneConnecting ||
this._retryMicrophoneTrack
) {
this._localReturnAudioTrack?.stop();
this._localReturnAudioTrack = undefined;
this._retryMicrophoneTrack?.stop();
this._retryMicrophoneTrack = undefined;
this._microphoneConnecting = false;
this._fireMicrophoneChanged();
}
@@ -666,6 +788,8 @@ export class HaWebRtcPlayer extends LitElement {
this._logEvent("loadedData", data);
this._stopTimer();
this._retries = 0;
this._hasPlayed = true;
// Without a track the microphone is still waiting for permission
if (this._microphoneConnecting && this._localReturnAudioTrack) {
+8 -3
View File
@@ -6,6 +6,7 @@ import { customElement, property, query, state } from "lit/decorators";
import type { ContextType } from "@lit/context";
import { consume } from "../common/decorators/consume";
import { fireEvent } from "../common/dom/fire_event";
import { localizeYamlErrorReason } from "../common/translations/localize-yaml-error";
import { copyToClipboard } from "../common/util/copy-clipboard";
import { haStyle } from "../resources/styles";
import { showToast } from "../util/toast";
@@ -180,7 +181,7 @@ export class HaYamlEditor extends LitElement {
let errorMsg: string | undefined;
let yamlError: {
mark?: { position: number; line: number; column: number };
message?: string;
reason?: string;
} | null = null;
if (this._yaml) {
@@ -189,8 +190,12 @@ export class HaYamlEditor extends LitElement {
} catch (err: any) {
// Invalid YAML
isValid = false;
yamlError = err;
errorMsg = `${this._i18n!.localize("ui.components.yaml-editor.error", { reason: err.reason })}${err.mark ? ` (${this._i18n!.localize("ui.components.yaml-editor.error_location", { line: err.mark.line + 1, column: err.mark.column + 1 })})` : ""}`;
const reason = localizeYamlErrorReason(
this._i18n!.localize,
err.reason
);
yamlError = { mark: err.mark, reason };
errorMsg = `${this._i18n!.localize("ui.components.yaml-editor.error", { reason })}${err.mark ? ` (${this._i18n!.localize("ui.components.yaml-editor.error_location", { line: err.mark.line + 1, column: err.mark.column + 1 })})` : ""}`;
}
} else {
parsed = {};
+116 -11
View File
@@ -2,6 +2,8 @@ import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html } from "lit";
import { customElement, property, query } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { keyed } from "lit/directives/keyed";
import { isInteractiveElement } from "../../common/dom/is-interactive-element";
import "../ha-ripple";
import { HaListItemBase } from "./ha-list-item-base";
@@ -15,6 +17,19 @@ import { HaListItemBase } from "./ha-list-item-base";
* roving tabindex, the host is the tab stop and the inner element carries
* `tabindex="-1"`. For a non-interactive row, use `ha-list-item-base`.
*
* Only the headline and supporting text are rendered inside the `<a>` or
* `<button>`, and its hit area is stretched over the whole row. The `start`
* and `end` slots sit next to it, so controls placed there stay separate
* controls for assistive technology. Slotted elements are raised above the
* stretched hit area, except for icons, badges, plain text and empty dividers
* without `tabindex`, so clicks and hover on those reach the row. To keep such
* an element clickable on its own, like a drag handle, give it `z-index: 1`.
*
* Subclasses customize the row with `_renderStart()`, `_renderContent()` and
* `_renderEnd()`. `_renderInner()` is not used.
*
* @csspart base - The row container.
* @csspart control - The inner `<a>` or `<button>`.
* @csspart ripple - The ripple effect element.
*
* @attr {string} href - URL. When set, renders an `<a>` instead of a `<button>`.
@@ -40,11 +55,27 @@ export class HaListItemButton extends HaListItemBase {
this._item?.click();
}
protected _renderBase(inner: TemplateResult): TemplateResult {
protected override render(): TemplateResult {
return this._renderBase(this._renderContent());
}
protected _renderBase(content: TemplateResult): TemplateResult {
// The ripple binds to #item on connect, so render it after the control and
// recreate it with the control
return html`<div part="base" class="base" @click=${this._handleBaseClick}>
${this._renderStart()}${this._renderControl(content)}${keyed(
`${this.href !== undefined}-${this.interactive}`,
this._renderRipple()
)}${this._renderEnd()}
</div>`;
}
/** Renders the native `<a>` or `<button>` around the row content. */
protected _renderControl(content: TemplateResult): TemplateResult {
if (this.href !== undefined) {
return html`<a
part="base"
class="base interactive"
part="control"
class="control"
id="item"
href=${ifDefined(this.disabled ? undefined : this.href)}
target=${ifDefined(this.target)}
@@ -53,18 +84,18 @@ export class HaListItemButton extends HaListItemBase {
tabindex="-1"
aria-disabled=${this.disabled ? "true" : "false"}
>
${this._renderRipple()}${inner}
${content}
</a>`;
}
return html`<button
part="base"
class="base interactive"
part="control"
class="control"
id="item"
type="button"
?disabled=${this.disabled}
tabindex="-1"
>
${this._renderRipple()}${inner}
${content}
</button>`;
}
@@ -76,18 +107,48 @@ export class HaListItemButton extends HaListItemBase {
></ha-ripple>`;
}
// Raised slot content that is not a control, like a wrapper without
// controls, still activates the row
private _handleBaseClick(ev: MouseEvent): void {
const item = this._item;
if (!item || this.disabled) {
return;
}
const path = ev.composedPath();
const baseIndex = path.indexOf(ev.currentTarget as EventTarget);
for (const node of path.slice(0, baseIndex)) {
if (node === item || isInteractiveElement(node)) {
return;
}
}
ev.stopPropagation();
// A copy of the event keeps modifier keys, so links can open in a new tab
item.dispatchEvent(new MouseEvent("click", ev));
}
static styles: CSSResultGroup = [
HaListItemBase.styles,
css`
:host {
cursor: pointer;
--ha-ripple-color: var(--primary-text-color);
/* Smooth the hover when moving between controls in the row */
--ha-ripple-hover-duration: var(--ha-animation-duration-fast);
}
:host([disabled]) {
cursor: default;
}
.base.interactive {
width: 100%;
.base {
isolation: isolate;
}
.control {
display: flex;
align-items: center;
align-self: stretch;
flex: 1 1 auto;
min-width: 0;
margin: 0;
padding: 0;
border: none;
background: transparent;
color: inherit;
@@ -97,8 +158,52 @@ export class HaListItemButton extends HaListItemBase {
appearance: none;
cursor: inherit;
}
:host([disabled]) .base.interactive {
color: var(--disabled-text-color);
/* Stretch the hit area of the control over the whole row */
.control::before {
content: "";
position: absolute;
inset: 0;
border-radius: var(--ha-list-item-focus-radius);
}
.control:focus-visible {
outline: none;
}
.control:focus-visible::before {
outline: var(--ha-list-item-focus-width) solid var(--ha-color-focus);
outline-offset: var(--ha-list-item-focus-offset);
}
/*
* Slotted content is painted above the hit area, so it can be clicked.
* Icons, badges, text and empty dividers go below it, so clicks on
* them reach the row.
* Some icons are positioned, so they need a negative z-index.
*/
::slotted([slot="start"]),
::slotted([slot="end"]) {
position: relative;
z-index: 1;
}
::slotted(
:is(
ha-svg-icon,
ha-icon,
ha-icon-next,
ha-state-icon,
ha-domain-icon,
ha-floor-icon,
ha-spinner,
ha-progress-ring,
ha-user-badge,
ha-person-badge,
ha-tree-indicator,
ha-app-icon,
state-badge,
img,
span,
div:empty
):not([tabindex])
) {
z-index: -1;
}
`,
];
+25 -11
View File
@@ -34,6 +34,8 @@ import type { HASSDomTargetEvent } from "../../common/dom/fire_event";
*
* @attr {string} headline - Primary text. Overridden by the `headline` slot.
* @attr {string} supporting-text - Secondary text. Overridden by the `supporting-text` slot.
* @attr {boolean} wrap-headline - Wraps the headline onto multiple lines instead of truncating it.
* @attr {boolean} wrap-supporting-text - Wraps the supporting text onto multiple lines instead of truncating it.
* @attr {boolean} disabled - Dims the row and blocks pointer events.
*/
@customElement("ha-row-item")
@@ -43,6 +45,12 @@ export class HaRowItem extends LitElement {
@property({ type: String, attribute: "supporting-text" })
public supportingText?: string;
@property({ type: Boolean, reflect: true, attribute: "wrap-headline" })
public wrapHeadline = false;
@property({ type: Boolean, reflect: true, attribute: "wrap-supporting-text" })
public wrapSupportingText = false;
@property({ type: Boolean, reflect: true }) public disabled = false;
protected readonly _slotController = new HasSlotController(
@@ -84,19 +92,21 @@ export class HaRowItem extends LitElement {
}
protected _renderInner(): TemplateResult {
return html`
${this._renderStart()}${this._renderContent()}${this._renderEnd()}
`;
}
protected _renderContent(): TemplateResult {
const hasContent = this._slotController.test("content");
return html`
${this._renderStart()}
<div part="content" class="content">
${
hasContent
? html`<slot name="content"></slot>`
: this._renderDefaultContent()
}
</div>
${this._renderEnd()}
`;
return html`<div part="content" class="content">
${
hasContent
? html`<slot name="content"></slot>`
: this._renderDefaultContent()
}
</div>`;
}
protected _renderStart(): TemplateResult {
@@ -190,6 +200,10 @@ export class HaRowItem extends LitElement {
text-overflow: ellipsis;
white-space: nowrap;
}
:host([wrap-headline]) .headline,
:host([wrap-supporting-text]) .supporting {
white-space: normal;
}
`;
}
@@ -22,11 +22,65 @@ const SMALL_THUMBNAIL_THRESHOLD = 16;
const isSvgUrl = (url: string): boolean =>
/\.svg(\?|#|$)/i.test(url) || url.startsWith("data:image/svg+xml");
// Local thumbnails can be slow to generate, for example when the integration
// extracts them from a recording on a camera. Without a limit they take all of
// the browser's connections to Home Assistant (6 for HTTP/1.1), and requests
// such as starting media playback wait until all queued thumbnails are loaded.
const MAX_PARALLEL_LOCAL_THUMBNAILS = 4;
let activeLocalThumbnails = 0;
const localThumbnailQueue: (() => void)[] = [];
const acquireLocalThumbnailSlot = (signal: AbortSignal): Promise<void> => {
if (signal.aborted) {
return Promise.reject(signal.reason);
}
if (activeLocalThumbnails < MAX_PARALLEL_LOCAL_THUMBNAILS) {
activeLocalThumbnails++;
return Promise.resolve();
}
return new Promise<void>((resolve, reject) => {
const start = () => {
signal.removeEventListener("abort", onAbort);
activeLocalThumbnails++;
resolve();
};
const onAbort = () => {
const index = localThumbnailQueue.indexOf(start);
if (index !== -1) {
localThumbnailQueue.splice(index, 1);
}
reject(signal.reason);
};
localThumbnailQueue.push(start);
signal.addEventListener("abort", onAbort, { once: true });
});
};
const releaseLocalThumbnailSlot = (): void => {
activeLocalThumbnails--;
localThumbnailQueue.shift()?.();
};
const fetchLocalThumbnail = async (
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
thumbnailUrl: string,
signal: AbortSignal
): Promise<Blob> => {
await acquireLocalThumbnailSlot(signal);
try {
const response = await fetchWithAuth(thumbnailUrl, { signal });
return await response.blob();
} finally {
releaseLocalThumbnailSlot();
}
};
const resolveThumbnailURL = (
thumbnailUrl: string,
darkMode: boolean | undefined,
hassUrl: string | undefined,
fetchWithAuth: HomeAssistantApi["fetchWithAuth"]
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
signal: AbortSignal
): Promise<string> => {
if (isBrandUrl(thumbnailUrl)) {
return Promise.resolve(
@@ -42,18 +96,16 @@ const resolveThumbnailURL = (
}
if (thumbnailUrl.startsWith("/")) {
// Local thumbnails require authentication; fetch and inline as base64.
return fetchWithAuth(thumbnailUrl)
.then((response) => response.blob())
.then(
(blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () =>
resolve(typeof reader.result === "string" ? reader.result : "");
reader.onerror = (e) => reject(e);
reader.readAsDataURL(blob);
})
);
return fetchLocalThumbnail(fetchWithAuth, thumbnailUrl, signal).then(
(blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () =>
resolve(typeof reader.result === "string" ? reader.result : "");
reader.onerror = (e) => reject(e);
reader.readAsDataURL(blob);
})
);
}
return Promise.resolve(thumbnailUrl);
};
@@ -85,6 +137,28 @@ export class HaMediaBrowserThumbnail extends LitElement {
@state() private _brand = false;
private _abortController?: AbortController;
public connectedCallback(): void {
super.connectedCallback();
// Resume a thumbnail which was aborted when this element was disconnected
if (this.hasUpdated && this.url && !this._resolvedUrl) {
this._resolve();
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
// Do not keep loading thumbnails which are no longer shown
if (this._abortController) {
this._abortController.abort();
this._abortController = undefined;
// A shown image can belong to a previous url, clear it so
// connectedCallback restarts loading the current url.
this._resolvedUrl = undefined;
}
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (
@@ -97,6 +171,8 @@ export class HaMediaBrowserThumbnail extends LitElement {
}
private async _resolve(): Promise<void> {
this._abortController?.abort();
this._abortController = undefined;
this._small = false;
this._brand = !!this.url && isBrandUrl(this.url);
if (!this.url) {
@@ -104,18 +180,28 @@ export class HaMediaBrowserThumbnail extends LitElement {
return;
}
const requested = this.url;
const abortController = new AbortController();
this._abortController = abortController;
try {
const resolved = await resolveThumbnailURL(
requested,
this._darkMode,
this._hassUrl,
this._api.fetchWithAuth
this._api.fetchWithAuth,
abortController.signal
);
if (requested !== this.url) return;
this._resolvedUrl = resolved;
this._probeSize(resolved);
} catch (_err) {
// Aborted when the url changed or this element was disconnected,
// which already restarted or reset the resolution.
if (abortController.signal.aborted) return;
if (requested === this.url) this._resolvedUrl = undefined;
} finally {
if (this._abortController === abortController) {
this._abortController = undefined;
}
}
}
@@ -0,0 +1,128 @@
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { HaListItemButton } from "../item/ha-list-item-button";
import "./ha-media-browser-thumbnail";
/**
* @element ha-media-player-browse-list-item
* @extends {HaListItemButton}
*
* @summary
* Row of the media browser list. Always reserves a graphic next to the title
* so titles line up, and shows a thumbnail with an optional play button over
* it. Without `interactive` the row is plain text, used for the "not shown"
* row. The row is rendered inside the shadow root of `ha-list-virtualized`, so
* it carries its own styles.
*
* @slot start - Play or pick button, shown over the thumbnail.
* @slot headline - Title of the row.
*
* @csspart start - The graphic container.
*
* @attr {string} thumbnail - URL of the thumbnail. Shown inside the graphic.
*/
@customElement("ha-media-player-browse-list-item")
export class HaMediaPlayerBrowseListItem extends HaListItemButton {
@property() public thumbnail?: string;
// The "not shown" row is plain text, not a button
protected override _renderControl(content: TemplateResult): TemplateResult {
if (!this.interactive) {
return content;
}
return super._renderControl(content);
}
// Always reserve the graphic, so titles line up across rows
protected override _renderStart(): TemplateResult {
return html`<div part="start" class="start">
<div class="graphic">
${
this.thumbnail
? html`<ha-media-browser-thumbnail
.url=${this.thumbnail}
></ha-media-browser-thumbnail>`
: nothing
}
<slot name="start"></slot>
</div>
</div>`;
}
static styles: CSSResultGroup = [
HaListItemButton.styles,
css`
:host {
direction: var(--direction);
--ha-row-item-padding-block: 0;
--ha-row-item-min-height: 48px;
}
:host(.show-images) {
--ha-row-item-padding-block: var(--ha-space-1);
--ha-row-item-min-height: 64px;
}
:host(.not-shown) {
font-style: italic;
color: var(--secondary-text-color);
cursor: default;
}
::slotted(ha-svg-icon) {
color: var(--secondary-text-color);
}
.graphic {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border-radius: var(--ha-border-radius-sm);
overflow: hidden;
}
:host(.show-images) .graphic {
width: 56px;
height: 56px;
}
ha-media-browser-thumbnail {
position: absolute;
inset: 0;
}
::slotted(.play) {
position: absolute;
inset: 0;
margin: auto;
width: 40px;
height: 40px;
opacity: 0;
transition: all 0.5s;
background-color: rgba(var(--rgb-card-background-color), 0.5);
border-radius: var(--ha-border-radius-circle);
--ha-icon-button-size: 40px;
}
:host(:hover) ::slotted(.play) {
opacity: 1;
color: var(--primary-text-color);
}
::slotted(.play.show) {
opacity: 1;
background-color: transparent;
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
}
}
@@ -77,7 +77,6 @@ import "../ha-svg-icon";
import "../ha-tooltip";
import "../input/ha-input-search";
import type { HaInputSearch } from "../input/ha-input-search";
import { HaListItemButton } from "../item/ha-list-item-button";
import "../list/ha-list-virtualized";
import type {
HaListVirtualized,
@@ -88,6 +87,7 @@ import type { ManualMediaPickedEvent } from "./ha-browse-media-manual";
import "./ha-browse-media-tts";
import type { TtsMediaPickedEvent } from "./ha-browse-media-tts";
import "./ha-media-browser-thumbnail";
import "./ha-media-player-browse-list-item";
declare global {
interface HASSDomEvents {
@@ -120,105 +120,6 @@ type MediaBrowseListRow =
count: number;
});
@customElement("ha-media-player-browse-list-item")
export class HaMediaPlayerBrowseListItem extends HaListItemButton {
@property() public thumbnail?: string;
// The "not shown" row is plain text, not a button
protected override _renderBase(inner: TemplateResult): TemplateResult {
if (!this.interactive) {
return html`<div part="base" class="base" id="item">${inner}</div>`;
}
return super._renderBase(inner);
}
// Always reserve the graphic, so titles line up across rows
protected override _renderStart(): TemplateResult {
return html`<div part="start" class="start">
<div class="graphic">
${
this.thumbnail
? html`<ha-media-browser-thumbnail
.url=${this.thumbnail}
></ha-media-browser-thumbnail>`
: nothing
}
<slot name="start"></slot>
</div>
</div>`;
}
static styles: CSSResultGroup = [
HaListItemButton.styles,
css`
:host {
direction: var(--direction);
--ha-row-item-padding-block: 0;
--ha-row-item-min-height: 48px;
}
:host(.show-images) {
--ha-row-item-padding-block: var(--ha-space-1);
--ha-row-item-min-height: 64px;
}
:host(.not-shown) {
font-style: italic;
color: var(--secondary-text-color);
cursor: default;
}
::slotted(ha-svg-icon) {
color: var(--secondary-text-color);
}
.graphic {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border-radius: var(--ha-border-radius-sm);
overflow: hidden;
}
:host(.show-images) .graphic {
width: 56px;
height: 56px;
}
ha-media-browser-thumbnail {
position: absolute;
inset: 0;
}
::slotted(.play) {
position: absolute;
inset: 0;
margin: auto;
width: 40px;
height: 40px;
opacity: 0;
transition: all 0.5s;
background-color: rgba(var(--rgb-card-background-color), 0.5);
border-radius: var(--ha-border-radius-circle);
--ha-icon-button-size: 40px;
}
:host(:hover) ::slotted(.play) {
opacity: 1;
color: var(--primary-text-color);
}
::slotted(.play.show) {
opacity: 1;
background-color: transparent;
}
`,
];
}
/** Folders with at least this many items get a filter field when their source cannot search. */
const FILTER_MIN_CHILDREN = 10;
@@ -1945,6 +1846,5 @@ export class HaMediaPlayerBrowse extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-media-player-browse": HaMediaPlayerBrowse;
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
}
}
@@ -1,11 +1,20 @@
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { ensureArray } from "../../../common/array/ensure-array";
import { consume } from "../../../common/decorators/consume";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
entitiesContext,
statesContext,
} from "../../../data/context";
import type { DeviceRegistryEntry } from "../../../data/device/device_registry";
import { getDeviceIntegrationLookup } from "../../../data/device/device_registry";
import type { HaEntityPickerEntityFilterFunc } from "../../../data/entity/entity";
@@ -33,7 +42,16 @@ import type { TargetDetailsDialogParams } from "./show-dialog-target-details";
@customElement("ha-dialog-target-details")
class DialogTargetDetails extends LitElement implements HassDialog {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@state() private _params?: TargetDetailsDialogParams;
@@ -50,8 +68,8 @@ class DialogTargetDetails extends LitElement implements HassDialog {
private _exclusionsRequest = 0;
private _deviceIntegrationLookup = memoizeOne(
(entities: HomeAssistant["entities"]) =>
getDeviceIntegrationLookup(Object.values(entities))
(entities: HomeAssistant["entities"] | null) =>
getDeviceIntegrationLookup(Object.values(entities ?? {}))
);
public showDialog(params: TargetDetailsDialogParams): void {
@@ -59,8 +77,17 @@ class DialogTargetDetails extends LitElement implements HassDialog {
this._initialExclusions = params.exclusions ?? [];
this._exclusions = this._initialExclusions;
this._opened = true;
if (!params.exclusions && params.exclude) {
this._resolveExclusions(params);
}
protected willUpdate(changedProperties: PropertyValues): void {
super.willUpdate(changedProperties);
if (
changedProperties.has("_params") &&
this._params &&
!this._params.exclusions &&
this._params.exclude
) {
this._resolveExclusions(this._params);
}
}
@@ -69,7 +96,7 @@ class DialogTargetDetails extends LitElement implements HassDialog {
let exclusions: TargetExclusion[];
try {
exclusions = await resolveItemExclusions(
this.hass,
this._api.callWS,
{ type: params.type, id: params.itemId },
params.exclude,
params.selector
@@ -128,8 +155,8 @@ class DialogTargetDetails extends LitElement implements HassDialog {
private async _loadEntitySources(): Promise<void> {
try {
this._entitySources = await fetchEntitySourcesWithCache(
this.hass.callWS,
this.hass.states
this._api.callWS,
this._states ?? {}
);
} catch (err) {
// eslint-disable-next-line no-console
@@ -155,7 +182,7 @@ class DialogTargetDetails extends LitElement implements HassDialog {
return true;
}
const deviceIntegrations = this._hasIntegration({ target })
? this._deviceIntegrationLookup(this.hass.entities)
? this._deviceIntegrationLookup(this._entities)
: undefined;
return ensureArray(target.device).some((d) =>
filterSelectorDevices(d, device, deviceIntegrations)
@@ -217,19 +244,19 @@ class DialogTargetDetails extends LitElement implements HassDialog {
return html`
<ha-adaptive-dialog
.open=${this._opened}
header-title=${this.hass.localize(
header-title=${this._localize(
"ui.components.target-picker.target_details"
)}
@closed=${this._dialogClosed}
>
<div class="type-wrapper">
<div class="type-label">
${this.hass.localize(
${this._localize(
`ui.components.target-picker.type.${this._params.type}`
)}
</div>
<ha-list-base
.ariaLabel=${`${this.hass.localize(`ui.components.target-picker.type.${this._params.type}`)}: ${this._params.title}`}
.ariaLabel=${`${this._localize(`ui.components.target-picker.type.${this._params.type}`)}: ${this._params.title}`}
wrap-focus
>
${
@@ -262,10 +289,10 @@ class DialogTargetDetails extends LitElement implements HassDialog {
appearance="plain"
@click=${this.closeDialog}
>
${this.hass.localize("ui.common.cancel")}
${this._localize("ui.common.cancel")}
</ha-button>
<ha-button slot="primaryAction" @click=${this._apply}>
${this.hass.localize("ui.common.apply")}
${this._localize("ui.common.apply")}
</ha-button>
</ha-dialog-footer>
`
@@ -3,14 +3,24 @@ import memoizeOne from "memoize-one";
import {
consumeContext,
ContextController,
ContextSubscriptionController,
} from "../../common/decorators/consume";
import {
apiContext,
registriesContext,
statesContext,
} from "../../data/context";
import type { HaEntityPickerEntityFilterFunc } from "../../data/entity/entity";
import {
explainTarget,
type HassServiceTargetWithExclude,
type TargetItem,
} from "../../data/target";
import type { HomeAssistant } from "../../types";
import type {
HomeAssistant,
HomeAssistantApi,
HomeAssistantRegistries,
} from "../../types";
import type { HaDevicePickerDeviceFilterFunc } from "../device/ha-device-picker";
import { filterTargetEntries } from "./filter-target-entries";
import { targetExpandGroupContext } from "./target-expand-group-context";
@@ -26,7 +36,6 @@ import {
export type TargetExclusionsHost = ReactiveControllerHost &
HTMLElement & {
hass: HomeAssistant;
value?: HassServiceTargetWithExclude;
allowExclude: boolean;
primaryEntitiesOnly?: boolean;
@@ -55,11 +64,31 @@ export class TargetExclusionsController extends ContextController {
@consumeContext({ context: targetExpandGroupContext, subscribe: true })
private _expandGroup?: boolean;
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries;
@consumeContext({
context: apiContext,
subscribe: true,
transform: (api) => api?.callWS,
})
private _callWS?: HomeAssistantApi["callWS"];
private _states?: HomeAssistant["states"] | null;
private _request = 0;
constructor(host: TargetExclusionsHost) {
super(host);
this._host = host;
// States change all the time, so they only resolve again once loaded.
new ContextSubscriptionController(host, statesContext, (states) => {
const loaded = !this._states && !!states;
this._states = states;
if (loaded) {
this.resolve();
}
});
}
protected contextUpdated() {
@@ -78,9 +107,9 @@ export class TargetExclusionsController extends ContextController {
*/
public async resolve({ force = false }: { force?: boolean } = {}) {
const request = ++this._request;
const { hass, value, allowExclude } = this._host;
const { value, allowExclude } = this._host;
if (
!hass ||
!this._ready ||
!value ||
(!force &&
!hasIncludedTargets(value.exclude) &&
@@ -140,7 +169,7 @@ export class TargetExclusionsController extends ContextController {
item: TargetItem
): Promise<TargetExclusion | undefined> {
const { value } = this._host;
if (!value) {
if (!this._ready || !value) {
return undefined;
}
const explained = await this._explain({
@@ -152,9 +181,19 @@ export class TargetExclusionsController extends ContextController {
]?.[0];
}
private get _ready(): boolean {
return !!(
this._callWS &&
this._states &&
this._registries?.entities &&
this._registries.devices &&
this._registries.areas
);
}
private _explain(target: HassServiceTargetWithExclude) {
return explainTarget(
this._host.hass.callWS,
this._callWS!,
target,
this.expandGroup,
this._host.primaryEntitiesOnly ?? true
@@ -170,8 +209,9 @@ export class TargetExclusionsController extends ContextController {
// What the picker's filters leave of a target, narrowed like the target's
// row, so what an exclusion takes out matches what the row counts.
private _keeps(): TargetNarrowing {
const states = this._states!;
const { entities, devices, areas } = this._registries!;
const {
hass,
deviceFilter,
entityFilter,
includeDomains,
@@ -180,10 +220,10 @@ export class TargetExclusionsController extends ContextController {
} = this._host;
return (include) =>
filterTargetEntries(
hass.states,
hass.entities,
hass.devices,
hass.areas,
states,
entities,
devices,
areas,
include,
{
referenced_areas: include.referenced_areas,
@@ -145,7 +145,7 @@ export const computeExclusionsPerTarget = (
* `expandGroup` follows what the target is used for.
*/
export const resolveItemExclusions = async (
hass: HomeAssistant,
callWS: HomeAssistant["callWS"],
item: TargetItem,
exclude: HassServiceTarget | undefined,
primaryEntitiesOnly?: boolean,
@@ -155,7 +155,7 @@ export const resolveItemExclusions = async (
return [];
}
const explained = await explainTarget(
hass.callWS,
callWS,
{ [`${item.type}_id`]: [item.id], exclude },
expandGroup,
primaryEntitiesOnly
@@ -112,7 +112,7 @@ export class HaTracePathDetails extends LitElement {
initialValue: {
options: [],
showIndices: false,
select: () => undefined,
select: () => true,
fixDuplicateIds: async () => undefined,
updateTriggerId: () => false,
},
+1 -1
View File
@@ -123,7 +123,7 @@ export const setProtectedAlarmControlPanelMode = async (
(mode === "disarmed" && stateObj.attributes.code_format)
) {
const entry = await getExtendedEntityRegistryEntry(
hass,
hass.callWS,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
+201
View File
@@ -0,0 +1,201 @@
import type { LocalizeFunc } from "../common/translations/localize";
export const ROOM_ICONS = {
living_room: [
"mdi:sofa",
"mdi:sofa-single",
"mdi:television",
"mdi:fireplace",
"mdi:floor-lamp",
],
bedroom: ["mdi:bed", "mdi:bed-king", "mdi:bed-double", "mdi:lamp"],
kids_room: ["mdi:teddy-bear", "mdi:toy-brick", "mdi:bunk-bed", "mdi:cradle"],
kitchen: [
"mdi:stove",
"mdi:fridge",
"mdi:countertop",
"mdi:chef-hat",
"mdi:pot-steam",
"mdi:coffee-maker",
],
dining_room: [
"mdi:silverware-fork-knife",
"mdi:table-chair",
"mdi:table-furniture",
"mdi:glass-wine",
],
bathroom: [
"mdi:shower",
"mdi:bathtub",
"mdi:shower-head",
"mdi:toothbrush",
"mdi:hair-dryer",
],
toilet: ["mdi:toilet", "mdi:paper-roll"],
office: [
"mdi:desk",
"mdi:laptop",
"mdi:monitor",
"mdi:chair-rolling",
"mdi:bookshelf",
],
laundry_room: [
"mdi:washing-machine",
"mdi:tumble-dryer",
"mdi:iron",
"mdi:hanger",
],
hallway: ["mdi:door", "mdi:door-open", "mdi:coat-rack", "mdi:key"],
stairs: ["mdi:stairs", "mdi:stairs-up", "mdi:stairs-down"],
garage: ["mdi:garage", "mdi:garage-variant", "mdi:car", "mdi:tools"],
garden: [
"mdi:flower",
"mdi:tree",
"mdi:grass",
"mdi:sprout",
"mdi:watering-can",
"mdi:greenhouse",
],
terrace: [
"mdi:balcony",
"mdi:grill",
"mdi:umbrella-outline",
"mdi:coach-lamp",
"mdi:patio-heater",
],
basement: [
"mdi:home-floor-negative-1",
"mdi:stairs-down",
"mdi:water-boiler",
],
attic: ["mdi:home-roof", "mdi:package-variant-closed"],
storage: ["mdi:archive", "mdi:package-variant-closed", "mdi:warehouse"],
utility_room: [
"mdi:water-boiler",
"mdi:heat-pump",
"mdi:server-network",
"mdi:flash",
],
pool: ["mdi:pool", "mdi:swim"],
media_room: [
"mdi:theater",
"mdi:projector",
"mdi:television",
"mdi:movie-open",
],
game_room: [
"mdi:gamepad-variant",
"mdi:billiards",
"mdi:cards-playing",
"mdi:dice-multiple",
],
music_room: ["mdi:piano", "mdi:guitar-acoustic", "mdi:music"],
library: ["mdi:bookshelf", "mdi:book-open-variant", "mdi:library"],
bar: [
"mdi:glass-cocktail",
"mdi:glass-mug-variant",
"mdi:bottle-wine",
"mdi:beer",
],
dressing_room: [
"mdi:hanger",
"mdi:wardrobe",
"mdi:tshirt-crew",
"mdi:shoe-heel",
],
workshop: ["mdi:tools", "mdi:hammer-wrench", "mdi:toolbox", "mdi:saw-blade"],
server_room: ["mdi:server-network", "mdi:server", "mdi:router-network"],
safe_room: ["mdi:shield-home", "mdi:shield-lock", "mdi:safe"],
prayer_room: ["mdi:hands-pray", "mdi:meditation", "mdi:candle"],
sauna: ["mdi:spa", "mdi:hot-tub", "mdi:thermometer-high"],
outdoor_kitchen: ["mdi:grill", "mdi:grill-outline", "mdi:pizza"],
driveway: ["mdi:road-variant", "mdi:car", "mdi:gate"],
} as const satisfies Record<string, readonly string[]>;
export type RoomType = keyof typeof ROOM_ICONS;
type RoomKeywords = Partial<Record<RoomType, string[]>>;
export const ROOM_TYPES = Object.keys(ROOM_ICONS) as RoomType[];
export const isRoomType = (value: string): value is RoomType =>
(ROOM_TYPES as string[]).includes(value);
// Languages written without spaces between words
const NO_WORD_SPACING =
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}]/u;
const normalizeRoomText = (text: string): string =>
text
.normalize("NFD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.replace(/['’]/g, "")
.replace(/[^\p{L}\p{N}]+/gu, " ")
.trim();
interface RoomMatch {
room: RoomType;
start: number;
end: number;
}
const findMatches = (name: string, keywords: RoomKeywords): RoomMatch[] => {
const text = ` ${normalizeRoomText(name)} `;
const candidates: RoomMatch[] = [];
for (const room of ROOM_TYPES) {
for (const keyword of keywords[room] ?? []) {
const phrase = normalizeRoomText(keyword);
if (!phrase) {
continue;
}
const needle = NO_WORD_SPACING.test(phrase) ? phrase : ` ${phrase} `;
const start = text.indexOf(needle);
if (start !== -1) {
candidates.push({ room, start, end: start + needle.length });
}
}
}
// The longest phrase wins, so "guest bedroom" is not also read as "bedroom"
candidates.sort((a, b) => b.end - b.start - (a.end - a.start));
const kept: RoomMatch[] = [];
for (const match of candidates) {
const overlaps = kept.some(
(other) => match.start < other.end - 1 && other.start < match.end - 1
);
if (!overlaps) {
kept.push(match);
}
}
return kept.sort((a, b) => a.start - b.start);
};
const matchRoomTypes = (
names: string[],
keywords: RoomKeywords
): RoomType[] => {
const rooms = new Set<RoomType>();
for (const name of names) {
for (const match of findMatches(name, keywords)) {
rooms.add(match.room);
}
}
return [...rooms];
};
const roomIconSuggestions = (rooms: RoomType[]): string[] => [
...new Set(rooms.flatMap((room) => ROOM_ICONS[room])),
];
export const getAreaIconSuggestions = (
names: string[],
localize: LocalizeFunc
): string[] => {
const keywords: RoomKeywords = Object.fromEntries(
ROOM_TYPES.map((room) => [
room,
localize(`ui.components.rooms.keywords.${room}`).split("|"),
])
);
return roomIconSuggestions(matchRoomTypes(names, keywords));
};
+80
View File
@@ -0,0 +1,80 @@
export const STREAM_TYPE_HLS = "hls";
export const STREAM_TYPE_WEB_RTC = "web_rtc";
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
export const MJPEG_STREAM = "mjpeg";
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
export interface CameraStream {
type: CameraStreamType;
visible: boolean;
}
/** What a player reported, `hasVideo: false` means it failed to load. */
export interface CameraStreamTracks {
hasAudio: boolean;
hasVideo: boolean;
}
export interface CameraStreamSelectionOptions {
supportedTypes?: StreamType[];
hlsStreams?: CameraStreamTracks;
webRtcStreams?: CameraStreamTracks;
}
/**
* Decides which players are rendered and which one is shown. Hidden players
* are still loading in the background.
*/
export const selectCameraStreams = ({
supportedTypes,
hlsStreams,
webRtcStreams,
}: CameraStreamSelectionOptions): CameraStream[] => {
if (!supportedTypes) {
return [];
}
if (supportedTypes.length === 0) {
// doesn't support any stream type, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
if (supportedTypes.length === 1) {
// only 1 stream type, no need to choose
if (
(supportedTypes[0] === STREAM_TYPE_HLS &&
hlsStreams?.hasVideo === false) ||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
webRtcStreams?.hasVideo === false)
) {
// stream failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
return [{ type: supportedTypes[0], visible: true }];
}
const hlsFailed = hlsStreams?.hasVideo === false;
if (webRtcStreams?.hasVideo) {
// WebRTC is preferred whenever it plays, it has the lowest latency
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
if (webRtcStreams?.hasVideo === false) {
if (hlsFailed) {
// both streams failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
return [{ type: STREAM_TYPE_HLS, visible: true }];
}
// WebRTC is still loading
if (hlsFailed) {
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
return [
{ type: STREAM_TYPE_HLS, visible: true },
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
};
+6 -4
View File
@@ -7,13 +7,15 @@ import { timeCacheEntityPromiseFunc } from "../common/util/time-cache-entity-pro
import type { HomeAssistant, HomeAssistantApi } from "../types";
import { fileDownload } from "../util/file_download";
import { getSignedPath } from "./auth";
import type { StreamType } from "./camera-streams";
export const CAMERA_ORIENTATIONS = [1, 2, 3, 4, 6, 8];
export const STREAM_TYPE_HLS = "hls";
export const STREAM_TYPE_WEB_RTC = "web_rtc";
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
export {
STREAM_TYPE_HLS,
STREAM_TYPE_WEB_RTC,
type StreamType,
} from "./camera-streams";
export { CameraEntityFeature } from "./feature/camera_entity_feature";
-70
View File
@@ -1,13 +1,5 @@
import type { ConfigPath } from "../common/util/config-path";
import type { HomeAssistant } from "../types";
export interface ConfigValidationError {
message: string;
/** Where the problem is, `[]` when core does not know. */
path: ConfigPath;
code?: string | null;
}
export interface ValidConfig {
valid: true;
error: null;
@@ -16,14 +8,10 @@ export interface ValidConfig {
export interface InvalidConfig {
valid: false;
error: string;
/** Paths start at the item index of the section. */
errors: ConfigValidationError[];
}
type ValidKeys = "triggers" | "actions" | "conditions";
export type ValidationSectionKeys = Partial<Record<ValidKeys, string>>;
export const validateConfig = <T extends Partial<Record<ValidKeys, unknown>>>(
hass: HomeAssistant,
config: T
@@ -32,61 +20,3 @@ export const validateConfig = <T extends Partial<Record<ValidKeys, unknown>>>(
type: "validate_config",
...config,
});
/**
* Flattens a `validate_config` result into errors with paths from the config
* root. `sectionKeys` names the config key of a section when it differs from
* the key it is validated under, e.g. `{ actions: "sequence" }` for scripts.
*/
export const validationResultErrors = (
result: Partial<Record<ValidKeys, ValidConfig | InvalidConfig>>,
sectionKeys: ValidationSectionKeys = {}
): ConfigValidationError[] =>
(Object.keys(result) as ValidKeys[]).flatMap((key) => {
const section = result[key];
if (!section || section.valid) {
return [];
}
const sectionKey = sectionKeys[key] ?? key;
return section.errors.map((error) => ({
...error,
path: [sectionKey, ...error.path],
}));
});
export const validateConfigErrors = async (
hass: HomeAssistant,
config: Partial<Record<ValidKeys, unknown>>,
sectionKeys?: ValidationSectionKeys
): Promise<ConfigValidationError[]> =>
validationResultErrors(await validateConfig(hass, config), sectionKeys);
export interface ConfigSaveError {
message: string;
errors: ConfigValidationError[];
}
/**
* Reads the errors of a failed config save. Errors that are not about the
* config, like a network error, only have a message.
*/
export const parseConfigSaveError = (err: unknown): ConfigSaveError => {
const { body, error } = (err ?? {}) as { body?: unknown; error?: unknown };
const bodyObject =
body && typeof body === "object"
? (body as { message?: unknown; errors?: unknown })
: undefined;
const message = String(
bodyObject?.message ||
error ||
(typeof body === "string" && body) ||
(err instanceof Error && err.message) ||
err
);
return {
message,
errors: Array.isArray(bodyObject?.errors)
? (bodyObject.errors as ConfigValidationError[])
: [],
};
};
+10 -4
View File
@@ -220,24 +220,30 @@ export class ConfigEntryStream {
private _entries: ConfigEntry[] = [];
processMessage(message: ConfigEntryUpdate[]) {
let entries =
message.length === 0 ||
message.some((configEntry) => configEntry.type === null)
? []
: [...this._entries];
message.forEach((configEntry) => {
if (configEntry.type === null || configEntry.type === "added") {
this._entries.push(configEntry.entry);
entries.push(configEntry.entry);
return;
}
if (configEntry.type === "removed") {
this._entries = this._entries.filter(
entries = entries.filter(
(entry) => entry.entry_id !== configEntry.entry.entry_id
);
return;
}
if (configEntry.type === "updated") {
const newEntry = configEntry.entry;
this._entries = this._entries.map((entry) =>
entries = entries.map((entry) =>
entry.entry_id === newEntry.entry_id ? newEntry : entry
);
}
});
return this._entries;
this._entries = entries;
return entries;
}
}
+4 -4
View File
@@ -30,11 +30,11 @@ const HEADERS = {
};
export const createConfigFlow = (
hass: HomeAssistant,
callApi: HomeAssistant["callApi"],
handler: string,
entry_id?: string
) =>
hass.callApi<DataEntryFlowStep>(
callApi<DataEntryFlowStep>(
"POST",
"config/config_entries/flow",
{
@@ -53,11 +53,11 @@ export const fetchConfigFlow = (hass: HomeAssistant, flowId: string) =>
);
export const handleConfigFlowStep = (
hass: HomeAssistant,
callApi: HomeAssistant["callApi"],
flowId: string,
data: Record<string, any>
) =>
hass.callApi<DataEntryFlowStep>(
callApi<DataEntryFlowStep>(
"POST",
`config/config_entries/flow/${flowId}`,
data,
+123 -25
View File
@@ -2,16 +2,37 @@ import type {
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import { stateActive } from "../common/entity/state_active";
import { supportsFeature } from "../common/entity/supports-feature";
import type { HomeAssistantFormatters } from "../types";
import { UNAVAILABLE } from "./entity/entity";
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
import { CoverEntityFeature } from "./feature/cover_entity_feature";
export { CoverEntityFeature };
export const DEFAULT_COVER_FAVORITE_POSITIONS = [0, 25, 75, 100];
export type CoverControlMode = "position" | "tilt";
export type CoverAction = "open" | "close" | "stop";
export type CoverCommand =
| { mode: CoverControlMode; action: CoverAction }
| { mode: CoverControlMode; action: "set"; value: number };
export interface CoverRequest {
mode: CoverControlMode;
value: number;
}
export interface CoverSwipe {
action: "open" | "close";
passedHalfway: boolean;
}
export interface CoverDrag {
value: number;
swipe?: CoverSwipe;
}
export const coverSupportsPosition = (stateObj: CoverEntity) =>
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION);
@@ -21,11 +42,79 @@ export const coverSupportsTiltPosition = (stateObj: CoverEntity) =>
export const coverSupportsAnyPosition = (stateObj: CoverEntity) =>
coverSupportsPosition(stateObj) || coverSupportsTiltPosition(stateObj);
export function isFullyOpen(stateObj: CoverEntity) {
if (stateObj.attributes.current_position !== undefined) {
return stateObj.attributes.current_position === 100;
export const coverSupportsSetValue = (
stateObj: CoverEntity,
mode: CoverControlMode
) =>
mode === "tilt"
? coverSupportsTiltPosition(stateObj)
: coverSupportsPosition(stateObj);
const POSITION_FEATURES = [
CoverEntityFeature.OPEN,
CoverEntityFeature.CLOSE,
CoverEntityFeature.STOP,
CoverEntityFeature.SET_POSITION,
];
const TILT_FEATURES = [
CoverEntityFeature.OPEN_TILT,
CoverEntityFeature.CLOSE_TILT,
CoverEntityFeature.STOP_TILT,
CoverEntityFeature.SET_TILT_POSITION,
];
export const coverHasPositionControls = (stateObj: CoverEntity) =>
POSITION_FEATURES.some((feature) => supportsFeature(stateObj, feature));
export const coverHasTiltControls = (stateObj: CoverEntity) =>
TILT_FEATURES.some((feature) => supportsFeature(stateObj, feature));
export const defaultCoverMode = (stateObj: CoverEntity): CoverControlMode =>
coverHasTiltControls(stateObj) && !coverHasPositionControls(stateObj)
? "tilt"
: "position";
export const coverModeAttribute = (mode: CoverControlMode) =>
mode === "tilt" ? "current_tilt_position" : "current_position";
const COVER_SERVICES: Record<
CoverControlMode,
Record<CoverCommand["action"], string>
> = {
position: {
open: "open_cover",
close: "close_cover",
stop: "stop_cover",
set: "set_cover_position",
},
tilt: {
open: "open_cover_tilt",
close: "close_cover_tilt",
stop: "stop_cover_tilt",
set: "set_cover_tilt_position",
},
};
export const coverCommandService = ({ mode, action }: CoverCommand) =>
COVER_SERVICES[mode][action];
export const coverCommandData = (
stateObj: CoverEntity,
command: CoverCommand
): Record<string, unknown> => {
const data = { entity_id: stateObj.entity_id };
if (command.action !== "set") {
return data;
}
return stateObj.state === "open";
if (command.mode === "tilt") {
return { ...data, tilt_position: command.value };
}
return { ...data, position: command.value };
};
export function isFullyOpen(stateObj: CoverEntity) {
return stateObj.attributes.current_position === 100;
}
export function isFullyClosed(stateObj: CoverEntity) {
@@ -51,6 +140,10 @@ export function isClosing(stateObj: CoverEntity) {
return stateObj.state === "closing";
}
export function isMoving(stateObj: CoverEntity) {
return isOpening(stateObj) || isClosing(stateObj);
}
export function isTiltOnly(stateObj: CoverEntity) {
const supportsCover =
supportsFeature(stateObj, CoverEntityFeature.OPEN) ||
@@ -113,24 +206,29 @@ export interface CoverEntity extends HassEntityBase {
attributes: CoverEntityAttributes;
}
export function computeCoverPositionStateDisplay(
export const coverCurrentValue = (
stateObj: CoverEntity,
formatEntityAttributeValue: HomeAssistantFormatters["formatEntityAttributeValue"],
position?: number
) {
const statePosition = stateActive(stateObj)
? (stateObj.attributes.current_position ??
stateObj.attributes.current_tilt_position)
: undefined;
mode: CoverControlMode
): number | undefined => {
if (mode === "tilt") {
return stateObj.attributes.current_tilt_position ?? undefined;
}
const position = stateObj.attributes.current_position;
if (
position != null ||
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION)
) {
return position ?? undefined;
}
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
};
const currentPosition = position ?? statePosition;
return currentPosition && currentPosition !== 100
? formatEntityAttributeValue(
stateObj,
// Always use position as it's the same formatting as tilt position
"current_position",
Math.round(currentPosition)
)
: "";
declare global {
interface HASSDomEvents {
"cover-command": CoverCommand;
"cover-drag-changed": { drag?: CoverDrag };
}
}
+323 -50
View File
@@ -81,7 +81,6 @@ export const emptyGridSourceEnergyPreference =
number_energy_price: null,
entity_energy_price_export: null,
number_energy_price_export: null,
cost_adjustment_day: 0,
});
export const emptySolarEnergyPreference =
@@ -97,13 +96,6 @@ export const emptyHomeEnergyPreference =
stat_energy_to: "",
});
export const emptyBatteryEnergyPreference =
(): BatterySourceTypeEnergyPreference => ({
type: "battery",
stat_energy_from: "",
stat_energy_to: "",
});
export const emptyGasEnergyPreference = (): GasSourceTypeEnergyPreference => ({
type: "gas",
stat_energy_from: "",
@@ -169,7 +161,6 @@ export interface GridSourceTypeEnergyPreference {
stat_rate?: string; // always available if power_config is set
power_config?: PowerConfig;
cost_adjustment_day: number;
name?: string;
}
@@ -190,16 +181,125 @@ export interface HomeSourceTypeEnergyPreference {
name?: string;
}
export interface BatterySourceTypeEnergyPreference {
export interface BatteryTotalsSourceTypeEnergyPreference {
type: "battery";
stat_energy_from: string;
stat_energy_to: string;
stat_energy_from: string; // out of the battery
stat_energy_to: string; // into the battery
stat_rate?: string; // always available if power_config is set
power_config?: PowerConfig;
stat_soc?: string;
capacity?: number; // usable capacity in kWh, used to weight the combined SOC
name?: string;
}
// Non-negative power sensors, any subset
export interface BatteryDirectionsPowerConfig {
stat_rate_from_grid?: string; // grid → battery
stat_rate_from_solar?: string; // solar → battery
stat_rate_to_home?: string; // battery → home
stat_rate_to_grid?: string; // battery → grid
}
// A missing direction is 0. At least one charge and one discharge direction is
// required, so getBatteryEnergyStatIds never returns an empty list.
export interface BatteryDirectionsSourceTypeEnergyPreference {
type: "battery";
stat_energy_from?: undefined;
stat_energy_to?: undefined;
stat_energy_from_grid?: string; // grid → battery
stat_energy_from_solar?: string; // solar → battery
stat_energy_to_home?: string; // battery → home
stat_energy_to_grid?: string; // battery → grid
// Net power generated from power_config, + discharge and − charge
stat_rate?: string;
power_config?: BatteryDirectionsPowerConfig;
stat_soc?: string;
capacity?: number;
name?: string;
}
export type BatterySourceTypeEnergyPreference =
| BatteryTotalsSourceTypeEnergyPreference
| BatteryDirectionsSourceTypeEnergyPreference;
export interface BatteryFlowStatIds {
grid_to_battery?: string;
solar_to_battery?: string;
battery_to_home?: string;
battery_to_grid?: string;
}
export const BATTERY_FLOW_KEYS = [
"grid_to_battery",
"solar_to_battery",
"battery_to_home",
"battery_to_grid",
] as const satisfies readonly (keyof BatteryFlowStatIds)[];
export const isBatteryDirections = (
source: BatterySourceTypeEnergyPreference
): source is BatteryDirectionsSourceTypeEnergyPreference => {
const directions = source as BatteryDirectionsSourceTypeEnergyPreference;
return !!(
directions.stat_energy_from_grid ||
directions.stat_energy_from_solar ||
directions.stat_energy_to_home ||
directions.stat_energy_to_grid
);
};
/** The direction statistics, or undefined for a battery configured with totals. */
export const getBatteryFlowStatIds = (
source: BatterySourceTypeEnergyPreference
): BatteryFlowStatIds | undefined =>
isBatteryDirections(source)
? {
grid_to_battery: source.stat_energy_from_grid || undefined,
solar_to_battery: source.stat_energy_from_solar || undefined,
battery_to_home: source.stat_energy_to_home || undefined,
battery_to_grid: source.stat_energy_to_grid || undefined,
}
: undefined;
/** The direction power sensors, or undefined for a battery configured with totals. */
export const getBatteryFlowPowerIds = (
source: BatterySourceTypeEnergyPreference
): BatteryFlowStatIds | undefined =>
isBatteryDirections(source)
? {
grid_to_battery: source.power_config?.stat_rate_from_grid || undefined,
solar_to_battery:
source.power_config?.stat_rate_from_solar || undefined,
battery_to_home: source.power_config?.stat_rate_to_home || undefined,
battery_to_grid: source.power_config?.stat_rate_to_grid || undefined,
}
: undefined;
/** Statistics whose sum is the energy going into and coming out of the battery. */
export const getBatteryEnergyStatIds = (
source: BatterySourceTypeEnergyPreference
): { charge: string[]; discharge: string[] } => {
if (!isBatteryDirections(source)) {
return {
charge: [source.stat_energy_to],
discharge: [source.stat_energy_from],
};
}
const ids = (...stats: (string | undefined)[]) =>
stats.filter((id): id is string => !!id);
return {
charge: ids(source.stat_energy_from_grid, source.stat_energy_from_solar),
discharge: ids(source.stat_energy_to_home, source.stat_energy_to_grid),
};
};
/** Identifies a battery in page keys and lookups. */
export const getBatteryPrimaryStat = (
source: BatterySourceTypeEnergyPreference
): string => {
const { charge, discharge } = getBatteryEnergyStatIds(source);
return discharge[0] ?? charge[0] ?? "";
};
export interface GasSourceTypeEnergyPreference {
type: "gas";
@@ -392,6 +492,28 @@ export const computeEnergyLabel = (
);
};
/**
* Name that cards show as "<name> charged" and "<name> discharged". Unnamed
* batteries configured with totals are labelled by each statistic instead.
*/
export const getBatteryName = (
states: HomeAssistant["states"],
formatEntityName: HomeAssistant["formatEntityName"],
source: BatterySourceTypeEnergyPreference,
statsMetadata?: Record<string, StatisticsMetaData>
): string | undefined => {
if (source.name || !isBatteryDirections(source)) {
return source.name;
}
const primary = getBatteryPrimaryStat(source);
return computeEnergyLabel(
states,
formatEntityName,
primary,
statsMetadata?.[primary]
);
};
export const computeEnergyStatisticArea = (
registries: HomeAssistantRegistries,
statisticId: string
@@ -552,8 +674,8 @@ export const getReferencedStatisticIds = (
}
if (source.type === "battery") {
statIDs.push(source.stat_energy_from);
statIDs.push(source.stat_energy_to);
const { charge, discharge } = getBatteryEnergyStatIds(source);
statIDs.push(...discharge, ...charge);
continue;
}
@@ -1637,7 +1759,8 @@ const getEnergyGasUnit = (
return [source.stat_energy_to];
}
if (source.type === "battery") {
return [source.stat_energy_from, source.stat_energy_to];
const { charge, discharge } = getBatteryEnergyStatIds(source);
return [...discharge, ...charge];
}
if (source.type === "grid") {
return [source.stat_energy_from, source.stat_energy_to].filter(
@@ -1710,6 +1833,14 @@ export interface EnergySumData {
from_battery?: Record<number, number>;
solar?: Record<number, number>;
home?: Record<number, number>;
// Set together, only when a battery has direction statistics
grid_to_battery?: Record<number, number>;
solar_to_battery?: Record<number, number>;
battery_to_home?: Record<number, number>;
battery_to_grid?: Record<number, number>;
// Charge and discharge of the batteries configured with totals
to_battery_totals?: Record<number, number>;
from_battery_totals?: Record<number, number>;
total: {
to_grid?: number;
from_grid?: number;
@@ -1717,6 +1848,12 @@ export interface EnergySumData {
from_battery?: number;
solar?: number;
home?: number;
grid_to_battery?: number;
solar_to_battery?: number;
battery_to_home?: number;
battery_to_grid?: number;
to_battery_totals?: number;
from_battery_totals?: number;
};
timestamps: number[];
}
@@ -1758,14 +1895,10 @@ const getSummedDataPartial = (
data: EnergyData,
compare?: boolean
): EnergySumData => {
const statIds: {
to_grid?: string[];
from_grid?: string[];
solar?: string[];
to_battery?: string[];
from_battery?: string[];
home?: string[];
} = {};
const statIds: Partial<
Record<Exclude<keyof EnergySumData, "total" | "timestamps">, string[]>
> = {};
const batteries: BatterySourceTypeEnergyPreference[] = [];
for (const source of data.prefs.energy_sources) {
if (source.type === "solar") {
@@ -1783,12 +1916,14 @@ const getSummedDataPartial = (
}
if (source.type === "battery") {
batteries.push(source);
const { charge, discharge } = getBatteryEnergyStatIds(source);
if (statIds.to_battery) {
statIds.to_battery.push(source.stat_energy_to);
statIds.from_battery!.push(source.stat_energy_from);
statIds.to_battery.push(...charge);
statIds.from_battery!.push(...discharge);
} else {
statIds.to_battery = [source.stat_energy_to];
statIds.from_battery = [source.stat_energy_from];
statIds.to_battery = [...charge];
statIds.from_battery = [...discharge];
}
continue;
}
@@ -1814,6 +1949,23 @@ const getSummedDataPartial = (
}
}
if (batteries.some(isBatteryDirections)) {
for (const key of BATTERY_FLOW_KEYS) {
statIds[key] = batteries.flatMap(
(battery) => getBatteryFlowStatIds(battery)?.[key] ?? []
);
}
const totalsBatteries = batteries.filter(
(battery) => !isBatteryDirections(battery)
);
statIds.to_battery_totals = totalsBatteries.flatMap(
(battery) => getBatteryEnergyStatIds(battery).charge
);
statIds.from_battery_totals = totalsBatteries.flatMap(
(battery) => getBatteryEnergyStatIds(battery).discharge
);
}
const summedData: EnergySumData = { total: {}, timestamps: [] };
const timestamps = new Set<number>();
Object.entries(statIds).forEach(([key, subStatIds]) => {
@@ -1884,11 +2036,12 @@ const computeConsumptionDataPartial = (
},
};
const measured = BATTERY_FLOW_KEYS.some((key) => data[key]);
const fromGrid = data.from_grid;
const toGrid = data.to_grid;
const solarData = data.solar;
const toBattery = data.to_battery;
const fromBattery = data.from_battery;
const toBattery = measured ? data.to_battery_totals : data.to_battery;
const fromBattery = measured ? data.from_battery_totals : data.from_battery;
const total = outData.total;
data.timestamps.forEach((t) => {
@@ -1903,13 +2056,25 @@ const computeConsumptionDataPartial = (
used_total,
solar_to_battery,
solar_to_grid,
} = computeConsumptionSingle({
from_grid: fromGrid && (fromGrid[t] ?? 0),
to_grid: toGrid && (toGrid[t] ?? 0),
solar: solarData && (solarData[t] ?? 0),
to_battery: toBattery && (toBattery[t] ?? 0),
from_battery: fromBattery && (fromBattery[t] ?? 0),
});
} = computeConsumptionSingle(
{
from_grid: fromGrid && (fromGrid[t] ?? 0),
to_grid: toGrid && (toGrid[t] ?? 0),
solar: solarData && (solarData[t] ?? 0),
to_battery: toBattery && (toBattery[t] ?? 0),
from_battery: fromBattery && (fromBattery[t] ?? 0),
},
measured
? {
measured: {
grid_to_battery: data.grid_to_battery?.[t] ?? 0,
solar_to_battery: data.solar_to_battery?.[t] ?? 0,
battery_to_home: data.battery_to_home?.[t] ?? 0,
battery_to_grid: data.battery_to_grid?.[t] ?? 0,
},
}
: undefined
);
const usedTotal = hasHome ? Math.max(homeUsed, 0) : used_total;
outData.used_total[t] = usedTotal;
@@ -1933,13 +2098,15 @@ const computeConsumptionDataPartial = (
return outData;
};
export const computeConsumptionSingle = (data: {
interface ConsumptionInput {
from_grid: number | undefined;
to_grid: number | undefined;
solar: number | undefined;
to_battery: number | undefined;
from_battery: number | undefined;
}): {
}
interface ConsumptionResult {
grid_to_battery: number;
battery_to_grid: number;
solar_to_battery: number;
@@ -1948,7 +2115,12 @@ export const computeConsumptionSingle = (data: {
used_grid: number;
used_battery: number;
used_total: number;
} => {
}
const inferConsumption = (
data: ConsumptionInput,
usedTotal?: number
): ConsumptionResult => {
let to_grid = Math.max(data.to_grid || 0, 0);
let to_battery = Math.max(data.to_battery || 0, 0);
let solar = Math.max(data.solar || 0, 0);
@@ -1956,11 +2128,12 @@ export const computeConsumptionSingle = (data: {
let from_battery = Math.max(data.from_battery || 0, 0);
const used_total =
usedTotal ??
(from_grid || 0) +
(solar || 0) +
(from_battery || 0) -
(to_grid || 0) -
(to_battery || 0);
(solar || 0) +
(from_battery || 0) -
(to_grid || 0) -
(to_battery || 0);
let grid_to_battery = 0;
@@ -2028,6 +2201,70 @@ export const computeConsumptionSingle = (data: {
};
};
export type MeasuredBatteryFlows = Record<
(typeof BATTERY_FLOW_KEYS)[number],
number | undefined
>;
/**
* Splits the energy or power of one period into flows. Batteries with
* direction statistics pass them in `measured`, and `to_battery` and
* `from_battery` then only hold the batteries configured with totals.
* Measured flows are kept as they are; only the rest is estimated. Leave a
* meter undefined when it isn't configured, rather than 0.
*/
export const computeConsumptionSingle = (
data: ConsumptionInput,
options?: { measured?: MeasuredBatteryFlows; used_total?: number }
): ConsumptionResult => {
const measured = options?.measured;
if (!measured) {
return inferConsumption(data, options?.used_total);
}
const clamp = (value: number | undefined) => Math.max(value || 0, 0);
const gridToBattery = clamp(measured.grid_to_battery);
const solarToBattery = clamp(measured.solar_to_battery);
const batteryToHome = clamp(measured.battery_to_home);
const batteryToGrid = clamp(measured.battery_to_grid);
const fromGrid = clamp(data.from_grid);
const toGrid = clamp(data.to_grid);
const solar = clamp(data.solar);
// A flow without a configured meter never passed one, so it stays out of
// the home load
const metered = (meter: number | undefined, flow: number) =>
meter === undefined ? 0 : flow;
const toBattery =
clamp(data.to_battery) +
metered(data.from_grid, gridToBattery) +
metered(data.solar, solarToBattery);
const fromBattery =
clamp(data.from_battery) +
batteryToHome +
metered(data.to_grid, batteryToGrid);
const usedTotal =
options.used_total ?? fromGrid + solar + fromBattery - toGrid - toBattery;
// Only what the measured flows leave over is estimated
const inferred = inferConsumption(
{
from_grid: Math.max(fromGrid - gridToBattery, 0),
to_grid: Math.max(toGrid - batteryToGrid, 0),
solar: Math.max(solar - solarToBattery, 0),
to_battery: data.to_battery,
from_battery: data.from_battery,
},
Math.max(usedTotal - batteryToHome, 0)
);
return {
...inferred,
grid_to_battery: inferred.grid_to_battery + gridToBattery,
solar_to_battery: inferred.solar_to_battery + solarToBattery,
battery_to_grid: inferred.battery_to_grid + batteryToGrid,
used_battery: inferred.used_battery + batteryToHome,
used_total: usedTotal,
};
};
export const formatConsumptionShort = (
locale: HomeAssistant["locale"],
consumption: number | null,
@@ -2517,18 +2754,54 @@ export const downloadEnergyData = (
grid_productions_cost
);
const batteries = energy_sources.filter(
(s): s is BatterySourceTypeEnergyPreference => s.type === "battery"
);
const battery_ins: string[] = [];
const battery_outs: string[] = [];
energy_sources
.filter((s) => s.type === "battery")
.forEach((source) => {
source = source as BatterySourceTypeEnergyPreference;
battery_ins.push(source.stat_energy_to);
battery_outs.push(source.stat_energy_from);
const battery_flows: Record<keyof BatteryFlowStatIds, string[]> = {
grid_to_battery: [],
solar_to_battery: [],
battery_to_home: [],
battery_to_grid: [],
};
batteries.forEach((source) => {
const flows = getBatteryFlowStatIds(source);
if (!flows) {
const { charge, discharge } = getBatteryEnergyStatIds(source);
battery_ins.push(...charge);
battery_outs.push(...discharge);
return;
}
BATTERY_FLOW_KEYS.forEach((key) => {
if (flows[key]) {
battery_flows[key].push(flows[key]);
}
});
});
printCategory("battery_in", battery_ins, electricUnit);
printCategory("battery_out", battery_outs, electricUnit);
printCategory(
"battery_in_from_grid",
battery_flows.grid_to_battery,
electricUnit
);
printCategory(
"battery_in_from_solar",
battery_flows.solar_to_battery,
electricUnit
);
printCategory(
"battery_out_to_home",
battery_flows.battery_to_home,
electricUnit
);
printCategory(
"battery_out_to_grid",
battery_flows.battery_to_grid,
electricUnit
);
const solar_productions: string[] = [];
energy_sources
@@ -2645,7 +2918,7 @@ export const downloadEnergyData = (
const hasSolar = !!solar_productions.length;
const hasHome = !!home_consumptions.length;
const hasBattery = !!battery_ins.length;
const hasBattery = batteries.length > 0;
const hasGridReturn = !!grid_productions.length;
const hasGridSource = !!grid_consumptions.length;
+23 -23
View File
@@ -6,6 +6,7 @@ import {
computeEntitySearchLabels,
} from "../../common/entity/compute_entity_name_display";
import type { RelatedIdSets } from "../../common/search/related-context";
import type { LocalizeFunc } from "../../common/translations/localize";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import type { PickerComboBoxItem } from "../../components/ha-picker-combo-box";
import type { FuseWeightedKey } from "../../resources/fuseMultiTerm";
@@ -51,6 +52,14 @@ export const entityComboBoxKeys: FuseWeightedKey[] = [
];
export interface GetEntitiesOptions {
states: HomeAssistant["states"];
entities: HomeAssistant["entities"];
devices: HomeAssistant["devices"];
areas: HomeAssistant["areas"];
floors: HomeAssistant["floors"];
localize: LocalizeFunc;
language: string;
translationMetadata: HomeAssistant["translationMetadata"];
includeDomains?: string[];
excludeDomains?: string[];
entityFilter?: HaEntityPickerEntityFilterFunc;
@@ -63,20 +72,11 @@ export interface GetEntitiesOptions {
}
export const getEntities = (
hass: Pick<
HomeAssistant,
| "states"
| "entities"
| "devices"
| "areas"
| "floors"
| "language"
| "translationMetadata"
| "localize"
>,
options?: GetEntitiesOptions
options: GetEntitiesOptions
): EntityComboBoxItem[] => {
const {
states,
localize,
includeDomains,
excludeDomains,
entityFilter,
@@ -86,11 +86,11 @@ export const getEntities = (
excludeEntities,
value,
idPrefix = "",
} = options ?? {};
} = options;
let items: EntityComboBoxItem[];
let entityIds = Object.keys(hass.states);
let entityIds = Object.keys(states);
// These run over every entity, so use Sets for O(1) membership instead of
// repeated Array.includes scans.
@@ -126,21 +126,21 @@ export const getEntities = (
// of inside the map over (potentially thousands of) entities.
const domainNames = new Map<string, string>();
const displayOptions = {
entities: hass.entities,
devices: hass.devices,
areas: hass.areas,
floors: hass.floors,
language: hass.language,
translationMetadata: hass.translationMetadata,
entities: options.entities,
devices: options.devices,
areas: options.areas,
floors: options.floors,
language: options.language,
translationMetadata: options.translationMetadata,
};
items = entityIds.map<EntityComboBoxItem>((entityId) => {
const stateObj = hass.states[entityId];
const stateObj = states[entityId];
const domain = computeDomain(entityId);
let domainName = domainNames.get(domain);
if (domainName === undefined) {
domainName = domainToName(hass.localize, domain);
domainName = domainToName(localize, domain);
domainNames.set(domain, domainName);
}
@@ -156,7 +156,7 @@ export const getEntities = (
domain_name: domainName,
sorting_label: [primary, secondary].filter(Boolean).join("_"),
search_labels: {
...computeEntitySearchLabels(stateObj, hass),
...computeEntitySearchLabels(stateObj, displayOptions),
domainName: domainName || null,
entityId: entityId,
},
+2 -2
View File
@@ -266,10 +266,10 @@ export const computeEntityRegistryName = (
};
export const getExtendedEntityRegistryEntry = (
hass: Pick<HomeAssistant, "callWS">,
callWS: HomeAssistant["callWS"],
entityId: string
): Promise<ExtEntityRegistryEntry> =>
hass.callWS({
callWS({
type: "config/entity_registry/get",
entity_id: entityId,
});
+55
View File
@@ -1,8 +1,11 @@
import type {
HassEntities,
HassEntity,
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import { computeDomain } from "../common/entity/compute_domain";
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
interface GroupEntityAttributes extends HassEntityAttributeBase {
entity_id: string[];
@@ -24,3 +27,55 @@ export const computeGroupDomain = (
];
return uniqueDomains.length === 1 ? uniqueDomains[0] : undefined;
};
/** Member entity IDs of a group, or undefined if it is not a group. */
export const computeGroupMemberIds = (
stateObj: HassEntity,
entry?: Pick<ExtEntityRegistryEntry, "capabilities"> | null
): string[] | undefined => {
const ids =
entry?.capabilities?.group_entities ??
stateObj.attributes.group_entities ??
stateObj.attributes.entity_id;
return Array.isArray(ids) ? ids : undefined;
};
/**
* 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
* hiding its bulbs doesn't read "All off".
*/
export const filterGroupsWithListedMembers = (
entityIds: string[],
states: HassEntities
): string[] => {
const listed = new Set(entityIds);
const hasListedDescendant = (groupId: string): boolean => {
const seen = new Set([groupId]);
const queue = [groupId];
while (queue.length) {
const stateObj = states[queue.shift()!];
for (const memberId of (stateObj && computeGroupMemberIds(stateObj)) ??
[]) {
if (seen.has(memberId)) {
continue;
}
if (listed.has(memberId)) {
return true;
}
seen.add(memberId);
queue.push(memberId);
}
}
return false;
};
return entityIds.filter((entityId) => {
if (!hasListedDescendant(entityId)) {
return true;
}
// A dropped group no longer counts as listed, so of two groups that
// contain each other one still stays.
listed.delete(entityId);
return false;
});
};
+15
View File
@@ -60,3 +60,18 @@ export const validateHassioSession = async (
): Promise<void> => {
await hass.callWS({ type: "supervisor/ingress/validate_session", session });
};
// Extends the session, or replaces it with a new one for the app if it has
// expired. Returns the session to keep using.
export const refreshHassioSession = async (
hass: Pick<HomeAssistant, "callWS">,
slug: string,
session: string
): Promise<string> => {
try {
await validateHassioSession(hass, session);
return session;
} catch (_err: any) {
return createHassioSession(hass, slug);
}
};
+5 -5
View File
@@ -6,7 +6,7 @@ import type { LocalizeFunc } from "../common/translations/localize";
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
import type { HomeAssistant } from "../types";
import { UNAVAILABLE } from "./entity/entity";
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
export enum LockEntityFeature {
OPEN = 1,
@@ -88,10 +88,10 @@ export const callProtectedLockService = async (
service: ProtectedLockService
) => {
let code: string | undefined;
const lockRegistryEntry = await callWS<ExtEntityRegistryEntry>({
type: "config/entity_registry/get",
entity_id: stateObj.entity_id,
}).catch(() => undefined);
const lockRegistryEntry = await getExtendedEntityRegistryEntry(
callWS,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = lockRegistryEntry?.options?.lock?.default_code;
if (stateObj!.attributes.code_format && !defaultCode) {
+11 -7
View File
@@ -209,7 +209,15 @@ export const watchForNewMatterDevice = (
callback: (device: DeviceRegistryEntry) => void
): UnsubscribeFunc => {
let curMatterDevices: Set<string> | undefined;
const unsubDeviceReg = subscribeDeviceRegistry(hass.connection, (entries) => {
let unsubDeviceReg: UnsubscribeFunc | undefined;
// Callers also unsubscribe after a find. The registry collection counts its
// subscribers, so a second unsubscribe would stop its updates for everyone.
const unsubscribe = () => {
unsubDeviceReg?.();
unsubDeviceReg = undefined;
curMatterDevices = undefined;
};
unsubDeviceReg = subscribeDeviceRegistry(hass.connection, (entries) => {
if (!curMatterDevices) {
curMatterDevices = new Set(
Object.values(entries)
@@ -226,15 +234,11 @@ export const watchForNewMatterDevice = (
!curMatterDevices!.has(device.id)
);
if (newMatterDevices.length) {
unsubDeviceReg();
curMatterDevices = undefined;
unsubscribe();
callback(newMatterDevices[0]);
}
});
return () => {
unsubDeviceReg();
curMatterDevices = undefined;
};
return unsubscribe;
};
export const redirectOnNewMatterDevice = (
+28 -19
View File
@@ -20,7 +20,7 @@ import {
registriesContext,
uiContext,
} from "./context";
import type { HomeAssistant } from "../types";
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
/**
* Reactive controller that keeps `NavigationPathInfo` in sync with a
@@ -45,19 +45,8 @@ export class NavigationPathInfoController extends ContextController {
})
private _panels?: HomeAssistant["panels"];
@consumeContext({
context: registriesContext,
subscribe: true,
transform: ({ areas }) => areas,
})
private _areas?: HomeAssistant["areas"];
@consumeContext({
context: registriesContext,
subscribe: true,
transform: ({ devices }) => devices,
})
private _devices?: HomeAssistant["devices"];
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries | null;
@consumeContext({
context: configContext,
@@ -79,6 +68,8 @@ export class NavigationPathInfoController extends ContextController {
private _path?: string;
private _resolvedInputs?: unknown[];
get info(): NavigationPathInfo {
return this._info;
}
@@ -97,13 +88,31 @@ export class NavigationPathInfoController extends ContextController {
this._unsubscribe();
}
// The resolved info depends on every consumed value, so re-resolve.
protected contextUpdated(): void {
const inputs = this._inputs();
if (
this._resolvedInputs &&
inputs.every((value, i) => value === this._resolvedInputs![i])
) {
return;
}
this._resolve();
}
private _inputs(): unknown[] {
return [
this._localize,
this._panels,
this._registries?.areas,
this._registries?.devices,
this._config,
this._connection,
];
}
private _resolve(): void {
this._unsubscribe();
this._resolvedInputs = this._inputs();
if (!this._path) {
if (this._info !== DEFAULT_NAVIGATION_PATH_INFO) {
@@ -116,8 +125,8 @@ export class NavigationPathInfoController extends ContextController {
if (
!this._localize ||
!this._panels ||
!this._areas ||
!this._devices ||
!this._registries?.areas ||
!this._registries.devices ||
!this._config ||
!this._connection
) {
@@ -128,8 +137,8 @@ export class NavigationPathInfoController extends ContextController {
{
localize: this._localize,
panels: this._panels,
areas: this._areas,
devices: this._devices,
areas: this._registries.areas,
devices: this._registries.devices,
config: this._config,
connection: this._connection,
},
+2 -2
View File
@@ -20,10 +20,10 @@ export interface SensorDeviceClassUnits {
}
export const getSensorDeviceClassConvertibleUnits = (
hass: HomeAssistant,
callWS: HomeAssistant["callWS"],
deviceClass: string
): Promise<SensorDeviceClassUnits> =>
hass.callWS({
callWS({
type: "sensor/device_class_convertible_units",
device_class: deviceClass,
});
+1 -1
View File
@@ -101,7 +101,7 @@ export const updateItem = (
"update_item",
{
item: item.uid,
rename: item.summary,
rename: item.summary || undefined,
status: item.status,
description: item.description,
due_datetime: item.due?.includes("T") ? item.due : undefined,
+13 -7
View File
@@ -364,19 +364,25 @@ const getWeatherExtrema = (
if (new Date(fc.datetime).getDate() !== today) {
break;
}
if (!tempHigh || fc.temperature > tempHigh) {
if (fc.temperature == null) {
continue;
}
if (tempHigh === undefined || fc.temperature > tempHigh) {
tempHigh =
temperatureFractionDigits === undefined
? fc.temperature
: round(fc.temperature, temperatureFractionDigits);
}
if (fc.templow !== undefined && (!tempLow || fc.templow < tempLow)) {
if (fc.templow != null && (tempLow === undefined || fc.templow < tempLow)) {
tempLow =
temperatureFractionDigits === undefined
? fc.templow
: round(fc.templow, temperatureFractionDigits);
}
if (!fc.templow && (!tempLow || fc.temperature < tempLow)) {
if (
fc.templow == null &&
(tempLow === undefined || fc.temperature < tempLow)
) {
tempLow =
temperatureFractionDigits === undefined
? fc.temperature
@@ -384,19 +390,19 @@ const getWeatherExtrema = (
}
}
if (!tempLow && !tempHigh) {
if (tempLow === undefined && tempHigh === undefined) {
return undefined;
}
return html`
${
tempHigh
tempHigh !== undefined
? formatEntityAttributeValue(stateObj, "temperature", tempHigh)
: ""
}
${tempLow && tempHigh ? " / " : ""}
${tempLow !== undefined && tempHigh !== undefined ? " / " : ""}
${
tempLow
tempLow !== undefined
? formatEntityAttributeValue(stateObj, "temperature", tempLow)
: ""
}
@@ -19,7 +19,7 @@ export const fetchEntityConfigFlow = async (
if (!entities || !(entityId in entities)) {
return undefined;
}
const regEntry = await getExtendedEntityRegistryEntry(api, entityId);
const regEntry = await getExtendedEntityRegistryEntry(api.callWS, entityId);
if (!regEntry.config_entry_id) {
return undefined;
}
@@ -26,7 +26,7 @@ export const showConfigFlowDialog = (
showDevices: true,
createFlow: async (hass, handler) => {
const [step] = await Promise.all([
createConfigFlow(hass, handler, dialogParams.entryId),
createConfigFlow(hass.callApi, handler, dialogParams.entryId),
hass.loadFragmentTranslation("config"),
hass.loadBackendTranslation("config", handler),
hass.loadBackendTranslation("selector", handler),
@@ -51,7 +51,7 @@ export const showConfigFlowDialog = (
return step;
},
handleFlowStep: async (hass, flowId, data) => {
const step = await handleConfigFlowStep(hass, flowId, data);
const step = await handleConfigFlowStep(hass.callApi, flowId, data);
await loadFlowStepTranslations(hass, step);
return step;
},
@@ -1,12 +1,21 @@
import type { ContextType } from "@lit/context";
import Cropper from "cropperjs";
// @ts-ignore
import cropperCss from "cropperjs/dist/cropper.css";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing, unsafeCSS } from "lit";
import "cropperjs";
import type {
CropperCanvas,
CropperGrid,
CropperHandle,
CropperImage,
CropperSelection,
CropperShade,
} from "cropperjs";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import "../../components/ha-alert";
import "../../components/ha-button";
import "../../components/ha-dialog-footer";
import "../../components/ha-dialog";
@@ -16,76 +25,314 @@ import { haStyleDialog } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
import type { HaImageCropperDialogParams } from "./show-image-cropper-dialog";
interface Rect {
x: number;
y: number;
width: number;
height: number;
}
const MIN_SELECTION_SIZE = 50;
const INITIAL_COVERAGE = 0.8;
const EPSILON = 0.05;
const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
const contains = (outer: Rect, inner: Rect): boolean =>
inner.x >= outer.x - EPSILON &&
inner.y >= outer.y - EPSILON &&
inner.x + inner.width <= outer.x + outer.width + EPSILON &&
inner.y + inner.height <= outer.y + outer.height + EPSILON;
const intersect = (a: Rect, b: Rect): Rect => {
const x = Math.max(a.x, b.x);
const y = Math.max(a.y, b.y);
return {
x,
y,
width: Math.min(a.x + a.width, b.x + b.width) - x,
height: Math.min(a.y + a.height, b.y + b.height) - y,
};
};
const sameSize = (a: Rect, b: Rect): boolean =>
Math.abs(a.width - b.width) < EPSILON &&
Math.abs(a.height - b.height) < EPSILON;
const moveInto = (rect: Rect, bounds: Rect): Rect => ({
...rect,
x: clamp(rect.x, bounds.x, bounds.x + bounds.width - rect.width),
y: clamp(rect.y, bounds.y, bounds.y + bounds.height - rect.height),
});
const anchorOf = (
start: number,
size: number,
nextStart: number,
nextSize: number
): number => {
if (Math.abs(nextStart - start) < EPSILON) {
return nextStart;
}
if (Math.abs(nextStart + nextSize - (start + size)) < EPSILON) {
return start + size;
}
return nextStart + nextSize / 2;
};
const shrinkInto = (current: Rect, next: Rect, bounds: Rect): Rect => {
const ax = anchorOf(current.x, current.width, next.x, next.width);
const ay = anchorOf(current.y, current.height, next.y, next.height);
let scale = 1;
if (next.x < bounds.x) {
scale = Math.min(scale, (ax - bounds.x) / (ax - next.x));
}
if (next.x + next.width > bounds.x + bounds.width) {
scale = Math.min(
scale,
(bounds.x + bounds.width - ax) / (next.x + next.width - ax)
);
}
if (next.y < bounds.y) {
scale = Math.min(scale, (ay - bounds.y) / (ay - next.y));
}
if (next.y + next.height > bounds.y + bounds.height) {
scale = Math.min(
scale,
(bounds.y + bounds.height - ay) / (next.y + next.height - ay)
);
}
return {
x: ax + (next.x - ax) * scale,
y: ay + (next.y - ay) * scale,
width: next.width * scale,
height: next.height * scale,
};
};
const scaleRect = ({ x, y, width, height }: Rect, ratio: number): Rect => ({
x: x * ratio,
y: y * ratio,
width: width * ratio,
height: height * ratio,
});
@customElement("image-cropper-dialog")
export class HaImagecropperDialog extends DirtyStateProviderMixin<Cropper.Data>()(
export class HaImagecropperDialog extends DirtyStateProviderMixin<Rect>()(
DialogMixin<HaImageCropperDialogParams>(LitElement)
) {
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@query("img") private _image!: HTMLImageElement;
@query("cropper-image") private _image?: CropperImage;
private _cropper?: Cropper;
@query("cropper-selection") private _selection?: CropperSelection;
@state() private _imageSize?: { width: number; height: number };
@state() private _shown = false;
@state() private _cropReady = false;
@state() private _loadError = false;
@state() private _isTargetAspectRatio?: boolean;
private _imageUrl?: string;
private _resizeObserver?: ResizeObserver;
private _canvasWidth?: number;
private _refitting = false;
private _cropped = false;
private _closing = false;
private _shiftLocked = false;
public disconnectedCallback(): void {
super.disconnectedCallback();
if (!this._cropped) {
this.params?.cancelCallback?.();
}
this._cropper?.destroy();
this._cropper = undefined;
if (this._imageUrl) {
URL.revokeObjectURL(this._imageUrl);
this._imageUrl = undefined;
}
this._resizeObserver?.disconnect();
this._resizeObserver = undefined;
}
protected firstUpdated() {
if (!this.params) {
return;
}
this._image.src = URL.createObjectURL(this.params.file);
this._cropper = new Cropper(this._image, {
aspectRatio: this.params.options.aspectRatio,
viewMode: 1,
dragMode: "move",
minCropBoxWidth: 50,
ready: () => {
this._isTargetAspectRatio = this._checkMatchAspectRatio();
URL.revokeObjectURL(this._image!.src);
this._initDirtyTracking({ type: "deep" }, this._cropper!.getData());
this._cropReady = true;
},
crop: () => {
if (this._cropReady) {
this._updateDirtyState(this._cropper!.getData());
}
},
});
this._imageUrl = URL.createObjectURL(this.params.file);
this._loadImageSize(this._imageUrl);
}
private _checkMatchAspectRatio(): boolean {
private async _loadImageSize(url: string) {
const image = new Image();
image.src = url;
try {
await image.decode();
} catch {
this._loadError = true;
return;
}
if (!this.isConnected) {
return;
}
this._imageSize = {
width: image.naturalWidth,
height: image.naturalHeight,
};
this._isTargetAspectRatio = this._checkMatchAspectRatio(
image.naturalWidth,
image.naturalHeight
);
}
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
if (
!this._cropReady &&
(changedProps.has("_imageSize") || changedProps.has("_shown")) &&
this._image
) {
this._initCropper(this._image);
}
}
private async _initCropper(image: CropperImage) {
try {
await image.$ready();
} catch {
this._loadError = true;
return;
}
if (!this.isConnected || image !== this._image) {
return;
}
const selection = this._selection!;
if (!selection.width) {
await new Promise<void>((resolve) => {
selection.addEventListener("change", () => resolve(), { once: true });
});
if (!this.isConnected || image !== this._image) {
return;
}
}
this._initDirtyTracking(
{ type: "deep" },
this._cropData(this._selectionRect(), this._imageRect())
);
this._cropReady = true;
this._resizeObserver = new ResizeObserver((entries) => {
this._refit(entries[0].contentRect);
});
this._resizeObserver.observe(image.parentElement!);
}
private _selectionRect(): Rect {
const { x, y, width, height } = this._selection!;
return { x, y, width, height };
}
private _canvasRect(): Rect {
const { width, height } =
this._image!.parentElement!.getBoundingClientRect();
return { x: 0, y: 0, width, height };
}
private _imageRect(): Rect {
const canvasRect = this._image!.parentElement!.getBoundingClientRect();
const imageRect = this._image!.getBoundingClientRect();
return {
x: imageRect.x - canvasRect.x,
y: imageRect.y - canvasRect.y,
width: imageRect.width,
height: imageRect.height,
};
}
private _cropData(selection: Rect, image: Rect): Rect {
const scale = image.width / this._imageSize!.width;
return {
x: Math.round((selection.x - image.x) / scale),
y: Math.round((selection.y - image.y) / scale),
width: Math.round(selection.width / scale),
height: Math.round(selection.height / scale),
};
}
private _refit(canvas: { width: number; height: number }) {
const previous = this._canvasWidth;
this._canvasWidth = canvas.width;
if (!previous || !canvas.width || previous === canvas.width) {
return;
}
const current = this._selectionRect();
const ratio = Math.min(
canvas.width / previous,
canvas.height / current.height
);
const image = scaleRect(this._imageRect(), ratio);
const selection = scaleRect(current, ratio);
const dy =
image.height <= canvas.height
? (canvas.height - image.height) / 2 - image.y
: clamp(
0,
-selection.y,
canvas.height - selection.y - selection.height
);
image.y += dy;
selection.y += dy;
const { width, height } = this._imageSize!;
this._refitting = true;
this._image!.$setTransform(
image.width / width,
0,
0,
image.height / height,
image.x + image.width / 2 - width / 2,
image.y + image.height / 2 - height / 2
);
this._selection!.$change(
selection.x,
selection.y,
selection.width,
selection.height
);
this._refitting = false;
}
private _checkMatchAspectRatio(
naturalWidth: number,
naturalHeight: number
): boolean {
const targetRatio = this.params?.options.aspectRatio;
if (!targetRatio) {
return true;
}
const imageData = this._cropper!.getImageData();
if (imageData.aspectRatio === targetRatio) {
if (naturalWidth / naturalHeight === targetRatio) {
return true;
}
// If the image is not exactly the aspect ratio see if it is within a pixel.
if (imageData.naturalWidth > imageData.naturalHeight) {
const targetHeight = imageData.naturalWidth / targetRatio;
return Math.abs(targetHeight - imageData.naturalHeight) <= 1;
if (naturalWidth > naturalHeight) {
const targetHeight = naturalWidth / targetRatio;
return Math.abs(targetHeight - naturalHeight) <= 1;
}
const targetWidth = imageData.naturalHeight * targetRatio;
return Math.abs(targetWidth - imageData.naturalWidth) <= 1;
const targetWidth = naturalHeight * targetRatio;
return Math.abs(targetWidth - naturalWidth) <= 1;
}
protected render(): TemplateResult | typeof nothing {
@@ -93,23 +340,74 @@ export class HaImagecropperDialog extends DirtyStateProviderMixin<Cropper.Data>(
return nothing;
}
const label = this._i18n.localize("ui.dialogs.image_cropper.crop_image");
return html`
<ha-dialog
open
header-title=${this._i18n.localize(
"ui.dialogs.image_cropper.crop_image"
)}
header-title=${label}
.preventScrimClose=${this.isDirtyState}
@wa-hide=${this._handleHide}
@after-show=${this._handleAfterShow}
>
<div
class="container ${classMap({
round: Boolean(this.params.options.round),
})}"
>
<img
alt=${this._i18n.localize("ui.dialogs.image_cropper.crop_image")}
/>
${
this._loadError
? html`<ha-alert alert-type="error">
${this._i18n.localize("ui.dialogs.image_cropper.load_error")}
</ha-alert>`
: this._imageSize && this._shown
? html`
<cropper-canvas
background
@actionmove=${this._handleCanvasActionMove}
style=${styleMap({
aspectRatio: `${this._imageSize.width} / ${this._imageSize.height}`,
})}
>
<cropper-image
src=${this._imageUrl!}
alt=${label}
scalable
translatable
@change=${this._handleImageChange}
></cropper-image>
<cropper-shade hidden></cropper-shade>
<cropper-handle action="move" plain></cropper-handle>
<cropper-selection
aspect-ratio=${ifDefined(
this.params.options.aspectRatio || undefined
)}
initial-coverage=${INITIAL_COVERAGE}
precise
movable
resizable
outlined
@change=${this._handleSelectionChange}
>
<cropper-grid
role="grid"
bordered
covered
></cropper-grid>
<cropper-handle action="move" plain></cropper-handle>
<cropper-handle action="n-resize"></cropper-handle>
<cropper-handle action="e-resize"></cropper-handle>
<cropper-handle action="s-resize"></cropper-handle>
<cropper-handle action="w-resize"></cropper-handle>
<cropper-handle action="ne-resize"></cropper-handle>
<cropper-handle action="nw-resize"></cropper-handle>
<cropper-handle action="se-resize"></cropper-handle>
<cropper-handle action="sw-resize"></cropper-handle>
</cropper-selection>
</cropper-canvas>
`
: nothing
}
</div>
<ha-dialog-footer slot="footer">
<ha-button
@@ -127,9 +425,7 @@ export class HaImagecropperDialog extends DirtyStateProviderMixin<Cropper.Data>(
appearance="plain"
@click=${this._useOriginal}
>
${this._i18n.localize(
"ui.dialogs.image_cropper.use_original"
)}
${this._i18n.localize("ui.dialogs.image_cropper.use_original")}
</ha-button>
`
: nothing
@@ -146,17 +442,99 @@ export class HaImagecropperDialog extends DirtyStateProviderMixin<Cropper.Data>(
`;
}
private _handleAfterShow() {
this._shown = true;
}
private _handleHide(ev: Event) {
// Ignore hide events from nested overlays and blocked dismissals.
if (ev.eventPhase !== Event.AT_TARGET || ev.defaultPrevented) {
return;
}
this._closing = true;
}
private _cropImage() {
const canvas = this._cropper?.getCroppedCanvas();
if (!canvas) {
private _handleCanvasActionMove(
ev: CustomEvent<{ relatedEvent?: PointerEvent }>
) {
this._shiftLocked = ev.detail.relatedEvent?.shiftKey ?? false;
}
private _handleSelectionChange(ev: CustomEvent<Rect>) {
if (!this._cropReady || this._refitting) {
return;
}
const selection = this._selectionRect();
const image = this._imageRect();
const bounds = intersect(image, this._canvasRect());
const next = ev.detail;
if (next.width < MIN_SELECTION_SIZE && next.width < selection.width) {
ev.preventDefault();
return;
}
if (!contains(bounds, next)) {
ev.preventDefault();
const fitted = sameSize(next, selection)
? moveInto(next, bounds)
: this.params?.options.aspectRatio || this._shiftLocked
? shrinkInto(selection, next, bounds)
: intersect(next, bounds);
this._selection!.$change(fitted.x, fitted.y, fitted.width, fitted.height);
return;
}
this._updateDirtyState(this._cropData(next, image));
}
private _handleImageChange(ev: CustomEvent<Rect>) {
if (!this._cropReady || this._refitting) {
return;
}
const selection = this._selectionRect();
const next = ev.detail;
if (!contains(next, selection)) {
ev.preventDefault();
const current = this._imageRect();
if (sameSize(next, current)) {
const x = clamp(
next.x,
selection.x + selection.width - next.width,
selection.x
);
const y = clamp(
next.y,
selection.y + selection.height - next.height,
selection.y
);
if (x !== current.x || y !== current.y) {
this._image!.$move(x - current.x, y - current.y);
}
}
return;
}
this._updateDirtyState(this._cropData(selection, next));
}
private async _cropImage() {
const selection = this._selection;
if (!selection || !this._cropReady) {
return;
}
const image = this._imageRect();
const rect = this._selectionRect();
const x = clamp(rect.x, image.x, image.x + image.width - rect.width);
const y = clamp(rect.y, image.y, image.y + image.height - rect.height);
if (x !== rect.x || y !== rect.y) {
selection.$change(x, y);
}
const crop = this._cropData(this._selectionRect(), image);
let canvas: HTMLCanvasElement;
try {
canvas = await selection.$toCanvas({
width: crop.width,
beforeDraw: (_context, target) => {
target.height = crop.height;
},
});
} catch {
return;
}
const params = this.params!;
@@ -188,22 +566,22 @@ export class HaImagecropperDialog extends DirtyStateProviderMixin<Cropper.Data>(
return [
haStyleDialog,
css`
${unsafeCSS(cropperCss)}
.container {
max-width: 640px;
}
img {
max-width: 100%;
cropper-canvas {
width: 100%;
direction: ltr;
--theme-color: var(--primary-color);
}
.container.round .cropper-view-box,
.container.round .cropper-face {
cropper-handle {
--theme-color: var(--primary-color);
}
.container.round cropper-selection,
.container.round cropper-shade,
.container.round cropper-grid {
border-radius: var(--ha-picture-border-radius);
}
.cropper-line,
.cropper-point,
.cropper-point.point-se::before {
background-color: var(--primary-color);
}
`,
];
}
@@ -212,5 +590,11 @@ export class HaImagecropperDialog extends DirtyStateProviderMixin<Cropper.Data>(
declare global {
interface HTMLElementTagNameMap {
"image-cropper-dialog": HaImagecropperDialog;
"cropper-canvas": CropperCanvas;
"cropper-image": CropperImage;
"cropper-shade": CropperShade;
"cropper-handle": CropperHandle;
"cropper-selection": CropperSelection;
"cropper-grid": CropperGrid;
}
}
@@ -0,0 +1,168 @@
import { mdiArrowBottomLeft, mdiArrowTopRight, mdiStop } from "@mdi/js";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { fireEvent } from "../../../../common/dom/fire_event";
import {
computeCloseIcon,
computeOpenIcon,
} from "../../../../common/entity/cover_icon";
import { supportsFeature } from "../../../../common/entity/supports-feature";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../../common/translations/localize";
import "../../../../components/ha-control-button";
import "../../../../components/ha-svg-icon";
import type {
CoverAction,
CoverControlMode,
CoverEntity,
} from "../../../../data/cover";
import {
CoverEntityFeature,
canClose,
canCloseTilt,
canOpen,
canOpenTilt,
canStop,
canStopTilt,
} from "../../../../data/cover";
interface CoverButton {
action: CoverAction;
feature: CoverEntityFeature;
icon: (stateObj: CoverEntity) => string;
label: LocalizeKeys;
enabled: (stateObj: CoverEntity) => boolean;
}
const BUTTONS: Record<CoverControlMode, CoverButton[]> = {
position: [
{
action: "open",
feature: CoverEntityFeature.OPEN,
icon: computeOpenIcon,
label: "ui.card.cover.open_cover",
enabled: canOpen,
},
{
action: "stop",
feature: CoverEntityFeature.STOP,
icon: () => mdiStop,
label: "ui.card.cover.stop_cover",
enabled: canStop,
},
{
action: "close",
feature: CoverEntityFeature.CLOSE,
icon: computeCloseIcon,
label: "ui.card.cover.close_cover",
enabled: canClose,
},
],
tilt: [
{
action: "open",
feature: CoverEntityFeature.OPEN_TILT,
icon: () => mdiArrowTopRight,
label: "ui.card.cover.open_tilt_cover",
enabled: canOpenTilt,
},
{
action: "stop",
feature: CoverEntityFeature.STOP_TILT,
icon: () => mdiStop,
label: "ui.card.cover.stop_cover",
enabled: canStopTilt,
},
{
action: "close",
feature: CoverEntityFeature.CLOSE_TILT,
icon: () => mdiArrowBottomLeft,
label: "ui.card.cover.close_tilt_cover",
enabled: canCloseTilt,
},
],
};
@customElement("ha-more-info-cover-buttons")
export class HaMoreInfoCoverButtons extends LitElement {
@property({ attribute: false }) public stateObj!: CoverEntity;
@property({ attribute: false }) public mode: CoverControlMode = "position";
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
private _handleClick(ev: Event) {
const action = (ev.currentTarget as HTMLElement).dataset
.action as CoverAction;
fireEvent(this, "cover-command", { mode: this.mode, action });
}
protected render() {
if (!this.stateObj) {
return nothing;
}
const stateObj = this.stateObj;
const buttons = BUTTONS[this.mode].filter((button) =>
supportsFeature(stateObj, button.feature)
);
if (!buttons.length) {
return nothing;
}
return html`
${buttons.map(
(button) => html`
<ha-control-button
.label=${this._localize(button.label)}
.disabled=${!button.enabled(stateObj)}
data-action=${button.action}
@click=${this._handleClick}
>
<div class="content">
<ha-svg-icon .path=${button.icon(stateObj)}></ha-svg-icon>
<span>
${this._localize(
`ui.dialogs.more_info_control.cover.${button.action}`
)}
</span>
</div>
</ha-control-button>
`
)}
`;
}
static styles = css`
:host {
display: flex;
justify-content: center;
gap: var(--ha-space-3);
width: 100%;
}
ha-control-button {
flex: 1;
max-width: 104px;
height: 64px;
--control-button-border-radius: var(--ha-border-radius-xl);
--mdc-icon-size: 22px;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--ha-space-1);
font-size: var(--ha-font-size-s);
font-weight: var(--ha-font-weight-medium);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-more-info-cover-buttons": HaMoreInfoCoverButtons;
}
}
@@ -8,14 +8,14 @@ import { consumeLocalize } from "../../../../common/decorators/consume-context-e
import { transform } from "../../../../common/decorators/transform";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { clamp } from "../../../../common/number/clamp";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-control-button";
import { apiContext, configContext } from "../../../../data/context";
import type { CoverEntity } from "../../../../data/cover";
import type { CoverControlMode, CoverEntity } from "../../../../data/cover";
import {
DEFAULT_COVER_FAVORITE_POSITIONS,
coverSupportsPosition,
coverSupportsTiltPosition,
coverCurrentValue,
} from "../../../../data/cover";
import { normalizeFavoritePositions } from "../../../../data/favorite_positions";
import { UNAVAILABLE } from "../../../../data/entity/entity";
@@ -37,8 +37,6 @@ import {
import "../ha-more-info-favorites";
import type { HaMoreInfoFavorites } from "../ha-more-info-favorites";
type FavoriteKind = "position" | "tilt";
type FavoriteLocalizeKey =
| "set"
| "edit"
@@ -50,8 +48,10 @@ type FavoriteLocalizeKey =
| "edit_title"
| "add_title";
const favoriteKindFromEvent = (ev: Event): FavoriteKind =>
(ev.currentTarget as HTMLElement).dataset.kind as FavoriteKind;
const OPTION_KEYS = {
position: "favorite_positions",
tilt: "favorite_tilt_positions",
} as const satisfies Record<CoverControlMode, keyof CoverEntityOptions>;
@customElement("ha-more-info-cover-favorite-positions")
export class HaMoreInfoCoverFavoritePositions extends LitElement {
@@ -76,145 +76,70 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
@property({ attribute: false }) public editMode?: boolean;
@state() private _favoritePositions: number[] = [];
@property({ attribute: false }) public mode: CoverControlMode = "position";
@state() private _favoriteTiltPositions: number[] = [];
@state() private _favorites: number[] = [];
protected updated(changedProps: PropertyValues<this>): void {
if (
(changedProps.has("entry") || changedProps.has("stateObj")) &&
this.entry &&
this.stateObj
) {
const options = this.entry.options?.cover;
this._favoritePositions = coverSupportsPosition(this.stateObj)
? normalizeFavoritePositions(
options?.favorite_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
)
: [];
this._favoriteTiltPositions = coverSupportsTiltPosition(this.stateObj)
? normalizeFavoritePositions(
options?.favorite_tilt_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
)
: [];
protected willUpdate(changedProps: PropertyValues<this>): void {
if (changedProps.has("entry") || changedProps.has("mode")) {
this._favorites = normalizeFavoritePositions(
this.entry?.options?.cover?.[OPTION_KEYS[this.mode]] ??
DEFAULT_COVER_FAVORITE_POSITIONS
);
}
}
private _localizeFavorite(
kind: FavoriteKind,
key: FavoriteLocalizeKey,
values?: Record<string, string | number>
): string {
return this._localize(
`ui.dialogs.more_info_control.cover.${kind === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
`ui.dialogs.more_info_control.cover.${this.mode === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
values
);
}
private _getFavorites(kind: FavoriteKind): number[] {
return kind === "position"
? this._favoritePositions
: this._favoriteTiltPositions;
}
private _getCurrentValue(kind: FavoriteKind): number | undefined {
const current =
kind === "position"
? this.stateObj.attributes.current_position
: this.stateObj.attributes.current_tilt_position;
return current == null ? undefined : current;
}
private async _save(options: CoverEntityOptions): Promise<void> {
private async _setFavorites(favorites: number[]): Promise<void> {
if (!this.entry) {
return;
}
const currentOptions: CoverEntityOptions = {
...(this.entry.options?.cover ?? {}),
};
if (coverSupportsPosition(this.stateObj)) {
currentOptions.favorite_positions = this._favoritePositions;
}
if (coverSupportsTiltPosition(this.stateObj)) {
currentOptions.favorite_tilt_positions = this._favoriteTiltPositions;
}
const normalized = normalizeFavoritePositions(favorites);
this._favorites = normalized;
const result = await updateEntityRegistryEntry(
this._api.callWS,
this.entry.entity_id,
{
options_domain: "cover",
options: {
...currentOptions,
...options,
...this.entry.options?.cover,
[OPTION_KEYS[this.mode]]: normalized,
},
}
);
fireEvent(this, "entity-entry-updated", result.entity_entry);
}
private async _setFavorites(
kind: FavoriteKind,
favorites: number[]
): Promise<void> {
const normalized = normalizeFavoritePositions(favorites);
if (kind === "position") {
this._favoritePositions = normalized;
await this._save({ favorite_positions: normalized });
return;
}
this._favoriteTiltPositions = normalized;
await this._save({ favorite_tilt_positions: normalized });
}
private _move(kind: FavoriteKind, index: number, newIndex: number): void {
const favorites = this._getFavorites(kind).concat();
const moved = favorites.splice(index, 1)[0];
favorites.splice(newIndex, 0, moved);
this._setFavorites(kind, favorites);
}
private _applyFavorite(kind: FavoriteKind, index: number): void {
const favorite = this._getFavorites(kind)[index];
private _applyFavorite(index: number): void {
const favorite = this._favorites[index];
if (favorite === undefined) {
return;
}
if (kind === "position") {
this._api.callService("cover", "set_cover_position", {
entity_id: this.stateObj.entity_id,
position: favorite,
});
return;
}
this._api.callService("cover", "set_cover_tilt_position", {
entity_id: this.stateObj.entity_id,
tilt_position: favorite,
fireEvent(this, "cover-command", {
mode: this.mode,
action: "set",
value: favorite,
});
}
private async _promptFavoriteValue(
kind: FavoriteKind,
value?: number
): Promise<number | undefined> {
const response = await showPromptDialog(this, {
title: this._localizeFavorite(
kind,
value === undefined ? "add_title" : "edit_title"
),
inputLabel: this._localize(
kind === "position"
this.mode === "position"
? "ui.card.cover.position"
: "ui.card.cover.tilt_position"
),
@@ -235,76 +160,56 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
return undefined;
}
return Math.max(0, Math.min(100, number));
return clamp(number, 0, 100);
}
private async _addFavorite(kind: FavoriteKind): Promise<void> {
const value = await this._promptFavoriteValue(kind);
private async _addFavorite(): Promise<void> {
const value = await this._promptFavoriteValue();
if (value === undefined) {
return;
}
await this._setFavorites(kind, [...this._getFavorites(kind), value]);
await this._setFavorites([...this._favorites, value]);
}
private async _editFavorite(
kind: FavoriteKind,
index: number
): Promise<void> {
const favorites = this._getFavorites(kind);
const current = favorites[index];
private async _editFavorite(index: number): Promise<void> {
const current = this._favorites[index];
if (current === undefined) {
return;
}
const value = await this._promptFavoriteValue(kind, current);
const value = await this._promptFavoriteValue(current);
if (value === undefined) {
return;
}
const updated = [...favorites];
const updated = [...this._favorites];
updated[index] = value;
await this._setFavorites(kind, updated);
await this._setFavorites(updated);
}
private async _deleteFavorite(
kind: FavoriteKind,
index: number
): Promise<void> {
private async _deleteFavorite(index: number): Promise<void> {
const confirmed = await showConfirmationDialog(this, {
destructive: true,
title: this._localizeFavorite(kind, "delete_confirm_title"),
text: this._localizeFavorite(kind, "delete_confirm_text"),
confirmText: this._localizeFavorite(kind, "delete_confirm_action"),
title: this._localizeFavorite("delete_confirm_title"),
text: this._localizeFavorite("delete_confirm_text"),
confirmText: this._localizeFavorite("delete_confirm_action"),
});
if (!confirmed) {
return;
}
await this._setFavorites(
kind,
this._getFavorites(kind).filter((_, itemIndex) => itemIndex !== index)
this._favorites.filter((_, itemIndex) => itemIndex !== index)
);
}
private _renderFavoriteButton =
(kind: FavoriteKind): HaMoreInfoFavorites["renderItem"] =>
(favorite, _index, editMode) => {
const currentValue = this._getCurrentValue(kind);
const active = currentValue === favorite;
const label = this._localizeFavorite(kind, editMode ? "edit" : "set", {
private _favoriteButtonRenderer(): HaMoreInfoFavorites["renderItem"] {
return (favorite, _index, editMode) => {
const active = coverCurrentValue(this.stateObj, this.mode) === favorite;
const label = this._localizeFavorite(editMode ? "edit" : "set", {
value: `${favorite as number}%`,
});
return html`
<ha-control-button
class=${classMap({
active,
})}
class=${classMap({ active })}
style=${styleMap({
"--control-button-border-radius": "var(--ha-border-radius-pill)",
width: "72px",
@@ -317,20 +222,15 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
</ha-control-button>
`;
};
}
private _deleteLabel =
(kind: FavoriteKind): HaMoreInfoFavorites["deleteLabel"] =>
(index) =>
this._localizeFavorite(kind, "delete", {
number: index + 1,
});
private _deleteLabel: HaMoreInfoFavorites["deleteLabel"] = (index) =>
this._localizeFavorite("delete", { number: index + 1 });
private _handleFavoriteAction = (
private _handleFavoriteAction(
ev: HASSDomEvent<HASSDomEvents["favorite-item-action"]>
): void => {
): void {
ev.stopPropagation();
const kind = favoriteKindFromEvent(ev);
const { action, index } = ev.detail;
if (action === "hold" && this._user?.is_admin) {
@@ -339,158 +239,87 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
}
if (this.editMode) {
this._editFavorite(kind, index);
this._editFavorite(index);
return;
}
this._applyFavorite(kind, index);
};
this._applyFavorite(index);
}
private _handleFavoriteMoved = (
private _handleFavoriteMoved(
ev: HASSDomEvent<HASSDomEvents["favorite-item-moved"]>
): void => {
): void {
ev.stopPropagation();
const kind = favoriteKindFromEvent(ev);
this._move(kind, ev.detail.oldIndex, ev.detail.newIndex);
};
const favorites = [...this._favorites];
const [moved] = favorites.splice(ev.detail.oldIndex, 1);
favorites.splice(ev.detail.newIndex, 0, moved);
this._setFavorites(favorites);
}
private _handleFavoriteDelete = (
private _handleFavoriteDelete(
ev: HASSDomEvent<HASSDomEvents["favorite-item-delete"]>
): void => {
): void {
ev.stopPropagation();
const kind = favoriteKindFromEvent(ev);
this._deleteFavorite(kind, ev.detail.index);
};
this._deleteFavorite(ev.detail.index);
}
private _handleFavoriteAdd = (
private _handleFavoriteAdd(
ev: HASSDomEvent<HASSDomEvents["favorite-item-add"]>
): void => {
): void {
ev.stopPropagation();
const kind = favoriteKindFromEvent(ev);
this._addFavorite(kind);
};
this._addFavorite();
}
private _handleFavoriteDone = (
private _handleFavoriteDone(
ev: HASSDomEvent<HASSDomEvents["favorite-item-done"]>
): void => {
): void {
ev.stopPropagation();
fireEvent(this, "toggle-edit-mode", false);
};
private _renderKindSection(
kind: FavoriteKind,
label: string,
favorites: number[],
showDone: boolean,
showLabel: boolean
): TemplateResult | typeof nothing {
if (!this.editMode && favorites.length === 0) {
return nothing;
}
return html`
<section class="group">
${showLabel ? html`<h4>${label}</h4>` : nothing}
<ha-more-info-favorites
data-kind=${kind}
.items=${favorites}
.renderItem=${this._renderFavoriteButton(kind)}
.deleteLabel=${this._deleteLabel(kind)}
.editMode=${this.editMode ?? false}
.disabled=${this.stateObj.state === UNAVAILABLE}
.isAdmin=${Boolean(this._user?.is_admin)}
.showDone=${showDone}
.addLabel=${this._localizeFavorite(kind, "add")}
.doneLabel=${this._localize(
"ui.dialogs.more_info_control.exit_edit_mode"
)}
@favorite-item-action=${this._handleFavoriteAction}
@favorite-item-moved=${this._handleFavoriteMoved}
@favorite-item-delete=${this._handleFavoriteDelete}
@favorite-item-add=${this._handleFavoriteAdd}
@favorite-item-done=${this._handleFavoriteDone}
></ha-more-info-favorites>
</section>
`;
}
protected render(): TemplateResult | typeof nothing {
if (!this.stateObj || !this.entry) {
return nothing;
}
const supportsPosition = coverSupportsPosition(this.stateObj);
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
const showPositionSection = supportsPosition
? this.editMode || this._favoritePositions.length > 0
: false;
const showTiltSection = supportsTiltPosition
? this.editMode || this._favoriteTiltPositions.length > 0
: false;
const showLabels =
[showPositionSection, showTiltSection].filter(Boolean).length > 1;
const showDoneOnPosition = supportsPosition && !supportsTiltPosition;
if (!this.editMode && this._favorites.length === 0) {
return nothing;
}
return html`
<div class="groups">
${
supportsPosition
? this._renderKindSection(
"position",
this._localize("ui.card.cover.position"),
this._favoritePositions,
showDoneOnPosition,
showLabels
)
: nothing
}
${
supportsTiltPosition
? this._renderKindSection(
"tilt",
this._localize("ui.card.cover.tilt_position"),
this._favoriteTiltPositions,
true,
showLabels
)
: nothing
}
</div>
<ha-more-info-favorites
.items=${this._favorites}
.renderItem=${this._favoriteButtonRenderer()}
.deleteLabel=${this._deleteLabel}
.editMode=${this.editMode ?? false}
.disabled=${this.stateObj.state === UNAVAILABLE}
.isAdmin=${Boolean(this._user?.is_admin)}
.showDone=${true}
.addLabel=${this._localizeFavorite("add")}
.doneLabel=${this._localize(
"ui.dialogs.more_info_control.exit_edit_mode"
)}
@favorite-item-action=${this._handleFavoriteAction}
@favorite-item-moved=${this._handleFavoriteMoved}
@favorite-item-delete=${this._handleFavoriteDelete}
@favorite-item-add=${this._handleFavoriteAdd}
@favorite-item-done=${this._handleFavoriteDone}
></ha-more-info-favorites>
`;
}
static styles = css`
:host {
display: block;
display: flex;
justify-content: center;
width: 100%;
}
.groups {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--ha-space-3);
}
.group {
ha-more-info-favorites {
width: 100%;
max-width: 384px;
margin: 0;
}
.group ha-more-info-favorites {
--favorite-items-max-width: 384px;
--favorite-item-active-background-color: var(--state-cover-active-color);
}
h4 {
margin: 0 0 var(--ha-space-2);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
font-weight: var(--ha-font-weight-medium);
text-align: center;
}
`;
}
@@ -167,16 +167,12 @@ export class HaMoreInfoFavorites extends LitElement {
display: flex;
align-items: center;
justify-content: center;
margin: calc(var(--ha-space-2) * -1);
gap: var(--ha-space-4);
flex-wrap: wrap;
max-width: var(--favorite-items-max-width, 250px);
user-select: none;
}
.container > * {
margin: var(--ha-space-2);
}
.favorite {
display: block;
}
@@ -1,6 +1,7 @@
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { consume } from "../../../common/decorators/consume";
import "../../../components/ha-absolute-time";
import "../../../components/ha-relative-time";
@@ -19,6 +20,10 @@ export class HaMoreInfoStateHeader extends LitElement {
@property({ attribute: false }) public changedOverride?: number;
@property({ attribute: false }) public changedTextOverride?: string;
@property({ attribute: false }) public stateAccent = false;
@state() private _absoluteTime = false;
@state()
@@ -51,30 +56,41 @@ export class HaMoreInfoStateHeader extends LitElement {
const stateDisplay = this.stateOverride ?? this._localizeState();
return html`
<p class="state">${stateDisplay}</p>
<p class=${classMap({ state: true, accent: this.stateAccent })}>
${stateDisplay}
</p>
<div class="time-row">
<p class="last-changed" @click=${this._toggleAbsolute}>
${
this._absoluteTime
? html`
<ha-absolute-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
></ha-absolute-time>
`
: html`
<ha-relative-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
capitalize
></ha-relative-time>
`
}
</p>
${
this.changedTextOverride
? html`<p class="last-changed secondary" aria-hidden="true">
${this.changedTextOverride}
</p>`
: html`<p class="last-changed" @click=${this._toggleAbsolute}>
${
this._absoluteTime
? html`
<ha-absolute-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
></ha-absolute-time>
`
: html`
<ha-relative-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
capitalize
></ha-relative-time>
`
}
</p>`
}
<slot name="after-time"></slot>
</div>
<span class="visually-hidden" aria-live="polite"
>${this.changedTextOverride ?? ""}</span
>
`;
}
@@ -113,6 +129,22 @@ export class HaMoreInfoStateHeader extends LitElement {
user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.visually-hidden {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px;
width: 1px;
margin: -1px;
padding: 0;
border: 0;
}
.state.accent {
color: var(--primary-color);
}
.last-changed.secondary {
cursor: default;
}
`;
}
@@ -22,7 +22,7 @@ export class HaMoreInfoViewVacuumCleanAreasHeaderAction extends LitElement {
if (!this.params.entityId || !this.hass.user?.is_admin) return;
try {
const entry = await getExtendedEntityRegistryEntry(
this.hass,
this.hass.callWS,
this.params.entityId
);
const areaMapping = entry?.options?.vacuum?.area_mapping;
@@ -56,7 +56,10 @@ export class HaMoreInfoViewVacuumCleanAreas extends LitElement {
try {
const entry: ExtEntityRegistryEntry =
await getExtendedEntityRegistryEntry(this.hass, this.params.entityId);
await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.params.entityId
);
const areaMapping = entry?.options?.vacuum?.area_mapping || {};
const mappedAreaIds = new Set(Object.keys(areaMapping));
@@ -50,7 +50,7 @@ export class HaMoreInfoViewVacuumSegmentMapping extends LitElement {
if (!this.params.entityId) return;
this._entry = await getExtendedEntityRegistryEntry(
this.hass,
this.hass.callWS,
this.params.entityId
);
+174 -141
View File
@@ -1,36 +1,46 @@
import { mdiMenu, mdiSwapVertical } from "@mdi/js";
import { mdiAngleAcute, mdiArrowUpDown } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import { supportsFeature } from "../../../common/entity/supports-feature";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-icon-button-group";
import "../../../components/ha-icon-button-toggle";
import { formattersContext } from "../../../data/context";
import {
shouldShowFavoriteOptions,
type ExtEntityRegistryEntry,
} from "../../../data/entity/entity_registry";
import type { CoverEntity } from "../../../data/cover";
import {
CoverEntityFeature,
coverSupportsAnyPosition,
coverSupportsPosition,
coverSupportsTiltPosition,
computeCoverPositionStateDisplay,
import { apiContext, formattersContext } from "../../../data/context";
import type {
CoverCommand,
CoverControlMode,
CoverDrag,
CoverEntity,
} from "../../../data/cover";
import "../../../state-control/cover/ha-state-control-cover-buttons";
import "../../../state-control/cover/ha-state-control-cover-position";
import "../../../state-control/cover/ha-state-control-cover-tilt-position";
import "../../../state-control/cover/ha-state-control-cover-toggle";
import type { HomeAssistantFormatters } from "../../../types";
import {
coverCommandData,
coverCommandService,
coverCurrentValue,
coverHasPositionControls,
coverHasTiltControls,
coverModeAttribute,
coverSupportsPosition,
coverSupportsSetValue,
defaultCoverMode,
} from "../../../data/cover";
import type { ExtEntityRegistryEntry } from "../../../data/entity/entity_registry";
import { CoverRequestController } from "../../../state-control/cover/cover-request-controller";
import "../../../state-control/cover/ha-state-control-cover";
import type { HomeAssistantApi, HomeAssistantFormatters } from "../../../types";
import "../components/covers/ha-more-info-cover-buttons";
import "../components/covers/ha-more-info-cover-favorite-positions";
import "../components/ha-more-info-state-header";
import { moreInfoControlStyle } from "../components/more-info-control-style";
type Mode = "position" | "button";
type CoverHintKey =
| "requested"
| "requested_open"
| "requested_closed"
| "currently"
| "currently_unknown";
@customElement("more-info-cover")
class MoreInfoCover extends LitElement {
@@ -42,159 +52,176 @@ class MoreInfoCover extends LitElement {
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@property({ attribute: false }) public stateObj?: CoverEntity;
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
@property({ attribute: false }) public editMode?: boolean;
@state() private _mode?: Mode;
@state() private _mode: CoverControlMode = "position";
private _setMode(ev) {
this._mode = ev.currentTarget.mode;
}
@state() private _drag?: CoverDrag;
private _requests = new CoverRequestController(this);
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (changedProps.has("stateObj") && this.stateObj) {
const entityId = this.stateObj.entity_id;
const oldEntityId = changedProps.get("stateObj")?.entity_id;
if (!this._mode || entityId !== oldEntityId) {
this._mode = coverSupportsAnyPosition(this.stateObj)
? "position"
: "button";
}
if (!changedProps.has("stateObj") || !this.stateObj) {
return;
}
if (changedProps.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
this._mode = defaultCoverMode(this.stateObj);
this._requests.clear();
this._drag = undefined;
return;
}
this._requests.stateChanged(this.stateObj);
}
private get _stateOverride() {
const stateDisplay = this._formatters.formatEntityState(this.stateObj!);
private _setMode(ev: Event) {
this._mode = (ev.currentTarget as HTMLElement).dataset
.mode as CoverControlMode;
}
const positionStateDisplay = computeCoverPositionStateDisplay(
private _handleCommand(ev: HASSDomEvent<CoverCommand>) {
ev.stopPropagation();
const stateObj = this.stateObj!;
const command = ev.detail;
this._api
.callService(
"cover",
coverCommandService(command),
coverCommandData(stateObj, command)
)
.catch(() => this._requests.clear());
this._requests.commandSent(command, stateObj);
}
private _handleDrag(ev: HASSDomEvent<HASSDomEvents["cover-drag-changed"]>) {
ev.stopPropagation();
this._drag = ev.detail.drag;
}
private _formatValue(mode: CoverControlMode, value: number) {
return this._formatters.formatEntityAttributeValue(
this.stateObj!,
this._formatters.formatEntityAttributeValue
coverModeAttribute(mode),
Math.round(value)
);
}
if (positionStateDisplay) {
return `${stateDisplay} · ${positionStateDisplay}`;
private _hint(key: CoverHintKey, values?: Record<string, string>) {
return this._localize(`ui.dialogs.more_info_control.cover.${key}`, values);
}
private _dragText(): string | undefined {
const drag = this._drag;
if (!drag) {
return undefined;
}
return stateDisplay;
if (!drag.swipe) {
return this._formatValue(this._mode, drag.value);
}
if (!drag.swipe.passedHalfway) {
return undefined;
}
return this._localize(
drag.swipe.action === "close"
? "ui.dialogs.more_info_control.cover.closes_on_release"
: "ui.dialogs.more_info_control.cover.opens_on_release"
);
}
private _stateText(): string {
const stateObj = this.stateObj!;
const stateDisplay = this._formatters.formatEntityState(stateObj);
const value = Math.round(
stateObj.attributes[coverModeAttribute(this._mode)] ?? 0
);
if (value === 0) {
return stateDisplay;
}
return `${stateDisplay} · ${this._formatValue(this._mode, value)}`;
}
private _dragHint(): string | undefined {
if (!this._drag || this._drag.swipe) {
return undefined;
}
const current = coverCurrentValue(this.stateObj!, this._mode);
return current === undefined
? this._hint("currently_unknown")
: this._hint("currently", {
value: this._formatValue(this._mode, current),
});
}
private _requestHint(): string | undefined {
const request = this._requests.request;
if (!request || this._drag) {
return undefined;
}
if (request.mode === "position" && !coverSupportsPosition(this.stateObj!)) {
return this._hint(request.value ? "requested_open" : "requested_closed");
}
return this._hint("requested", {
value: this._formatValue(request.mode, request.value),
});
}
private _showFavorites(stateObj: CoverEntity): boolean {
if (!this.entry) {
return false;
}
return coverSupportsSetValue(stateObj, this._mode);
}
protected render() {
if (!this.stateObj) {
return nothing;
}
const supportsPosition = coverSupportsPosition(this.stateObj);
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
const showFavoriteControls = Boolean(
this.entry &&
(this.editMode ||
(coverSupportsPosition(this.stateObj) &&
shouldShowFavoriteOptions(
this.entry.options?.cover?.favorite_positions
)) ||
(coverSupportsTiltPosition(this.stateObj) &&
shouldShowFavoriteOptions(
this.entry.options?.cover?.favorite_tilt_positions
)))
);
const supportsOpenClose =
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) ||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) ||
supportsFeature(this.stateObj, CoverEntityFeature.STOP);
const supportsTilt =
supportsFeature(this.stateObj, CoverEntityFeature.OPEN_TILT) ||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE_TILT) ||
supportsFeature(this.stateObj, CoverEntityFeature.STOP_TILT);
const supportsOpenCloseOnly =
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) &&
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) &&
!supportsFeature(this.stateObj, CoverEntityFeature.STOP) &&
!supportsTilt &&
!supportsPosition &&
!supportsTiltPosition;
const stateObj = this.stateObj;
const bothModes =
coverHasPositionControls(stateObj) && coverHasTiltControls(stateObj);
const dragText = this._dragText();
return html`
<ha-more-info-state-header
.stateObj=${this.stateObj}
.stateOverride=${this._stateOverride}
.stateObj=${stateObj}
.stateOverride=${dragText ?? this._stateText()}
.changedTextOverride=${this._dragHint() ?? this._requestHint()}
.stateAccent=${dragText !== undefined}
></ha-more-info-state-header>
<div class="controls">
<div
class="controls"
@cover-command=${this._handleCommand}
@cover-drag-changed=${this._handleDrag}
>
<div class="main-control">
<ha-state-control-cover
.stateObj=${stateObj}
.mode=${this._mode}
.request=${this._requests.request}
></ha-state-control-cover>
${
this._mode === "position"
? html`
${
supportsPosition
? html`
<ha-state-control-cover-position
.stateObj=${this.stateObj}
></ha-state-control-cover-position>
`
: nothing
}
${
supportsTiltPosition
? html`
<ha-state-control-cover-tilt-position
.stateObj=${this.stateObj}
></ha-state-control-cover-tilt-position>
`
: nothing
}
`
: nothing
}
${
this._mode === "button"
? html`
${
supportsOpenCloseOnly
? html`
<ha-state-control-cover-toggle
.stateObj=${this.stateObj}
></ha-state-control-cover-toggle>
`
: supportsOpenClose || supportsTilt
? html`
<ha-state-control-cover-buttons
.stateObj=${this.stateObj}
></ha-state-control-cover-buttons>
`
: nothing
}
`
: nothing
}
</div>
${
(supportsPosition || supportsTiltPosition) &&
(supportsOpenClose || supportsTilt)
bothModes
? html`
<ha-icon-button-group>
<ha-icon-button-toggle
.label=${this._localize(
`ui.dialogs.more_info_control.cover.switch_mode.position`
)}
.label=${this._localize("ui.card.cover.position")}
.selected=${this._mode === "position"}
.path=${mdiMenu}
.mode=${"position"}
.path=${mdiArrowUpDown}
data-mode="position"
@click=${this._setMode}
></ha-icon-button-toggle>
<ha-icon-button-toggle
.label=${this._localize(
`ui.dialogs.more_info_control.cover.switch_mode.button`
)}
.selected=${this._mode === "button"}
.path=${mdiSwapVertical}
.mode=${"button"}
.label=${this._localize("ui.card.cover.tilt_position")}
.selected=${this._mode === "tilt"}
.path=${mdiAngleAcute}
data-mode="tilt"
@click=${this._setMode}
></ha-icon-button-toggle>
</ha-icon-button-group>
@@ -202,13 +229,18 @@ class MoreInfoCover extends LitElement {
: nothing
}
</div>
<ha-more-info-cover-buttons
.stateObj=${stateObj}
.mode=${this._mode}
></ha-more-info-cover-buttons>
${
showFavoriteControls
this._showFavorites(stateObj)
? html`
<ha-more-info-cover-favorite-positions
.stateObj=${this.stateObj}
.stateObj=${stateObj}
.entry=${this.entry}
.editMode=${this.editMode}
.mode=${this._mode}
></ha-more-info-cover-favorite-positions>
`
: nothing
@@ -223,11 +255,12 @@ class MoreInfoCover extends LitElement {
css`
.main-control {
display: flex;
flex-direction: row;
flex-direction: column;
align-items: center;
gap: var(--ha-space-4);
}
.main-control > * {
margin: 0 var(--ha-space-2);
ha-more-info-cover-buttons {
max-width: 360px;
}
`,
];
@@ -88,10 +88,7 @@ class MoreInfoGroup extends LitElement {
return "";
}
return html`
<state-card-content
.stateObj=${entityState}
.hass=${this.hass}
></state-card-content>
<state-card-content .stateObj=${entityState}></state-card-content>
`;
})}`;
}
@@ -124,7 +124,12 @@ class MoreInfoMediaPlayer extends LitElement {
private _volumeController = new VolumeSliderController({
getSlider: () => this._volumeSlider,
step: this._volumeStep,
onSetVolume: (value) => this._setVolume(value),
onSetVolume: (value) => {
// The final value is set right away, so drop the pending update from
// the input events before it, or the same value is sent twice
this._debouncedVolumeSet.cancel();
this._setVolume(value);
},
onSetVolumeDebounced: (value) => this._debouncedVolumeSet(value),
});
@@ -227,7 +227,7 @@ class MoreInfoWeather extends LitElement {
.datetime=${this.stateObj.last_changed}
capitalize
></ha-relative-time>
<ha-tooltip for="relative-time">
<ha-tooltip trigger="hover focus click" for="relative-time">
<div class="row">
<span class="column-name">
${this._i18n.localize(
+1 -1
View File
@@ -217,7 +217,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
}
try {
this._entry = await getExtendedEntityRegistryEntry(
this.hass,
this.hass.callWS,
this._entityId
);
} catch (_e) {
Loaded 100 of 328 files, more files were not shown because too many files have changed in this diff. Show more