Compare commits

...
Author SHA1 Message Date
Maarten Lakerveld 8823dce36c Hide maintenance entities through Lovelace edit mode
The maintenance pencil faked an edit mode: it regenerated the view with every card wrapped in an entity-visibility card, while the Lovelace object kept editMode off. That card type had to be registered with the card factory, so any YAML dashboard could use it.

The panel now turns on real edit mode and sets entityVisibility on the Lovelace object. With that set, view, header, footer, sidebar and badges skip their layout editing chrome, and grid sections wrap each entity card in a hui-card-visibility-edit-mode overlay that toggles it. Cards without an entity are inert while editing, as in regular edit mode. The strategy only takes hidden_entities; while editing, the panel leaves it out so hidden entities show, dimmed.

A toggle saves and hands the view a new Lovelace object with the same config, so nothing is rebuilt and focus stays on the card. The entity-visibility card, its wrapper helper and the edit_visibility strategy option are removed.
2026-11-12 14:08:17 +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
141 changed files with 9525 additions and 5253 deletions

No files matched your search

@@ -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",
}),
],
-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
@@ -165,6 +165,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 +186,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>`
+66
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();
@@ -220,6 +226,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 +479,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 +599,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);
+5 -5
View File
@@ -79,16 +79,16 @@
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.3",
"@tsparticles/preset-links": "4.5.3",
"@versatiles/style": "8.1.1",
"@versatiles/style": "9.0.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",
@@ -108,7 +108,7 @@
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.16.0",
"maplibre-gl": "6.17.0",
"marked": "18.1.3",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
@@ -147,7 +147,7 @@
"@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",
+156 -54
View File
@@ -277,7 +277,7 @@ importers:
version: 1.0.3
'@maplibre/maplibre-gl-leaflet':
specifier: 0.1.4
version: 0.1.4(@types/[email protected])([email protected])([email protected]6.0)
version: 0.1.4(@types/[email protected])([email protected])([email protected]7.0)
'@mdi/js':
specifier: 7.4.47
version: 7.4.47
@@ -297,14 +297,14 @@ importers:
specifier: 4.5.3
version: 4.5.3
'@versatiles/style':
specifier: 8.1.1
version: 8.1.1([email protected]6.0)
specifier: 9.0.0
version: 9.0.0([email protected]7.0)
'@vibrant/color':
specifier: 4.0.4
version: 4.0.4
'@vvo/tzdb':
specifier: 6.203.0
version: 6.203.0
specifier: 6.204.0
version: 6.204.0
'@webcomponents/scoped-custom-element-registry':
specifier: 0.0.10
version: 0.0.10
@@ -324,8 +324,8 @@ importers:
specifier: 3.51.0
version: 3.51.0
cropperjs:
specifier: 1.7.0
version: 1.7.0
specifier: 2.3.1
version: 2.3.1
culori:
specifier: 4.0.2
version: 4.0.2
@@ -384,8 +384,8 @@ importers:
specifier: 3.3.3
version: 3.3.3
maplibre-gl:
specifier: 6.16.0
version: 6.16.0
specifier: 6.17.0
version: 6.17.0
marked:
specifier: 18.1.3
version: 18.1.3
@@ -496,8 +496,8 @@ importers:
specifier: workspace:*
version: link:packages/components
'@html-eslint/eslint-plugin':
specifier: 0.67.0
version: 0.67.0([email protected]([email protected]))
specifier: 0.68.0
version: 0.68.0([email protected]([email protected]))
'@lokalise/node-api':
specifier: 17.0.1
version: 17.0.1
@@ -1863,6 +1863,39 @@ packages:
peerDependencies:
commander: ~15.0.0
'@cropper/[email protected]':
resolution: {integrity: sha512-UH3VMyjn58PdwYkPiTHuvRUjGzmyKr6E2pYWxTxN/04wnjgYLA77B5u5c1HhV6vD1ZKSvxJ/i9TkiySR9P1D6A==}
'@cropper/[email protected]':
resolution: {integrity: sha512-Vz2heRwr2nd2rZ161vKyE4JwYV3eSodGCGGZq39TR0LICGOOeggLq0R664Af/eFB9PU8+tfJ42lWLoUdxQlVJQ==}
'@cropper/[email protected]':
resolution: {integrity: sha512-6LDaUDxH2xdA7biTcqnihPQVHjlT4bXysA403s9rU4jo5f4pPnFHtNbB+FQTYKNz5EKun52WgVtR+6oWbmbxlg==}
'@cropper/[email protected]':
resolution: {integrity: sha512-ygLw89PWu9k8SuKW7rjRBpD6ZfmtVr5ayWux9YKHU7PxX0SeL5kbCD+PpOxQB1ycW4UcyH0tHt77EWnsdSoOHw==}
'@cropper/[email protected]':
resolution: {integrity: sha512-rPE7OX/BPTw66+DjpN5aOuPb1xSAjQMgAJZXdRgmeJnn0YcDDhfGQm8VwcL8/PMLxtWFcKEM+aUiezbO01j4fg==}
'@cropper/[email protected]':
resolution: {integrity: sha512-b8sabaFbHeQYY459uItDIeDY0IisZBO/wF+SYhKvAgI8TExj/f2mNcBZXjPHYCkWel2+1BSUTTNZxy+tR8sDEA==}
'@cropper/[email protected]':
resolution: {integrity: sha512-X5ceZsy7iBxuIRhsL05H9+cPYzxZuvM7/9j5irXIbNsDiNwTedxIHdjhEhPbUYa+FaNn9wsKId24AEyH43JTGw==}
'@cropper/[email protected]':
resolution: {integrity: sha512-EdrYDbnkj0IOl/kyWKzzvcDRobr7Tfzho7FkVu8mpSk1ILDHmVf8pfZrYVwou8l4znLqp8ZqwuabAezJPfC2Yg==}
'@cropper/[email protected]':
resolution: {integrity: sha512-CgrLOx0qERWlfJK1Ed6ePq7SXcB6gLHtj3mtDVypyzti70fJdmNxrFm5Ucbq8vpp2Yo3tW2L6uDI0IBDoiT17A==}
'@cropper/[email protected]':
resolution: {integrity: sha512-+D5rFlfFlWSL1lp0vPYI59/R6XM2vMnTSX0/B1zKRvmkc0t0N0m9lxVsaDb+9RkHx6PwAkBBNPZSRUeau33jMg==}
'@cropper/[email protected]':
resolution: {integrity: sha512-b5qFTwws/osx0asIGLK1V//hdL08frGvfpi6s+p6zj5XH05ofVcz0Xl+Tot7sUx12pbfhhAlsquQTOJ1IsOoFw==}
'@ctrl/[email protected]':
resolution: {integrity: sha512-WyOx8cJQ+FQus4Mm4uPIZA64gbk3Wxh0so5Lcii0aJifqwoVOlfFtorjLE0Hen4OYyHZMXDWqMmaQemBhgxFRQ==}
engines: {node: '>=14'}
@@ -2075,27 +2108,27 @@ packages:
resolution: {integrity: sha512-EX1qiX5h3LAoTjuE3rgfuRlNq3Rds5tGrgDGlHoFbxhXaCSTTtuYU6tdR8vgOXKGUDi5gBDrcoNdLYKFXSrknA==}
engines: {node: '>=14.17.0'}
'@html-eslint/[email protected]7.0':
resolution: {integrity: sha512-MPoKw4woCkuFYs2xdt0vEjzGbUzU8lxeTZkxyrtHM+zZlaK/u/lqcIapZmyCTQBqNE0H9J8zc9TmXjygfHcuXg==}
'@html-eslint/[email protected]8.0':
resolution: {integrity: sha512-u3HioqcKIH6dVQp2uulmpcuUqgKLqiuOWyHAl7hV4hIUkuJ3ge7vEUwPoWvNRbfy3aWOMygttokdGxL5q9YFIg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@html-eslint/[email protected]7.0':
resolution: {integrity: sha512-gr2wKoS1OOZa6uL8DDNCjvPyTu6mWsyQJ/WXmvP/DeFRe6pdumsb8ePYfP7qZW5741MtVd0OpLbxa82XivxxWQ==}
'@html-eslint/[email protected]8.0':
resolution: {integrity: sha512-fiR8UTYBr4+fGftEG1u+tT3AiuOSowvSZbsY4tLcMl9hOuFzquHw4BIaFFlV3xTeqF5Y0M69aPJoEhFJUkQyog==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: '>=8.0.0 || ^10.0.0-0'
'@html-eslint/[email protected]7.0':
resolution: {integrity: sha512-ejdtqLqclQPDfivgsD2yWHXa+FyyEytMlGNNfiHw/UbUeV9tn1hBjIZLJ5VvzjO0IweaAIWIZKlEPgKT6tYP8A==}
'@html-eslint/[email protected]8.0':
resolution: {integrity: sha512-X22bU2qzEpzPI0bHtnfXzoUS8q/It/DNycJnIdsPzBDXcly+PItV5AJU4nm/+9FZCXSE3IZJvORRCTuvvpV8Bg==}
'@html-eslint/[email protected]7.0':
resolution: {integrity: sha512-fvFAuAaKzkg9deV69uT1NoVJSwXTu3mvGDWzlZKe+xwm5JnkbWC626eyDRlAQDzff2/zX7tWFq4EMgOoZmgtRA==}
'@html-eslint/[email protected]8.0':
resolution: {integrity: sha512-zLgikGAF7izvrvUefy5EBEl6WpM0sTN9xzldwp7UgkkjR+zaFvqi9YsOWj+Y7Tu3XMXI0d7Gxv7PPPumVmJTuw==}
'@html-eslint/[email protected]7.0':
resolution: {integrity: sha512-leHUXnpFgRSR3o7rpw5OtOVGfzcChIgrhXDgPlBwdoL7V4+5KZjxGLJAPVwbj7sVVNrSWynlIQ1Wn4FuNKxZhw==}
'@html-eslint/[email protected]8.0':
resolution: {integrity: sha512-qbIF3MqmRckg6pXhwY/Ytxnb0eOoq5LPVt9wq8N4UBQHxL2z4cF407FHAiLNhpy8DO4AJUQbI6IZzhN8fHkvPA==}
'@html-eslint/[email protected]7.0':
resolution: {integrity: sha512-8w9V0sTm2DGLh2uslL7+Un9g/FHNcevgouiTLhlAJoBhhGOK5+fX76QCKdWbgmpudNGo8Nh1kHKsJP3a6twzXA==}
'@html-eslint/[email protected]8.0':
resolution: {integrity: sha512-FW+FjFHp/w1V4uZ0us7keR6mAA+WGh6OsHvJ+Kzy8aBeogyOapDPEMT+zkXSsiJ+V9maJ6umqG20BXcs2y6lsw==}
'@humanfs/[email protected]':
resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}
@@ -3785,8 +3818,8 @@ packages:
cpu: [x64]
os: [win32]
'@versatiles/style@8.1.1':
resolution: {integrity: sha512-wotbl1VYI0JK94oq7Ji/QTdUi4jHoXtWpBnia/tcFBvAM8Ho4URnRjkNdJ6VbMM/3PqoFEYhUispAhsdCvv5hA==}
'@versatiles/style@9.0.0':
resolution: {integrity: sha512-hKtVfdQvxLYX7BaGKQhgtcnOHtj+dc1qU7hXL3V4KzMWU+RZtmGI83m5JPxGIB5M/UoDKc3cyXZaf2OeiL5jCA==}
engines: {node: '>=20'}
peerDependencies:
maplibre-gl: '>=5.5.0'
@@ -3864,8 +3897,8 @@ packages:
'@vscode/[email protected]':
resolution: {integrity: sha512-2ZUIRfhofZ/npLlf872EBnPmn27Kt4M2UssmQIfnJvgGgMYZJ5fvtHEDnttBBf2hnVtBgNCqZMVHJA+wsFVqTA==}
'@vvo/[email protected]3.0':
resolution: {integrity: sha512-VdAiMSmHFzdL2csQU4QtNEV0l4JOgMPdFvk7cEm4a5LRVZsM3tQ2Kxyk5O6plB55DjOwIyoTt29mFi+vA9GYSw==}
'@vvo/[email protected]4.0':
resolution: {integrity: sha512-GC7i3D4rCs6l5jnf6NofoRRumZwVHS1cBNhgbenDLLyJNqJOrTo/8zrWovIrJl5BujiFurqn0Ayj10wysmOKrQ==}
'@web/[email protected]':
resolution: {integrity: sha512-XVKH79pk4d3EHRhofete8eAnqto1e8mCRAqPV00KLNFzCWSe8sWmLnqKCqkPNARC6nksMaGrATnA5sPDRllMpQ==}
@@ -4576,8 +4609,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==}
cropperjs@1.7.0:
resolution: {integrity: sha512-AkGnZxr7xAJBa63ObXq5ZKLkh9c8wisC+Ym8VzIDn3KZ+6qRTbBnOl2w2dFOTMzLP5IcfOpEK9PICDywNXhncg==}
cropperjs@2.3.1:
resolution: {integrity: sha512-bgy+iHRFjsBxBCriXkTuFuHRJGSGZISuqDGhDQG7gLK0F7qOzhH06bdXzGf4b0bZSQ+mApakybiW9xvKnS9dbg==}
[email protected]:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
@@ -6116,8 +6149,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-C0X0KQmGm3N2ftbTGBhSyuydQ+vV1LC3f3zPvT3RXHXNZrvfPZcoXp/N5DOa8vedX/rTMm2CjTtivFg2STJMRQ==}
[email protected]6.0:
resolution: {integrity: sha512-gApO66EMtoDZuio680RUBvskR7ahFd/NNhLN4tBAs+Y7FeT4gQV8zVFgYVMRmFxQznOEzecW19w6xOd9XjZjiA==}
[email protected]7.0:
resolution: {integrity: sha512-2chIZwpLGenoUQOcnm9Pk4SLbA8ppNFq8jlpXiq9vcYm3Y1wJ3fc82FL0GLwBaPYJCLzPv/mC46KEupVov75rQ==}
engines: {node: '>=16.14.0', npm: '>=8.1.0'}
[email protected]:
@@ -9531,6 +9564,72 @@ snapshots:
dependencies:
commander: 15.0.0
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/element-canvas': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/element-canvas': 2.3.1
'@cropper/element-image': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/element-canvas': 2.3.1
'@cropper/element-selection': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/element-canvas': 2.3.1
'@cropper/element-image': 2.3.1
'@cropper/element-selection': 2.3.1
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/utils': 2.3.1
'@cropper/[email protected]':
dependencies:
'@cropper/element': 2.3.1
'@cropper/element-canvas': 2.3.1
'@cropper/element-crosshair': 2.3.1
'@cropper/element-grid': 2.3.1
'@cropper/element-handle': 2.3.1
'@cropper/element-image': 2.3.1
'@cropper/element-selection': 2.3.1
'@cropper/element-shade': 2.3.1
'@cropper/element-viewer': 2.3.1
'@cropper/[email protected]': {}
'@ctrl/[email protected]': {}
'@custom-elements-manifest/[email protected]':
@@ -9797,40 +9896,40 @@ snapshots:
- '@types/node'
- '@types/react'
'@html-eslint/[email protected]7.0':
'@html-eslint/[email protected]8.0':
dependencies:
'@html-eslint/types': 0.67.0
'@html-eslint/types': 0.68.0
html-standard: 0.0.13
'@html-eslint/[email protected]7.0([email protected]([email protected]))':
'@html-eslint/[email protected]8.0([email protected]([email protected]))':
dependencies:
'@eslint/plugin-kit': 0.4.1
'@html-eslint/core': 0.67.0
'@html-eslint/parser': 0.67.0
'@html-eslint/template-parser': 0.67.0
'@html-eslint/template-syntax-parser': 0.67.0
'@html-eslint/types': 0.67.0
'@html-eslint/core': 0.68.0
'@html-eslint/parser': 0.68.0
'@html-eslint/template-parser': 0.68.0
'@html-eslint/template-syntax-parser': 0.68.0
'@html-eslint/types': 0.68.0
'@rviscomi/capo.js': 2.2.1
eslint: 10.14.0([email protected])
html-standard: 0.0.13
'@html-eslint/[email protected]7.0':
'@html-eslint/[email protected]8.0':
dependencies:
'@html-eslint/template-syntax-parser': 0.67.0
'@html-eslint/types': 0.67.0
'@html-eslint/template-syntax-parser': 0.68.0
'@html-eslint/types': 0.68.0
css-tree: 3.2.1
es-html-parser: 0.3.2
'@html-eslint/[email protected]7.0':
'@html-eslint/[email protected]8.0':
dependencies:
'@html-eslint/types': 0.67.0
'@html-eslint/types': 0.68.0
es-html-parser: 0.3.2
'@html-eslint/[email protected]7.0':
'@html-eslint/[email protected]8.0':
dependencies:
'@html-eslint/types': 0.67.0
'@html-eslint/types': 0.68.0
'@html-eslint/[email protected]7.0':
'@html-eslint/[email protected]8.0':
dependencies:
'@types/css-tree': 2.3.11
'@types/estree': 1.0.9
@@ -10080,11 +10179,11 @@ snapshots:
dependencies:
kdbush: 4.1.0
'@maplibre/[email protected](@types/[email protected])([email protected])([email protected]6.0)':
'@maplibre/[email protected](@types/[email protected])([email protected])([email protected]7.0)':
dependencies:
'@types/leaflet': 1.9.22
leaflet: 1.9.4
maplibre-gl: 6.16.0
maplibre-gl: 6.17.0
'@maplibre/[email protected]':
dependencies:
@@ -11527,11 +11626,11 @@ snapshots:
'@unrs/[email protected]':
optional: true
'@versatiles/style@8.1.1([email protected]6.0)':
'@versatiles/style@9.0.0([email protected]7.0)':
dependencies:
'@maplibre/maplibre-gl-style-spec': 26.5.1
optionalDependencies:
maplibre-gl: 6.16.0
maplibre-gl: 6.17.0
'@vibrant/[email protected]': {}
@@ -11621,7 +11720,7 @@ snapshots:
'@vscode/[email protected]': {}
'@vvo/[email protected]3.0': {}
'@vvo/[email protected]4.0': {}
'@web/[email protected]':
dependencies:
@@ -12287,7 +12386,10 @@ snapshots:
[email protected]: {}
cropperjs@1.7.0: {}
cropperjs@2.3.1:
dependencies:
'@cropper/elements': 2.3.1
'@cropper/utils': 2.3.1
[email protected]:
dependencies:
@@ -13994,7 +14096,7 @@ snapshots:
[email protected]: {}
[email protected]6.0:
[email protected]7.0:
dependencies:
'@mapbox/point-geometry': 1.1.0
'@mapbox/tiny-sdf': 2.3.0
+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);
+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);
};
+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;
};
+56 -12
View File
@@ -30,10 +30,40 @@ export class HaAutomationRow extends LitElement {
@property({ type: Boolean, reflect: true })
public dim = 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"
@@ -53,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>
`;
}
@@ -119,7 +139,7 @@ export class HaAutomationRow extends LitElement {
public focus() {
requestAnimationFrame(() => {
this._rowElement?.focus();
(this._linkElement ?? this._rowElement)?.focus();
});
}
@@ -144,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);
+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)
);
+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(
+7 -11
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";
@@ -34,17 +35,14 @@ class HaConfigNavigationList extends LitElement {
.href=${externalApp ? undefined : page.path}
@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>
style=${styleMap({ backgroundColor: page.iconColor })}
.path=${page.iconPath}
.secondaryPath=${page.iconSecondaryPath}
.viewBox=${page.iconViewBox}
></ha-svg-icon>
<span slot="headline">${page.name}</span>
${
this.hasSecondary
@@ -82,8 +80,6 @@ class HaConfigNavigationList extends LitElement {
}
.icon-background {
border-radius: var(--ha-border-radius-circle);
}
.icon-background ha-svg-icon {
color: #fff;
}
`;
@@ -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;
+3 -2
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")
@@ -396,8 +397,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)
+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`
+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;
}
`,
];
+13 -11
View File
@@ -84,19 +84,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 {
@@ -125,11 +125,11 @@ 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 {
protected override _renderControl(content: TemplateResult): TemplateResult {
if (!this.interactive) {
return html`<div part="base" class="base" id="item">${inner}</div>`;
return content;
}
return super._renderBase(inner);
return super._renderControl(content);
}
// Always reserve the graphic, so titles line up across rows
@@ -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
+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,
+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
@@ -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,
@@ -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;
}
}
@@ -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),
});
@@ -74,7 +74,6 @@ export class MoreInfoInfo extends LitElement {
<state-card-content
in-dialog
.stateObj=${stateObj}
.hass=${this.hass}
></state-card-content>
`
}
+11 -1
View File
@@ -642,7 +642,17 @@ export class QuickBar extends LitElement {
);
private _getEntitiesMemoized = memoizeOne((hass: HomeAssistant) =>
getEntities(hass, { idPrefix: `entity${SEPARATOR}` })
getEntities({
states: hass.states,
entities: hass.entities,
devices: hass.devices,
areas: hass.areas,
floors: hass.floors,
localize: hass.localize,
language: hass.language,
translationMetadata: hass.translationMetadata,
idPrefix: `entity${SEPARATOR}`,
})
);
private _getDevicesMemoized = memoizeOne(
+21 -26
View File
@@ -150,9 +150,11 @@ class DialogRestart extends LitElement {
"ui.dialogs.restart.reload.description"
)}
</div>
<div slot="start" class="icon-background reload">
<ha-svg-icon .path=${mdiAutoFix}></ha-svg-icon>
</div>
<ha-svg-icon
slot="start"
class="icon-background reload"
.path=${mdiAutoFix}
></ha-svg-icon>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button
@@ -160,9 +162,11 @@ class DialogRestart extends LitElement {
@click=${this._handleAction}
.disabled=${this._loadingBackupInfo}
>
<div slot="start" class="icon-background restart">
<ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
</div>
<ha-svg-icon
slot="start"
class="icon-background restart"
.path=${mdiRefresh}
></ha-svg-icon>
<div slot="headline">
${this.hass.localize("ui.dialogs.restart.restart.title")}
</div>
@@ -188,14 +192,11 @@ class DialogRestart extends LitElement {
@click=${this._handleAction}
.disabled=${this._loadingBackupInfo}
>
<div
<ha-svg-icon
slot="start"
class="icon-background reboot"
>
<ha-svg-icon
.path=${mdiPowerCycle}
></ha-svg-icon>
</div>
.path=${mdiPowerCycle}
></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
"ui.dialogs.restart.reboot.title"
@@ -213,12 +214,11 @@ class DialogRestart extends LitElement {
@click=${this._handleAction}
.disabled=${this._loadingBackupInfo}
>
<div
<ha-svg-icon
slot="start"
class="icon-background shutdown"
>
<ha-svg-icon .path=${mdiPower}></ha-svg-icon>
</div>
.path=${mdiPower}
></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
"ui.dialogs.restart.shutdown.title"
@@ -239,12 +239,11 @@ class DialogRestart extends LitElement {
@click=${this._handleAction}
.disabled=${this._loadingBackupInfo}
>
<div
<ha-svg-icon
slot="start"
class="icon-background restart-safe-mode"
>
<ha-svg-icon .path=${mdiLifebuoy}></ha-svg-icon>
</div>
.path=${mdiLifebuoy}
></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
"ui.dialogs.restart.restart-safe-mode.title"
@@ -436,12 +435,8 @@ class DialogRestart extends LitElement {
.icon-background {
border-radius: var(--ha-border-radius-circle);
color: #fff;
display: flex;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
/* 24px icon + padding = 40px circle */
padding: var(--ha-space-2);
}
.reload {
background-color: #5f8a49;
@@ -310,7 +310,7 @@ export class HaVoiceAssistantSetupStepLocal extends LitElement {
if (configFlow) {
const step = await handleConfigFlowStep(
this.hass,
this.hass.callApi,
configFlow.flow_id,
{}
);
@@ -343,11 +343,15 @@ export class HaVoiceAssistantSetupStepLocal extends LitElement {
}
private async _createConfigEntry(type: "tts" | "stt") {
const configFlow = await createConfigFlow(this.hass, "wyoming");
const step = await handleConfigFlowStep(this.hass, configFlow.flow_id, {
host: type === "tts" ? this._ttsHostName : this._sttHostName,
port: type === "tts" ? this._ttsPort : this._sttPort,
});
const configFlow = await createConfigFlow(this.hass.callApi, "wyoming");
const step = await handleConfigFlowStep(
this.hass.callApi,
configFlow.flow_id,
{
host: type === "tts" ? this._ttsHostName : this._sttHostName,
port: type === "tts" ? this._ttsPort : this._sttPort,
}
);
if (step.type !== "create_entry") {
throw new Error(
`${this.hass.localize("ui.panel.config.voice_assistants.satellite_wizard.local.errors.failed_create_entry", { app: type === "tts" ? this._ttsProviderName : this._sttProviderName })}${"errors" in step ? `: ${step.errors?.base}` : ""}`
+39 -2
View File
@@ -45,15 +45,42 @@
}
#ha-launch-screen .ha-launch-screen-spacer-top {
flex: 1;
margin-top: calc( 2 * max(var(--safe-area-inset-top, 0px), 48px) + 46px );
margin-top: 142px;
padding-top: 48px;
}
#ha-launch-screen .ha-launch-screen-spacer-bottom {
flex: 1;
padding-top: 16px;
}
#ha-launch-screen-info-box p {
max-width: 400px;
margin: 0 16px 16px;
text-align: center;
}
/* Margins, not flex `gap` (Safari 14.1). */
#ha-launch-screen .ha-launch-screen-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: -4px 16px;
}
#ha-launch-screen .ha-launch-screen-actions button {
margin: 4px;
padding: 8px 16px;
border: 1px solid transparent;
border-radius: 18px;
background: none;
color: #009ac7;
font: inherit;
font-size: 14px;
font-weight: 500;
cursor: pointer;
}
#ha-launch-screen .ha-launch-screen-actions .ha-launch-screen-continue {
border-color: currentColor;
}
.ohf-logo {
margin: max(var(--safe-area-inset-bottom, 0px), 48px) 0;
margin: 48px 0;
display: flex;
flex-direction: column;
align-items: center;
@@ -73,6 +100,16 @@
aspect-ratio: 237 / 24;
height: auto;
}
/* max() with var() fails after the cascade, so plain fallbacks above
need @supports (Chrome below 79). `body`: Jinja2, see below. */
@supports (margin: max(1px, 2px)) {
body #ha-launch-screen .ha-launch-screen-spacer-top {
margin-top: calc( 2 * max(var(--safe-area-inset-top, 0px), 48px) + 46px );
}
.ohf-logo {
margin: max(var(--safe-area-inset-bottom, 0px), 48px) 0;
}
}
@media (prefers-color-scheme: dark) {
/*
* Core renders the app's index.html through Jinja2, where the minified
+77 -17
View File
@@ -65,23 +65,83 @@
</script>
<script>
if (!window.latestJS) {
// Below the [legacy] browserslist floor the entry bundles cannot be
// parsed, or dialogs cannot open, and nothing would ever leave the
// launch screen. Test the features that set the floors: BigInt for
// Chrome 67, native <dialog> for Safari 15.4 and Firefox 98. Not
// transpiled, so keep this ES5.
if (
typeof BigInt === "undefined" ||
typeof document.createElement("dialog").showModal !== "function"
) {
document.getElementById("ha-launch-screen-info-box").textContent =
"This browser is too old to run Home Assistant.";
} else {
window.customPanelJS = "<%= es5CustomPanelJS %>";
<% for (const entry of es5EntryJS) { %>
_ls("<%= entry %>", true);
<% } %>
}
// Floor check: BigInt for Chrome 67, <dialog> for Safari 15.4 and
// Firefox 98. Not transpiled, so keep this ES5.
(function () {
var ACCEPTED_KEY = "haUnsupportedBrowserAccepted";
var REMIND_AFTER = 30 * 24 * 60 * 60 * 1000;
function loadApp() {
window.customPanelJS = "<%= es5CustomPanelJS %>";
<% for (const entry of es5EntryJS) { %>
_ls("<%= entry %>", true);
<% } %>
}
if (
typeof BigInt !== "undefined" &&
typeof document.createElement("dialog").showModal === "function"
) {
loadApp();
return;
}
// Shown while the app loads too.
var box = document.getElementById("ha-launch-screen-info-box");
var message = document.createElement("p");
message.textContent =
"This browser is no longer supported. Some parts of Home Assistant may not work.";
box.appendChild(message);
// Stored: "always", or when the user last continued (ms).
var stored = null;
try {
stored = localStorage.getItem(ACCEPTED_KEY);
} catch (_err) {
// Ask on every load.
}
if (stored === "always") {
loadApp();
return;
}
var acceptedAt = Number(stored) || 0;
// A clock behind the stored time asks again.
var age = Date.now() - acceptedAt;
if (acceptedAt && age >= 0 && age < REMIND_AFTER) {
loadApp();
return;
}
var actions = document.createElement("div");
actions.className = "ha-launch-screen-actions";
box.appendChild(actions);
function addButton(label, value) {
var button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.addEventListener("click", function () {
try {
localStorage.setItem(ACCEPTED_KEY, value());
} catch (_err) {
// Continue this time only.
}
box.removeChild(actions);
loadApp();
});
actions.appendChild(button);
return button;
}
addButton("Continue anyway", function () {
return String(Date.now());
}).className = "ha-launch-screen-continue";
if (acceptedAt) {
addButton("Don't show again", function () {
return "always";
});
}
})();
}
</script>
+4
View File
@@ -155,6 +155,10 @@ export const DirtyStateProviderMixin =
protected updated(changedProperties: PropertyValues<this>): void {
super.updated(changedProperties);
// A late fetch can still update a removed provider
if (!this.isConnected) {
return;
}
connectedDirtyStateProviders.set(this, this._blocksReload);
publishGlobalDirtyState();
}
@@ -102,19 +102,6 @@ import type {
AutomationItemComboBoxItem,
} from "./types";
type PickerSources = Pick<
HomeAssistant,
| "states"
| "entities"
| "devices"
| "areas"
| "floors"
| "localize"
| "language"
| "locale"
| "translationMetadata"
>;
const TARGET_SEARCH_SECTIONS = [
"separator",
"entity",
@@ -218,18 +205,20 @@ export class HaAutomationAddSearch extends LitElement {
private _getDevicesMemoized = memoizeOne(
(
sources: PickerSources,
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>,
configEntryLookup: Record<string, ConfigEntry>,
idPrefix: string
) =>
getDevices({
states: sources.states,
areas: sources.areas,
devices: sources.devices,
entities: sources.entities,
localize: sources.localize,
language: sources.locale.language,
translationMetadata: sources.translationMetadata,
states,
areas: registries.areas,
devices: registries.devices,
entities: registries.entities,
localize: i18n.localize,
language: i18n.locale.language,
translationMetadata: i18n.translationMetadata,
configEntryLookup,
idPrefix,
})
@@ -238,8 +227,23 @@ export class HaAutomationAddSearch extends LitElement {
private _getLabelsMemoized = memoizeOne(getLabels);
private _getEntitiesMemoized = memoizeOne(
(sources: PickerSources, idPrefix: string) =>
getEntities(sources, { idPrefix })
(
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>,
idPrefix: string
) =>
getEntities({
states,
entities: registries.entities,
devices: registries.devices,
areas: registries.areas,
floors: registries.floors,
localize: i18n.localize,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
idPrefix,
})
);
private _getAreasAndFloorsMemoized = memoizeOne(getAreasAndFloors);
@@ -247,21 +251,6 @@ export class HaAutomationAddSearch extends LitElement {
private _formatAreaFloorId = (value: AreaFloorValue): string =>
[value.type, value.id].join(TARGET_SEPARATOR);
private _getPickerSources = memoizeOne(
(
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>
): PickerSources => ({
states,
...registries,
localize: i18n.localize,
language: i18n.language,
locale: i18n.locale,
translationMetadata: i18n.translationMetadata,
})
);
private _removeKeyboardShortcuts?: () => void;
protected willUpdate(changedProps: PropertyValues<this>) {
@@ -683,7 +672,9 @@ export class HaAutomationAddSearch extends LitElement {
if (!selectedSection || selectedSection === "entity") {
let entityItems = this._getEntitiesMemoized(
this._getPickerSources(this._states, this._registries, this._i18n),
this._states,
this._registries,
this._i18n,
`entity${TARGET_SEPARATOR}`
);
@@ -720,7 +711,9 @@ export class HaAutomationAddSearch extends LitElement {
if (!selectedSection || selectedSection === "device") {
let deviceItems = this._getDevicesMemoized(
this._getPickerSources(this._states, this._registries, this._i18n),
this._states,
this._registries,
this._i18n,
configEntryLookup,
`device${TARGET_SEPARATOR}`
);
+2 -2
View File
@@ -229,9 +229,9 @@ export class MCPPref extends LitElement {
this._enabling = true;
try {
// The config flow only asks for confirmation, so submit it directly
let step = await createConfigFlow(this.hass, MCP_SERVER_DOMAIN);
let step = await createConfigFlow(this.hass.callApi, MCP_SERVER_DOMAIN);
if (step.type === "form") {
step = await handleConfigFlowStep(this.hass, step.flow_id, {});
step = await handleConfigFlowStep(this.hass.callApi, step.flow_id, {});
}
if (step.type === "form") {
showConfigFlowDialog(this, {
@@ -60,9 +60,10 @@ class HaConfigUpdates extends LitElement {
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
private _renderUpdateProgress(entity: UpdateEntity) {
private _renderUpdateProgress(entity: UpdateEntity, slot?: string) {
if (entity.attributes.update_percentage != null) {
return html`<ha-progress-ring
slot=${ifDefined(slot)}
size="small"
.value=${entity.attributes.update_percentage}
.label=${this._localize("ui.panel.config.updates.update_in_progress")}
@@ -71,6 +72,7 @@ class HaConfigUpdates extends LitElement {
if (entity.attributes.in_progress) {
return html`<ha-spinner
slot=${ifDefined(slot)}
size="small"
.ariaLabel=${this._localize(
"ui.panel.config.updates.update_in_progress"
@@ -78,7 +80,7 @@ class HaConfigUpdates extends LitElement {
></ha-spinner>`;
}
return html`<ha-icon-next></ha-icon-next>`;
return html`<ha-icon-next slot=${ifDefined(slot)}></ha-icon-next>`;
}
protected render() {
@@ -150,9 +152,7 @@ class HaConfigUpdates extends LitElement {
</span>
${
!this.narrow
? html`<div slot="end">
${this._renderUpdateProgress(entity)}
</div>`
? this._renderUpdateProgress(entity, "end")
: nothing
}
</ha-list-item-button>
@@ -1173,6 +1173,9 @@ export class HaConfigDevicePage extends LitElement {
buttons.push({
action: async () => {
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize(
"ui.panel.config.devices.confirm_delete_title"
),
text:
this._integrations(device, this.entries, this.manifests)
.length > 1
@@ -1188,7 +1191,7 @@ export class HaConfigDevicePage extends LitElement {
: this.hass.localize(
`ui.panel.config.devices.confirm_delete`
),
confirmText: this.hass.localize("ui.common.delete"),
confirmText: this.hass.localize("ui.common.remove"),
dismissText: this.hass.localize("ui.common.cancel"),
destructive: true,
});
@@ -474,6 +474,7 @@ export class HaConfigDeviceDashboard extends LitElement {
name: computeDeviceNameDisplay(device, this.hass.localize),
model:
device.model ||
device.model_id ||
`<${localize("ui.panel.config.devices.data_table.unknown")}>`,
manufacturer:
device.manufacturer ||
@@ -1,13 +1,15 @@
import { mdiBatteryHigh, mdiDelete, mdiPencil, mdiPlus } from "@mdi/js";
import { mdiBatteryHigh, mdiDelete, mdiPlus } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { html, LitElement, nothing } from "lit";
import memoizeOne from "memoize-one";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-card";
import "../../../../components/ha-button";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-settings-row";
import type {
BatterySourceTypeEnergyPreference,
EnergyPreferences,
@@ -24,10 +26,17 @@ import {
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsBatteryDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
const isBatterySource = (
source: EnergyPreferences["energy_sources"][number]
): source is BatterySourceTypeEnergyPreference => source.type === "battery";
@customElement("ha-energy-battery-settings")
export class EnergyBatterySettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -41,12 +50,29 @@ export class EnergyBatterySettings extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const batterySources: BatterySourceTypeEnergyPreference[] = [];
const batteryValidation: EnergyValidationIssue[][] = [];
this.preferences.energy_sources.forEach((source, idx) => {
if (source.type !== "battery") {
if (!isBatterySource(source)) {
return;
}
batterySources.push(source);
@@ -86,38 +112,36 @@ export class EnergyBatterySettings extends LitElement {
${
batterySources.length > 0
? html`
<div class="items-container">
<div class="items">
${batterySources.map((source) => {
const toEntityState =
this.hass.states[source.stat_energy_to];
return html`
<div class="row" .source=${source}>
${
toEntityState?.attributes.icon
? html`<ha-icon
.icon=${toEntityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiBatteryHigh}
></ha-svg-icon>`
}
<div class="content">
<span class="label"
>${
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
}</span
>
<ha-card outlined>
<ha-automation-row
.source=${source}
.href=${this._editorHref(source)}
@click=${this.listPath ? nothing : this._editSource}
>
${
source.name
? nothing
: html`
<span class="label"
toEntityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${toEntityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiBatteryHigh}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label"
>${this._sourceName(source)}</span
>
${
source.name
? nothing
: html`<span class="label secondary"
>${getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
@@ -126,127 +150,207 @@ export class EnergyBatterySettings extends LitElement {
source.stat_energy_to
]
)}</span
>
`
}
</div>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.battery.edit_battery_system"
)}
@click=${this._editSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.battery.delete_battery_system"
)}
@click=${this._deleteSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
>`
}
</div>
<ha-icon-button
slot="icons"
.label=${this.hass.localize(
"ui.panel.config.energy.battery.delete_battery_system"
)}
.path=${mdiDelete}
.source=${source}
@click=${this._deleteSourceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`;
})}
</div>
`
: ""
: nothing
}
<div class="row">
<ha-button @click=${this._addSource} appearance="filled" size="s">
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.battery.add_battery_system"
)}</ha-button
>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.battery.add_battery_system"
)}
</ha-button>
</div>
</ha-card>
`;
}
private _sourceName(source: BatterySourceTypeEnergyPreference) {
return (
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
);
}
private _addSource() {
showEnergySettingsBatteryDialog(this, {
statsMetadata: this.statsMetadata,
battery_sources: this.preferences.energy_sources.filter(
(src) => src.type === "battery"
) as BatterySourceTypeEnergyPreference[],
saveCallback: async (source) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.concat(source),
});
},
});
this._openEditor();
}
private _editSource(ev) {
const origSource: BatterySourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
showEnergySettingsBatteryDialog(this, {
statsMetadata: this.statsMetadata,
source: { ...origSource },
battery_sources: this.preferences.energy_sources.filter(
(src) => src.type === "battery"
) as BatterySourceTypeEnergyPreference[],
saveCallback: async (newSource) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src === origSource ? newSource : src
),
});
},
this._openEditor(ev.currentTarget.source);
}
private _openEditor(source?: BatterySourceTypeEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, source),
});
}
private async _deleteSource(ev) {
const sourceToDelete: BatterySourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
private _editorHref(source?: BatterySourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/battery/${source ? encodeURIComponent(source.stat_energy_from) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
source?: BatterySourceTypeEnergyPreference
): EnergyEditorConfig {
return {
kind: "battery",
params: {
statsMetadata: this.statsMetadata,
source: source ? { ...source } : undefined,
battery_sources: preferences.energy_sources.filter(isBatterySource),
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
}
private _sourceIndex(source: BatterySourceTypeEnergyPreference) {
const sources = this.preferences.energy_sources;
const index = sources.indexOf(source);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return sources.findIndex(
(src) =>
isBatterySource(src) && src.stat_energy_from === source.stat_energy_from
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const source = this.preferences.energy_sources.find(
(src): src is BatterySourceTypeEnergyPreference =>
isBatterySource(src) && src.stat_energy_from === key
);
return (
source &&
this._pageConfig(this._editorConfig(this.preferences, source), source)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
source?: BatterySourceTypeEnergyPreference
): EnergyEditorPageConfig {
if (!source) {
return {
editor,
title: this.hass.localize(
"ui.panel.config.energy.battery.add_battery_system"
),
};
}
return {
editor,
title: this._sourceName(source),
delete: {
label: this.hass.localize(
"ui.panel.config.energy.battery.delete_battery_system"
),
action: () => this._deleteSource(source),
},
};
}
private async _saveSource(
source: BatterySourceTypeEnergyPreference,
original?: BatterySourceTypeEnergyPreference
) {
const sources = [...this.preferences.energy_sources];
const index = original ? this._sourceIndex(original) : -1;
if (index === -1) {
sources.push(source);
} else {
sources[index] = source;
}
await this._savePreferences({
...this.preferences,
energy_sources: sources,
});
}
private _deleteSourceClicked(ev) {
ev.stopPropagation();
this._deleteSource(ev.currentTarget.source);
}
private async _deleteSource(
source: BatterySourceTypeEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._sourceIndex(source);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.filter(
(source) => source !== sourceToDelete
(_src, idx) => idx !== index
),
});
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
return [
haStyle,
energyCardStyles,
css`
.row {
height: 58px;
}
.content {
display: flex;
flex-direction: column;
}
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
`,
];
return [haStyle, energyCardStyles];
}
}
@@ -3,17 +3,20 @@ import {
mdiDelete,
mdiDragHorizontalVariant,
mdiFire,
mdiPencil,
mdiPlus,
mdiWater,
} from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import type { LocalizeKeys } from "../../../../common/translations/localize";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import { getEntityAreaId } from "../../../../common/entity/context/get_entity_context";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-card";
import "../../../../components/ha-button";
import "../../../../components/ha-icon-button";
@@ -42,10 +45,12 @@ import {
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsDeviceWaterGasDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
import type { LocalizeKeys } from "../../../../common/translations/localize";
const ICONS: Record<WaterGasResource, string> = {
water: mdiWater,
@@ -67,6 +72,14 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
private get _devices(): DeviceConsumptionEnergyPreference[] {
return getWaterGasDevices(this.preferences, this.resource);
}
@@ -87,15 +100,18 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
}
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const devices = this._devices;
const validation =
this.validationResult?.[getWaterGasDevicesKey(this.resource)];
const labels = computeEnergyDeviceLabels(
this.hass.states,
this.hass.formatEntityName,
devices,
this.statsMetadata
);
return html`
<ha-card>
@@ -128,63 +144,40 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
${
devices.length > 0
? html`
<div class="items-container">
<ha-sortable
handle-selector=".handle"
@item-moved=${this._itemMoved}
>
<div class="devices">
${repeat(
devices,
(device) => device.stat_consumption,
(device, index) => html`
<div class="row" .device=${device}>
<div class="handle">
<ha-svg-icon
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
</div>
${this._renderName(device, labels)}
${this._renderIssueIndicator(
validation?.[index],
index
)}
<ha-icon-button
.label=${this.hass.localize("ui.common.edit")}
@click=${this._editDevice}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize("ui.common.delete")}
@click=${this._deleteDevice}
.device=${device}
.path=${mdiDelete}
></ha-icon-button>
</div>
`
)}
</div>
</ha-sortable>
</div>
<ha-sortable
handle-selector=".handle"
@item-moved=${this._itemMoved}
>
<div class="items">
${repeat(
devices,
(device) => device.stat_consumption,
(device, index) => this._renderDevice(device, index)
)}
</div>
</ha-sortable>
`
: ""
: nothing
}
<div class="row">
<ha-button @click=${this._addDevice} appearance="filled" size="s">
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon
>${this._t("add_device")}</ha-button
>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addDevice}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this._t("add_device")}
</ha-button>
</div>
</ha-card>
`;
}
private _renderName(
private _renderDevice(
device: DeviceConsumptionEnergyPreference,
labels: Record<string, string>
index: number
) {
const name = labels[device.stat_consumption];
const entityState = this.hass.states[device.stat_consumption];
const areaId = getEntityAreaId(
device.stat_consumption,
this.hass.entities,
@@ -193,17 +186,64 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
const area = areaId ? this.hass.areas[areaId] : undefined;
const areaName = area ? computeAreaName(area) : undefined;
return html`
<div class="content">
<span class="label">${name}</span>
${
areaName
? html`<span class="label secondary">${areaName}</span>`
: nothing
}
</div>
<ha-card outlined>
<ha-automation-row
.device=${device}
.href=${this._editorHref(device)}
@click=${this.listPath ? nothing : this._editDevice}
>
${
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${ICONS[this.resource]}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label">${this._deviceName(device)}</span>
${
areaName
? html`<span class="label secondary">${areaName}</span>`
: nothing
}
</div>
${this._renderIssueIndicator(
this.validationResult?.[getWaterGasDevicesKey(this.resource)]?.[
index
],
index
)}
<ha-icon-button
slot="icons"
.label=${this.hass.localize("ui.common.delete")}
.path=${mdiDelete}
.device=${device}
@click=${this._deleteDeviceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
<div class="handle" slot="icons" @click=${stopPropagation}>
<ha-svg-icon .path=${mdiDragHorizontalVariant}></ha-svg-icon>
</div>
</ha-automation-row>
</ha-card>
`;
}
private _deviceLabels = memoizeOne(computeEnergyDeviceLabels);
private _deviceName(device: DeviceConsumptionEnergyPreference) {
return this._deviceLabels(
this.hass.states,
this.hass.formatEntityName,
this._devices,
this.statsMetadata
)[device.stat_consumption];
}
private _renderIssueIndicator(
issues: EnergyValidationIssue[] | undefined,
index: number
@@ -221,11 +261,12 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
return html`
<ha-svg-icon
id=${id}
slot="icons"
class="issue-icon"
.path=${mdiAlertCircle}
aria-label=${label}
></ha-svg-icon>
<ha-tooltip .for=${id} placement="top">${label}</ha-tooltip>
<ha-tooltip slot="icons" .for=${id} placement="top">${label}</ha-tooltip>
`;
}
@@ -241,6 +282,43 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
this._savePreferences(newPrefs);
}
private _addDevice() {
this._openEditor();
}
private _editDevice(ev) {
this._openEditor(ev.currentTarget.device);
}
private _openEditor(device?: DeviceConsumptionEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, device),
});
}
private _editorHref(device?: DeviceConsumptionEnergyPreference) {
return this.listPath
? `${this.listPath}/device/${device ? encodeURIComponent(device.stat_consumption) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
device?: DeviceConsumptionEnergyPreference
): EnergyEditorConfig {
return {
kind: "water_gas_device",
params: {
resource: this.resource,
allowedUnitClass: this._allowedUnitClass(device?.stat_consumption),
statsMetadata: this.statsMetadata,
device: device ? { ...device } : undefined,
device_consumptions: getWaterGasDevices(preferences, this.resource),
saveCallback: (newDevice) => this._saveDevice(newDevice, device),
},
};
}
private _allowedUnitClass(excludeSource?: string) {
return this.resource === "gas"
? getEnergyGasUnitClass(
@@ -252,36 +330,68 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
: undefined;
}
private _editDevice(ev) {
const origDevice: DeviceConsumptionEnergyPreference =
ev.currentTarget.closest(".row").device;
showEnergySettingsDeviceWaterGasDialog(this, {
resource: this.resource,
statsMetadata: this.statsMetadata,
device: { ...origDevice },
allowedUnitClass: this._allowedUnitClass(origDevice.stat_consumption),
device_consumptions: this._devices,
saveCallback: async (newDevice) => {
const newPrefs = this._withDevices(
this._devices.map((d) => (d === origDevice ? newDevice : d))
);
await this._savePreferences(this._sanitizeParents(newPrefs));
},
});
private _deviceIndex(device: DeviceConsumptionEnergyPreference) {
const devices = this._devices;
const index = devices.indexOf(device);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return devices.findIndex(
(d) => d.stat_consumption === device.stat_consumption
);
}
private _addDevice() {
showEnergySettingsDeviceWaterGasDialog(this, {
resource: this.resource,
statsMetadata: this.statsMetadata,
allowedUnitClass: this._allowedUnitClass(),
device_consumptions: this._devices,
saveCallback: async (device) => {
await this._savePreferences(
this._withDevices(this._devices.concat(device))
);
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const device = this._devices.find(
(item) => item.stat_consumption === key
);
return (
device &&
this._pageConfig(this._editorConfig(this.preferences, device), device)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
device?: DeviceConsumptionEnergyPreference
): EnergyEditorPageConfig {
if (!device) {
return {
editor,
title: this._t("add_device"),
};
}
return {
editor,
title: this._deviceName(device),
delete: {
label: this.hass.localize("ui.common.delete"),
action: () => this._deleteDevice(device),
},
});
};
}
private async _saveDevice(
device: DeviceConsumptionEnergyPreference,
original?: DeviceConsumptionEnergyPreference
) {
const devices = [...this._devices];
const index = original ? this._deviceIndex(original) : -1;
if (index === -1) {
devices.push(device);
} else {
devices[index] = device;
}
await this._savePreferences(
this._sanitizeParents(this._withDevices(devices))
);
}
private _sanitizeParents(prefs: EnergyPreferences): EnergyPreferences {
@@ -297,33 +407,49 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
} as EnergyPreferences;
}
private async _deleteDevice(ev) {
const deviceToDelete: DeviceConsumptionEnergyPreference =
ev.currentTarget.device;
private _deleteDeviceClicked(ev) {
ev.stopPropagation();
this._deleteDevice(ev.currentTarget.device);
}
private async _deleteDevice(
device: DeviceConsumptionEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._deviceIndex(device);
if (index === -1) {
return false;
}
try {
const newPrefs = this._sanitizeParents(
this._withDevices(
this._devices.filter((device) => device !== deviceToDelete)
await this._savePreferences(
this._sanitizeParents(
this._withDevices(
this._devices.filter((_device, idx) => idx !== index)
)
)
);
await this._savePreferences(newPrefs);
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
@@ -331,26 +457,6 @@ export class EnergyDeviceSettingsWaterGas extends LitElement {
haStyle,
energyCardStyles,
css`
.row {
height: 58px;
}
.content {
display: flex;
flex-direction: column;
}
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.label.secondary {
color: var(--secondary-text-color);
font-size: 0.9em;
}
.handle {
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
}
.issue-icon {
color: var(--warning-color);
}
@@ -3,16 +3,18 @@ import {
mdiDelete,
mdiDevices,
mdiDragHorizontalVariant,
mdiPencil,
mdiPlus,
} from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import { getEntityAreaId } from "../../../../common/entity/context/get_entity_context";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-card";
import "../../../../components/ha-button";
import "../../../../components/ha-icon-button";
@@ -37,7 +39,10 @@ import {
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsDeviceDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
@@ -54,13 +59,23 @@ export class EnergyDeviceSettings extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
protected render(): TemplateResult {
const labels = computeEnergyDeviceLabels(
this.hass.states,
this.hass.formatEntityName,
this.preferences.device_consumption,
this.statsMetadata
);
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
return html`
<ha-card>
@@ -99,67 +114,42 @@ export class EnergyDeviceSettings extends LitElement {
${
this.preferences.device_consumption.length > 0
? html`
<div class="items-container">
<ha-sortable
handle-selector=".handle"
@item-moved=${this._itemMoved}
>
<div class="devices">
${repeat(
this.preferences.device_consumption,
(device) => device.stat_consumption,
(device, index) => html`
<div class="row" .device=${device}>
<div class="handle">
<ha-svg-icon
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
</div>
${this._renderName(device, labels)}
${this._renderIssueIndicator(
this.validationResult?.device_consumption[
index
],
index
)}
<ha-icon-button
.label=${this.hass.localize("ui.common.edit")}
@click=${this._editDevice}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize("ui.common.delete")}
@click=${this._deleteDevice}
.device=${device}
.path=${mdiDelete}
></ha-icon-button>
</div>
`
)}
</div>
</ha-sortable>
</div>
<ha-sortable
handle-selector=".handle"
@item-moved=${this._itemMoved}
>
<div class="items">
${repeat(
this.preferences.device_consumption,
(device) => device.stat_consumption,
(device, index) => this._renderDevice(device, index)
)}
</div>
</ha-sortable>
`
: ""
: nothing
}
<div class="row">
<ha-button @click=${this._addDevice} appearance="filled" size="s">
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.device_consumption.add_device"
)}</ha-button
>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addDevice}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.device_consumption.add_device"
)}
</ha-button>
</div>
</ha-card>
`;
}
private _renderName(
private _renderDevice(
device: DeviceConsumptionEnergyPreference,
labels: Record<string, string>
index: number
) {
const name = labels[device.stat_consumption];
const entityState = this.hass.states[device.stat_consumption];
const areaId = getEntityAreaId(
device.stat_consumption,
this.hass.entities,
@@ -168,17 +158,62 @@ export class EnergyDeviceSettings extends LitElement {
const area = areaId ? this.hass.areas[areaId] : undefined;
const areaName = area ? computeAreaName(area) : undefined;
return html`
<div class="content">
<span class="label">${name}</span>
${
areaName
? html`<span class="label secondary">${areaName}</span>`
: nothing
}
</div>
<ha-card outlined>
<ha-automation-row
.device=${device}
.href=${this._editorHref(device)}
@click=${this.listPath ? nothing : this._editDevice}
>
${
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiDevices}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label">${this._deviceName(device)}</span>
${
areaName
? html`<span class="label secondary">${areaName}</span>`
: nothing
}
</div>
${this._renderIssueIndicator(
this.validationResult?.device_consumption[index],
index
)}
<ha-icon-button
slot="icons"
.label=${this.hass.localize("ui.common.delete")}
.path=${mdiDelete}
.device=${device}
@click=${this._deleteDeviceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
<div class="handle" slot="icons" @click=${stopPropagation}>
<ha-svg-icon .path=${mdiDragHorizontalVariant}></ha-svg-icon>
</div>
</ha-automation-row>
</ha-card>
`;
}
private _deviceLabels = memoizeOne(computeEnergyDeviceLabels);
private _deviceName(device: DeviceConsumptionEnergyPreference) {
return this._deviceLabels(
this.hass.states,
this.hass.formatEntityName,
this.preferences.device_consumption,
this.statsMetadata
)[device.stat_consumption];
}
private _renderIssueIndicator(
issues: EnergyValidationIssue[] | undefined,
index: number
@@ -196,11 +231,12 @@ export class EnergyDeviceSettings extends LitElement {
return html`
<ha-svg-icon
id=${id}
slot="icons"
class="issue-icon"
.path=${mdiAlertCircle}
aria-label=${label}
></ha-svg-icon>
<ha-tooltip .for=${id} placement="top">${label}</ha-tooltip>
<ha-tooltip slot="icons" .for=${id} placement="top">${label}</ha-tooltip>
`;
}
@@ -219,40 +255,105 @@ export class EnergyDeviceSettings extends LitElement {
this._savePreferences(newPrefs);
}
private _addDevice() {
this._openEditor();
}
private _editDevice(ev) {
const origDevice: DeviceConsumptionEnergyPreference =
ev.currentTarget.closest(".row").device;
showEnergySettingsDeviceDialog(this, {
statsMetadata: this.statsMetadata,
device: { ...origDevice },
device_consumptions: this.preferences
.device_consumption as DeviceConsumptionEnergyPreference[],
saveCallback: async (newDevice) => {
const newPrefs = {
...this.preferences,
device_consumption: this.preferences.device_consumption.map((d) =>
d === origDevice ? newDevice : d
),
};
this._sanitizeParents(newPrefs);
await this._savePreferences(newPrefs);
},
this._openEditor(ev.currentTarget.device);
}
private _openEditor(device?: DeviceConsumptionEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, device),
});
}
private _addDevice() {
showEnergySettingsDeviceDialog(this, {
statsMetadata: this.statsMetadata,
device_consumptions: this.preferences
.device_consumption as DeviceConsumptionEnergyPreference[],
saveCallback: async (device) => {
await this._savePreferences({
...this.preferences,
device_consumption:
this.preferences.device_consumption.concat(device),
});
private _editorHref(device?: DeviceConsumptionEnergyPreference) {
return this.listPath
? `${this.listPath}/device/${device ? encodeURIComponent(device.stat_consumption) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
device?: DeviceConsumptionEnergyPreference
): EnergyEditorConfig {
return {
kind: "device",
params: {
statsMetadata: this.statsMetadata,
device: device ? { ...device } : undefined,
device_consumptions: preferences.device_consumption,
saveCallback: (newDevice) => this._saveDevice(newDevice, device),
},
});
};
}
private _deviceIndex(device: DeviceConsumptionEnergyPreference) {
const devices = this.preferences.device_consumption;
const index = devices.indexOf(device);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return devices.findIndex(
(d) => d.stat_consumption === device.stat_consumption
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const device = this.preferences.device_consumption.find(
(item) => item.stat_consumption === key
);
return (
device &&
this._pageConfig(this._editorConfig(this.preferences, device), device)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
device?: DeviceConsumptionEnergyPreference
): EnergyEditorPageConfig {
if (!device) {
return {
editor,
title: this.hass.localize(
"ui.panel.config.energy.device_consumption.add_device"
),
};
}
return {
editor,
title: this._deviceName(device),
delete: {
label: this.hass.localize("ui.common.delete"),
action: () => this._deleteDevice(device),
},
};
}
private async _saveDevice(
device: DeviceConsumptionEnergyPreference,
original?: DeviceConsumptionEnergyPreference
) {
const devices = [...this.preferences.device_consumption];
const index = original ? this._deviceIndex(original) : -1;
if (index === -1) {
devices.push(device);
} else {
devices[index] = device;
}
const newPrefs = { ...this.preferences, device_consumption: devices };
this._sanitizeParents(newPrefs);
await this._savePreferences(newPrefs);
}
private _sanitizeParents(prefs: EnergyPreferences) {
@@ -264,35 +365,50 @@ export class EnergyDeviceSettings extends LitElement {
});
}
private async _deleteDevice(ev) {
const deviceToDelete: DeviceConsumptionEnergyPreference =
ev.currentTarget.device;
private _deleteDeviceClicked(ev) {
ev.stopPropagation();
this._deleteDevice(ev.currentTarget.device);
}
private async _deleteDevice(
device: DeviceConsumptionEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._deviceIndex(device);
if (index === -1) {
return false;
}
try {
const newPrefs = {
...this.preferences,
device_consumption: this.preferences.device_consumption.filter(
(device) => device !== deviceToDelete
(_device, idx) => idx !== index
),
};
this._sanitizeParents(newPrefs);
await this._savePreferences(newPrefs);
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
@@ -300,26 +416,6 @@ export class EnergyDeviceSettings extends LitElement {
haStyle,
energyCardStyles,
css`
.row {
height: 58px;
}
.content {
display: flex;
flex-direction: column;
}
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.label.secondary {
color: var(--secondary-text-color);
font-size: 0.9em;
}
.handle {
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
}
.issue-icon {
color: var(--warning-color);
}
@@ -1,11 +1,15 @@
import { mdiDelete, mdiFire, mdiPencil, mdiPlus } from "@mdi/js";
import { mdiDelete, mdiFire, mdiPlus } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { html, LitElement } from "lit";
import { html, LitElement, nothing } from "lit";
import memoizeOne from "memoize-one";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-button";
import "../../../../components/ha-card";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-svg-icon";
import type {
EnergyPreferences,
EnergyPreferencesValidation,
@@ -25,10 +29,17 @@ import {
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsGasDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
const isGasSource = (
source: EnergyPreferences["energy_sources"][number]
): source is GasSourceTypeEnergyPreference => source.type === "gas";
@customElement("ha-energy-gas-settings")
export class EnergyGasSettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -42,12 +53,29 @@ export class EnergyGasSettings extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const gasSources: GasSourceTypeEnergyPreference[] = [];
const gasValidation: EnergyValidationIssue[][] = [];
this.preferences.energy_sources.forEach((source, idx) => {
if (source.type !== "gas") {
if (!isGasSource(source)) {
return;
}
gasSources.push(source);
@@ -85,141 +113,230 @@ export class EnergyGasSettings extends LitElement {
${
gasSources.length > 0
? html`
<div class="items-container">
<div class="items">
${gasSources.map((source) => {
const entityState =
this.hass.states[source.stat_energy_from];
return html`
<div class="row" .source=${source}>
${
entityState?.attributes.icon
? html`<ha-icon
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiFire}
></ha-svg-icon>`
}
<span class="content"
>${
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
}</span
<ha-card outlined>
<ha-automation-row
.source=${source}
.href=${this._editorHref(source)}
@click=${this.listPath ? nothing : this._editSource}
>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.gas.edit_gas_source"
)}
@click=${this._editSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.gas.delete_gas_source"
)}
@click=${this._deleteSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
${
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiFire}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label"
>${this._sourceName(source)}</span
>
</div>
<ha-icon-button
slot="icons"
.label=${this.hass.localize(
"ui.panel.config.energy.gas.delete_gas_source"
)}
.path=${mdiDelete}
.source=${source}
@click=${this._deleteSourceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`;
})}
</div>
`
: ""
: nothing
}
<div class="row">
<ha-button @click=${this._addSource} appearance="filled" size="s">
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.gas.add_gas_source"
)}</ha-button
>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize("ui.panel.config.energy.gas.add_gas_source")}
</ha-button>
</div>
</ha-card>
`;
}
private _sourceName(source: GasSourceTypeEnergyPreference) {
return (
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
);
}
private _addSource() {
showEnergySettingsGasDialog(this, {
statsMetadata: this.statsMetadata,
allowedGasUnitClass: getEnergyGasUnitClass(
this.preferences,
undefined,
this.statsMetadata,
"source"
),
gas_sources: this.preferences.energy_sources.filter(
(src) => src.type === "gas"
) as GasSourceTypeEnergyPreference[],
saveCallback: async (source) => {
delete source.unit_of_measurement;
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.concat(source),
});
},
});
this._openEditor();
}
private _editSource(ev) {
const origSource: GasSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
showEnergySettingsGasDialog(this, {
source: { ...origSource },
statsMetadata: this.statsMetadata,
allowedGasUnitClass: getEnergyGasUnitClass(
this.preferences,
origSource.stat_energy_from,
this.statsMetadata,
"source"
),
gas_sources: this.preferences.energy_sources.filter(
(src) => src.type === "gas"
) as GasSourceTypeEnergyPreference[],
saveCallback: async (newSource) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src === origSource ? newSource : src
),
});
},
this._openEditor(ev.currentTarget.source);
}
private _openEditor(source?: GasSourceTypeEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, source),
});
}
private async _deleteSource(ev) {
const sourceToDelete: GasSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
private _editorHref(source?: GasSourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/gas/${source ? encodeURIComponent(source.stat_energy_from) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
source?: GasSourceTypeEnergyPreference
): EnergyEditorConfig {
return {
kind: "gas",
params: {
source: source ? { ...source } : undefined,
statsMetadata: this.statsMetadata,
allowedGasUnitClass: getEnergyGasUnitClass(
preferences,
source?.stat_energy_from,
this.statsMetadata,
"source"
),
gas_sources: preferences.energy_sources.filter(isGasSource),
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
}
private _sourceIndex(source: GasSourceTypeEnergyPreference) {
const sources = this.preferences.energy_sources;
const index = sources.indexOf(source);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return sources.findIndex(
(src) =>
isGasSource(src) && src.stat_energy_from === source.stat_energy_from
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const source = this.preferences.energy_sources.find(
(src): src is GasSourceTypeEnergyPreference =>
isGasSource(src) && src.stat_energy_from === key
);
return (
source &&
this._pageConfig(this._editorConfig(this.preferences, source), source)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
source?: GasSourceTypeEnergyPreference
): EnergyEditorPageConfig {
if (!source) {
return {
editor,
title: this.hass.localize("ui.panel.config.energy.gas.add_gas_source"),
};
}
return {
editor,
title: this._sourceName(source),
delete: {
label: this.hass.localize(
"ui.panel.config.energy.gas.delete_gas_source"
),
action: () => this._deleteSource(source),
},
};
}
private async _saveSource(
source: GasSourceTypeEnergyPreference,
original?: GasSourceTypeEnergyPreference
) {
const sources = [...this.preferences.energy_sources];
const index = original ? this._sourceIndex(original) : -1;
if (index === -1) {
delete source.unit_of_measurement;
sources.push(source);
} else {
sources[index] = source;
}
await this._savePreferences({
...this.preferences,
energy_sources: sources,
});
}
private _deleteSourceClicked(ev) {
ev.stopPropagation();
this._deleteSource(ev.currentTarget.source);
}
private async _deleteSource(
source: GasSourceTypeEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._sourceIndex(source);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.filter(
(source) => source !== sourceToDelete
(_src, idx) => idx !== index
),
});
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
@@ -1,8 +1,11 @@
import { mdiDelete, mdiPencil, mdiPlus, mdiTransmissionTower } from "@mdi/js";
import { mdiDelete, mdiPlus, mdiTransmissionTower } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { html, LitElement, nothing } from "lit";
import memoizeOne from "memoize-one";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-button";
import "../../../../components/ha-card";
import "../../../../components/ha-icon-button";
@@ -30,10 +33,21 @@ import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { brandsUrl } from "../../../../util/brands-url";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsGridDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
const isGridSource = (
source: EnergyPreferences["energy_sources"][number]
): source is GridSourceTypeEnergyPreference => source.type === "grid";
// At least one of import/export/power must exist (enforced by validation)
const primaryStat = (source: GridSourceTypeEnergyPreference) =>
(source.stat_energy_from || source.stat_energy_to || source.stat_rate)!;
@customElement("ha-energy-grid-settings")
export class EnergyGridSettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -47,6 +61,14 @@ export class EnergyGridSettings extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
@state() private _co2ConfigEntry?: ConfigEntry;
protected firstUpdated() {
@@ -54,11 +76,20 @@ export class EnergyGridSettings extends LitElement {
}
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const gridSources: GridSourceTypeEnergyPreference[] = [];
const gridValidation: EnergyValidationIssue[][] = [];
this.preferences.energy_sources.forEach((source, idx) => {
if (source.type !== "grid") {
if (!isGridSource(source)) {
return;
}
gridSources.push(source);
@@ -107,82 +138,76 @@ export class EnergyGridSettings extends LitElement {
${
gridSources.length > 0
? html`
<div class="items-container">
${gridSources.map((source, idx) => {
// At least one of import/export/power must exist (enforced by validation)
const primaryStat = (source.stat_energy_from ||
source.stat_energy_to ||
source.stat_rate)!;
const primaryEntityState = this.hass.states[primaryStat];
<div class="items">
${gridSources.map((source) => {
const stat = primaryStat(source);
const entityState = this.hass.states[stat];
return html`
<div class="row" .source=${source} .sourceIndex=${idx}>
${
primaryEntityState?.attributes.icon
? html`<ha-icon
.icon=${primaryEntityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiTransmissionTower}
></ha-svg-icon>`
}
<div class="content">
<span class="label"
>${
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
primaryStat,
this.statsMetadata?.[primaryStat]
)
}</span
>
<ha-card outlined>
<ha-automation-row
.source=${source}
.href=${this._editorHref(source)}
@click=${this.listPath ? nothing : this._editSource}
>
${
source.stat_energy_from &&
source.stat_energy_to &&
!source.name
? html`<span class="label secondary"
>${getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_to,
this.statsMetadata?.[
source.stat_energy_to
]
)}</span
>`
: nothing
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiTransmissionTower}
></ha-svg-icon>`
}
</div>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.edit_connection"
)}
@click=${this._editSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.delete_connection"
)}
@click=${this._deleteSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
<div slot="header" class="row-header">
<span class="label"
>${this._sourceName(source)}</span
>
${
source.stat_energy_from &&
source.stat_energy_to &&
!source.name
? html`<span class="label secondary"
>${getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_to,
this.statsMetadata?.[
source.stat_energy_to
]
)}</span
>`
: nothing
}
</div>
<ha-icon-button
slot="icons"
.label=${this.hass.localize(
"ui.panel.config.energy.grid.delete_connection"
)}
.path=${mdiDelete}
.source=${source}
@click=${this._deleteSourceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`;
})}
</div>
`
: nothing
}
<div class="row">
<ha-button @click=${this._addSource} appearance="filled" size="s">
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.grid.add_connection"
)}</ha-button
>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
${this.hass.localize("ui.panel.config.energy.grid.add_connection")}
</ha-button>
<h3>
${this.hass.localize(
@@ -192,50 +217,54 @@ export class EnergyGridSettings extends LitElement {
${
this._co2ConfigEntry
? html`
<div class="items-container">
<div class="row" .entry=${this._co2ConfigEntry}>
<img
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: "co2signal",
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>
<span class="content">${this._co2ConfigEntry.title}</span>
<ha-icon-button
.path=${mdiPencil}
href=${`/config/integrations/integration/${this._co2ConfigEntry?.domain}`}
<div class="items">
<ha-card outlined>
<ha-automation-row
.href=${`/config/integrations/integration/${this._co2ConfigEntry.domain}`}
>
</ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.remove_co2_signal"
)}
@click=${this._removeCO2Sensor}
.path=${mdiDelete}
></ha-icon-button>
</div>
<img
slot="leading-icon"
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: "co2signal",
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>
<div slot="header" class="row-header">
<span class="label"
>${this._co2ConfigEntry.title}</span
>
</div>
<ha-icon-button
slot="icons"
.label=${this.hass.localize(
"ui.panel.config.energy.grid.remove_co2_signal"
)}
.path=${mdiDelete}
@click=${this._removeCO2Sensor}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
</div>
`
: html`
<div class="row">
<ha-button
@click=${this._addCO2Sensor}
appearance="filled"
size="s"
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.grid.add_co2_signal"
)}
</ha-button>
</div>
<ha-button
@click=${this._addCO2Sensor}
appearance="filled"
size="s"
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.grid.add_co2_signal"
)}
</ha-button>
`
}
</div>
@@ -243,6 +272,19 @@ export class EnergyGridSettings extends LitElement {
`;
}
private _sourceName(source: GridSourceTypeEnergyPreference) {
const stat = primaryStat(source);
return (
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
stat,
this.statsMetadata?.[stat]
)
);
}
private async _fetchCO2SignalConfigEntries() {
const entries = await getConfigEntries(this.hass, { domain: "co2signal" });
this._co2ConfigEntry = entries.length ? entries[0] : undefined;
@@ -257,8 +299,8 @@ export class EnergyGridSettings extends LitElement {
});
}
private async _removeCO2Sensor(ev) {
const entryId = ev.currentTarget.closest(".row").entry.entry_id;
private async _removeCO2Sensor(ev: Event) {
ev.stopPropagation();
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_integration"),
@@ -267,114 +309,160 @@ export class EnergyGridSettings extends LitElement {
return;
}
await deleteConfigEntry(this.hass, entryId);
await deleteConfigEntry(this.hass, this._co2ConfigEntry!.entry_id);
this._fetchCO2SignalConfigEntries();
}
private _getGridSources(): GridSourceTypeEnergyPreference[] {
return this.preferences.energy_sources.filter(
(src): src is GridSourceTypeEnergyPreference => src.type === "grid"
);
}
private _addSource() {
showEnergySettingsGridDialog(this, {
statsMetadata: this.statsMetadata,
grid_sources: this._getGridSources(),
saveCallback: async (source) => {
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: [...this.preferences.energy_sources, source],
};
await this._savePreferences(preferences);
},
});
this._openEditor();
}
private _editSource(ev) {
const row = ev.currentTarget.closest(".row");
const origSource: GridSourceTypeEnergyPreference = row.source;
const sourceIndex: number = row.sourceIndex;
this._openEditor(ev.currentTarget.source);
}
showEnergySettingsGridDialog(this, {
statsMetadata: this.statsMetadata,
source: { ...origSource },
grid_sources: this._getGridSources(),
saveCallback: async (newSource) => {
const nonGridSources = this.preferences.energy_sources.filter(
(src) => src.type !== "grid"
);
const updatedGrids = this._getGridSources().map((src, idx) =>
idx === sourceIndex ? newSource : src
);
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: [...nonGridSources, ...updatedGrids],
};
await this._savePreferences(preferences);
},
private _openEditor(source?: GridSourceTypeEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, source),
});
}
private async _deleteSource(ev) {
const row = ev.currentTarget.closest(".row");
const sourceIndex: number = row.sourceIndex;
private _editorHref(source?: GridSourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/grid/${source ? encodeURIComponent(primaryStat(source)) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
source?: GridSourceTypeEnergyPreference
): EnergyEditorConfig {
return {
kind: "grid",
params: {
statsMetadata: this.statsMetadata,
source: source ? { ...source } : undefined,
grid_sources: preferences.energy_sources.filter(isGridSource),
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
}
private _sourceIndex(source: GridSourceTypeEnergyPreference) {
const sources = this.preferences.energy_sources;
const index = sources.indexOf(source);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
const stat = primaryStat(source);
return sources.findIndex(
(src) => isGridSource(src) && primaryStat(src) === stat
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const source = this.preferences.energy_sources.find(
(src): src is GridSourceTypeEnergyPreference =>
isGridSource(src) && primaryStat(src) === key
);
return (
source &&
this._pageConfig(this._editorConfig(this.preferences, source), source)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
source?: GridSourceTypeEnergyPreference
): EnergyEditorPageConfig {
if (!source) {
return {
editor,
title: this.hass.localize("ui.panel.config.energy.grid.add_connection"),
};
}
return {
editor,
title: this._sourceName(source),
delete: {
label: this.hass.localize(
"ui.panel.config.energy.grid.delete_connection"
),
action: () => this._deleteSource(source),
},
};
}
private async _saveSource(
source: GridSourceTypeEnergyPreference,
original?: GridSourceTypeEnergyPreference
) {
const sources = [...this.preferences.energy_sources];
const index = original ? this._sourceIndex(original) : -1;
if (index === -1) {
sources.push(source);
} else {
sources[index] = source;
}
await this._savePreferences({
...this.preferences,
energy_sources: sources,
});
}
private _deleteSourceClicked(ev) {
ev.stopPropagation();
this._deleteSource(ev.currentTarget.source);
}
private async _deleteSource(
source: GridSourceTypeEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const nonGridSources = this.preferences.energy_sources.filter(
(src) => src.type !== "grid"
);
const updatedGrids = this._getGridSources().filter(
(_, idx) => idx !== sourceIndex
);
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: [...nonGridSources, ...updatedGrids],
};
await this._savePreferences(preferences);
const index = this._sourceIndex(source);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.filter(
(_src, idx) => idx !== index
),
});
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
try {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
}
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
return [
haStyle,
energyCardStyles,
css`
.row {
height: 58px;
}
.content {
display: flex;
flex-direction: column;
}
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.label.secondary {
color: var(--secondary-text-color);
font-size: 0.9em;
}
`,
];
return [haStyle, energyCardStyles];
}
}
@@ -1,9 +1,12 @@
import { mdiDelete, mdiHome, mdiPencil, mdiPlus } from "@mdi/js";
import { mdiDelete, mdiHome, mdiPlus } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { html, LitElement } from "lit";
import { html, LitElement, nothing } from "lit";
import memoizeOne from "memoize-one";
import { customElement, property, state } from "lit/decorators";
import type { ContextType } from "@lit/context";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-card";
import "../../../../components/ha-button";
import "../../../../components/ha-icon-button";
@@ -26,10 +29,17 @@ import {
} from "../../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { showEnergySettingsHomeDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
const isHomeSource = (
source: EnergyPreferences["energy_sources"][number]
): source is HomeSourceTypeEnergyPreference => source.type === "home";
@customElement("ha-energy-home-settings")
export class EnergyHomeSettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -52,12 +62,29 @@ export class EnergyHomeSettings extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const homeSources: HomeSourceTypeEnergyPreference[] = [];
const homeValidation: EnergyValidationIssue[][] = [];
this.preferences.energy_sources.forEach((source, idx) => {
if (source.type !== "home") {
if (!isHomeSource(source)) {
return;
}
homeSources.push(source);
@@ -87,116 +114,198 @@ export class EnergyHomeSettings extends LitElement {
${
homeSources.length > 0
? html`
<div class="items-container">
<div class="items">
${homeSources.map((source) => {
const entityState = this._states[source.stat_energy_to];
return html`
<div class="row" .source=${source}>
${
entityState?.attributes.icon
? html`<ha-icon
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiHome}
></ha-svg-icon>`
}
<span class="content"
>${
source.name ||
this._hassConfig.config.location_name
}</span
<ha-card outlined>
<ha-automation-row
.source=${source}
.href=${this._editorHref(source)}
@click=${this.listPath ? nothing : this._editSource}
>
<ha-icon-button
.label=${this._i18n.localize(
"ui.panel.config.energy.home.edit_home_meter"
)}
@click=${this._editSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this._i18n.localize(
"ui.panel.config.energy.home.remove_home_meter"
)}
@click=${this._deleteSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
${
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiHome}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label"
>${this._sourceName(source)}</span
>
</div>
<ha-icon-button
slot="icons"
.label=${this._i18n.localize(
"ui.panel.config.energy.home.remove_home_meter"
)}
.path=${mdiDelete}
.source=${source}
@click=${this._deleteSourceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`;
})}
</div>
`
: ""
: nothing
}
${
homeSources.length === 0
? html`
<div class="row">
<ha-button
@click=${this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this._i18n.localize(
"ui.panel.config.energy.home.add_home_meter"
)}
</ha-button>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this._i18n.localize(
"ui.panel.config.energy.home.add_home_meter"
)}
</ha-button>
`
: ""
: nothing
}
</div>
</ha-card>
`;
}
private _sourceName(source: HomeSourceTypeEnergyPreference) {
return source.name || this._hassConfig.config.location_name;
}
private _addSource() {
showEnergySettingsHomeDialog(this, {
hass: this.hass,
saveCallback: async (source) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.concat(source),
});
},
});
this._openEditor();
}
private _editSource(ev) {
const origSource: HomeSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
showEnergySettingsHomeDialog(this, {
hass: this.hass,
source: { ...origSource },
saveCallback: async (newSource) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src === origSource ? newSource : src
),
});
this._openEditor(ev.currentTarget.source);
}
private _openEditor(source?: HomeSourceTypeEnergyPreference) {
showEnergySettingsDialog(this, { editor: this._editorConfig(source) });
}
private _editorHref(source?: HomeSourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/home/${source ? encodeURIComponent(source.stat_energy_to) : "new"}`
: undefined;
}
private _editorConfig(
source?: HomeSourceTypeEnergyPreference
): EnergyEditorConfig {
return {
kind: "home",
params: {
source: source ? { ...source } : undefined,
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
}
private _sourceIndex(source: HomeSourceTypeEnergyPreference) {
const sources = this.preferences.energy_sources;
const index = sources.indexOf(source);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return sources.findIndex(
(src) => isHomeSource(src) && src.stat_energy_to === source.stat_energy_to
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig());
}
const source = this.preferences.energy_sources.find(
(src): src is HomeSourceTypeEnergyPreference =>
isHomeSource(src) && src.stat_energy_to === key
);
return source && this._pageConfig(this._editorConfig(source), source);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
source?: HomeSourceTypeEnergyPreference
): EnergyEditorPageConfig {
if (!source) {
return {
editor,
title: this._i18n.localize(
"ui.panel.config.energy.home.add_home_meter"
),
};
}
return {
editor,
title: this._sourceName(source),
delete: {
label: this._i18n.localize(
"ui.panel.config.energy.home.remove_home_meter"
),
action: () => this._deleteSource(source),
},
};
}
private async _saveSource(
source: HomeSourceTypeEnergyPreference,
original?: HomeSourceTypeEnergyPreference
) {
const sources = [...this.preferences.energy_sources];
const index = original ? this._sourceIndex(original) : -1;
if (index === -1) {
sources.push(source);
} else {
sources[index] = source;
}
await this._savePreferences({
...this.preferences,
energy_sources: sources,
});
}
private async _deleteSource(ev) {
const sourceToDelete: HomeSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
private _deleteSourceClicked(ev) {
ev.stopPropagation();
this._deleteSource(ev.currentTarget.source);
}
private async _deleteSource(
source: HomeSourceTypeEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this._i18n.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._sourceIndex(source);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.filter(
(source) => source !== sourceToDelete
(_src, idx) => idx !== index
),
});
} catch (err: any) {
@@ -206,12 +315,15 @@ export class EnergyHomeSettings extends LitElement {
{ error: err.message }
),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
@@ -1,11 +1,15 @@
import { mdiDelete, mdiPencil, mdiPlus, mdiSolarPower } from "@mdi/js";
import { mdiDelete, mdiPlus, mdiSolarPower } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { html, LitElement } from "lit";
import { html, LitElement, nothing } from "lit";
import memoizeOne from "memoize-one";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-card";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-button";
import "../../../../components/ha-card";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-svg-icon";
import type {
EnergyInfo,
EnergyPreferences,
@@ -17,16 +21,23 @@ import { saveEnergyPreferences } from "../../../../data/energy";
import type { StatisticsMetaData } from "../../../../data/recorder";
import { getStatisticLabel } from "../../../../data/recorder";
import {
showConfirmationDialog,
showAlertDialog,
showConfirmationDialog,
} from "../../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsSolarDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
const isSolarSource = (
source: EnergyPreferences["energy_sources"][number]
): source is SolarSourceTypeEnergyPreference => source.type === "solar";
@customElement("ha-energy-solar-settings")
export class EnergySolarSettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -43,12 +54,29 @@ export class EnergySolarSettings extends LitElement {
@property({ attribute: false })
public info?: EnergyInfo;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const solarSources: SolarSourceTypeEnergyPreference[] = [];
const solarValidation: EnergyValidationIssue[][] = [];
this.preferences.energy_sources.forEach((source, idx) => {
if (source.type !== "solar") {
if (!isSolarSource(source)) {
return;
}
solarSources.push(source);
@@ -88,146 +116,237 @@ export class EnergySolarSettings extends LitElement {
${
solarSources.length > 0
? html`
<div class="items-container">
<div class="items">
${solarSources.map((source) => {
const entityState =
this.hass.states[source.stat_energy_from];
return html`
<div class="row" .source=${source}>
${
entityState?.attributes.icon
? html`<ha-icon
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiSolarPower}
></ha-svg-icon>`
}
<span class="content"
>${
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
}</span
<ha-card outlined>
<ha-automation-row
.source=${source}
.href=${this._editorHref(source)}
@click=${this.listPath ? nothing : this._editSource}
>
${
this.info
? html`
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.solar.edit_solar_production"
)}
@click=${this._editSource}
.path=${mdiPencil}
></ha-icon-button>
`
: ""
}
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.solar.delete_solar_production"
)}
@click=${this._deleteSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
${
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiSolarPower}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label"
>${this._sourceName(source)}</span
>
</div>
<ha-icon-button
slot="icons"
.label=${this.hass.localize(
"ui.panel.config.energy.solar.delete_solar_production"
)}
.path=${mdiDelete}
.source=${source}
@click=${this._deleteSourceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`;
})}
</div>
`
: ""
: nothing
}
${
this.info
? html`
<div class="row">
<ha-button
@click=${this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.solar.add_solar_production"
)}
</ha-button>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.solar.add_solar_production"
)}
</ha-button>
`
: ""
: nothing
}
</div>
</ha-card>
`;
}
private _sourceName(source: SolarSourceTypeEnergyPreference) {
return (
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
);
}
private _addSource() {
showEnergySettingsSolarDialog(this, {
statsMetadata: this.statsMetadata,
info: this.info!,
solar_sources: this.preferences.energy_sources.filter(
(src) => src.type === "solar"
) as SolarSourceTypeEnergyPreference[],
saveCallback: async (source) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.concat(source),
});
},
});
this._openEditor();
}
private _editSource(ev) {
const origSource: SolarSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
showEnergySettingsSolarDialog(this, {
statsMetadata: this.statsMetadata,
info: this.info!,
source: { ...origSource },
solar_sources: this.preferences.energy_sources.filter(
(src) => src.type === "solar"
) as SolarSourceTypeEnergyPreference[],
saveCallback: async (newSource) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src === origSource ? newSource : src
),
});
},
if (!this.info) {
return;
}
this._openEditor(ev.currentTarget.source);
}
private _openEditor(source?: SolarSourceTypeEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, source),
});
}
private async _deleteSource(ev) {
const sourceToDelete: SolarSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
private _editorHref(source?: SolarSourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/solar/${source ? encodeURIComponent(source.stat_energy_from) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
source?: SolarSourceTypeEnergyPreference
): EnergyEditorConfig {
return {
kind: "solar",
params: {
statsMetadata: this.statsMetadata,
info: this.info!,
source: source ? { ...source } : undefined,
solar_sources: preferences.energy_sources.filter(isSolarSource),
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
}
private _sourceIndex(source: SolarSourceTypeEnergyPreference) {
const sources = this.preferences.energy_sources;
const index = sources.indexOf(source);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return sources.findIndex(
(src) =>
isSolarSource(src) && src.stat_energy_from === source.stat_energy_from
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const source = this.preferences.energy_sources.find(
(src): src is SolarSourceTypeEnergyPreference =>
isSolarSource(src) && src.stat_energy_from === key
);
return (
source &&
this._pageConfig(this._editorConfig(this.preferences, source), source)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
source?: SolarSourceTypeEnergyPreference
): EnergyEditorPageConfig {
if (!source) {
return {
editor,
title: this.hass.localize(
"ui.panel.config.energy.solar.add_solar_production"
),
};
}
return {
editor,
title: this._sourceName(source),
delete: {
label: this.hass.localize(
"ui.panel.config.energy.solar.delete_solar_production"
),
action: () => this._deleteSource(source),
},
};
}
private async _saveSource(
source: SolarSourceTypeEnergyPreference,
original?: SolarSourceTypeEnergyPreference
) {
const sources = [...this.preferences.energy_sources];
const index = original ? this._sourceIndex(original) : -1;
if (index === -1) {
sources.push(source);
} else {
sources[index] = source;
}
await this._savePreferences({
...this.preferences,
energy_sources: sources,
});
}
private _deleteSourceClicked(ev) {
ev.stopPropagation();
this._deleteSource(ev.currentTarget.source);
}
private async _deleteSource(
source: SolarSourceTypeEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._sourceIndex(source);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.filter(
(source) => source !== sourceToDelete
(_src, idx) => idx !== index
),
});
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
@@ -1,11 +1,15 @@
import { mdiDelete, mdiWater, mdiPencil, mdiPlus } from "@mdi/js";
import { mdiDelete, mdiPlus, mdiWater } from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { html, LitElement } from "lit";
import { html, LitElement, nothing } from "lit";
import memoizeOne from "memoize-one";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-card";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-button";
import "../../../../components/ha-card";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-svg-icon";
import type {
EnergyPreferences,
EnergyPreferencesValidation,
@@ -22,10 +26,17 @@ import {
import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { documentationUrl } from "../../../../util/documentation-url";
import { showEnergySettingsWaterDialog } from "../dialogs/show-dialogs-energy";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
const isWaterSource = (
source: EnergyPreferences["energy_sources"][number]
): source is WaterSourceTypeEnergyPreference => source.type === "water";
@customElement("ha-energy-water-settings")
export class EnergyWaterSettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -39,12 +50,29 @@ export class EnergyWaterSettings extends LitElement {
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const waterSources: WaterSourceTypeEnergyPreference[] = [];
const waterValidation: EnergyValidationIssue[][] = [];
this.preferences.energy_sources.forEach((source, idx) => {
if (source.type !== "water") {
if (!isWaterSource(source)) {
return;
}
waterSources.push(source);
@@ -84,129 +112,228 @@ export class EnergyWaterSettings extends LitElement {
${
waterSources.length > 0
? html`
<div class="items-container">
<div class="items">
${waterSources.map((source) => {
const entityState =
this.hass.states[source.stat_energy_from];
return html`
<div class="row" .source=${source}>
${
entityState?.attributes.icon
? html`<ha-icon
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiWater}
></ha-svg-icon>`
}
<span class="content"
>${
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
}</span
<ha-card outlined>
<ha-automation-row
.source=${source}
.href=${this._editorHref(source)}
@click=${this.listPath ? nothing : this._editSource}
>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.water.edit_water_source"
)}
@click=${this._editSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.water.delete_water_source"
)}
@click=${this._deleteSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
${
entityState?.attributes.icon
? html`<ha-icon
slot="leading-icon"
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
slot="leading-icon"
.path=${mdiWater}
></ha-svg-icon>`
}
<div slot="header" class="row-header">
<span class="label"
>${this._sourceName(source)}</span
>
</div>
<ha-icon-button
slot="icons"
.label=${this.hass.localize(
"ui.panel.config.energy.water.delete_water_source"
)}
.path=${mdiDelete}
.source=${source}
@click=${this._deleteSourceClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`;
})}
</div>
`
: ""
: nothing
}
<div class="row">
<ha-button @click=${this._addSource} appearance="filled" size="s">
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.water.add_water_source"
)}</ha-button
>
</div>
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addSource}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.water.add_water_source"
)}
</ha-button>
</div>
</ha-card>
`;
}
private _sourceName(source: WaterSourceTypeEnergyPreference) {
return (
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
);
}
private _addSource() {
showEnergySettingsWaterDialog(this, {
statsMetadata: this.statsMetadata,
water_sources: this.preferences.energy_sources.filter(
(src) => src.type === "water"
) as WaterSourceTypeEnergyPreference[],
saveCallback: async (source) => {
delete source.unit_of_measurement;
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.concat(source),
});
},
});
this._openEditor();
}
private _editSource(ev) {
const origSource: WaterSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
showEnergySettingsWaterDialog(this, {
statsMetadata: this.statsMetadata,
source: { ...origSource },
water_sources: this.preferences.energy_sources.filter(
(src) => src.type === "water"
) as WaterSourceTypeEnergyPreference[],
saveCallback: async (newSource) => {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src === origSource ? newSource : src
),
});
},
this._openEditor(ev.currentTarget.source);
}
private _openEditor(source?: WaterSourceTypeEnergyPreference) {
showEnergySettingsDialog(this, {
editor: this._editorConfig(this.preferences, source),
});
}
private async _deleteSource(ev) {
const sourceToDelete: WaterSourceTypeEnergyPreference =
ev.currentTarget.closest(".row").source;
private _editorHref(source?: WaterSourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/water/${source ? encodeURIComponent(source.stat_energy_from) : "new"}`
: undefined;
}
private _editorConfig(
preferences: EnergyPreferences,
source?: WaterSourceTypeEnergyPreference
): EnergyEditorConfig {
return {
kind: "water",
params: {
source: source ? { ...source } : undefined,
statsMetadata: this.statsMetadata,
water_sources: preferences.energy_sources.filter(isWaterSource),
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
}
private _sourceIndex(source: WaterSourceTypeEnergyPreference) {
const sources = this.preferences.energy_sources;
const index = sources.indexOf(source);
if (index !== -1) {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
return sources.findIndex(
(src) =>
isWaterSource(src) && src.stat_energy_from === source.stat_energy_from
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig(this.preferences));
}
const source = this.preferences.energy_sources.find(
(src): src is WaterSourceTypeEnergyPreference =>
isWaterSource(src) && src.stat_energy_from === key
);
return (
source &&
this._pageConfig(this._editorConfig(this.preferences, source), source)
);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
source?: WaterSourceTypeEnergyPreference
): EnergyEditorPageConfig {
if (!source) {
return {
editor,
title: this.hass.localize(
"ui.panel.config.energy.water.add_water_source"
),
};
}
return {
editor,
title: this._sourceName(source),
delete: {
label: this.hass.localize(
"ui.panel.config.energy.water.delete_water_source"
),
action: () => this._deleteSource(source),
},
};
}
private async _saveSource(
source: WaterSourceTypeEnergyPreference,
original?: WaterSourceTypeEnergyPreference
) {
const sources = [...this.preferences.energy_sources];
const index = original ? this._sourceIndex(original) : -1;
if (index === -1) {
delete source.unit_of_measurement;
sources.push(source);
} else {
sources[index] = source;
}
await this._savePreferences({
...this.preferences,
energy_sources: sources,
});
}
private _deleteSourceClicked(ev) {
ev.stopPropagation();
this._deleteSource(ev.currentTarget.source);
}
private async _deleteSource(
source: WaterSourceTypeEnergyPreference
): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
return false;
}
const index = this._sourceIndex(source);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.filter(
(source) => source !== sourceToDelete
(_src, idx) => idx !== index
),
});
} catch (err: any) {
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
showAlertDialog(this, {
title: this.hass.localize("ui.panel.config.energy.save_config_failed", {
error: err.message,
}),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
@@ -57,4 +57,41 @@ export const energyCardStyles = css`
flex-direction: column;
gap: var(--ha-space-2);
}
.items {
display: flex;
flex-direction: column;
gap: var(--ha-space-2);
margin-bottom: var(--ha-space-3);
}
ha-automation-row img[slot="leading-icon"] {
display: block;
height: 24px;
}
.row-header {
/* Two lines fit the row's 48px, which keeps its icons centered */
display: flex;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
min-width: 0;
min-height: 48px;
padding: var(--ha-space-1) 0;
}
.row-header .label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.row-header .secondary {
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
line-height: var(--ha-line-height-condensed);
}
.handle {
display: flex;
padding: var(--ha-space-3);
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
color: var(--secondary-text-color);
}
`;
@@ -1,649 +0,0 @@
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-markdown";
import "../../../../components/radio/ha-radio-group";
import type { HaRadioGroup } from "../../../../components/radio/ha-radio-group";
import "../../../../components/radio/ha-radio-option";
import "../../../../components/input/ha-input";
import type { GasSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
emptyGasEnergyPreference,
energyStatisticHelpUrl,
} from "../../../../data/energy";
import {
getDisplayUnit,
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyle, haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { EnergySettingsGasDialogParams } from "./show-dialogs-energy";
import type { HaInput } from "../../../../components/input/ha-input";
import type { IntegralUnits } from "./energy-integral";
import {
confirmIntegrals,
findIntegral,
integralTotalUnit,
integralUnits,
} from "./energy-integral";
type CostType = "no-costs" | "number" | "entity" | "statistic";
interface GasFormState {
source: GasSourceTypeEnergyPreference;
costs: CostType;
}
const gasDeviceClasses = ["gas", "energy"];
const gasUnitClasses = ["volume", "energy"];
const flowRateUnitClasses = ["volume_flow_rate"];
@customElement("dialog-energy-gas-settings")
export class DialogEnergyGasSettings
extends DirtyStateProviderMixin<GasFormState>()(LitElement)
implements HassDialog<EnergySettingsGasDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: EnergySettingsGasDialogParams;
@state() private _open = false;
@state() private _source?: GasSourceTypeEnergyPreference;
@state() private _costs?: CostType;
@state() private _numberPriceText = "";
@state() private _pickedDisplayUnit?: string | null;
@state() private _energy_units?: string[];
@state() private _gas_units?: string[];
@state() private _flow_rate_units?: string[];
@state() private _error?: string;
@state() private _saving = false;
private _excludeList?: string[];
private _excludeListFlowRate?: string[];
public async showDialog(
params: EnergySettingsGasDialogParams
): Promise<void> {
this._params = params;
this._error = undefined;
this._saving = false;
this._source = params.source
? { ...params.source }
: emptyGasEnergyPreference();
this._pickedDisplayUnit = getDisplayUnit(
this.hass.states,
params.source?.stat_energy_from,
params.source?.stat_energy_from
? params.statsMetadata?.[params.source?.stat_energy_from]
: undefined
);
this._costs = this._source.entity_energy_price
? "entity"
: typeof this._source.number_energy_price === "number"
? "number"
: this._source.stat_cost
? "statistic"
: "no-costs";
this._numberPriceText =
typeof this._source.number_energy_price === "number"
? String(this._source.number_energy_price)
: "";
this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units;
this._gas_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "gas")
).units;
this._flow_rate_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "volume_flow_rate")
).units;
this._excludeList = this._params.gas_sources
.map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from);
this._excludeListFlowRate = this._params.gas_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
this._open = true;
this._initDirtyTracking(
{ type: "deep" },
{ source: this._source!, costs: this._costs! }
);
}
public closeDialog() {
this._open = false;
return true;
}
private _dialogClosed() {
this._params = undefined;
this._source = undefined;
this._pickedDisplayUnit = undefined;
this._error = undefined;
this._excludeList = undefined;
this._excludeListFlowRate = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render() {
if (!this._params || !this._source) {
return nothing;
}
const pickableUnit =
this._params.allowedGasUnitClass === undefined
? [...(this._gas_units || []), ...(this._energy_units || [])].join(", ")
: this._params.allowedGasUnitClass === "energy"
? this._energy_units?.join(", ") || ""
: this._gas_units?.join(", ") || "";
const displayUnit = this._source.stat_energy_from
? this._pickedDisplayUnit
: this._integralTotalUnit();
const unitPrice = displayUnit
? `${this.hass.config.currency}/${displayUnit}`
: undefined;
const pickedUnitClass =
displayUnit && this._energy_units?.includes(displayUnit)
? "energy"
: displayUnit && this._gas_units?.includes(displayUnit)
? "volume"
: undefined;
const labelStatistic =
this._source.stat_energy_from || this._source.stat_rate;
const externalSource =
this._source.stat_energy_from &&
isExternalStatistic(this._source.stat_energy_from);
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.header"
)}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
<p>
${this.hass.localize("ui.panel.config.energy.gas.dialog.paragraph")}
</p>
<p>
${this.hass.localize("ui.panel.config.energy.gas.dialog.note_para")}
</p>
</div>
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${
this._params.allowedGasUnitClass || gasUnitClasses
}
.includeDeviceClass=${gasDeviceClasses}
.value=${this._source.stat_energy_from}
.label=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.gas_usage"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.entity_para",
{ unit: pickableUnit }
)}
autofocus
></ha-statistic-picker>
<ha-statistic-picker
.includeUnitClass=${flowRateUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.gas_flow_rate"
)}
.excludeStatistics=${this._excludeListFlowRate}
@value-changed=${this._flowRateStatisticChanged}
.disabled=${this._saving}
.invalid=${!!this._flowRateError()}
.errorMessage=${this._flowRateError()}
.helper=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.flow_rate_para",
{ unit: this._flow_rate_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-input
.label=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source?.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
labelStatistic,
this._params?.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
<ha-radio-group
.disabled=${this._saving}
.label=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_para"
)}
.value=${this._costs}
name="costs"
@change=${this._handleCostChanged}
>
<ha-radio-option value="no-costs">
${this.hass.localize("ui.panel.config.energy.gas.dialog.no_cost")}
</ha-radio-option>
<ha-radio-option value="statistic">
${this.hass.localize("ui.panel.config.energy.gas.dialog.cost_stat")}
</ha-radio-option>
<ha-radio-option value="entity" .disabled=${externalSource}>
${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_entity"
)}
</ha-radio-option>
<ha-radio-option value="number" .disabled=${externalSource}>
${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_number"
)}
</ha-radio-option>
</ha-radio-group>
${
this._costs === "statistic"
? html`<ha-statistic-picker
.disabled=${this._saving}
class="price-options"
statistic-types="sum"
.value=${this._source.stat_cost}
.label=${`${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_stat_input"
)} (${this.hass.config.currency})`}
@value-changed=${this._priceStatChanged}
></ha-statistic-picker>`
: this._costs === "entity"
? html`<ha-entity-picker
.disabled=${this._saving}
class="price-options"
include-domains='["sensor", "input_number"]'
.value=${this._source.entity_energy_price}
.label=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_entity_input"
)}
.helper=${
pickedUnitClass
? html`<ha-markdown
.content=${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_entity_helper",
pickedUnitClass === "energy"
? {
currency: this.hass.config.currency,
class: this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_entity_helper_energy"
),
unit1: "kWh",
unit2: "Wh",
}
: {
currency: this.hass.config.currency,
class: this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_entity_helper_volume"
),
unit1: "m³",
unit2: "ft³",
}
)}
></ha-markdown>`
: nothing
}
@value-changed=${this._priceEntityChanged}
></ha-entity-picker>`
: this._costs === "number"
? html`<ha-input
.disabled=${this._saving}
.label=${`${this.hass.localize(
"ui.panel.config.energy.gas.dialog.cost_number_input"
)} ${unitPrice ? ` (${unitPrice})` : ""}`}
class="price-options"
step="any"
type="number"
required
auto-validate
.value=${this._numberPriceText}
@input=${this._numberPriceChanged}
>
${
unitPrice
? html`<span slot="end">${unitPrice}</span>`
: nothing
}
</ha-input>`
: nothing
}
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!(this._source!.stat_energy_from || this._integralUnits()) ||
(this._costs === "number" &&
typeof this._source!.number_energy_price !== "number") ||
(!!this._params?.source && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private _handleCostChanged(ev: HASSDomCurrentTargetEvent<HaRadioGroup>) {
this._costs = (ev.currentTarget as HaRadioGroup).value as CostType;
this._updateFormDirtyState();
}
private _numberPriceChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
// Render the typed text so partial input such as "0." is not rewritten
this._numberPriceText = ev.currentTarget.value ?? "";
this._source = {
...this._source!,
number_energy_price: this._numberPriceText
? parseFloat(this._numberPriceText)
: null,
entity_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _priceStatChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: null,
number_energy_price: null,
stat_cost: ev.detail.value,
};
this._updateFormDirtyState();
}
private _priceEntityChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: ev.detail.value,
number_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _flowRateStatisticChanged(ev: ValueChangedEvent<string>) {
this._source = {
...this._source!,
stat_rate: ev.detail.value || undefined,
};
this._updateFormDirtyState();
}
private async _statisticChanged(ev: ValueChangedEvent<string>) {
if (ev.detail.value) {
const [metadata] = await getStatisticMetadata(this.hass.callWS, [
ev.detail.value,
]);
if (
metadata &&
isExternalStatistic(ev.detail.value) &&
this._params?.statsMetadata &&
!(ev.detail.value in this._params.statsMetadata)
) {
this._params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate("_params");
}
this._pickedDisplayUnit = getDisplayUnit(
this.hass.states,
ev.detail.value,
metadata
);
if (isExternalStatistic(ev.detail.value) && this._costs !== "statistic") {
this._costs = "no-costs";
}
} else {
this._pickedDisplayUnit = undefined;
}
this._source = {
...this._source!,
stat_energy_from: ev.detail.value,
};
this._updateFormDirtyState();
}
private _nameChanged(ev: InputEvent) {
this._source = {
...this._source!,
name: (ev.target as HaInput).value,
};
if (!this._source.name) {
delete this._source.name;
}
this._updateFormDirtyState();
}
private _updateFormDirtyState(): void {
this._updateDirtyState({ source: this._source!, costs: this._costs! });
}
private _integralUnits(): IntegralUnits | undefined {
const statRate = this._source?.stat_rate;
// Gas sources can't mix volume and energy units
if (
!statRate ||
!this._gas_units ||
this._params?.allowedGasUnitClass === "energy"
) {
return undefined;
}
return integralUnits(
this.hass.states[statRate]?.attributes.unit_of_measurement,
this._gas_units
);
}
private _flowRateError(): string | undefined {
if (
this._source?.stat_energy_from ||
!this._source?.stat_rate ||
!this._gas_units ||
this._integralUnits()
) {
return undefined;
}
return this.hass.localize(
this._params?.allowedGasUnitClass === "energy"
? "ui.panel.config.energy.gas.dialog.flow_rate_energy_sources"
: "ui.panel.config.energy.gas.dialog.flow_rate_no_volume"
);
}
private _integralTotalUnit(): string | undefined {
const units = this._integralUnits();
if (!units) {
return undefined;
}
const statRate = this._source!.stat_rate!;
// A reused helper can display another unit than a new one would
const existing = findIntegral(
this.hass.states,
this.hass.entities,
statRate,
"gas",
this._excludeList
);
return existing
? getDisplayUnit(this.hass.states, existing, undefined) || undefined
: integralTotalUnit(
this.hass.states[statRate].attributes.unit_of_measurement!,
units
);
}
private async _save() {
// Closing or reopening the dialog replaces its state, but a created helper
// must still be saved with the submitted source
const params = this._params!;
const costs = this._costs;
let source = this._source!;
const isCurrent = () => this._params === params;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_from) {
const statEnergyFrom = await this._gasFromFlowRate(source);
if (!statEnergyFrom) {
return;
}
source = { ...source, stat_energy_from: statEnergyFrom };
if (isCurrent()) {
this._pickedDisplayUnit = this._integralTotalUnit();
// Keep edits made meanwhile, only fill in the new sensor
this._source = { ...this._source!, stat_energy_from: statEnergyFrom };
this._updateFormDirtyState();
}
}
if (costs === "no-costs") {
source = {
...source,
entity_energy_price: null,
number_energy_price: null,
stat_cost: null,
};
}
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
private async _gasFromFlowRate(
draft: GasSourceTypeEnergyPreference
): Promise<string | undefined> {
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, this.hass, {
deviceClass: "gas",
states: this.hass.states,
entities: this.hass.entities,
requests: [
{
rate: statRate,
units,
name: this.hass.localize(
"ui.panel.config.energy.integral.gas.sensor_name",
{
name: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
statRate,
this._params?.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this.hass.localize(
"ui.panel.config.energy.gas.dialog.gas_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this._params?.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
ha-radio-group {
margin-top: var(--ha-space-4);
}
.price-options {
display: block;
margin-top: var(--ha-space-3);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-gas-settings": DialogEnergyGasSettings;
}
}
@@ -0,0 +1,102 @@
import { html, LitElement, nothing } from "lit";
import { customElement, query, state } from "lit/decorators";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import { DialogMixin } from "../../../../dialogs/dialog-mixin";
import type {
EnergyEditorConfig,
EnergyEditorElement,
EnergyEditorStatus,
} from "../editors/energy-editor";
import { renderEnergyEditor } from "../editors/render-energy-editor";
import type { EnergySettingsDialogParams } from "./show-dialogs-energy";
const HEADERS = {
grid: "ui.panel.config.energy.grid.dialog.header",
solar: "ui.panel.config.energy.solar.dialog.header",
home: "ui.panel.config.energy.home.dialog.header",
battery: "ui.panel.config.energy.battery.dialog.header",
device: "ui.panel.config.energy.device_consumption.dialog.header",
gas: "ui.panel.config.energy.gas.dialog.header",
water: "ui.panel.config.energy.water.dialog.header",
water_gas_device: {
water: "ui.panel.config.energy.device_consumption_water.dialog.header",
gas: "ui.panel.config.energy.device_consumption_gas.dialog.header",
},
} as const;
@customElement("dialog-energy-settings")
export class DialogEnergySettings extends DialogMixin<EnergySettingsDialogParams>(
LitElement
) {
@consumeLocalize()
private _localize!: LocalizeFunc;
@state() private _status?: EnergyEditorStatus;
@query(".energy-editor") private _editor?: EnergyEditorElement;
protected render() {
if (!this.params) {
return nothing;
}
return html`
<ha-dialog
open
header-title=${this._localize(this._header(this.params.editor))}
.preventScrimClose=${!!this._status?.dirty}
@energy-editor-status-changed=${this._statusChanged}
>
${renderEnergyEditor(this.params.editor)}
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this._localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
!this._status?.dirty || !this._status.valid || this._status.saving
}
.loading=${!!this._status?.saving}
slot="primaryAction"
>
${this._localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private _header(editor: EnergyEditorConfig) {
return editor.kind === "water_gas_device"
? HEADERS.water_gas_device[editor.params.resource]
: HEADERS[editor.kind];
}
private _statusChanged(
ev: HASSDomEvent<HASSDomEvents["energy-editor-status-changed"]>
) {
this._status = ev.detail;
}
private async _save() {
if (await this._editor?.save()) {
this.closeDialog();
}
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-settings": DialogEnergySettings;
}
}
@@ -1,530 +0,0 @@
import { mdiPlus } from "@mdi/js";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-checkbox";
import type { HaCheckbox } from "../../../../components/ha-checkbox";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-svg-icon";
import "../../../../components/radio/ha-radio-group";
import "../../../../components/input/ha-input";
import { domainToName } from "../../../../data/integration";
import type { HaRadioGroup } from "../../../../components/radio/ha-radio-group";
import "../../../../components/radio/ha-radio-option";
import type { ConfigEntry } from "../../../../data/config_entries";
import { getConfigEntries } from "../../../../data/config_entries";
import type { SolarSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
emptySolarEnergyPreference,
energyStatisticHelpUrl,
} from "../../../../data/energy";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import { showConfigFlowDialog } from "../../../../dialogs/config-flow/show-dialog-config-flow";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyle, haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import { brandsUrl } from "../../../../util/brands-url";
import type { EnergySettingsSolarDialogParams } from "./show-dialogs-energy";
import {
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
} from "../../../../data/recorder";
import type { HaInput } from "../../../../components/input/ha-input";
import type { IntegralUnits } from "./energy-integral";
import { confirmIntegrals, integralUnits } from "./energy-integral";
interface SolarFormState {
source: SolarSourceTypeEnergyPreference;
forecast: boolean;
}
const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-solar-settings")
export class DialogEnergySolarSettings
extends DirtyStateProviderMixin<SolarFormState>()(LitElement)
implements HassDialog<EnergySettingsSolarDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: EnergySettingsSolarDialogParams;
@state() private _open = false;
@state() private _source?: SolarSourceTypeEnergyPreference;
@state() private _configEntries?: ConfigEntry[];
@state() private _forecast?: boolean;
@state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string;
@state() private _saving = false;
private _excludeList?: string[];
private _excludeListPower?: string[];
public async showDialog(
params: EnergySettingsSolarDialogParams
): Promise<void> {
this._params = params;
this._error = undefined;
this._saving = false;
this._fetchSolarForecastConfigEntries();
this._source = params.source
? { ...params.source }
: emptySolarEnergyPreference();
this._forecast = this._source.config_entry_solar_forecast !== null;
this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeList = this._params.solar_sources
.map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from);
this._excludeListPower = this._params.solar_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
this._open = true;
this._initDirtyTracking(
{ type: "deep" },
{ source: this._source!, forecast: this._forecast! }
);
}
public closeDialog() {
this._open = false;
return true;
}
private _dialogClosed() {
this._params = undefined;
this._source = undefined;
this._error = undefined;
this._excludeList = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render() {
if (!this._params || !this._source) {
return nothing;
}
const labelStatistic =
this._source.stat_energy_from || this._source.stat_rate;
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.header"
)}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${energyUnitClasses}
.value=${this._source.stat_energy_from}
.label=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_energy"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._energy_units?.join(", ") || "" }
)}
autofocus
></ha-statistic-picker>
<ha-input
.label=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source?.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
labelStatistic,
this._params?.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
<ha-statistic-picker
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<h3>
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_forecast"
)}
</h3>
<p>
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_forecast_description"
)}
</p>
<ha-radio-group
.value=${this._forecast ? "true" : "false"}
.disabled=${this._saving}
name="forecast"
@change=${this._handleForecastChanged}
>
<ha-radio-option value="false">
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.dont_forecast_production"
)}
</ha-radio-option>
<ha-radio-option value="true">
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.forecast_production"
)}
</ha-radio-option>
</ha-radio-group>
${
this._forecast
? html`<div class="forecast-options">
${this._configEntries?.map(
(entry) =>
html`<ha-checkbox
.entry=${entry}
@change=${this._forecastCheckChanged}
.disabled=${this._saving}
.checked=${!!this._source?.config_entry_solar_forecast?.includes(
entry.entry_id
)}
>
<div style="display: flex; align-items: center;">
<img
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
style="height: 24px; margin-right: 16px; margin-inline-end: 16px; margin-inline-start: initial;"
src=${brandsUrl(
{
domain: entry.domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>${entry.title || domainToName(this.hass.localize, entry.domain)}
</div>
</ha-checkbox>`
)}
<ha-button
appearance="filled"
size="s"
@click=${this._addForecast}
.disabled=${this._saving}
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.add_forecast"
)}
</ha-button>
</div>`
: ""
}
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!(this._source!.stat_energy_from || this._integralUnits()) ||
(!!this._params?.source && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private async _fetchSolarForecastConfigEntries() {
const domains = this._params!.info.solar_forecast_domains;
this._configEntries =
domains.length === 0
? []
: domains.length === 1
? await getConfigEntries(this.hass, {
type: ["service"],
domain: domains[0],
})
: (await getConfigEntries(this.hass, { type: ["service"] })).filter(
(entry) => domains.includes(entry.domain)
);
}
private _handleForecastChanged(ev: HASSDomCurrentTargetEvent<HaRadioGroup>) {
this._forecast = (ev.currentTarget as HaRadioGroup).value === "true";
this._updateFormDirtyState();
}
private _forecastCheckChanged(ev) {
const input = ev.currentTarget as HaCheckbox;
const entry = (input as any).entry as ConfigEntry;
const checked = input.checked;
const list = this._source!.config_entry_solar_forecast
? [...this._source!.config_entry_solar_forecast]
: [];
if (checked) {
list.push(entry.entry_id);
} else {
list.splice(list.indexOf(entry.entry_id), 1);
}
this._source = { ...this._source!, config_entry_solar_forecast: list };
this._updateFormDirtyState();
}
private _addForecast() {
showConfigFlowDialog(this, {
startFlowHandler: "forecast_solar",
dialogClosedCallback: (params) => {
if (params.entryId) {
const list = this._source!.config_entry_solar_forecast
? [...this._source!.config_entry_solar_forecast]
: [];
list.push(params.entryId);
this._source = {
...this._source!,
config_entry_solar_forecast: list,
};
this._fetchSolarForecastConfigEntries();
this._updateFormDirtyState();
}
},
});
}
private async _statisticChanged(ev: ValueChangedEvent<string>) {
this._source = { ...this._source!, stat_energy_from: ev.detail.value };
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this._params?.statsMetadata &&
!(ev.detail.value in this._params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this.hass.callWS, [
ev.detail.value,
]);
if (metadata) {
this._params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate("_params");
}
}
this._updateFormDirtyState();
}
private _powerStatisticChanged(ev: ValueChangedEvent<string>) {
this._source = { ...this._source!, stat_rate: ev.detail.value };
this._updateFormDirtyState();
}
private _nameChanged(ev: InputEvent) {
this._source = {
...this._source!,
name: (ev.target as HaInput).value,
};
if (!this._source.name) {
delete this._source.name;
}
this._updateFormDirtyState();
}
private _updateFormDirtyState(): void {
this._updateDirtyState({
source: this._source!,
forecast: this._forecast!,
});
}
private _integralUnits(): IntegralUnits | undefined {
const statRate = this._source?.stat_rate;
if (!statRate || !this._energy_units) {
return undefined;
}
return integralUnits(
this.hass.states[statRate]?.attributes.unit_of_measurement,
this._energy_units
);
}
private async _save() {
// Closing or reopening the dialog replaces its state, but a created helper
// must still be saved with the submitted source
const params = this._params!;
const forecast = this._forecast;
let source = this._source!;
const isCurrent = () => this._params === params;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_from) {
const statEnergyFrom = await this._energyFromPower(source);
if (!statEnergyFrom) {
return;
}
source = { ...source, stat_energy_from: statEnergyFrom };
if (isCurrent()) {
// Keep edits made meanwhile, only fill in the new energy sensor
this._source = { ...this._source!, stat_energy_from: statEnergyFrom };
this._updateFormDirtyState();
}
}
if (!forecast) {
source = { ...source, config_entry_solar_forecast: null };
}
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
private async _energyFromPower(
draft: SolarSourceTypeEnergyPreference
): Promise<string | undefined> {
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, this.hass, {
deviceClass: "energy",
states: this.hass.states,
entities: this.hass.entities,
requests: [
{
rate: statRate,
units,
name: this.hass.localize(
"ui.panel.config.energy.integral.energy.sensor_name",
{
name: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
statRate,
this._params?.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this.hass.localize(
"ui.panel.config.energy.solar.dialog.energy_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this._params?.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
img {
height: 24px;
margin-right: 16px;
margin-inline-end: 16px;
margin-inline-start: initial;
}
ha-statistic-picker {
width: 100%;
}
ha-radio-group {
margin-bottom: var(--ha-space-3);
}
.forecast-options {
display: flex;
flex-direction: column;
min-width: 0;
gap: var(--ha-space-2);
margin-inline-start: var(--ha-space-3);
}
.forecast-options ha-button {
margin-top: var(--ha-space-4);
width: fit-content;
}
.forecast-options ha-checkbox {
justify-content: center;
min-height: 40px;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-solar-settings": DialogEnergySolarSettings;
}
}
@@ -1,546 +0,0 @@
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-markdown";
import "../../../../components/ha-dialog";
import "../../../../components/radio/ha-radio-group";
import type { HaRadioGroup } from "../../../../components/radio/ha-radio-group";
import "../../../../components/radio/ha-radio-option";
import "../../../../components/input/ha-input";
import type { WaterSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
emptyWaterEnergyPreference,
energyStatisticHelpUrl,
} from "../../../../data/energy";
import {
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyle, haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { EnergySettingsWaterDialogParams } from "./show-dialogs-energy";
import type { HaInput } from "../../../../components/input/ha-input";
import type { IntegralUnits } from "./energy-integral";
import { confirmIntegrals, integralUnits } from "./energy-integral";
type CostType = "no-costs" | "number" | "entity" | "statistic";
interface WaterFormState {
source: WaterSourceTypeEnergyPreference;
costs: CostType;
}
const flowRateUnitClasses = ["volume_flow_rate"];
@customElement("dialog-energy-water-settings")
export class DialogEnergyWaterSettings
extends DirtyStateProviderMixin<WaterFormState>()(LitElement)
implements HassDialog<EnergySettingsWaterDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: EnergySettingsWaterDialogParams;
@state() private _open = false;
@state() private _source?: WaterSourceTypeEnergyPreference;
@state() private _costs?: CostType;
@state() private _numberPriceText = "";
@state() private _water_units?: string[];
@state() private _flow_rate_units?: string[];
@state() private _error?: string;
@state() private _saving = false;
private _excludeList?: string[];
private _excludeListFlowRate?: string[];
public async showDialog(
params: EnergySettingsWaterDialogParams
): Promise<void> {
this._params = params;
this._error = undefined;
this._saving = false;
this._source = params.source
? { ...params.source }
: emptyWaterEnergyPreference();
this._costs = this._source.entity_energy_price
? "entity"
: typeof this._source.number_energy_price === "number"
? "number"
: this._source.stat_cost
? "statistic"
: "no-costs";
this._numberPriceText =
typeof this._source.number_energy_price === "number"
? String(this._source.number_energy_price)
: "";
this._water_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "water")
).units;
this._flow_rate_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "volume_flow_rate")
).units;
this._excludeList = this._params.water_sources
.map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from);
this._excludeListFlowRate = this._params.water_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
this._open = true;
this._initDirtyTracking(
{ type: "deep" },
{ source: this._source!, costs: this._costs! }
);
}
public closeDialog() {
this._open = false;
return true;
}
private _dialogClosed() {
this._params = undefined;
this._source = undefined;
this._error = undefined;
this._excludeList = undefined;
this._excludeListFlowRate = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render() {
if (!this._params || !this._source) {
return nothing;
}
const pickableUnit = this._water_units?.join(", ") || "";
const unitPriceFixed = `${this.hass.config.currency}/${
this.hass.config.unit_system.volume === "gal" ? "gal" : "m³"
}`;
const externalSource =
this._source.stat_energy_from &&
isExternalStatistic(this._source.stat_energy_from);
const labelStatistic =
this._source.stat_energy_from || this._source.stat_rate;
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.energy.water.dialog.header"
)}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
include-unit-class="volume"
include-device-class="water"
.value=${this._source.stat_energy_from}
.label=${this.hass.localize(
"ui.panel.config.energy.water.dialog.water_usage"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
"ui.panel.config.energy.water.dialog.entity_para",
{ unit: pickableUnit }
)}
autofocus
></ha-statistic-picker>
<ha-statistic-picker
.includeUnitClass=${flowRateUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.water.dialog.water_flow_rate"
)}
.excludeStatistics=${this._excludeListFlowRate}
@value-changed=${this._flowRateStatisticChanged}
.disabled=${this._saving}
.invalid=${!!this._flowRateError()}
.errorMessage=${this._flowRateError()}
.helper=${this.hass.localize(
"ui.panel.config.energy.water.dialog.flow_rate_para",
{ unit: this._flow_rate_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-input
.label=${this.hass.localize(
"ui.panel.config.energy.water.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source?.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
labelStatistic,
this._params?.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
<ha-radio-group
.disabled=${this._saving}
.label=${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_para"
)}
.value=${this._costs}
name="costs"
@change=${this._handleCostChanged}
>
<ha-radio-option value="no-costs">
${this.hass.localize("ui.panel.config.energy.water.dialog.no_cost")}
</ha-radio-option>
<ha-radio-option value="statistic">
${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_stat"
)}
</ha-radio-option>
<ha-radio-option value="entity" .disabled=${externalSource}>
${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_entity"
)}
</ha-radio-option>
<ha-radio-option value="number" .disabled=${externalSource}>
${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_number"
)}
</ha-radio-option>
</ha-radio-group>
${
this._costs === "statistic"
? html`<ha-statistic-picker
.disabled=${this._saving}
class="price-options"
statistic-types="sum"
.value=${this._source.stat_cost}
.label=${`${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_stat_input"
)} (${this.hass.config.currency})`}
@value-changed=${this._priceStatChanged}
></ha-statistic-picker>`
: this._costs === "entity"
? html`<ha-entity-picker
.disabled=${this._saving}
class="price-options"
include-domains='["sensor", "input_number"]'
.value=${this._source.entity_energy_price}
.label=${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_entity_input"
)}
.helper=${html`<ha-markdown
.content=${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_entity_helper",
{ currency: this.hass.config.currency }
)}
></ha-markdown>`}
@value-changed=${this._priceEntityChanged}
></ha-entity-picker>`
: this._costs === "number"
? html`<ha-input
.disabled=${this._saving}
.label=${`${this.hass.localize(
"ui.panel.config.energy.water.dialog.cost_number_input"
)} (${unitPriceFixed})`}
class="price-options"
step="any"
type="number"
required
auto-validate
.value=${this._numberPriceText}
@input=${this._numberPriceChanged}
>
<span slot="end">${unitPriceFixed}</span>
</ha-input>`
: nothing
}
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!(this._source!.stat_energy_from || this._integralUnits()) ||
(this._costs === "number" &&
typeof this._source!.number_energy_price !== "number") ||
(!!this._params?.source && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private _handleCostChanged(ev: HASSDomCurrentTargetEvent<HaRadioGroup>) {
this._costs = (ev.currentTarget as HaRadioGroup).value as CostType;
this._updateFormDirtyState();
}
private _numberPriceChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
// Render the typed text so partial input such as "0." is not rewritten
this._numberPriceText = ev.currentTarget.value ?? "";
this._source = {
...this._source!,
number_energy_price: this._numberPriceText
? parseFloat(this._numberPriceText)
: null,
entity_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _priceStatChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: null,
number_energy_price: null,
stat_cost: ev.detail.value,
};
this._updateFormDirtyState();
}
private _priceEntityChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: ev.detail.value,
number_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _flowRateStatisticChanged(ev: ValueChangedEvent<string>) {
this._source = {
...this._source!,
stat_rate: ev.detail.value || undefined,
};
this._updateFormDirtyState();
}
private async _statisticChanged(ev: ValueChangedEvent<string>) {
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this._costs !== "statistic"
) {
this._costs = "no-costs";
}
this._source = {
...this._source!,
stat_energy_from: ev.detail.value,
};
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this._params?.statsMetadata &&
!(ev.detail.value in this._params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this.hass.callWS, [
ev.detail.value,
]);
if (metadata) {
this._params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate("_params");
}
}
this._updateFormDirtyState();
}
private _nameChanged(ev: InputEvent) {
this._source = {
...this._source!,
name: (ev.target as HaInput).value,
};
if (!this._source.name) {
delete this._source.name;
}
this._updateFormDirtyState();
}
private _updateFormDirtyState(): void {
this._updateDirtyState({ source: this._source!, costs: this._costs! });
}
private _flowRateError(): string | undefined {
if (
this._source?.stat_energy_from ||
!this._source?.stat_rate ||
!this._water_units ||
this._integralUnits()
) {
return undefined;
}
return this.hass.localize(
"ui.panel.config.energy.water.dialog.flow_rate_no_volume"
);
}
private _integralUnits(): IntegralUnits | undefined {
const statRate = this._source?.stat_rate;
if (!statRate || !this._water_units) {
return undefined;
}
return integralUnits(
this.hass.states[statRate]?.attributes.unit_of_measurement,
this._water_units
);
}
private async _save() {
// Closing or reopening the dialog replaces its state, but a created helper
// must still be saved with the submitted source
const params = this._params!;
const costs = this._costs;
let source = this._source!;
const isCurrent = () => this._params === params;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_from) {
const statEnergyFrom = await this._waterFromFlowRate(source);
if (!statEnergyFrom) {
return;
}
source = { ...source, stat_energy_from: statEnergyFrom };
if (isCurrent()) {
// Keep edits made meanwhile, only fill in the new sensor
this._source = { ...this._source!, stat_energy_from: statEnergyFrom };
this._updateFormDirtyState();
}
}
if (costs === "no-costs") {
source = {
...source,
entity_energy_price: null,
number_energy_price: null,
stat_cost: null,
};
}
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
private async _waterFromFlowRate(
draft: WaterSourceTypeEnergyPreference
): Promise<string | undefined> {
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, this.hass, {
deviceClass: "water",
states: this.hass.states,
entities: this.hass.entities,
requests: [
{
rate: statRate,
units,
name: this.hass.localize(
"ui.panel.config.energy.integral.water.sensor_name",
{
name: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
statRate,
this._params?.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this.hass.localize(
"ui.panel.config.energy.water.dialog.water_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this._params?.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
ha-radio-group {
margin-top: var(--ha-space-4);
}
.price-options {
display: block;
margin-top: var(--ha-space-3);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-water-settings": DialogEnergyWaterSettings;
}
}
@@ -10,7 +10,12 @@ import type { StatisticsMetaData } from "../../../../data/recorder";
import { getStatisticLabel } from "../../../../data/recorder";
import { findRelated } from "../../../../data/search";
import { showConfirmationDialog } from "../../../../dialogs/generic/show-dialog-box";
import type { HomeAssistant } from "../../../../types";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type {
HomeAssistant,
HomeAssistantApi,
HomeAssistantFormatters,
} from "../../../../types";
import type { PowerType } from "./power-config";
export type IntegralDeviceClass = "energy" | "gas" | "water";
@@ -154,23 +159,24 @@ export function integralFlowInput(
}
async function createIntegral(
hass: HomeAssistant,
api: HomeAssistantApi,
localize: LocalizeFunc,
request: IntegralRequest,
deviceClass: IntegralDeviceClass
): Promise<string> {
let flowId: string | undefined;
let entityId: string | undefined;
try {
flowId = (await createConfigFlow(hass, "integration")).flow_id;
flowId = (await createConfigFlow(api.callApi, "integration")).flow_id;
const step = await handleConfigFlowStep(
hass,
api.callApi,
flowId,
integralFlowInput(request.name, request.rate, request.units, deviceClass)
);
if (step.type === "create_entry" && step.result) {
flowId = undefined;
const related = await findRelated(
hass,
api,
"config_entry",
step.result.entry_id
);
@@ -181,17 +187,18 @@ async function createIntegral(
}
if (flowId) {
// Rejected input keeps the flow open
await deleteConfigFlow(hass, flowId).catch(() => undefined);
await deleteConfigFlow(api, flowId).catch(() => undefined);
}
if (!entityId) {
throw new Error(
hass.localize("ui.panel.config.energy.integral.create_failed")
);
throw new Error(localize("ui.panel.config.energy.integral.create_failed"));
}
return entityId;
}
export interface ConfirmIntegralsOptions {
api: HomeAssistantApi;
localize: LocalizeFunc;
formatEntityName: HomeAssistantFormatters["formatEntityName"];
deviceClass: IntegralDeviceClass;
/** Live states and entities, so a retry finds the helpers already created. */
states: HomeAssistant["states"];
@@ -211,11 +218,10 @@ export interface ConfirmIntegralsOptions {
*/
export async function confirmIntegrals(
element: HTMLElement,
hass: HomeAssistant,
options: ConfirmIntegralsOptions
): Promise<string[] | undefined> {
const { localize, formatEntityName } = hass;
const { deviceClass, states, entities } = options;
const { api, localize, formatEntityName, deviceClass, states, entities } =
options;
const label = (statisticId: string) =>
getStatisticLabel(
states,
@@ -284,7 +290,7 @@ export async function confirmIntegrals(
const settled = await Promise.allSettled(
plan.map(
({ request, existing }) =>
existing ?? createIntegral(hass, request, deviceClass)
existing ?? createIntegral(api, localize, request, deviceClass)
)
);
const failure = settled.find(
@@ -1,21 +1,21 @@
import { mdiInformationOutline } from "@mdi/js";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, 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 { fireEvent } from "../../../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import type { LocalizeKeys } from "../../../../common/translations/localize";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../../common/translations/localize";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import "../../../../components/radio/ha-radio-group";
import type { HaRadioGroup } from "../../../../components/radio/ha-radio-group";
import "../../../../components/radio/ha-radio-option";
import "../../../../components/ha-select";
import type { HaSelectSelectEvent } from "../../../../components/ha-select";
import { apiContext } from "../../../../data/context";
import type { PowerConfig } from "../../../../data/energy";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import { buttonLinkStyle } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { HomeAssistantApi, ValueChangedEvent } from "../../../../types";
import type { PowerType } from "./power-config";
const powerUnitClasses = ["power"];
@@ -28,8 +28,6 @@ declare global {
@customElement("ha-energy-power-config")
export class HaEnergyPowerConfig extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public powerType: PowerType = "none";
@property({ attribute: false }) public powerConfig: PowerConfig = {};
@@ -50,67 +48,67 @@ export class HaEnergyPowerConfig extends LitElement {
@property({ attribute: false }) public localizeBaseKey =
"ui.panel.config.energy.battery.dialog";
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@state() private _powerUnits?: string[];
protected async willUpdate(
changedProps: PropertyValues<this>
): Promise<void> {
super.willUpdate(changedProps);
if (changedProps.has("hass") && !this._powerUnits) {
this._powerUnits = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
}
protected async firstUpdated(): Promise<void> {
this._powerUnits = (
await getSensorDeviceClassConvertibleUnits(this._api.callWS, "power")
).units;
}
private get _requiredError(): string {
return this.hass.localize("ui.common.error_required");
return this._localize("ui.common.error_required");
}
protected render(): TemplateResult {
const helperSensorNote = this._localize(
`${this.localizeBaseKey}.helper_sensor_note` as LocalizeKeys
);
return html`
<p class="power-section-label">
${this.hass.localize(
<ha-select
.label=${this._localize(
`${this.localizeBaseKey}.sensor_type` as LocalizeKeys
)}
</p>
<p class="power-section-description">
${this.hass.localize(
.helper=${this._localize(
`${this.localizeBaseKey}.sensor_type_para` as LocalizeKeys
)}
</p>
<ha-radio-group
.value=${this.powerType}
.options=${[
{
value: "none",
label: this._localize(
`${this.localizeBaseKey}.type_none` as LocalizeKeys
),
},
{
value: "standard",
label: this._localize(
`${this.localizeBaseKey}.type_standard` as LocalizeKeys
),
},
{
value: "inverted",
label: this._localize(
`${this.localizeBaseKey}.type_inverted` as LocalizeKeys
),
secondary: helperSensorNote,
},
{
value: "two_sensors",
label: this._localize(
`${this.localizeBaseKey}.type_two_sensors` as LocalizeKeys
),
secondary: helperSensorNote,
},
]}
.disabled=${this.disabled}
name="powerType"
@change=${this._handlePowerTypeChanged}
>
<ha-radio-option value="none">
${this.hass.localize(
`${this.localizeBaseKey}.type_none` as LocalizeKeys
)}
</ha-radio-option>
<ha-radio-option value="standard">
${this.hass.localize(
`${this.localizeBaseKey}.type_standard` as LocalizeKeys
)}
</ha-radio-option>
<ha-radio-option value="inverted">
${this.hass.localize(
`${this.localizeBaseKey}.type_inverted` as LocalizeKeys
)}
${this._renderHelperSensorNote("inverted")}
</ha-radio-option>
<ha-radio-option value="two_sensors">
${this.hass.localize(
`${this.localizeBaseKey}.type_two_sensors` as LocalizeKeys
)}
${this._renderHelperSensorNote("two_sensors")}
</ha-radio-option>
</ha-radio-group>
@selected=${this._handlePowerTypeChanged}
></ha-select>
${
this.powerType === "standard"
? html`
@@ -118,12 +116,12 @@ export class HaEnergyPowerConfig extends LitElement {
.disabled=${this.disabled}
.includeUnitClass=${powerUnitClasses}
.value=${this.powerConfig.stat_rate}
.label=${this.hass.localize(
.label=${this._localize(
`${this.localizeBaseKey}.power` as LocalizeKeys
)}
.excludeStatistics=${this.excludeList}
@value-changed=${this._standardPowerChanged}
.helper=${this.hass.localize(
.helper=${this._localize(
`${this.localizeBaseKey}.power_helper` as LocalizeKeys,
{ unit: this._powerUnits?.join(", ") || "" }
)}
@@ -141,12 +139,12 @@ export class HaEnergyPowerConfig extends LitElement {
.disabled=${this.disabled}
.includeUnitClass=${powerUnitClasses}
.value=${this.powerConfig.stat_rate_inverted}
.label=${this.hass.localize(
.label=${this._localize(
`${this.localizeBaseKey}.power` as LocalizeKeys
)}
.excludeStatistics=${this.excludeList}
@value-changed=${this._invertedPowerChanged}
.helper=${this.hass.localize(
.helper=${this._localize(
`${this.localizeBaseKey}.type_inverted_description` as LocalizeKeys
)}
required
@@ -165,7 +163,7 @@ export class HaEnergyPowerConfig extends LitElement {
.disabled=${this.disabled}
.includeUnitClass=${powerUnitClasses}
.value=${this.powerConfig.stat_rate_from}
.label=${this.hass.localize(
.label=${this._localize(
`${this.localizeBaseKey}.power_from` as LocalizeKeys
)}
.excludeStatistics=${[
@@ -180,7 +178,7 @@ export class HaEnergyPowerConfig extends LitElement {
.disabled=${this.disabled}
.includeUnitClass=${powerUnitClasses}
.value=${this.powerConfig.stat_rate_to}
.label=${this.hass.localize(
.label=${this._localize(
`${this.localizeBaseKey}.power_to` as LocalizeKeys
)}
.excludeStatistics=${[
@@ -198,31 +196,13 @@ export class HaEnergyPowerConfig extends LitElement {
`;
}
private _renderHelperSensorNote(powerType: PowerType) {
const id = `helper-sensor-note-${powerType}`;
return html`
<ha-svg-icon
id=${id}
tabindex="0"
class="note-icon"
.path=${mdiInformationOutline}
@click=${stopPropagation}
></ha-svg-icon>
<ha-tooltip .for=${id} placement="top">
${this.hass.localize(
`${this.localizeBaseKey}.helper_sensor_note` as LocalizeKeys
)}
</ha-tooltip>
`;
}
private _renderHelperSensorInUse() {
if (!this.helperEntityId) {
return nothing;
}
return html`
<p class="helper-sensor-in-use">
${this.hass.localize(
${this._localize(
`${this.localizeBaseKey}.helper_sensor_in_use` as LocalizeKeys,
{
entity: html`<button class="link" @click=${this._showHelperSensor}>
@@ -238,8 +218,8 @@ export class HaEnergyPowerConfig extends LitElement {
fireEvent(this, "hass-more-info", { entityId: this.helperEntityId! });
}
private _handlePowerTypeChanged(ev: HASSDomCurrentTargetEvent<HaRadioGroup>) {
const newPowerType = (ev.currentTarget as HaRadioGroup).value as PowerType;
private _handlePowerTypeChanged(ev: HaSelectSelectEvent) {
const newPowerType = ev.detail.value as PowerType;
// Clear power config when switching types
fireEvent(this, "power-config-changed", {
powerType: newPowerType,
@@ -284,33 +264,17 @@ export class HaEnergyPowerConfig extends LitElement {
static readonly styles: CSSResultGroup = [
buttonLinkStyle,
css`
:host {
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
}
ha-select,
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
ha-statistic-picker:last-of-type {
margin-bottom: 0;
}
ha-radio-group {
margin-bottom: var(--ha-space-4);
}
.power-section-label {
margin-top: var(--ha-space-4);
margin-bottom: var(--ha-space-2);
}
.power-section-description {
margin-top: 0;
margin-bottom: var(--ha-space-2);
color: var(--secondary-text-color);
font-size: 0.875em;
}
.note-icon {
margin-inline-start: var(--ha-space-1);
color: var(--secondary-text-color);
--mdc-icon-size: 18px;
}
.helper-sensor-in-use {
margin: var(--ha-space-2) 0 0 0;
margin: 0;
color: var(--secondary-text-color);
font-size: 0.875em;
}
@@ -1,20 +1,30 @@
import type { ContextType } from "@lit/context";
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import { mdiChartLine, mdiShape } from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import { html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { transform } from "../../../../common/decorators/transform";
import {
computeEntityNameParts,
computeEntitySearchLabels,
} from "../../../../common/entity/compute_entity_name_display";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/entity/state-badge";
import "../../../../components/ha-combo-box-item";
import "../../../../components/ha-generic-picker";
import type { PickerComboBoxItem } from "../../../../components/ha-picker-combo-box";
import type { PickerValueRenderer } from "../../../../components/ha-picker-field";
import "../../../../components/ha-svg-icon";
import {
formattersContext,
registriesContext,
statesContext,
} from "../../../../data/context";
import type { DeviceConsumptionEnergyPreference } from "../../../../data/energy";
import {
computeAmbiguousEnergyDevices,
@@ -25,7 +35,10 @@ import {
getStatisticLabel,
type StatisticsMetaData,
} from "../../../../data/recorder";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type {
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
interface UpstreamDeviceComboBoxItem extends PickerComboBoxItem {
stateObj?: HassEntity;
@@ -44,8 +57,6 @@ const SEARCH_KEYS = [
@customElement("ha-energy-upstream-device-picker")
export class HaEnergyUpstreamDevicePicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property() public value?: string;
@property() public label?: string;
@@ -67,10 +78,30 @@ export class HaEnergyUpstreamDevicePicker extends LitElement {
@property({ attribute: false })
public statsMetadata?: Record<string, StatisticsMetaData>;
@state()
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
private _ambiguousStatisticIds = memoizeOne(
(
states: HomeAssistant["states"],
formatEntityName: HomeAssistant["formatEntityName"],
states: ContextType<typeof statesContext>,
formatEntityName: HomeAssistantFormatters["formatEntityName"],
devices: DeviceConsumptionEnergyPreference[]
) => computeAmbiguousEnergyDevices(states, formatEntityName, devices)
);
@@ -80,35 +111,38 @@ export class HaEnergyUpstreamDevicePicker extends LitElement {
const name = this.devices.find(
(device) => device.stat_consumption === statisticId
)?.name;
const stateObj = this.hass.states[statisticId];
const stateObj = this._states[statisticId];
if (stateObj) {
const { area: areaName } = computeEntityNameParts(stateObj, this.hass);
const { area: areaName } = computeEntityNameParts(
stateObj,
this._registries
);
return {
id: statisticId,
// Match the label shown in the device list and the graphs.
primary: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statisticId,
this.statsMetadata?.[statisticId],
name,
this._ambiguousStatisticIds(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
this.devices
).has(statisticId)
),
secondary: areaName,
stateObj,
search_labels: computeEntitySearchLabels(stateObj, this.hass),
search_labels: computeEntitySearchLabels(stateObj, this._registries),
};
}
const label = getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statisticId,
this.statsMetadata?.[statisticId]
);
@@ -116,7 +150,7 @@ export class HaEnergyUpstreamDevicePicker extends LitElement {
if (isExternal) {
const domainName = domainToName(
this.hass.localize,
this._localize,
statisticId.split(":")[0]
);
return {
@@ -131,7 +165,7 @@ export class HaEnergyUpstreamDevicePicker extends LitElement {
return {
id: statisticId,
primary: name || label,
secondary: this.hass.localize("ui.components.statistic-picker.no_state"),
secondary: this._localize("ui.components.statistic-picker.no_state"),
icon_path: mdiShape,
search_labels: { label },
};
@@ -139,7 +173,10 @@ export class HaEnergyUpstreamDevicePicker extends LitElement {
private _items = memoizeOne(
(
_hass: HomeAssistant,
_states: ContextType<typeof statesContext>,
_registries: ContextType<typeof registriesContext>,
_formatEntityName: HomeAssistantFormatters["formatEntityName"],
_localize: LocalizeFunc,
_value: string | undefined,
_possibleParents: DeviceConsumptionEnergyPreference[],
_devices: DeviceConsumptionEnergyPreference[],
@@ -161,7 +198,10 @@ export class HaEnergyUpstreamDevicePicker extends LitElement {
private _getItems = () =>
this._items(
this.hass,
this._states,
this._registries,
this._formatEntityName,
this._localize,
this.value,
this.possibleParents,
this.devices,
@@ -1,162 +1,17 @@
import { fireEvent } from "../../../../common/dom/fire_event";
import type {
BatterySourceTypeEnergyPreference,
DeviceConsumptionEnergyPreference,
EnergyGasUnitClass,
EnergyInfo,
GasSourceTypeEnergyPreference,
GridSourceTypeEnergyPreference,
SolarSourceTypeEnergyPreference,
WaterSourceTypeEnergyPreference,
HomeSourceTypeEnergyPreference,
WaterGasResource,
} from "../../../../data/energy";
import type { StatisticsMetaData } from "../../../../data/recorder";
import type { HomeAssistant } from "../../../../types";
import type { EnergyEditorConfig } from "../editors/energy-editor";
export interface EnergySettingsGridDialogParams {
source?: GridSourceTypeEnergyPreference;
grid_sources: GridSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: GridSourceTypeEnergyPreference) => Promise<void>;
export interface EnergySettingsDialogParams {
editor: EnergyEditorConfig;
}
export interface EnergySettingsSolarDialogParams {
info: EnergyInfo;
source?: SolarSourceTypeEnergyPreference;
solar_sources: SolarSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: SolarSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergySettingsHomeDialogParams {
hass: HomeAssistant;
source?: HomeSourceTypeEnergyPreference;
saveCallback: (source: HomeSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergySettingsBatteryDialogParams {
source?: BatterySourceTypeEnergyPreference;
battery_sources: BatterySourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: BatterySourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergySettingsGasDialogParams {
source?: GasSourceTypeEnergyPreference;
allowedGasUnitClass?: EnergyGasUnitClass;
gas_sources: GasSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: GasSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergySettingsWaterDialogParams {
source?: WaterSourceTypeEnergyPreference;
water_sources: WaterSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: WaterSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergySettingsDeviceDialogParams {
device?: DeviceConsumptionEnergyPreference;
device_consumptions: DeviceConsumptionEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (device: DeviceConsumptionEnergyPreference) => Promise<void>;
}
export interface EnergySettingsDeviceWaterGasDialogParams {
resource: WaterGasResource;
device?: DeviceConsumptionEnergyPreference;
device_consumptions: DeviceConsumptionEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
allowedUnitClass?: EnergyGasUnitClass;
saveCallback: (device: DeviceConsumptionEnergyPreference) => Promise<void>;
}
export const showEnergySettingsDeviceDialog = (
export const showEnergySettingsDialog = (
element: HTMLElement,
dialogParams: EnergySettingsDeviceDialogParams
dialogParams: EnergySettingsDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-device-settings",
dialogImport: () => import("./dialog-energy-device-settings"),
dialogParams: dialogParams,
});
};
export const showEnergySettingsBatteryDialog = (
element: HTMLElement,
dialogParams: EnergySettingsBatteryDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-battery-settings",
dialogImport: () => import("./dialog-energy-battery-settings"),
dialogParams: dialogParams,
});
};
export const showEnergySettingsSolarDialog = (
element: HTMLElement,
dialogParams: EnergySettingsSolarDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-solar-settings",
dialogImport: () => import("./dialog-energy-solar-settings"),
dialogParams: dialogParams,
});
};
export const showEnergySettingsHomeDialog = (
element: HTMLElement,
dialogParams: EnergySettingsHomeDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-home-settings",
dialogImport: () => import("./dialog-energy-home-settings"),
dialogParams: dialogParams,
});
};
export const showEnergySettingsGasDialog = (
element: HTMLElement,
dialogParams: EnergySettingsGasDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-gas-settings",
dialogImport: () => import("./dialog-energy-gas-settings"),
dialogParams: dialogParams,
});
};
export const showEnergySettingsWaterDialog = (
element: HTMLElement,
dialogParams: EnergySettingsWaterDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-water-settings",
dialogImport: () => import("./dialog-energy-water-settings"),
dialogParams: dialogParams,
});
};
export const showEnergySettingsDeviceWaterGasDialog = (
element: HTMLElement,
dialogParams: EnergySettingsDeviceWaterGasDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-device-settings-water-gas",
dialogImport: () => import("./dialog-energy-device-settings-water-gas"),
dialogParams,
});
};
export const showEnergySettingsGridDialog = (
element: HTMLElement,
dialogParams: EnergySettingsGridDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-grid-settings",
dialogImport: () => import("./dialog-energy-grid-settings"),
dialogTag: "dialog-energy-settings",
dialogImport: () => import("./dialog-energy-settings"),
dialogParams: dialogParams,
});
};
@@ -0,0 +1,171 @@
import type { LitElement, PropertyValues } from "lit";
import { css } from "lit";
import { fireEvent } from "../../../../common/dom/fire_event";
import { shallowEqual } from "../../../../common/util/shallow-equal";
import type {
BatterySourceTypeEnergyPreference,
DeviceConsumptionEnergyPreference,
EnergyGasUnitClass,
EnergyInfo,
GasSourceTypeEnergyPreference,
GridSourceTypeEnergyPreference,
HomeSourceTypeEnergyPreference,
SolarSourceTypeEnergyPreference,
WaterGasResource,
WaterSourceTypeEnergyPreference,
} from "../../../../data/energy";
import type { StatisticsMetaData } from "../../../../data/recorder";
import type { Constructor } from "../../../../types";
export interface EnergyGridSourceEditorParams {
source?: GridSourceTypeEnergyPreference;
grid_sources: GridSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: GridSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergySolarSourceEditorParams {
info: EnergyInfo;
source?: SolarSourceTypeEnergyPreference;
solar_sources: SolarSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: SolarSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergyHomeSourceEditorParams {
source?: HomeSourceTypeEnergyPreference;
saveCallback: (source: HomeSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergyBatterySourceEditorParams {
source?: BatterySourceTypeEnergyPreference;
battery_sources: BatterySourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: BatterySourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergyGasSourceEditorParams {
source?: GasSourceTypeEnergyPreference;
allowedGasUnitClass?: EnergyGasUnitClass;
gas_sources: GasSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: GasSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergyWaterSourceEditorParams {
source?: WaterSourceTypeEnergyPreference;
water_sources: WaterSourceTypeEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: WaterSourceTypeEnergyPreference) => Promise<void>;
}
export interface EnergyDeviceEditorParams {
device?: DeviceConsumptionEnergyPreference;
device_consumptions: DeviceConsumptionEnergyPreference[];
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (device: DeviceConsumptionEnergyPreference) => Promise<void>;
}
export interface EnergyWaterGasDeviceEditorParams extends EnergyDeviceEditorParams {
resource: WaterGasResource;
allowedUnitClass?: EnergyGasUnitClass;
}
export type EnergyEditorConfig =
| { kind: "grid"; params: EnergyGridSourceEditorParams }
| { kind: "solar"; params: EnergySolarSourceEditorParams }
| { kind: "home"; params: EnergyHomeSourceEditorParams }
| { kind: "battery"; params: EnergyBatterySourceEditorParams }
| { kind: "device"; params: EnergyDeviceEditorParams }
| { kind: "gas"; params: EnergyGasSourceEditorParams }
| { kind: "water"; params: EnergyWaterSourceEditorParams }
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams };
export interface EnergyEditorStatus {
/** Whether there are changes to save */
dirty: boolean;
/** Whether the changes can be saved */
valid: boolean;
saving: boolean;
}
export interface EnergyEditorElement extends HTMLElement {
save(): Promise<boolean>;
}
declare global {
interface HASSDomEvents {
"energy-editor-status-changed": EnergyEditorStatus;
}
}
/**
* Lets the dialog or page hosting an energy editor render its save button.
*/
export const EnergyEditorMixin = <T extends Constructor<LitElement>>(
superClass: T
) =>
class extends superClass {
private _reportedStatus?: EnergyEditorStatus;
protected get editorStatus(): EnergyEditorStatus {
throw new Error("Not implemented");
}
public save(): Promise<boolean> {
throw new Error("Not implemented");
}
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
const status = this.editorStatus;
if (
!this._reportedStatus ||
!shallowEqual(status, this._reportedStatus)
) {
this._reportedStatus = status;
fireEvent(this, "energy-editor-status-changed", status);
}
}
};
export const energyEditorStyles = css`
:host {
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
}
ha-alert,
ha-statistic-picker,
ha-entity-picker,
ha-select,
ha-input {
display: block;
}
ha-input {
--ha-input-padding-bottom: 0;
}
wa-divider {
--spacing: 0;
}
.group {
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
}
.group-header {
display: flex;
flex-direction: column;
gap: var(--ha-space-1);
}
.group-header h3 {
margin: 0;
font-size: var(--ha-font-size-l);
font-weight: var(--ha-font-weight-medium);
line-height: var(--ha-line-height-condensed);
}
.group-header p {
margin: 0;
color: var(--secondary-text-color);
}
`;
@@ -1,13 +1,18 @@
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import { consume } from "../../../../common/decorators/consume";
import { deepEqual } from "../../../../common/util/deep-equal";
import { transform } from "../../../../common/decorators/transform";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-alert";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import type {
BatterySourceTypeEnergyPreference,
PowerConfig,
@@ -23,13 +28,24 @@ import {
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import {
apiContext,
entitiesContext,
formattersContext,
statesContext,
} from "../../../../data/context";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyle, haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { PowerIntegral } from "./energy-integral";
import { confirmIntegrals, pendingPowerIntegrals } from "./energy-integral";
import "./ha-energy-power-config";
import type {
HomeAssistantApi,
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
import type { PowerIntegral } from "../dialogs/energy-integral";
import {
confirmIntegrals,
pendingPowerIntegrals,
} from "../dialogs/energy-integral";
import "../dialogs/ha-energy-power-config";
import {
buildPowerExcludeList,
getInitialPowerConfig,
@@ -37,9 +53,12 @@ import {
getPowerTypeFromConfig,
isPowerConfigValid,
type PowerType,
} from "./power-config";
import type { EnergySettingsBatteryDialogParams } from "./show-dialogs-energy";
import type { HaInput } from "../../../../components/input/ha-input";
} from "../dialogs/power-config";
import type {
EnergyBatterySourceEditorParams,
EnergyEditorStatus,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
interface BatteryFormState {
source: BatterySourceTypeEnergyPreference;
@@ -51,16 +70,56 @@ const energyUnitClasses = ["energy"];
const socStatisticsUnits = ["%"];
const socDeviceClass = "battery";
@customElement("dialog-energy-battery-settings")
export class DialogEnergyBatterySettings
extends DirtyStateProviderMixin<BatteryFormState>()(LitElement)
implements HassDialog<EnergySettingsBatteryDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@customElement("ha-energy-battery-source-editor")
export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<BatteryFormState>()(LitElement)
) {
@property({ attribute: false })
public params!: EnergyBatterySourceEditorParams;
@state() private _params?: EnergySettingsBatteryDialogParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _open = false;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
// Keeps the previous array while the result is unchanged, so other state
// changes don't render
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, PowerIntegral[]>({
transformer: function (this: HaEnergyBatterySourceEditor, states) {
const pending =
states && this._source && this._energy_units
? pendingPowerIntegrals(
states,
this._source,
this._powerType,
this._powerConfig,
this._energy_units
)
: [];
return deepEqual(pending, this._pending) ? this._pending : pending;
},
watch: ["_source", "_powerType", "_powerConfig", "_energy_units"],
})
private _pending?: PowerIntegral[];
@state() private _source?: BatterySourceTypeEnergyPreference;
@@ -78,17 +137,21 @@ export class DialogEnergyBatterySettings
private _excludeListPower?: string[];
public async showDialog(
params: EnergySettingsBatteryDialogParams
): Promise<void> {
this._params = params;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._error = undefined;
this._saving = false;
this._source = params.source
? { ...params.source }
: emptyBatteryEnergyPreference();
// Initialize power type and config from existing source
this._powerType = getPowerTypeFromConfig(
params.source?.power_config,
params.source?.stat_rate
@@ -98,13 +161,8 @@ export class DialogEnergyBatterySettings
params.source?.stat_rate
);
this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units;
// Build energy exclude list
const allSources: string[] = [];
this._params.battery_sources.forEach((entry) => {
params.battery_sources.forEach((entry) => {
allSources.push(entry.stat_energy_from);
allSources.push(entry.stat_energy_to);
});
@@ -114,67 +172,60 @@ export class DialogEnergyBatterySettings
id !== this._source?.stat_energy_to
);
// Build power exclude list using shared helper
this._excludeListPower = buildPowerExcludeList(
this._params.battery_sources,
params.battery_sources,
this._powerConfig,
params.source?.stat_rate
);
this._open = true;
this._initDirtyTracking(
{ type: "deep" },
{
source: this._source!,
source: this._source,
powerType: this._powerType,
powerConfig: this._powerConfig,
}
);
this._loadUnits();
}
public closeDialog() {
this._open = false;
return true;
private async _loadUnits() {
this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this._api.callWS, "energy")
).units;
}
private _dialogClosed() {
this._params = undefined;
this._source = undefined;
this._powerType = "none";
this._powerConfig = {};
this._error = undefined;
this._excludeList = undefined;
this._excludeListPower = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid: this._isValid(this._pending ?? []),
saving: this._saving,
};
}
protected render() {
if (!this._params || !this._source) {
if (!this._source) {
return nothing;
}
const pending = this._pendingIntegrals();
const pending = this._pending ?? [];
const labelStatistic =
this._source.stat_energy_from ||
this._source.stat_energy_to ||
pending[0]?.rate;
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.header"
)}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${this._error ? html`<p class="error">${this._error}</p>` : nothing}
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${energyUnitClasses}
.value=${this._source.stat_energy_from}
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.energy_out_of_battery"
)}
.excludeStatistics=${[
@@ -183,18 +234,16 @@ export class DialogEnergyBatterySettings
]}
@value-changed=${this._statisticFromChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
.helper=${this._localize(
"ui.panel.config.energy.battery.dialog.energy_helper_out",
{ unit: this._energy_units?.join(", ") || "" }
)}
autofocus
></ha-statistic-picker>
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${energyUnitClasses}
.value=${this._source.stat_energy_to}
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.energy_into_battery"
)}
.excludeStatistics=${[
@@ -203,70 +252,73 @@ export class DialogEnergyBatterySettings
]}
@value-changed=${this._statisticToChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
.helper=${this._localize(
"ui.panel.config.energy.battery.dialog.energy_helper_into",
{ unit: this._energy_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-input
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source?.name || ""}
.value=${this._source.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
labelStatistic,
this._params?.statsMetadata?.[labelStatistic]
this.params.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
</div>
<ha-energy-power-config
.hass=${this.hass}
.powerType=${this._powerType}
.powerConfig=${this._powerConfig}
.excludeList=${this._excludeListPower}
.helperEntityId=${getPowerHelperEntityId(
this._params.source,
this._powerConfig
)}
.localizeBaseKey=${"ui.panel.config.energy.battery.dialog"}
.disabled=${this._saving}
@power-config-changed=${this._handlePowerConfigChanged}
></ha-energy-power-config>
<wa-divider></wa-divider>
<ha-energy-power-config
.powerType=${this._powerType}
.powerConfig=${this._powerConfig}
.excludeList=${this._excludeListPower}
.helperEntityId=${getPowerHelperEntityId(
this.params.source,
this._powerConfig
)}
.localizeBaseKey=${"ui.panel.config.energy.battery.dialog"}
.disabled=${this._saving}
@power-config-changed=${this._handlePowerConfigChanged}
></ha-energy-power-config>
<wa-divider></wa-divider>
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.value=${this._source.stat_soc}
.includeStatisticsUnitOfMeasurement=${socStatisticsUnits}
.includeDeviceClass=${socDeviceClass}
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.state_of_charge"
)}
.helper=${this.hass.localize(
.helper=${this._localize(
"ui.panel.config.energy.battery.dialog.state_of_charge_helper"
)}
@value-changed=${this._statisticSocChanged}
.disabled=${this._saving}
></ha-statistic-picker>
<ha-input
.value=${
this._source.capacity != null ? String(this._source.capacity) : ""
}
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity"
)}
.hint=${this.hass.localize(
.hint=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_helper"
)}
type="number"
@@ -277,29 +329,7 @@ export class DialogEnergyBatterySettings
>
<span slot="end">kWh</span>
</ha-input>
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!this._isValid(pending) ||
(!!this._params?.source && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
</div>
`;
}
@@ -312,7 +342,6 @@ export class DialogEnergyBatterySettings
return false;
}
// Check power config validity
return isPowerConfigValid(this._powerType, this._powerConfig);
}
@@ -320,13 +349,13 @@ export class DialogEnergyBatterySettings
if (
statId &&
isExternalStatistic(statId) &&
this._params?.statsMetadata &&
!(statId in this._params.statsMetadata)
this.params.statsMetadata &&
!(statId in this.params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this.hass.callWS, [statId]);
const [metadata] = await getStatisticMetadata(this._api.callWS, [statId]);
if (metadata) {
this._params.statsMetadata[statId] = metadata;
this.requestUpdate("_params");
this.params.statsMetadata[statId] = metadata;
this.requestUpdate();
}
}
}
@@ -391,35 +420,22 @@ export class DialogEnergyBatterySettings
this._updateFormDirtyState();
}
private _pendingIntegrals(): PowerIntegral[] {
if (!this._source || !this._energy_units) {
return [];
}
return pendingPowerIntegrals(
this.hass.states,
this._source,
this._powerType,
this._powerConfig,
this._energy_units
);
}
private async _save() {
// Closing or reopening the dialog replaces its state, but created helpers
// must still be saved with the submitted source
const params = this._params!;
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but created helpers must still
// be saved with the submitted source
const params = this.params;
const powerType = this._powerType;
const powerConfig = this._powerConfig;
let draft = this._source!;
const isCurrent = () => this._params === params;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
const pending = this._pendingIntegrals();
const pending = this._pending ?? [];
if (pending.length) {
const sensors = await this._energyFromPower(draft, pending);
if (!sensors) {
return;
return false;
}
const created = Object.fromEntries(
pending.map(({ energy }, index) => [energy, sensors[index]])
@@ -441,7 +457,6 @@ export class DialogEnergyBatterySettings
source.name = draft.name;
}
// Only include power_config if a power type is selected
if (powerType !== "none") {
source.power_config = { ...powerConfig };
}
@@ -457,12 +472,13 @@ export class DialogEnergyBatterySettings
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
@@ -474,29 +490,32 @@ export class DialogEnergyBatterySettings
draft: BatterySourceTypeEnergyPreference,
pending: PowerIntegral[]
): Promise<string[] | undefined> {
return confirmIntegrals(this, this.hass, {
return confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: "energy",
states: this.hass.states,
entities: this.hass.entities,
states: this._states,
entities: this._entities,
requests: pending.map(({ energy, rate, units }) => ({
rate,
units,
name: this.hass.localize(
name: this._localize(
energy === "stat_energy_from"
? "ui.panel.config.energy.battery.dialog.discharged_energy_name"
: "ui.panel.config.energy.battery.dialog.charged_energy_name",
{
name: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
rate,
this._params?.statsMetadata?.[rate],
this.params.statsMetadata?.[rate],
draft.name
),
}
),
})),
intro: this.hass.localize(
intro: this._localize(
"ui.panel.config.energy.battery.dialog.energy_sensors_needed"
),
// Neither direction may reuse the statistic of the other
@@ -505,34 +524,17 @@ export class DialogEnergyBatterySettings
draft.stat_energy_from,
draft.stat_energy_to,
].filter((id): id is string => Boolean(id)),
statsMetadata: this._params?.statsMetadata,
statsMetadata: this.params.statsMetadata,
});
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
ha-statistic-picker,
ha-energy-power-config {
display: block;
margin-bottom: var(--ha-space-4);
}
ha-input {
margin-bottom: var(--ha-space-4);
--ha-input-padding-bottom: 0;
}
ha-input:last-of-type {
margin-bottom: 0;
}
`,
];
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-battery-settings": DialogEnergyBatterySettings;
"ha-energy-battery-source-editor": HaEnergyBatterySourceEditor;
}
}
@@ -1,14 +1,15 @@
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import { consume } from "../../../../common/decorators/consume";
import { transform } from "../../../../common/decorators/transform";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-alert";
import "../../../../components/input/ha-input";
import "./ha-energy-upstream-device-picker";
import type { HaInput } from "../../../../components/input/ha-input";
import type { DeviceConsumptionEnergyPreference } from "../../../../data/energy";
import {
@@ -21,13 +22,26 @@ import {
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import {
apiContext,
entitiesContext,
formattersContext,
statesContext,
} from "../../../../data/context";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { IntegralUnits } from "./energy-integral";
import { confirmIntegrals, integralUnits } from "./energy-integral";
import type { EnergySettingsDeviceDialogParams } from "./show-dialogs-energy";
import type {
HomeAssistantApi,
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
import type { IntegralUnits } from "../dialogs/energy-integral";
import { confirmIntegrals, integralUnits } from "../dialogs/energy-integral";
import "../dialogs/ha-energy-upstream-device-picker";
import type {
EnergyDeviceEditorParams,
EnergyEditorStatus,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@@ -35,16 +49,46 @@ const powerUnitClasses = ["power"];
// Without an energy sensor, saving offers to create one from the power sensor
type DeviceConsumptionDraft = Partial<DeviceConsumptionEnergyPreference>;
@customElement("dialog-energy-device-settings")
export class DialogEnergyDeviceSettings
extends DirtyStateProviderMixin<DeviceConsumptionDraft | null>()(LitElement)
implements HassDialog<EnergySettingsDeviceDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@customElement("ha-energy-device-editor")
export class HaEnergyDeviceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<DeviceConsumptionDraft | null>()(LitElement)
) {
@property({ attribute: false }) public params!: EnergyDeviceEditorParams;
@state() private _params?: EnergySettingsDeviceDialogParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _open = false;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, string>({
transformer: function (this: HaEnergyDeviceEditor, states) {
const statRate = this._device?.stat_rate;
return statRate
? states?.[statRate]?.attributes.unit_of_measurement
: undefined;
},
watch: ["_device"],
})
private _rateUnit?: string;
@state() private _device?: DeviceConsumptionDraft;
@@ -62,29 +106,36 @@ export class DialogEnergyDeviceSettings
private _possibleParents: DeviceConsumptionEnergyPreference[] = [];
public async showDialog(
params: EnergySettingsDeviceDialogParams
): Promise<void> {
this._params = params;
this._device = this._params.device;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._device = params.device;
this._error = undefined;
this._saving = false;
this._computePossibleParents();
this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeList = this._params.device_consumptions
this._excludeList = params.device_consumptions
.map((entry) => entry.stat_consumption)
.filter((id) => id !== this._device?.stat_consumption);
this._excludeListPower = this._params.device_consumptions
this._excludeListPower = params.device_consumptions
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._device?.stat_rate) as string[];
this._open = true;
this._initDirtyTracking({ type: "deep" }, this._device ?? null);
this._loadUnits();
}
private async _loadUnits() {
const [energy, power] = await Promise.all([
getSensorDeviceClassConvertibleUnits(this._api.callWS, "energy"),
getSensorDeviceClassConvertibleUnits(this._api.callWS, "power"),
]);
this._energy_units = energy.units;
this._power_units = power.units;
}
// Label the device would get without a display name, so the placeholder
@@ -102,44 +153,44 @@ export class DialogEnergyDeviceSettings
// device will be labelled by, so there is no entity to tell it apart yet.
if (!device.stat_consumption) {
return computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statisticId,
this._params?.statsMetadata?.[statisticId]
this.params.statsMetadata?.[statisticId]
);
}
// The saved entry of the device being edited is replaced by the draft
// without a display name, which is what the placeholder stands for. The
// draft may point at another statistic by now, so match the saved one.
const edited = this._params?.device?.stat_consumption;
const edited = this.params.device?.stat_consumption;
const devices = [
...(this._params?.device_consumptions ?? []).filter(
...this.params.device_consumptions.filter(
(other) => other.stat_consumption !== edited
),
{ ...device, name: undefined },
];
return computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statisticId,
this._params?.statsMetadata?.[statisticId],
this.params.statsMetadata?.[statisticId],
undefined,
computeAmbiguousEnergyDevices(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
devices
).has(statisticId)
);
}
private _computePossibleParents() {
if (!this._device || !this._params) {
if (!this._device) {
this._possibleParents = [];
return;
}
const children: string[] = [];
const devices = this._params.device_consumptions;
const devices = this.params.device_consumptions;
function getChildren(stat) {
devices.forEach((d) => {
if (d.included_in_stat === stat) {
@@ -150,81 +201,51 @@ export class DialogEnergyDeviceSettings
}
// Saving without an energy sensor can reuse the original one
const stat =
this._device.stat_consumption ?? this._params.device?.stat_consumption;
this._device.stat_consumption ?? this.params.device?.stat_consumption;
if (stat) {
getChildren(stat);
}
this._possibleParents = this._params.device_consumptions.filter(
this._possibleParents = this.params.device_consumptions.filter(
(d) =>
d.stat_consumption !== this._device!.stat_consumption &&
d.stat_consumption !== this._params?.device?.stat_consumption &&
d.stat_consumption !== this.params.device?.stat_consumption &&
!children.includes(d.stat_consumption)
);
}
public closeDialog() {
this._open = false;
return true;
}
private _dialogClosed() {
this._params = undefined;
this._device = undefined;
this._error = undefined;
this._excludeList = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid: !!(this._device?.stat_consumption || this._integralUnits()),
saving: this._saving,
};
}
protected render() {
if (!this._params) {
return nothing;
}
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.header"
)}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${energyUnitClasses}
.value=${this._device?.stat_consumption}
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.device_consumption_energy"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
.helper=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._energy_units?.join(", ") || "" }
)}
autofocus
></ha-statistic-picker>
<ha-statistic-picker
.includeUnitClass=${powerUnitClasses}
.value=${this._device?.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.device_consumption_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.disabled=${this._saving}
.helper=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-input
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.display_name"
)}
.disabled=${!this._device || this._saving}
@@ -233,48 +254,44 @@ export class DialogEnergyDeviceSettings
@input=${this._nameChanged}
>
</ha-input>
</div>
<ha-energy-upstream-device-picker
.hass=${this.hass}
.label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.included_in_device"
)}
.helper=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.included_in_device_helper"
)}
.value=${this._device?.included_in_stat}
.possibleParents=${this._possibleParents}
.devices=${this._params.device_consumptions}
.statsMetadata=${this._params.statsMetadata}
.emptyLabel=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.no_upstream_devices"
)}
.disabled=${!this._device || this._saving}
@value-changed=${this._parentChanged}
></ha-energy-upstream-device-picker>
<wa-divider></wa-divider>
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!(this._device?.stat_consumption || this._integralUnits()) ||
(!!this._params?.device && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
<ha-statistic-picker
.includeUnitClass=${powerUnitClasses}
.value=${this._device?.stat_rate}
.label=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.device_consumption_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.disabled=${this._saving}
.helper=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<wa-divider></wa-divider>
<ha-energy-upstream-device-picker
.label=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.included_in_device"
)}
.helper=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.included_in_device_helper"
)}
.value=${this._device?.included_in_stat}
.possibleParents=${this._possibleParents}
.devices=${this.params.device_consumptions}
.statsMetadata=${this.params.statsMetadata}
.emptyLabel=${this._localize(
"ui.panel.config.energy.device_consumption.dialog.no_upstream_devices"
)}
.disabled=${!this._device || this._saving}
@value-changed=${this._parentChanged}
></ha-energy-upstream-device-picker>
`;
}
@@ -302,15 +319,15 @@ export class DialogEnergyDeviceSettings
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this._params?.statsMetadata &&
!(ev.detail.value in this._params.statsMetadata)
this.params.statsMetadata &&
!(ev.detail.value in this.params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this.hass.callWS, [
const [metadata] = await getStatisticMetadata(this._api.callWS, [
ev.detail.value,
]);
if (metadata) {
this._params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate("_params");
this.params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate();
}
}
}
@@ -358,25 +375,22 @@ export class DialogEnergyDeviceSettings
if (!statRate || !this._energy_units) {
return undefined;
}
return integralUnits(
this.hass.states[statRate]?.attributes.unit_of_measurement,
this._energy_units
);
return integralUnits(this._rateUnit, this._energy_units);
}
private async _save() {
// Closing or reopening the dialog replaces its state, but a created helper
// must still be saved with the submitted device
const params = this._params!;
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but a created helper must still
// be saved with the submitted device
const params = this.params;
const draft = this._device!;
const isCurrent = () => this._params === params;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
const statConsumption =
draft.stat_consumption ?? (await this._energyFromPower(draft));
if (!statConsumption) {
return;
return false;
}
const device = { ...draft, stat_consumption: statConsumption };
if (isCurrent()) {
@@ -386,12 +400,13 @@ export class DialogEnergyDeviceSettings
await params.saveCallback(device);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
@@ -407,65 +422,47 @@ export class DialogEnergyDeviceSettings
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, this.hass, {
const sensors = await confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: "energy",
states: this.hass.states,
entities: this.hass.entities,
states: this._states,
entities: this._entities,
requests: [
{
rate: statRate,
units,
name: this.hass.localize(
name: this._localize(
"ui.panel.config.energy.integral.energy.sensor_name",
{
name: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statRate,
this._params?.statsMetadata?.[statRate],
this.params.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this.hass.localize(
intro: this._localize(
"ui.panel.config.energy.device_consumption.dialog.energy_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this._params?.statsMetadata,
statsMetadata: this.params.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return [
haStyleDialog,
css`
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-2);
}
ha-statistic-picker {
width: 100%;
}
ha-energy-upstream-device-picker {
display: block;
margin-top: var(--ha-space-4);
width: 100%;
}
ha-input {
margin-top: var(--ha-space-4);
--ha-input-padding-bottom: 0;
width: 100%;
}
`,
];
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-device-settings": DialogEnergyDeviceSettings;
"ha-energy-device-editor": HaEnergyDeviceEditor;
}
}
@@ -0,0 +1,671 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HassConfig } from "home-assistant-js-websocket";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { transform } from "../../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-alert";
import "../../../../components/ha-markdown";
import "../../../../components/ha-select";
import type {
HaSelectOption,
HaSelectSelectEvent,
} from "../../../../components/ha-select";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import {
apiContext,
configContext,
entitiesContext,
formattersContext,
statesContext,
} from "../../../../data/context";
import type { GasSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
emptyGasEnergyPreference,
energyStatisticHelpUrl,
} from "../../../../data/energy";
import {
getDisplayUnit,
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
import type { IntegralUnits } from "../dialogs/energy-integral";
import {
confirmIntegrals,
findIntegral,
integralTotalUnit,
integralUnits,
} from "../dialogs/energy-integral";
import type {
EnergyEditorStatus,
EnergyGasSourceEditorParams,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
type CostType = "no-costs" | "number" | "entity" | "statistic";
interface GasFormState {
source: GasSourceTypeEnergyPreference;
costs: CostType;
}
const gasDeviceClasses = ["gas", "energy"];
const gasUnitClasses = ["volume", "energy"];
const flowRateUnitClasses = ["volume_flow_rate"];
@customElement("ha-energy-gas-source-editor")
export class HaEnergyGasSourceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<GasFormState>()(LitElement)
) {
@property({ attribute: false }) public params!: EnergyGasSourceEditorParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, string>({
transformer: function (this: HaEnergyGasSourceEditor, states) {
const statRate = this._source?.stat_rate;
return statRate
? states?.[statRate]?.attributes.unit_of_measurement
: undefined;
},
watch: ["_source"],
})
private _rateUnit?: string;
@state() private _source?: GasSourceTypeEnergyPreference;
@state() private _costs: CostType = "no-costs";
@state() private _numberPriceText = "";
@state() private _pickedDisplayUnit?: string | null;
@state() private _energy_units?: string[];
@state() private _gas_units?: string[];
@state() private _flow_rate_units?: string[];
@state() private _error?: string;
@state() private _saving = false;
private _excludeList?: string[];
private _excludeListFlowRate?: string[];
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._error = undefined;
this._saving = false;
this._source = params.source
? { ...params.source }
: emptyGasEnergyPreference();
this._pickedDisplayUnit = getDisplayUnit(
this._states,
params.source?.stat_energy_from,
params.source?.stat_energy_from
? params.statsMetadata?.[params.source.stat_energy_from]
: undefined
);
this._costs = this._source.entity_energy_price
? "entity"
: typeof this._source.number_energy_price === "number"
? "number"
: this._source.stat_cost
? "statistic"
: "no-costs";
this._numberPriceText =
typeof this._source.number_energy_price === "number"
? String(this._source.number_energy_price)
: "";
this._excludeList = params.gas_sources
.map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from);
this._excludeListFlowRate = params.gas_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
this._initDirtyTracking(
{ type: "deep" },
{ source: this._source, costs: this._costs }
);
this._loadUnits();
}
private async _loadUnits() {
const [energy, gas, flowRate] = await Promise.all([
getSensorDeviceClassConvertibleUnits(this._api.callWS, "energy"),
getSensorDeviceClassConvertibleUnits(this._api.callWS, "gas"),
getSensorDeviceClassConvertibleUnits(
this._api.callWS,
"volume_flow_rate"
),
]);
this._energy_units = energy.units;
this._gas_units = gas.units;
this._flow_rate_units = flowRate.units;
}
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid:
!!(this._source?.stat_energy_from || this._integralUnits()) &&
(this._costs !== "number" ||
typeof this._source?.number_energy_price === "number"),
saving: this._saving,
};
}
protected render() {
if (!this._source) {
return nothing;
}
const pickableUnit =
this.params.allowedGasUnitClass === undefined
? [...(this._gas_units || []), ...(this._energy_units || [])].join(", ")
: this.params.allowedGasUnitClass === "energy"
? this._energy_units?.join(", ") || ""
: this._gas_units?.join(", ") || "";
const labelStatistic =
this._source.stat_energy_from || this._source.stat_rate;
return html`
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<div class="group-header">
<p>
${this._localize("ui.panel.config.energy.gas.dialog.paragraph")}
</p>
<p>
${this._localize("ui.panel.config.energy.gas.dialog.note_para")}
</p>
</div>
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${this.params.allowedGasUnitClass || gasUnitClasses}
.includeDeviceClass=${gasDeviceClasses}
.value=${this._source.stat_energy_from}
.label=${this._localize(
"ui.panel.config.energy.gas.dialog.gas_usage"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this._localize(
"ui.panel.config.energy.gas.dialog.entity_para",
{ unit: pickableUnit }
)}
></ha-statistic-picker>
<ha-input
.label=${this._localize(
"ui.panel.config.energy.gas.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this._states,
this._formatEntityName,
labelStatistic,
this.params.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
</div>
<wa-divider></wa-divider>
<ha-statistic-picker
.includeUnitClass=${flowRateUnitClasses}
.value=${this._source.stat_rate}
.label=${this._localize(
"ui.panel.config.energy.gas.dialog.gas_flow_rate"
)}
.excludeStatistics=${this._excludeListFlowRate}
@value-changed=${this._flowRateStatisticChanged}
.disabled=${this._saving}
.invalid=${!!this._flowRateError()}
.errorMessage=${this._flowRateError()}
.helper=${this._localize(
"ui.panel.config.energy.gas.dialog.flow_rate_para",
{ unit: this._flow_rate_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<wa-divider></wa-divider>
<div class="group">
<ha-select
.label=${this._localize(
"ui.panel.config.energy.gas.dialog.cost_tracking"
)}
.helper=${this._localize(
"ui.panel.config.energy.gas.dialog.cost_para"
)}
.value=${this._costs}
.options=${this._costOptions()}
.disabled=${this._saving}
@selected=${this._handleCostChanged}
></ha-select>
${this._renderCost()}
</div>
`;
}
private _costOptions(): HaSelectOption[] {
// External statistics (from integrations) cannot use entity/number cost tracking
const externalSource =
!!this._source?.stat_energy_from &&
isExternalStatistic(this._source.stat_energy_from);
return [
{
value: "no-costs",
label: this._localize("ui.panel.config.energy.gas.dialog.no_cost"),
},
{
value: "statistic",
label: this._localize("ui.panel.config.energy.gas.dialog.cost_stat"),
},
{
value: "entity",
label: this._localize("ui.panel.config.energy.gas.dialog.cost_entity"),
disabled: externalSource,
},
{
value: "number",
label: this._localize("ui.panel.config.energy.gas.dialog.cost_number"),
disabled: externalSource,
},
];
}
private _renderCost() {
const displayUnit = this._source!.stat_energy_from
? this._pickedDisplayUnit
: this._integralTotalUnit();
const unitPrice = displayUnit
? `${this._hassConfig.currency}/${displayUnit}`
: undefined;
const pickedUnitClass =
displayUnit && this._energy_units?.includes(displayUnit)
? "energy"
: displayUnit && this._gas_units?.includes(displayUnit)
? "volume"
: undefined;
switch (this._costs) {
case "statistic":
return html`<ha-statistic-picker
.disabled=${this._saving}
statistic-types="sum"
.value=${this._source!.stat_cost}
.label=${`${this._localize(
"ui.panel.config.energy.gas.dialog.cost_stat_input"
)} (${this._hassConfig.currency})`}
@value-changed=${this._priceStatChanged}
></ha-statistic-picker>`;
case "entity":
return html`<ha-entity-picker
.disabled=${this._saving}
include-domains='["sensor", "input_number"]'
.value=${this._source!.entity_energy_price}
.label=${this._localize(
"ui.panel.config.energy.gas.dialog.cost_entity_input"
)}
.helper=${
pickedUnitClass
? html`<ha-markdown
.content=${this._localize(
"ui.panel.config.energy.gas.dialog.cost_entity_helper",
pickedUnitClass === "energy"
? {
currency: this._hassConfig.currency,
class: this._localize(
"ui.panel.config.energy.gas.dialog.cost_entity_helper_energy"
),
unit1: "kWh",
unit2: "Wh",
}
: {
currency: this._hassConfig.currency,
class: this._localize(
"ui.panel.config.energy.gas.dialog.cost_entity_helper_volume"
),
unit1: "m³",
unit2: "ft³",
}
)}
></ha-markdown>`
: nothing
}
@value-changed=${this._priceEntityChanged}
></ha-entity-picker>`;
case "number":
return html`<ha-input
.disabled=${this._saving}
.label=${`${this._localize(
"ui.panel.config.energy.gas.dialog.cost_number_input"
)} ${unitPrice ? ` (${unitPrice})` : ""}`}
step="any"
type="number"
required
auto-validate
.value=${this._numberPriceText}
@input=${this._numberPriceChanged}
>
${unitPrice ? html`<span slot="end">${unitPrice}</span>` : nothing}
</ha-input>`;
default:
return nothing;
}
}
private _handleCostChanged(ev: HaSelectSelectEvent) {
this._costs = ev.detail.value as CostType;
this._updateFormDirtyState();
}
private _numberPriceChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
// Render the typed text so partial input such as "0." is not rewritten
this._numberPriceText = ev.currentTarget.value ?? "";
this._source = {
...this._source!,
number_energy_price: this._numberPriceText
? parseFloat(this._numberPriceText)
: null,
entity_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _priceStatChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: null,
number_energy_price: null,
stat_cost: ev.detail.value,
};
this._updateFormDirtyState();
}
private _priceEntityChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: ev.detail.value,
number_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _flowRateStatisticChanged(ev: ValueChangedEvent<string>) {
this._source = {
...this._source!,
stat_rate: ev.detail.value || undefined,
};
this._updateFormDirtyState();
}
private async _statisticChanged(ev: ValueChangedEvent<string>) {
if (ev.detail.value) {
const [metadata] = await getStatisticMetadata(this._api.callWS, [
ev.detail.value,
]);
if (
metadata &&
isExternalStatistic(ev.detail.value) &&
this.params.statsMetadata &&
!(ev.detail.value in this.params.statsMetadata)
) {
this.params.statsMetadata[ev.detail.value] = metadata;
}
this._pickedDisplayUnit = getDisplayUnit(
this._states,
ev.detail.value,
metadata
);
if (isExternalStatistic(ev.detail.value) && this._costs !== "statistic") {
this._costs = "no-costs";
}
} else {
this._pickedDisplayUnit = undefined;
}
this._source = {
...this._source!,
stat_energy_from: ev.detail.value,
};
this._updateFormDirtyState();
}
private _nameChanged(ev: InputEvent) {
this._source = {
...this._source!,
name: (ev.target as HaInput).value,
};
if (!this._source.name) {
delete this._source.name;
}
this._updateFormDirtyState();
}
private _updateFormDirtyState(): void {
this._updateDirtyState({ source: this._source!, costs: this._costs });
}
private _integralUnits(): IntegralUnits | undefined {
const statRate = this._source?.stat_rate;
// Gas sources can't mix volume and energy units
if (
!statRate ||
!this._gas_units ||
this.params.allowedGasUnitClass === "energy"
) {
return undefined;
}
return integralUnits(this._rateUnit, this._gas_units);
}
private _flowRateError(): string | undefined {
if (
this._source?.stat_energy_from ||
!this._source?.stat_rate ||
!this._gas_units ||
this._integralUnits()
) {
return undefined;
}
return this._localize(
this.params.allowedGasUnitClass === "energy"
? "ui.panel.config.energy.gas.dialog.flow_rate_energy_sources"
: "ui.panel.config.energy.gas.dialog.flow_rate_no_volume"
);
}
private _integralTotalUnit(): string | undefined {
const units = this._integralUnits();
if (!units) {
return undefined;
}
const statRate = this._source!.stat_rate!;
// A reused helper can display another unit than a new one would
const existing = findIntegral(
this._states,
this._entities,
statRate,
"gas",
this._excludeList
);
return existing
? getDisplayUnit(this._states, existing, undefined) || undefined
: integralTotalUnit(this._rateUnit!, units);
}
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but a created helper must still
// be saved with the submitted source
const params = this.params;
const costs = this._costs;
let source = this._source!;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_from) {
const statEnergyFrom = await this._gasFromFlowRate(source);
if (!statEnergyFrom) {
return false;
}
source = { ...source, stat_energy_from: statEnergyFrom };
if (isCurrent()) {
this._pickedDisplayUnit = this._integralTotalUnit();
// Keep edits made meanwhile, only fill in the new sensor
this._source = { ...this._source!, stat_energy_from: statEnergyFrom };
this._updateFormDirtyState();
}
}
if (costs === "no-costs") {
source = {
...source,
entity_energy_price: null,
number_energy_price: null,
stat_cost: null,
};
}
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
private async _gasFromFlowRate(
draft: GasSourceTypeEnergyPreference
): Promise<string | undefined> {
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: "gas",
states: this._states,
entities: this._entities,
requests: [
{
rate: statRate,
units,
name: this._localize(
"ui.panel.config.energy.integral.gas.sensor_name",
{
name: computeEnergyLabel(
this._states,
this._formatEntityName,
statRate,
this.params.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this._localize(
"ui.panel.config.energy.gas.dialog.gas_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this.params.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-energy-gas-source-editor": HaEnergyGasSourceEditor;
}
}
@@ -1,15 +1,24 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HassConfig } from "home-assistant-js-websocket";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { transform } from "../../../../common/decorators/transform";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-alert";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import {
apiContext,
configContext,
entitiesContext,
formattersContext,
statesContext,
} from "../../../../data/context";
import type { HomeSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
@@ -18,33 +27,50 @@ import {
} from "../../../../data/energy";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyle, haStyleDialog } from "../../../../resources/styles";
import type { ValueChangedEvent } from "../../../../types";
import type { IntegralUnits } from "./energy-integral";
import { confirmIntegrals, integralUnits } from "./energy-integral";
import type { EnergySettingsHomeDialogParams } from "./show-dialogs-energy";
import { DialogMixin } from "../../../../dialogs/dialog-mixin";
import {
configContext,
entitiesContext,
internationalizationContext,
statesContext,
} from "../../../../data/context";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
import type { IntegralUnits } from "../dialogs/energy-integral";
import { confirmIntegrals, integralUnits } from "../dialogs/energy-integral";
import type {
EnergyEditorStatus,
EnergyHomeSourceEditorParams,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-home-settings")
export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSourceTypeEnergyPreference>()(
DialogMixin<EnergySettingsHomeDialogParams>(LitElement)
@customElement("ha-energy-home-source-editor")
export class HaEnergyHomeSourceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<HomeSourceTypeEnergyPreference>()(LitElement)
) {
@property({ attribute: false }) public params!: EnergyHomeSourceEditorParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@state()
@consume({ context: configContext, subscribe: true })
private _hassConfig!: ContextType<typeof configContext>;
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
@@ -56,7 +82,7 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, string>({
transformer: function (this: DialogEnergyHomeSettings, states) {
transformer: function (this: HaEnergyHomeSourceEditor, states) {
const statRate = this._source?.stat_rate;
return statRate
? states?.[statRate]?.attributes.unit_of_measurement
@@ -76,60 +102,64 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
@state() private _saving = false;
connectedCallback() {
super.connectedCallback();
if (!this.params) {
return;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._error = undefined;
this._saving = false;
this._source = this.params.source
? { ...this.params.source }
: emptyHomeEnergyPreference();
this._initDirtyTracking({ type: "deep" }, this._source);
this._loadUnits();
}
this._source = this.params.source
? { ...this.params.source }
: emptyHomeEnergyPreference();
this._initDirtyTracking({ type: "deep" }, this._source);
this._loadUnits();
}
private async _loadUnits() {
const [energy, power] = await Promise.all([
getSensorDeviceClassConvertibleUnits(this.params!.hass, "energy"),
getSensorDeviceClassConvertibleUnits(this.params!.hass, "power"),
getSensorDeviceClassConvertibleUnits(this._api.callWS, "energy"),
getSensorDeviceClassConvertibleUnits(this._api.callWS, "power"),
]);
this._energy_units = energy.units;
this._power_units = power.units;
}
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid: !!(this._source?.stat_energy_to || this._integralUnits()),
saving: this._saving,
};
}
protected render() {
if (!this.params || !this._source) {
if (!this._source) {
return nothing;
}
return html`
<ha-dialog
open
header-title=${this._i18n.localize(
"ui.panel.config.energy.home.dialog.header"
)}
.preventScrimClose=${this.isDirtyState}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${energyUnitClasses}
.value=${this._source.stat_energy_to}
.label=${this._i18n.localize(
.label=${this._localize(
"ui.panel.config.energy.home.dialog.home_energy"
)}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this._i18n.localize(
.helper=${this._localize(
"ui.panel.config.energy.home.dialog.entity_para",
{ unit: this._energy_units?.join(", ") || "" }
)}
autofocus
></ha-statistic-picker>
<ha-input
.label=${this._i18n.localize(
.label=${this._localize(
"ui.panel.config.energy.home.dialog.display_name"
)}
type="text"
@@ -138,47 +168,27 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
this._saving
}
.value=${this._source.name || ""}
.placeholder=${this._hassConfig.config.location_name}
.placeholder=${this._hassConfig.location_name}
@input=${this._nameChanged}
>
</ha-input>
</div>
<ha-statistic-picker
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this._i18n.localize(
"ui.panel.config.energy.home.dialog.home_power"
)}
@value-changed=${this._powerStatisticChanged}
.disabled=${this._saving}
.helper=${this._i18n.localize(
"ui.panel.config.energy.home.dialog.entity_para",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<wa-divider></wa-divider>
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this._i18n.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!(this._source.stat_energy_to || this._integralUnits()) ||
(!!this.params.source && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this._i18n.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
<ha-statistic-picker
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this._localize(
"ui.panel.config.energy.home.dialog.home_power"
)}
@value-changed=${this._powerStatisticChanged}
.disabled=${this._saving}
.helper=${this._localize(
"ui.panel.config.energy.home.dialog.entity_para",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
`;
}
@@ -209,19 +219,19 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
: undefined;
}
private async _save() {
// Closing or reopening the dialog replaces its state, but a created helper
// must still be saved with the submitted source
const params = this.params!;
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but a created helper must still
// be saved with the submitted source
const params = this.params;
let source = this._source!;
const isCurrent = () => this.params === params;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_to) {
const statEnergyTo = await this._energyFromPower(source);
if (!statEnergyTo) {
return;
return false;
}
source = { ...source, stat_energy_to: statEnergyTo };
if (isCurrent()) {
@@ -233,12 +243,13 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
@@ -249,13 +260,15 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
private async _energyFromPower(
draft: HomeSourceTypeEnergyPreference
): Promise<string | undefined> {
const hass = this.params!.hass;
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, hass, {
const sensors = await confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: "energy",
states: this._states,
entities: this._entities,
@@ -263,12 +276,12 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
{
rate: statRate,
units,
name: this._i18n.localize(
name: this._localize(
"ui.panel.config.energy.integral.energy.sensor_name",
{
name: computeEnergyLabel(
this._states,
hass.formatEntityName,
this._formatEntityName,
statRate,
undefined,
draft.name
@@ -277,7 +290,7 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
),
},
],
intro: this._i18n.localize(
intro: this._localize(
"ui.panel.config.energy.home.dialog.energy_sensor_needed"
),
});
@@ -285,22 +298,12 @@ export class DialogEnergyHomeSettings extends DirtyStateProviderMixin<HomeSource
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
ha-statistic-picker {
display: block;
width: 100%;
margin-bottom: var(--ha-space-4);
}
`,
];
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-home-settings": DialogEnergyHomeSettings;
"ha-energy-home-source-editor": HaEnergyHomeSourceEditor;
}
}
@@ -0,0 +1,519 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import { mdiPlus } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import { transform } from "../../../../common/decorators/transform";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-alert";
import "../../../../components/ha-button";
import "../../../../components/ha-checkbox";
import type { HaCheckbox } from "../../../../components/ha-checkbox";
import "../../../../components/ha-svg-icon";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import type { ConfigEntry } from "../../../../data/config_entries";
import { getConfigEntries } from "../../../../data/config_entries";
import type { SolarSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
emptySolarEnergyPreference,
energyStatisticHelpUrl,
} from "../../../../data/energy";
import { domainToName } from "../../../../data/integration";
import {
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import { showConfigFlowDialog } from "../../../../dialogs/config-flow/show-dialog-config-flow";
import {
apiContext,
brandsAccessTokenContext,
connectionContext,
entitiesContext,
formattersContext,
statesContext,
uiContext,
} from "../../../../data/context";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import type {
HomeAssistantApi,
HomeAssistantFormatters,
HomeAssistantUI,
ValueChangedEvent,
} from "../../../../types";
import { brandsUrl } from "../../../../util/brands-url";
import type { IntegralUnits } from "../dialogs/energy-integral";
import { confirmIntegrals, integralUnits } from "../dialogs/energy-integral";
import type {
EnergyEditorStatus,
EnergySolarSourceEditorParams,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("ha-energy-solar-source-editor")
export class HaEnergySolarSourceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<SolarSourceTypeEnergyPreference>()(LitElement)
) {
@property({ attribute: false })
public params!: EnergySolarSourceEditorParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@consume({ context: connectionContext, subscribe: true })
private _connection!: ContextType<typeof connectionContext>;
@state()
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, boolean | undefined>({
transformer: ({ themes }) => themes?.darkMode,
})
private _darkMode?: boolean;
@state()
@consume({ context: brandsAccessTokenContext, subscribe: true })
// @ts-ignore re-render trigger only, its value is never read
private _brandsAccessToken?: string;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, string>({
transformer: function (this: HaEnergySolarSourceEditor, states) {
const statRate = this._source?.stat_rate;
return statRate
? states?.[statRate]?.attributes.unit_of_measurement
: undefined;
},
watch: ["_source"],
})
private _rateUnit?: string;
@state() private _source?: SolarSourceTypeEnergyPreference;
@state() private _configEntries?: ConfigEntry[];
@state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string;
@state() private _saving = false;
private _excludeList?: string[];
private _excludeListPower?: string[];
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._error = undefined;
this._saving = false;
this._source = params.source
? { ...params.source }
: emptySolarEnergyPreference();
this._excludeList = params.solar_sources
.map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from);
this._excludeListPower = params.solar_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
this._initDirtyTracking({ type: "deep" }, this._source);
this._fetchSolarForecastConfigEntries();
this._loadUnits();
}
private async _loadUnits() {
const [energy, power] = await Promise.all([
getSensorDeviceClassConvertibleUnits(this._api.callWS, "energy"),
getSensorDeviceClassConvertibleUnits(this._api.callWS, "power"),
]);
this._energy_units = energy.units;
this._power_units = power.units;
}
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid: !!(this._source?.stat_energy_from || this._integralUnits()),
saving: this._saving,
};
}
protected render() {
if (!this._source) {
return nothing;
}
const labelStatistic =
this._source.stat_energy_from || this._source.stat_rate;
return html`
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${energyUnitClasses}
.value=${this._source.stat_energy_from}
.label=${this._localize(
"ui.panel.config.energy.solar.dialog.solar_production_energy"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this._localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._energy_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-input
.label=${this._localize(
"ui.panel.config.energy.solar.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this._states,
this._formatEntityName,
labelStatistic,
this.params.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
</div>
<wa-divider></wa-divider>
<ha-statistic-picker
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this._localize(
"ui.panel.config.energy.solar.dialog.solar_production_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.disabled=${this._saving}
.helper=${this._localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<wa-divider></wa-divider>
<div class="group">
<div class="group-header">
<h3>
${this._localize(
"ui.panel.config.energy.solar.dialog.solar_production_forecast"
)}
</h3>
<p>
${this._localize(
"ui.panel.config.energy.solar.dialog.solar_production_forecast_description"
)}
</p>
</div>
${
this._configEntries?.length
? html`<div class="forecast-options">
${this._configEntries.map(
(entry) =>
html`<ha-checkbox
.entry=${entry}
@change=${this._forecastCheckChanged}
.disabled=${this._saving}
.checked=${!!this._source?.config_entry_solar_forecast?.includes(
entry.entry_id
)}
>
<div class="forecast-option">
<img
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: entry.domain,
type: "icon",
darkOptimized: this._darkMode,
},
this._connection.hassUrl()
)}
/>${entry.title || domainToName(this._localize, entry.domain)}
</div>
</ha-checkbox>`
)}
</div>`
: nothing
}
<ha-button
appearance="filled"
size="s"
@click=${this._addForecast}
.disabled=${this._saving}
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
${this._localize("ui.panel.config.energy.solar.dialog.add_forecast")}
</ha-button>
</div>
`;
}
private async _fetchSolarForecastConfigEntries() {
const domains = this.params.info.solar_forecast_domains;
this._configEntries =
domains.length === 0
? []
: domains.length === 1
? await getConfigEntries(this._api, {
type: ["service"],
domain: domains[0],
})
: (await getConfigEntries(this._api, { type: ["service"] })).filter(
(entry) => domains.includes(entry.domain)
);
}
private _forecastCheckChanged(ev) {
const input = ev.currentTarget as HaCheckbox;
const entry = (input as any).entry as ConfigEntry;
const checked = input.checked;
const list = this._source!.config_entry_solar_forecast
? [...this._source!.config_entry_solar_forecast]
: [];
if (checked) {
list.push(entry.entry_id);
} else {
list.splice(list.indexOf(entry.entry_id), 1);
}
this._source = {
...this._source!,
config_entry_solar_forecast: list.length ? list : null,
};
this._updateDirtyState(this._source);
}
private _addForecast() {
showConfigFlowDialog(this, {
startFlowHandler: "forecast_solar",
dialogClosedCallback: (params) => {
if (params.entryId) {
const list = this._source!.config_entry_solar_forecast
? [...this._source!.config_entry_solar_forecast]
: [];
list.push(params.entryId);
this._source = {
...this._source!,
config_entry_solar_forecast: list,
};
this._fetchSolarForecastConfigEntries();
this._updateDirtyState(this._source);
}
},
});
}
private async _statisticChanged(ev: ValueChangedEvent<string>) {
this._source = { ...this._source!, stat_energy_from: ev.detail.value };
this._updateDirtyState(this._source);
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this.params.statsMetadata &&
!(ev.detail.value in this.params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this._api.callWS, [
ev.detail.value,
]);
if (metadata) {
this.params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate();
}
}
}
private _powerStatisticChanged(ev: ValueChangedEvent<string>) {
this._source = { ...this._source!, stat_rate: ev.detail.value };
this._updateDirtyState(this._source);
}
private _nameChanged(ev: InputEvent) {
this._source = {
...this._source!,
name: (ev.target as HaInput).value,
};
if (!this._source.name) {
delete this._source.name;
}
this._updateDirtyState(this._source);
}
private _integralUnits(): IntegralUnits | undefined {
const statRate = this._source?.stat_rate;
if (!statRate || !this._energy_units) {
return undefined;
}
return integralUnits(this._rateUnit, this._energy_units);
}
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but a created helper must still
// be saved with the submitted source
const params = this.params;
let source = this._source!;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_from) {
const statEnergyFrom = await this._energyFromPower(source);
if (!statEnergyFrom) {
return false;
}
source = { ...source, stat_energy_from: statEnergyFrom };
if (isCurrent()) {
// Keep edits made meanwhile, only fill in the new energy sensor
this._source = { ...this._source!, stat_energy_from: statEnergyFrom };
this._updateDirtyState(this._source);
}
}
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
private async _energyFromPower(
draft: SolarSourceTypeEnergyPreference
): Promise<string | undefined> {
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: "energy",
states: this._states,
entities: this._entities,
requests: [
{
rate: statRate,
units,
name: this._localize(
"ui.panel.config.energy.integral.energy.sensor_name",
{
name: computeEnergyLabel(
this._states,
this._formatEntityName,
statRate,
this.params.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this._localize(
"ui.panel.config.energy.solar.dialog.energy_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this.params.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return [
energyEditorStyles,
css`
.forecast-options {
display: flex;
flex-direction: column;
min-width: 0;
gap: var(--ha-space-2);
}
.forecast-options ha-checkbox {
justify-content: center;
min-height: 40px;
}
.forecast-option {
display: flex;
align-items: center;
gap: var(--ha-space-4);
}
.forecast-option img {
height: 24px;
}
ha-button {
width: fit-content;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-energy-solar-source-editor": HaEnergySolarSourceEditor;
}
}
@@ -1,15 +1,25 @@
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import { consume } from "../../../../common/decorators/consume";
import { transform } from "../../../../common/decorators/transform";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../../common/translations/localize";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-alert";
import "../../../../components/input/ha-input";
import "./ha-energy-upstream-device-picker";
import type { HaInput } from "../../../../components/input/ha-input";
import {
apiContext,
entitiesContext,
formattersContext,
statesContext,
} from "../../../../data/context";
import type {
DeviceConsumptionEnergyPreference,
WaterGasResource,
@@ -24,30 +34,67 @@ import {
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { IntegralUnits } from "./energy-integral";
import { confirmIntegrals, integralUnits } from "./energy-integral";
import type { EnergySettingsDeviceWaterGasDialogParams } from "./show-dialogs-energy";
import type { LocalizeKeys } from "../../../../common/translations/localize";
import type {
HomeAssistantApi,
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
import type { IntegralUnits } from "../dialogs/energy-integral";
import { confirmIntegrals, integralUnits } from "../dialogs/energy-integral";
import "../dialogs/ha-energy-upstream-device-picker";
import type {
EnergyEditorStatus,
EnergyWaterGasDeviceEditorParams,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
const flowRateUnitClasses = ["volume_flow_rate"];
// Without a consumption sensor, saving offers to create one from the flow rate sensor
type DeviceConsumptionDraft = Partial<DeviceConsumptionEnergyPreference>;
@customElement("dialog-energy-device-settings-water-gas")
export class DialogEnergyDeviceSettingsWaterGas
extends DirtyStateProviderMixin<DeviceConsumptionDraft | null>()(LitElement)
implements HassDialog<EnergySettingsDeviceWaterGasDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@customElement("ha-energy-water-gas-device-editor")
export class HaEnergyWaterGasDeviceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<DeviceConsumptionDraft | null>()(LitElement)
) {
@property({ attribute: false })
public params!: EnergyWaterGasDeviceEditorParams;
@state() private _params?: EnergySettingsDeviceWaterGasDialogParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _open = false;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, string>({
transformer: function (this: HaEnergyWaterGasDeviceEditor, states) {
const statRate = this._device?.stat_rate;
return statRate
? states?.[statRate]?.attributes.unit_of_measurement
: undefined;
},
watch: ["_device"],
})
private _rateUnit?: string;
@state() private _device?: DeviceConsumptionDraft;
@@ -67,50 +114,62 @@ export class DialogEnergyDeviceSettingsWaterGas
private _possibleParents: DeviceConsumptionEnergyPreference[] = [];
public async showDialog(
params: EnergySettingsDeviceWaterGasDialogParams
): Promise<void> {
this._params = params;
this._device = this._params.device;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._device = params.device;
this._error = undefined;
this._saving = false;
this._computePossibleParents();
this._volume_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, params.resource)
).units;
this._energy_units =
params.resource === "gas"
? (await getSensorDeviceClassConvertibleUnits(this.hass, "energy"))
.units
: [];
this._flow_rate_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "volume_flow_rate")
).units;
this._excludeList = this._params.device_consumptions
this._excludeList = params.device_consumptions
.map((entry) => entry.stat_consumption)
.filter((id) => id !== this._device?.stat_consumption);
this._excludeListFlowRate = this._params.device_consumptions
this._excludeListFlowRate = params.device_consumptions
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._device?.stat_rate) as string[];
this._open = true;
this._initDirtyTracking({ type: "deep" }, this._device ?? null);
this._loadUnits();
}
private async _loadUnits() {
const [volume, flowRate, energy] = await Promise.all([
getSensorDeviceClassConvertibleUnits(
this._api.callWS,
this.params.resource
),
getSensorDeviceClassConvertibleUnits(
this._api.callWS,
"volume_flow_rate"
),
this.params.resource === "gas"
? getSensorDeviceClassConvertibleUnits(this._api.callWS, "energy")
: { units: [] },
]);
this._volume_units = volume.units;
this._flow_rate_units = flowRate.units;
this._energy_units = energy.units;
}
private get _resource(): WaterGasResource {
return this._params!.resource;
return this.params.resource;
}
private _t(key: string, params?: Record<string, string>): string {
return this.hass.localize(
return this._localize(
`ui.panel.config.energy.device_consumption_${this._resource}.dialog.${key}` as LocalizeKeys,
params as any
params
);
}
private get _unitClasses(): string[] {
if (this._params?.allowedUnitClass) {
return [this._params.allowedUnitClass];
if (this.params.allowedUnitClass) {
return [this.params.allowedUnitClass];
}
return this._resource === "gas" ? ["volume", "energy"] : ["volume"];
}
@@ -119,7 +178,7 @@ export class DialogEnergyDeviceSettingsWaterGas
if (this._resource === "water") {
return undefined;
}
switch (this._params?.allowedUnitClass) {
switch (this.params.allowedUnitClass) {
case "volume":
return ["gas"];
case "energy":
@@ -144,44 +203,44 @@ export class DialogEnergyDeviceSettingsWaterGas
// device will be labelled by, so there is no entity to tell it apart yet.
if (!device.stat_consumption) {
return computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statisticId,
this._params?.statsMetadata?.[statisticId]
this.params.statsMetadata?.[statisticId]
);
}
// The saved entry of the device being edited is replaced by the draft
// without a display name, which is what the placeholder stands for. The
// draft may point at another statistic by now, so match the saved one.
const edited = this._params?.device?.stat_consumption;
const edited = this.params.device?.stat_consumption;
const devices = [
...(this._params?.device_consumptions ?? []).filter(
...this.params.device_consumptions.filter(
(other) => other.stat_consumption !== edited
),
{ ...device, name: undefined },
];
return computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statisticId,
this._params?.statsMetadata?.[statisticId],
this.params.statsMetadata?.[statisticId],
undefined,
computeAmbiguousEnergyDevices(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
devices
).has(statisticId)
);
}
private _computePossibleParents() {
if (!this._device || !this._params) {
if (!this._device) {
this._possibleParents = [];
return;
}
const children: string[] = [];
const devices = this._params.device_consumptions;
const devices = this.params.device_consumptions;
function getChildren(stat) {
devices.forEach((d) => {
if (d.included_in_stat === stat) {
@@ -192,56 +251,44 @@ export class DialogEnergyDeviceSettingsWaterGas
}
// Saving without a consumption sensor can reuse the original one
const stat =
this._device.stat_consumption ?? this._params.device?.stat_consumption;
this._device.stat_consumption ?? this.params.device?.stat_consumption;
if (stat) {
getChildren(stat);
}
this._possibleParents = this._params.device_consumptions.filter(
this._possibleParents = this.params.device_consumptions.filter(
(d) =>
d.stat_consumption !== this._device!.stat_consumption &&
d.stat_consumption !== this._params?.device?.stat_consumption &&
d.stat_consumption !== this.params.device?.stat_consumption &&
!children.includes(d.stat_consumption)
);
}
public closeDialog() {
this._open = false;
return true;
}
private _dialogClosed() {
this._params = undefined;
this._device = undefined;
this._error = undefined;
this._excludeList = undefined;
this._excludeListFlowRate = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid: !!(this._device?.stat_consumption || this._integralUnits()),
saving: this._saving,
};
}
protected render() {
if (!this._params) {
return nothing;
}
const resource = this._resource;
const pickableUnit = [
...(this._params.allowedUnitClass === "energy"
...(this.params.allowedUnitClass === "energy"
? []
: this._volume_units || []),
...(this._params.allowedUnitClass === "volume"
...(this.params.allowedUnitClass === "volume"
? []
: this._energy_units || []),
].join(", ");
return html`
<ha-dialog
.open=${this._open}
header-title=${this._t("header")}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${this._unitClasses}
@@ -252,23 +299,7 @@ export class DialogEnergyDeviceSettingsWaterGas
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this._t("selected_stat_intro", { unit: pickableUnit })}
autofocus
></ha-statistic-picker>
<ha-statistic-picker
.includeUnitClass=${flowRateUnitClasses}
.value=${this._device?.stat_rate}
.label=${this._t(`device_consumption_${resource}_flow_rate`)}
.excludeStatistics=${this._excludeListFlowRate}
@value-changed=${this._flowRateStatisticChanged}
.disabled=${this._saving}
.invalid=${!!this._flowRateError()}
.errorMessage=${this._flowRateError()}
.helper=${this._t("selected_stat_intro", {
unit: this._flow_rate_units?.join(", ") || "",
})}
></ha-statistic-picker>
<ha-input
.label=${this._t("display_name")}
type="text"
@@ -278,42 +309,37 @@ export class DialogEnergyDeviceSettingsWaterGas
@input=${this._nameChanged}
>
</ha-input>
</div>
<ha-energy-upstream-device-picker
.hass=${this.hass}
.label=${this._t("included_in_device")}
.helper=${this._t("included_in_device_helper")}
.value=${this._device?.included_in_stat}
.possibleParents=${this._possibleParents}
.devices=${this._params.device_consumptions}
.statsMetadata=${this._params.statsMetadata}
.emptyLabel=${this._t("no_upstream_devices")}
.disabled=${!this._device || this._saving}
@value-changed=${this._parentChanged}
></ha-energy-upstream-device-picker>
<wa-divider></wa-divider>
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${
this._saving ||
!(this._device?.stat_consumption || this._integralUnits()) ||
(!!this._params?.device && !this.isDirtyState)
}
.loading=${this._saving}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
<ha-statistic-picker
.includeUnitClass=${flowRateUnitClasses}
.value=${this._device?.stat_rate}
.label=${this._t(`device_consumption_${resource}_flow_rate`)}
.excludeStatistics=${this._excludeListFlowRate}
@value-changed=${this._flowRateStatisticChanged}
.disabled=${this._saving}
.invalid=${!!this._flowRateError()}
.errorMessage=${this._flowRateError()}
.helper=${this._t("selected_stat_intro", {
unit: this._flow_rate_units?.join(", ") || "",
})}
></ha-statistic-picker>
<wa-divider></wa-divider>
<ha-energy-upstream-device-picker
.label=${this._t("included_in_device")}
.helper=${this._t("included_in_device_helper")}
.value=${this._device?.included_in_stat}
.possibleParents=${this._possibleParents}
.devices=${this.params.device_consumptions}
.statsMetadata=${this.params.statsMetadata}
.emptyLabel=${this._t("no_upstream_devices")}
.disabled=${!this._device || this._saving}
@value-changed=${this._parentChanged}
></ha-energy-upstream-device-picker>
`;
}
@@ -341,15 +367,15 @@ export class DialogEnergyDeviceSettingsWaterGas
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this._params?.statsMetadata &&
!(ev.detail.value in this._params.statsMetadata)
this.params.statsMetadata &&
!(ev.detail.value in this.params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this.hass.callWS, [
const [metadata] = await getStatisticMetadata(this._api.callWS, [
ev.detail.value,
]);
if (metadata) {
this._params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate("_params");
this.params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate();
}
}
}
@@ -402,7 +428,7 @@ export class DialogEnergyDeviceSettingsWaterGas
return undefined;
}
return this._t(
this._params?.allowedUnitClass === "energy"
this.params.allowedUnitClass === "energy"
? "flow_rate_energy_sources"
: "flow_rate_no_volume"
);
@@ -413,29 +439,26 @@ export class DialogEnergyDeviceSettingsWaterGas
if (
!statRate ||
!this._volume_units ||
this._params?.allowedUnitClass === "energy"
this.params.allowedUnitClass === "energy"
) {
return undefined;
}
return integralUnits(
this.hass.states[statRate]?.attributes.unit_of_measurement,
this._volume_units
);
return integralUnits(this._rateUnit, this._volume_units);
}
private async _save() {
// Closing or reopening the dialog replaces its state, but a created helper
// must still be saved with the submitted device
const params = this._params!;
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but a created helper must still
// be saved with the submitted device
const params = this.params;
const draft = this._device!;
const isCurrent = () => this._params === params;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
const statConsumption =
draft.stat_consumption ?? (await this._volumeFromFlowRate(draft));
if (!statConsumption) {
return;
return false;
}
const device = { ...draft, stat_consumption: statConsumption };
if (isCurrent()) {
@@ -445,12 +468,13 @@ export class DialogEnergyDeviceSettingsWaterGas
await params.saveCallback(device);
if (isCurrent()) {
this._markDirtyStateClean();
this.closeDialog();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
@@ -467,61 +491,45 @@ export class DialogEnergyDeviceSettingsWaterGas
return undefined;
}
const resource = this._resource;
const sensors = await confirmIntegrals(this, this.hass, {
const sensors = await confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: resource,
states: this.hass.states,
entities: this.hass.entities,
states: this._states,
entities: this._entities,
requests: [
{
rate: statRate,
units,
name: this.hass.localize(
name: this._localize(
`ui.panel.config.energy.integral.${resource}.sensor_name` as LocalizeKeys,
{
name: computeEnergyLabel(
this.hass.states,
this.hass.formatEntityName,
this._states,
this._formatEntityName,
statRate,
this._params?.statsMetadata?.[statRate],
this.params.statsMetadata?.[statRate],
draft.name
),
} as any
}
),
},
],
intro: this._t(`${resource}_sensor_needed`),
exclude: this._excludeList,
statsMetadata: this._params?.statsMetadata,
statsMetadata: this.params.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return [
haStyleDialog,
css`
ha-statistic-picker {
display: block;
width: 100%;
margin-bottom: var(--ha-space-4);
}
ha-energy-upstream-device-picker {
display: block;
margin-top: var(--ha-space-4);
width: 100%;
}
ha-input {
margin-top: var(--ha-space-4);
--ha-input-padding-bottom: 0;
width: 100%;
}
`,
];
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-device-settings-water-gas": DialogEnergyDeviceSettingsWaterGas;
"ha-energy-water-gas-device-editor": HaEnergyWaterGasDeviceEditor;
}
}
@@ -0,0 +1,583 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HassConfig } from "home-assistant-js-websocket";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { transform } from "../../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-alert";
import "../../../../components/ha-markdown";
import "../../../../components/ha-select";
import type {
HaSelectOption,
HaSelectSelectEvent,
} from "../../../../components/ha-select";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import {
apiContext,
configContext,
entitiesContext,
formattersContext,
statesContext,
} from "../../../../data/context";
import type { WaterSourceTypeEnergyPreference } from "../../../../data/energy";
import {
computeEnergyLabel,
emptyWaterEnergyPreference,
energyStatisticHelpUrl,
} from "../../../../data/energy";
import {
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
} from "../../../../data/recorder";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
import type { IntegralUnits } from "../dialogs/energy-integral";
import { confirmIntegrals, integralUnits } from "../dialogs/energy-integral";
import type {
EnergyEditorStatus,
EnergyWaterSourceEditorParams,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
type CostType = "no-costs" | "number" | "entity" | "statistic";
interface WaterFormState {
source: WaterSourceTypeEnergyPreference;
costs: CostType;
}
const flowRateUnitClasses = ["volume_flow_rate"];
@customElement("ha-energy-water-source-editor")
export class HaEnergyWaterSourceEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<WaterFormState>()(LitElement)
) {
@property({ attribute: false })
public params!: EnergyWaterSourceEditorParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
// Kept current without rendering on every state change
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, string>({
transformer: function (this: HaEnergyWaterSourceEditor, states) {
const statRate = this._source?.stat_rate;
return statRate
? states?.[statRate]?.attributes.unit_of_measurement
: undefined;
},
watch: ["_source"],
})
private _rateUnit?: string;
@state() private _source?: WaterSourceTypeEnergyPreference;
@state() private _costs: CostType = "no-costs";
@state() private _numberPriceText = "";
@state() private _water_units?: string[];
@state() private _flow_rate_units?: string[];
@state() private _error?: string;
@state() private _saving = false;
private _excludeList?: string[];
private _excludeListFlowRate?: string[];
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._error = undefined;
this._saving = false;
this._source = params.source
? { ...params.source }
: emptyWaterEnergyPreference();
this._costs = this._source.entity_energy_price
? "entity"
: typeof this._source.number_energy_price === "number"
? "number"
: this._source.stat_cost
? "statistic"
: "no-costs";
this._numberPriceText =
typeof this._source.number_energy_price === "number"
? String(this._source.number_energy_price)
: "";
this._excludeList = params.water_sources
.map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from);
this._excludeListFlowRate = params.water_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
this._initDirtyTracking(
{ type: "deep" },
{ source: this._source, costs: this._costs }
);
this._loadUnits();
}
private async _loadUnits() {
const [water, flowRate] = await Promise.all([
getSensorDeviceClassConvertibleUnits(this._api.callWS, "water"),
getSensorDeviceClassConvertibleUnits(
this._api.callWS,
"volume_flow_rate"
),
]);
this._water_units = water.units;
this._flow_rate_units = flowRate.units;
}
protected get editorStatus(): EnergyEditorStatus {
return {
dirty: this.isDirtyState,
valid:
!!(this._source?.stat_energy_from || this._integralUnits()) &&
(this._costs !== "number" ||
typeof this._source?.number_energy_price === "number"),
saving: this._saving,
};
}
protected render() {
if (!this._source) {
return nothing;
}
const labelStatistic =
this._source.stat_energy_from || this._source.stat_rate;
return html`
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<div class="group">
<ha-statistic-picker
.helpMissingEntityUrl=${energyStatisticHelpUrl}
include-unit-class="volume"
include-device-class="water"
.value=${this._source.stat_energy_from}
.label=${this._localize(
"ui.panel.config.energy.water.dialog.water_usage"
)}
.excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged}
.disabled=${this._saving}
.helper=${this._localize(
"ui.panel.config.energy.water.dialog.entity_para",
{ unit: this._water_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-input
.label=${this._localize(
"ui.panel.config.energy.water.dialog.display_name"
)}
type="text"
.disabled=${!labelStatistic || this._saving}
.value=${this._source.name || ""}
.placeholder=${
labelStatistic
? getStatisticLabel(
this._states,
this._formatEntityName,
labelStatistic,
this.params.statsMetadata?.[labelStatistic]
)
: ""
}
@input=${this._nameChanged}
>
</ha-input>
</div>
<wa-divider></wa-divider>
<ha-statistic-picker
.includeUnitClass=${flowRateUnitClasses}
.value=${this._source.stat_rate}
.label=${this._localize(
"ui.panel.config.energy.water.dialog.water_flow_rate"
)}
.excludeStatistics=${this._excludeListFlowRate}
@value-changed=${this._flowRateStatisticChanged}
.disabled=${this._saving}
.invalid=${!!this._flowRateError()}
.errorMessage=${this._flowRateError()}
.helper=${this._localize(
"ui.panel.config.energy.water.dialog.flow_rate_para",
{ unit: this._flow_rate_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<wa-divider></wa-divider>
<div class="group">
<ha-select
.label=${this._localize(
"ui.panel.config.energy.water.dialog.cost_tracking"
)}
.helper=${this._localize(
"ui.panel.config.energy.water.dialog.cost_para"
)}
.value=${this._costs}
.options=${this._costOptions()}
.disabled=${this._saving}
@selected=${this._handleCostChanged}
></ha-select>
${this._renderCost()}
</div>
`;
}
private _costOptions(): HaSelectOption[] {
// External statistics (from integrations) cannot use entity/number cost tracking
const externalSource =
!!this._source?.stat_energy_from &&
isExternalStatistic(this._source.stat_energy_from);
return [
{
value: "no-costs",
label: this._localize("ui.panel.config.energy.water.dialog.no_cost"),
},
{
value: "statistic",
label: this._localize("ui.panel.config.energy.water.dialog.cost_stat"),
},
{
value: "entity",
label: this._localize(
"ui.panel.config.energy.water.dialog.cost_entity"
),
disabled: externalSource,
},
{
value: "number",
label: this._localize(
"ui.panel.config.energy.water.dialog.cost_number"
),
disabled: externalSource,
},
];
}
private _renderCost() {
const unitPriceFixed = `${this._hassConfig.currency}/${
this._hassConfig.unit_system.volume === "gal" ? "gal" : "m³"
}`;
switch (this._costs) {
case "statistic":
return html`<ha-statistic-picker
.disabled=${this._saving}
statistic-types="sum"
.value=${this._source!.stat_cost}
.label=${`${this._localize(
"ui.panel.config.energy.water.dialog.cost_stat_input"
)} (${this._hassConfig.currency})`}
@value-changed=${this._priceStatChanged}
></ha-statistic-picker>`;
case "entity":
return html`<ha-entity-picker
.disabled=${this._saving}
include-domains='["sensor", "input_number"]'
.value=${this._source!.entity_energy_price}
.label=${this._localize(
"ui.panel.config.energy.water.dialog.cost_entity_input"
)}
.helper=${html`<ha-markdown
.content=${this._localize(
"ui.panel.config.energy.water.dialog.cost_entity_helper",
{ currency: this._hassConfig.currency }
)}
></ha-markdown>`}
@value-changed=${this._priceEntityChanged}
></ha-entity-picker>`;
case "number":
return html`<ha-input
.disabled=${this._saving}
.label=${`${this._localize(
"ui.panel.config.energy.water.dialog.cost_number_input"
)} (${unitPriceFixed})`}
step="any"
type="number"
required
auto-validate
.value=${this._numberPriceText}
@input=${this._numberPriceChanged}
>
<span slot="end">${unitPriceFixed}</span>
</ha-input>`;
default:
return nothing;
}
}
private _handleCostChanged(ev: HaSelectSelectEvent) {
this._costs = ev.detail.value as CostType;
this._updateFormDirtyState();
}
private _numberPriceChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
// Render the typed text so partial input such as "0." is not rewritten
this._numberPriceText = ev.currentTarget.value ?? "";
this._source = {
...this._source!,
number_energy_price: this._numberPriceText
? parseFloat(this._numberPriceText)
: null,
entity_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _priceStatChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: null,
number_energy_price: null,
stat_cost: ev.detail.value,
};
this._updateFormDirtyState();
}
private _priceEntityChanged(ev: CustomEvent) {
this._numberPriceText = "";
this._source = {
...this._source!,
entity_energy_price: ev.detail.value,
number_energy_price: null,
stat_cost: null,
};
this._updateFormDirtyState();
}
private _flowRateStatisticChanged(ev: ValueChangedEvent<string>) {
this._source = {
...this._source!,
stat_rate: ev.detail.value || undefined,
};
this._updateFormDirtyState();
}
private async _statisticChanged(ev: ValueChangedEvent<string>) {
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this._costs !== "statistic"
) {
this._costs = "no-costs";
}
this._source = {
...this._source!,
stat_energy_from: ev.detail.value,
};
if (
ev.detail.value &&
isExternalStatistic(ev.detail.value) &&
this.params.statsMetadata &&
!(ev.detail.value in this.params.statsMetadata)
) {
const [metadata] = await getStatisticMetadata(this._api.callWS, [
ev.detail.value,
]);
if (metadata) {
this.params.statsMetadata[ev.detail.value] = metadata;
this.requestUpdate();
}
}
this._updateFormDirtyState();
}
private _nameChanged(ev: InputEvent) {
this._source = {
...this._source!,
name: (ev.target as HaInput).value,
};
if (!this._source.name) {
delete this._source.name;
}
this._updateFormDirtyState();
}
private _updateFormDirtyState(): void {
this._updateDirtyState({ source: this._source!, costs: this._costs });
}
private _flowRateError(): string | undefined {
if (
this._source?.stat_energy_from ||
!this._source?.stat_rate ||
!this._water_units ||
this._integralUnits()
) {
return undefined;
}
return this._localize(
"ui.panel.config.energy.water.dialog.flow_rate_no_volume"
);
}
private _integralUnits(): IntegralUnits | undefined {
const statRate = this._source?.stat_rate;
if (!statRate || !this._water_units) {
return undefined;
}
return integralUnits(this._rateUnit, this._water_units);
}
public async save(): Promise<boolean> {
// The editor can be replaced while saving, but a created helper must still
// be saved with the submitted source
const params = this.params;
const costs = this._costs;
let source = this._source!;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
if (!source.stat_energy_from) {
const statEnergyFrom = await this._waterFromFlowRate(source);
if (!statEnergyFrom) {
return false;
}
source = { ...source, stat_energy_from: statEnergyFrom };
if (isCurrent()) {
// Keep edits made meanwhile, only fill in the new sensor
this._source = { ...this._source!, stat_energy_from: statEnergyFrom };
this._updateFormDirtyState();
}
}
if (costs === "no-costs") {
source = {
...source,
entity_energy_price: null,
number_energy_price: null,
stat_cost: null,
};
}
await params.saveCallback(source);
if (isCurrent()) {
this._markDirtyStateClean();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
private async _waterFromFlowRate(
draft: WaterSourceTypeEnergyPreference
): Promise<string | undefined> {
const statRate = draft.stat_rate!;
const units = this._integralUnits();
if (!units) {
return undefined;
}
const sensors = await confirmIntegrals(this, {
api: this._api,
localize: this._localize,
formatEntityName: this._formatEntityName,
deviceClass: "water",
states: this._states,
entities: this._entities,
requests: [
{
rate: statRate,
units,
name: this._localize(
"ui.panel.config.energy.integral.water.sensor_name",
{
name: computeEnergyLabel(
this._states,
this._formatEntityName,
statRate,
this.params.statsMetadata?.[statRate],
draft.name
),
}
),
},
],
intro: this._localize(
"ui.panel.config.energy.water.dialog.water_sensor_needed"
),
exclude: this._excludeList,
statsMetadata: this.params.statsMetadata,
});
return sensors?.[0];
}
static get styles(): CSSResultGroup {
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-energy-water-source-editor": HaEnergyWaterSourceEditor;
}
}
@@ -0,0 +1,57 @@
import { html, nothing } from "lit";
import type { EnergyEditorConfig } from "./energy-editor";
import "./ha-energy-battery-source-editor";
import "./ha-energy-device-editor";
import "./ha-energy-gas-source-editor";
import "./ha-energy-grid-source-editor";
import "./ha-energy-home-source-editor";
import "./ha-energy-solar-source-editor";
import "./ha-energy-water-gas-device-editor";
import "./ha-energy-water-source-editor";
export const renderEnergyEditor = (config: EnergyEditorConfig) => {
switch (config.kind) {
case "grid":
return html`<ha-energy-grid-source-editor
class="energy-editor"
.params=${config.params}
></ha-energy-grid-source-editor>`;
case "solar":
return html`<ha-energy-solar-source-editor
class="energy-editor"
.params=${config.params}
></ha-energy-solar-source-editor>`;
case "home":
return html`<ha-energy-home-source-editor
class="energy-editor"
.params=${config.params}
></ha-energy-home-source-editor>`;
case "battery":
return html`<ha-energy-battery-source-editor
class="energy-editor"
.params=${config.params}
></ha-energy-battery-source-editor>`;
case "device":
return html`<ha-energy-device-editor
class="energy-editor"
.params=${config.params}
></ha-energy-device-editor>`;
case "gas":
return html`<ha-energy-gas-source-editor
class="energy-editor"
.params=${config.params}
></ha-energy-gas-source-editor>`;
case "water":
return html`<ha-energy-water-source-editor
class="energy-editor"
.params=${config.params}
></ha-energy-water-source-editor>`;
case "water_gas_device":
return html`<ha-energy-water-gas-device-editor
class="energy-editor"
.params=${config.params}
></ha-energy-water-gas-device-editor>`;
default:
return nothing;
}
};
+159 -4
View File
@@ -70,6 +70,13 @@ const TABS: PageNavigation[] = [
},
];
// Editor pages are at <tab>/<kind>/<key>, with `new` as the key of a new item
const EDITOR_KINDS: Record<string, string[]> = {
electricity: ["grid", "solar", "home", "battery", "device"],
gas: ["gas", "device"],
water: ["water", "device"],
};
@customElement("ha-config-energy")
class HaConfigEnergy extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -91,17 +98,25 @@ class HaConfigEnergy extends LitElement {
@state() private _statsMetadata?: Record<string, StatisticsMetaData>;
private get _currTab(): string {
return this.route.path.substring(1) || "electricity";
return this.route.path.split("/")[1] || "electricity";
}
protected willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has("route")) {
const tab = this.route.path.substring(1);
const [, tab, kind, ...key] = this.route.path.split("/");
if (!tab || !TABS.some((t) => t.path.endsWith(`/${tab}`))) {
navigate(`${this.route.prefix}/electricity${location.search}`, {
replace: true,
keepDialogs: true,
});
} else if (
kind &&
(!key.join("/") || !EDITOR_KINDS[tab].includes(kind))
) {
navigate(`${this.route.prefix}/${tab}${location.search}`, {
replace: true,
keepDialogs: true,
});
}
}
}
@@ -110,7 +125,7 @@ class HaConfigEnergy extends LitElement {
this._fetchConfig();
}
protected render(): TemplateResult {
protected render(): TemplateResult | typeof nothing {
if (!this._preferences && !this._error) {
return html`<hass-loading-screen
.hass=${this.hass}
@@ -126,6 +141,17 @@ class HaConfigEnergy extends LitElement {
></hass-error-screen>`;
}
const [, , kind, ...key] = this.route.path.split("/");
if (kind) {
// The page labels statistics with their metadata
return this._statsMetadata
? this._renderEditorPage(kind, decodeURIComponent(key.join("/")))
: html`<hass-loading-screen
.hass=${this.hass}
.narrow=${this.narrow}
></hass-loading-screen>`;
}
return html`
<hass-tabs-subpage
.hass=${this.hass}
@@ -158,12 +184,14 @@ class HaConfigEnergy extends LitElement {
}
private _renderTabContent(): TemplateResult | typeof nothing {
const listPath = `${this.route.prefix}/${this._currTab}`;
switch (this._currTab) {
case "electricity":
return html`
<ha-energy-grid-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -171,6 +199,7 @@ class HaConfigEnergy extends LitElement {
<ha-energy-solar-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
.info=${this._info}
@@ -179,12 +208,14 @@ class HaConfigEnergy extends LitElement {
<ha-energy-home-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
></ha-energy-home-settings>
<ha-energy-battery-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -192,6 +223,7 @@ class HaConfigEnergy extends LitElement {
<ha-energy-device-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -202,6 +234,7 @@ class HaConfigEnergy extends LitElement {
<ha-energy-gas-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -210,6 +243,7 @@ class HaConfigEnergy extends LitElement {
.hass=${this.hass}
.resource=${"gas"}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -220,6 +254,7 @@ class HaConfigEnergy extends LitElement {
<ha-energy-water-settings
.hass=${this.hass}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -228,6 +263,7 @@ class HaConfigEnergy extends LitElement {
.hass=${this.hass}
.resource=${"water"}
.preferences=${this._preferences!}
.listPath=${listPath}
.statsMetadata=${this._statsMetadata}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
@@ -238,6 +274,115 @@ class HaConfigEnergy extends LitElement {
}
}
private _renderEditorPage(kind: string, key: string) {
const listPath = `${this.route.prefix}/${this._currTab}`;
switch (`${this._currTab}/${kind}`) {
case "electricity/grid":
return html`<ha-energy-grid-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-grid-settings>`;
case "electricity/solar":
return html`<ha-energy-solar-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.info=${this._info}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-solar-settings>`;
case "electricity/home":
return html`<ha-energy-home-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-home-settings>`;
case "electricity/battery":
return html`<ha-energy-battery-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-battery-settings>`;
case "electricity/device":
return html`<ha-energy-device-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-device-settings>`;
case "gas/gas":
return html`<ha-energy-gas-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-gas-settings>`;
case "water/water":
return html`<ha-energy-water-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-water-settings>`;
case "gas/device":
return html`<ha-energy-device-settings-water-gas
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.resource=${"gas"}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-device-settings-water-gas>`;
case "water/device":
return html`<ha-energy-device-settings-water-gas
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.resource=${"water"}
.preferences=${this._preferences!}
.statsMetadata=${this._statsMetadata}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-device-settings-water-gas>`;
default:
return nothing;
}
}
private async _fetchConfig() {
this._error = undefined;
@@ -258,7 +403,11 @@ class HaConfigEnergy extends LitElement {
this._error = err.message;
}
this._info = await energyInfoPromise;
await this._fetchMetaData();
try {
await this._fetchMetaData();
} catch (err: any) {
this._error = err.message;
}
}
private async _prefsChanged(ev: CustomEvent) {
@@ -360,6 +509,12 @@ class HaConfigEnergy extends LitElement {
display: block;
margin-bottom: 12px;
}
.editor-page {
height: 100%;
max-width: none;
margin: 0;
}
`,
];
}
@@ -0,0 +1,214 @@
import { mdiDelete, mdiDotsVertical } from "@mdi/js";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { stopPropagation } from "../../../common/dom/stop_propagation";
import { goBack, navigate } from "../../../common/navigate";
import { afterNextRender } from "../../../common/util/render-status";
import "../../../components/ha-button";
import "../../../components/ha-card";
import "../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
import "../../../components/ha-dropdown-item";
import "../../../components/ha-icon-button";
import "../../../components/ha-svg-icon";
import { showConfirmationDialog } from "../../../dialogs/generic/show-dialog-box";
import "../../../layouts/hass-subpage";
import { PreventUnsavedMixin } from "../../../mixins/prevent-unsaved-mixin";
import type { HomeAssistant } from "../../../types";
import type {
EnergyEditorConfig,
EnergyEditorElement,
EnergyEditorStatus,
} from "./editors/energy-editor";
import { renderEnergyEditor } from "./editors/render-energy-editor";
export interface EnergyEditorPageConfig {
editor: EnergyEditorConfig;
title: string;
/** Resolves to whether the item was deleted */
delete?: { label: string; action: () => Promise<boolean> };
}
@customElement("ha-energy-editor-page")
export class HaEnergyEditorPage extends PreventUnsavedMixin(LitElement) {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public narrow = false;
/** The list the page returns to */
@property({ attribute: false }) public backPath!: string;
/** Undefined when the item doesn't exist */
@property({ attribute: false }) public config?: EnergyEditorPageConfig;
@state() private _status?: EnergyEditorStatus;
@state() private _deleting = false;
@query(".energy-editor") private _editor?: EnergyEditorElement;
public isDirtyState = false;
protected updated(changedProps: PropertyValues<this>) {
super.updated(changedProps);
// The item is gone or the link was wrong
if (!this.config) {
navigate(this.backPath, { replace: true });
}
}
protected render() {
if (!this.config) {
return nothing;
}
return html`
<hass-subpage
.hass=${this.hass}
.narrow=${this.narrow}
.header=${this.config.title}
.backPath=${this.backPath}
.backCallback=${this._backTapped}
>
${
this.config.delete
? html`
<ha-dropdown
slot="toolbar-icon"
@wa-select=${this._handleMenuAction}
>
<ha-icon-button
slot="trigger"
.label=${this.hass.localize("ui.common.menu")}
.path=${mdiDotsVertical}
></ha-icon-button>
<ha-dropdown-item
value="delete"
variant="danger"
.disabled=${!!this._status?.saving || this._deleting}
>
<ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
${this.config.delete.label}
</ha-dropdown-item>
</ha-dropdown>
`
: nothing
}
<div class="content">
<!-- The list around the page saves the preferences on its own value-changed -->
<ha-card
@energy-editor-status-changed=${this._statusChanged}
@value-changed=${stopPropagation}
>
<div class="card-content">
${keyed(this.config, renderEnergyEditor(this.config.editor))}
</div>
<div class="card-actions">
<ha-button
appearance="filled"
.disabled=${
!this._status?.dirty ||
!this._status.valid ||
this._status.saving ||
this._deleting
}
.loading=${!!this._status?.saving}
@click=${this._save}
>
${this.hass.localize("ui.common.save")}
</ha-button>
</div>
</ha-card>
</div>
</hass-subpage>
`;
}
private _statusChanged(
ev: HASSDomEvent<HASSDomEvents["energy-editor-status-changed"]>
) {
this._status = ev.detail;
this.isDirtyState = ev.detail.dirty;
}
private async _save() {
if (await this._editor?.save()) {
this._leave();
}
}
private async _handleMenuAction(ev: HaDropdownSelectEvent) {
if (ev.detail?.item?.value !== "delete" || !this.config?.delete) {
return;
}
// Saving and deleting both write all preferences, so they never overlap
this._deleting = true;
try {
if (await this.config.delete.action()) {
this._leave();
}
} finally {
this._deleting = false;
}
}
private _leave() {
// The user can leave while a save or delete runs
if (!this.isConnected) {
return;
}
this.isDirtyState = false;
goBack(this.backPath);
}
private _backTapped = async () => {
if (await this._confirmDiscard()) {
afterNextRender(() => goBack(this.backPath));
}
};
private async _confirmDiscard(addHistory = true): Promise<boolean> {
if (!this._status?.dirty) {
return true;
}
return showConfirmationDialog(this, {
addHistory,
title: this.hass.localize("ui.panel.config.energy.unsaved_confirm_title"),
text: this.hass.localize("ui.panel.config.energy.unsaved_confirm_text"),
confirmText: this.hass.localize("ui.common.leave"),
dismissText: this.hass.localize("ui.common.stay"),
destructive: true,
});
}
protected async promptDiscardChanges(): Promise<boolean> {
return this._confirmDiscard(false);
}
static styles = css`
:host {
display: block;
height: 100%;
}
.content {
padding: var(--ha-space-7) var(--ha-space-5) 0;
}
ha-card {
max-width: 600px;
margin: 0 auto var(--ha-space-6);
}
.card-actions {
display: flex;
justify-content: flex-end;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-energy-editor-page": HaEnergyEditorPage;
}
}
@@ -27,6 +27,7 @@ import "../../../components/entity/ha-entity-picker";
import "../../../components/ha-alert";
import "../../../components/ha-area-picker";
import "../../../components/ha-color-picker";
import "../../../components/ha-domain-icon";
import "../../../components/ha-dropdown-item";
import "../../../components/ha-icon";
import "../../../components/ha-icon-button";
@@ -150,6 +151,13 @@ const SWITCH_AS_DOMAINS_INVERT = ["cover", "lock", "valve"];
const PRECISIONS = [0, 1, 2, 3, 4, 5, 6];
const DEFAULT_DEVICE_CLASS = "default";
const DEVICE_CLASS_ICON_STATES: Record<string, string> = {
cover: "open",
binary_sensor: "on",
};
const SCANNER_SOURCE_TYPES = ["router", "bluetooth", "bluetooth_le"];
const ZONE_DOMAINS = ["zone"];
@@ -160,7 +168,7 @@ export interface EntitySettingsState {
entityId: string;
areaId: string | null;
labels: string[];
deviceClass: string | undefined;
deviceClass: string | null;
disabledBy: EntityRegistryEntry["disabled_by"];
hiddenBy: EntityRegistryEntry["hidden_by"];
unitOfMeasurement: string | null | undefined;
@@ -176,6 +184,68 @@ export interface EntitySettingsState {
switchAsInvert: boolean;
}
interface DeviceClassOption {
value: string;
deviceClass?: string;
label: string;
}
interface DeviceClassOptions {
defaultOption: DeviceClassOption;
related: DeviceClassOption[];
others: DeviceClassOption[];
}
const computeDeviceClassOptions = (
domain: string,
originalDeviceClass: string | undefined,
localize: LocalizeFunc,
language: string
): DeviceClassOptions => {
const deviceClassLabel = (deviceClass: string) =>
localize(
`ui.dialogs.entity_registry.editor.device_classes.${domain}.${deviceClass}`
);
const toSortedOptions = (deviceClasses: string[]): DeviceClassOption[] =>
deviceClasses
.map((deviceClass) => ({
value: deviceClass,
deviceClass,
label: deviceClassLabel(deviceClass),
}))
.sort((a, b) => stringCompare(a.label, b.label, language));
const related: string[] = [];
const others: string[] = [];
const groups: string[][] = OVERRIDE_DEVICE_CLASSES[domain];
for (const group of groups) {
if (originalDeviceClass && group.includes(originalDeviceClass)) {
related.push(
...group.filter((deviceClass) => deviceClass !== originalDeviceClass)
);
} else {
others.push(...group);
}
}
const defaultType = originalDeviceClass
? deviceClassLabel(originalDeviceClass)
: domainToName(localize, domain);
return {
defaultOption: {
value: DEFAULT_DEVICE_CLASS,
deviceClass: originalDeviceClass,
label: localize("ui.dialogs.entity_registry.editor.type_default", {
type: defaultType,
}),
},
related: toSortedOptions(related),
others: toSortedOptions(others),
};
};
@customElement("entity-registry-settings-editor")
export class EntityRegistrySettingsEditor extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -205,7 +275,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
@state() private _entityId!: EntitySettingsState["entityId"];
@state() private _deviceClass?: EntitySettingsState["deviceClass"];
@state() private _deviceClass: EntitySettingsState["deviceClass"] = null;
@state() private _switchAsDomain: EntitySettingsState["switchAsDomain"] =
"switch";
@@ -260,8 +330,6 @@ export class EntityRegistrySettingsEditor extends LitElement {
private _origEntityId!: string;
private _deviceClassOptions?: string[][];
protected willUpdate(changedProperties: PropertyValues<this>) {
super.willUpdate(changedProperties);
this._device = this.entry.device_id
@@ -278,7 +346,9 @@ export class EntityRegistrySettingsEditor extends LitElement {
this._isMainEntity = !!this._device && !this._entryName;
this._icon = this.entry.icon || "";
this._deviceClass =
this.entry.device_class || this.entry.original_device_class;
this.entry.device_class === this._originalDeviceClass
? null
: (this.entry.device_class ?? null);
this._origEntityId = this.entry.entity_id;
this._areaId = this.entry.area_id;
this._mainEntityWithOwnArea = this._isMainEntity && !!this.entry.area_id;
@@ -334,32 +404,19 @@ export class EntityRegistrySettingsEditor extends LitElement {
this._visibility_unit = stateObj?.attributes?.visibility_unit;
this._wind_speed_unit = stateObj?.attributes?.wind_speed_unit;
}
const deviceClasses: string[][] = OVERRIDE_DEVICE_CLASSES[domain];
if (!deviceClasses || this._hideDeviceClassOverride(domain)) {
this._deviceClassOptions = undefined;
return;
}
this._deviceClassOptions = [[], []];
for (const deviceClass of deviceClasses) {
if (deviceClass.includes(this.entry.original_device_class!)) {
this._deviceClassOptions[0] = deviceClass;
} else {
this._deviceClassOptions[1].push(...deviceClass);
}
}
}
private _hideDeviceClassOverride(domain: string): boolean {
private _showDeviceClassSelect(domain: string): boolean {
if (!(domain in OVERRIDE_DEVICE_CLASSES)) {
return false;
}
// Template binary sensor device_class should be edited via template options,
// not the entity registry override UI used by other binary sensors.
return (
const isTemplateBinarySensor =
domain === "binary_sensor" &&
this.entry.platform === "template" &&
!!this.entry.config_entry_id
);
!!this.entry.config_entry_id;
return !isTemplateBinarySensor;
}
private _precisionLabel(precision?: number, stateValue?: string) {
@@ -424,19 +481,19 @@ export class EntityRegistrySettingsEditor extends LitElement {
if (changedProps.has("_deviceClass")) {
const domain = computeDomain(this.entry.entity_id);
if (domain === "number" && this._deviceClass) {
if (domain === "number" && this._effectiveDeviceClass) {
const { units } = await getNumberDeviceClassConvertibleUnits(
this.hass,
this._deviceClass
this._effectiveDeviceClass
);
this._numberDeviceClassConvertibleUnits = units;
} else {
this._numberDeviceClassConvertibleUnits = [];
}
if (domain === "sensor" && this._deviceClass) {
if (domain === "sensor" && this._effectiveDeviceClass) {
const { units } = await getSensorDeviceClassConvertibleUnits(
this.hass,
this._deviceClass
this.hass.callWS,
this._effectiveDeviceClass
);
this._sensorDeviceClassConvertibleUnits = units;
} else {
@@ -477,6 +534,10 @@ export class EntityRegistrySettingsEditor extends LitElement {
const defaultPrecision =
this.entry.options?.sensor?.suggested_display_precision ?? undefined;
const defaultName = this._originalName;
const previewStateObj = this._previewStateObj(
stateObj,
this._effectiveDeviceClass
);
return html`
${
@@ -565,13 +626,13 @@ export class EntityRegistrySettingsEditor extends LitElement {
.placeholder=${
this.entry.original_icon ||
stateObj?.attributes.icon ||
(stateObj &&
(previewStateObj &&
until(
entityIcon(
this.hass.entities,
this.hass.config,
this.hass.connection,
stateObj
previewStateObj
)
)) ||
until(entryIcon(this.hass, this.entry))
@@ -579,11 +640,11 @@ export class EntityRegistrySettingsEditor extends LitElement {
.disabled=${this.disabled}
>
${
!this._icon && !stateObj?.attributes.icon && stateObj
!this._icon && !stateObj?.attributes.icon && previewStateObj
? html`
<ha-state-icon
slot="start"
.stateObj=${stateObj}
.stateObj=${previewStateObj}
></ha-state-icon>
`
: nothing
@@ -600,14 +661,15 @@ export class EntityRegistrySettingsEditor extends LitElement {
@selected=${this._switchAsDomainChanged}
value=${this._switchAsLabel(
this._switchAsDomain,
this._deviceClass
this._effectiveDeviceClass
)}
>
<ha-dropdown-item
value="switch"
.selected=${
this._switchAsDomain === "switch" &&
(!this._deviceClass || this._deviceClass === "switch")
(!this._effectiveDeviceClass ||
this._effectiveDeviceClass === "switch")
}
>
${domainToName(this.hass.localize, "switch")}
@@ -616,7 +678,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
value="outlet"
.selected=${
this._switchAsDomain === "switch" &&
this._deviceClass === "outlet"
this._effectiveDeviceClass === "outlet"
}
>
${this.hass.localize(
@@ -700,64 +762,10 @@ export class EntityRegistrySettingsEditor extends LitElement {
} `
: nothing
}
${
this._deviceClassOptions && !this._hideDeviceClassOverride(domain)
? html`
<ha-select
.label=${this.hass.localize(
"ui.dialogs.entity_registry.editor.device_class"
)}
.value=${
this._deviceClass
? this.hass.localize(
`ui.dialogs.entity_registry.editor.device_classes.${domain}.${this._deviceClass}`
)
: undefined
}
clearable
@selected=${this._deviceClassChanged}
>
${this._deviceClassesSorted(
domain,
this._deviceClassOptions[0],
this.hass.localize
).map(
(entry) => html`
<ha-dropdown-item
.value=${entry.deviceClass}
.selected=${entry.deviceClass === this._deviceClass}
>
${entry.label}
</ha-dropdown-item>
`
)}
${
this._deviceClassOptions[0].length &&
this._deviceClassOptions[1].length
? html`<wa-divider></wa-divider>`
: nothing
}
${this._deviceClassesSorted(
domain,
this._deviceClassOptions[1],
this.hass.localize
).map(
(entry) => html`
<ha-dropdown-item
.value=${entry.deviceClass}
.selected=${entry.deviceClass === this._deviceClass}
>
${entry.label}
</ha-dropdown-item>
`
)}
</ha-select>
`
: nothing
}
${this._renderDeviceClassSelect(domain)}
${
domain === "number" &&
this._deviceClass &&
this._effectiveDeviceClass &&
stateObj?.attributes.unit_of_measurement &&
this._numberDeviceClassConvertibleUnits?.includes(
stateObj?.attributes.unit_of_measurement
@@ -846,7 +854,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
}
${
domain === "sensor" &&
this._deviceClass &&
this._effectiveDeviceClass &&
stateObj?.attributes.unit_of_measurement &&
this._sensorDeviceClassConvertibleUnits?.includes(
stateObj?.attributes.unit_of_measurement
@@ -871,7 +879,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
domain === "sensor" &&
// Allow customizing the precision for a sensor with numerical device class,
// a unit of measurement or state class
(isNumericSensorDeviceClass(this._deviceClass) ||
(isNumericSensorDeviceClass(this._effectiveDeviceClass) ||
stateObj?.attributes.unit_of_measurement ||
stateObj?.attributes.state_class)
? html`
@@ -1317,12 +1325,8 @@ export class EntityRegistrySettingsEditor extends LitElement {
new_entity_id: this._entityId.trim(),
};
// Only update device class if changed by user
if (
this._deviceClass !==
(this.entry.device_class || this.entry.original_device_class)
) {
params.device_class = this._deviceClass ?? null;
if (this._deviceClass !== (this.entry.device_class ?? null)) {
params.device_class = this._deviceClass;
}
const stateObj: HassEntity | undefined =
@@ -1449,9 +1453,12 @@ export class EntityRegistrySettingsEditor extends LitElement {
),
})
) {
const configFlow = await createConfigFlow(this.hass, "switch_as_x");
const configFlow = await createConfigFlow(
this.hass.callApi,
"switch_as_x"
);
const configFlowResult = (await handleConfigFlowStep(
this.hass,
this.hass.callApi,
configFlow.flow_id,
{
entity_id: this._entityId.trim(),
@@ -1515,9 +1522,12 @@ export class EntityRegistrySettingsEditor extends LitElement {
showMoreInfoDialog(parent, { entityId: origEntityId });
close = false;
} else {
const configFlow = await createConfigFlow(this.hass, "switch_as_x");
const configFlow = await createConfigFlow(
this.hass.callApi,
"switch_as_x"
);
const configFlowResult = (await handleConfigFlowStep(
this.hass,
this.hass.callApi,
configFlow.flow_id,
{
entity_id: origEntityId,
@@ -1616,8 +1626,9 @@ export class EntityRegistrySettingsEditor extends LitElement {
this._entityId = `${computeDomain(this._origEntityId)}.${(ev.target as HTMLInputElement).value}`;
}
private _deviceClassChanged(ev: HaSelectSelectEvent<string, true>): void {
this._deviceClass = ev.detail.value;
private _deviceClassChanged(ev: HaSelectSelectEvent): void {
const value = ev.detail.value;
this._deviceClass = value === DEFAULT_DEVICE_CLASS ? null : value;
}
private _unitChanged(ev: HaSelectSelectEvent): void {
@@ -1679,7 +1690,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
value === "outlet") ||
value === "switch"
) {
this._deviceClass = value;
this._deviceClass = value === this._originalDeviceClass ? null : value;
}
}
@@ -1789,6 +1800,88 @@ export class EntityRegistrySettingsEditor extends LitElement {
return String(this.entry.original_name ?? "");
}
private get _originalDeviceClass(): string | undefined {
return this.entry.original_device_class || undefined;
}
private get _effectiveDeviceClass(): string | undefined {
return this._deviceClass || this._originalDeviceClass;
}
private _renderDeviceClassSelect(domain: string) {
if (!this._showDeviceClassSelect(domain)) {
return nothing;
}
const options = this._deviceClassOptions(
domain,
this._originalDeviceClass,
this.hass.localize,
this.hass.locale.language
);
const selectedValue = this._deviceClass || DEFAULT_DEVICE_CLASS;
const selectedOption = [
options.defaultOption,
...options.related,
...options.others,
].find((option) => option.value === selectedValue);
return html`
<ha-select
.label=${this.hass.localize("ui.dialogs.entity_registry.editor.type")}
.value=${selectedOption?.label}
@selected=${this._deviceClassChanged}
>
${this._renderDeviceClassItem(domain, options.defaultOption)}
<wa-divider></wa-divider>
${options.related.map((option) =>
this._renderDeviceClassItem(domain, option)
)}
${
options.related.length && options.others.length
? html`<wa-divider></wa-divider>`
: nothing
}
${options.others.map((option) =>
this._renderDeviceClassItem(domain, option)
)}
</ha-select>
`;
}
private _renderDeviceClassItem(domain: string, option: DeviceClassOption) {
return html`
<ha-dropdown-item
.value=${option.value}
.selected=${option.value === (this._deviceClass || DEFAULT_DEVICE_CLASS)}
>
<ha-domain-icon
slot="icon"
.domain=${domain}
.deviceClass=${option.deviceClass}
.state=${DEVICE_CLASS_ICON_STATES[domain]}
></ha-domain-icon>
${option.label}
</ha-dropdown-item>
`;
}
private _deviceClassOptions = memoizeOne(computeDeviceClassOptions);
private _previewStateObj = memoizeOne(
(
stateObj: HassEntity | undefined,
deviceClass: string | undefined
): HassEntity | undefined => {
if (!stateObj || stateObj.attributes.device_class === deviceClass) {
return stateObj;
}
return {
...stateObj,
attributes: { ...stateObj.attributes, device_class: deviceClass },
};
}
);
private _restoreName(): void {
this._name = this._originalName;
if (this._device && !this._originalName) {
@@ -1866,20 +1959,6 @@ export class EntityRegistrySettingsEditor extends LitElement {
)
);
private _deviceClassesSorted = memoizeOne(
(domain: string, deviceClasses: string[], localize: LocalizeFunc) =>
deviceClasses
.map((entry) => ({
deviceClass: entry,
label: localize(
`ui.dialogs.entity_registry.editor.device_classes.${domain}.${entry}`
),
}))
.sort((a, b) =>
stringCompare(a.label, b.label, this.hass.locale.language)
)
);
private _switchAsLabel = memoizeOne(
(switchAsDomain: string, deviceClass?: string) => {
if (switchAsDomain !== "switch") {
+9 -19
View File
@@ -207,13 +207,12 @@ class HaConfigInfo extends LitElement {
<ha-card outlined class="pages">
<ha-list-base>
<ha-list-item-button @click=${this._showShortcuts}>
<div
<ha-svg-icon
slot="start"
class="icon-background"
style="background-color: #9e4dd1;"
>
<ha-svg-icon .path=${mdiKeyboard}></ha-svg-icon>
</div>
.path=${mdiKeyboard}
></ha-svg-icon>
<span slot="headline"
>${this.hass.localize("ui.panel.config.info.shortcuts")}</span
>
@@ -226,13 +225,12 @@ class HaConfigInfo extends LitElement {
target="_blank"
rel="noopener noreferrer"
>
<div
<ha-svg-icon
slot="start"
class="icon-background"
style=${`background-color: ${page.iconColor};`}
>
<ha-svg-icon .path=${page.iconPath}></ha-svg-icon>
</div>
.path=${page.iconPath}
></ha-svg-icon>
<span slot="headline">
${this.hass.localize(
`ui.panel.config.info.items.${page.name}`
@@ -398,18 +396,10 @@ class HaConfigInfo extends LitElement {
padding: 4px 0;
}
.icon-background ha-svg-icon {
height: 24px;
width: 24px;
color: #fff;
}
.icon-background {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
color: #fff;
/* 24px icon + padding = 40px circle */
padding: var(--ha-space-2);
border-radius: var(--ha-border-radius-circle);
}
@@ -76,7 +76,10 @@ class HaConfigEntryDeviceRow extends LitElement {
const supportingText = [
area ? html`<span class="area">${area.name}</span>` : undefined,
device.model || device.sw_version || device.manufacturer,
device.model ||
device.model_id ||
device.sw_version ||
device.manufacturer,
entities.length
? bidiIsolate(
this.hass.localize(
@@ -127,7 +130,7 @@ class HaConfigEntryDeviceRow extends LitElement {
)}</span
>
${!this.narrow ? html`<ha-icon-next slot="end"></ha-icon-next>` : nothing}
<div class="vertical-divider" slot="end" @click=${stopPropagation}></div>
<div class="vertical-divider" slot="end"></div>
${
!this.narrow
? html`<ha-icon-button
@@ -350,8 +353,9 @@ class HaConfigEntryDeviceRow extends LitElement {
private _handleDeleteDevice = async () => {
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.devices.confirm_delete_title"),
text: this.hass.localize("ui.panel.config.devices.confirm_delete"),
confirmText: this.hass.localize("ui.common.delete"),
confirmText: this.hass.localize("ui.common.remove"),
dismissText: this.hass.localize("ui.common.cancel"),
destructive: true,
});
@@ -478,14 +478,13 @@ export class HaConfigEntryRow extends LitElement {
expanded: this._devicesExpanded,
})}"
>
<ha-icon-button
class="expand-button ${classMap({
<ha-svg-icon
class="expand-icon ${classMap({
expanded: this._devicesExpanded,
})}"
.path=${mdiChevronDown}
slot="start"
>
</ha-icon-button>
></ha-svg-icon>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.integrations.config_entry.devices_without_subentry"
@@ -892,6 +891,12 @@ export class HaConfigEntryRow extends LitElement {
.expand-button.expanded {
transform: rotate(180deg);
}
.expand-icon {
transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
}
.expand-icon.expanded {
transform: rotate(180deg);
}
.config-entry-wrapper {
border: 1px solid var(--divider-color);
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
@@ -21,13 +21,17 @@ import memoizeOne from "memoize-one";
import { ensureArray } from "../../../common/array/ensure-array";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
import { ContextSubscriptionController } from "../../../common/decorators/consume";
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
import {
PROTOCOL_INTEGRATIONS,
protocolIntegrationPicked,
} from "../../../common/integrations/protocolIntegrationPicked";
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
import {
caseInsensitiveStringCompare,
stringCompare,
} from "../../../common/string/compare";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
integrationQueryParamConfig,
@@ -39,7 +43,9 @@ import "../../../components/ha-dropdown";
import "../../../components/ha-dropdown-item";
import "../../../components/input/ha-input-search";
import type { HaInputSearch } from "../../../components/input/ha-input-search";
import "../../../components/ha-icon-next";
import "../../../components/item/ha-list-item-base";
import "../../../components/item/ha-list-item-button";
import "../../../components/list/ha-list-base";
import { getSignedPath } from "../../../data/auth";
import type { ConfigEntry, SubEntry } from "../../../data/config_entries";
@@ -59,7 +65,9 @@ import {
getCoreLogFileDownloadUnavailableReason,
getErrorLogDownloadUrl,
} from "../../../data/error_log";
import { manifestsContext } from "../../../data/context";
import type {
DomainManifestLookup,
IntegrationLogInfo,
IntegrationManifest,
} from "../../../data/integration";
@@ -167,6 +175,11 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
@state() private _manifest?: IntegrationManifest;
/** The manifests of all loaded integrations, to find the dependents. */
@state() private _loadedManifests?: DomainManifestLookup;
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
@state() private _extraConfigEntries?: ConfigEntry[];
@state() private _diagnosticHandler?: DiagnosticInfo;
@@ -263,6 +276,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
this.hass.loadBackendTranslation("config", [this.domain]);
this.hass.loadBackendTranslation("config_subentries", [this.domain]);
this._extraConfigEntries = undefined;
this._manifest = undefined;
this._resetDebugLogReady();
this._filter = "";
this._subEntries = {};
@@ -415,6 +429,25 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
this.domain
);
// Without the dependents, a dependency looks like a YAML integration.
const dependents =
this._manifest && !this._manifest.config_flow
? this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
)
: [];
const showDependents = normalEntries.length === 0 && dependents.length > 0;
// Hold back the YAML texts and "Add entry" until the manifest and the
// dependents are known. Entries do not wait, so a failed request cannot
// hide them.
const dependentsLoading =
normalEntries.length === 0 &&
(!this._manifest ||
(!this._manifest.config_flow && !this._loadedManifests));
const configPanel = isComponentLoaded(this.hass.config, this.domain)
? getConfigPanelPath(this.domain, this.hass.panels)
: undefined;
@@ -425,6 +458,8 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
const showAddEntry =
this._manifest?.integration_type !== "hardware" &&
!showDependents &&
!dependentsLoading &&
!setUpInPanel &&
(!this._manifest?.single_config_entry ||
(normalData.length === 0 && attentionData.length === 0));
@@ -614,6 +649,8 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
${
normalEntries.length === 0 &&
!showDependents &&
!dependentsLoading &&
!setUpInPanel &&
this._manifest &&
!this._manifest.config_flow &&
@@ -726,7 +763,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
${
configPanel
? html`<ha-button
.appearance=${setUpInPanel ? "accent" : "outlined"}
.appearance=${
showAddEntry || canAddDevice ? "outlined" : "accent"
}
href=${`/${configPanel}`}
>
${this.hass.localize(
@@ -975,7 +1014,21 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
: nothing
}
${
setUpInPanel && normalEntries.length === 0
showDependents
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
${
showDependents ||
dependentsLoading ||
(setUpInPanel && normalEntries.length === 0)
? nothing
: html`<div class="section">
<h3 class="section-header">
@@ -1032,6 +1085,76 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
`;
}
// Only an integration without a config flow needs the loaded manifests, so
// other integration pages do not make the context fetch them.
private _watchLoadedManifests(): void {
if (this._manifestsConsumer) {
return;
}
this._manifestsConsumer = new ContextSubscriptionController(
this,
manifestsContext,
(manifests) => {
this._loadedManifests = manifests;
}
);
}
private _getDependents = memoizeOne(
(
domain: string,
manifests: DomainManifestLookup | undefined,
localize: LocalizeFunc,
language: string
) =>
Object.values(manifests ?? {})
.filter(
// System integrations, like Default Configuration, are not useful to list.
(manifest) =>
manifest.integration_type !== "system" &&
manifest.dependencies?.includes(domain)
)
// The manifests come in no fixed order.
.sort((a, b) =>
stringCompare(
domainToName(localize, a.domain, a),
domainToName(localize, b.domain, b),
language
)
)
);
private _renderDependents(dependents: IntegrationManifest[]) {
return html`<ha-list-base>
${dependents.map(
(manifest) =>
html`<ha-list-item-button
class="dependent"
href=${`/config/integrations/integration/${manifest.domain}`}
>
<img
slot="start"
alt=""
src=${brandsUrl(
{
domain: manifest.domain,
type: "icon@2x",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<div slot="headline">
${domainToName(this.hass.localize, manifest.domain, manifest)}
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
)}
</ha-list-base>`;
}
private _onImageLoad(ev) {
ev.target.style.display = "inline-block";
}
@@ -1072,6 +1195,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
return;
}
this._manifest = await fetchIntegrationManifest(this.hass, this.domain);
if (!this._manifest.config_flow) {
this._watchLoadedManifests();
}
if (
this._manifest.integration_type &&
!["device", "hub", "service"].includes(this._manifest.integration_type)
@@ -1258,6 +1384,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
"name",
"manufacturer",
"model",
"model_id",
"sw_version",
"area",
];
@@ -1267,6 +1394,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
name: device.name_by_user || device.name || "",
manufacturer: device.manufacturer || "",
model: device.model || "",
model_id: device.model_id || "",
sw_version: device.sw_version || "",
area: device.area_id ? areas[device.area_id]?.name || "" : "",
});
@@ -1748,6 +1876,17 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
ha-list-item-base.discovered {
--ha-row-item-min-height: 72px;
}
ha-list-item-button.dependent {
--ha-row-item-min-height: 72px;
}
ha-list-item-button.dependent + ha-list-item-button.dependent {
border-top: var(--ha-border-width-sm) solid var(--divider-color);
}
ha-list-item-button.dependent img {
width: 40px;
height: 40px;
object-fit: contain;
}
ha-list-item-base.config_entry {
position: relative;
}
@@ -243,6 +243,14 @@ class HaConfigIntegrationsDashboard extends KeyboardShortcutMixin(
] => {
const entryDomains = new Set(configEntries.map((entry) => entry.domain));
// An integration loaded as a dependency of another is not set up in YAML.
const dependencies = new Set<string>();
for (const component of components) {
manifests[component.split(".")[0]]?.dependencies?.forEach((domain) =>
dependencies.add(domain)
);
}
const domains = new Set<string>();
for (const component of components) {
@@ -250,6 +258,7 @@ class HaConfigIntegrationsDashboard extends KeyboardShortcutMixin(
const manifest = manifests[componentDomain];
if (
!entryDomains.has(componentDomain) &&
!dependencies.has(componentDomain) &&
manifest &&
!manifest.config_flow &&
(!manifest.integration_type ||
@@ -25,12 +25,8 @@ export class HaIntegrationListItem extends HaListItemButton {
@consumeLocalize()
private _localize!: LocalizeFunc;
protected override _renderInner(): TemplateResult {
protected override _renderStart(): TemplateResult {
const integration = this.integration;
const yamlOnly =
!integration.config_flow &&
!integration.integrations &&
!integration.iot_standards;
return html`
<div part="start" class="start">
${
@@ -45,6 +41,12 @@ export class HaIntegrationListItem extends HaListItemButton {
></ha-domain-icon>`
}
</div>
`;
}
protected override _renderContent(): TemplateResult {
const integration = this.integration;
return html`
<div part="content" class="content">
<div part="headline" class="headline">
${
@@ -57,6 +59,16 @@ export class HaIntegrationListItem extends HaListItemButton {
}
</div>
</div>
`;
}
protected override _renderEnd(): TemplateResult {
const integration = this.integration;
const yamlOnly =
!integration.config_flow &&
!integration.integrations &&
!integration.iot_standards;
return html`
<div part="end" class="end">
${
integration.cloud
@@ -117,6 +129,15 @@ export class HaIntegrationListItem extends HaListItemButton {
align-items: center;
gap: var(--ha-space-2);
}
/* Raise the icons above the row's hit area so their tooltips open */
.end ha-svg-icon {
position: relative;
z-index: 1;
}
/* The chevron is decorative, keep it below the row's hit area */
.end ha-icon-next {
z-index: -1;
}
.discovered-icon {
color: var(--primary-color);
}
@@ -170,9 +170,11 @@ class DialogMatterLockManage extends LitElement {
.user=${user}
@click=${this._handleUserClick}
>
<div slot="start" class="icon-background">
<ha-svg-icon .path=${mdiLock}></ha-svg-icon>
</div>
<ha-svg-icon
slot="start"
class="icon-background"
.path=${mdiLock}
></ha-svg-icon>
<div slot="headline">
${user.user_name || `User ${user.user_index}`}
</div>
@@ -336,11 +338,8 @@ class DialogMatterLockManage extends LitElement {
border-radius: var(--ha-border-radius-circle);
background-color: var(--primary-color);
color: #fff;
display: flex;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
/* 24px icon + padding = 40px circle */
padding: var(--ha-space-2);
}
`,
];
@@ -53,9 +53,11 @@ class MatterAddDeviceExisting extends LitElement {
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button .step=${"generic"} @click=${this._onItemClick}>
<div class="logo" slot="start">
<ha-svg-icon path=${mdiHomeAutomation}></ha-svg-icon>
</div>
<ha-svg-icon
class="logo-icon"
slot="start"
.path=${mdiHomeAutomation}
></ha-svg-icon>
<span slot="headline">
${this.hass.localize(
`ui.dialogs.matter-add-device.existing.answer_generic`
@@ -88,8 +90,12 @@ class MatterAddDeviceExisting extends LitElement {
justify-content: center;
object-fit: contain;
}
.logo ha-svg-icon {
/* 36px icon + padding + border = the 48px logo box */
.logo-icon {
--mdc-icon-size: 36px;
padding: 5px;
border-radius: var(--ha-border-radius-lg);
border: 1px solid var(--divider-color);
}
`,
];
@@ -1,6 +1,24 @@
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import { computeAreaName } from "../../../../../common/entity/compute_area_name";
import { getDeviceArea } from "../../../../../common/entity/context/get_device_context";
import type { Cluster, ZHADevice, ZHAGroup } from "../../../../../data/zha";
import { ZHADeviceType } from "../../../../../data/zha";
import type { HomeAssistant } from "../../../../../types";
export const getZHADeviceAreaName = (
device: ZHADevice,
areas: HomeAssistant["areas"],
devices: HomeAssistant["devices"]
): string | undefined => {
// The device registry is authoritative: an entry with no effective
// area means the device has no area, even if ZHA still reports one
// from its cached response. Resolve via the registry so a child
// device inherits its parent's area, matching the ZHA network
// visualization.
const haDevice = devices[device.device_reg_id];
const area = haDevice ? getDeviceArea(haDevice, areas, devices) : undefined;
return area ? computeAreaName(area) : undefined;
};
export const formatAsPaddedHex = (value: string | number): string => {
let hex = value;
@@ -1,3 +1,4 @@
import type { Connection } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
@@ -42,6 +43,11 @@ class ZHAAddDevicesPage extends LitElement {
private _wakeLock?: Promise<WakeLockSentinel>;
private _connection?: Connection;
// Set for the search in flight, so a pending subscription can tell it ended
private _search?: object;
public connectedCallback(): void {
super.connectedCallback();
if (this.route && this.route.path && this.route.path !== "") {
@@ -194,28 +200,34 @@ class ZHAAddDevicesPage extends LitElement {
}
}
// The backend ends the subscription when the connection drops, and it is not
// sent again, so end the search here and show "Search again"
private _connectionLost = () => {
this._unsubscribe();
};
private _unsubscribe(): Promise<void> {
this._active = false;
this._search = undefined;
this._connection?.removeEventListener("disconnected", this._connectionLost);
this._connection = undefined;
if (this._addDevicesTimeoutHandle) {
clearTimeout(this._addDevicesTimeoutHandle);
}
let unsubscribed = Promise.resolve();
if (this._subscribed) {
unsubscribed = this._subscribed.then((unsub) => unsub());
unsubscribed = this._subscribed.then(
(unsub) => unsub(),
// A subscription that was cancelled or lost with the connection has
// nothing to unsubscribe
() => undefined
);
this._subscribed = undefined;
}
this._wakeLock?.then((wakeLock) => wakeLock.release());
return unsubscribed;
}
private _deactivate(): void {
this._active = false;
if (this._addDevicesTimeoutHandle) {
clearTimeout(this._addDevicesTimeoutHandle);
}
this._wakeLock?.then((wakeLock) => wakeLock.release());
}
private _subscribe(): void {
if (!this.hass) {
return;
@@ -225,22 +237,35 @@ class ZHAAddDevicesPage extends LitElement {
// session before starting the next one
const unsubscribed = this._unsubscribe();
this._active = true;
const search = {};
this._search = search;
const data: any = { type: "zha/devices/permit", duration: 254 };
if (this._ieeeAddress) {
data.ieee = this._ieeeAddress;
}
const connection = this.hass.connection;
this._connection = connection;
connection.addEventListener("disconnected", this._connectionLost);
this._subscribed = unsubscribed
// A failed unsubscribe leaves nothing to wait for
.catch(() => undefined)
.then(() =>
// Each subscription opens the network for joining and turns on ZHA
// debug logging, so don't send it again after a reconnect
connection.subscribeMessage(
(message) => this._handleMessage(message),
data
data,
{
resubscribe: false,
// While offline, subscribeMessage waits for the connection. Don't
// open the network if this search ended in the meantime
preCheck: () => this._search === search,
}
)
);
this._addDevicesTimeoutHandle = setTimeout(
() => this._deactivate(),
// End the subscription with the search, so debug logging ends too
() => this._unsubscribe(),
254000
);
if ("wakeLock" in navigator) {
@@ -2,12 +2,12 @@ import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../../../components/buttons/ha-progress-button";
import "../../../../../components/ha-select";
import type { HaSelectSelectEvent } from "../../../../../components/ha-select";
import "../../../../../components/device/ha-device-picker";
import type { HaDevicePickerDeviceFilterFunc } from "../../../../../components/device/ha-device-picker";
import type { ZHADevice } from "../../../../../data/zha";
import { bindDevices, unbindDevices } from "../../../../../data/zha";
import { haStyle } from "../../../../../resources/styles";
import type { HomeAssistant } from "../../../../../types";
import type { HomeAssistant, ValueChangedEvent } from "../../../../../types";
@customElement("zha-device-binding-control")
export class ZHADeviceBindingControl extends LitElement {
@@ -17,8 +17,6 @@ export class ZHADeviceBindingControl extends LitElement {
@property({ attribute: false }) public bindableDevices: ZHADevice[] = [];
@state() private _bindTargetIndex = -1;
@state() private _deviceToBind?: ZHADevice;
@state() private _bindingOperationInProgress = false;
@@ -29,7 +27,6 @@ export class ZHADeviceBindingControl extends LitElement {
changedProperties.has("device") && this.device?.ieee !== oldDevice?.ieee;
if (deviceChanged || changedProperties.has("bindableDevices")) {
this._bindTargetIndex = -1;
this._deviceToBind = undefined;
}
super.updated(changedProperties);
@@ -39,21 +36,15 @@ export class ZHADeviceBindingControl extends LitElement {
return html`
<div class="content">
<div class="command-picker">
<ha-select
<ha-device-picker
label=${this.hass!.localize(
"ui.panel.config.zha.device_binding.picker_label"
)}
class="menu"
.value=${String(this._bindTargetIndex)}
@selected=${this._bindTargetIndexChanged}
.options=${this.bindableDevices.map((device, idx) => ({
value: String(idx),
label: device.user_given_name
? device.user_given_name
: device.name,
}))}
.value=${this._deviceToBind?.device_reg_id}
.deviceFilter=${this._filterBindableDevices}
@value-changed=${this._bindTargetChanged}
>
</ha-select>
</ha-device-picker>
</div>
<div class="card-actions">
<ha-progress-button
@@ -81,12 +72,16 @@ export class ZHADeviceBindingControl extends LitElement {
`;
}
private _bindTargetIndexChanged(event: HaSelectSelectEvent): void {
this._bindTargetIndex = Number(event.detail.value);
this._deviceToBind =
this._bindTargetIndex === -1
? undefined
: this.bindableDevices[this._bindTargetIndex];
private _filterBindableDevices: HaDevicePickerDeviceFilterFunc = (device) =>
this.bindableDevices.some(
(bindableDevice) => bindableDevice.device_reg_id === device.id
);
private _bindTargetChanged(event: ValueChangedEvent<string>): void {
event.stopPropagation();
this._deviceToBind = this.bindableDevices.find(
(device) => device.device_reg_id === event.detail.value
);
}
private async _onBindDevicesClick(ev: CustomEvent): Promise<void> {
@@ -131,7 +126,8 @@ export class ZHADeviceBindingControl extends LitElement {
return [
haStyle,
css`
.menu {
ha-device-picker {
display: block;
width: 100%;
}
@@ -17,10 +17,12 @@ import { fetchDevices } from "../../../../../data/zha";
import { haStyle } from "../../../../../resources/styles";
import type { HomeAssistant } from "../../../../../types";
import { zhaDevicePageCardStyles } from "./device-page/zha-device-page-card-styles";
import { getZHADeviceAreaName } from "./functions";
export interface DeviceRowData extends DataTableRowData {
id: string;
name: string;
area: string | undefined;
lqi: number;
depth: number;
relationship: string;
@@ -56,7 +58,9 @@ class ZHADeviceNeighbors extends LitElement {
private _deviceNeighbors = memoizeOne(
(
device: ZHADevice | undefined,
devices: Map<string, ZHADevice> | undefined
devices: Map<string, ZHADevice> | undefined,
areas: HomeAssistant["areas"],
haDevices: HomeAssistant["devices"]
) => {
const outputDevices: DeviceRowData[] = [];
if (device && devices) {
@@ -65,6 +69,9 @@ class ZHADeviceNeighbors extends LitElement {
outputDevices.push({
name:
zhaDevice?.user_given_name || zhaDevice?.name || neighbor.ieee,
area: zhaDevice
? getZHADeviceAreaName(zhaDevice, areas, haDevices)
: undefined,
id: zhaDevice?.device_reg_id || neighbor.ieee,
lqi: Number(neighbor.lqi),
depth: Number(neighbor.depth),
@@ -86,6 +93,11 @@ class ZHADeviceNeighbors extends LitElement {
direction: "asc",
flex: 2,
},
area: {
title: this.hass.localize("ui.panel.config.generic.headers.area"),
sortable: true,
filterable: true,
},
lqi: {
title: this.hass.localize("ui.panel.config.zha.neighbors.lqi"),
sortable: true,
@@ -101,6 +113,11 @@ class ZHADeviceNeighbors extends LitElement {
direction: "asc",
flex: 2,
},
area: {
title: this.hass.localize("ui.panel.config.generic.headers.area"),
sortable: true,
filterable: true,
},
lqi: {
title: this.hass.localize("ui.panel.config.zha.neighbors.lqi"),
sortable: true,
@@ -140,7 +157,12 @@ class ZHADeviceNeighbors extends LitElement {
return html`<ha-card class="empty-card">${this._error}</ha-card>`;
}
const neighbors = this._deviceNeighbors(this.device, this._devices);
const neighbors = this._deviceNeighbors(
this.device,
this._devices,
this.hass.areas,
this.hass.devices
);
if (!neighbors.length) {
return html`
@@ -1,14 +1,13 @@
import { mdiHelpNetworkOutline, mdiLeaf, mdiZigbee } from "@mdi/js";
import { getDeviceArea } from "../../../../../common/entity/context/get_device_context";
import type {
NetworkData,
NetworkLink,
NetworkNode,
} from "../../../../../components/chart/ha-network-graph";
import type { DeviceRegistryEntry } from "../../../../../data/device/device_registry";
import type { ZHADevice } from "../../../../../data/zha";
import { ZHADeviceType } from "../../../../../data/zha";
import type { HomeAssistant } from "../../../../../types";
import { getZHADeviceAreaName } from "./functions";
function getLQIWidth(lqi: number): number {
return lqi > 200 ? 3 : lqi > 100 ? 2 : 1;
@@ -120,16 +119,11 @@ export function createZHANetworkChartData(
category = 2; // End Device
}
const haDevice = hass.devices[device.device_reg_id] as
DeviceRegistryEntry | undefined;
const area = haDevice
? getDeviceArea(haDevice, hass.areas, hass.devices)
: undefined;
// Create node
nodes.push({
id: device.ieee,
name: device.user_given_name || device.name || device.ieee,
context: area?.name,
context: getZHADeviceAreaName(device, hass.areas, hass.devices),
category,
value: isCoordinator
? 3
@@ -7,13 +7,11 @@ import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HASSDomTargetEvent } from "../../../../../common/dom/fire_event";
import { getDeviceArea } from "../../../../../common/entity/context/get_device_context";
import { navigate } from "../../../../../common/navigate";
import "../../../../../components/chart/ha-network-graph";
import type { NetworkData } from "../../../../../components/chart/ha-network-graph";
import "../../../../../components/input/ha-input-search";
import type { HaInputSearch } from "../../../../../components/input/ha-input-search";
import type { DeviceRegistryEntry } from "../../../../../data/device/device_registry";
import type { ZHADevice } from "../../../../../data/zha";
import {
fetchDevices,
@@ -27,6 +25,7 @@ import {
computeZHADeviceType,
formatAsPaddedHex,
formatGreenPowerSrcId,
getZHADeviceAreaName,
} from "./functions";
import {
createZHANetworkChartData,
@@ -199,11 +198,11 @@ export class ZHANetworkVisualizationPage extends MobileAwareMixin(LitElement) {
if (!device) {
return html`${name}`;
}
const haDevice = this.hass.devices[device.device_reg_id] as
DeviceRegistryEntry | undefined;
const area = haDevice
? getDeviceArea(haDevice, this.hass.areas, this.hass.devices)
: undefined;
const areaName = getZHADeviceAreaName(
device,
this.hass.areas,
this.hass.devices
);
return html`<b>IEEE: </b>${device.ieee}<br /><b
>${this.hass.localize("ui.panel.config.zha.visualization.device_type")}: </b
>${computeZHADeviceType(device, this.hass.localize)}${
@@ -231,10 +230,10 @@ export class ZHANetworkVisualizationPage extends MobileAwareMixin(LitElement) {
)}</b
>`
}${
area
areaName
? html`<br /><b
>${this.hass.localize("ui.panel.config.zha.visualization.area")}: </b
>${area.name}`
>${areaName}`
: nothing
}`;
};
@@ -229,9 +229,11 @@ class DialogZwaveCredentialManage extends LitElement {
data-user-id=${user.user_id}
@click=${this._handleUserClick}
>
<div slot="start" class="icon-background">
<ha-svg-icon .path=${mdiAccountKey}></ha-svg-icon>
</div>
<ha-svg-icon
slot="start"
class="icon-background"
.path=${mdiAccountKey}
></ha-svg-icon>
<div slot="headline">
${
user.user_name ||
@@ -430,11 +432,8 @@ class DialogZwaveCredentialManage extends LitElement {
border-radius: var(--ha-border-radius-circle);
background-color: var(--primary-color);
color: #fff;
display: flex;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
/* 24px icon + padding = 40px circle */
padding: var(--ha-space-2);
}
.credential-count {
margin-inline-start: var(--ha-space-2);
@@ -6,6 +6,7 @@ import {
mdiHomeEdit,
mdiPencil,
mdiPlus,
mdiContentDuplicate,
} from "@mdi/js";
import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
@@ -38,6 +39,7 @@ import type { LovelaceRawConfig } from "../../../../data/lovelace/config/types";
import {
isStrategyDashboard,
saveConfig,
fetchConfig,
} from "../../../../data/lovelace/config/types";
import { fetchResources } from "../../../../data/lovelace/resource";
import type {
@@ -72,6 +74,7 @@ import type { NewDashboardSelection } from "../../dashboard/show-dialog-new-dash
import { showNewDashboardDialog } from "../../dashboard/show-dialog-new-dashboard";
import { lovelaceTabs } from "../ha-config-lovelace";
import { showDashboardConfigureStrategyDialog } from "./show-dialog-lovelace-dashboard-configure-strategy";
import { replaceDashboardLinks } from "./replace-dashboard-links";
import { showDashboardDetailDialog } from "./show-dialog-lovelace-dashboard-detail";
import { showPanelDetailDialog } from "./show-dialog-panel-detail";
@@ -318,6 +321,13 @@ export class HaConfigLovelaceDashboards extends LitElement {
),
action: () => this._handleEdit(dashboard),
},
{
path: mdiContentDuplicate,
label: this.hass.localize(
"ui.panel.config.lovelace.dashboards.picker.duplicate"
),
action: () => this._handleDuplicate(dashboard),
},
{
label: this.hass.localize(
"ui.panel.config.lovelace.dashboards.picker.delete"
@@ -601,6 +611,40 @@ export class HaConfigLovelaceDashboards extends LitElement {
this._deleteDashboard(dashboard);
};
private _handleDuplicate = async (item: DataTableItem) => {
try {
const config = await fetchConfig(
this.hass.connection,
item.url_path,
false
).catch((err) => {
if (err.code === "config_not_found") {
return undefined;
}
throw err;
});
const title = this.hass.localize(
"ui.panel.config.lovelace.dashboards.duplicate_title",
{ title: item.title }
);
this._openDetailDialog(
undefined,
undefined,
config,
{ title, icon: item.icon },
item.url_path
);
} catch {
showAlertDialog(this, {
text: this.hass.localize(
"ui.panel.config.lovelace.dashboards.duplicate_failed"
),
});
}
};
private async _addDashboard() {
showNewDashboardDialog(this, {
selectConfig: async ({ config }: NewDashboardSelection) => {
@@ -644,7 +688,8 @@ export class HaConfigLovelaceDashboards extends LitElement {
dashboard?: LovelaceDashboard,
urlPath?: string,
defaultConfig?: LovelaceRawConfig,
fieldSuggestions?: LovelaceDashboardSuggestions
fieldSuggestions?: LovelaceDashboardSuggestions,
duplicateOfUrlPath?: string
): Promise<void> {
const defaultPanel = this.hass.systemData?.default_panel || DEFAULT_PANEL;
showDashboardDetailDialog(this, {
@@ -666,7 +711,17 @@ export class HaConfigLovelaceDashboards extends LitElement {
)
);
if (defaultConfig) {
await saveConfig(this.hass!, created.url_path, defaultConfig);
await saveConfig(
this.hass!,
created.url_path,
duplicateOfUrlPath
? replaceDashboardLinks(
defaultConfig,
duplicateOfUrlPath,
created.url_path
)
: defaultConfig
);
}
},
updateDashboard: async (values) => {
@@ -0,0 +1,89 @@
import type {
LovelaceConfig,
LovelaceRawConfig,
} from "../../../../data/lovelace/config/types";
import { isStrategyDashboard } from "../../../../data/lovelace/config/types";
/**
* Points a root-relative path at another dashboard. Only the first segment is
* replaced, so a view that shares its path with the dashboard keeps it.
*/
export const replaceDashboardInPath = (
path: string,
fromUrlPath: string,
toUrlPath: string
): string => {
if (!path.startsWith(`/${fromUrlPath}`)) {
return path;
}
const rest = path.slice(fromUrlPath.length + 1);
return rest === "" || "/?#".includes(rest[0]) ? `/${toUrlPath}${rest}` : path;
};
const linkKey = (obj: Record<string, unknown>): string | undefined => {
if (obj.action === "navigate") {
return "navigation_path";
}
if (obj.action === "url") {
return "url_path";
}
switch (obj.type) {
case "area":
return "navigation_path";
case "weblink":
case "iframe":
return "url";
default:
return undefined;
}
};
const replaceLinks = (
value: unknown,
fromUrlPath: string,
toUrlPath: string
): unknown => {
if (Array.isArray(value)) {
return value.map((item) => replaceLinks(item, fromUrlPath, toUrlPath));
}
if (!value || typeof value !== "object") {
return value;
}
const obj = value as Record<string, unknown>;
const result = Object.fromEntries(
Object.entries(obj).map(([key, child]) => [
key,
// Strategy options are not card config
key === "strategy" ? child : replaceLinks(child, fromUrlPath, toUrlPath),
])
);
const key = linkKey(obj);
if (key && typeof result[key] === "string") {
result[key] = replaceDashboardInPath(result[key], fromUrlPath, toUrlPath);
}
if (obj.type === "cast" && obj.dashboard === fromUrlPath) {
result.dashboard = toUrlPath;
}
return result;
};
export const replaceDashboardLinks = (
config: LovelaceRawConfig,
fromUrlPath: string,
toUrlPath: string
): LovelaceRawConfig => {
if (isStrategyDashboard(config)) {
return config;
}
const result = replaceLinks(config, fromUrlPath, toUrlPath) as LovelaceConfig;
result.views?.forEach((view) => {
if (typeof view.back_path === "string") {
view.back_path = replaceDashboardInPath(
view.back_path,
fromUrlPath,
toUrlPath
);
}
});
return result;
};
@@ -74,9 +74,9 @@ class IntegrationsStartupTime extends LitElement {
${domainToName(this.hass.localize, setup.domain, manifest)}
</span>
<span slot="supporting-text">${setup.domain}</span>
<div slot="end">
<span slot="end">
${setupSeconds ? html`${setupSeconds} s` : ""}
</div>
</span>
</ha-list-item-button>
`;
})}
@@ -115,7 +115,7 @@ class IntegrationsStartupTime extends LitElement {
max-width: 40px;
border-radius: var(--ha-border-radius-square);
}
div[slot="end"] {
span[slot="end"] {
font-size: var(--ha-font-size-s);
}
`;
-1
View File
@@ -250,7 +250,6 @@ class HaPanelHistory extends LitElement {
@clear-filter=${this._clearSources}
>
<ha-sources-picker
.hass=${this.hass}
.value=${this._targetPickerValue}
.filters=${this._filters}
.entitySources=${this._entitySources}
-1
View File
@@ -176,7 +176,6 @@ export class HaPanelLogbook extends LitElement {
@clear-filter=${this._clearSources}
>
<ha-sources-picker
.hass=${this.hass}
.value=${this._targetPickerValue}
.filters=${this._filters}
.entitySources=${this._entitySources}
@@ -16,6 +16,7 @@ import "../../../components/ha-svg-icon";
import "../components/hui-badge-edit-mode";
import { moveAtPath } from "../editor/lovelace-path";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import type { HuiBadge } from "./hui-badge";
const BADGE_SORTABLE_OPTIONS: HaSortableOptions = {
@@ -46,7 +47,8 @@ export class HuiViewBadges extends LitElement {
private _checkAllHidden() {
const allHidden =
!this.lovelace.editMode && this.badges.every((section) => section.hidden);
!isLayoutEditMode(this.lovelace) &&
this.badges.every((section) => section.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -125,7 +127,7 @@ export class HuiViewBadges extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = this.lovelace.editMode;
const editMode = isLayoutEditMode(this.lovelace);
const badges = this.badges;
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more