Compare commits

...
Author SHA1 Message Date
Matthias AlphartandClaude Fable 5.2 985be1ba66 Show icon of selected option in ha-select field (#56406)
* Show icon of selected option in ha-select field

When the selected option of ha-select has an iconPath, render the icon
next to the value in the trigger field, like the dropdown items do.

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

* Remove ha-select rendering test

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

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-12-03 09:44:07 +00:00
renovate[bot] 3823386297 Update dependency tar to v8.0.3 (#56393)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 11:34:21 +02:00
Thomas Freudenberg dfae0a7a38 Respect profile date format for date-only states (#56296) 2026-12-03 09:34:09 +00:00
Petar Petrov 45c5bb2d3f Rerender ha-form when the language changes (#56402)
* Rerender ha-form when the language changes

Consume the localize context in ha-form so labels and helpers update for forms that no longer get hass.

* Pass the consumed localize to ha-form fields
2026-12-03 09:32:42 +00:00
Petar Petrov 5429cd2bb1 Drop hass from the confirm entity rows (#56395)
The button, input button, lock, scene and script rows read contexts, and confirmAction takes the user id and localize.
2026-12-03 09:31:56 +00:00
Petar Petrov 2d5d97b8aa Migrate Lovelace service rows to contexts (#56394)
Date, time, fan, number, select and text rows consume entity state, i18n, formatters, config and the API instead of taking hass.
2026-12-03 09:31:29 +00:00
Petar Petrov f86e59b58e Move the condition evaluator onto Lit context (#56400)
* Move the condition evaluator onto Lit context

The visibility evaluator reads states, config, locale, registries and the connection from context; ha-visibility-status drops hass.

* Pass time condition inputs as separate values

Skip evaluator input rebuilds on hosts without conditions and drop the redundant hass trigger in the conditional listener mixin.
2026-12-03 09:30:36 +00:00
Petar Petrov e33b94e34c Move areas strategy editor and location condition editor to contexts (#56397)
getAreaGroupedEntities, resolveLocationZones and migrateLocationCondition take the values they read.
2026-12-03 09:29:53 +00:00
Petar Petrov 235a5d01e2 Drop hass from the display entity rows (#56398)
Climate, cover, event, humidifier, sensor, simple, timer, toggle, update, valve and attribute rows read their entity, localize, config and formatters from contexts.
2026-12-03 09:29:44 +00:00
Petar Petrov 8479c83c49 Move group, select and media player rows to contexts (#56399)
The rows read their entity, formatters, config and services from Lit contexts instead of hass.
2026-12-03 09:28:38 +00:00
Petar Petrov 6869fa1ad6 Pass separate values to computeTooltip in Lovelace tooltip users (#56396)
Buttons row, header and base, and the icon, state-icon and state-label picture elements read contexts instead of hass.
2026-12-03 09:28:05 +00:00
6bace34775 Add MQTT network visualization (#55786)
* Add MQTT network visualization

Add a map to the MQTT config panel that shows how MQTT devices, entities,
device triggers and tags are set up, where they came from and the topics
they use. A focused item shows its config, and a topic shows its stored
and live messages.

The topic view and the payload helpers are based on the MQTT explorer
from #55656.

Co-authored-by: Erwin Douna <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* Fix MQTT map build and review findings

Keep the template placeholders of the broker tooltip intact for the
minifier, show tag scanners without a device, take hidden nodes before
renumbering the categories, ignore stale topic subscriptions, show the
QoS of the live subscription, follow theme and language changes, and
use narrow contexts in the config and message views.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the last message of MQTT tags and device triggers

Show the last received message of the topic of a focused tag or device
trigger in its tooltip, like for entities.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the raw MQTT payloads when the key diff finds no change

Parsing JSON hides changes in whitespace or in numbers beyond the safe
integer range, so show the previous and current payload instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the physics button on the MQTT map

With physics off, nodes in the MQTT map can be dragged. The
physicsToggle property is removed again, as nothing else uses it.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Group MQTT subentries under one node

Subentries share one "Subentries" source node, with the device of each
subentry right under it, instead of a source node per subentry above its
device. All sources have the same color.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Add a tree view to the MQTT map and show items on focus

A button switches the MQTT map between the graph and a tree from left
to right, remembered in the browser. Entities, device triggers and tags
start switched off in the legend; a focused device shows its own items,
and a focused item shows only itself with its topics.

ha-network-graph gets two opt-in properties: fixedLayout places the
nodes at the positions of the data, and hiddenCategories sets the
selection of the legend.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the graph icon on the tree view button in the tree view

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Keep the selected node left in the MQTT tree and ring every selection

In a fixed layout, which grows to the right like a tree, the selected
node sits at a quarter of the width and only its children to the right,
with room for their labels, decide the zoom.

The selected node of the MQTT map gets the ring color of the theme, also
an entity with a border color of its own.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Fit the network graph view after switching the layout

* Do not pin nodes dragged in a fixed network graph layout

* Animate the network graph view after switching the layout

* Keep the MQTT map layout button above the zoom reset button

* Move network graph nodes smoothly between the tree and force layouts

* Restore the force layout view and fit the tree after a layout switch

* Move the network graph view along with the nodes on a layout switch

* Focus the parent node when a node is deselected

* Keep force layout positions on legend changes in the tree and stop wheel zoom on reset

* Show the MQTT map details in an adaptive dialog on narrow screens

* Keep nodes of a fixed layout readable around a selected node

* Toggle MQTT map sources with the keyboard too

* Use the shared chart control frame for the MQTT source filter

* Announce the state of the MQTT map layout toggle

* Address Copilot review of the MQTT map

* Show MQTT states in the tooltip as they are

* Keep physics on after leaving the MQTT map mid transition

* Test the visibility of nodes on the MQTT map

* Apply UX suggestions to the MQTT map

* Address review of the MQTT map

* Read the zoom of the MQTT map from the series option

* Address review of the MQTT map

* Refresh the last messages of the MQTT map on an unchanged structure

* Keep the whitespace of raw payloads in the MQTT topic view

* Keep the MQTT map state stable on language, fetch and viewport changes

* Move the MQTT map source filter next to the search

* Clear the MQTT map focus when its node leaves the map

Pass darkMode and localize to the chart data builder instead of hass.

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

* Use the split network graph changes in the MQTT map

Take ha-network-graph from #56309, #56310 and #56313 and use treeLayout
instead of fixedLayout. The wheel zoom glide is dropped.

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

* Take over the review fixes of the split network graph PRs

Take ha-network-graph and its helpers from #56309 (8a6fe8cee1) and #56313
(cfbc45bb2e), with the fixes for the Copilot reviews.

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

* Take over the layout controller and zoom reset fix of #56313

Take ha-network-graph and its helpers from #56309 (ed8794a548) and
#56313 (149f159880, ca68e3a2c2). Without the style fade the map fades
without animation, and the topic diamonds lose their transparent
border, as nodeClickRadius already makes them easy to click.

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

* Keep the node size along with an animated view move

Take network-graph-view.ts, network-layout-controller.ts and their tests
from #56313 (d3cf4fa2fe).

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

* Drop the node size fix again

Revert 5acba41905: #56313 dropped d3cf4fa2fe, and the size change
during an animated view move is reported upstream as
apache/echarts#21894.

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

---------

Co-authored-by: Erwin Douna <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 10:25:21 +02:00
Paul Bottein 852d0b750a Use the state selector in the light effect feature editor (#56375) 2026-12-03 09:03:41 +02:00
Paul Bottein b4ab33bc08 Add a reorderable chips display to the state selector (#56374)
* Add a reorderable chips display to the state selector

* Disable the chips without an entity and add the default label

* Disable the chips with an empty entity list and keep any state exclusive
2026-12-03 09:03:40 +02:00
Balloob BotandPaulus Schoutsen b16979b1f5 Collapse long lists of energy meter suggestions (#56390)
* Collapse long energy suggestion lists

* Preserve keyboard focus when expanding energy suggestions

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
2026-12-03 08:49:47 +02:00
renovate[bot] 9ba31a3d5f Update Node.js to v24.23.0 (#56391)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 08:42:10 +02:00
renovate[bot] 27308b03f9 Update dependency glob to v15 (#56392)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 08:42:01 +02:00
Paul Bottein ffc4233111 Read the gauge card entity from the form context (#56372) 2026-12-03 06:20:50 +00:00
Jan BouwhuisandClaude Opus 5.5 40a2317637 Add a left-to-right tree layout to the network graph (#56313)
With treeLayout set, the graph shows every node at the x and y of the
data, without the force layout, the physics button or saved positions.
Nodes keep their size on zoom, and the selected node is kept left with
room for its label and children.

NetworkLayoutController moves the view to a selected node and along with
the nodes on a switch between the tree and the force layout, with a
series center/zoom that ECharts animates. The chart base also checks the
graph roam when a render finishes, so the zoom reset shows after such a
move.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 07:50:09 +02:00
renovate[bot] d5c9dc89df Update pnpm to v12.25.1 (#56387)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 23:52:13 +00:00
renovate[bot] a7d9a8721e Update dependency glob to v14.0.7 (#56386)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 23:51:41 +00:00
Paul Bottein 30cf5240a1 Pass the form context to nested forms (#56373) 2026-12-02 23:43:21 +00:00
renovate[bot] 81e088885d Update dependency temporal-polyfill to v1.0.9 (#56379)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 20:08:09 +01:00
95 changed files with 7773 additions and 1596 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
24.22.3
24.23.0
+5 -5
View File
@@ -124,7 +124,7 @@
"sortablejs": "1.15.7",
"stacktrace-js": "2.0.2",
"superstruct": "2.0.2",
"temporal-polyfill": "1.0.8",
"temporal-polyfill": "1.0.9",
"tinykeys": "4.0.1",
"weekstart": "2.0.0",
"workbox-cacheable-response": "7.4.1",
@@ -189,7 +189,7 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "14.0.6",
"glob": "15.0.0",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
@@ -211,7 +211,7 @@
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "8.0.2",
"tar": "8.0.3",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
@@ -223,8 +223,8 @@
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]4.0",
"packageManager": "[email protected]5.1",
"volta": {
"node": "24.22.3"
"node": "24.23.0"
}
}
+104 -108
View File
@@ -7,172 +7,172 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.24.0
version: 12.24.0
specifier: 12.25.1
version: 12.25.1
packages:
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-X22iCSEW/KDoYthnl5DXWv/ikFBuXHx91Gl6sjCcSVVIN3emVFQYkezWzaYYyG/I82e3jXEpZei4ItBGMtxxCA==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-QHXIyWMsuntq05xq9twYS6upQZS2TYeJIfmBWDFw1Xyi8XQxiaD06DSTWwZYjR38GwOP/dveeMC2jk2Y68IAAg==}
cpu: [arm64]
os: [android]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-gRJtKBWbmztU5GEpUIPNR2oHDKljHsyKyUrJK9JBDnwVDdnabVUHCNYeO+wukkiYSvWt7zkRBtOP3IXMDDiNLQ==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-bOJZTzi5c0MrI8xn6qU+0QzYu3gHMUtwLxb8ZRzuk/by7u6XhGXpn+gfppw7BF3te+rxpqK/mSR2PXb40d/7kg==}
cpu: [x64]
os: [android]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-0BT++Bo1b5cHULSRiKAiNwwh5KNFlVvA+qupw+MjhkOfKdVY7iSztUeHqQT3pwkE/Ls3Sv7PhszBdaB7j6T20g==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-NXG2kaXA7ui3T7aznhAmG8AwWZ/BmKkxqT9DIIQJ0jU1jLKkRhGce1gbyJ+RAeGKx0HcRHAJbRi38lcHgpCteA==}
cpu: [arm64]
os: [darwin]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-zRT0h/538rJgoxSaYRccWPVlEh/v/vsE0VhfiOuNCxTnX9GCi//ttM7F+gkb5uD5Anspj52SR1iUU8C3oqmpbw==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-cDnnUeocsg6ESvgjxTs9az5SUt9MEaINaMKGzAEqrfFMCRvaYgkC+0Ct7eYb/41i9WYPvd9DFv8H29LHECwcVA==}
cpu: [x64]
os: [darwin]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-irpbUEPP8LCGlX7SElqZrzcTIZ/B1pgwO0uYlf1DiedVBnsYM9COoWuoXnbudtFpuwCtWGSOOhsMNGGOsiAonA==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-LEDM+BE5BdYEetfEHKSD9f5IhOWmMAHix9bMqhds6dn3cMICNQeJZQaoimwUDeVVAR8yMtvaDwRZGuWXOq5gJw==}
cpu: [x64]
os: [freebsd]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-LCvWPUR1+/EQ/AVp9U1zLKMOo2i0G9+6jSSw1xaL59VR13KEPbTFsKFDO8fmn2o1BAQG5rh9lx+KHVinTSDWpQ==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-LtURUp1sJoS0ENQtKLk+oTI7oSlcEDHl3SOxxS8AUD/FTmP1AM1htwYwxi+91J+MTinOYqcUFrgb1f87Zn1Vfw==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-xSu3krlF1mW+v20odelPYs56om88VGZp6pE0vJKmUtPJ+8EUB6OA4WbVyyxEuqtubhkvFxyZiWDN/cvDKF2OWw==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-55Ni6+zebnL2zdvKq23tZCEWbtPSMKeQ1MwJAwqDqS/VjD/Z6hT0BlJSTFvHKUgrWOBxnH501iTIyQgLVD+Cfw==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-xuIEolHGrT9LbKhLeSrjCT3xlC62kNrEHGjkuUJIHCdgWCRSVoH4Xh0jvVn29/ArKN7aFurqnl8EQoQ7leVJuw==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-52Fzal3IdcqsJ1kChNZC00JoFcwA9tDem/qTuZxpeJcc0KTALXTI5U/LbVF1+OXBfn72ADjS0Hxewkng7Q1iBA==}
cpu: [loong64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-OQxi46cY9uc91A6yv7qz6l1NlyVCTsWxbbgk0oKzhMIQuCt+U7OCHcwbfly5Y9FJSsERJVz2MYwVGvy4sgRtPw==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-x3b9VQyrmHi1IIejDGqZWrdmgbtTV/qgE3Sca0NVYmY6gT1cAvkKFq6tQvHJEgeEdny7hGKl+1sk6YkKRs1Sfg==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-uIFs1byuK2ZRcqmb6+9/KddZdHE+JUYM3yjxnN7H+x9A237EoGRnw8UeruWFW9OYMMfFTGRAxuq2b0DiYx4gHQ==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-lPQ5PjYog/N07VsOBEZr661GgZ7y39wQLRCviHcL4RfpMBpe4XeJKK3W7YKl9NJz6+5/nzMYYfTcvZPFLWuMvA==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-Ct1ggli4DyL/LnasrhqgEc8PDlzmhKx0DculRiWygyN+STzQWA/qwHtuMzgbLQd84CNUJGZfTrUkBYaXmLifKw==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-5kdJeOXns1O/PYqdR2Zk/0ci/0mCz1LhaJDIA6NiqNdgFxwCC6ufRTBiu9u4FB/F2MWBLPDtyHxwzpcbBFCP9Q==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-NeIW64Azg/b+QFj6Z14BYb84pUKVIrvf15JhhuV7YmouaZbiMRG/8nDwIvEIRvwLqXacd4gVdcsGqUcO7oIYhQ==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-GRsFj54bSmdhceZwrA+zReMfGJw6X6qpC4pJh6iLaUcy3p0fG7A7Zqr70AKmtzvW1Zm2VGkeeIzja6QSkN09Vw==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-5As5an12DTY8MlssTLCaMtRDYpn9C3hxcasEDCJQC0VqS6ZnRmlLWsL8dI0ocqdh3ejW6o6F0esucP5MECo1nA==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-Db2T6CtSNO8hjG6FISkOaZ2PW/OpynoXcT+jWEh44xDgSBt68rgbjGIbzjXSKJ+vH2mkoUxaUZCcLLusBVqelw==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-bZxzTQU8hqBoLzjb6VELvxJNDnWUrNf3/xSbl7ewIPfVgvs8+R77Rc+30ynxWndr3tD6zJB/iEYIdxuGZB/bnQ==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-2hU5yNM/C8FT5eqbrNzB+0yGw/SS3oMJ1afk8pXEDsGU4vWdiiWxSqQ0kM8GHIvCDa/qRyw9ns98XWu5KZxxiA==}
cpu: [x64]
os: [netbsd]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-TzhbjiypYbZ7HejRPjxzJreWVymMFtxcm9pvxOY7DUCmYxEcOqR0iJruzLXJL7STJ6O+KrpwpcybmiKPrhOZyg==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-v7YduE+TgEid1AiIThVBmYBnF0dj6vtk3ymcCkcM5FvanAM8MXoZhSiQYayQruh8xDwTXf5n8Zgn1OOi8WtqDg==}
cpu: [arm64]
os: [win32]
'@pnpm/[email protected]4.0':
resolution: {integrity: sha512-h0s1cTRBVxKLv7uDQaN0YIXRc6itKv3mbuw5m093HL9bqy7Ys+FPZ8gvR/+cABheg64ke1xwmqO4QbuBI+qbhQ==}
'@pnpm/[email protected]5.1':
resolution: {integrity: sha512-cMfLsOE4zxSYBZYWyK1tr6BvCKVDyC81CnZg953t/6MEL592D8gk0eGdHQilEcd+yO+o6Ey1W9LLQdjl7pglsQ==}
cpu: [x64]
os: [win32]
[email protected]4.0:
resolution: {integrity: sha512-X5D1CkiqQPAdxDvTrLUoki/YmdO5CQFf2yOvc7sxxXjynOspvppNbwFGrbNCBqrDMnlgQ8xQJLgV73YojLrHZw==}
[email protected]5.1:
resolution: {integrity: sha512-psZ31wNNPXmvE28z2zPNbUEz1z+lZaBr1kqPCW0lN92HoI1o4Y/zd3cf9RwY4uwxvgO0RnDrGeJBiQ6uOu0Bag==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
'@pnpm/[email protected]4.0':
'@pnpm/[email protected]5.1':
optional: true
[email protected]4.0:
[email protected]5.1:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.24.0
'@pnpm/exe.android-x64': 12.24.0
'@pnpm/exe.darwin-arm64': 12.24.0
'@pnpm/exe.darwin-x64': 12.24.0
'@pnpm/exe.freebsd-x64': 12.24.0
'@pnpm/exe.linux-arm64': 12.24.0
'@pnpm/exe.linux-arm64-musl': 12.24.0
'@pnpm/exe.linux-loong64': 12.24.0
'@pnpm/exe.linux-ppc64': 12.24.0
'@pnpm/exe.linux-riscv64': 12.24.0
'@pnpm/exe.linux-s390x': 12.24.0
'@pnpm/exe.linux-x64': 12.24.0
'@pnpm/exe.linux-x64-musl': 12.24.0
'@pnpm/exe.netbsd-x64': 12.24.0
'@pnpm/exe.win32-arm64': 12.24.0
'@pnpm/exe.win32-x64': 12.24.0
'@pnpm/exe.android-arm64': 12.25.1
'@pnpm/exe.android-x64': 12.25.1
'@pnpm/exe.darwin-arm64': 12.25.1
'@pnpm/exe.darwin-x64': 12.25.1
'@pnpm/exe.freebsd-x64': 12.25.1
'@pnpm/exe.linux-arm64': 12.25.1
'@pnpm/exe.linux-arm64-musl': 12.25.1
'@pnpm/exe.linux-loong64': 12.25.1
'@pnpm/exe.linux-ppc64': 12.25.1
'@pnpm/exe.linux-riscv64': 12.25.1
'@pnpm/exe.linux-s390x': 12.25.1
'@pnpm/exe.linux-x64': 12.25.1
'@pnpm/exe.linux-x64-musl': 12.25.1
'@pnpm/exe.netbsd-x64': 12.25.1
'@pnpm/exe.win32-arm64': 12.25.1
'@pnpm/exe.win32-x64': 12.25.1
---
lockfileVersion: '9.0'
@@ -371,7 +371,7 @@ importers:
version: 3.0.2
fullcalendar:
specifier: 7.1.5
version: 7.1.5([email protected].8)
version: 7.1.5([email protected].9)
fuse.js:
specifier: 7.5.0
version: 7.5.0
@@ -451,8 +451,8 @@ importers:
specifier: 2.0.2
version: 2.0.2
temporal-polyfill:
specifier: 1.0.8
version: 1.0.8
specifier: 1.0.9
version: 1.0.9
tinykeys:
specifier: 4.0.1
version: 4.0.1(patch_hash=cdc7ece96d53357d38ff3c124a2553f86e3a5dc333d641d223eb6f07e28275f0)
@@ -641,8 +641,8 @@ importers:
specifier: 4.2.5
version: 4.2.5([email protected])
glob:
specifier: 14.0.6
version: 14.0.6
specifier: 15.0.0
version: 15.0.0
globals:
specifier: 17.14.0
version: 17.14.0
@@ -707,8 +707,8 @@ importers:
specifier: 22.1.0
version: 22.1.0
tar:
specifier: 8.0.2
version: 8.0.2
specifier: 8.0.3
version: 8.0.3
terser-webpack-plugin:
specifier: 5.6.1
version: 5.6.1([email protected])([email protected])([email protected])([email protected])([email protected])
@@ -5424,9 +5424,9 @@ packages:
resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}
engines: {node: 18 || 20 || >=22}
glob@14.0.6:
resolution: {integrity: sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==}
engines: {node: 18 || 20 || >=22}
glob@15.0.0:
resolution: {integrity: sha512-tiRK5MxAsWTadBLU7T3r2hanLM785BdqH9cfQ9wSTQNU+yULR5gTNiHjB1jpp88qIbX1U+rdrCUXhNv9A2G91g==}
engines: {node: 20 || >=22}
[email protected]:
resolution: {integrity: sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==}
@@ -6718,9 +6718,9 @@ packages:
resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}
engines: {node: 18 || 20 || >=22}
path-scurry@3.0.0:
resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==}
engines: {node: 18 || 20 || >=22}
path-scurry@4.1.0:
resolution: {integrity: sha512-V/lmmLwmIUkQzwMR7vAvmTfFH6Pq3QLJryRRO7QSEH5ZpjxpWXA5hGVH1fVnUaT8q8qb1J08NGaaTu501JLRnA==}
engines: {node: 20 || >=22}
[email protected]:
resolution: {integrity: sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==}
@@ -7435,8 +7435,8 @@ packages:
resolution: {integrity: sha512-to/OxuCk5DeVONcjjODT7aeoRq5NIPPlfPc0tNML+wLlnf6u5BcJz97Uukv3pT3jzorkFhUevylkAiBr+ZmV2w==}
engines: {node: '>=18'}
[email protected].2:
resolution: {integrity: sha512-1keL/dBVXwzliTinVjILeV/qZ2K3NNVFpg4JM1h3REOUJFamSLZmzVbCJXS6mF91//NwSaCbQ0gqmNwzE+ExCA==}
[email protected].3:
resolution: {integrity: sha512-S+Gnl5H2+dD5DF7h4e6BOftgFcCqPv3rDRXCvhPLPeX7o2hnQ/aCax5bjdzRBb886xvBGR1vs+wHComyXbnRhQ==}
engines: {node: '>=22'}
[email protected]:
@@ -7446,14 +7446,14 @@ packages:
resolution: {integrity: sha512-aoBAniQmmwtcKp/7BzsH8Cxzv8OL736p7v1ihGb5e9DJ9kTwGWHrQrVB5+lfVDzfGrdRzXch+ig7LHaY1JTOrg==}
engines: {node: '>=8'}
[email protected].8:
resolution: {integrity: sha512-RCCGa0GddT099XG49ijdD0tDf86L8vfuZun1+JyJiO4Y2NP9PACQsG0OnvNPXwVLisdvhr/zqL2nhKQmXXx08A==}
[email protected].9:
resolution: {integrity: sha512-DPZZyb4Q8fwVUtWCN0Ugj4ZEHC0BfNHJxqRkNKpCSC9A0m7KowVRBz6mq8SjVvafMG+f7y8uioOICCNmj+j84Q==}
[email protected]:
resolution: {integrity: sha512-wxVoanmDeavXie1vu2JaQ3WIc3JZnWAOYFBsJyATaVsXsycKYUflGsyBmrRSnoCpZJpwPyr38VpgSUlQ8CbFxg==}
[email protected].4:
resolution: {integrity: sha512-4mAcgbWlaxe+gn23gk8g0iHxCVGVOhKzSCfF5HM3lfvH8BdT+/pBmH/R/E4CrIse+koUgs8ThkPzCLnui6Fi8w==}
[email protected].5:
resolution: {integrity: sha512-8gRTzLbYDO3e4riWZ+wbKQ70Q8A5j8EI7fpSPgni151f/dDg26mPwfin1d/xk0TssDGuPE3hNfUwWsZf9DZi3A==}
[email protected]:
resolution: {integrity: sha512-G13vtMYPT/J8A4X2SjdtBTphZlrp1gKv6hZiOjw14RCWg6GbHuQBGtjlx75xLbYV/wEc0D7G5K4rxKP/cXk8Bw==}
@@ -9918,14 +9918,14 @@ snapshots:
optionalDependencies:
typescript: 6.0.3
'@full-ui/[email protected]([email protected].8)':
'@full-ui/[email protected]([email protected].9)':
dependencies:
temporal-polyfill: 1.0.8
temporal-polyfill: 1.0.9
'@fullcalendar/[email protected](@full-ui/[email protected]([email protected].8))([email protected].8)':
'@fullcalendar/[email protected](@full-ui/[email protected]([email protected].9))([email protected].9)':
dependencies:
'@full-ui/headless-calendar': 7.1.5([email protected].8)
temporal-polyfill: 1.0.8
'@full-ui/headless-calendar': 7.1.5([email protected].9)
temporal-polyfill: 1.0.9
'@gar/[email protected]': {}
@@ -13274,12 +13274,12 @@ snapshots:
[email protected]:
optional: true
[email protected]([email protected].8):
[email protected]([email protected].9):
dependencies:
'@full-ui/headless-calendar': 7.1.5([email protected].8)
'@fullcalendar/core': 7.1.5(@full-ui/[email protected]([email protected].8))([email protected].8)
'@full-ui/headless-calendar': 7.1.5([email protected].9)
'@fullcalendar/core': 7.1.5(@full-ui/[email protected]([email protected].9))([email protected].9)
preact: 10.29.8
temporal-polyfill: 1.0.8
temporal-polyfill: 1.0.9
transitivePeerDependencies:
- preact-render-to-string
@@ -13409,11 +13409,10 @@ snapshots:
minipass: 7.1.3
path-scurry: 2.0.2
glob@14.0.6:
glob@15.0.0:
dependencies:
minimatch: 11.0.5
minipass: 7.1.3
path-scurry: 3.0.0
path-scurry: 4.1.0
[email protected]:
dependencies:
@@ -14833,10 +14832,7 @@ snapshots:
lru-cache: 11.5.3
minipass: 7.1.3
path-scurry@3.0.0:
dependencies:
lru-cache: 11.5.3
minipass: 7.1.3
path-scurry@4.1.0: {}
[email protected]: {}
@@ -15657,7 +15653,7 @@ snapshots:
minizlib: 3.1.0
yallist: 5.0.0
[email protected].2: {}
[email protected].3: {}
[email protected]:
dependencies:
@@ -15668,14 +15664,14 @@ snapshots:
[email protected]: {}
[email protected].8:
[email protected].9:
dependencies:
temporal-spec: 1.0.1
temporal-utils: 1.0.4
temporal-utils: 1.0.5
[email protected]: {}
[email protected].4: {}
[email protected].5: {}
[email protected]:
dependencies:
+1 -7
View File
@@ -1,8 +1,6 @@
/* eslint-disable lit/prefer-static-styles */
import { html } from "lit";
import { customElement, state } from "lit/decorators";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../common/translations/localize";
import { customElement } from "lit/decorators";
import { HaForm } from "../components/ha-form/ha-form";
import "./ha-auth-form-string";
@@ -10,10 +8,6 @@ const localizeBaseKey = "ui.panel.page-authorize.form";
@customElement("ha-auth-form")
export class HaAuthForm extends HaForm {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
protected getFormProperties(): Record<string, any> {
return {
localize: this._localize,
+20 -7
View File
@@ -1,5 +1,6 @@
import type { HassConfig } from "home-assistant-js-websocket";
import { listenMediaQuery } from "../dom/media_query";
import type { HomeAssistant } from "../../types";
import type { FrontendLocaleData } from "../../data/translation";
import type {
TimeCondition,
VisibilityCondition,
@@ -19,7 +20,8 @@ const MAX_TIMEOUT_DELAY = 2147483647;
* Delays past the setTimeout max are capped and retried without firing.
*/
function scheduleTimeBoundaryListener(
getHass: () => HomeAssistant,
getLocale: () => FrontendLocaleData,
getConfig: () => HassConfig,
timeCondition: Omit<TimeCondition, "condition">,
addListener: (unsub: () => void) => void,
onBoundary: () => void
@@ -27,8 +29,12 @@ function scheduleTimeBoundaryListener(
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const scheduleUpdate = () => {
// Read hass here so a timezone change applies at the next boundary.
const delay = calculateNextTimeUpdate(getHass(), timeCondition);
// Read these here so a timezone change applies at the next boundary.
const delay = calculateNextTimeUpdate(
getLocale(),
getConfig(),
timeCondition
);
if (delay === undefined) return;
@@ -59,13 +65,14 @@ function scheduleTimeBoundaryListener(
* could have flipped.
*
* This does not evaluate the conditions itself: the caller recombines client
* and server results on notification. Used by `ConditionEvaluatorController`,
* and server results on notification. Used by `ConditionEvaluator`,
* which merges these client signals with the results of `subscribe_condition`
* subscriptions.
*/
export function observeConditionChanges(
conditions: VisibilityCondition[],
getHass: () => HomeAssistant,
getLocale: () => FrontendLocaleData,
getConfig: () => HassConfig,
addListener: (unsub: () => void) => void,
onChange: () => void
): void {
@@ -74,6 +81,12 @@ export function observeConditionChanges(
});
extractTimeConditions(conditions).forEach((timeCondition) => {
scheduleTimeBoundaryListener(getHass, timeCondition, addListener, onChange);
scheduleTimeBoundaryListener(
getLocale,
getConfig,
timeCondition,
addListener,
onChange
);
});
}
+7 -15
View File
@@ -1,4 +1,3 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ConditionContext,
VisibilityCondition,
@@ -6,7 +5,7 @@ import type {
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluator } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
@@ -28,17 +27,9 @@ export const subscribeVisibility = (
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
// The controller only needs a host to register with and to re-render.
const host: ReactiveControllerHost = {
addController: () => undefined,
removeController: () => undefined,
requestUpdate: () => undefined,
updateComplete: Promise.resolve(true),
};
let active = true;
const controller = new ConditionEvaluatorController(host, {
const evaluator = new ConditionEvaluator({
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
@@ -57,18 +48,19 @@ export const subscribeVisibility = (
: sanitized;
const getContext = () => context;
controller.hostConnected();
controller.observe(validConditions, hass, getContext);
evaluator.connect();
evaluator.setInputs(hass, hass.connection, hass.localize);
evaluator.observe(validConditions, getContext);
return {
update: (newHass) => {
if (active) {
controller.observe(validConditions, newHass, getContext);
evaluator.setInputs(newHass, newHass.connection, newHass.localize);
}
},
unsubscribe: () => {
active = false;
controller.hostDisconnected();
evaluator.disconnect();
},
};
};
+8 -5
View File
@@ -5,24 +5,27 @@ import {
addMinutes,
differenceInMilliseconds,
} from "date-fns";
import type { HomeAssistant } from "../../types";
import type { HassConfig } from "home-assistant-js-websocket";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import { parseTimeString } from "../datetime/check_time";
import type { TimeCondition } from "../../panels/lovelace/common/validate-condition";
/**
* Calculate milliseconds until next time boundary for a time condition
* @param hass Home Assistant object
* @param locale User locale (time zone preference)
* @param config Core config (server time zone)
* @param timeCondition Time condition to calculate next update for
* @returns Milliseconds until next boundary, or undefined if no boundaries
*/
export function calculateNextTimeUpdate(
hass: HomeAssistant,
locale: FrontendLocaleData,
config: HassConfig,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): number | undefined {
const timezone =
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
locale.time_zone === TimeZone.server
? config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
@@ -1,16 +1,31 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
Connection,
HassEntities,
UnsubscribeFunc,
} from "home-assistant-js-websocket";
import { subscribeCondition } from "../../data/automation";
import {
configContext,
connectionContext,
internationalizationContext,
registriesContext,
statesContext,
} from "../../data/context";
import type {
Condition,
ConditionContext,
ConditionHass,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
HomeAssistantRegistries,
} from "../../types";
import { consumeContext, ContextController } from "../decorators/consume";
import type { LocalizeFunc } from "../translations/localize";
import { observeConditionChanges } from "../condition/listeners";
import { isPureClientCondition } from "../condition/translate";
import type {
@@ -38,19 +53,22 @@ const firstDefined = (
/**
* Live evaluation of a visibility tree: `subscribe_condition` for server
* subtrees, local checks for screen/user/time/etc. Call {@link observe} when
* inputs change. Result stays `unknown` until server replies so nothing flashes.
* subtrees, local checks for screen/user/time/etc. Call {@link observe} and
* {@link setInputs} when inputs change. Result stays `unknown` until server
* replies so nothing flashes.
*/
export class ConditionEvaluatorController implements ReactiveController {
private _host: ReactiveControllerHost;
export class ConditionEvaluator {
private readonly _onResult: ConditionEvaluatorOptions["onResult"];
private readonly _resubscribeDelay: number;
private _conditions?: VisibilityCondition[];
private _hass?: HomeAssistant;
private _conditionHass?: ConditionHass;
private _connection?: Connection;
private _localize?: LocalizeFunc;
private _getContext?: () => ConditionContext;
@@ -65,7 +83,7 @@ export class ConditionEvaluatorController implements ReactiveController {
private _hasPendingResubscribe = false;
// Resubscribe if hass.connection is replaced even when the tree is unchanged.
// Resubscribe if the connection is replaced even when the tree is unchanged.
private _subscribedConnection?: Connection;
// Skip JSON.stringify when the same array is observed again.
@@ -100,15 +118,10 @@ export class ConditionEvaluatorController implements ReactiveController {
private _notifiedError?: string;
constructor(
host: ReactiveControllerHost,
options: ConditionEvaluatorOptions
) {
this._host = host;
constructor(options: ConditionEvaluatorOptions) {
this._onResult = options.onResult;
this._resubscribeDelay =
options.resubscribeDelay ?? DEFAULT_RESUBSCRIBE_DELAY;
host.addController(this);
}
public get result(): ConditionEvaluation {
@@ -120,25 +133,38 @@ export class ConditionEvaluatorController implements ReactiveController {
}
/**
* Update inputs. Resubscribes only when the tree (or connection) changes.
* Update the tree. Resubscribes only when its content changes.
*/
public observe(
conditions: VisibilityCondition[] | undefined,
hass: HomeAssistant | undefined,
getContext?: () => ConditionContext
): void {
this._conditions = conditions;
this._hass = hass;
this._getContext = getContext;
this._sync();
}
public hostConnected(): void {
/**
* Update what client conditions read and where server subtrees subscribe.
* Resubscribes only when the connection is replaced.
*/
public setInputs(
conditionHass: ConditionHass | undefined,
connection: Connection | undefined,
localize: LocalizeFunc | undefined
): void {
this._conditionHass = conditionHass;
this._connection = connection;
this._localize = localize;
this._sync();
}
public connect(): void {
this._connected = true;
this._sync();
}
public hostDisconnected(): void {
public disconnect(): void {
this._connected = false;
this._teardown();
// Subscriptions are gone; don't keep showing a stale result.
@@ -176,14 +202,14 @@ export class ConditionEvaluatorController implements ReactiveController {
return;
}
const signature = this._signatureOf(this._conditions);
// Resubscribe when the tree content or hass.connection changed.
// Resubscribe when the tree content or the connection changed.
const targetSignature = this._hasPendingResubscribe
? this._pendingSignature
: this._subscribedSignature;
const connectionReplaced =
this._subscribedConnection !== undefined &&
this._hass !== undefined &&
this._hass.connection !== this._subscribedConnection;
this._connection !== undefined &&
this._connection !== this._subscribedConnection;
if (signature !== targetSignature || connectionReplaced) {
// Drop the old subscriptions immediately so their result can't leak through.
this._teardown();
@@ -217,12 +243,13 @@ export class ConditionEvaluatorController implements ReactiveController {
this._teardown();
const conditions = this._conditions;
const hass = this._hass;
const conditionHass = this._conditionHass;
const connection = this._connection;
this._pendingSignature = undefined;
this._hasPendingResubscribe = false;
if (!conditions || !hass) {
// Don't mark subscribed yet; hass often arrives after connect.
if (!conditions || !conditionHass || !connection) {
// Don't mark subscribed yet; inputs often arrive after connect.
this._setResult("unknown", undefined);
return;
}
@@ -232,7 +259,6 @@ export class ConditionEvaluatorController implements ReactiveController {
this._split = split;
const generation = this._generation;
const connection: Connection = hass.connection;
this._subscribedConnection = connection;
for (const subtree of split.serverSubtrees) {
@@ -267,7 +293,9 @@ export class ConditionEvaluatorController implements ReactiveController {
}
this._serverResults[subtree.id] = undefined;
this._subtreeErrors[subtree.id] =
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
getWsErrorMessage(err) ??
this._localize?.("ui.common.unknown_error") ??
String(err);
this._recompute();
});
this._subscriptions.push(subscription);
@@ -275,7 +303,8 @@ export class ConditionEvaluatorController implements ReactiveController {
observeConditionChanges(
conditions,
() => this._hass ?? hass,
() => (this._conditionHass ?? conditionHass).locale,
() => (this._conditionHass ?? conditionHass).config,
(unsub) => this._listeners.push(unsub),
() => this._recompute()
);
@@ -284,16 +313,20 @@ export class ConditionEvaluatorController implements ReactiveController {
}
private _recompute(): void {
if (!this._split || !this._hass) {
if (!this._split || !this._conditionHass) {
this._setResult("unknown", undefined);
return;
}
const hass = this._hass;
const conditionHass = this._conditionHass;
const context = this._getContext?.() ?? {};
const clientEvaluator: ClientConditionEvaluator = (condition) => {
try {
return checkConditionsMet([condition as Condition], hass, context);
return checkConditionsMet(
[condition as Condition],
conditionHass,
context
);
} catch (_err) {
return false;
}
@@ -326,7 +359,6 @@ export class ConditionEvaluatorController implements ReactiveController {
this._notifiedResult = result;
this._notifiedError = error;
this._onResult(result, error);
this._host.requestUpdate();
}
private _teardown(): void {
@@ -353,3 +385,108 @@ export class ConditionEvaluatorController implements ReactiveController {
this._subscribedConnection = undefined;
}
}
/**
* {@link ConditionEvaluator} for a Lit host. Reads states, user, config,
* locale, registries and the connection from context; the host only passes
* the tree to {@link observe}.
*/
export class ConditionEvaluatorController extends ContextController {
@consumeContext({ context: statesContext, subscribe: true })
private _states?: HassEntities | null;
@consumeContext({ context: configContext, subscribe: true })
private _hassConfig?: HomeAssistantConfig | null;
@consumeContext({ context: internationalizationContext, subscribe: true })
private _i18n?: HomeAssistantInternationalization | null;
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries | null;
@consumeContext({
context: connectionContext,
subscribe: true,
transform: (value) => value?.connection,
})
private _connection?: Connection;
private readonly _evaluator: ConditionEvaluator;
// Hosts without conditions skip the per-state-message input rebuild.
private _observing = false;
private _inputsStale = false;
constructor(
host: ReactiveControllerHost & HTMLElement,
options: ConditionEvaluatorOptions
) {
super(host);
this._evaluator = new ConditionEvaluator({
resubscribeDelay: options.resubscribeDelay,
onResult: (result, error) => {
options.onResult(result, error);
host.requestUpdate();
},
});
}
public get result(): ConditionEvaluation {
return this._evaluator.result;
}
public get error(): string | undefined {
return this._evaluator.error;
}
public observe(
conditions: VisibilityCondition[] | undefined,
getContext?: () => ConditionContext
): void {
this._observing = conditions !== undefined;
if (this._observing && this._inputsStale) {
this._pushInputs();
}
this._evaluator.observe(conditions, getContext);
}
public hostConnected(): void {
this._evaluator.connect();
}
public hostDisconnected(): void {
this._evaluator.disconnect();
}
protected contextUpdated(): void {
if (!this._observing) {
this._inputsStale = true;
return;
}
this._pushInputs();
}
private _pushInputs(): void {
this._inputsStale = false;
const hassConfig = this._hassConfig;
const locale = this._i18n?.locale;
// States and registries load after connect; missing ones read as empty,
// so conditions that don't need them are not held back.
this._evaluator.setInputs(
hassConfig && locale
? {
states: this._states ?? {},
user: hassConfig.user,
locale,
config: hassConfig.config,
entities: this._registries?.entities ?? {},
devices: this._registries?.devices ?? {},
areas: this._registries?.areas ?? {},
}
: undefined,
this._connection,
this._i18n?.localize
);
}
}
+2 -2
View File
@@ -5,7 +5,7 @@ import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_regist
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import type { HomeAssistant, ValuePart } from "../../types";
import { formatDate } from "../datetime/format_date";
import { formatDateNumeric } from "../datetime/format_date";
import { formatDateTime } from "../datetime/format_date_time";
import { DURATION_UNITS, formatDuration } from "../datetime/format_duration";
import { formatTime } from "../datetime/format_time";
@@ -226,7 +226,7 @@ const computeStateToPartsFromEntityAttributes = (
return [
{
type: "value",
value: formatDate(
value: formatDateNumeric(
parseISO(`${state}T00:00:00Z`),
{ ...locale, time_zone: TimeZone.server },
{ ...config, time_zone: "UTC" }
+10 -6
View File
@@ -1059,12 +1059,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this.chart!.dispatchAction({ type: "downplay" });
});
this.chart.on("graphroam", () => {
this._isGraphRoamed = this._getGraphRoams().some(
({ zoom, x, y }) =>
Math.abs(zoom - 1) > 1e-6 || Math.abs(x) > 0.5 || Math.abs(y) > 0.5
);
});
this.chart.on("graphroam", this._updateGraphRoamed);
if (!this.options?.dataZoom) {
this.chart.getZr().on("dblclick", this._handleClickZoom);
@@ -2383,9 +2378,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
private _handleChartRenderFinished = () => {
// Also after a center or zoom in the options, which ends without graphroam
this._updateGraphRoamed();
this._resizeChartIfNeeded();
};
private _updateGraphRoamed = () => {
this._isGraphRoamed = this._getGraphRoams().some(
({ zoom, x, y }) =>
Math.abs(zoom - 1) > 1e-6 || Math.abs(x) > 0.5 || Math.abs(y) > 0.5
);
};
private _resizeChartIfNeeded() {
if (!this.chart || !this._shouldResizeChart) {
return;
+111 -61
View File
@@ -20,6 +20,13 @@ import type { HaECOption } from "../../resources/echarts/echarts";
import "./ha-chart-base";
import type { HaChartBase } from "./ha-chart-base";
import { deepEqual } from "../../common/util/deep-equal";
import type { FollowRoam, ViewNeighbor } from "./network-graph-view";
import { labelReach, selectedNodeRoam } from "./network-graph-view";
import {
graphSeries,
graphView,
NetworkLayoutController,
} from "./network-layout-controller";
export interface NetworkNode {
id: string;
@@ -90,11 +97,6 @@ const LEGEND_SELECT_EVENTS = [
"legendinverseselect",
];
const SELECTED_NODE_MAX_ZOOM = 2;
// Keeps neighbors clear of the search field, buttons and legend
const SELECTED_NODE_FIT_MARGIN = 72;
const FOLLOW_ROAM = "follow-selected-node";
type Displayable = ReturnType<
@@ -149,6 +151,13 @@ export class HaNetworkGraph extends LitElement {
*/
@property({ attribute: false }) public hiddenCategories?: string[];
/**
* Lay the nodes out as a tree that grows from left to right: each node at
* the x and y of the data, without the force layout or positions saved from
* it. The selected node is kept left with room for its label and children.
*/
@property({ attribute: false }) public treeLayout = false;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _highlightedNodes?: Set<string>;
@@ -187,6 +196,21 @@ export class HaNetworkGraph extends LitElement {
@query("ha-chart-base") private _baseChart?: HaChartBase;
private _layout = new NetworkLayoutController(this, {
chart: () => this._baseChart,
treeLayout: () => this.treeLayout,
reducedMotion: () => this._reducedMotion,
selectedNode: () => this.selectedNode,
selectedNodeRoam: (chart) => this._selectedNodeRoam(chart),
saveNodePositions: () => this._saveNodePositions(),
// A drag or zoom while the view moves still stops following
moveStarted: () => {
this._followSelectedNode = !!this.selectedNode;
this._updateFollowing();
},
moveEnded: () => this._centerOnSelectedNode(),
});
constructor() {
super();
if (!GraphChart) {
@@ -224,13 +248,16 @@ export class HaNetworkGraph extends LitElement {
return html`<ha-chart-base
.data=${this._getSeries(
this.data,
this._physicsEnabled ?? false,
!this.treeLayout &&
!this._layout.settling &&
(this._physicsEnabled ?? false),
this._reducedMotion,
this._showLabels,
isMobile,
hasHighlightedNodes,
this.selectedNode,
this.hoverFocus,
this.treeLayout,
this._nodePositions,
this._pinnedNodes,
this._fewVisibleNodes()
@@ -246,14 +273,20 @@ export class HaNetworkGraph extends LitElement {
>
<slot name="search" slot="search"></slot>
<slot name="button" slot="button"></slot>
<ha-icon-button
slot="button"
class=${this._physicsEnabled ? "active" : "inactive"}
.ariaPressed=${this._physicsEnabled ? "true" : "false"}
.path=${mdiGoogleCirclesGroup}
@click=${this._togglePhysics}
label=${this._localize("ui.panel.config.common.graph.toggle_physics")}
></ha-icon-button>
${
this.treeLayout
? nothing
: html`<ha-icon-button
slot="button"
class=${this._physicsEnabled ? "active" : "inactive"}
.ariaPressed=${this._physicsEnabled ? "true" : "false"}
.path=${mdiGoogleCirclesGroup}
@click=${this._togglePhysics}
label=${this._localize(
"ui.panel.config.common.graph.toggle_physics"
)}
></ha-icon-button>`
}
<ha-icon-button
slot="button"
class=${this._showLabels ? "active" : "inactive"}
@@ -320,8 +353,7 @@ export class HaNetworkGraph extends LitElement {
this._updateMouseoverHandler();
}
if (changedProperties.has("selectedNode")) {
this._followSelectedNode = !!this.selectedNode;
this._updateFollowing();
this._layout.moveToSelectedNode();
}
}
@@ -356,6 +388,7 @@ export class HaNetworkGraph extends LitElement {
hasHighlightedNodes?: boolean,
selectedNode?: string,
hoverFocus = true,
treeLayout = false,
nodePositions: Record<string, { x: number; y: number }> = {},
pinnedNodes: string[] = [],
fewVisibleNodes = true
@@ -363,6 +396,10 @@ export class HaNetworkGraph extends LitElement {
id: "network",
type: "graph",
layout: physicsEnabled ? "force" : "none",
// Nodes of a tree keep their size, like the labels, so a zoom spreads
// the rows instead of growing the nodes into each other. ECharts reads
// 0 as 1.
nodeScaleRatio: treeLayout ? Number.EPSILON : 0.6,
draggable: true,
roam: true,
roamTrigger: "global",
@@ -407,7 +444,7 @@ export class HaNetworkGraph extends LitElement {
data: this._getSeriesData(
data.nodes,
data.links,
nodePositions,
treeLayout ? {} : nodePositions,
pinnedNodes,
selectedNode
),
@@ -636,6 +673,9 @@ export class HaNetworkGraph extends LitElement {
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
chart?.on("rendered", this._handleRendered);
if (chart) {
this._layout.chartSetup(chart);
}
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
@@ -657,8 +697,11 @@ export class HaNetworkGraph extends LitElement {
const fewVisibleNodes = this._fewVisibleNodes();
this._setHiddenCategories(selected);
if (this._fewVisibleNodes() !== fewVisibleNodes) {
// The new series option lays out again from where the nodes are now
this._saveNodePositions();
// The new series option lays out again from where the nodes are now.
// The positions of a tree would overwrite those of the force layout.
if (!this.treeLayout) {
this._saveNodePositions();
}
this.requestUpdate();
}
fireEvent(this, "network-legend-changed", {
@@ -799,8 +842,9 @@ export class HaNetworkGraph extends LitElement {
this._dragMoved = false;
this._dragTarget?.off("drag", this._handleNodeDrag);
this._dragTarget = undefined;
// The positions of a tree come from the data, not from the force layout.
// A click also ends a drag, which releases a pinned node in ECharts
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
if (this.treeLayout || !id || (!moved && !this._pinnedNodes.includes(id))) {
return;
}
this._pinNodeInChart(id);
@@ -916,58 +960,68 @@ export class HaNetworkGraph extends LitElement {
private _centerOnSelectedNode = () => {
const chart = this._followedChart;
if (!chart) {
if (!chart || this._layout.moving) {
return;
}
const roam = this._selectedNodeRoam(chart);
if (roam) {
chart.dispatchAction({
type: "graphRoam",
from: FOLLOW_ROAM,
seriesId: "network",
...roam,
});
}
};
private _selectedNodeRoam(chart: EChartsType): FollowRoam | undefined {
const series = this._getGraphSeries(chart);
const node = series?.getGraph().getNodeById(this.selectedNode);
const position: number[] | undefined = node?.getLayout();
if (!position) {
return;
return undefined;
}
const toPixel = (point: number[]) =>
chart.convertToPixel({ seriesId: "network" }, point);
const [x, y] = toPixel(position);
const zoom = series.coordinateSystem.getRoamTransform()[0];
const centerX = chart.getWidth() / 2;
const centerY = chart.getHeight() / 2;
// Zoom so the neighbors stay in view
const fitX = Math.max(centerX - SELECTED_NODE_FIT_MARGIN, centerX / 2);
const fitY = Math.max(centerY - SELECTED_NODE_FIT_MARGIN, centerY / 2);
let targetZoom = SELECTED_NODE_MAX_ZOOM;
const neighbors: ViewNeighbor[] = [];
for (const edge of node.edges) {
const neighbor: number[] | undefined = (
edge.node1 === node ? edge.node2 : edge.node1
).getLayout();
const neighborNode = edge.node1 === node ? edge.node2 : edge.node1;
const neighbor: number[] | undefined = neighborNode.getLayout();
if (neighbor) {
const [neighborX, neighborY] = toPixel(neighbor);
targetZoom = Math.min(
targetZoom,
(zoom * fitX) / Math.abs(neighborX - x),
(zoom * fitY) / Math.abs(neighborY - y)
);
const size = neighborNode.getVisual("symbolSize");
neighbors.push({
x: neighborX,
y: neighborY,
size: Array.isArray(size) ? size[1] : (size ?? 0),
});
}
}
const zoomChanged = Math.abs(zoom - targetZoom) >= 1e-3;
if (
!zoomChanged &&
Math.abs(centerX - x) < 0.5 &&
Math.abs(centerY - y) < 0.5
) {
return;
return selectedNodeRoam(
graphView(chart, series, this.treeLayout),
{ x, y },
neighbors,
this.treeLayout ? this._labelReach(series, node) : undefined
);
}
// How far the shown label of a node reaches to the right of its center in
// pixels, which does not change with a zoom
private _labelReach(series: any, node: any): number | undefined {
const symbolPath = series
.getData()
.getItemGraphicEl(node.dataIndex)
?.getSymbolPath?.();
const label = symbolPath?.getTextContent?.();
const center = symbolPath?.getComputedTransform?.();
if (!label || label.ignore || !center) {
return undefined;
}
chart.dispatchAction({
type: "graphRoam",
from: FOLLOW_ROAM,
seriesId: "network",
dx: centerX - x,
dy: centerY - y,
// Any zoom, even 1, rescales every node and edge
zoom: zoomChanged ? targetZoom / zoom : undefined,
originX: centerX,
originY: centerY,
});
};
const rect = label.getBoundingRect().clone();
rect.applyTransform(label.getComputedTransform());
return labelReach(rect, center[4]);
}
public disconnectedCallback(): void {
super.disconnectedCallback();
@@ -1006,11 +1060,7 @@ export class HaNetworkGraph extends LitElement {
}
private _getGraphSeries(chart = this._baseChart?.chart): any {
if (!chart || chart.isDisposed()) {
return undefined;
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
return graphSeries(chart);
}
static styles = css`
+307
View File
@@ -0,0 +1,307 @@
/**
* A pan and zoom of the network graph view, as in a `graphRoam` action
*/
export interface FollowRoam {
dx: number;
dy: number;
zoom?: number;
originX: number;
originY: number;
}
/**
* The chart that a roam is computed for
*/
export interface GraphView {
width: number;
height: number;
/** The zoom of the roam so far, 1 before any zoom */
zoom: number;
/** A tree that grows from left to right */
treeLayout: boolean;
}
export interface ViewPoint {
x: number;
y: number;
}
export interface ViewNeighbor extends ViewPoint {
/** Size of the symbol in pixels */
size: number;
}
export interface ViewBounds {
left: number;
top: number;
right: number;
bottom: number;
}
/**
* From layout to pixels, the same scale for x and y
*/
export interface ViewTransform {
scale: number;
x: number;
y: number;
}
/**
* The transform of a view and the size of the chart it was in
*/
export interface SizedViewTransform extends ViewTransform {
width: number;
height: number;
}
export const SELECTED_NODE_MAX_ZOOM = 2;
// Keeps neighbors clear of the search field, buttons and legend
export const SELECTED_NODE_FIT_MARGIN = 72;
// In a tree layout, the place of the selected node as a part of the width,
// and the room for the labels of the neighbors to its right
export const TREE_SELECTED_NODE_X = 0.25;
export const TREE_LABEL_ROOM = 240;
// The place of a selected node in a tree layout that moved left to make room
// for its label
export const TREE_MIN_SELECTED_NODE_X = 32;
// The room between the children of a selected node in a tree layout and the
// least distance for their labels, also when they then no longer fit, e.g.
// many children on a phone
export const TREE_CHILD_SPACING = 8;
export const TREE_MIN_CHILD_GAP = 24;
/**
* The point that a roam moves to the given point
*/
export const roamSource = (
roam: FollowRoam,
point: ViewPoint
): [number, number] => {
const zoom = roam.zoom ?? 1;
return [
(point.x - roam.originX) / zoom + roam.originX - roam.dx,
(point.y - roam.originY) / zoom + roam.originY - roam.dy,
];
};
// Undefined when the view would not move
const viewRoam = (
dx: number,
dy: number,
zoom: number | undefined,
originX: number,
originY: number
): FollowRoam | undefined =>
zoom === undefined && Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5
? undefined
: { dx, dy, zoom, originX, originY };
/**
* How far a label reaches to the right of the center of its node, in pixels.
*/
export const labelReach = (
label: { x: number; width: number },
nodeCenterX: number
) => label.x + label.width - nodeCenterX;
/**
* The bounds of the given positions, or undefined without any
*/
export const layoutBounds = (
positions: Iterable<readonly number[] | undefined>
): ViewBounds | undefined => {
const bounds = {
left: Infinity,
top: Infinity,
right: -Infinity,
bottom: -Infinity,
};
for (const position of positions) {
if (position) {
bounds.left = Math.min(bounds.left, position[0]);
bounds.right = Math.max(bounds.right, position[0]);
bounds.top = Math.min(bounds.top, position[1]);
bounds.bottom = Math.max(bounds.bottom, position[1]);
}
}
return bounds.left > bounds.right ? undefined : bounds;
};
/**
* The roam that puts the selected node in the center, zoomed so its neighbors
* stay in view, or undefined when it is there already. A tree layout keeps the
* node left instead, with room for its label and its children to the right.
*
* @param node the selected node in pixels
* @param neighbors the nodes linked to it in pixels
* @param nodeLabelReach how far the label of the node reaches to the right of
* its center, see `labelReach`
*/
export const selectedNodeRoam = (
view: GraphView,
node: ViewPoint,
neighbors: ViewNeighbor[],
nodeLabelReach?: number
): FollowRoam | undefined => {
const { width, zoom, treeLayout } = view;
const { x, y } = node;
const children = treeLayout
? neighbors.filter((neighbor) => neighbor.x > x)
: [];
// In a tree layout the label of the node gets room before its children,
// as its nodes keep their size
const labelRoom =
children.length && nodeLabelReach
? nodeLabelReach +
TREE_CHILD_SPACING +
Math.max(...children.map((child) => child.size)) / 2
: 0;
// Its parents need not fit, so the node moves left to make room for its
// label
const anchorX = treeLayout
? Math.max(
TREE_MIN_SELECTED_NODE_X,
Math.min(
width * TREE_SELECTED_NODE_X,
width - TREE_LABEL_ROOM - labelRoom
)
)
: width / 2;
const centerY = view.height / 2;
// Zoom so the neighbors stay in view
const fitLeft = Math.max(anchorX - SELECTED_NODE_FIT_MARGIN, anchorX / 2);
const rightRoom = width - anchorX;
const fitRight = Math.max(
rightRoom - (treeLayout ? TREE_LABEL_ROOM : SELECTED_NODE_FIT_MARGIN),
rightRoom / 2
);
const fitY = Math.max(centerY - SELECTED_NODE_FIT_MARGIN, centerY / 2);
let fitZoom = Infinity;
// In a tree layout only the children have to fit
for (const neighbor of treeLayout ? children : neighbors) {
const fitX = neighbor.x > x ? fitRight : fitLeft;
fitZoom = Math.min(
fitZoom,
(zoom * fitX) / Math.abs(neighbor.x - x),
(zoom * fitY) / Math.abs(neighbor.y - y)
);
}
let targetZoom = Math.min(SELECTED_NODE_MAX_ZOOM, fitZoom);
// Many children rather go out of view than over the label or too close to
// read. Their nodes keep their size, so only the gaps grow with the zoom.
if (labelRoom) {
const childDistance = Math.min(...children.map((child) => child.x - x));
targetZoom = Math.max(targetZoom, (zoom * labelRoom) / childDistance);
}
const sortedChildren = [...children].sort((a, b) => a.y - b.y);
for (let i = 1; i < sortedChildren.length; i++) {
const child = sortedChildren[i];
const previous = sortedChildren[i - 1];
const gap = child.y - previous.y;
const needed = Math.max(
TREE_MIN_CHILD_GAP,
(child.size + previous.size) / 2 + TREE_CHILD_SPACING
);
// Hidden nodes fold onto their parent, at the same position
if (gap > 0) {
targetZoom = Math.max(targetZoom, (zoom * needed) / gap);
}
}
const zoomChanged = Math.abs(zoom - targetZoom) >= 1e-3;
return viewRoam(
anchorX - x,
centerY - y,
// Any zoom, even 1, rescales every node and edge
zoomChanged ? targetZoom / zoom : undefined,
anchorX,
centerY
);
};
/**
* The roam that fits the given bounds in pixels in the view, clear of the
* controls, or undefined when they fit already. A tree layout grows to the
* right, so its labels get room there.
*/
export const fitRoam = (
view: GraphView,
bounds: ViewBounds
): FollowRoam | undefined => {
const { width, height } = view;
const rightRoom = view.treeLayout
? TREE_LABEL_ROOM
: SELECTED_NODE_FIT_MARGIN;
const fitWidth = Math.max(
width - SELECTED_NODE_FIT_MARGIN - rightRoom,
width / 2
);
const fitHeight = Math.max(height - 2 * SELECTED_NODE_FIT_MARGIN, height / 2);
const zoom = Math.min(
fitWidth / (bounds.right - bounds.left),
fitHeight / (bounds.bottom - bounds.top),
SELECTED_NODE_MAX_ZOOM / view.zoom
);
// A narrow view shrinks the margins along with the fitted width
const leftMargin =
((width - fitWidth) * SELECTED_NODE_FIT_MARGIN) /
(SELECTED_NODE_FIT_MARGIN + rightRoom);
const centerX = leftMargin + fitWidth / 2;
const centerY = height / 2;
return viewRoam(
centerX - (bounds.left + bounds.right) / 2,
centerY - (bounds.top + bounds.bottom) / 2,
Math.abs(zoom - 1) >= 1e-3 ? zoom : undefined,
centerX,
centerY
);
};
/**
* The roam to the view of a layout that was switched to: the whole tree
* layout, or the force layout as it first showed, as its nodes keep their
* positions. When nodes shown since, e.g. of another legend category, do not
* fit in that, or the chart has another size, the roam fits them.
*
* @param bounds the bounds of the nodes in the layout
* @param current the transform of the view now
* @param initial the transform of the view when the force layout first showed
*/
export const layoutRoam = (
view: GraphView,
bounds: ViewBounds,
current: ViewTransform,
initial?: SizedViewTransform
): FollowRoam | undefined => {
const margin = SELECTED_NODE_FIT_MARGIN;
if (
view.treeLayout ||
!initial ||
// Its pixels no longer match, as ECharts scales the graph to the chart
initial.width !== view.width ||
initial.height !== view.height ||
initial.scale * bounds.left + initial.x < margin ||
initial.scale * bounds.top + initial.y < margin ||
initial.scale * bounds.right + initial.x > view.width - margin ||
initial.scale * bounds.bottom + initial.y > view.height - margin
) {
return fitRoam(view, {
left: current.scale * bounds.left + current.x,
top: current.scale * bounds.top + current.y,
right: current.scale * bounds.right + current.x,
bottom: current.scale * bounds.bottom + current.y,
});
}
const zoom = initial.scale / current.scale;
return viewRoam(
initial.x - current.x,
initial.y - current.y,
Math.abs(zoom - 1) >= 1e-3 ? zoom : undefined,
initial.x,
initial.y
);
};
@@ -0,0 +1,281 @@
import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { EChartsType } from "echarts/core";
import type { HaChartBase } from "./ha-chart-base";
import type {
FollowRoam,
GraphView,
SizedViewTransform,
ViewTransform,
} from "./network-graph-view";
import { layoutBounds, layoutRoam, roamSource } from "./network-graph-view";
// The nodes of another layout move for at most this many ms
export const LAYOUT_ANIMATION_TIMEOUT = 1000;
export const graphSeries = (chart: EChartsType | undefined): any => {
if (!chart || chart.isDisposed()) {
return undefined;
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
};
export const graphView = (
chart: EChartsType,
series: any,
treeLayout: boolean
): GraphView => ({
width: chart.getWidth(),
height: chart.getHeight(),
zoom: series.coordinateSystem.getRoamTransform()[0],
treeLayout,
});
// From layout to pixels
const viewTransform = (chart: EChartsType): ViewTransform => {
const [x, y] = chart.convertToPixel({ seriesId: "network" }, [0, 0]);
const [x1] = chart.convertToPixel({ seriesId: "network" }, [1, 0]);
return { scale: x1 - x, x, y };
};
export interface NetworkLayoutControllerConfig {
chart: () => HaChartBase | undefined;
treeLayout: () => boolean;
reducedMotion: () => boolean;
selectedNode: () => string | undefined;
/** The roam to the selected node, undefined when it is in view */
selectedNodeRoam: (chart: EChartsType) => FollowRoam | undefined;
/** Before the positions of the force layout make way for the tree */
saveNodePositions: () => void;
/** When the view starts to move to the selected node or another layout */
moveStarted: () => void;
/** When the view is free again */
moveEnded: () => void;
}
/**
* Moves the view of a network graph to a selected node, and along with the
* nodes on a switch between the tree and the force layout. The view moves in
* the same animation as the nodes, as ECharts animates the transform of the
* group they are in.
*/
export class NetworkLayoutController implements ReactiveController {
/**
* Without the force layout until the nodes moved back to their positions in
* it, as the first step of the force layout stops their animation
*/
public settling = false;
/**
* While the view moves. A roam in the meantime would draw the edges at the
* end of their animation at once.
*/
public moving = false;
private _host: ReactiveControllerHost;
private _config: NetworkLayoutControllerConfig;
private _treeLayout?: boolean;
private _switched = false;
// Each move replaces the one before, and waits for the nodes of a layout
// switch that it replaces
private _move = 0;
private _layoutSwitch = false;
private _stopWaiting?: () => void;
// How the force layout first showed its nodes, which the view goes back to
// after the tree layout
private _initialForceView?: SizedViewTransform;
constructor(
host: ReactiveControllerHost,
config: NetworkLayoutControllerConfig
) {
this._host = host;
this._config = config;
host.addController(this);
}
public hostUpdate(): void {
const treeLayout = this._config.treeLayout();
const previous = this._treeLayout;
this._treeLayout = treeLayout;
if (previous === undefined || previous === treeLayout) {
return;
}
this._switched = true;
if (treeLayout) {
// The force layout comes back from here
this._config.saveNodePositions();
} else if (!this._config.reducedMotion() && this._config.chart()) {
this.settling = true;
}
}
public hostUpdated(): void {
if (this._switched) {
this._switched = false;
this._moveView(true);
}
}
public hostDisconnected(): void {
this._move++;
this._stopWaiting?.();
// The layout no longer settles, so physics would stay off and the view
// would not follow on return
this._layoutSwitch = false;
this.settling = false;
this.moving = false;
}
/**
* Moves the view to the selected node, after the chart drew the change
*/
public moveToSelectedNode() {
this._moveView(false);
}
/**
* Keeps the first view of the force layout. Call when the chart is set up.
*/
public chartSetup(chart: EChartsType) {
chart.on("finished", this._captureInitialForceView);
}
private _moveView(layoutSwitch: boolean) {
const move = ++this._move;
this._stopWaiting?.();
this._layoutSwitch ||= layoutSwitch;
this.moving = true;
this._config.moveStarted();
const done = () => {
this._layoutSwitch = false;
this.moving = false;
if (this.settling) {
this.settling = false;
this._host.requestUpdate();
}
this._config.moveEnded();
};
const baseChart = this._config.chart();
if (!baseChart) {
// Nothing is drawn, so nothing moves
done();
return;
}
baseChart.updateComplete.then(() => {
if (move !== this._move) {
return;
}
const chart = baseChart.chart;
const moved = chart && this._setRoam(chart, this._layoutSwitch);
// The nodes of another layout move also when the view stays
if (moved || this._layoutSwitch) {
this._afterAnimation(chart, done);
} else {
done();
}
});
}
// A new center and zoom of the series moves the view in the same animation
// as the nodes. Returns whether the view moves.
private _setRoam(chart: EChartsType, layoutSwitch: boolean): boolean {
const series = graphSeries(chart);
const view = series?.coordinateSystem;
if (!view) {
return false;
}
const roam = this._config.selectedNode()
? this._config.selectedNodeRoam(chart)
: layoutSwitch
? this._layoutRoam(chart, series)
: undefined;
if (!roam) {
return false;
}
const viewRect = view.getViewRect();
const center = view.pointToData(
roamSource(roam, {
x: viewRect.x + viewRect.width / 2,
y: viewRect.y + viewRect.height / 2,
})
);
// The view keeps its zoom to itself, ECharts syncs it back to the option
const currentZoom: number = series.get("zoom") ?? 1;
chart.setOption({
series: [{ id: "network", center, zoom: currentZoom * (roam.zoom ?? 1) }],
});
return true;
}
private _layoutRoam(chart: EChartsType, series: any) {
const positions: (number[] | undefined)[] = [];
series.getGraph().eachNode((node: any) => {
positions.push(node.getLayout());
});
const bounds = layoutBounds(positions);
return bounds
? layoutRoam(
graphView(chart, series, this._config.treeLayout()),
bounds,
viewTransform(chart),
this._initialForceView
)
: undefined;
}
private _afterAnimation(
chart: EChartsType | undefined,
callback: () => void
) {
// Also without animation while the force layout moves the nodes, as
// ECharts then shows each step at once
if (!chart || !graphSeries(chart)?.isAnimationEnabled()) {
callback();
return;
}
const done = () => {
this._stopWaiting?.();
callback();
};
// Not every change of the layout ends in a finished event
const timeout = window.setTimeout(done, LAYOUT_ANIMATION_TIMEOUT);
chart.on("finished", done);
this._stopWaiting = () => {
clearTimeout(timeout);
chart.off("finished", done);
this._stopWaiting = undefined;
};
}
private _captureInitialForceView = () => {
const chart = this._config.chart()?.chart;
// Not while the view moves after a switch from the tree layout
if (
this._initialForceView ||
this._config.treeLayout() ||
this.settling ||
this.moving ||
!chart ||
!graphSeries(chart)?.forceLayout
) {
return;
}
this._initialForceView = {
...viewTransform(chart),
width: chart.getWidth(),
height: chart.getHeight(),
};
chart.off("finished", this._captureInitialForceView);
};
}
+92 -82
View File
@@ -18,6 +18,87 @@ import "../ha-generic-picker";
import type { PickerComboBoxItem } from "../ha-picker-combo-box";
import type { PickerValueRenderer } from "../ha-picker-field";
export const computeEntityStateItems = (
states: HassEntities | null | undefined,
formatters: HomeAssistantFormatters,
language: string,
entityId: string | string[] | undefined,
attribute: string | undefined,
hideStates: string[] | undefined,
extraOptions: PickerComboBoxItem[] | undefined
): PickerComboBoxItem[] => {
const entityIds = entityId ? ensureArray(entityId) : [];
const entitiesOptions = entityIds.map<PickerComboBoxItem[]>(
(entityIdItem) => {
const stateObj =
states?.[entityIdItem] ||
({ entity_id: entityIdItem, attributes: {} } as HassEntity);
const options = getStates(
states ?? {},
language,
stateObj,
attribute
).filter((s) => !hideStates?.includes(s));
return options
.map((s) => {
const primary = attribute
? formatters.formatEntityAttributeValue(stateObj, attribute, s)
: formatters.formatEntityState(stateObj, s);
return {
id: s,
primary,
sorting_label: primary,
};
})
.filter((option) => option.id && option.primary);
}
);
const options: PickerComboBoxItem[] = [];
const optionsSet = new Set<string>();
for (const entityOptions of entitiesOptions) {
for (const option of entityOptions) {
if (!optionsSet.has(option.id)) {
optionsSet.add(option.id);
options.push(option);
}
}
}
if (extraOptions) {
// Filter out any extraOptions with empty primary or id fields
const validExtraOptions = extraOptions.filter(
(option) => option.id && option.primary
);
options.unshift(...validExtraOptions);
}
return options;
};
// When an attribute is configured, default to the attribute's friendly
// name (e.g. "Source") instead of the generic "State". Requires a concrete
// entity to resolve the translated name; otherwise fall back to "State".
export const computeDefaultStateLabel = (
i18n: ContextType<typeof internationalizationContext>,
formatters: HomeAssistantFormatters,
stateObjs: Record<string, HassEntity> | undefined,
entityId: string | string[] | undefined,
attribute: string | undefined
): string => {
if (attribute && entityId) {
const firstEntityId = ensureArray(entityId)[0];
const stateObj = firstEntityId ? stateObjs?.[firstEntityId] : undefined;
if (stateObj) {
return formatters.formatEntityAttributeName(stateObj, attribute);
}
}
return i18n.localize("ui.components.entity.entity-state-picker.state");
};
@customElement("ha-entity-state-picker")
export class HaEntityStatePicker extends LitElement {
@property({ attribute: false }) public entityId?: string | string[];
@@ -60,68 +141,7 @@ export class HaEntityStatePicker extends LitElement {
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
private _getItems = memoizeOne(
(
states: HassEntities | null | undefined,
formatters: HomeAssistantFormatters,
language: string,
entityId: string | string[] | undefined,
attribute: string | undefined,
hideStates: string[] | undefined,
extraOptions: PickerComboBoxItem[] | undefined
): PickerComboBoxItem[] => {
const entityIds = entityId ? ensureArray(entityId) : [];
const entitiesOptions = entityIds.map<PickerComboBoxItem[]>(
(entityIdItem) => {
const stateObj =
states?.[entityIdItem] ||
({ entity_id: entityIdItem, attributes: {} } as HassEntity);
const options = getStates(
states ?? {},
language,
stateObj,
attribute
).filter((s) => !hideStates?.includes(s));
return options
.map((s) => {
const primary = attribute
? formatters.formatEntityAttributeValue(stateObj, attribute, s)
: formatters.formatEntityState(stateObj, s);
return {
id: s,
primary,
sorting_label: primary,
};
})
.filter((option) => option.id && option.primary);
}
);
const options: PickerComboBoxItem[] = [];
const optionsSet = new Set<string>();
for (const entityOptions of entitiesOptions) {
for (const option of entityOptions) {
if (!optionsSet.has(option.id)) {
optionsSet.add(option.id);
options.push(option);
}
}
}
if (extraOptions) {
// Filter out any extraOptions with empty primary or id fields
const validExtraOptions = extraOptions.filter(
(option) => option.id && option.primary
);
options.unshift(...validExtraOptions);
}
return options;
}
);
private _getItems = memoizeOne(computeEntityStateItems);
private _getFilteredItems = (
_searchString?: string,
@@ -143,25 +163,6 @@ export class HaEntityStatePicker extends LitElement {
return html`<span slot="headline">${item?.primary ?? value}</span>`;
};
private _computeDefaultLabel(): string {
// When an attribute is configured, default to the attribute's friendly
// name (e.g. "Source") instead of the generic "State". Requires a concrete
// entity to resolve the translated name; otherwise fall back to "State".
if (this.attribute && this.entityId) {
const entityId = ensureArray(this.entityId)[0];
const stateObj = entityId ? this._stateObjs?.[entityId] : undefined;
if (stateObj) {
return this._formatters.formatEntityAttributeName(
stateObj,
this.attribute
);
}
}
return this._i18n.localize(
"ui.components.entity.entity-state-picker.state"
);
}
protected render() {
const noEntity = !ensureArray(this.entityId)?.length;
@@ -171,7 +172,16 @@ export class HaEntityStatePicker extends LitElement {
.disabled=${this.disabled || noEntity}
.autofocus=${this.autofocus}
.required=${this.required}
.label=${this.label ?? this._computeDefaultLabel()}
.label=${
this.label ??
computeDefaultStateLabel(
this._i18n,
this._formatters,
this._stateObjs,
this.entityId,
this.attribute
)
}
.helper=${this.helper}
.value=${this.value}
.getItems=${this._getFilteredItems}
@@ -1,16 +1,33 @@
import type { ContextType } from "@lit/context";
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed";
import { repeat } from "lit/directives/repeat";
import { fireEvent } from "../../common/dom/fire_event";
import { ANY_STATE_VALUE } from "./const";
import memoizeOne from "memoize-one";
import { ensureArray } from "../../common/array/ensure-array";
import "./ha-entity-state-picker";
import { consume } from "../../common/decorators/consume";
import { consumeEntityStates } from "../../common/decorators/consume-context-entry";
import { fireEvent } from "../../common/dom/fire_event";
import {
formattersContext,
internationalizationContext,
statesContext,
} from "../../data/context";
import type { SelectSelector } from "../../data/selector";
import type { HomeAssistantFormatters } from "../../types";
import type { PickerComboBoxItem } from "../ha-picker-combo-box";
import "../ha-selector/ha-selector-select";
import { ANY_STATE_VALUE } from "./const";
import {
computeDefaultStateLabel,
computeEntityStateItems,
} from "./ha-entity-state-picker";
@customElement("ha-entity-states-picker")
export class HaEntityStatesPicker extends LitElement {
@property({ attribute: false }) public entityId?: string;
@property({ attribute: false }) public entityId?: string | string[];
@property() public attribute?: string;
@@ -32,6 +49,61 @@ export class HaEntityStatesPicker extends LitElement {
@property({ attribute: false })
public hideStates?: string[];
@property({ type: Boolean }) public reorder = false;
@state()
@consumeEntityStates({ entityIdPath: ["entityId"] })
private _stateObjs?: Record<string, HassEntity>;
@consume({ context: statesContext, subscribe: true })
private _states?: ContextType<typeof statesContext>;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
private _chipsSelector = memoizeOne(
(
states: HassEntities | null | undefined,
formatters: HomeAssistantFormatters,
language: string,
entityId: string | string[] | undefined,
attribute: string | undefined,
hideStates: string[] | undefined,
extraOptions: PickerComboBoxItem[] | undefined,
customValue: boolean,
lockedValue: string[] | undefined
): SelectSelector => {
const items = computeEntityStateItems(
states,
formatters,
language,
entityId,
attribute,
hideStates,
extraOptions
);
const options = items
.filter((item) => !lockedValue || lockedValue.includes(item.id))
.map((item) => ({
value: item.id,
label: item.primary,
}));
return {
select: {
multiple: true,
reorder: true,
custom_value: customValue && !lockedValue,
options,
},
};
}
);
private _keys: string[] = [];
private _getKey(index: number) {
@@ -48,7 +120,50 @@ export class HaEntityStatesPicker extends LitElement {
}
}
private _renderChips() {
const value = this.value ?? [];
const anyStateSelected = value.includes(ANY_STATE_VALUE);
const noEntity = !ensureArray(this.entityId)?.length;
const selector = this._chipsSelector(
this._states,
this._formatters,
this._i18n.locale.language,
this.entityId,
this.attribute,
this.hideStates,
this.extraOptions,
Boolean(this.allowCustomValue),
anyStateSelected ? value : undefined
);
const label =
this.label ??
computeDefaultStateLabel(
this._i18n,
this._formatters,
this._stateObjs,
this.entityId,
this.attribute
);
return html`
<ha-selector-select
.selector=${selector}
.value=${this.value}
.label=${label}
.helper=${this.helper}
.disabled=${this.disabled || noEntity}
.required=${this.required}
></ha-selector-select>
`;
}
protected render() {
if (this.reorder) {
return this._renderChips();
}
const value = this.value || [];
const hide = [...(this.hideStates || []), ...value];
const hideValue = value.includes(ANY_STATE_VALUE);
@@ -56,18 +171,18 @@ export class HaEntityStatesPicker extends LitElement {
return html`
${repeat(
value,
(_state, index) => this._getKey(index),
(state, index) => html`
(_item, index) => this._getKey(index),
(item, index) => html`
<div>
<ha-entity-state-picker
.index=${index}
.entityId=${this.entityId}
.attribute=${this.attribute}
.extraOptions=${this.extraOptions}
.hideStates=${hide.filter((v) => v !== state)}
.hideStates=${hide.filter((v) => v !== item)}
.allowCustomValue=${this.allowCustomValue}
.label=${this.label}
.value=${state}
.value=${item}
.disabled=${this.disabled}
.helper=${
this.disabled && index === value.length - 1
@@ -1,5 +1,6 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators";
import type { LocalizeFunc } from "../../common/translations/localize";
import type { HomeAssistant } from "../../types";
import "../ha-expansion-panel";
import "./ha-form";
@@ -36,6 +37,10 @@ export class HaFormExpandable extends LitElement implements HaFormElement {
key: string
) => string;
@property({ attribute: false }) public localize?: LocalizeFunc;
@property({ attribute: false }) public context?: Record<string, any>;
@query("ha-form", true) private _form?: HaForm;
public reportValidity(): boolean {
@@ -109,6 +114,7 @@ export class HaFormExpandable extends LitElement implements HaFormElement {
.computeLabel=${this._computeLabel}
.computeHelper=${this._computeHelper}
.localizeValue=${this.localizeValue}
.context=${this.context}
></ha-form>
</div>
</ha-expansion-panel>
+3
View File
@@ -35,6 +35,8 @@ export class HaFormGrid extends LitElement implements HaFormElement {
key: string
) => string;
@property({ attribute: false }) public context?: Record<string, any>;
@queryAll("ha-form", true) private _forms?: HaForm[];
static shadowRootOptions = {
@@ -83,6 +85,7 @@ export class HaFormGrid extends LitElement implements HaFormElement {
.computeLabel=${this.computeLabel}
.computeHelper=${this.computeHelper}
.localizeValue=${this.localizeValue}
.context=${this.context}
></ha-form>
`
)}
@@ -54,6 +54,8 @@ export class HaFormOptionalActions extends LitElement implements HaFormElement {
key: string
) => string;
@property({ attribute: false }) public context?: Record<string, any>;
@state() private _displayActions?: string[];
@query("ha-form") private _form?: HaForm;
@@ -130,6 +132,7 @@ export class HaFormOptionalActions extends LitElement implements HaFormElement {
.computeLabel=${this.computeLabel}
.computeHelper=${this.computeHelper}
.localizeValue=${this.localizeValue}
.context=${this.context}
></ha-form>
`
: nothing
+6 -2
View File
@@ -1,8 +1,10 @@
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { dynamicElement } from "../../common/dom/dynamic-element-directive";
import { fireEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { resolveSelectorContext } from "../../data/selector";
import type { HomeAssistant, ValueChangedEvent } from "../../types";
import "../ha-alert";
@@ -112,6 +114,8 @@ export class HaForm extends LitElement implements HaFormElement {
@property({ attribute: false }) public context?: Record<string, any>;
@state() @consumeLocalize() protected _localize?: LocalizeFunc;
protected getFormProperties(): Record<string, any> {
return {};
}
@@ -256,7 +260,7 @@ export class HaForm extends LitElement implements HaFormElement {
helper: this._computeHelper(item),
disabled: this.disabled || item.disabled || false,
hass: this.hass,
localize: this.hass?.localize,
localize: this._localize,
computeLabel: this.computeLabel,
computeHelper: this.computeHelper,
localizeValue: this.localizeValue,
+14
View File
@@ -243,6 +243,20 @@ export class HaPickerField extends PickerMixin(LitElement) {
color: var(--secondary-text-color);
}
.value-with-icon {
display: flex;
align-items: center;
gap: var(--ha-space-2);
}
.value-with-icon ha-svg-icon {
flex: none;
--mdc-icon-size: 20px;
}
.value-with-icon span {
overflow: hidden;
text-overflow: ellipsis;
}
.placeholder {
color: var(--secondary-text-color);
}
+35 -1
View File
@@ -8,7 +8,7 @@ import type { HaDropdownSelectEvent } from "./ha-dropdown";
import "./ha-dropdown-item";
import "./ha-input-helper-text";
import "./ha-picker-field";
import type { HaPickerField } from "./ha-picker-field";
import type { HaPickerField, PickerValueRenderer } from "./ha-picker-field";
import "./ha-svg-icon";
export interface HaSelectOption {
@@ -81,6 +81,38 @@ export class HaSelect extends LitElement {
}
);
private _getValueIconPath = memoizeOne(
(
options: HaSelectOption[] | string[] | number[] | undefined,
value: string | number | undefined
) => {
const valueStr = value !== undefined ? String(value) : undefined;
if (!options || !valueStr) {
return undefined;
}
for (const option of options) {
if (typeof option === "object" && String(option.value) === valueStr) {
return option.iconPath;
}
}
return undefined;
}
);
// Rendered in the shadow root of ha-picker-field, which styles .value-with-icon
private _getValueRenderer = memoizeOne(
(iconPath: string | undefined): PickerValueRenderer | undefined =>
iconPath
? (value) =>
html`<span slot="headline" class="value-with-icon"
><ha-svg-icon .path=${iconPath}></ha-svg-icon
><span>${value}</span></span
>`
: undefined
);
protected override render() {
if (this.disabled) {
return html`${this._renderField()}${this._renderHelper()}`;
@@ -138,6 +170,7 @@ export class HaSelect extends LitElement {
private _renderField() {
const valueLabel = this._getValueLabel(this.options, this.value);
const valueIconPath = this._getValueIconPath(this.options, this.value);
return html`
<ha-picker-field
@@ -149,6 +182,7 @@ export class HaSelect extends LitElement {
@clear=${this._clearValue}
.label=${this.label}
.value=${valueLabel}
.valueRenderer=${this._getValueRenderer(valueIconPath)}
.required=${this.required}
.disabled=${this.disabled}
.hideClearIcon=${
@@ -86,6 +86,7 @@ export class HaSelectorState extends SubscribeMixin(LitElement) {
.required=${this.required}
allow-custom-value
.hideStates=${this.selector.state?.hide_states}
.reorder=${this.selector.state?.reorder ?? false}
></ha-entity-states-picker>
`;
}
+101
View File
@@ -41,6 +41,107 @@ export interface MQTTDeviceDebugInfo {
triggers: MQTTTriggerDebugInfo[];
}
export type MQTTExplorerSourceType = "yaml" | "subentry" | "discovery";
export interface MQTTExplorerOrigin {
name: string;
sw_version: string | null;
support_url: string | null;
}
export interface MQTTExplorerSource {
id: string;
type: MQTTExplorerSourceType;
title: string | null;
// The software version of a discovery origin
sw_version: string | null;
}
export interface MQTTExplorerDevice {
device_id: string;
name: string | null;
sources: string[];
// The parent device: a via_device, or the parent of a child device
via_device_id: string | null;
child_device: boolean;
}
export interface MQTTExplorerEntityTopic {
topic: string;
direction: "subscribe" | "publish";
// Subscribe: configured QoS. Publish: QoS of the last sent message.
qos: number;
}
export interface MQTTExplorerEntity {
entity_id: string;
name: string | null;
available: boolean;
// Null for an entity that was not set up and is placed under its device
source: string | null;
device_id: string | null;
// The node ID of the discovery topic, if it has one
node_id: string | null;
topics: MQTTExplorerEntityTopic[];
}
export interface MQTTExplorerArtifact {
artifact_id: string;
type: "device_trigger" | "tag";
source: string;
// Null for a tag scanner without a device
device_id: string | null;
node_id: string | null;
topics: MQTTExplorerEntityTopic[];
}
export interface MQTTExplorerStructure {
broker: {
connected: boolean;
host: string;
port: number;
};
sources: MQTTExplorerSource[];
devices: MQTTExplorerDevice[];
entities: MQTTExplorerEntity[];
artifacts: MQTTExplorerArtifact[];
}
export const fetchMQTTExplorerStructure = (
hass: HomeAssistant
): Promise<MQTTExplorerStructure> =>
hass.callWS<MQTTExplorerStructure>({ type: "mqtt/explorer/structure" });
export interface MQTTExplorerConfig {
source: string;
type: MQTTExplorerSourceType;
discovery_topic: string | null;
origin: MQTTExplorerOrigin | null;
payload: Record<string, unknown>;
// From a device based discovery payload. For a device, the payload is then
// that whole device discovery payload, built again from its components.
device_discovery: boolean;
}
export interface MQTTExplorerTopicDetails extends MQTTExplorerEntityTopic {
// Stored messages, oldest first
messages: MQTTLoggedMessage[];
}
export interface MQTTExplorerDetails {
configs: MQTTExplorerConfig[];
topics: MQTTExplorerTopicDetails[];
}
export type MQTTExplorerItem =
{ entity_id: string } | { device_id: string } | { artifact_id: string };
export const fetchMQTTExplorerDetails = (
hass: HomeAssistant,
item: MQTTExplorerItem
): Promise<MQTTExplorerDetails> =>
hass.callWS<MQTTExplorerDetails>({ type: "mqtt/explorer/details", ...item });
export const subscribeMQTTTopic = (
hass: HomeAssistant,
topic: string,
+1
View File
@@ -576,6 +576,7 @@ export interface StateSelector {
attribute?: string;
hide_states?: string[];
multiple?: boolean;
reorder?: boolean;
} | null;
}
-2
View File
@@ -108,7 +108,6 @@ export const ConditionalListenerMixin = <
super.updated(changedProperties);
// After willUpdate so consumers can set `_conditionContext.entity_id`.
if (
changedProperties.has("hass") ||
changedProperties.has("config") ||
changedProperties.has("_config") ||
changedProperties.has("_maxColumns")
@@ -180,7 +179,6 @@ export const ConditionalListenerMixin = <
this.__conditionEvaluator.observe(
this.__observed,
this.hass,
() => this._conditionContext
);
}
@@ -3,7 +3,7 @@ import type { ContextType } from "@lit/context";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
@@ -88,6 +88,11 @@ export class EnergySuggestions extends LitElement {
@state() private _loadFailed = false;
@state() private _expanded = false;
@query(".items-container .suggestion:nth-child(4) button.link")
private _firstRevealedSuggestion?: HTMLButtonElement;
// Read by the @consumeEntityStates decorator below.
@state() protected _statisticIds: string[] = [];
@@ -217,6 +222,13 @@ export class EnergySuggestions extends LitElement {
}
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (changedProps.has("tab")) {
this._expanded = false;
}
}
protected render(): TemplateResult | typeof nothing {
if (this._loadFailed) {
return html`
@@ -242,6 +254,11 @@ export class EnergySuggestions extends LitElement {
return nothing;
}
const visibleSuggestions =
!this._expanded && suggestions.length >= 6
? suggestions.slice(0, 3)
: suggestions;
return html`
<ha-card>
<h1 class="card-header">
@@ -286,10 +303,26 @@ export class EnergySuggestions extends LitElement {
suggestions.length
? html`<div class="items-container">
${repeat(
suggestions,
visibleSuggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion, false)
)}
${
visibleSuggestions.length < suggestions.length
? html`<ha-button
appearance="plain"
@click=${this._showMore}
>
${this._i18n.localize(
"ui.panel.config.energy.suggestions.show_more",
{
count:
suggestions.length - visibleSuggestions.length,
}
)}
</ha-button>`
: nothing
}
</div>`
: nothing
}
@@ -318,6 +351,12 @@ export class EnergySuggestions extends LitElement {
`;
}
private async _showMore() {
this._expanded = true;
await this.updateComplete;
this._firstRevealedSuggestion?.focus();
}
private _renderSuggestion(
suggestion: EnergyMeterSuggestion,
dismissed: boolean
+2 -2
View File
@@ -202,9 +202,9 @@ class HaPanelConfig extends HassRouterPage {
import("./integrations/integration-panels/lorawan/lorawan-router"),
},
mqtt: {
tag: "mqtt-config-panel",
tag: "mqtt-config-router",
load: () =>
import("./integrations/integration-panels/mqtt/mqtt-config-panel"),
import("./integrations/integration-panels/mqtt/mqtt-config-router"),
},
zwave_js: {
tag: "zwave_js-config-router",
@@ -4,6 +4,7 @@ import {
mdiDevices,
mdiShape,
mdiTune,
mdiVectorPolyline,
} from "@mdi/js";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
@@ -213,6 +214,10 @@ export class MQTTConfigPanel extends LitElement {
<ha-card class="nav-card">
<div class="card-header">
${this.hass.localize("ui.panel.config.mqtt.my_network_title")}
<ha-button appearance="filled" href="/config/mqtt/visualization">
<ha-svg-icon slot="start" .path=${mdiVectorPolyline}></ha-svg-icon>
${this.hass.localize("ui.panel.config.mqtt.show_map")}
</ha-button>
</div>
<div class="card-content">
<ha-list-nav
@@ -435,6 +440,9 @@ export class MQTTConfigPanel extends LitElement {
}
.nav-card .card-header {
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: var(--ha-space-2);
}
.content {
@@ -0,0 +1,41 @@
import { customElement, property } from "lit/decorators";
import type { RouterOptions } from "../../../../../layouts/hass-router-page";
import { HassRouterPage } from "../../../../../layouts/hass-router-page";
import type { HomeAssistant } from "../../../../../types";
@customElement("mqtt-config-router")
class MQTTConfigRouter extends HassRouterPage {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: "is-wide", type: Boolean }) public isWide = false;
@property({ type: Boolean }) public narrow = false;
protected routerOptions: RouterOptions = {
defaultPage: "dashboard",
showLoading: true,
routes: {
dashboard: {
tag: "mqtt-config-panel",
load: () => import("./mqtt-config-panel"),
},
visualization: {
tag: "mqtt-network-visualization-page",
load: () => import("./mqtt-network-visualization-page"),
},
},
};
protected updatePageEl(el): void {
el.route = this.routeTail;
el.hass = this.hass;
el.isWide = this.isWide;
el.narrow = this.narrow;
}
}
declare global {
interface HTMLElementTagNameMap {
"mqtt-config-router": MQTTConfigRouter;
}
}
@@ -0,0 +1,426 @@
import { mdiClose, mdiContentCopy } from "@mdi/js";
import { dump } from "js-yaml";
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consumeLocalize } from "../../../../../common/decorators/consume-context-entry";
import { fireEvent } from "../../../../../common/dom/fire_event";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../../../common/translations/localize";
import { sanitizeHttpUrl } from "../../../../../common/url/sanitize-http-url";
import { copyToClipboard } from "../../../../../common/util/copy-clipboard";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-icon-button";
import "../../../../../components/ha-spinner";
import "../../../../../components/ha-switch";
import type {
MQTTExplorerConfig,
MQTTExplorerSource,
} from "../../../../../data/mqtt";
import { showToast } from "../../../../../util/toast";
import { sourceName } from "./mqtt-network-data";
@customElement("mqtt-config-view")
class MqttConfigView extends LitElement {
@state()
@consumeLocalize()
private _localizeFunc!: LocalizeFunc;
// The name of the device, entity, trigger or tag
@property({ attribute: false }) public name!: string;
// What the item is, like "Device"
@property({ attribute: false }) public kind!: string;
// Undefined while loading
@property({ attribute: false }) public configs?: MQTTExplorerConfig[];
@property({ attribute: false }) public sources: MQTTExplorerSource[] = [];
// The platform of an entity, which can be shown as YAML
@property({ attribute: false }) public platform?: string;
// The config of a device from YAML is part of the config of its entities,
// so it is not shown on its own
@property({ type: Boolean }) public device = false;
@property({ type: Boolean }) public failed = false;
// The name opens the entity or device
@property({ type: Boolean }) public openable = false;
// An entity from YAML, which can only be matched to its config by its
// unique ID
@property({ attribute: "yaml-entity", type: Boolean })
public yamlEntity = false;
// The format chosen per source for a discovered entity, which shows as JSON
// without a choice
@state() private _yaml: Record<string, boolean> = {};
protected willUpdate(changedProps: PropertyValues<this>): void {
if (changedProps.has("name") || changedProps.has("kind")) {
this._yaml = {};
}
}
// Only an entity discovered on its own can be shown as JSON. The JSON of an
// entity from YAML or a subentry says little without a discovery topic, and
// that of an entity from device discovery is not what was discovered.
private _canSwitch(config: MQTTExplorerConfig): boolean {
return (
!!this.platform && config.type === "discovery" && !config.device_discovery
);
}
private _showYaml(config: MQTTExplorerConfig): boolean {
if (!this.platform) {
return false;
}
return this._canSwitch(config)
? (this._yaml[config.source] ?? false)
: true;
}
private _localize(key: string): string {
return this._localizeFunc(
`ui.panel.config.mqtt.visualization.config_view.${key}` as LocalizeKeys
);
}
protected render(): TemplateResult {
return html`
<div class="header">
<div class="title">
${
this.openable
? html`<button class="name link" @click=${this._open}>
${this.name}
</button>`
: html`<span class="name">${this.name}</span>`
}
<span class="secondary">${this.kind}</span>
</div>
<ha-icon-button
.path=${mdiClose}
.label=${this._localizeFunc("ui.common.close")}
@click=${this._close}
></ha-icon-button>
</div>
${this._renderContent()}
`;
}
private _renderContent() {
if (this.failed) {
return html`<ha-alert alert-type="error"
>${this._localize("load_failed")}</ha-alert
>`;
}
if (!this.configs) {
return html`<div class="center"><ha-spinner></ha-spinner></div>`;
}
if (!this.configs.length) {
return html`<p class="secondary">
${this._localize(this.yamlEntity ? "no_unique_id" : "no_config")}
</p>`;
}
return this.configs.map((config) => this._renderConfig(config));
}
private _renderConfig(config: MQTTExplorerConfig) {
const source = this.sources.find((s) => s.id === config.source);
const origin = config.origin;
// The origin is published by any MQTT client
const supportUrl = sanitizeHttpUrl(origin?.support_url);
const title = source
? sourceName(source, this._localizeFunc)
: config.source;
if (this.device && config.type === "yaml") {
return html`<p class="secondary">${this._localize("yaml_device")}</p>`;
}
if (this.device && config.type === "subentry") {
return html`<p class="secondary">
${this._localize("subentry_device")}
<button
class="link"
data-source=${config.source}
@click=${this._reconfigure}
>
${this._localize("reconfigure_subentry")}
</button>
</p>`;
}
// A device discovered with its entities only has the device part of their
// config, which belongs to the discovery topic of an entity
const devicePart = this.device && !config.device_discovery;
const yaml = this._showYaml(config);
const formatted = devicePart
? dump(config.payload)
: this._format(config.payload, yaml);
return html`
<div class="section-header">
<h3>${title}</h3>
${
this._canSwitch(config)
? html`<ha-switch
class="yaml"
.checked=${yaml}
data-source=${config.source}
@change=${this._handleYaml}
>${this._localize("show_as_yaml")}</ha-switch
>`
: nothing
}
</div>
<dl>
${
config.discovery_topic && !devicePart
? html`<dt>
${this._localize(
// An entity from device discovery was discovered with its
// device
this.platform && config.device_discovery
? "device_discovery_topic"
: "discovery_topic"
)}
</dt>
<dd class="copyable">
<code>${config.discovery_topic}</code>
<ha-icon-button
.path=${mdiContentCopy}
.label=${this._localize("copy_discovery_topic")}
data-text=${config.discovery_topic}
@click=${this._copy}
></ha-icon-button>
</dd>`
: nothing
}
${
origin
? html`<dt>${this._localize("origin")}</dt>
<dd>
${origin.name}${
origin.sw_version ? ` ${origin.sw_version}` : nothing
}${
supportUrl
? html` ·
<a href=${supportUrl} target="_blank" rel="noreferrer"
>${this._localize("support")}</a
>`
: nothing
}
</dd>`
: nothing
}
</dl>
<div class="code-label">${this._localize(this._configLabel(config))}</div>
<div class="code">
<pre dir="ltr">${formatted}</pre>
<ha-icon-button
.path=${mdiContentCopy}
.label=${this._localize("copy_config")}
data-text=${formatted}
@click=${this._copy}
></ha-icon-button>
</div>
`;
}
// What the shown config is
private _configLabel(config: MQTTExplorerConfig): string {
if (this.device) {
return config.device_discovery
? "device_discovery_payload"
: "device_config";
}
if (config.type === "discovery" && !config.device_discovery) {
return "discovery_payload";
}
return this.platform ? "entity_config" : "discovery_payload";
}
private _format(payload: Record<string, unknown>, yaml: boolean): string {
if (!yaml || !this.platform) {
return JSON.stringify(payload, null, 2);
}
// In YAML the config is listed under the mqtt key and its platform
const { platform: _platform, ...config } = payload;
return dump({ mqtt: { [this.platform]: [config] } });
}
private _handleYaml(ev: Event): void {
const target = ev.target as HTMLInputElement;
this._yaml = {
...this._yaml,
[target.dataset.source!]: target.checked,
};
}
private async _copy(ev: Event): Promise<void> {
await copyToClipboard((ev.currentTarget as HTMLElement).dataset.text!);
showToast(this, {
message: this._localizeFunc("ui.common.copied_clipboard"),
});
}
private _close(): void {
fireEvent(this, "mqtt-config-view-closed");
}
private _open(): void {
fireEvent(this, "mqtt-config-view-open");
}
private _reconfigure(ev: Event): void {
fireEvent(this, "mqtt-config-view-reconfigure", {
source: (ev.currentTarget as HTMLElement).dataset.source!,
});
}
static readonly styles = css`
:host {
display: block;
min-width: 0;
}
.header,
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--ha-space-2);
}
.title {
display: flex;
flex-direction: column;
min-width: 0;
}
.name {
font-size: var(--ha-font-size-l);
word-break: break-word;
}
.link {
padding: 0;
border: none;
background: none;
font-family: inherit;
font-size: inherit;
text-align: start;
color: var(--primary-color);
cursor: pointer;
}
.link:hover {
text-decoration: underline;
}
.link.name {
font-size: var(--ha-font-size-l);
}
.secondary {
color: var(--secondary-text-color);
}
.center {
display: flex;
justify-content: center;
padding: var(--ha-space-4);
}
.section-header {
margin-top: var(--ha-space-4);
}
.yaml {
font-size: var(--ha-font-size-s);
}
h3 {
flex: 1;
font-size: var(--ha-font-size-m);
font-weight: var(--ha-font-weight-medium);
margin: 0;
}
.copyable {
display: flex;
align-items: flex-start;
gap: var(--ha-space-1);
}
.copyable code {
flex: 1;
min-width: 0;
padding-top: var(--ha-space-1);
}
.copyable ha-icon-button {
--ha-icon-button-size: 32px;
--mdc-icon-size: 18px;
margin-top: calc(var(--ha-space-1) * -1);
}
.code-label {
margin-bottom: var(--ha-space-1);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
.code {
position: relative;
}
.code ha-icon-button {
position: absolute;
top: var(--ha-space-1);
inset-inline-end: var(--ha-space-1);
--ha-icon-button-size: 32px;
--mdc-icon-size: 18px;
}
dl {
display: grid;
grid-template-columns: auto 1fr;
gap: var(--ha-space-1) var(--ha-space-3);
margin: var(--ha-space-2) 0;
}
dt {
color: var(--secondary-text-color);
}
dd {
margin: 0;
word-break: break-all;
}
pre {
margin: 0;
padding: var(--ha-space-2);
/* Room for the copy button */
padding-inline-end: var(--ha-space-10);
max-height: 480px;
overflow: auto;
white-space: pre-wrap;
word-break: break-all;
background-color: var(
--code-editor-background-color,
var(--secondary-background-color)
);
border-radius: var(--ha-border-radius-md);
font-family: var(--ha-font-family-code);
font-size: var(--ha-font-size-s);
}
/* Room for a finger, and no scroll area within the scrolling sheet */
@media (pointer: coarse) {
dl {
gap: var(--ha-space-3);
}
.copyable ha-icon-button,
.code ha-icon-button {
--ha-icon-button-size: 40px;
--mdc-icon-size: 20px;
}
pre {
max-height: none;
}
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"mqtt-config-view": MqttConfigView;
}
interface HASSDomEvents {
"mqtt-config-view-closed": undefined;
"mqtt-config-view-open": undefined;
"mqtt-config-view-reconfigure": { source: string };
}
}
@@ -0,0 +1,766 @@
import {
mdiFileDocumentOutline,
mdiMagnify,
mdiNoteTextOutline,
} from "@mdi/js";
import { hexBlend } from "../../../../../common/color/hex";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../../../common/translations/localize";
import type {
NetworkData,
NetworkLink,
NetworkNode,
} from "../../../../../components/chart/ha-network-graph";
import type {
MQTTExplorerEntityTopic,
MQTTExplorerSource,
MQTTExplorerStructure,
} from "../../../../../data/mqtt";
import { mdiMqttLogo } from "../../../../../resources/mqtt-logo-svg";
export const BROKER_NODE_ID = "broker";
// The subentries share one node, the device of each subentry hangs under it
export const SUBENTRIES_NODE_ID = "subentries";
export const SOURCE_PREFIX = "source:";
export const DEVICE_PREFIX = "device:";
export const NO_DEVICE_PREFIX = "no_device:";
export const ENTITY_PREFIX = "entity:";
export const ARTIFACT_PREFIX = "artifact:";
export const TOPIC_PREFIX = "topic:";
// IDs and topics can hold ":", so the parts are separated by a line break
const TOPIC_ID_SEPARATOR = "\n";
// The ID of a topic node of an entity or artifact node
export const topicNodeId = (
ownerNodeId: string,
topic: MQTTExplorerEntityTopic
): string =>
`${TOPIC_PREFIX}${[ownerNodeId, topic.direction, topic.topic].join(TOPIC_ID_SEPARATOR)}`;
export const parseTopicNodeId = (id: string) => {
const [ownerNodeId, direction, ...topic] = id
.substring(TOPIC_PREFIX.length)
.split(TOPIC_ID_SEPARATOR);
return {
ownerNodeId,
direction: direction as MQTTExplorerEntityTopic["direction"],
topic: topic.join(TOPIC_ID_SEPARATOR),
};
};
// Entities that were not set up have no source and hang under their device
const UNKNOWN_SOURCE = "discovery";
// Devices are circles, so entities get their own shape
const ENTITY_SYMBOL =
"path://M50 0 L93.3 25 L93.3 75 L50 100 L6.7 75 L6.7 25 Z";
const FADED_OPACITY = 0.15;
// A faded node keeps a stronger border, so it keeps its shape
const FADED_BORDER_OPACITY = 0.45;
const FADED_BORDER_WIDTH = 1;
// The purple of the MQTT logo
const MQTT_LOGO_COLOR = "#660066";
// A link has the color of the node below it, and gets thinner further down
const SOURCE_LINK_WIDTH = 3;
const DEVICE_LINK_WIDTH = 2.25;
const CHILD_DEVICE_LINK_WIDTH = 1.75;
const ENTITY_LINK_WIDTH = 1.5;
const TOPIC_LINK_WIDTH = 1;
const ROOT_SYMBOL_SIZE = 60;
const ROOT_SYMBOL_SIZE_MOBILE = 40;
const SOURCE_SYMBOL_SIZE = 40;
const SOURCE_SYMBOL_SIZE_MOBILE = 30;
const ROOT_LABEL = {
position: "bottom",
fontWeight: "bold",
fontSize: 14.4,
} as const;
const iconSymbol = (
color: string,
iconColor: string,
iconPath: string,
borderColor?: string
): string => {
const border = borderColor
? ` stroke="${borderColor}" stroke-width="${FADED_BORDER_WIDTH}"`
: "";
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect x="0.5" y="0.5" width="31" height="31" rx="6" fill="${color.trim()}"${border}/><path transform="translate(6 6) scale(0.8333)" fill="${iconColor}" d="${iconPath}"/></svg>`;
return `image://data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
};
const TREE_COLUMN_WIDTH = 240;
const TREE_ROW_HEIGHT = 36;
// Places the nodes in columns from the broker on the left, each node level
// with the middle of its children. A node with more than one parent goes under
// the first one found, and the nodes the legend hides fold onto their parent.
const placeInTree = (
nodesById: Map<string, NetworkNode>,
childIds: Map<string, string[]>,
isShown: (id: string) => boolean
) => {
const treeChildren = new Map<string, string[]>();
const treeParent = new Map<string, string>();
const order = [BROKER_NODE_ID];
// The loop also visits the children it adds, breadth first
for (const parentId of order) {
const children = [...new Set(childIds.get(parentId))].filter(
(id) => id !== BROKER_NODE_ID && !treeParent.has(id)
);
children.forEach((id) => treeParent.set(id, parentId));
treeChildren.set(parentId, children);
order.push(...children);
}
let row = 0;
const place = (id: string, depth: number): number => {
const children = (treeChildren.get(id) ?? []).filter(isShown);
const childRows = children.map((childId) => place(childId, depth + 1));
const y = childRows.length
? (childRows[0] + childRows[childRows.length - 1]) / 2
: row++ * TREE_ROW_HEIGHT;
const node = nodesById.get(id)!;
node.x = depth * TREE_COLUMN_WIDTH;
node.y = y;
return y;
};
place(BROKER_NODE_ID, 0);
// The hidden nodes still need a position, for when the legend shows them
order.forEach((id) => {
const node = nodesById.get(id)!;
if (node.x == null) {
const parentId = treeParent.get(id);
const parent = parentId ? nodesById.get(parentId) : undefined;
node.x = (parent?.x ?? 0) + TREE_COLUMN_WIDTH;
node.y = parent?.y ?? 0;
}
});
};
export const enum MQTTNodeCategory {
Broker = 0,
Source = 1,
Device = 2,
ChildDevice = 3,
Entity = 4,
DeviceTrigger = 5,
Tag = 6,
SubscribeTopic = 7,
PublishTopic = 8,
}
// The translation keys of the categories, in the order of MQTTNodeCategory
export const CATEGORY_KEYS = [
"broker",
"source",
"device",
"child_device",
"entity",
"artifact_device_trigger",
"artifact_tag",
"subscribe_topic",
"publish_topic",
] as const;
export const sourceName = (
source: MQTTExplorerSource,
localize: LocalizeFunc
): string => {
if (source.type === "yaml") {
return localize("ui.panel.config.mqtt.visualization.source_yaml");
}
// A discovery origin is named by its title
if (source.type === "discovery" && !source.title) {
return localize("ui.panel.config.mqtt.visualization.source_discovery");
}
return source.title ?? source.id;
};
export function createMQTTNetworkChartData(
structure: MQTTExplorerStructure,
darkMode: boolean,
localize: LocalizeFunc,
element: Element,
isMobileSize: boolean,
hiddenSources: string[],
focusedNode?: string,
searchFilter = "",
// Names of the legend categories that are switched off
hiddenCategories: string[] = [],
// Place the nodes in a tree from left to right
treeLayout = false
): NetworkData {
const style = getComputedStyle(element);
const color = (name: string) => style.getPropertyValue(name).trim();
const iconColor = color("--text-primary-color");
// The purple of the logo has too little contrast on a dark background
const brokerColor = darkMode ? color("--purple-color") : MQTT_LOGO_COLOR;
const sourceColor = color("--orange-color");
const deviceColor = color("--indigo-color");
const childDeviceColor = color("--light-blue-color");
const entityColor = color("--green-color");
const artifactStyles = {
device_trigger: {
category: MQTTNodeCategory.DeviceTrigger,
symbol: "triangle",
color: color("--amber-color"),
},
tag: {
category: MQTTNodeCategory.Tag,
symbol: "rect",
color: color("--pink-color"),
},
};
const subscribeColor = color("--cyan-color");
const publishColor = color("--deep-orange-color");
const unavailableColor = color("--disabled-color");
const backgroundColor = color("--card-background-color");
const selectedBorderColor = color("--primary-text-color");
// A faded node is mixed with the background instead of made transparent,
// so the links behind it do not show through
const graphBackgroundColor = color("--primary-background-color");
const fade = (value: string, opacity = FADED_OPACITY) => {
try {
return hexBlend(value, graphBackgroundColor, opacity * 100);
} catch (_err) {
// A theme color that is no hex color, like color-mix(), stays unfaded
return value;
}
};
const nodes: NetworkNode[] = [];
const links: NetworkLink[] = [];
// The icon of the broker and the sources, which is redrawn when faded
const nodeIcons = new Map<string, { color: string; path: string }>();
// The topics of a focused entity or artifact, linked to its node
const addTopicNodes = (
ownerNodeId: string,
topics: MQTTExplorerEntityTopic[]
) => {
topics.forEach((topic) => {
const topicId = topicNodeId(ownerNodeId, topic);
const isPublish = topic.direction === "publish";
nodes.push({
id: topicId,
name: topic.topic,
category: isPublish
? MQTTNodeCategory.PublishTopic
: MQTTNodeCategory.SubscribeTopic,
value: 0,
symbolSize: 10,
symbol: "diamond",
itemStyle: {
color: isPublish ? publishColor : subscribeColor,
},
polarDistance: 0.95,
});
links.push({
source: ownerNodeId,
target: topicId,
value: 0,
symbol: "none",
lineStyle: {
width: TOPIC_LINK_WIDTH,
color: isPublish ? publishColor : subscribeColor,
type: isPublish ? "dashed" : "solid",
},
});
});
};
const localizeText = (key: string) =>
localize(`ui.panel.config.mqtt.visualization.${key}` as LocalizeKeys);
const categories = [
{ symbol: "roundRect", itemStyle: { color: brokerColor } },
{ symbol: "roundRect", itemStyle: { color: sourceColor } },
{ symbol: "circle", itemStyle: { color: deviceColor } },
{ symbol: "circle", itemStyle: { color: childDeviceColor } },
{ symbol: ENTITY_SYMBOL, itemStyle: { color: entityColor } },
{
symbol: artifactStyles.device_trigger.symbol,
itemStyle: { color: artifactStyles.device_trigger.color },
},
{
symbol: artifactStyles.tag.symbol,
itemStyle: { color: artifactStyles.tag.color },
},
{ symbol: "diamond", itemStyle: { color: subscribeColor } },
{ symbol: "diamond", itemStyle: { color: publishColor } },
].map((category, index) => ({
name: localizeText(CATEGORY_KEYS[index]),
...category,
}));
nodes.push({
id: BROKER_NODE_ID,
name: localizeText("broker"),
category: MQTTNodeCategory.Broker,
value: 4,
symbolSize: isMobileSize ? ROOT_SYMBOL_SIZE_MOBILE : ROOT_SYMBOL_SIZE,
symbol: iconSymbol(brokerColor, iconColor, mdiMqttLogo),
itemStyle: { color: brokerColor },
label: ROOT_LABEL,
polarDistance: 0,
fixed: true,
});
nodeIcons.set(BROKER_NODE_ID, { color: brokerColor, path: mdiMqttLogo });
const sourceIcons: Record<MQTTExplorerSource["type"], string> = {
yaml: mdiFileDocumentOutline,
subentry: mdiNoteTextOutline,
discovery: mdiMagnify,
};
const hidden = new Set(hiddenSources);
const visibleSources = structure.sources.filter((s) => !hidden.has(s.id));
const addSourceNode = (
id: string,
name: string,
type: MQTTExplorerSource["type"],
context?: string
) => {
nodes.push({
id,
name,
context,
category: MQTTNodeCategory.Source,
value: 3,
symbolSize: isMobileSize ? SOURCE_SYMBOL_SIZE_MOBILE : SOURCE_SYMBOL_SIZE,
symbol: iconSymbol(sourceColor, iconColor, sourceIcons[type]),
itemStyle: { color: sourceColor },
label: ROOT_LABEL,
polarDistance: 0.25,
});
nodeIcons.set(id, { color: sourceColor, path: sourceIcons[type] });
links.push({
source: BROKER_NODE_ID,
target: id,
value: 3,
symbol: "none",
// Links are half transparent by default
lineStyle: { width: SOURCE_LINK_WIDTH, color: sourceColor, opacity: 1 },
});
};
visibleSources.forEach((source) => {
if (source.type !== "subentry") {
addSourceNode(
`${SOURCE_PREFIX}${source.id}`,
sourceName(source, localize),
source.type,
source.sw_version ?? undefined
);
}
});
if (visibleSources.some((source) => source.type === "subentry")) {
addSourceNode(
SUBENTRIES_NODE_ID,
localizeText("source_subentries"),
"subentry"
);
}
const sourceIds = new Set(visibleSources.map((s) => s.id));
const subentrySourceIds = new Set(
visibleSources.filter((s) => s.type === "subentry").map((s) => s.id)
);
// Link to the broker if a source is missing, so no link points to nothing
const sourceNode = (source: string) => {
if (subentrySourceIds.has(source)) {
return SUBENTRIES_NODE_ID;
}
return sourceIds.has(source) ? `${SOURCE_PREFIX}${source}` : BROKER_NODE_ID;
};
// Only items of the sources that are shown
const devices = structure.devices.filter((d) =>
d.sources.some((source) => sourceIds.has(source))
);
const deviceIds = new Set(devices.map((d) => d.device_id));
const viaDeviceIds = new Map(
devices.map((d) => [d.device_id, d.via_device_id])
);
// A device in a loop of parents would never reach a source
const inParentLoop = (deviceId: string) => {
const seen = new Set<string>();
let parentId = viaDeviceIds.get(deviceId);
while (parentId && deviceIds.has(parentId) && !seen.has(parentId)) {
if (parentId === deviceId) {
return true;
}
seen.add(parentId);
parentId = viaDeviceIds.get(parentId);
}
return false;
};
devices.forEach((device) => {
const id = `${DEVICE_PREFIX}${device.device_id}`;
const deviceNodeColor = device.child_device
? childDeviceColor
: deviceColor;
nodes.push({
id,
name: device.name ?? device.device_id,
category: device.child_device
? MQTTNodeCategory.ChildDevice
: MQTTNodeCategory.Device,
value: 2,
symbolSize: device.child_device ? 20 : 24,
symbol: "circle",
itemStyle: { color: deviceNodeColor },
polarDistance: 0.5,
});
// A device linked to a parent hangs under that parent, otherwise under
// each of its sources
if (
device.via_device_id &&
deviceIds.has(device.via_device_id) &&
!inParentLoop(device.device_id)
) {
links.push({
source: `${DEVICE_PREFIX}${device.via_device_id}`,
target: id,
value: 2,
symbol: "none",
lineStyle: {
width: CHILD_DEVICE_LINK_WIDTH,
color: deviceNodeColor,
type: device.child_device ? "solid" : "dashed",
},
});
return;
}
device.sources.forEach((source) => {
if (!sourceIds.has(source)) {
return;
}
links.push({
source: sourceNode(source),
target: id,
value: 2,
symbol: "none",
lineStyle: { width: DEVICE_LINK_WIDTH, color: deviceNodeColor },
});
});
});
const noDeviceNodes = new Set<string>();
// Items without a device hang under "No linked device" of their source
const noDeviceNode = (source: string): string => {
const id = `${NO_DEVICE_PREFIX}${source}`;
if (!noDeviceNodes.has(id)) {
noDeviceNodes.add(id);
nodes.push({
id,
name: localizeText("no_linked_device"),
category: MQTTNodeCategory.Device,
value: 2,
symbolSize: 24,
symbol: "emptyCircle",
itemStyle: { color: deviceColor },
polarDistance: 0.5,
});
links.push({
source: sourceNode(source),
target: id,
value: 2,
symbol: "none",
lineStyle: {
width: DEVICE_LINK_WIDTH,
color: deviceColor,
type: "dashed",
},
});
}
return id;
};
structure.entities.forEach((entity) => {
const source = entity.source ?? UNKNOWN_SOURCE;
const onDevice = !!entity.device_id && deviceIds.has(entity.device_id);
// An entity without a source is shown when its device is shown
if (entity.source ? !sourceIds.has(source) : !onDevice) {
return;
}
const id = `${ENTITY_PREFIX}${entity.entity_id}`;
const parent = onDevice
? `${DEVICE_PREFIX}${entity.device_id}`
: noDeviceNode(source);
// A focused entity shows its topics
const isExpanded = id === focusedNode;
const entityNodeColor = entity.available ? entityColor : unavailableColor;
// A filled hexagon has topics that can be expanded
const filled = entity.topics.length > 0 && !isExpanded;
nodes.push({
id,
name: entity.name ?? entity.entity_id,
context: entity.entity_id,
// Unavailable entities are only grayed out, the legend filters them
// with the other entities
category: MQTTNodeCategory.Entity,
value: 1,
symbolSize: 16,
symbol: ENTITY_SYMBOL,
itemStyle: {
color: filled ? entityNodeColor : backgroundColor,
borderColor: entityNodeColor,
borderWidth: 2,
},
polarDistance: 0.75,
});
links.push({
source: parent,
target: id,
value: 1,
symbol: "none",
lineStyle: { width: ENTITY_LINK_WIDTH, color: entityNodeColor },
});
if (isExpanded) {
addTopicNodes(id, entity.topics);
}
});
structure.artifacts.forEach((artifact) => {
if (
!sourceIds.has(artifact.source) ||
(artifact.device_id && !deviceIds.has(artifact.device_id))
) {
return;
}
const id = `${ARTIFACT_PREFIX}${artifact.artifact_id}`;
const artifactStyle = artifactStyles[artifact.type];
nodes.push({
id,
name: artifact.artifact_id.split(":").slice(1).join(":"),
context: localizeText(`artifact_${artifact.type}`),
category: artifactStyle.category,
value: 1,
symbolSize: 12,
symbol: artifactStyle.symbol,
itemStyle: { color: artifactStyle.color },
polarDistance: 0.75,
});
links.push({
source: artifact.device_id
? `${DEVICE_PREFIX}${artifact.device_id}`
: noDeviceNode(artifact.source),
target: id,
value: 1,
symbol: "none",
lineStyle: {
width: ENTITY_LINK_WIDTH,
color: artifactStyle.color,
type: "dotted",
},
});
// A focused trigger or tag shows its topic
if (id === focusedNode) {
addTopicNodes(id, artifact.topics);
}
});
// Keep the focused node with its parents and children clear and fade the
// rest, so the topics of an entity or the items of a device stand out. A
// search keeps the matches clear instead, with the links between them.
const focusNodes = new Set<string>();
// Links point from parent to child
const childIds = new Map<string, string[]>();
links.forEach((link) => {
const list = childIds.get(link.source);
if (list) {
list.push(link.target);
} else {
childIds.set(link.source, [link.target]);
}
});
const filter = searchFilter.trim().toLowerCase();
if (filter) {
const topicsByNode = new Map([
...structure.entities.map((entity) => [
`${ENTITY_PREFIX}${entity.entity_id}`,
entity.topics.map((topic) => topic.topic),
]),
...structure.artifacts.map((artifact) => [
`${ARTIFACT_PREFIX}${artifact.artifact_id}`,
artifact.topics.map((topic) => topic.topic),
]),
] as [string, string[]][]);
nodes.forEach((node) => {
if (
[node.name, node.context, ...(topicsByNode.get(node.id) ?? [])].some(
(value) => value?.toLowerCase().includes(filter)
)
) {
focusNodes.add(node.id);
}
});
} else if (focusedNode && nodes.some((node) => node.id === focusedNode)) {
// Walk up to the broker and down to all the children of the focused node
const parents = new Map<string, string[]>();
links.forEach((link) => {
const list = parents.get(link.target);
if (list) {
list.push(link.source);
} else {
parents.set(link.target, [link.source]);
}
});
const walk = (start: string, next: Map<string, string[]>) => {
const queue = [start];
while (queue.length) {
const nodeId = queue.pop()!;
(next.get(nodeId) ?? []).forEach((other) => {
if (!focusNodes.has(other)) {
focusNodes.add(other);
queue.push(other);
}
});
}
};
focusNodes.add(focusedNode);
walk(focusedNode, parents);
walk(focusedNode, childIds);
}
const fadedNodes = new Set<string>();
const fadeNode = (node: NetworkNode) => {
fadedNodes.add(node.id);
const icon = nodeIcons.get(node.id);
if (icon) {
node.symbol = iconSymbol(
fade(icon.color),
fade(iconColor),
icon.path,
fade(icon.color, FADED_BORDER_OPACITY)
);
}
const { color: fill, borderColor, borderWidth } = node.itemStyle ?? {};
// A node without a border gets one in its own color
const edgeColor = borderColor ?? fill;
node.itemStyle = {
...node.itemStyle,
...(fill && { color: fade(fill) }),
...(edgeColor &&
!icon && {
borderColor: fade(edgeColor, FADED_BORDER_OPACITY),
borderWidth: Math.max(borderWidth ?? 0, FADED_BORDER_WIDTH),
}),
};
node.label = { ...node.label, show: false };
};
if (focusNodes.size || filter) {
nodes.forEach((node) => {
if (!focusNodes.has(node.id)) {
fadeNode(node);
}
});
}
// The selected node gets the ring of the theme, also an entity with a border
// of its own
const selectedNode = nodes.find((node) => node.id === focusedNode);
if (selectedNode && !fadedNodes.has(selectedNode.id)) {
selectedNode.itemStyle = {
...selectedNode.itemStyle,
borderColor: selectedBorderColor,
};
}
// Only show the categories that are in the graph, and renumber the nodes.
// The broker and the sources have an icon of their own, not a legend entry.
const usedCategories = new Set(nodes.map((node) => node.category));
const newIndex = new Map<number, number>();
const shownCategories = categories.filter((_, index) => {
if (
!usedCategories.has(index) ||
index === MQTTNodeCategory.Broker ||
index === MQTTNodeCategory.Source
) {
return false;
}
newIndex.set(index, newIndex.size);
return true;
});
const hiddenCategoryNames = new Set(hiddenCategories);
// Taken before the nodes get their new category index below
const hiddenNodeIds = new Set(
nodes
.filter((node) =>
hiddenCategoryNames.has(categories[node.category!]?.name)
)
.map((node) => node.id)
);
const nodesById = new Map(nodes.map((node) => [node.id, node]));
// A focused device shows its own items, also when the legend switches their
// category off. A focused item shows only itself with its topics, so the
// other items of its device do not crowd them.
// Search matches show too, else a match the legend hides seems not found
const revealedNodeIds = new Set<string>(filter ? focusNodes : []);
if (focusedNode && nodesById.has(focusedNode)) {
revealedNodeIds.add(focusedNode);
if (
focusedNode.startsWith(DEVICE_PREFIX) ||
focusedNode.startsWith(NO_DEVICE_PREFIX)
) {
(childIds.get(focusedNode) ?? []).forEach((childId) => {
if (
!childId.startsWith(DEVICE_PREFIX) &&
!childId.startsWith(NO_DEVICE_PREFIX)
) {
revealedNodeIds.add(childId);
}
});
}
}
const isHidden = (node: NetworkNode) =>
hiddenNodeIds.has(node.id) && !revealedNodeIds.has(node.id);
const shownBelow = new Map<string, boolean>();
// Whether a node has a node below it that the legend shows
const hasShownBelow = (id: string): boolean => {
if (!shownBelow.has(id)) {
shownBelow.set(id, false);
shownBelow.set(
id,
(childIds.get(id) ?? []).some((childId) => {
const child = nodesById.get(childId);
return child && (!isHidden(child) || hasShownBelow(childId));
})
);
}
return shownBelow.get(id)!;
};
nodes.forEach((node) => {
// The legend hides the nodes of its unselected categories with their
// links. A hidden node with shown nodes below it would leave those
// unlinked, so it stays without a category, faded like the nodes outside
// a focus. A revealed node loses its category too, so the legend keeps it.
if (hiddenNodeIds.has(node.id) && revealedNodeIds.has(node.id)) {
node.category = undefined;
} else if (isHidden(node) && hasShownBelow(node.id)) {
if (!fadedNodes.has(node.id)) {
fadeNode(node);
}
node.category = undefined;
} else {
node.category = newIndex.get(node.category!);
}
});
links.forEach((link) => {
if (fadedNodes.has(link.source) || fadedNodes.has(link.target)) {
link.lineStyle = { ...link.lineStyle, opacity: FADED_OPACITY };
}
});
if (treeLayout) {
placeInTree(nodesById, childIds, (id) => {
const node = nodesById.get(id);
return !!node && !(isHidden(node) && !hasShownBelow(id));
});
}
return { nodes, links, categories: shownCategories };
}
@@ -0,0 +1,148 @@
export const parseJsonPayload = (payload: string): unknown => {
const trimmed = payload.trim();
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
return undefined;
}
try {
return JSON.parse(trimmed);
} catch (_err) {
return undefined;
}
};
const JSON_WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
/**
* Indents a JSON payload without parsing it into values, so numbers, duplicate
* keys and escapes stay exactly as received. Returns undefined when the payload
* is not a JSON object or array.
*/
export const prettyPrintJson = (payload: string): string | undefined => {
if (parseJsonPayload(payload) === undefined) {
return undefined;
}
const text = payload.trim();
let out = "";
let depth = 0;
let inString = false;
let escaped = false;
const newline = () => `\n${" ".repeat(depth)}`;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (inString) {
out += char;
if (escaped) {
escaped = false;
} else if (char === "\\") {
escaped = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (JSON_WHITESPACE.has(char)) {
continue;
}
if (char === "{" || char === "[") {
let next = i + 1;
while (JSON_WHITESPACE.has(text[next])) {
next++;
}
if (text[next] === (char === "{" ? "}" : "]")) {
out += char + text[next];
i = next;
continue;
}
depth++;
out += char + newline();
} else if (char === "}" || char === "]") {
depth--;
out += newline() + char;
} else if (char === ",") {
out += `,${newline()}`;
} else if (char === ":") {
out += ": ";
} else {
if (char === '"') {
inString = true;
}
out += char;
}
}
return out;
};
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
// Keys that need it are quoted, so `{"a.b": 1}` and `{"a": {"b": 1}}` or an
// array index and a numeric object key never end up on the same path.
const childPath = (prefix: string, key: string, isArray: boolean): string => {
if (isArray) {
return `${prefix}[${key}]`;
}
if (!IDENTIFIER.test(key)) {
return `${prefix}[${JSON.stringify(key)}]`;
}
return prefix ? `${prefix}.${key}` : key;
};
const flatten = (
value: unknown,
prefix: string,
out: Map<string, string>
): Map<string, string> => {
if (value !== null && typeof value === "object") {
const entries = Object.entries(value);
if (!entries.length && prefix) {
out.set(prefix, JSON.stringify(value));
}
const isArray = Array.isArray(value);
for (const [key, child] of entries) {
flatten(child, childPath(prefix, key, isArray), out);
}
} else {
out.set(prefix, JSON.stringify(value));
}
return out;
};
export interface PayloadChange {
key: string;
type: "added" | "removed" | "changed";
oldValue?: string;
newValue?: string;
}
// Returns undefined when the payloads cannot be compared key by key.
export const diffJsonPayloads = (
oldPayload: string,
newPayload: string
): PayloadChange[] | undefined => {
const oldJson = parseJsonPayload(oldPayload);
const newJson = parseJsonPayload(newPayload);
// Also when the root changes between object and array: both empty flatten alike.
if (
oldJson === undefined ||
newJson === undefined ||
Array.isArray(oldJson) !== Array.isArray(newJson)
) {
return undefined;
}
const oldFlat = flatten(oldJson, "", new Map());
const newFlat = flatten(newJson, "", new Map());
const changes: PayloadChange[] = [];
for (const [key, newValue] of newFlat) {
const oldValue = oldFlat.get(key);
if (oldValue === undefined) {
changes.push({ key, type: "added", newValue });
} else if (oldValue !== newValue) {
changes.push({ key, type: "changed", oldValue, newValue });
}
}
for (const [key, oldValue] of oldFlat) {
if (!newFlat.has(key)) {
changes.push({ key, type: "removed", oldValue });
}
}
return changes;
};
@@ -0,0 +1,418 @@
import { mdiClose, mdiContentCopy } from "@mdi/js";
import type { HassConfig } from "home-assistant-js-websocket";
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../../../../../common/decorators/consume";
import { storage } from "../../../../../common/decorators/storage";
import { transform } from "../../../../../common/decorators/transform";
import { formatTimeWithSeconds } from "../../../../../common/datetime/format_time";
import { fireEvent } from "../../../../../common/dom/fire_event";
import type { LocalizeKeys } from "../../../../../common/translations/localize";
import { copyToClipboard } from "../../../../../common/util/copy-clipboard";
import "../../../../../components/ha-icon-button";
import "../../../../../components/ha-switch";
import "../../../../../components/item/ha-list-item-option";
import "../../../../../components/list/ha-list-selectable";
import {
configContext,
internationalizationContext,
} from "../../../../../data/context";
import type { MQTTExplorerEntityTopic } from "../../../../../data/mqtt";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../../../../types";
import { showToast } from "../../../../../util/toast";
import { diffJsonPayloads, prettyPrintJson } from "./mqtt-payload";
export interface MQTTTopicMessage {
// Client side id, stable while the message is kept
id: number;
// The topic the message was published to, differs for wildcard subscriptions
topic: string;
payload: string;
qos: number;
retain: boolean;
time: Date;
// Received while the view was open, the others were stored by Home Assistant
live: boolean;
}
const CHANGE_SIGNS = { added: "+", removed: "−", changed: "~" } as const;
@customElement("mqtt-topic-messages")
class MqttTopicMessages extends LitElement {
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _config!: HassConfig;
@property({ attribute: false }) public topic!: MQTTExplorerEntityTopic;
// Newest first
@property({ attribute: false }) public messages: MQTTTopicMessage[] = [];
// The live subscription is active
@property({ type: Boolean }) public live = false;
// The QoS of the live subscription
@property({ type: Number }) public qos = 0;
@state() private _selectedId?: number;
@state()
@storage({
key: "mqtt-visualization-pretty",
state: true,
subscribe: false,
})
private _pretty = true;
// Every live message renders again, mostly with the same selected payload
private _prettyPrint = memoizeOne(prettyPrintJson);
private _diff = memoizeOne(diffJsonPayloads);
protected willUpdate(changedProps: PropertyValues<this>): void {
const previous = changedProps.get("topic");
if (
previous &&
(previous.topic !== this.topic.topic ||
previous.direction !== this.topic.direction)
) {
this._selectedId = undefined;
}
}
private _localize(key: string, values?: Record<string, unknown>): string {
return this._i18n.localize(
`ui.panel.config.mqtt.visualization.topic_view.${key}` as LocalizeKeys,
values as any
);
}
protected render(): TemplateResult {
const index = Math.max(
0,
this.messages.findIndex((msg) => msg.id === this._selectedId)
);
const selected = this.messages[index];
// A wildcard subscription receives messages of more than one topic
const previous = this.messages
.slice(index + 1)
.find((msg) => msg.topic === selected.topic);
const pretty = selected ? this._prettyPrint(selected.payload) : undefined;
const shownPayload =
this._pretty && pretty !== undefined ? pretty : selected?.payload;
const isPublish = this.topic.direction === "publish";
return html`
<div class="header">
<code class="topic">${this.topic.topic}</code>
<ha-icon-button
.path=${mdiClose}
.label=${this._i18n.localize("ui.common.close")}
@click=${this._close}
></ha-icon-button>
</div>
<div class="stats">
${
this.live
? this._localize("listening", { qos: this.qos })
: this._localize("not_listening")
}
</div>
<h3>${this._localize("messages", { count: this.messages.length })}</h3>
${
this.messages.length
? html`<ha-list-selectable
class="messages"
controlled
aria-label=${this._localize("messages", {
count: this.messages.length,
})}
@ha-list-item-selected=${this._selectMessage}
>
${repeat(
this.messages,
(msg) => msg.id,
(msg, i) => html`
<ha-list-item-option .selected=${i === index}>
<span slot="headline"
>${formatTimeWithSeconds(
msg.time,
this._i18n.locale,
this._config
)}</span
>
${
msg.topic !== this.topic.topic
? html`<span slot="supporting-text"
><code>${msg.topic}</code></span
>`
: nothing
}
<span slot="end" class="message-meta">
${this._localize("qos", { qos: msg.qos })}${
msg.retain
? html` · ${this._localize("retained")}`
: nothing
}${
// Only the newest message is marked live. A retained
// message comes from the broker's store, so is never live.
i === 0 && msg.live && !msg.retain
? html` · ${this._localize("live")}`
: nothing
}
</span>
</ha-list-item-option>
`
)}
</ha-list-selectable>`
: html`<p class="secondary">
${this._localize(isPublish ? "no_messages_sent" : "no_messages")}
</p>`
}
${
selected
? html`
<div class="section-header">
<h3>${this._localize("payload")}</h3>
${
pretty !== undefined
? html`<ha-switch
class="pretty"
.checked=${this._pretty}
@change=${this._handlePretty}
>${this._localize("pretty_print")}</ha-switch
>`
: nothing
}
<ha-icon-button
.path=${mdiContentCopy}
.label=${this._localize("copy_payload")}
@click=${this._copyPayload}
></ha-icon-button>
</div>
<pre dir="ltr">${shownPayload}</pre>
<h3>${this._localize("changes")}</h3>
${this._renderChanges(selected, previous)}
`
: nothing
}
`;
}
private _renderChanges(
selected: MQTTTopicMessage,
previous?: MQTTTopicMessage
): TemplateResult {
if (!previous) {
return html`<p class="secondary">${this._localize("no_previous")}</p>`;
}
if (previous.payload === selected.payload) {
return html`<p class="secondary">${this._localize("unchanged")}</p>`;
}
const changes = this._diff(previous.payload, selected.payload);
// Parsing hides changes in whitespace or in numbers beyond the safe range
if (!changes?.length) {
return html`
<div class="changes" dir="ltr">
${this._renderChange(
"removed",
"previous",
html`<span class="raw">${previous.payload}</span>`
)}
${this._renderChange(
"added",
"current",
html`<span class="raw">${selected.payload}</span>`
)}
</div>
`;
}
return html`
<div class="changes" dir="ltr">
${changes.map((change) =>
this._renderChange(
change.type,
change.type,
html`<code>${change.key}</code>:
${
change.type === "changed"
? `${change.oldValue} → ${change.newValue}`
: (change.newValue ?? change.oldValue)
}`
)
)}
</div>
`;
}
private _renderChange(
type: keyof typeof CHANGE_SIGNS,
label: "added" | "removed" | "changed" | "previous" | "current",
content: unknown
): TemplateResult {
return html`
<div class=${type}>
<span class="sign" aria-hidden="true">${CHANGE_SIGNS[type]}</span>
<span class="visually-hidden"
>${this._localize(`change_${label}`)}:</span
>
${content}
</div>
`;
}
private _selectMessage(ev: CustomEvent<number>): void {
this._selectedId = this.messages[ev.detail]?.id;
}
private _handlePretty(ev: Event): void {
this._pretty = (ev.target as HTMLInputElement).checked;
}
private async _copyPayload(): Promise<void> {
const selected =
this.messages.find((msg) => msg.id === this._selectedId) ??
this.messages[0];
if (!selected) {
return;
}
await copyToClipboard(selected.payload);
showToast(this, {
message: this._i18n.localize("ui.common.copied_clipboard"),
});
}
private _close(): void {
fireEvent(this, "mqtt-topic-messages-closed");
}
static readonly styles = css`
:host {
display: block;
min-width: 0;
}
.header,
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--ha-space-3);
}
.topic {
font-size: var(--ha-font-size-l);
word-break: break-all;
}
.stats,
.secondary {
color: var(--secondary-text-color);
}
h3 {
font-size: var(--ha-font-size-m);
font-weight: var(--ha-font-weight-medium);
margin: var(--ha-space-4) 0 var(--ha-space-2);
}
.section-header h3 {
flex: 1;
margin: var(--ha-space-2) 0 0;
}
.pretty {
margin-top: var(--ha-space-2);
font-size: var(--ha-font-size-s);
}
.messages {
display: block;
max-height: 220px;
overflow-y: auto;
border: 1px solid var(--divider-color);
border-radius: var(--ha-border-radius-md);
--ha-row-item-min-height: 32px;
--ha-row-item-padding-block: var(--ha-space-1);
}
.message-meta {
font-size: var(--ha-font-size-s);
color: var(--secondary-text-color);
white-space: nowrap;
}
pre,
.changes {
margin: 0;
padding: var(--ha-space-2);
max-height: 320px;
overflow: auto;
background-color: var(
--code-editor-background-color,
var(--secondary-background-color)
);
border-radius: var(--ha-border-radius-md);
font-family: var(--ha-font-family-code);
font-size: var(--ha-font-size-s);
word-break: break-all;
}
pre {
white-space: pre-wrap;
}
.changes {
position: relative;
}
/* Payloads that only differ in whitespace would look the same */
.raw {
white-space: pre-wrap;
}
.sign {
display: inline-block;
width: 1ch;
font-weight: var(--ha-font-weight-bold);
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.added {
color: var(--success-color);
}
.removed {
color: var(--error-color);
}
.changed {
color: var(--warning-color);
}
/* Rows a finger can hit, and no scroll area within the scrolling sheet */
@media (pointer: coarse) {
.messages {
max-height: 260px;
--ha-row-item-min-height: 48px;
}
pre,
.changes {
max-height: none;
}
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"mqtt-topic-messages": MqttTopicMessages;
}
interface HASSDomEvents {
"mqtt-topic-messages-closed": undefined;
}
}
+22 -19
View File
@@ -1,5 +1,7 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { ActionConfig } from "../../../data/lovelace/config/action";
import type { HomeAssistant } from "../../../types";
import type { HomeAssistantFormatters } from "../../../types";
interface Config {
entity?: string;
@@ -10,7 +12,7 @@ interface Config {
}
function computeActionTooltip(
hass: HomeAssistant,
localize: LocalizeFunc,
state: string,
config: ActionConfig,
isHold: boolean
@@ -20,36 +22,35 @@ function computeActionTooltip(
}
let tooltip = isHold
? hass.localize("ui.panel.lovelace.cards.picture-elements.hold")
: hass.localize("ui.panel.lovelace.cards.picture-elements.tap");
? localize("ui.panel.lovelace.cards.picture-elements.hold")
: localize("ui.panel.lovelace.cards.picture-elements.tap");
switch (config.action) {
case "navigate":
tooltip += ` ${hass.localize(
tooltip += ` ${localize(
"ui.panel.lovelace.cards.picture-elements.navigate_to",
{ location: config.navigation_path }
)}`;
break;
case "url":
tooltip += ` ${hass.localize(
"ui.panel.lovelace.cards.picture-elements.url",
{ url_path: config.url_path }
)}`;
tooltip += ` ${localize("ui.panel.lovelace.cards.picture-elements.url", {
url_path: config.url_path,
})}`;
break;
case "toggle":
tooltip += ` ${hass.localize(
tooltip += ` ${localize(
"ui.panel.lovelace.cards.picture-elements.toggle",
{ name: state }
)}`;
break;
case "call-service":
tooltip += `${hass.localize(
tooltip += `${localize(
"ui.panel.lovelace.cards.picture-elements.perform_action",
{ name: config.service }
)}`;
break;
case "more-info":
tooltip += `${hass.localize(
tooltip += `${localize(
"ui.panel.lovelace.cards.picture-elements.more_info",
{ name: state }
)}`;
@@ -59,7 +60,12 @@ function computeActionTooltip(
return tooltip;
}
export const computeTooltip = (hass: HomeAssistant, config: Config): string => {
export const computeTooltip = (
localize: LocalizeFunc,
formatEntityName: HomeAssistantFormatters["formatEntityName"],
config: Config,
stateObj: HassEntity | undefined
): string => {
if (config.title === null) {
return "";
}
@@ -71,10 +77,7 @@ export const computeTooltip = (hass: HomeAssistant, config: Config): string => {
let stateName = "";
if (config.entity) {
stateName =
config.entity in hass.states
? hass.formatEntityName(hass.states[config.entity])
: config.entity;
stateName = stateObj ? formatEntityName(stateObj) : config.entity;
}
if (!config.tap_action && !config.hold_action) {
@@ -82,10 +85,10 @@ export const computeTooltip = (hass: HomeAssistant, config: Config): string => {
}
const tapTooltip = config.tap_action
? computeActionTooltip(hass, stateName, config.tap_action, false)
? computeActionTooltip(localize, stateName, config.tap_action, false)
: "";
const holdTooltip = config.hold_action
? computeActionTooltip(hass, stateName, config.hold_action, true)
? computeActionTooltip(localize, stateName, config.hold_action, true)
: "";
const newline = tapTooltip && holdTooltip ? "\n" : "";
+5 -7
View File
@@ -1,24 +1,22 @@
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { ConfirmationRestrictionConfig } from "../../../data/lovelace/config/action";
import { showConfirmationDialog } from "../../../dialogs/generic/show-dialog-box";
import type { HomeAssistant } from "../../../types";
export const confirmAction = async (
node: HTMLElement,
hass: HomeAssistant,
userId: string | undefined,
localize: LocalizeFunc,
config: ConfirmationRestrictionConfig,
action: string
): Promise<boolean> => {
if (
config.exemptions &&
config.exemptions.some((e) => e.user === hass!.user?.id)
) {
if (config.exemptions && config.exemptions.some((e) => e.user === userId)) {
return true;
}
return showConfirmationDialog(node, {
text:
config.text ||
hass.localize("ui.panel.lovelace.cards.actions.action_confirmation", {
localize("ui.panel.lovelace.cards.actions.action_confirmation", {
action,
}),
title: config.title,
@@ -321,7 +321,13 @@ function checkLocationCondition(
if (!isValidTarget(condition.target)) {
return false;
}
const zones = resolveLocationZones(hass, condition.target);
const zones = resolveLocationZones(
hass.states,
hass.entities,
hass.devices,
hass.areas,
condition.target
);
const inZones = stateObj.attributes.in_zones;
// Legacy device trackers don't report `in_zones` (person only adds
// zone.home for them), so their state, the active zone name, is all there
@@ -414,55 +420,59 @@ const resolvedZonesCache = new WeakMap<
* currently have a state.
*/
export function resolveLocationZones(
hass: ConditionHass,
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
target: HassServiceTargetWithExclude
): string[] {
// Checked on every call rather than cached, so a zone that loses its state
// is dropped and a directly selected zone that appears later is picked up.
return resolveTargetZones(hass, target).filter(
(zoneId) => zoneId in hass.states
return resolveTargetZones(states, entities, devices, areas, target).filter(
(zoneId) => zoneId in states
);
}
function resolveTargetZones(
hass: ConditionHass,
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
target: HassServiceTargetWithExclude
): string[] {
const cached = resolvedZonesCache.get(target);
if (
cached &&
cached.entities === hass.entities &&
cached.devices === hass.devices &&
cached.areas === hass.areas
cached.entities === entities &&
cached.devices === devices &&
cached.areas === areas
) {
return cached.zones;
}
// Resolving skips entities without a state, such as zones while they
// reload. Give registered zones a placeholder state so the result only
// depends on the registries; zones without a state are left out per check.
let states = hass.states;
for (const entityId of Object.keys(hass.entities)) {
if (computeDomain(entityId) === "zone" && !(entityId in states)) {
if (states === hass.states) {
states = { ...hass.states };
let zoneStates = states;
for (const entityId of Object.keys(entities)) {
if (computeDomain(entityId) === "zone" && !(entityId in zoneStates)) {
if (zoneStates === states) {
zoneStates = { ...states };
}
states[entityId] = { entity_id: entityId, attributes: {} } as HassEntity;
zoneStates[entityId] = {
entity_id: entityId,
attributes: {},
} as HassEntity;
}
}
const zones = resolveEntityIDs(
states === hass.states ? hass : { ...hass, states },
{ states: zoneStates, entities, devices },
target,
hass.entities,
hass.devices,
hass.areas,
entities,
devices,
areas,
ZONE_TARGET_SELECTOR
).filter((entityId) => computeDomain(entityId) === "zone");
resolvedZonesCache.set(target, {
entities: hass.entities,
devices: hass.devices,
areas: hass.areas,
zones,
});
resolvedZonesCache.set(target, { entities, devices, areas, zones });
return zones;
}
@@ -1,19 +1,23 @@
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, state, property } from "lit/decorators";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { preserveUnchangedEntityStatesRecord } from "../../../common/decorators/consume-context-entry";
import {
consumeLocalize,
preserveUnchangedEntityStatesRecord,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/entity/state-badge";
import { statesContext } from "../../../data/context";
import { formattersContext, statesContext } from "../../../data/context";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import type { HomeAssistantFormatters } from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { computeTooltip } from "../common/compute-tooltip";
import { actionHandler } from "../common/directives/action-handler-directive";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { handleAction } from "../common/handle-action";
import { hasAction } from "../common/has-action";
import "../../../components/chips/ha-assist-chip";
import "../../../components/chips/ha-chip-set";
@@ -21,9 +25,6 @@ import { haStyleScrollbar } from "../../../resources/styles";
@customElement("hui-buttons-base")
export class HuiButtonsBase extends LitElement {
@property({ attribute: false })
public hass!: HomeAssistant;
@property({ attribute: false })
public configEntities?: EntitiesCardEntityConfig[];
@@ -43,7 +44,27 @@ export class HuiButtonsBase extends LitElement {
})
private _entityStates: Record<string, HassEntity | undefined> = {};
protected render(): TemplateResult {
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName?: HomeAssistantFormatters["formatEntityName"];
protected render() {
if (!this._localize || !this._formatEntityName) {
return nothing;
}
const localize = this._localize;
const formatEntityName = this._formatEntityName;
return html`
<ha-chip-set class="ha-scrollbar">
${(this.configEntities || []).map((entityConf) => {
@@ -53,7 +74,7 @@ export class HuiButtonsBase extends LitElement {
(entityConf.show_name && stateObj) ||
(entityConf.name && entityConf.show_name !== false)
? stateObj
? this.hass.formatEntityName(stateObj, entityConf.name)
? formatEntityName(stateObj, entityConf.name)
: typeof entityConf.name === "string"
? entityConf.name
: ""
@@ -75,7 +96,12 @@ export class HuiButtonsBase extends LitElement {
entityConf.show_icon !== false
? html`
<state-badge
title=${computeTooltip(this.hass, entityConf)}
title=${computeTooltip(
localize,
formatEntityName,
entityConf,
stateObj
)}
.stateObj=${stateObj}
.overrideIcon=${entityConf.icon}
.overrideImage=${entityConf.image}
@@ -98,7 +124,10 @@ export class HuiButtonsBase extends LitElement {
> &
ActionHandlerEvent
) {
handleAction(this, this.hass, ev.currentTarget.config, ev.detail.action);
fireEvent(this, "hass-action", {
config: ev.currentTarget.config,
action: ev.detail.action,
});
}
static get styles(): CSSResultGroup {
@@ -34,10 +34,7 @@ export class HuiBadgeVisibilityEditor extends LitElement {
render() {
const conditions = this.config.visibility ?? [];
return html`
<ha-visibility-status
.hass=${this.hass}
.conditions=${conditions}
></ha-visibility-status>
<ha-visibility-status .conditions=${conditions}></ha-visibility-status>
<ha-card-conditions-editor
.hass=${this.hass}
.conditions=${conditions}
@@ -34,10 +34,7 @@ export class HuiCardVisibilityEditor extends LitElement {
render() {
const conditions = this.config.visibility ?? [];
return html`
<ha-visibility-status
.hass=${this.hass}
.conditions=${conditions}
></ha-visibility-status>
<ha-visibility-status .conditions=${conditions}></ha-visibility-status>
<ha-card-conditions-editor
.hass=${this.hass}
.conditions=${conditions}
@@ -15,6 +15,7 @@ import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { ensureArray } from "../../../../common/array/ensure-array";
import {
isLogicalCondition,
@@ -27,6 +28,7 @@ import { dynamicElement } from "../../../../common/dom/dynamic-element-directive
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import { capitalizeFirstLetter } from "../../../../common/string/capitalize-first-letter";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { handleStructError } from "../../../../common/structs/handle-errors";
import "../../../../components/automation/ha-automation-condition-summary";
import "../../../../components/automation/ha-automation-row-event-chip";
@@ -252,6 +254,8 @@ export class HaCardConditionEditor extends LitElement {
@consume({ context: conditionsEntityContext, subscribe: true })
private _entityContext?: ConditionsEntityContext;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
private get _noEntity(): boolean {
return this._entityContext?.mode === "filter";
}
@@ -356,7 +360,7 @@ export class HaCardConditionEditor extends LitElement {
this._uiWarnings = [];
} catch (err) {
this._uiWarnings = handleStructError(
this.hass.localize,
this._localize,
err as Error
).warnings;
this._uiAvailable = false;
@@ -372,7 +376,10 @@ export class HaCardConditionEditor extends LitElement {
}
}
if (changedProperties.has("condition") || changedProperties.has("hass")) {
if (
changedProperties.has("condition") ||
(changedProperties as Map<string, unknown>).has("_localize")
) {
this._updateLiveTest();
}
}
@@ -396,7 +403,7 @@ export class HaCardConditionEditor extends LitElement {
this._hideLiveTest(this._condition)
) {
this._override = "unknown";
this._conditionEvaluator.observe(undefined, this.hass);
this._conditionEvaluator.observe(undefined);
this._liveTestResult = { state: "unknown" };
return;
}
@@ -417,10 +424,10 @@ export class HaCardConditionEditor extends LitElement {
if (this.__clientInvalid) {
this._override = "invalid";
this._conditionEvaluator.observe(undefined, this.hass);
this._conditionEvaluator.observe(undefined);
this._liveTestResult = {
state: "invalid",
message: this.hass.localize(
message: this._localize(
"ui.panel.lovelace.editor.condition-editor.live_test_state.invalid"
),
};
@@ -432,7 +439,7 @@ export class HaCardConditionEditor extends LitElement {
this._override = undefined;
this._liveTestResult = { state: "unknown" };
}
this._conditionEvaluator.observe(this.__observed, this.hass, () =>
this._conditionEvaluator.observe(this.__observed, () =>
this._liveTestContext()
);
}
@@ -449,7 +456,7 @@ export class HaCardConditionEditor extends LitElement {
result === "visible" ? "pass" : result === "hidden" ? "fail" : "unknown";
this._liveTestResult = {
state: liveState,
message: this.hass.localize(
message: this._localize(
`ui.panel.lovelace.editor.condition-editor.live_test_state.${liveState}`
),
};
@@ -488,7 +495,7 @@ export class HaCardConditionEditor extends LitElement {
? nothing
: html`<ha-automation-row-live-test
.state=${this._liveTestResult.state}
.label=${this.hass.localize(
.label=${this._localize(
`ui.panel.lovelace.editor.condition-editor.live_test_state.${this._liveTestResult.state}`
)}
></ha-automation-row-live-test>`
@@ -518,7 +525,7 @@ export class HaCardConditionEditor extends LitElement {
this._entityReg
)
)
: this.hass.localize(
: this._localize(
`ui.panel.lovelace.editor.condition-editor.condition.${condition.condition}.label`
) || condition.condition
}
@@ -532,10 +539,10 @@ export class HaCardConditionEditor extends LitElement {
>
${
this._testingResult
? this.hass.localize(
? this._localize(
"ui.panel.lovelace.editor.condition-editor.testing_pass"
)
: this.hass.localize(
: this._localize(
"ui.panel.lovelace.editor.condition-editor.testing_error"
)
}
@@ -547,7 +554,7 @@ export class HaCardConditionEditor extends LitElement {
? html`
<ha-alert
alert-type="warning"
.title=${this.hass.localize(
.title=${this._localize(
"ui.errors.config.editor_not_supported"
)}
>
@@ -563,9 +570,7 @@ export class HaCardConditionEditor extends LitElement {
`
: nothing
}
${this.hass.localize(
"ui.errors.config.edit_in_yaml_supported"
)}
${this._localize("ui.errors.config.edit_in_yaml_supported")}
</ha-alert>
`
: nothing
@@ -620,7 +625,7 @@ export class HaCardConditionEditor extends LitElement {
>
<ha-icon-button
slot="trigger"
.label=${this.hass.localize("ui.common.menu")}
.label=${this._localize("ui.common.menu")}
.path=${mdiDotsVertical}
>
</ha-icon-button>
@@ -629,7 +634,7 @@ export class HaCardConditionEditor extends LitElement {
hideLiveTest
? nothing
: html`<ha-dropdown-item value="test">
${this.hass.localize(
${this._localize(
"ui.panel.lovelace.editor.condition-editor.test"
)}
<ha-svg-icon slot="icon" .path=${mdiFlask}></ha-svg-icon>
@@ -637,32 +642,32 @@ export class HaCardConditionEditor extends LitElement {
}
<ha-dropdown-item value="duplicate">
${this.hass.localize("ui.panel.lovelace.editor.edit_card.duplicate")}
${this._localize("ui.panel.lovelace.editor.edit_card.duplicate")}
<ha-svg-icon slot="icon" .path=${mdiContentDuplicate}></ha-svg-icon>
</ha-dropdown-item>
<ha-dropdown-item value="copy">
${this.hass.localize("ui.panel.lovelace.editor.edit_card.copy")}
${this._localize("ui.panel.lovelace.editor.edit_card.copy")}
<ha-svg-icon slot="icon" .path=${mdiContentCopy}></ha-svg-icon>
</ha-dropdown-item>
<ha-dropdown-item value="cut">
${this.hass.localize("ui.panel.lovelace.editor.edit_card.cut")}
${this._localize("ui.panel.lovelace.editor.edit_card.cut")}
<ha-svg-icon slot="icon" .path=${mdiContentCut}></ha-svg-icon>
</ha-dropdown-item>
<ha-dropdown-item value="move_up" .disabled=${this.first}>
${this.hass.localize("ui.panel.config.automation.editor.move_up")}
${this._localize("ui.panel.config.automation.editor.move_up")}
<ha-svg-icon slot="icon" .path=${mdiArrowUp}></ha-svg-icon>
</ha-dropdown-item>
<ha-dropdown-item value="move_down" .disabled=${this.last}>
${this.hass.localize("ui.panel.config.automation.editor.move_down")}
${this._localize("ui.panel.config.automation.editor.move_down")}
<ha-svg-icon slot="icon" .path=${mdiArrowDown}></ha-svg-icon>
</ha-dropdown-item>
<ha-dropdown-item value="toggle_yaml" .disabled=${!this._uiAvailable}>
${this.hass.localize(
${this._localize(
`ui.panel.lovelace.editor.edit_view.edit_${!this._yamlMode ? "yaml" : "ui"}`
)}
<ha-svg-icon slot="icon" .path=${mdiPlaylistEdit}></ha-svg-icon>
@@ -671,7 +676,7 @@ export class HaCardConditionEditor extends LitElement {
<wa-divider></wa-divider>
<ha-dropdown-item variant="danger" value="delete">
${this.hass!.localize("ui.common.delete")}
${this._localize("ui.common.delete")}
<ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
</ha-dropdown-item>
</ha-dropdown>
@@ -763,10 +768,7 @@ export class HaCardConditionEditor extends LitElement {
// Automation editors emit this when UI mode can't handle the config.
private _handleUiModeNotAvailable(ev: CustomEvent) {
ev.stopPropagation();
this._uiWarnings = handleStructError(
this.hass.localize,
ev.detail
).warnings;
this._uiWarnings = handleStructError(this._localize, ev.detail).warnings;
this._uiAvailable = false;
if (!this._yamlMode) {
this._yamlMode = true;
@@ -3,12 +3,13 @@ import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { ConditionEvaluation } from "../../../../common/controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../../../../common/controllers/condition-evaluator-controller";
import "../../../../components/ha-alert";
import "../../../../components/ha-svg-icon";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { HaRowItem } from "../../../../components/item/ha-row-item";
import type { HomeAssistant } from "../../../../types";
import type {
ConditionContext,
VisibilityCondition,
@@ -39,8 +40,6 @@ const STATE_ICONS: Record<VisibilityState, string> = {
*/
@customElement("ha-visibility-status")
export class HaVisibilityStatus extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false })
public conditions: VisibilityCondition[] = [];
@@ -48,6 +47,8 @@ export class HaVisibilityStatus extends LitElement {
@consume({ context: conditionsEntityContext, subscribe: true })
private _entityContext?: ConditionsEntityContext;
@state() @consumeLocalize() private _localize?: LocalizeFunc;
@property()
public state: VisibilityState = "visible";
@@ -70,7 +71,6 @@ export class HaVisibilityStatus extends LitElement {
protected willUpdate(changedProperties: PropertyValues<this>): void {
super.willUpdate(changedProperties);
if (
changedProperties.has("hass") ||
changedProperties.has("conditions") ||
(changedProperties as Map<string, unknown>).has("_entityContext")
) {
@@ -93,12 +93,12 @@ export class HaVisibilityStatus extends LitElement {
>
<ha-svg-icon slot="icon" .path=${STATE_ICONS[this.state]}></ha-svg-icon>
<div class="headline">
${this.hass?.localize(
${this._localize?.(
`ui.panel.lovelace.editor.condition-editor.visibility_status.${this.state}.headline`
)}
</div>
<div class="supporting">
${this.hass?.localize(
${this._localize?.(
`ui.panel.lovelace.editor.condition-editor.visibility_status.${this.state}.supporting${(this.conditions?.length ?? 0) === 0 ? "_empty" : ""}`
)}
</div>
@@ -117,7 +117,7 @@ export class HaVisibilityStatus extends LitElement {
if (conditions.length === 0) {
this._override = "visible";
this._conditionEvaluator.observe(undefined, this.hass);
this._conditionEvaluator.observe(undefined);
this.state = "visible";
return;
}
@@ -141,7 +141,7 @@ export class HaVisibilityStatus extends LitElement {
if (this.__clientInvalid) {
this._override = "invalid";
this._conditionEvaluator.observe(undefined, this.hass);
this._conditionEvaluator.observe(undefined);
this.state = "invalid";
return;
}
@@ -151,9 +151,7 @@ export class HaVisibilityStatus extends LitElement {
this._override = undefined;
this.state = "unknown";
}
this._conditionEvaluator.observe(this.__observed, this.hass, () =>
this._context()
);
this._conditionEvaluator.observe(this.__observed, () => this._context());
}
private _applyResult(result: ConditionEvaluation, error?: string) {
@@ -1,3 +1,4 @@
import type { ContextType } from "@lit/context";
import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
@@ -14,6 +15,7 @@ import {
} from "superstruct";
import type { HassEntity } from "home-assistant-js-websocket";
import { ensureArray } from "../../../../../common/array/ensure-array";
import { consume } from "../../../../../common/decorators/consume";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { computeDomain } from "../../../../../common/entity/compute_domain";
import { computeStateName } from "../../../../../common/entity/compute_state_name";
@@ -24,6 +26,11 @@ import "../../../../../components/ha-alert";
import "../../../../../components/ha-form/ha-form";
import type { HaFormSchema } from "../../../../../components/ha-form/types";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import {
internationalizationContext,
registriesContext,
statesContext,
} from "../../../../../data/context";
import { targetStruct } from "../../../../../data/script";
import type { HomeAssistant } from "../../../../../types";
import {
@@ -53,17 +60,14 @@ const LOCALIZE_PREFIX =
*/
function missingZoneId(
name: string,
hass: HomeAssistant,
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
reserved: Set<string>
): string {
const baseId = `zone.${slugify(name)}`;
let entityId = baseId;
let i = 2;
while (
entityId in hass.states ||
entityId in hass.entities ||
reserved.has(entityId)
) {
while (entityId in states || entityId in entities || reserved.has(entityId)) {
entityId = `${baseId}_${i}`;
i++;
}
@@ -76,13 +80,14 @@ function missingZoneId(
*/
export function migrateLocationCondition(
condition: LocationCondition,
hass: HomeAssistant
states: HomeAssistant["states"],
entities: HomeAssistant["entities"]
): LocationCondition {
// The person state is "home" for zone.home, otherwise the zone name.
// Zone names aren't unique, and the old condition matched every zone with
// the name, so keep all of them.
const zoneIdsByName = new Map<string, string[]>();
for (const stateObj of Object.values(hass.states)) {
for (const stateObj of Object.values(states)) {
const name = stateObj.attributes.friendly_name;
if (
stateObj.entity_id.startsWith("zone.") &&
@@ -116,7 +121,7 @@ export function migrateLocationCondition(
} else if (name !== "home" && name !== "not_home") {
// Names that match no zone are kept, so the picker shows them as not
// found instead of silently removing them.
const entityId = missingZoneId(name, hass, missingIds);
const entityId = missingZoneId(name, states, entities, missingIds);
missingIds.add(entityId);
entityIds.add(entityId);
}
@@ -134,7 +139,17 @@ export function migrateLocationCondition(
@customElement("ha-card-condition-location")
export class HaCardConditionLocation extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@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: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@property({ attribute: false }) public condition!: LocationCondition;
@@ -148,7 +163,7 @@ export class HaCardConditionLocation extends LitElement {
@state() private _migrated = false;
// The zone states `_data` was built from, including registered zones and
// zones it names that have no state, so hass updates that change no zone
// zones it names that have no state, so state updates that change no zone
// skip the migration.
private _zoneStates?: Map<string, HassEntity | undefined>;
@@ -172,8 +187,12 @@ export class HaCardConditionLocation extends LitElement {
}
}
protected willUpdate(changedProps: PropertyValues<this>): void {
if (!changedProps.has("condition") && !changedProps.has("hass")) {
protected willUpdate(changedProps: PropertyValues): void {
if (
!changedProps.has("condition") &&
!changedProps.has("_states") &&
!changedProps.has("_registries")
) {
return;
}
if (this.condition.locations === undefined) {
@@ -182,26 +201,40 @@ export class HaCardConditionLocation extends LitElement {
return;
}
this._migrated = true;
if (!this._states || !this._registries) {
return;
}
const entities = this._registries.entities;
const entitiesChanged =
changedProps.has("_registries") &&
(
changedProps.get("_registries") as
ContextType<typeof registriesContext> | undefined
)?.entities !== entities;
// Redo only when a zone state or the entity registry changes, so a
// renamed, added or removed zone is picked up.
if (
!changedProps.has("condition") &&
changedProps.get("hass")?.entities === this.hass.entities &&
!entitiesChanged &&
!this._zonesChanged()
) {
return;
}
const data = migrateLocationCondition(this.condition, this.hass);
const data = migrateLocationCondition(
this.condition,
this._states,
entities
);
this._zoneStates = new Map();
for (const entityId of [
...Object.keys(this.hass.states),
...Object.keys(this.hass.entities),
...Object.keys(this._states),
...Object.keys(entities),
...ensureArray(data.target?.entity_id ?? []),
]) {
if (computeDomain(entityId) !== "zone") {
continue;
}
this._zoneStates.set(entityId, this.hass.states[entityId]);
this._zoneStates.set(entityId, this._states[entityId]);
}
// Keep the same object when nothing changed so the form doesn't re-render.
if (!deepEqual(data, this._data)) {
@@ -214,7 +247,7 @@ export class HaCardConditionLocation extends LitElement {
return true;
}
for (const [entityId, stateObj] of this._zoneStates) {
if (this.hass.states[entityId] !== stateObj) {
if (this._states[entityId] !== stateObj) {
return true;
}
}
@@ -261,11 +294,23 @@ export class HaCardConditionLocation extends LitElement {
/** Selected passive zones, which never match `active_zone`. */
private _passiveZones(): string[] {
if (this._data?.match_mode !== "active_zone" || !this._data.target) {
if (
this._data?.match_mode !== "active_zone" ||
!this._data.target ||
!this._states ||
!this._registries
) {
return [];
}
return resolveLocationZones(this.hass, this._data.target)
.map((zoneId) => this.hass.states[zoneId])
const { entities, devices, areas } = this._registries;
return resolveLocationZones(
this._states,
entities,
devices,
areas,
this._data.target
)
.map((zoneId) => this._states[zoneId])
.filter((stateObj) => stateObj?.attributes.passive)
.map((stateObj) => computeStateName(stateObj));
}
@@ -280,15 +325,14 @@ export class HaCardConditionLocation extends LitElement {
this._migrated
? html`
<ha-alert alert-type="info">
${this.hass.localize(`${LOCALIZE_PREFIX}.migrated`)}
${this._i18n.localize(`${LOCALIZE_PREFIX}.migrated`)}
</ha-alert>
`
: nothing
}
<ha-form
.hass=${this.hass}
.data=${this._formData(this._data)}
.schema=${this._schema(this.hass.localize)}
.schema=${this._schema(this._i18n.localize)}
.disabled=${this.disabled}
@value-changed=${this._valueChanged}
.computeLabel=${this._computeLabelCallback}
@@ -298,9 +342,9 @@ export class HaCardConditionLocation extends LitElement {
passiveZones.length
? html`
<ha-alert alert-type="warning">
${this.hass.localize(`${LOCALIZE_PREFIX}.passive_zones`, {
${this._i18n.localize(`${LOCALIZE_PREFIX}.passive_zones`, {
count: passiveZones.length,
zones: formatListWithAnds(this.hass.locale, passiveZones),
zones: formatListWithAnds(this._i18n.locale, passiveZones),
})}
</ha-alert>
`
@@ -334,10 +378,10 @@ export class HaCardConditionLocation extends LitElement {
}
private _computeLabelCallback = (schema: HaFormSchema): string =>
this.hass.localize(`${LOCALIZE_PREFIX}.${schema.name}`);
this._i18n.localize(`${LOCALIZE_PREFIX}.${schema.name}`);
private _computeHelperCallback = (schema: HaFormSchema): string =>
this.hass.localize(`${LOCALIZE_PREFIX}.${schema.name}_helper`);
this._i18n.localize(`${LOCALIZE_PREFIX}.${schema.name}_helper`);
static styles = css`
:host {
@@ -151,7 +151,6 @@ export class HuiConditionalCardEditor
`
: html`
<ha-visibility-status
.hass=${this.hass}
.conditions=${this._config.conditions ?? []}
></ha-visibility-status>
<ha-card-conditions-editor
@@ -89,7 +89,7 @@ export class HuiGaugeCardEditor
}
private _schema = memoizeOne(
(localize: LocalizeFunc, entityId?: string) =>
(localize: LocalizeFunc) =>
[
{
name: "entity",
@@ -103,10 +103,10 @@ export class HuiGaugeCardEditor
name: "attribute",
selector: {
attribute: {
entity_id: entityId,
hide_attributes: NON_NUMERIC_ATTRIBUTES,
},
},
context: { filter_entity: "entity" },
},
{
name: "name",
@@ -269,7 +269,7 @@ export class HuiGaugeCardEditor
return nothing;
}
const schema = this._schema(this.hass.localize, this._config!.entity);
const schema = this._schema(this.hass.localize);
const data = {
color_mode: this._colorMode(this._config!),
...this._config,
@@ -1,23 +1,19 @@
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../../common/decorators/consume-context-entry";
import { transform } from "../../../../common/decorators/transform";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { FormatEntityAttributeValueFunc } from "../../../../common/translations/entity-state";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-form/ha-form";
import type { SchemaUnion } from "../../../../components/ha-form/types";
import { formattersContext } from "../../../../data/context";
import type { LightEntity } from "../../../../data/light";
import type {
HomeAssistantFormatters,
ValueChangedEvent,
} from "../../../../types";
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import type { LightEntity } from "../../../../data/light";
import type { ValueChangedEvent } from "../../../../types";
import type {
LightEffectCardFeatureConfig,
LovelaceCardFeatureContext,
@@ -25,10 +21,20 @@ import type {
import type { LovelaceCardFeatureEditor } from "../../types";
import {
customizableListData,
customizableListSchema,
processCustomizableListValue,
} from "./customizable-list-feature";
const SCHEMA = [
{ name: "customize", selector: { boolean: {} } },
{
name: "effects",
visible: { field: "customize", value: true },
selector: {
state: { attribute: "effect", multiple: true, reorder: true },
},
},
] as const satisfies readonly HaFormSchema[];
@customElement("hui-light-effect-card-feature-editor")
export class HuiLightEffectCardFeatureEditor
extends LitElement
@@ -40,13 +46,6 @@ export class HuiLightEffectCardFeatureEditor
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
private _stateObj?: LightEntity;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<HomeAssistantFormatters, FormatEntityAttributeValueFunc>({
transformer: (formatters) => formatters?.formatEntityAttributeValue,
})
private _formatEntityAttributeValue!: FormatEntityAttributeValueFunc;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _config?: LightEffectCardFeatureConfig;
@@ -55,20 +54,9 @@ export class HuiLightEffectCardFeatureEditor
this._config = config;
}
private _schema = memoizeOne(
(
formatEntityAttributeValue: FormatEntityAttributeValueFunc,
stateObj: LightEntity | undefined
) =>
customizableListSchema({
field: "effects",
options:
stateObj?.attributes.effect_list?.map((effect) => ({
value: effect,
label: formatEntityAttributeValue(stateObj, "effect", effect),
})) ?? [],
})
);
private _formContext = memoizeOne((entityId: string | undefined) => ({
filter_entity: entityId,
}));
protected render() {
if (!this._config) {
@@ -76,15 +64,12 @@ export class HuiLightEffectCardFeatureEditor
}
const data = customizableListData(this._config, "effects");
const schema = this._schema(
this._formatEntityAttributeValue,
this._stateObj
);
return html`
<ha-form
.data=${data}
.schema=${schema}
.schema=${SCHEMA}
.context=${this._formContext(this.context?.entity_id)}
.computeLabel=${this._computeLabelCallback}
@value-changed=${this._valueChanged}
></ha-form>
@@ -103,9 +88,7 @@ export class HuiLightEffectCardFeatureEditor
fireEvent(this, "config-changed", { config });
}
private _computeLabelCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) =>
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) =>
this._localize(
`ui.panel.lovelace.editor.features.types.light-effect.${schema.name}`
);
@@ -16,10 +16,7 @@ export class HuiDialogEditSection extends LitElement {
render() {
const conditions = this.config.visibility ?? [];
return html`
<ha-visibility-status
.hass=${this.hass}
.conditions=${conditions}
></ha-visibility-status>
<ha-visibility-status .conditions=${conditions}></ha-visibility-status>
<ha-card-conditions-editor
.hass=${this.hass}
.conditions=${conditions}
@@ -1,12 +1,21 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-icon";
import { formattersContext } from "../../../data/context";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import type { HomeAssistantFormatters } from "../../../types";
import { computeTooltip } from "../common/compute-tooltip";
import { actionHandler } from "../common/directives/action-handler-directive";
import { handleAction } from "../common/handle-action";
import { hasAction } from "../common/has-action";
import type { LovelacePictureElementEditor } from "../types";
import type {
@@ -26,14 +35,30 @@ export class HuiIconElement extends LitElement implements LovelaceElement {
return { type: "icon", icon: "mdi:alert-circle" };
}
public hass?: HomeAssistant;
// Pointer gestures are delegated to the picture-elements card's routing;
// this element keeps keyboard activation (see LovelaceElement).
public delegatedActions = false;
@state() private _config?: IconElementConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName?: HomeAssistantFormatters["formatEntityName"];
public constructor() {
super();
// Listen on the host so both the own (keyboard) gesture path and an
@@ -71,14 +96,19 @@ export class HuiIconElement extends LitElement implements LovelaceElement {
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config || !this._localize || !this._formatEntityName) {
return nothing;
}
return html`
<ha-icon
.icon=${this._config.icon}
.title=${computeTooltip(this.hass, this._config)}
.title=${computeTooltip(
this._localize,
this._formatEntityName,
this._config,
this._stateObj
)}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config!.hold_action),
hasDoubleClick: hasAction(this._config!.double_tap_action),
@@ -92,7 +122,10 @@ export class HuiIconElement extends LitElement implements LovelaceElement {
}
private _handleAction(ev: ActionHandlerEvent) {
handleAction(this, this.hass!, this._config!, ev.detail.action!);
fireEvent(this, "hass-action", {
config: this._config!,
action: ev.detail.action,
});
}
static styles = css`
@@ -79,7 +79,14 @@ export class HuiImageElement extends LitElement implements LovelaceElement {
.cameraView=${this._config.camera_view}
.filter=${this._config.filter}
.stateFilter=${this._config.state_filter}
.title=${computeTooltip(this.hass, this._config)}
.title=${computeTooltip(
this.hass.localize,
this.hass.formatEntityName,
this._config,
this._config.entity
? this.hass.states[this._config.entity]
: undefined
)}
.aspectRatio=${this._config.aspect_ratio}
.darkModeImage=${this._config.dark_mode_image}
.darkModeFilter=${this._config.dark_mode_filter}
@@ -1,18 +1,28 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/entity/state-badge";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistant,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import { computeTooltip } from "../common/compute-tooltip";
import { actionHandler } from "../common/directives/action-handler-directive";
import { findEntities } from "../common/find-entities";
import { handleAction } from "../common/handle-action";
import { hasAction } from "../common/has-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import "../components/hui-warning-element";
import type { LovelacePictureElementEditor } from "../types";
@@ -50,14 +60,37 @@ export class HuiStateIconElement extends LitElement implements LovelaceElement {
return { type: "state-icon", entity: foundEntities[0] || "" };
}
@property({ attribute: false }) public hass?: HomeAssistant;
// Pointer gestures are delegated to the picture-elements card's routing;
// this element keeps keyboard activation (see LovelaceElement).
public delegatedActions = false;
@state() private _config?: StateIconElementConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig?: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName?: HomeAssistantFormatters["formatEntityName"];
public constructor() {
super();
// Listen on the host so both the own (keyboard) gesture path and an
@@ -68,7 +101,7 @@ export class HuiStateIconElement extends LitElement implements LovelaceElement {
}
public getHitInfo(): LovelaceElementHitInfo | null {
if (!this._config || !this.hass?.states[this._config.entity!]) {
if (!this._config || !this._stateObj) {
return null;
}
const options = {
@@ -95,21 +128,22 @@ export class HuiStateIconElement extends LitElement implements LovelaceElement {
};
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (
!this._config ||
!this._localize ||
!this._hassConfig ||
!this._formatEntityName
) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity!];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning-element
.label=${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
.label=${createEntityNotFoundWarning(this._localize, this._hassConfig)}
></hui-warning-element>
`;
}
@@ -117,7 +151,12 @@ export class HuiStateIconElement extends LitElement implements LovelaceElement {
return html`
<state-badge
.stateObj=${stateObj}
.title=${computeTooltip(this.hass, this._config)}
.title=${computeTooltip(
this._localize,
this._formatEntityName,
this._config,
stateObj
)}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config!.hold_action),
hasDoubleClick: hasAction(this._config!.double_tap_action),
@@ -144,7 +183,10 @@ export class HuiStateIconElement extends LitElement implements LovelaceElement {
`;
private _handleAction(ev: ActionHandlerEvent) {
handleAction(this, this.hass!, this._config!, ev.detail.action!);
fireEvent(this, "hass-action", {
config: this._config!,
action: ev.detail.action,
});
}
}
@@ -1,17 +1,27 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { customElement, query, state } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistant,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import { computeTooltip } from "../common/compute-tooltip";
import { actionHandler } from "../common/directives/action-handler-directive";
import { findEntities } from "../common/find-entities";
import { handleAction } from "../common/handle-action";
import { hasAction } from "../common/has-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import "../components/hui-warning-element";
import type { LovelacePictureElementEditor } from "../types";
@@ -49,14 +59,31 @@ class HuiStateLabelElement extends LitElement implements LovelaceElement {
return { type: "state-label", entity: foundEntities[0] || "" };
}
@property({ attribute: false }) public hass?: HomeAssistant;
// Pointer gestures are delegated to the picture-elements card's routing;
// this element keeps keyboard activation (see LovelaceElement).
public delegatedActions = false;
@state() private _config?: StateLabelElementConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig?: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters?: HomeAssistantFormatters;
@query("div") private _content?: HTMLDivElement;
public constructor() {
@@ -80,21 +107,22 @@ class HuiStateLabelElement extends LitElement implements LovelaceElement {
};
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (
!this._config ||
!this._localize ||
!this._hassConfig ||
!this._formatters
) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity!];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning-element
.label=${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
.label=${createEntityNotFoundWarning(this._localize, this._hassConfig)}
></hui-warning-element>
`;
}
@@ -105,7 +133,7 @@ class HuiStateLabelElement extends LitElement implements LovelaceElement {
) {
return html`
<hui-warning-element
label=${this.hass.localize(
label=${this._localize(
"ui.panel.lovelace.warning.attribute_not_found",
{ attribute: this._config.attribute, entity: this._config.entity }
)}
@@ -115,7 +143,12 @@ class HuiStateLabelElement extends LitElement implements LovelaceElement {
return html`
<div
.title=${computeTooltip(this.hass, this._config)}
.title=${computeTooltip(
this._localize,
this._formatters.formatEntityName,
this._config,
stateObj
)}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config!.hold_action),
hasDoubleClick: hasAction(this._config!.double_tap_action),
@@ -127,7 +160,7 @@ class HuiStateLabelElement extends LitElement implements LovelaceElement {
>
${this._config.prefix}${
!this._config.attribute
? this.hass.formatEntityState(stateObj)
? this._formatters.formatEntityState(stateObj)
: stateObj.attributes[this._config.attribute]
}${this._config.suffix}
</div>
@@ -135,16 +168,19 @@ class HuiStateLabelElement extends LitElement implements LovelaceElement {
}
private _handleAction(ev: ActionHandlerEvent) {
handleAction(this, this.hass!, this._config!, ev.detail.action!);
fireEvent(this, "hass-action", {
config: this._config!,
action: ev.detail.action,
});
}
// The visible text's bounds (excluding the padded host box), so routing
// only claims the text the label shows; null while a warning is rendered.
public getHitInfo(): LovelaceElementHitInfo | null {
if (!this._config || !this.hass || !this._content) {
if (!this._config || !this._content) {
return null;
}
const stateObj = this.hass.states[this._config.entity!];
const stateObj = this._stateObj;
if (
!stateObj ||
(this._config.attribute &&
@@ -1,21 +1,38 @@
import type { PropertyValues } from "lit";
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import { apiContext, configContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { HomeAssistant } from "../../../types";
import { confirmAction } from "../common/confirm-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { ActionRowConfig, LovelaceRow } from "./types";
@customElement("hui-button-entity-row")
class HuiButtonEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _config?: ActionRowConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
private _hassConfig!: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
public setConfig(config: ActionRowConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -23,21 +40,17 @@ class HuiButtonEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config || !this._localize || !this._hassConfig) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig.config)}
</hui-warning>
`;
}
@@ -50,7 +63,7 @@ class HuiButtonEntityRow extends LitElement implements LovelaceRow {
@click=${this._pressButton}
.disabled=${stateObj.state === UNAVAILABLE}
>
${this.hass.localize("ui.card.button.press")}
${this._localize("ui.card.button.press")}
</ha-button>
</hui-generic-entity-row>
`;
@@ -70,12 +83,13 @@ class HuiButtonEntityRow extends LitElement implements LovelaceRow {
!this._config?.confirmation ||
(await confirmAction(
this,
this.hass,
this._hassConfig.user?.id,
this._localize,
this._config.confirmation,
this.hass.localize("ui.card.button.press")
this._localize("ui.card.button.press")
))
) {
this.hass.callService("button", "press", {
this._api.callService("button", "press", {
entity_id: this._config!.entity,
});
}
@@ -1,19 +1,38 @@
import type { PropertyValues } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-climate-state";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type { ClimateEntity } from "../../../data/climate";
import { configContext } from "../../../data/context";
import type { HomeAssistantConfig } from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-climate-entity-row")
class HuiClimateEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: ClimateEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
public setConfig(config: EntityConfig): void {
if (!config || !config.entity) {
throw new Error("Entity must be specified");
@@ -22,21 +41,17 @@ class HuiClimateEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this.hass || !this._config) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -1,22 +1,40 @@
import type { PropertyValues } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-cover-controls";
import "../../../components/ha-cover-tilt-controls";
import { configContext } from "../../../data/context";
import type { CoverEntity } from "../../../data/cover";
import { isTiltOnly } from "../../../data/cover";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type { HomeAssistantConfig } from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-cover-entity-row")
class HuiCoverEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: CoverEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -24,21 +42,17 @@ class HuiCoverEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as CoverEntity;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -1,21 +1,62 @@
import type { PropertyValues, TemplateResult } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeEntityState } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import "../../../components/ha-date-input";
import {
apiContext,
configContext,
formattersContext,
internationalizationContext,
} from "../../../data/context";
import { setDateValue } from "../../../data/date";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
HomeAssistantInternationalization,
ValueChangedEvent,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-date-entity-row")
class HuiDateEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@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;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -23,33 +64,29 @@ class HuiDateEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render(): TemplateResult | typeof nothing {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._i18n.localize, this._hassConfig)}
</hui-warning>
`;
}
const unavailable = stateObj.state === UNAVAILABLE;
const name = this.hass.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-date-input
.locale=${this.hass.locale}
.locale=${this._i18n.locale}
.disabled=${unavailable}
.accessibleLabel=${name}
.value=${
@@ -67,7 +104,7 @@ class HuiDateEntityRow extends LitElement implements LovelaceRow {
private _dateChanged(ev: ValueChangedEvent<string>): void {
if (ev.detail.value) {
setDateValue(
this.hass!.callService,
this._api.callService,
this._config!.entity,
ev.detail.value
);
@@ -1,23 +1,64 @@
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { format } from "date-fns";
import type { PropertyValues, TemplateResult } from "lit";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeEntityState } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import {
apiContext,
configContext,
formattersContext,
internationalizationContext,
} from "../../../data/context";
import "../../../components/ha-date-input";
import "../../../components/ha-time-input";
import { setDateTimeValue } from "../../../data/datetime";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
HomeAssistantInternationalization,
ValueChangedEvent,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-datetime-entity-row")
class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@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;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -25,21 +66,17 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render(): TemplateResult | typeof nothing {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._i18n.localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -53,7 +90,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
const time = dateObj ? format(dateObj, "HH:mm:ss") : undefined;
const date = dateObj ? format(dateObj, "yyyy-MM-dd") : undefined;
const name = this.hass!.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row
@@ -64,7 +101,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
<div>
<ha-date-input
.label=${name}
.locale=${this.hass.locale}
.locale=${this._i18n.locale}
.value=${date}
.disabled=${unavailable}
@value-changed=${this._dateChanged}
@@ -74,7 +111,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
.value=${time}
.accessibleLabel=${name}
.disabled=${unavailable}
.locale=${this.hass.locale}
.locale=${this._i18n.locale}
@value-changed=${this._timeChanged}
@click=${this._stopEventPropagation}
></ha-time-input>
@@ -89,23 +126,23 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
private _timeChanged(ev: ValueChangedEvent<string>): void {
if (ev.detail.value) {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
const dateObj = new Date(stateObj.state);
const newTime = ev.detail.value.split(":").map(Number);
dateObj.setHours(newTime[0], newTime[1], newTime[2]);
setDateTimeValue(this.hass!.callService, stateObj.entity_id, dateObj);
setDateTimeValue(this._api.callService, stateObj.entity_id, dateObj);
}
}
private _dateChanged(ev: ValueChangedEvent<string>): void {
if (ev.detail.value) {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
const dateObj = new Date(stateObj.state);
const newDate = ev.detail.value.split("-").map(Number);
dateObj.setFullYear(newDate[0], newDate[1] - 1, newDate[2]);
setDateTimeValue(this.hass!.callService, stateObj.entity_id, dateObj);
setDateTimeValue(this._api.callService, stateObj.entity_id, dateObj);
}
}
@@ -1,14 +1,24 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { actionHandler } from "../common/directives/action-handler-directive";
import { handleAction } from "../common/handle-action";
import { hasAction } from "../common/has-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import "../components/hui-timestamp-display";
import { createEntityNotFoundWarning } from "../components/hui-warning";
@@ -21,10 +31,25 @@ interface EventEntityConfig extends EntitiesCardEntityConfig {
@customElement("hui-event-entity-row")
class HuiEventEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EventEntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
public setConfig(config: EventEntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -32,21 +57,17 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -70,7 +91,7 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
<div class="when">
${
noValue
? this.hass.formatEntityState(stateObj)
? this._formatters.formatEntityState(stateObj)
: html`<hui-timestamp-display
.ts=${new Date(stateObj.state)}
.format=${this._config.time_format}
@@ -82,7 +103,10 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
${
noValue
? nothing
: this.hass.formatEntityAttributeValue(stateObj, "event_type")
: this._formatters.formatEntityAttributeValue(
stateObj,
"event_type"
)
}
</div>
</div>
@@ -93,7 +117,10 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
private _handleAction(ev: ActionHandlerEvent) {
ev.preventDefault();
ev.stopPropagation();
handleAction(this, this.hass!, this._config!, ev.detail.action);
fireEvent(this, "hass-action", {
config: this._config!,
action: ev.detail.action,
});
}
static styles = css`
@@ -1,12 +1,27 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import { debounce } from "../../../common/util/debounce";
import "../../../components/ha-slider";
import "../../../components/entity/ha-entity-toggle";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@@ -20,10 +35,34 @@ import type { HaSlider } from "../../../components/ha-slider";
@customElement("hui-fan-entity-row")
class HuiFanEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityState"]
>({
transformer: ({ formatEntityState }) => formatEntityState,
})
private _formatEntityState!: HomeAssistantFormatters["formatEntityState"];
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
private _loaded?: boolean;
private _updated?: boolean;
@@ -58,21 +97,17 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
this._attachObserver();
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -110,7 +145,7 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
@change=${this._selectedValueChanged}
></ha-slider>
<span class="state">
${this.hass.formatEntityState(stateObj)}
${this._formatEntityState(stateObj)}
</span>
</div>
`
@@ -124,7 +159,7 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
`
: html`
<div class="text-content">
${this.hass.formatEntityState(stateObj)}
${this._formatEntityState(stateObj)}
</div>
`
}
@@ -186,11 +221,11 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
}
private _selectedValueChanged(ev: Event): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
const value = Number((ev.target as HaSlider).value);
if (value !== stateObj.attributes.percentage) {
this.hass!.callService("fan", "set_percentage", {
this._api.callService("fan", "set_percentage", {
entity_id: stateObj.entity_id,
percentage: value,
});
@@ -1,37 +1,93 @@
import type { PropertyValues } from "lit";
import type {
HassConfig,
HassEntities,
HassEntity,
} from "home-assistant-js-websocket";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/entity/ha-entity-toggle";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import {
configContext,
formattersContext,
statesContext,
} from "../../../data/context";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
const computeCanToggle = (
states: HassEntities,
entityIds: string[] | undefined,
visited = new Set<string>()
): boolean =>
// Nested groups may not exist
(entityIds ?? []).some((entityId) => {
const domain = computeDomain(entityId);
if (domain === "group") {
if (visited.has(entityId)) {
return false;
}
visited.add(entityId);
return computeCanToggle(
states,
states[entityId]?.attributes.entity_id,
visited
);
}
return DOMAINS_TOGGLE.has(domain);
});
@customElement("hui-group-entity-row")
class HuiGroupEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
private _computeCanToggle(
hass: HomeAssistant,
entityIds: string[] | undefined
): boolean {
// Nested groups may not exist
return (entityIds ?? []).some((entityId) => {
const domain = computeDomain(entityId);
if (domain === "group") {
return this._computeCanToggle(
hass,
hass.states[entityId]?.attributes.entity_id
);
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HassEntities | null, boolean>({
transformer: function (this: HuiGroupEntityRow, states) {
const entityId = this._config?.entity;
if (!states || !entityId) {
return false;
}
return DOMAINS_TOGGLE.has(domain);
});
}
return computeCanToggle(
states,
states[entityId]?.attributes.entity_id,
new Set([entityId])
);
},
watch: ["_config"],
})
private _canToggle?: boolean;
@state() @consumeLocalize() private _localize?: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters?: HomeAssistantFormatters;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig?: HassConfig;
public setConfig(config: EntityConfig): void {
if (!config) {
@@ -40,21 +96,22 @@ class HuiGroupEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (
!this._config ||
!this._localize ||
!this._hassConfig ||
!this._formatters
) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -62,13 +119,13 @@ class HuiGroupEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
this._computeCanToggle(this.hass, stateObj.attributes.entity_id)
this._canToggle
? html`
<ha-entity-toggle .stateObj=${stateObj}></ha-entity-toggle>
`
: html`
<div class="text-content">
${this.hass.formatEntityState(stateObj)}
${this._formatters.formatEntityState(stateObj)}
</div>
`
}
@@ -1,20 +1,38 @@
import type { PropertyValues } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-humidifier-state";
import { configContext } from "../../../data/context";
import type { HumidifierEntity } from "../../../data/humidifier";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type { HomeAssistantConfig } from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-humidifier-entity-row")
class HuiHumidifierEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HumidifierEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
public setConfig(config: EntityConfig): void {
if (!config || !config.entity) {
throw new Error("Entity must be specified");
@@ -23,21 +41,17 @@ class HuiHumidifierEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this.hass || !this._config) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as HumidifierEntity;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -1,21 +1,38 @@
import type { PropertyValues } from "lit";
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import { apiContext, configContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { HomeAssistant } from "../../../types";
import { confirmAction } from "../common/confirm-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { ActionRowConfig, LovelaceRow } from "./types";
@customElement("hui-input-button-entity-row")
class HuiInputButtonEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _config?: ActionRowConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
private _hassConfig!: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
public setConfig(config: ActionRowConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -23,21 +40,17 @@ class HuiInputButtonEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config || !this._localize || !this._hassConfig) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig.config)}
</hui-warning>
`;
}
@@ -50,7 +63,7 @@ class HuiInputButtonEntityRow extends LitElement implements LovelaceRow {
@click=${this._pressButton}
.disabled=${stateObj.state === UNAVAILABLE}
>
${this.hass.localize("ui.card.button.press")}
${this._localize("ui.card.button.press")}
</ha-button>
</hui-generic-entity-row>
`;
@@ -70,12 +83,13 @@ class HuiInputButtonEntityRow extends LitElement implements LovelaceRow {
!this._config?.confirmation ||
(await confirmAction(
this,
this.hass,
this._hassConfig.user?.id,
this._localize,
this._config.confirmation,
this.hass.localize("ui.card.button.press")
this._localize("ui.card.button.press")
))
) {
this.hass.callService("input_button", "press", {
this._api.callService("input_button", "press", {
entity_id: this._config!.entity,
});
}
@@ -1,6 +1,15 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeEntityState } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import {
apiContext,
configContext,
formattersContext,
internationalizationContext,
} from "../../../data/context";
import "../../../components/ha-date-input";
import "../../../components/ha-time-input";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
@@ -8,18 +17,49 @@ import {
setInputDateTimeValue,
stateToIsoDateString,
} from "../../../data/input_datetime";
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
HomeAssistantInternationalization,
ValueChangedEvent,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-input-datetime-entity-row")
class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@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;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -27,26 +67,22 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._i18n.localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass!.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row
@@ -69,7 +105,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
<ha-date-input
.label=${stateObj.attributes.has_time ? name : undefined}
.accessibleLabel=${stateObj.attributes.has_time ? undefined : name}
.locale=${this.hass.locale}
.locale=${this._i18n.locale}
.disabled=${stateObj.state === UNAVAILABLE}
.value=${stateToIsoDateString(stateObj)}
@value-changed=${this._dateChanged}
@@ -90,7 +126,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
: stateObj.state
}
.accessibleLabel=${name}
.locale=${this.hass.locale}
.locale=${this._i18n.locale}
.disabled=${stateObj.state === UNAVAILABLE}
@value-changed=${this._timeChanged}
@click=${this._stopEventPropagation}
@@ -108,9 +144,9 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
}
private _timeChanged(ev: ValueChangedEvent<string>): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
setInputDateTimeValue(
this.hass!.callService,
this._api.callService,
stateObj.entity_id,
ev.detail.value,
stateObj.attributes.has_date ? stateObj.state.split(" ")[0] : undefined
@@ -118,10 +154,10 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
}
private _dateChanged(ev: ValueChangedEvent<string>): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
setInputDateTimeValue(
this.hass!.callService,
this._api.callService,
stateObj.entity_id,
stateObj.attributes.has_time ? stateObj.state.split(" ")[1] : undefined,
ev.detail.value
@@ -1,23 +1,56 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import { debounce } from "../../../common/util/debounce";
import "../../../components/ha-slider";
import "../../../components/input/ha-input";
import { UNAVAILABLE } from "../../../data/entity/entity";
import { setValue } from "../../../data/input_text";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-input-number-entity-row")
class HuiInputNumberEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
private _loaded?: boolean;
private _updated?: boolean;
@@ -52,26 +85,22 @@ class HuiInputNumberEntityRow extends LitElement implements LovelaceRow {
this._attachObserver();
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass.formatEntityName(stateObj, this._config.name);
const name = this._formatters.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
@@ -90,7 +119,7 @@ class HuiInputNumberEntityRow extends LitElement implements LovelaceRow {
@change=${this._selectedValueChanged}
></ha-slider>
<span class="state">
${this.hass.formatEntityState(stateObj)}
${this._formatters.formatEntityState(stateObj)}
</span>
</div>
`
@@ -180,11 +209,11 @@ class HuiInputNumberEntityRow extends LitElement implements LovelaceRow {
}
private _selectedValueChanged(ev: Event): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
if ((ev.target as HTMLInputElement).value !== stateObj.state) {
setValue(
this.hass!.callService,
this._api.callService,
stateObj.entity_id,
(ev.target as HTMLInputElement).value
);
@@ -1,25 +1,64 @@
import type { PropertyValues } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import type { HaSelectSelectEvent } from "../../../components/ha-select";
import "../../../components/ha-select";
import { UNAVAILABLE } from "../../../data/entity/entity";
import { forwardHaptic } from "../../../data/haptics";
import type { InputSelectEntity } from "../../../data/input_select";
import { setInputSelectOption } from "../../../data/input_select";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { LovelaceRow } from "./types";
@customElement("hui-input-select-entity-row")
class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntitiesCardEntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: InputSelectEntity;
@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;
public setConfig(config: EntitiesCardEntityConfig): void {
if (!config || !config.entity) {
throw new Error("Entity must be specified");
@@ -28,27 +67,22 @@ class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this.hass || !this._config) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as
InputSelectEntity | undefined;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass!.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row
@@ -82,9 +116,7 @@ class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
`;
private _selectedChanged(ev: HaSelectSelectEvent): void {
const stateObj = this.hass!.states[
this._config!.entity
] as InputSelectEntity;
const stateObj = this._stateObj!;
const option = ev.detail.value;
if (
option === stateObj.state ||
@@ -95,7 +127,7 @@ class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
forwardHaptic(this, "light");
setInputSelectOption(this.hass!.callService, stateObj.entity_id, option);
setInputSelectOption(this._api.callService, stateObj.entity_id, option);
}
}
@@ -1,22 +1,61 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import "../../../components/input/ha-input";
import type { HaInput } from "../../../components/input/ha-input";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import { setValue } from "../../../data/input_text";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-input-text-entity-row")
class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@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;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -24,26 +63,22 @@ class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass!.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row
@@ -61,14 +96,14 @@ class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
.pattern=${stateObj.attributes.pattern}
.type=${stateObj.attributes.mode}
@change=${this._selectedValueChanged}
.placeholder=${this.hass.localize("ui.card.text.empty_value")}
.placeholder=${this._localize("ui.card.text.empty_value")}
></ha-input>
</hui-generic-entity-row>
`;
}
private _selectedValueChanged(ev: InputEvent): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
const target = ev.target as HaInput;
const newValue = target.value ?? "";
@@ -80,7 +115,7 @@ class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
}
if (newValue !== stateObj.state) {
setValue(this.hass!.callService, stateObj.entity_id, newValue);
setValue(this._api.callService, stateObj.entity_id, newValue);
}
target.blur();
@@ -1,22 +1,39 @@
import type { PropertyValues } from "lit";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import { apiContext, configContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { LockEntity } from "../../../data/lock";
import { callProtectedLockService } from "../../../data/lock";
import type { HomeAssistant } from "../../../types";
import { confirmAction } from "../common/confirm-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { ConfirmableRowConfig, LovelaceRow } from "./types";
@customElement("hui-lock-entity-row")
class HuiLockEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: ConfirmableRowConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: LockEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
private _hassConfig!: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
public setConfig(config: ConfirmableRowConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -24,21 +41,17 @@ class HuiLockEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config || !this._localize || !this._hassConfig) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig.config)}
</hui-warning>
`;
}
@@ -54,8 +67,8 @@ class HuiLockEntityRow extends LitElement implements LovelaceRow {
>
${
stateObj.state === "locked"
? this.hass!.localize("ui.card.lock.unlock")
: this.hass!.localize("ui.card.lock.lock")
? this._localize("ui.card.lock.unlock")
: this._localize("ui.card.lock.lock")
}
</ha-button>
</hui-generic-entity-row>
@@ -72,22 +85,23 @@ class HuiLockEntityRow extends LitElement implements LovelaceRow {
private async _callService(ev): Promise<void> {
ev.stopPropagation();
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
const action = stateObj.state === "locked" ? "unlock" : "lock";
if (
!this._config?.confirmation ||
(await confirmAction(
this,
this.hass!,
this._hassConfig.user?.id,
this._localize,
this._config.confirmation,
this.hass!.localize(`ui.card.lock.${action}`)
this._localize(`ui.card.lock.${action}`)
))
) {
callProtectedLockService(
this,
this.hass!.callService,
this.hass!.callWS,
this.hass!.localize,
this._api.callService,
this._api.callWS,
this._localize,
stateObj,
action
);
@@ -13,15 +13,26 @@ import {
mdiVolumeOff,
mdiVolumePlus,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { stateActive } from "../../../common/entity/state_active";
import { supportsFeature } from "../../../common/entity/supports-feature";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { debounce } from "../../../common/util/debounce";
import "../../../components/ha-icon-button";
import "../../../components/ha-slider";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type {
ControlButton,
@@ -31,18 +42,39 @@ import {
MediaPlayerEntityFeature,
computeMediaDescription,
} from "../../../data/media-player";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-media-player-entity-row")
class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: MediaPlayerEntity;
@state() @consumeLocalize() private _localize?: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters?: HomeAssistantFormatters;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig?: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api?: HomeAssistantApi;
@state() private _narrow?: boolean = false;
@state() private _veryNarrow?: boolean = false;
@@ -77,25 +109,22 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
this._attachObserver();
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return (
hasConfigOrEntityChanged(this, changedProps) ||
changedProps.size > 1 ||
!changedProps.has("hass")
);
}
protected render() {
if (!this.hass || !this._config) {
if (
!this._config ||
!this._localize ||
!this._hassConfig ||
!this._formatters
) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as MediaPlayerEntity;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -112,7 +141,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${mdiSkipPrevious}
.label=${this.hass.localize(
.label=${this._localize(
"ui.card.media_player.media_previous_track"
)}
@click=${this._previousTrack}
@@ -133,7 +162,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${controlButton.icon}
.label=${this.hass.localize(
.label=${this._localize(
`ui.card.media_player.${controlButton.action}`
)}
@click=${this._playPauseStop}
@@ -146,7 +175,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${mdiPlay}
.label=${this.hass.localize(`ui.card.media_player.media_play`)}
.label=${this._localize(`ui.card.media_player.media_play`)}
@click=${this._play}
></ha-icon-button>
`
@@ -158,7 +187,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${mdiPause}
.label=${this.hass.localize(`ui.card.media_player.media_pause`)}
.label=${this._localize(`ui.card.media_player.media_pause`)}
@click=${this._pause}
></ha-icon-button>
`
@@ -171,7 +200,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${mdiStop}
.label=${this.hass.localize(`ui.card.media_player.media_stop`)}
.label=${this._localize(`ui.card.media_player.media_stop`)}
@click=${this._stop}
></ha-icon-button>
`
@@ -185,7 +214,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${mdiSkipNext}
.label=${this.hass.localize(
.label=${this._localize(
"ui.card.media_player.media_next_track"
)}
@click=${this._nextTrack}
@@ -202,7 +231,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
.stateObj=${stateObj}
.config=${this._config}
.secondaryText=${
mediaDescription || this.hass.formatEntityState(stateObj)
mediaDescription || this._formatters.formatEntityState(stateObj)
}
>
<div class="controls">
@@ -213,7 +242,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${assumedState ? mdiPowerOn : mdiPowerStandby}
.label=${this.hass.localize("ui.card.media_player.turn_on")}
.label=${this._localize("ui.card.media_player.turn_on")}
@click=${this._turnOn}
></ha-icon-button>
`
@@ -235,7 +264,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${assumedState ? mdiPowerOff : mdiPowerStandby}
.label=${this.hass.localize("ui.card.media_player.turn_off")}
.label=${this._localize("ui.card.media_player.turn_off")}
@click=${this._turnOff}
></ha-icon-button>
`
@@ -262,7 +291,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? mdiVolumeOff
: mdiVolumeHigh
}
.label=${this.hass.localize(
.label=${this._localize(
`ui.card.media_player.${
stateObj.attributes.is_volume_muted
? "media_volume_mute"
@@ -296,14 +325,14 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? html`
<ha-icon-button
.path=${mdiVolumeMinus}
.label=${this.hass.localize(
.label=${this._localize(
"ui.card.media_player.media_volume_down"
)}
@click=${this._volumeDown}
></ha-icon-button>
<ha-icon-button
.path=${mdiVolumePlus}
.label=${this.hass.localize(
.label=${this._localize(
"ui.card.media_player.media_volume_up"
)}
@click=${this._volumeUp}
@@ -349,19 +378,22 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
}
private _turnOn(): void {
this.hass!.callService("media_player", "turn_on", {
this._api?.callService("media_player", "turn_on", {
entity_id: this._config!.entity,
});
}
private _turnOff(): void {
this.hass!.callService("media_player", "turn_off", {
this._api?.callService("media_player", "turn_off", {
entity_id: this._config!.entity,
});
}
private _playPauseStop(): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return;
}
const service =
stateObj.state !== "playing"
@@ -370,63 +402,62 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
? "media_pause"
: "media_stop";
this.hass!.callService("media_player", service, {
this._api?.callService("media_player", service, {
entity_id: this._config!.entity,
});
}
private _play(): void {
this.hass!.callService("media_player", "media_play", {
this._api?.callService("media_player", "media_play", {
entity_id: this._config!.entity,
});
}
private _pause(): void {
this.hass!.callService("media_player", "media_pause", {
this._api?.callService("media_player", "media_pause", {
entity_id: this._config!.entity,
});
}
private _stop(): void {
this.hass!.callService("media_player", "media_stop", {
this._api?.callService("media_player", "media_stop", {
entity_id: this._config!.entity,
});
}
private _previousTrack(): void {
this.hass!.callService("media_player", "media_previous_track", {
this._api?.callService("media_player", "media_previous_track", {
entity_id: this._config!.entity,
});
}
private _nextTrack(): void {
this.hass!.callService("media_player", "media_next_track", {
this._api?.callService("media_player", "media_next_track", {
entity_id: this._config!.entity,
});
}
private _toggleMute() {
this.hass!.callService("media_player", "volume_mute", {
this._api?.callService("media_player", "volume_mute", {
entity_id: this._config!.entity,
is_volume_muted:
!this.hass!.states[this._config!.entity].attributes.is_volume_muted,
is_volume_muted: !this._stateObj?.attributes.is_volume_muted,
});
}
private _volumeDown() {
this.hass!.callService("media_player", "volume_down", {
this._api?.callService("media_player", "volume_down", {
entity_id: this._config!.entity,
});
}
private _volumeUp() {
this.hass!.callService("media_player", "volume_up", {
this._api?.callService("media_player", "volume_up", {
entity_id: this._config!.entity,
});
}
private _selectedValueChanged(ev): void {
this.hass!.callService("media_player", "volume_set", {
this._api?.callService("media_player", "volume_set", {
entity_id: this._config!.entity,
volume_level: ev.target.value / 100,
});
@@ -1,7 +1,19 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { live } from "lit/directives/live";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import { debounce } from "../../../common/util/debounce";
import "../../../components/ha-slider";
import "../../../components/input/ha-input";
@@ -9,18 +21,39 @@ import type { HaInput } from "../../../components/input/ha-input";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import { setValue } from "../../../data/input_text";
import { showNumberSlider } from "../../../data/number";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-number-entity-row")
class HuiNumberEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
private _loaded?: boolean;
private _updated?: boolean;
@@ -55,26 +88,22 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
this._attachObserver();
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass.formatEntityName(stateObj, this._config.name);
const name = this._formatters.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
@@ -97,7 +126,7 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
stateObj.state === UNAVAILABLE ||
stateObj.state === UNKNOWN
? "—"
: this.hass.formatEntityState(stateObj)
: this._formatters.formatEntityState(stateObj)
}
</span>
</div>
@@ -187,11 +216,11 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
}
private _selectedValueChanged(ev: InputEvent): void {
const stateObj = this.hass!.states[this._config!.entity];
const stateObj = this._stateObj!;
if ((ev.target as HaInput).value !== stateObj.state) {
setValue(
this.hass!.callService,
this._api.callService,
stateObj.entity_id,
(ev.target as HaInput).value!
);
@@ -1,22 +1,39 @@
import type { PropertyValues } from "lit";
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import { apiContext, configContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import { activateScene } from "../../../data/scene";
import type { HomeAssistant } from "../../../types";
import { confirmAction } from "../common/confirm-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { ActionRowConfig, LovelaceRow } from "./types";
@customElement("hui-scene-entity-row")
class HuiSceneEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _config?: ActionRowConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
private _hassConfig!: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
public setConfig(config: ActionRowConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -24,21 +41,17 @@ class HuiSceneEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config || !this._localize || !this._hassConfig) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig.config)}
</hui-warning>
`;
}
@@ -53,8 +66,7 @@ class HuiSceneEntityRow extends LitElement implements LovelaceRow {
class="text-content"
>
${
this._config.action_name ||
this.hass!.localize("ui.card.scene.activate")
this._config.action_name || this._localize("ui.card.scene.activate")
}
</ha-button>
</hui-generic-entity-row>
@@ -75,12 +87,13 @@ class HuiSceneEntityRow extends LitElement implements LovelaceRow {
!this._config?.confirmation ||
(await confirmAction(
this,
this.hass,
this._hassConfig.user?.id,
this._localize,
this._config.confirmation,
this._config.action_name || this.hass.localize("ui.card.scene.activate")
this._config.action_name || this._localize("ui.card.scene.activate")
))
) {
activateScene(this.hass.callService, this._config!.entity);
activateScene(this._api.callService, this._config!.entity);
}
}
}
@@ -1,24 +1,47 @@
import type { PropertyValues } from "lit";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-button";
import {
apiContext,
configContext,
servicesContext,
} from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { ScriptEntity } from "../../../data/script";
import { canRun, hasScriptFields } from "../../../data/script";
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
import type { HomeAssistant } from "../../../types";
import { confirmAction } from "../common/confirm-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { ActionRowConfig, LovelaceRow } from "./types";
@customElement("hui-script-entity-row")
class HuiScriptEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: ActionRowConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: ScriptEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
private _hassConfig!: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@consume({ context: servicesContext, subscribe: true })
private _services!: ContextType<typeof servicesContext>;
public setConfig(config: ActionRowConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -26,21 +49,17 @@ class HuiScriptEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config || !this._localize || !this._hassConfig) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as ScriptEntity;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig.config)}
</hui-warning>
`;
}
@@ -59,10 +78,10 @@ class HuiScriptEntityRow extends LitElement implements LovelaceRow {
stateObj.attributes.mode !== "single" &&
stateObj.attributes.current &&
stateObj.attributes.current > 0
? this.hass.localize("ui.card.script.cancel_multiple", {
? this._localize("ui.card.script.cancel_multiple", {
number: stateObj.attributes.current,
})
: this.hass.localize("ui.card.script.cancel")
: this._localize("ui.card.script.cancel")
}
</ha-button>`
: nothing
@@ -75,10 +94,7 @@ class HuiScriptEntityRow extends LitElement implements LovelaceRow {
@click=${this._runScript}
.disabled=${stateObj.state === UNAVAILABLE || !canRun(stateObj)}
>
${
this._config.action_name ||
this.hass!.localize("ui.card.script.run")
}
${this._config.action_name || this._localize("ui.card.script.run")}
</ha-button>`
: nothing
}
@@ -102,15 +118,19 @@ class HuiScriptEntityRow extends LitElement implements LovelaceRow {
private async _runScript(ev): Promise<void> {
ev.stopPropagation();
if (hasScriptFields(this.hass!.services, this._config!.entity)) {
if (
this._services &&
hasScriptFields(this._services, this._config!.entity)
) {
showMoreInfoDialog(this, { entityId: this._config!.entity });
} else if (
!this._config?.confirmation ||
(await confirmAction(
this,
this.hass!,
this._hassConfig.user?.id,
this._localize,
this._config.confirmation,
this._config.action_name || this.hass!.localize("ui.card.script.run")
this._config.action_name || this._localize("ui.card.script.run")
))
) {
this._callService("turn_on");
@@ -118,7 +138,7 @@ class HuiScriptEntityRow extends LitElement implements LovelaceRow {
}
private _callService(service: string): void {
this.hass!.callService("script", service, {
this._api.callService("script", service, {
entity_id: this._config!.entity,
});
}
@@ -1,25 +1,59 @@
import type { HassConfig } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { HaSelectSelectEvent } from "../../../components/ha-select";
import "../../../components/ha-select";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import { forwardHaptic } from "../../../data/haptics";
import type { SelectEntity } from "../../../data/select";
import { setSelectOption } from "../../../data/select";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { LovelaceRow } from "./types";
@customElement("hui-select-entity-row")
class HuiSelectEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntitiesCardEntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: SelectEntity;
@state() @consumeLocalize() private _localize?: LocalizeFunc;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters?: HomeAssistantFormatters;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig?: HassConfig;
@consume({ context: apiContext, subscribe: true })
private _api?: HomeAssistantApi;
@state() private _selectedEntityRow?: string;
public setConfig(config: EntitiesCardEntityConfig): void {
@@ -30,43 +64,35 @@ class HuiSelectEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues): boolean {
return (
hasConfigOrEntityChanged(this, changedProps) ||
changedProps.has("_selectedEntityRow")
);
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (
this.hass &&
this._config &&
changedProps.get("hass") &&
this.hass.states[this._config.entity] !==
changedProps.get("hass").states[this._config.entity]
) {
if (changedProps.has("_stateObj")) {
this._selectedEntityRow = undefined;
}
}
protected render() {
if (!this.hass || !this._config) {
if (
!this._config ||
!this._localize ||
!this._hassConfig ||
!this._formatters
) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as
SelectEntity | undefined;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass!.formatEntityName(stateObj, this._config.name);
const formatters = this._formatters;
const name = formatters.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row
@@ -79,7 +105,7 @@ class HuiSelectEntityRow extends LitElement implements LovelaceRow {
.value=${this._selectedEntityRow || stateObj.state}
.options=${stateObj.attributes.options?.map((option) => ({
value: option,
label: this.hass!.formatEntityState(stateObj, option),
label: formatters.formatEntityState(stateObj, option),
}))}
.disabled=${stateObj.state === UNAVAILABLE}
@selected=${this._handleAction}
@@ -101,11 +127,13 @@ class HuiSelectEntityRow extends LitElement implements LovelaceRow {
`;
private _handleAction(ev: HaSelectSelectEvent): void {
const stateObj = this.hass!.states[this._config!.entity] as SelectEntity;
const stateObj = this._stateObj;
const option = ev.detail.value;
if (
!stateObj ||
!this._api ||
option === stateObj.state ||
!stateObj.attributes.options.includes(option)
) {
@@ -116,14 +144,13 @@ class HuiSelectEntityRow extends LitElement implements LovelaceRow {
this._selectedEntityRow = option;
setSelectOption(this.hass!.callService, stateObj.entity_id, option)
setSelectOption(this._api.callService, stateObj.entity_id, option)
.catch((_err) => {
// silently swallow exception
})
.finally(() =>
setTimeout(() => {
const newStateObj = this.hass!.states[this._config!.entity];
if (newStateObj === stateObj) {
if (this._stateObj === stateObj) {
this._selectedEntityRow = undefined;
}
}, 2000)
@@ -1,14 +1,24 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import {
SENSOR_DEVICE_CLASS_UPTIME,
SENSOR_TIMESTAMP_DEVICE_CLASSES,
} from "../../../data/sensor";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import "../components/hui-timestamp-display";
import { createEntityNotFoundWarning } from "../components/hui-warning";
@@ -18,10 +28,31 @@ interface SensorEntityConfig extends EntitiesCardEntityConfig {}
@customElement("hui-sensor-entity-row")
class HuiSensorEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: SensorEntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityState"]
>({
transformer: ({ formatEntityState }) => formatEntityState,
})
private _formatEntityState!: HomeAssistantFormatters["formatEntityState"];
public setConfig(config: SensorEntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -29,21 +60,17 @@ class HuiSensorEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -69,7 +96,7 @@ class HuiSensorEntityRow extends LitElement implements LovelaceRow {
capitalize
></hui-timestamp-display>
`
: this.hass.formatEntityState(stateObj)
: this._formatEntityState(stateObj)
}
</hui-generic-entity-row>
`;
@@ -1,23 +1,54 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HomeAssistant } from "../../../types";
import { customElement, state } from "lit/decorators";
import { TIMESTAMP_STATE_DOMAINS } from "../../../common/const";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import "../components/hui-timestamp-display";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { LovelaceRow } from "./types";
import { TIMESTAMP_STATE_DOMAINS } from "../../../common/const";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import { computeDomain } from "../../../common/entity/compute_domain";
@customElement("hui-simple-entity-row")
class HuiSimpleEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntitiesCardEntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityState"]
>({
transformer: ({ formatEntityState }) => formatEntityState,
})
private _formatEntityState!: HomeAssistantFormatters["formatEntityState"];
public setConfig(config: EntitiesCardEntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -25,21 +56,17 @@ class HuiSimpleEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -57,7 +84,7 @@ class HuiSimpleEntityRow extends LitElement implements LovelaceRow {
capitalize
></hui-timestamp-display>
`
: this.hass.formatEntityState(stateObj)
: this._formatEntityState(stateObj)
}
</hui-generic-entity-row>
`;
@@ -1,23 +1,62 @@
import type { PropertyValues } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
configContext,
formattersContext,
} from "../../../data/context";
import "../../../components/input/ha-input";
import type { HaInput } from "../../../components/input/ha-input";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { TextEntity } from "../../../data/text";
import { setValue } from "../../../data/text";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-text-entity-row")
class HuiTextEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: TextEntity;
@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;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -25,27 +64,22 @@ class HuiTextEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as
TextEntity | undefined;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
const name = this.hass!.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row
@@ -63,14 +97,14 @@ class HuiTextEntityRow extends LitElement implements LovelaceRow {
.pattern=${stateObj.attributes.pattern}
.type=${stateObj.attributes.mode}
@change=${this._valueChanged}
.placeholder=${this.hass!.localize("ui.card.text.empty_value")}
.placeholder=${this._localize("ui.card.text.empty_value")}
></ha-input>
</hui-generic-entity-row>
`;
}
private _valueChanged(ev: InputEvent): void {
const stateObj = this.hass!.states[this._config!.entity] as TextEntity;
const stateObj = this._stateObj!;
const target = ev.target as HaInput;
const newValue = target.value ?? "";
@@ -81,7 +115,7 @@ class HuiTextEntityRow extends LitElement implements LovelaceRow {
}
if (newValue !== stateObj.state) {
setValue(this.hass!.callService, stateObj.entity_id, newValue);
setValue(this._api.callService, stateObj.entity_id, newValue);
}
target.blur();
@@ -1,21 +1,62 @@
import type { PropertyValues, TemplateResult } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import type { TemplateResult } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeEntityState } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import {
apiContext,
configContext,
formattersContext,
internationalizationContext,
} from "../../../data/context";
import "../../../components/ha-time-input";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import { setTimeValue } from "../../../data/time";
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantFormatters,
HomeAssistantInternationalization,
ValueChangedEvent,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-time-entity-row")
class HuiTimeEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@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;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -23,28 +64,24 @@ class HuiTimeEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render(): TemplateResult | typeof nothing {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._i18n.localize, this._hassConfig)}
</hui-warning>
`;
}
const unavailable = stateObj.state === UNAVAILABLE;
const name = this.hass.formatEntityName(stateObj, this._config.name);
const name = this._formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
@@ -55,7 +92,7 @@ class HuiTimeEntityRow extends LitElement implements LovelaceRow {
: stateObj.state
}
.accessibleLabel=${name}
.locale=${this.hass.locale}
.locale=${this._i18n.locale}
.disabled=${unavailable}
@value-changed=${this._timeChanged}
@click=${this._stopEventPropagation}
@@ -70,8 +107,8 @@ class HuiTimeEntityRow extends LitElement implements LovelaceRow {
private _timeChanged(ev: ValueChangedEvent<string>): void {
if (ev.detail.value) {
const stateObj = this.hass!.states[this._config!.entity];
setTimeValue(this.hass!.callService, stateObj.entity_id, ev.detail.value);
const stateObj = this._stateObj!;
setTimeValue(this._api.callService, stateObj.entity_id, ev.detail.value);
}
}
}
@@ -1,19 +1,37 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { configContext } from "../../../data/context";
import "../../../state-display/ha-timer-remaining-time";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type { HomeAssistantConfig } from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig } from "./types";
@customElement("hui-timer-entity-row")
class HuiTimerEntityRow extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -22,16 +40,16 @@ class HuiTimerEntityRow extends LitElement {
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -46,10 +64,6 @@ class HuiTimerEntityRow extends LitElement {
</hui-generic-entity-row>
`;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
}
declare global {
@@ -1,20 +1,51 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/entity/ha-entity-toggle";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-toggle-entity-row")
class HuiToggleEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityState"]
>({
transformer: ({ formatEntityState }) => formatEntityState,
})
private _formatEntityState!: HomeAssistantFormatters["formatEntityState"];
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -22,21 +53,17 @@ class HuiToggleEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -60,7 +87,7 @@ class HuiToggleEntityRow extends LitElement implements LovelaceRow {
`
: html`
<div class="text-content">
${this.hass.formatEntityState(stateObj)}
${this._formatEntityState(stateObj)}
</div>
`
}
@@ -1,21 +1,55 @@
import type { PropertyValues } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeEntityState } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import {
configContext,
formattersContext,
internationalizationContext,
} from "../../../data/context";
import type { UpdateEntity } from "../../../data/update";
import { computeUpdateStateDisplay } from "../../../data/update";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
HomeAssistantInternationalization,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { LovelaceRow } from "./types";
@customElement("hui-update-entity-row")
class HuiUpdateEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntitiesCardEntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: UpdateEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityState"]
>({
transformer: ({ formatEntityState }) => formatEntityState,
})
private _formatEntityState!: HomeAssistantFormatters["formatEntityState"];
public setConfig(config: EntitiesCardEntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -23,22 +57,17 @@ class HuiUpdateEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity] as
UpdateEntity | undefined;
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._i18n.localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -47,9 +76,9 @@ class HuiUpdateEntityRow extends LitElement implements LovelaceRow {
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${computeUpdateStateDisplay(
stateObj,
this.hass.localize,
this.hass.locale,
this.hass.formatEntityState
this._i18n.localize,
this._i18n.locale,
this._formatEntityState
)}
</hui-generic-entity-row>
`;
@@ -1,20 +1,51 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/entity/ha-entity-toggle";
import { configContext, formattersContext } from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { EntityConfig, LovelaceRow } from "./types";
@customElement("hui-valve-entity-row")
class HuiValveEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntityConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityState"]
>({
transformer: ({ formatEntityState }) => formatEntityState,
})
private _formatEntityState!: HomeAssistantFormatters["formatEntityState"];
public setConfig(config: EntityConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -22,21 +53,17 @@ class HuiValveEntityRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -60,7 +87,7 @@ class HuiValveEntityRow extends LitElement implements LovelaceRow {
`
: html`
<div class="text-content">
${this.hass.formatEntityState(stateObj)}
${this._formatEntityState(stateObj)}
</div>
`
}
@@ -3,7 +3,6 @@ import { css, html, LitElement } from "lit";
import { classMap } from "lit/directives/class-map";
import { customElement, property, state } from "lit/decorators";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { HomeAssistant } from "../../../types";
import { processConfigEntities } from "../common/process-config-entities";
import "../components/hui-buttons-base";
import type { EntityConfig } from "../entity-rows/types";
@@ -19,8 +18,6 @@ export class HuiButtonsHeaderFooter
return { entities: [] };
}
@property({ attribute: false }) public hass?: HomeAssistant;
@property() public type!: "header" | "footer";
@state() private _configEntities?: EntityConfig[];
@@ -57,7 +54,6 @@ export class HuiButtonsHeaderFooter
: ""
}
<hui-buttons-base
.hass=${this.hass}
.configEntities=${this._configEntities}
class=${classMap({
footer: this.type === "footer",
@@ -1,10 +1,17 @@
import type { PropertyValues } from "lit";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import checkValidDate from "../../../common/datetime/check_valid_date";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-attribute-value";
import type { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import { configContext } from "../../../data/context";
import type { HomeAssistantConfig } from "../../../types";
import "../components/hui-generic-entity-row";
import "../components/hui-timestamp-display";
import { createEntityNotFoundWarning } from "../components/hui-warning";
@@ -12,10 +19,21 @@ import type { AttributeRowConfig, LovelaceRow } from "../entity-rows/types";
@customElement("hui-attribute-row")
class HuiAttributeRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: AttributeRowConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
public setConfig(config: AttributeRowConfig): void {
if (!config) {
throw new Error("Invalid configuration");
@@ -29,21 +47,17 @@ class HuiAttributeRow extends LitElement implements LovelaceRow {
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render() {
if (!this._config || !this.hass) {
if (!this._config) {
return nothing;
}
const stateObj = this.hass.states[this._config.entity];
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -1,9 +1,8 @@
import type { TemplateResult } from "lit";
import { html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { HomeAssistant } from "../../../types";
import { processConfigEntities } from "../common/process-config-entities";
import "../components/hui-buttons-base";
import type {
@@ -18,8 +17,6 @@ export class HuiButtonsRow extends LitElement implements LovelaceRow {
return { entities: [] };
}
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _configEntities?: EntityConfig[];
public setConfig(config: ButtonsRowConfig): void {
@@ -41,7 +38,6 @@ export class HuiButtonsRow extends LitElement implements LovelaceRow {
protected render(): TemplateResult | undefined {
return html`
<hui-buttons-base
.hass=${this.hass}
.configEntities=${this._configEntities}
></hui-buttons-base>
`;
@@ -77,7 +77,11 @@ export class AreaViewStrategy extends ReactiveElement {
const groupedEntities = getAreaGroupedEntities(
config.area,
hass,
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
config.groups_options
);
@@ -1,13 +1,17 @@
import { mdiThermometerWater } from "@mdi/js";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { cache } from "lit/directives/cache";
import { keyed } from "lit/directives/keyed";
import memoizeOne from "memoize-one";
import { consume } from "../../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../../common/decorators/consume-context-entry";
import {
fireEvent,
type HASSDomCurrentTargetEvent,
} from "../../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import "../../../../../components/ha-areas-display-editor";
import type { AreasDisplayValue } from "../../../../../components/ha-areas-display-editor";
import "../../../../../components/ha-areas-floors-display-editor";
@@ -23,12 +27,16 @@ import {
updateAreaRegistryEntry,
type AreaRegistryEntry,
} from "../../../../../data/area/area_registry";
import {
apiContext,
registriesContext,
statesContext,
} from "../../../../../data/context";
import {
haCardSizeLarge,
haCardSizeSmall,
} from "../../../../../resources/ha-icons";
import { buttonLinkStyle } from "../../../../../resources/styles";
import type { HomeAssistant } from "../../../../../types";
import { showAreaRegistryDetailDialog } from "../../../../config/areas/show-dialog-area-registry-detail";
import type { LovelaceStrategyEditor } from "../../types";
import type { AreasDashboardStrategyConfig } from "../areas-dashboard-strategy";
@@ -44,7 +52,18 @@ export class HuiAreasDashboardStrategyEditor
extends LitElement
implements LovelaceStrategyEditor
{
@property({ attribute: false }) public hass?: HomeAssistant;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state()
private _config?: AreasDashboardStrategyConfig;
@@ -57,7 +76,7 @@ export class HuiAreasDashboardStrategyEditor
private _area?: string;
protected render() {
if (!this.hass || !this._config) {
if (!this._config) {
return nothing;
}
@@ -67,13 +86,17 @@ export class HuiAreasDashboardStrategyEditor
}
private _renderOverviewEditor() {
if (!this.hass || !this._config || !this._area) {
if (!this._config || !this._area || !this._states || !this._registries) {
return nothing;
}
const groups = getAreaGroupedEntities(this._area, this.hass);
const area = this._registries.areas[this._area];
const area = this.hass.areas[this._area];
const groups = this._groupedEntities(
this._area,
this._states,
this._registries
);
return keyed(
area.area_id,
@@ -83,9 +106,7 @@ export class HuiAreasDashboardStrategyEditor
<p>${area.name}</p>
</div>
<ha-expansion-panel
.header=${this.hass!.localize(
`ui.panel.lovelace.strategy.areas.sensors`
)}
.header=${this._localize(`ui.panel.lovelace.strategy.areas.sensors`)}
left-chevron
expanded
outlined
@@ -95,12 +116,12 @@ export class HuiAreasDashboardStrategyEditor
.path=${mdiThermometerWater}
></ha-svg-icon>
<p>
${this.hass!.localize(
${this._localize(
`ui.panel.lovelace.strategy.areas.sensors_description`,
{
edit_the_area: html`
<button class="link" @click=${this._editArea} .area=${area}>
${this.hass!.localize(
${this._localize(
"ui.panel.lovelace.strategy.areas.edit_the_area"
)}
</button>
@@ -116,7 +137,7 @@ export class HuiAreasDashboardStrategyEditor
return html`
<ha-expansion-panel
.header=${this.hass!.localize(
.header=${this._localize(
`ui.panel.lovelace.strategy.areas.groups.${group}`
)}
left-chevron
@@ -141,7 +162,7 @@ export class HuiAreasDashboardStrategyEditor
`
: html`
<p>
${this.hass!.localize(
${this._localize(
"ui.panel.lovelace.editor.strategy.areas.no_entities"
)}
</p>
@@ -155,7 +176,7 @@ export class HuiAreasDashboardStrategyEditor
}
private _renderAreaEditor() {
if (!this.hass || !this._config) {
if (!this._config) {
return nothing;
}
@@ -164,7 +185,7 @@ export class HuiAreasDashboardStrategyEditor
return html`
<ha-areas-floors-display-editor
.value=${value}
.label=${this.hass.localize(
.label=${this._localize(
"ui.panel.lovelace.editor.strategy.areas.areas_display"
)}
@value-changed=${this._areasFloorsDisplayChanged}
@@ -185,7 +206,7 @@ export class HuiAreasDashboardStrategyEditor
return html`
<ha-icon-button
.label=${this.hass!.localize(
.label=${this._localize(
`ui.panel.lovelace.editor.strategy.areas.${isLarge ? "use_compact_card" : "use_large_card"}`
)}
@click=${this._toggleAreaLargeCard}
@@ -237,6 +258,22 @@ export class HuiAreasDashboardStrategyEditor
}
}
private _groupedEntities = memoizeOne(
(
area: string,
states: ContextType<typeof statesContext>,
registries: ContextType<typeof registriesContext>
) =>
getAreaGroupedEntities(
area,
states,
registries.entities,
registries.devices,
registries.areas,
registries.floors
)
);
private _areasFloorsDisplayValue = memoizeOne(
(config: AreasDashboardStrategyConfig): AreasFloorsDisplayValue => ({
areas_display: config.areas_display,
@@ -252,7 +289,7 @@ export class HuiAreasDashboardStrategyEditor
showAreaRegistryDetailDialog(this, {
entry: area,
updateEntry: (values) =>
updateAreaRegistryEntry(this.hass!.callWS, area.area_id, values),
updateAreaRegistryEntry(this._api.callWS, area.area_id, values),
});
}
@@ -1,5 +1,8 @@
import { computeDomain } from "../../../../../common/entity/compute_domain";
import type { EntityFilterFunc } from "../../../../../common/entity/entity_filter";
import type {
EntityFilter,
EntityFilterFunc,
} from "../../../../../common/entity/entity_filter";
import { generateEntityFilter } from "../../../../../common/entity/entity_filter";
import { orderCompare } from "../../../../../common/string/compare";
import type { AreaRegistryEntry } from "../../../../../data/area/area_registry";
@@ -53,256 +56,136 @@ type AreaGroupsDisplayOptions = Record<string, DisplayOptions>;
export const getAreaGroupedEntities = (
area: string,
hass: HomeAssistant,
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
floors: HomeAssistant["floors"],
displayOptions?: AreaGroupsDisplayOptions
): AreaEntitiesByGroup => {
const allEntities = Object.keys(hass.states);
const allEntities = Object.keys(states);
const areaFilter = (filter: EntityFilter) =>
generateEntityFilter(states, entities, devices, areas, floors, filter);
const groupedFilters: AreaFilteredByGroup = {
lights: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "light",
area: area,
entity_category: "none",
}
),
areaFilter({
domain: "light",
area: area,
entity_category: "none",
}),
],
covers: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "cover",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "binary_sensor",
area: area,
device_class: ["door", "garage_door", "window"],
entity_category: "none",
}
),
areaFilter({
domain: "cover",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "binary_sensor",
area: area,
device_class: ["door", "garage_door", "window"],
entity_category: "none",
}),
],
climate: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "climate",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "humidifier",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "water_heater",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "fan",
area: area,
entity_category: "none",
}
),
areaFilter({
domain: "climate",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "humidifier",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "water_heater",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "fan",
area: area,
entity_category: "none",
}),
],
media_players: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "media_player",
area: area,
entity_category: "none",
}
),
areaFilter({
domain: "media_player",
area: area,
entity_category: "none",
}),
],
security: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "alarm_control_panel",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "lock",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "camera",
area: area,
entity_category: "none",
}
),
areaFilter({
domain: "alarm_control_panel",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "lock",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "camera",
area: area,
entity_category: "none",
}),
],
actions: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: ["script", "scene"],
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: ["automation"],
area: area,
entity_category: "none",
}
),
areaFilter({
domain: ["script", "scene"],
area: area,
entity_category: "none",
}),
areaFilter({
domain: ["automation"],
area: area,
entity_category: "none",
}),
],
others: [
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "vacuum",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "lawn_mower",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: "valve",
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: ["switch", "button", "input_boolean", "input_button"],
area: area,
entity_category: "none",
}
),
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
{
domain: [
"select",
"number",
"input_select",
"input_number",
"counter",
"timer",
"timer_list",
],
area: area,
entity_category: "none",
}
),
areaFilter({
domain: "vacuum",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "lawn_mower",
area: area,
entity_category: "none",
}),
areaFilter({
domain: "valve",
area: area,
entity_category: "none",
}),
areaFilter({
domain: ["switch", "button", "input_boolean", "input_button"],
area: area,
entity_category: "none",
}),
areaFilter({
domain: [
"select",
"number",
"input_select",
"input_number",
"counter",
"timer",
"timer_list",
],
area: area,
entity_category: "none",
}),
],
};
return Object.fromEntries(
Object.entries(groupedFilters).map(([group, filters]) => {
const entities = filters.reduce<string[]>(
const groupEntities = filters.reduce<string[]>(
(acc, filter) => [
...acc,
...allEntities.filter((entity) => filter(entity)),
@@ -316,9 +199,9 @@ export const getAreaGroupedEntities = (
const order = displayOptions?.[group]?.order;
let filteredEntities = entities;
let filteredEntities = groupEntities;
if (hidden) {
filteredEntities = entities.filter(
filteredEntities = groupEntities.filter(
(entity: string) => !hidden.has(entity)
);
}
+74
View File
@@ -4836,6 +4836,7 @@
"dismiss_failed": "Couldn't dismiss this meter",
"dismiss_all": "Dismiss all",
"dismiss_all_failed": "Couldn't dismiss these meters",
"show_more": "Show {count} more",
"show_dismissed": "Show dismissed meters ({count})",
"hide_dismissed": "Hide dismissed meters",
"dismissed": "Dismissed",
@@ -8593,9 +8594,82 @@
"status_online": "Online",
"status_offline": "Offline",
"my_network_title": "My network",
"show_map": "Show map",
"devices": "{count, plural,\n one {# device}\n other {# devices}\n}",
"device_count": "{count, plural,\n one {# device}\n other {# devices}\n}",
"entity_count": "{count, plural,\n one {# entity}\n other {# entities}\n}",
"visualization": {
"header": "MQTT map",
"toggle_tree_layout": "Tree view",
"show_more_info": "Show more info",
"go_to_device": "Go to device",
"show_config": "Show configuration",
"not_loaded": "MQTT is not loaded.",
"not_supported": "This version of Home Assistant does not support the MQTT map yet.",
"broker": "Broker",
"connected": "Connected",
"disconnected": "Disconnected",
"source": "Source",
"source_yaml": "YAML",
"source_discovery": "Other discovered",
"source_subentries": "Added in the UI",
"device": "Device",
"child_device": "Child device",
"no_linked_device": "No linked device",
"entity": "Entity",
"artifact_device_trigger": "Device trigger",
"artifact_tag": "Tag",
"subscribe_topic": "Subscribed topic",
"publish_topic": "Published topic",
"unavailable": "Unavailable",
"version": "Version",
"topic_count": "{count, plural,\n one {# topic}\n other {# topics}\n}",
"select_topic": "Select to show live messages",
"state": "State",
"node_id": "Node ID",
"last_received": "Last received",
"last_sent": "Last sent",
"config_view": {
"discovery_topic": "Discovery topic",
"device_discovery_topic": "Device discovery topic",
"origin": "Origin",
"support": "Support",
"show_as_yaml": "Show as YAML",
"copy_config": "Copy configuration",
"device_config": "Device configuration",
"device_discovery_payload": "Device discovery payload",
"discovery_payload": "Discovery payload",
"entity_config": "Entity configuration",
"copy_discovery_topic": "Copy discovery topic",
"no_config": "There is no known configuration for this item.",
"no_unique_id": "The configuration cannot be shown, because this entity has no unique_id in YAML.",
"yaml_device": "This device is set up in the YAML configuration of its entities.",
"subentry_device": "This device was added in the UI.",
"reconfigure_subentry": "Reconfigure device",
"load_failed": "The configuration could not be loaded."
},
"topic_view": {
"listening": "Listening at QoS {qos}",
"qos": "QoS {qos}",
"not_listening": "Not listening",
"live": "Live",
"messages": "{count, plural,\n one {# message}\n other {# messages}\n}",
"no_messages": "No messages received yet. New messages show up here live.",
"no_messages_sent": "No messages sent yet. New messages show up here live.",
"retained": "Retained",
"payload": "Payload",
"pretty_print": "Format JSON",
"copy_payload": "Copy payload",
"changes": "Changes from the previous message",
"no_previous": "There is no previous message to compare with.",
"unchanged": "The payload did not change.",
"change_added": "Added",
"change_removed": "Removed",
"change_changed": "Changed",
"change_previous": "Previous",
"change_current": "Current"
}
},
"description_publish": "Publish a packet",
"topic": "Topic",
"payload": "Payload (template allowed)",
+30 -15
View File
@@ -55,7 +55,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -90,7 +91,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -130,7 +132,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -162,7 +165,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -207,7 +211,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -233,7 +238,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -252,7 +258,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
[],
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -280,7 +287,8 @@ describe("observeConditionChanges – time boundaries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -350,7 +358,8 @@ describe("observeConditionChanges – media queries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -379,7 +388,8 @@ describe("observeConditionChanges – media queries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -408,7 +418,8 @@ describe("observeConditionChanges – media queries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -445,7 +456,8 @@ describe("observeConditionChanges – media queries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -468,7 +480,8 @@ describe("observeConditionChanges – media queries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -479,7 +492,8 @@ describe("observeConditionChanges – media queries", () => {
it("should handle empty conditions array", () => {
observeConditionChanges(
[],
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
@@ -504,7 +518,8 @@ describe("observeConditionChanges – media queries", () => {
observeConditionChanges(
conditions,
() => hass,
() => hass.locale,
() => hass.config,
(unsub) => listeners.push(unsub),
onChangeCallback
);
+53 -23
View File
@@ -37,7 +37,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
});
// Should be ~1 hour + 1 minute buffer = 61 minutes
expect(result).toBeGreaterThan(60 * 60 * 1000); // > 60 minutes
@@ -48,7 +50,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 9:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 9, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
});
// Should be ~23 hours + 1 minute buffer
expect(result).toBeGreaterThan(23 * 60 * 60 * 1000);
@@ -59,7 +63,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 8:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 8, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
});
// Should be scheduled for tomorrow
expect(result).toBeGreaterThan(23 * 60 * 60 * 1000);
@@ -69,7 +75,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:59:30 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 59, 30));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00:00",
});
// Should be ~30 seconds + 1 minute buffer
expect(result).toBeGreaterThan(30 * 1000);
@@ -82,7 +90,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 4:00 PM
vi.setSystemTime(new Date(2024, 0, 15, 16, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { before: "17:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
before: "17:00",
});
// Should be ~1 hour + 1 minute buffer
expect(result).toBeGreaterThan(60 * 60 * 1000);
@@ -93,7 +103,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 6:00 PM
vi.setSystemTime(new Date(2024, 0, 15, 18, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { before: "17:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
before: "17:00",
});
// Should be ~23 hours + 1 minute buffer
expect(result).toBeGreaterThan(23 * 60 * 60 * 1000);
@@ -106,7 +118,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
before: "17:00",
});
@@ -120,7 +132,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 10:00 AM (within 08:00-17:00 range)
vi.setSystemTime(new Date(2024, 0, 15, 10, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
before: "17:00",
});
@@ -134,7 +146,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 11:00 PM
vi.setSystemTime(new Date(2024, 0, 15, 23, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "22:00",
before: "06:00",
});
@@ -150,7 +162,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to Monday 10:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 10, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
weekdays: ["mon", "wed", "fri"],
});
@@ -163,7 +175,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to Monday 10:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 10, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
weekdays: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"],
});
@@ -175,7 +187,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to Monday 7:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
weekdays: ["mon", "wed", "fri"],
});
@@ -189,7 +201,7 @@ describe("calculateNextTimeUpdate", () => {
// Set time to Monday 11:00 PM
vi.setSystemTime(new Date(2024, 0, 15, 23, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
weekdays: ["mon", "wed", "fri"],
});
@@ -204,7 +216,11 @@ describe("calculateNextTimeUpdate", () => {
it("should return undefined when no conditions specified", () => {
vi.setSystemTime(new Date(2024, 0, 15, 10, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {});
const result = calculateNextTimeUpdate(
mockHass.locale,
mockHass.config,
{}
);
expect(result).toBeUndefined();
});
@@ -212,7 +228,7 @@ describe("calculateNextTimeUpdate", () => {
it("should return undefined when only all weekdays specified", () => {
vi.setSystemTime(new Date(2024, 0, 15, 10, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
weekdays: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"],
});
@@ -222,7 +238,7 @@ describe("calculateNextTimeUpdate", () => {
it("should return undefined when empty weekdays array", () => {
vi.setSystemTime(new Date(2024, 0, 15, 10, 0, 0));
const result = calculateNextTimeUpdate(mockHass, {
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
weekdays: [],
});
@@ -235,7 +251,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:59 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 59, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
});
// Should be ~1 minute for the boundary + 1 minute buffer = ~2 minutes
expect(result).toBeGreaterThan(60 * 1000); // > 1 minute
@@ -251,7 +269,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:00 AM local time
vi.setSystemTime(new Date(2024, 0, 15, 7, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
});
// Should calculate based on server timezone
expect(result).toBeDefined();
@@ -264,7 +284,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:00 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00",
});
// Should calculate based on local timezone
expect(result).toBeDefined();
@@ -277,7 +299,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 11:00 PM
vi.setSystemTime(new Date(2024, 0, 15, 23, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "00:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "00:00",
});
// Should be ~1 hour + 1 minute buffer until midnight
expect(result).toBeGreaterThan(60 * 60 * 1000);
@@ -288,7 +312,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 11:00 PM
vi.setSystemTime(new Date(2024, 0, 15, 23, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { before: "23:59" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
before: "23:59",
});
// Should be ~59 minutes + 1 minute buffer
expect(result).toBeGreaterThan(59 * 60 * 1000);
@@ -299,7 +325,9 @@ describe("calculateNextTimeUpdate", () => {
// Set time to 7:59:50 AM
vi.setSystemTime(new Date(2024, 0, 15, 7, 59, 50));
const result = calculateNextTimeUpdate(mockHass, { after: "08:00:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "08:00:00",
});
// Should be ~10 seconds + 1 minute buffer
expect(result).toBeGreaterThan(10 * 1000);
@@ -310,7 +338,9 @@ describe("calculateNextTimeUpdate", () => {
// March 10, 2024 at 1:00 AM PST - before spring forward
vi.setSystemTime(new Date(2024, 2, 10, 1, 0, 0));
const result = calculateNextTimeUpdate(mockHass, { after: "03:00" });
const result = calculateNextTimeUpdate(mockHass.locale, mockHass.config, {
after: "03:00",
});
// Should handle the transition where 2:00 AM doesn't exist
expect(result).toBeDefined();
@@ -1,7 +1,20 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type { Context, ContextType } from "@lit/context";
import { ContextProvider } from "@lit/context";
import { ReactiveElement } from "lit";
import { customElement } from "lit/decorators";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ConditionEvaluation } from "../../../src/common/controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../../../src/common/controllers/condition-evaluator-controller";
import {
ConditionEvaluator,
ConditionEvaluatorController,
} from "../../../src/common/controllers/condition-evaluator-controller";
import {
configContext,
connectionContext,
internationalizationContext,
registriesContext,
statesContext,
} from "../../../src/data/context";
import type { VisibilityCondition } from "../../../src/panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../../src/types";
@@ -24,13 +37,6 @@ interface CapturedSubscription {
let subs: CapturedSubscription[];
const createHost = (): ReactiveControllerHost => ({
addController: vi.fn(),
removeController: vi.fn(),
requestUpdate: vi.fn(),
updateComplete: Promise.resolve(true),
});
const createHass = (overrides: Partial<HomeAssistant> = {}): HomeAssistant =>
({
connection: {
@@ -47,9 +53,17 @@ const createHass = (overrides: Partial<HomeAssistant> = {}): HomeAssistant =>
...overrides,
}) as unknown as HomeAssistant;
const observeWith = (
controller: ConditionEvaluator,
conditions: VisibilityCondition[] | undefined,
hass: HomeAssistant | undefined
) => {
controller.setInputs(hass, hass?.connection, hass?.localize);
controller.observe(conditions);
};
interface Harness {
controller: ConditionEvaluatorController;
host: ReactiveControllerHost;
controller: ConditionEvaluator;
results: { result: ConditionEvaluation; error?: string }[];
last: () => { result: ConditionEvaluation; error?: string } | undefined;
}
@@ -58,19 +72,18 @@ const setup = async (
conditions: VisibilityCondition[],
hass: HomeAssistant = createHass()
): Promise<Harness> => {
const host = createHost();
const results: { result: ConditionEvaluation; error?: string }[] = [];
const controller = new ConditionEvaluatorController(host, {
const controller = new ConditionEvaluator({
resubscribeDelay: 0,
onResult: (result, error) => results.push({ result, error }),
});
controller.hostConnected();
controller.observe(conditions, hass);
controller.connect();
observeWith(controller, conditions, hass);
await tick();
return { controller, host, results, last: () => results[results.length - 1] };
return { controller, results, last: () => results[results.length - 1] };
};
describe("ConditionEvaluatorController", () => {
describe("ConditionEvaluator", () => {
beforeEach(() => {
subs = [];
global.matchMedia = vi.fn().mockImplementation((query) => ({
@@ -231,14 +244,14 @@ describe("ConditionEvaluatorController", () => {
it("re-subscribes when the condition tree changes and tears the old one down", async () => {
const hass = createHass();
const host = createHost();
const controller = new ConditionEvaluatorController(host, {
const controller = new ConditionEvaluator({
resubscribeDelay: 0,
onResult: () => undefined,
});
controller.hostConnected();
controller.connect();
controller.observe(
observeWith(
controller,
[cond({ condition: "state", entity: "light.a", state: "on" })],
hass
);
@@ -246,7 +259,8 @@ describe("ConditionEvaluatorController", () => {
expect(subs).toHaveLength(1);
const firstUnsub = subs[0].unsub;
controller.observe(
observeWith(
controller,
[cond({ condition: "state", entity: "light.b", state: "off" })],
hass
);
@@ -265,15 +279,15 @@ describe("ConditionEvaluatorController", () => {
vi.useFakeTimers();
try {
const hass = createHass();
const host = createHost();
const results: ConditionEvaluation[] = [];
const controller = new ConditionEvaluatorController(host, {
const controller = new ConditionEvaluator({
resubscribeDelay: 1000,
onResult: (result) => results.push(result),
});
controller.hostConnected();
controller.connect();
controller.observe(
observeWith(
controller,
[cond({ condition: "state", entity: "light.a", state: "on" })],
hass
);
@@ -283,7 +297,8 @@ describe("ConditionEvaluatorController", () => {
expect(controller.result).toBe("visible");
// Drop the old subscription immediately; don't keep its result.
controller.observe(
observeWith(
controller,
[cond({ condition: "state", entity: "light.a", state: "off" })],
hass
);
@@ -306,27 +321,34 @@ describe("ConditionEvaluatorController", () => {
it("re-subscribes an all-client tree change immediately", async () => {
const hass = createHass();
const host = createHost();
const controller = new ConditionEvaluatorController(host, {
const controller = new ConditionEvaluator({
resubscribeDelay: 1000,
onResult: () => undefined,
});
controller.hostConnected();
controller.observe([cond({ condition: "user", users: ["user1"] })], hass);
controller.connect();
observeWith(
controller,
[cond({ condition: "user", users: ["user1"] })],
hass
);
expect(controller.result).toBe("visible");
controller.observe([cond({ condition: "user", users: ["other"] })], hass);
observeWith(
controller,
[cond({ condition: "user", users: ["other"] })],
hass
);
// no debounce for a tree with nothing to subscribe to
expect(controller.result).toBe("hidden");
});
it("drops the subscription when observation is cleared, even under hass churn", async () => {
const host = createHost();
const controller = new ConditionEvaluatorController(host, {
const controller = new ConditionEvaluator({
resubscribeDelay: 20,
onResult: () => undefined,
});
controller.hostConnected();
controller.observe(
controller.connect();
observeWith(
controller,
[cond({ condition: "state", entity: "light.a", state: "on" })],
createHass()
);
@@ -336,9 +358,9 @@ describe("ConditionEvaluatorController", () => {
expect(subs).toHaveLength(1);
// Clearing used to keep rescheduling because `undefined` meant "nothing pending".
controller.observe(undefined, createHass());
controller.observe(undefined, createHass());
controller.observe(undefined, createHass());
observeWith(controller, undefined, createHass());
observeWith(controller, undefined, createHass());
observeWith(controller, undefined, createHass());
await tick();
expect(subs[0].unsub).toHaveBeenCalledTimes(1);
expect(subs).toHaveLength(1);
@@ -346,8 +368,7 @@ describe("ConditionEvaluatorController", () => {
});
it("subscribes once hass arrives after the conditions were observed", async () => {
const host = createHost();
const controller = new ConditionEvaluatorController(host, {
const controller = new ConditionEvaluator({
resubscribeDelay: 0,
onResult: () => undefined,
});
@@ -355,13 +376,13 @@ describe("ConditionEvaluatorController", () => {
cond({ condition: "state", entity: "light.a", state: "on" }),
];
// Host connected with its config set, hass not yet provided.
controller.hostConnected();
controller.observe(conditions, undefined);
controller.connect();
observeWith(controller, conditions, undefined);
await tick();
expect(subs).toHaveLength(0);
expect(controller.result).toBe("unknown");
controller.observe(conditions, createHass());
observeWith(controller, conditions, createHass());
await tick();
expect(subs).toHaveLength(1);
subs[0].push({ result: true });
@@ -383,7 +404,8 @@ describe("ConditionEvaluatorController", () => {
hass
);
expect(subs).toHaveLength(1);
controller.observe(
observeWith(
controller,
[
cond({
condition: "numeric_state",
@@ -408,7 +430,10 @@ describe("ConditionEvaluatorController", () => {
// same conditions reference, new hass object on the same connection →
// recompute only, no new subscription
controller.observe(conditions, { ...hass, states: {} } as HomeAssistant);
observeWith(controller, conditions, {
...hass,
states: {},
} as HomeAssistant);
await tick();
expect(subs).toHaveLength(1);
});
@@ -422,7 +447,7 @@ describe("ConditionEvaluatorController", () => {
const firstUnsub = subs[0].unsub;
// a replacement connection carries none of the old subscriptions
controller.observe(conditions, createHass());
observeWith(controller, conditions, createHass());
await tick();
expect(firstUnsub).toHaveBeenCalledTimes(1);
expect(subs).toHaveLength(2);
@@ -433,7 +458,7 @@ describe("ConditionEvaluatorController", () => {
cond({ condition: "state", entity: "light.a", state: "on" }),
]);
const { unsub } = subs[0];
controller.hostDisconnected();
controller.disconnect();
await tick();
expect(unsub).toHaveBeenCalledTimes(1);
});
@@ -443,7 +468,7 @@ describe("ConditionEvaluatorController", () => {
cond({ condition: "state", entity: "light.a", state: "on" }),
]);
const stale = subs[0];
controller.hostDisconnected();
controller.disconnect();
await tick();
stale.push({ result: true });
// still unknown — the stale push from the torn-down subscription is ignored
@@ -460,7 +485,7 @@ describe("ConditionEvaluatorController", () => {
expect(subs).toHaveLength(1);
const firstUnsub = subs[0].unsub;
controller.observe(make(), { ...hass, states: {} } as HomeAssistant);
observeWith(controller, make(), { ...hass, states: {} } as HomeAssistant);
await tick();
expect(subs).toHaveLength(1);
@@ -474,7 +499,7 @@ describe("ConditionEvaluatorController", () => {
subs[0].push({ result: true });
expect(controller.result).toBe("visible");
controller.hostDisconnected();
controller.disconnect();
await tick();
expect(controller.result).toBe("unknown");
@@ -493,13 +518,128 @@ describe("ConditionEvaluatorController", () => {
expect(results.length).toBe(countBefore + 1);
expect(results[results.length - 1].result).toBe("visible");
});
});
it("requests a host update when the result changes", async () => {
const { host } = await setup([
@customElement("test-condition-evaluator-host")
class TestHost extends ReactiveElement {
public results: ConditionEvaluation[] = [];
public controller = new ConditionEvaluatorController(this, {
resubscribeDelay: 0,
onResult: (result) => this.results.push(result),
});
}
declare global {
interface HTMLElementTagNameMap {
"test-condition-evaluator-host": TestHost;
}
}
describe("ConditionEvaluatorController", () => {
let container: HTMLElement | undefined;
beforeEach(() => {
subs = [];
});
afterEach(() => {
container?.remove();
container = undefined;
});
it("evaluates with inputs from context and follows their changes", async () => {
const hass = createHass();
container = document.createElement("div");
const provide = <T>(context: Context<unknown, T>, value: T) =>
new ContextProvider(container!, { context, initialValue: value });
provide(statesContext, hass.states);
const config = provide(configContext, {
config: hass.config,
user: hass.user,
} as ContextType<typeof configContext>);
provide(internationalizationContext, {
locale: hass.locale,
localize: (key: string) => key,
} as unknown as ContextType<typeof internationalizationContext>);
provide(registriesContext, {
entities: {},
devices: {},
areas: {},
floors: {},
});
const connection = provide(connectionContext, {
connection: hass.connection,
} as ContextType<typeof connectionContext>);
const host = document.createElement("test-condition-evaluator-host");
const requestUpdate = vi.spyOn(host, "requestUpdate");
container.appendChild(host);
document.body.appendChild(container);
await host.updateComplete;
host.controller.observe([
cond({ condition: "user", users: ["user1"] }),
cond({ condition: "state", entity: "light.a", state: "on" }),
]);
(host.requestUpdate as ReturnType<typeof vi.fn>).mockClear();
await tick();
expect(subs).toHaveLength(1);
subs[0].push({ result: true });
expect(host.requestUpdate).toHaveBeenCalled();
expect(host.controller.result).toBe("visible");
expect(requestUpdate).toHaveBeenCalled();
config.setValue({
config: hass.config,
user: { id: "other" },
} as ContextType<typeof configContext>);
expect(host.controller.result).toBe("hidden");
connection.setValue({
connection: createHass().connection,
} as ContextType<typeof connectionContext>);
await tick();
expect(subs[0].unsub).toHaveBeenCalledTimes(1);
expect(subs).toHaveLength(2);
});
it("evaluates client conditions before states and registries load", async () => {
const hass = createHass();
container = document.createElement("div");
const provide = <T>(context: Context<unknown, T>, value: T) =>
new ContextProvider(container!, { context, initialValue: value });
provide(statesContext, null as unknown as HomeAssistant["states"]);
provide(configContext, {
config: hass.config,
user: hass.user,
} as ContextType<typeof configContext>);
provide(internationalizationContext, {
locale: hass.locale,
} as unknown as ContextType<typeof internationalizationContext>);
provide(registriesContext, {
entities: null,
devices: null,
areas: null,
floors: null,
} as unknown as ContextType<typeof registriesContext>);
provide(connectionContext, {
connection: hass.connection,
} as ContextType<typeof connectionContext>);
const host = document.createElement("test-condition-evaluator-host");
container.appendChild(host);
document.body.appendChild(container);
await host.updateComplete;
host.controller.observe([
cond({
condition: "or",
conditions: [
{ condition: "user", users: ["user1"] },
{ condition: "state", entity: "light.a", state: "on" },
],
}),
]);
await tick();
expect(host.controller.result).toBe("visible");
});
});
@@ -247,8 +247,8 @@ describe("computeStateDisplay", () => {
};
it.each([
["en", "November 18, 2017"],
["de", "18. November 2017"],
["en", "11/18/2017"],
["de", "18.11.2017"],
])("Uses the language's date format: %s", (language, expected) => {
localeData.language = language;
assert.strictEqual(
@@ -257,6 +257,37 @@ describe("computeStateDisplay", () => {
);
});
it.each([
[DateFormat.DMY, "18/11/2017"],
[DateFormat.MDY, "11/18/2017"],
[DateFormat.YMD, "2017/11/18"],
])("Uses the selected date format %s", (dateFormat, expected) => {
localeData.date_format = dateFormat;
assert.strictEqual(
computeStateDisplay(localize, stateObj, localeData, demoConfig, {}),
expected
);
});
it("Uses the system date format independently of the language", () => {
const locale = { ...localeData, date_format: DateFormat.system };
const englishDisplay = computeStateDisplay(
localize,
stateObj,
{ ...locale, language: "en" },
demoConfig,
{}
);
const germanDisplay = computeStateDisplay(
localize,
stateObj,
{ ...locale, language: "de" },
demoConfig,
{}
);
assert.strictEqual(germanDisplay, englishDisplay);
});
it("Does not shift the calendar date to the server timezone", () => {
localeData.time_zone = TimeZone.server;
assert.strictEqual(
@@ -270,7 +301,7 @@ describe("computeStateDisplay", () => {
},
{}
),
"November 18, 2017"
"11/18/2017"
);
});
@@ -284,7 +315,7 @@ describe("computeStateDisplay", () => {
{},
"2021-07-04"
),
"July 4, 2021"
"7/4/2021"
);
});
@@ -312,7 +343,7 @@ describe("computeStateDisplay", () => {
{},
"2020-02-29"
),
"February 29, 2020"
"2/29/2020"
);
});
@@ -371,6 +402,7 @@ describe("computeStateDisplay", () => {
});
it.each(["date", "input_datetime"])("Localizes %s with date", (domain) => {
localeData.date_format = DateFormat.DMY;
const stateObj: any = {
entity_id: `${domain}.test`,
state: "2017-11-18",
@@ -387,7 +419,7 @@ describe("computeStateDisplay", () => {
};
assert.strictEqual(
computeStateDisplay(localize, stateObj, localeData, demoConfig, {}),
"November 18, 2017"
"18/11/2017"
);
});
@@ -490,7 +522,7 @@ describe("computeStateDisplay", () => {
{},
"2021-07-04"
),
"July 4, 2021"
"7/4/2021"
);
});
@@ -0,0 +1,327 @@
import { describe, expect, it } from "vitest";
import type {
FollowRoam,
GraphView,
} from "../../../src/components/chart/network-graph-view";
import {
fitRoam,
labelReach,
layoutBounds,
layoutRoam,
roamSource,
selectedNodeRoam,
TREE_LABEL_ROOM,
} from "../../../src/components/chart/network-graph-view";
// A graphRoam pans first and then zooms around the origin
const applyRoamX = (x: number, roam: FollowRoam) =>
roam.originX + (x + roam.dx - roam.originX) * (roam.zoom ?? 1);
const applyRoamY = (y: number, roam: FollowRoam) =>
roam.originY + (y + roam.dy - roam.originY) * (roam.zoom ?? 1);
const forceView: GraphView = {
width: 800,
height: 600,
zoom: 1,
treeLayout: false,
};
const treeView: GraphView = { ...forceView, treeLayout: true };
describe("roamSource", () => {
it("is the point that the roam moves to the given point", () => {
const roam = { dx: 120, dy: -40, zoom: 1.5, originX: 300, originY: 200 };
const [x, y] = roamSource(roam, { x: 400, y: 250 });
expect(applyRoamX(x, roam)).toBeCloseTo(400);
expect(applyRoamY(y, roam)).toBeCloseTo(250);
});
});
describe("labelReach", () => {
it("is the distance from the node center to the right of the label", () => {
expect(labelReach({ x: 110, width: 90 }, 100)).toBe(100);
});
});
describe("layoutBounds", () => {
it("spans the positions and skips missing ones", () => {
expect(layoutBounds([[1, 5], undefined, [-3, 2], [4, -1]])).toEqual({
left: -3,
top: -1,
right: 4,
bottom: 5,
});
});
it("is undefined without positions", () => {
expect(layoutBounds([undefined])).toBeUndefined();
});
});
describe("selectedNodeRoam in a force layout", () => {
it("centers the node, zoomed in up to the max zoom", () => {
expect(
selectedNodeRoam(forceView, { x: 100, y: 100 }, [
{ x: 200, y: 100, size: 30 },
])
).toEqual({ dx: 300, dy: 200, zoom: 2, originX: 400, originY: 300 });
});
it("zooms out so the neighbors stay clear of the controls", () => {
const roam = selectedNodeRoam(forceView, { x: 100, y: 100 }, [
{ x: 756, y: 100, size: 30 },
{ x: 100, y: 556, size: 30 },
]);
expect(roam?.zoom).toBeCloseTo(0.5);
expect(applyRoamX(756, roam!)).toBeCloseTo(800 - 72);
});
it("is undefined when the node is centered at its zoom", () => {
expect(
selectedNodeRoam({ ...forceView, zoom: 2 }, { x: 400, y: 300 }, [
{ x: 600, y: 300, size: 30 },
])
).toBeUndefined();
});
it("keeps all neighbors in view and leaves out the label", () => {
const neighbors = [
{ x: -556, y: 100, size: 30 },
{ x: 150, y: 100, size: 30 },
];
const roam = selectedNodeRoam(
forceView,
{ x: 100, y: 100 },
neighbors,
500
);
expect(roam).toEqual(
selectedNodeRoam(forceView, { x: 100, y: 100 }, neighbors)
);
// The neighbor to the left limits the zoom
expect(roam?.zoom).toBeCloseTo(328 / 656);
});
});
describe("selectedNodeRoam in a tree layout", () => {
it("keeps the node left, with room for the labels of its children", () => {
const roam = selectedNodeRoam(treeView, { x: 100, y: 300 }, [
{ x: 300, y: 300, size: 10 },
]);
expect(roam?.originX).toBe(200);
expect(roam?.dx).toBe(100);
expect(roam?.dy).toBe(0);
// The child ends the label room away from the right
expect(applyRoamX(300, roam!)).toBeCloseTo(800 - TREE_LABEL_ROOM);
});
it("leaves out the parents", () => {
const children = [{ x: 300, y: 300, size: 10 }];
expect(
selectedNodeRoam(treeView, { x: 100, y: 300 }, [
{ x: -1000, y: 0, size: 10 },
...children,
])
).toEqual(selectedNodeRoam(treeView, { x: 100, y: 300 }, children));
});
it("zooms so the label of the node fits before its children", () => {
const roam = selectedNodeRoam(
treeView,
{ x: 100, y: 300 },
[{ x: 120, y: 300, size: 10 }],
150
);
// The label, the spacing and half the child
const labelRoom = 150 + 8 + 5;
expect(applyRoamX(120, roam!) - applyRoamX(100, roam!)).toBeCloseTo(
labelRoom
);
});
it("keeps the label clear of children that do not all fit", () => {
const roam = selectedNodeRoam(
treeView,
{ x: 100, y: 300 },
[
{ x: 300, y: -700, size: 30 },
{ x: 300, y: 300, size: 30 },
{ x: 300, y: 1300, size: 30 },
],
200
);
// The label, the spacing and half the child
expect(applyRoamX(300, roam!) - applyRoamX(100, roam!)).toBeCloseTo(
200 + 8 + 15
);
});
it("moves the node left for its label on a narrow view", () => {
const children = [{ x: 120, y: 300, size: 10 }];
expect(
selectedNodeRoam(
{ ...treeView, width: 500 },
{ x: 100, y: 300 },
children,
150
)?.originX
).toBe(500 - TREE_LABEL_ROOM - 163);
expect(
selectedNodeRoam(
{ ...treeView, width: 300 },
{ x: 100, y: 300 },
children,
150
)?.originX
).toBe(32);
});
it("ignores the label without children", () => {
expect(
selectedNodeRoam(treeView, { x: 100, y: 300 }, [], 150)?.originX
).toBe(200);
});
it("zooms so the children get room between them", () => {
const roam = selectedNodeRoam(treeView, { x: 100, y: 300 }, [
{ x: 300, y: 310, size: 20 },
{ x: 300, y: 300, size: 20 },
]);
// Half of both nodes and the spacing
expect(roam?.zoom).toBeCloseTo(28 / 10);
});
it("keeps a least gap for the labels of small children", () => {
const roam = selectedNodeRoam(treeView, { x: 100, y: 300 }, [
{ x: 300, y: 300, size: 4 },
{ x: 300, y: 310, size: 4 },
]);
expect(roam?.zoom).toBeCloseTo(24 / 10);
});
it("gives room to children that are less than a pixel apart", () => {
const roam = selectedNodeRoam(treeView, { x: 100, y: 300 }, [
{ x: 300, y: 300, size: 20 },
{ x: 300, y: 300.4, size: 20 },
]);
expect(roam?.zoom).toBeCloseTo(28 / 0.4);
});
it("skips children folded onto each other", () => {
const roam = selectedNodeRoam(treeView, { x: 100, y: 300 }, [
{ x: 300, y: 300, size: 20 },
{ x: 300, y: 300, size: 20 },
]);
expect(roam?.zoom).toBeCloseTo(360 / 200);
});
});
describe("fitRoam", () => {
it("fits the bounds centered between the margins", () => {
const roam = fitRoam(forceView, {
left: 100,
top: 100,
right: 600,
bottom: 200,
});
// 656 of the width is left between the margins
expect(roam?.zoom).toBeCloseTo(656 / 500);
expect(applyRoamX(100, roam!)).toBeCloseTo(72);
expect(applyRoamX(600, roam!)).toBeCloseTo(800 - 72);
expect(applyRoamY(150, roam!)).toBeCloseTo(300);
});
it("zooms in no further than the max zoom", () => {
const roam = fitRoam(
{ ...forceView, zoom: 1.5 },
{ left: 390, top: 290, right: 410, bottom: 310 }
);
expect(roam?.zoom).toBeCloseTo(2 / 1.5);
});
it("leaves room for the labels right of a tree", () => {
const roam = fitRoam(treeView, {
left: 0,
top: 100,
right: 976,
bottom: 200,
});
expect(roam?.zoom).toBeCloseTo(0.5);
expect(applyRoamX(0, roam!)).toBeCloseTo(72);
expect(applyRoamX(976, roam!)).toBeCloseTo(800 - TREE_LABEL_ROOM);
});
it("shrinks the margins on a narrow view", () => {
const view = { ...treeView, width: 320 };
const roam = fitRoam(view, { left: 0, top: 0, right: 1000, bottom: 100 });
// Half the width is left for the tree, the rest for the margins
expect(roam?.zoom).toBeCloseTo(160 / 1000);
expect(applyRoamX(0, roam!)).toBeCloseTo((160 * 72) / (72 + 240));
expect(320 - applyRoamX(1000, roam!)).toBeCloseTo((160 * 240) / (72 + 240));
});
it("centers a force layout on a narrow view", () => {
const roam = fitRoam(
{ ...forceView, width: 200 },
{ left: 0, top: 0, right: 1000, bottom: 100 }
);
expect(applyRoamX(500, roam!)).toBeCloseTo(100);
});
it("is undefined when the bounds fit already", () => {
expect(
fitRoam(
{ ...forceView, zoom: 2 },
{ left: 300, top: 250, right: 500, bottom: 350 }
)
).toBeUndefined();
});
});
describe("layoutRoam", () => {
const bounds = { left: -50, top: -50, right: 50, bottom: 50 };
const current = { scale: 1, x: 100, y: 50 };
const initial = { scale: 2, x: 400, y: 300, width: 800, height: 600 };
const currentBounds = { left: 50, top: 0, right: 150, bottom: 100 };
it("goes back to the first view of the force layout", () => {
const roam = layoutRoam(forceView, bounds, current, initial)!;
for (const point of [-50, 0, 50]) {
expect(applyRoamX(current.scale * point + current.x, roam)).toBeCloseTo(
initial.scale * point + initial.x
);
expect(applyRoamY(current.scale * point + current.y, roam)).toBeCloseTo(
initial.scale * point + initial.y
);
}
});
it("is undefined when the view is there already", () => {
expect(layoutRoam(forceView, bounds, initial, initial)).toBeUndefined();
});
it("fits the nodes when they no longer fit in the first view", () => {
const wider = { ...bounds, right: 200 };
expect(layoutRoam(forceView, wider, current, initial)).toEqual(
fitRoam(forceView, { ...currentBounds, right: 300 })
);
});
it("fits the nodes when the chart has another size", () => {
const wider = { ...forceView, width: 1200 };
expect(layoutRoam(wider, bounds, current, initial)).toEqual(
fitRoam(wider, currentBounds)
);
});
it("fits the nodes without a first view", () => {
expect(layoutRoam(forceView, bounds, current)).toEqual(
fitRoam(forceView, currentBounds)
);
});
it("fits a tree", () => {
expect(layoutRoam(treeView, bounds, current, initial)).toEqual(
fitRoam(treeView, currentBounds)
);
});
});
@@ -0,0 +1,173 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type { HaChartBase } from "../../../src/components/chart/ha-chart-base";
import {
LAYOUT_ANIMATION_TIMEOUT,
NetworkLayoutController,
} from "../../../src/components/chart/network-layout-controller";
// A graph series without a view, so the view has nowhere to move. Reduced
// motion and a running force layout leave its animation off.
const createChart = (animated: boolean) => {
const handlers = new Map<string, Set<() => void>>();
const series = { isAnimationEnabled: () => animated };
return {
handlers,
isDisposed: () => false,
getModel: () => ({ getSeriesByIndex: () => series }),
on: (event: string, handler: () => void) => {
if (!handlers.has(event)) {
handlers.set(event, new Set());
}
handlers.get(event)!.add(handler);
},
off: (event: string, handler: () => void) => {
handlers.get(event)?.delete(handler);
},
trigger: (event: string) => {
for (const handler of [...(handlers.get(event) ?? [])]) {
handler();
}
},
};
};
const setup = (options: { chart?: boolean; reducedMotion?: boolean } = {}) => {
const chart = createChart(!options.reducedMotion);
const baseChart = { chart, updateComplete: Promise.resolve(true) };
const state = { treeLayout: false };
const host = {
addController: vi.fn(),
removeController: vi.fn(),
requestUpdate: vi.fn(),
updateComplete: Promise.resolve(true),
} as ReactiveControllerHost;
const config = {
chart: () =>
options.chart === false
? undefined
: (baseChart as unknown as HaChartBase),
treeLayout: () => state.treeLayout,
reducedMotion: () => options.reducedMotion ?? false,
selectedNode: () => undefined,
selectedNodeRoam: () => undefined,
saveNodePositions: vi.fn(),
moveStarted: vi.fn(),
moveEnded: vi.fn(),
};
const controller = new NetworkLayoutController(host, config);
const update = (treeLayout: boolean) => {
state.treeLayout = treeLayout;
controller.hostUpdate();
controller.hostUpdated();
};
return { chart, host, config, controller, update };
};
describe("NetworkLayoutController", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("does not move the view on the first update", () => {
const { config, controller, update } = setup();
update(true);
expect(controller.moving).toBe(false);
expect(config.saveNodePositions).not.toHaveBeenCalled();
expect(config.moveStarted).not.toHaveBeenCalled();
});
it("saves the positions of the force layout on a switch to the tree", () => {
const { config, controller, update } = setup();
update(false);
update(true);
expect(config.saveNodePositions).toHaveBeenCalledOnce();
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(true);
});
it("keeps physics off until the nodes are back in the force layout", async () => {
const { chart, config, controller, host, update } = setup();
update(true);
update(false);
expect(controller.settling).toBe(true);
expect(controller.moving).toBe(true);
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
chart.trigger("finished");
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
expect(host.requestUpdate).toHaveBeenCalledOnce();
expect(config.moveEnded).toHaveBeenCalledOnce();
expect(chart.handlers.get("finished")?.size).toBe(0);
});
it("stops waiting for the nodes after a timeout", async () => {
const { chart, controller, update } = setup();
update(true);
update(false);
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
vi.advanceTimersByTime(LAYOUT_ANIMATION_TIMEOUT);
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
expect(chart.handlers.get("finished")?.size).toBe(0);
});
it("does not wait without a chart or with reduced motion", async () => {
for (const options of [{ chart: false }, { reducedMotion: true }]) {
const { config, controller, update } = setup(options);
update(true);
update(false);
// eslint-disable-next-line no-await-in-loop
await vi.waitFor(() => expect(config.moveEnded).toHaveBeenCalledOnce());
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
}
});
it("ends a selection at once when the view stays", async () => {
const { chart, config, controller } = setup();
controller.moveToSelectedNode();
expect(controller.moving).toBe(true);
expect(config.moveStarted).toHaveBeenCalledOnce();
await vi.waitFor(() => expect(config.moveEnded).toHaveBeenCalledOnce());
expect(controller.moving).toBe(false);
expect(chart.handlers.get("finished")).toBeUndefined();
});
it("waits for the nodes of a layout switch that a selection replaces", async () => {
const { chart, config, controller, update } = setup();
update(true);
update(false);
controller.moveToSelectedNode();
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
expect(controller.settling).toBe(true);
chart.trigger("finished");
expect(controller.settling).toBe(false);
expect(config.moveEnded).toHaveBeenCalledOnce();
});
it("clears its state when the host disconnects", async () => {
const { chart, config, controller, update } = setup();
update(true);
update(false);
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
controller.hostDisconnected();
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
expect(chart.handlers.get("finished")?.size).toBe(0);
vi.advanceTimersByTime(LAYOUT_ANIMATION_TIMEOUT);
expect(config.moveEnded).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,258 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { NetworkData } from "../../../../../../src/components/chart/ha-network-graph";
import type { MQTTExplorerStructure } from "../../../../../../src/data/mqtt";
import { createMQTTNetworkChartData } from "../../../../../../src/panels/config/integrations/integration-panels/mqtt/mqtt-network-data";
import type { LocalizeFunc } from "../../../../../../src/common/translations/localize";
// The localize stub returns the key, so the legend names are the keys
const category = (key: string) => `ui.panel.config.mqtt.visualization.${key}`;
const DEFAULT_HIDDEN = [
category("entity"),
category("artifact_device_trigger"),
category("artifact_tag"),
];
const HUB = "device:hub";
const CHILD = "device:child";
const HUB_ENTITY = "entity:sensor.hub_temperature";
const CHILD_ENTITY = "entity:sensor.child_humidity";
const TRIGGER = "artifact:device_trigger:hub_button";
const STRUCTURE: MQTTExplorerStructure = {
broker: { connected: true, host: "localhost", port: 1883 },
sources: [
{ id: "origin:Z2M", type: "discovery", title: "Z2M", sw_version: null },
],
devices: [
{
device_id: "hub",
name: "Hub",
sources: ["origin:Z2M"],
via_device_id: null,
child_device: false,
},
{
device_id: "child",
name: "Child",
sources: ["origin:Z2M"],
via_device_id: "hub",
child_device: true,
},
],
entities: [
{
entity_id: "sensor.hub_temperature",
name: "Temperature",
available: true,
source: "origin:Z2M",
device_id: "hub",
node_id: null,
topics: [{ topic: "z2m/hub", direction: "subscribe", qos: 0 }],
},
{
entity_id: "sensor.child_humidity",
name: "Humidity",
available: true,
source: "origin:Z2M",
device_id: "child",
node_id: null,
topics: [{ topic: "z2m/child/humidity", direction: "subscribe", qos: 0 }],
},
],
artifacts: [
{
artifact_id: "device_trigger:hub_button",
type: "device_trigger",
source: "origin:Z2M",
device_id: "hub",
node_id: null,
topics: [{ topic: "z2m/hub/action", direction: "subscribe", qos: 0 }],
},
],
};
const localize = ((key: string) => key) as LocalizeFunc;
interface Scenario {
focusedNode?: string;
searchFilter?: string;
hiddenCategories: string[];
}
const chartData = (
scenario: Scenario,
treeLayout = false,
structure = STRUCTURE
) =>
createMQTTNetworkChartData(
structure,
false,
localize,
{} as Element,
false,
[],
scenario.focusedNode,
scenario.searchFilter,
scenario.hiddenCategories,
treeLayout
);
// The IDs of the nodes the legend shows: a node without a category always shows
const shownNodeIds = (data: NetworkData, hiddenCategories: string[]) =>
data.nodes
.filter(
(node) =>
node.category === undefined ||
!hiddenCategories.includes(data.categories![node.category].name)
)
.map((node) => node.id);
const SCENARIOS = {
default_legend: { hiddenCategories: DEFAULT_HIDDEN },
focused_device: { focusedNode: HUB, hiddenCategories: DEFAULT_HIDDEN },
search_in_hidden_category: {
searchFilter: "humidity",
hiddenCategories: DEFAULT_HIDDEN,
},
hidden_child_device_with_match_below: {
searchFilter: "humidity",
hiddenCategories: [...DEFAULT_HIDDEN, category("child_device")],
},
} satisfies Record<string, Scenario>;
describe("createMQTTNetworkChartData", () => {
beforeEach(() => {
vi.stubGlobal("getComputedStyle", () => ({
getPropertyValue: () => "#808080",
}));
});
afterEach(() => {
vi.unstubAllGlobals();
});
it.each([
{
name: "default_legend",
shown: ["broker", "source:origin:Z2M", HUB, CHILD],
},
{
name: "focused_device",
// The child device's own items stay hidden
shown: ["broker", "source:origin:Z2M", HUB, CHILD, HUB_ENTITY, TRIGGER],
},
{
name: "search_in_hidden_category",
shown: ["broker", "source:origin:Z2M", HUB, CHILD, CHILD_ENTITY],
},
{
name: "hidden_child_device_with_match_below",
// The hidden child device stays, so the match keeps its link
shown: ["broker", "source:origin:Z2M", HUB, CHILD, CHILD_ENTITY],
},
] as const)("shows the right nodes: $name", ({ name, shown }) => {
const scenario = SCENARIOS[name];
expect(
shownNodeIds(chartData(scenario), scenario.hiddenCategories).sort()
).toEqual([...shown].sort());
});
it.each(Object.keys(SCENARIOS) as (keyof typeof SCENARIOS)[])(
"links every shown node to a shown parent: %s",
(name) => {
const scenario = SCENARIOS[name];
const data = chartData(scenario);
const nodeIds = new Set(data.nodes.map((node) => node.id));
for (const link of data.links) {
expect(nodeIds).toContain(link.source);
expect(nodeIds).toContain(link.target);
}
const shown = new Set(shownNodeIds(data, scenario.hiddenCategories));
for (const id of shown) {
if (id !== "broker") {
expect(
data.links.some(
(link) => link.target === id && shown.has(link.source)
)
).toBe(true);
}
}
}
);
it.each(Object.keys(SCENARIOS) as (keyof typeof SCENARIOS)[])(
"gives each shown node its own place in the tree: %s",
(name) => {
const scenario = SCENARIOS[name];
const data = chartData(scenario, true);
const shown = new Set(shownNodeIds(data, scenario.hiddenCategories));
const places = data.nodes
.filter((node) => shown.has(node.id))
.map((node) => `${node.x},${node.y}`);
expect(new Set(places).size).toBe(places.length);
}
);
it("keeps a theme color it cannot fade", () => {
vi.stubGlobal("getComputedStyle", () => ({
getPropertyValue: () => "light-dark(#ffffff, #000000)",
}));
// A focus fades the other nodes
const data = chartData({ focusedNode: HUB, hiddenCategories: [] });
expect(
data.nodes.find((node) => node.id === CHILD_ENTITY)!.itemStyle!.color
).toBe("light-dark(#ffffff, #000000)");
});
it("folds a hidden node onto its parent in the tree", () => {
const data = chartData({ hiddenCategories: DEFAULT_HIDDEN }, true);
const hub = data.nodes.find((node) => node.id === HUB)!;
const entity = data.nodes.find((node) => node.id === HUB_ENTITY)!;
expect(entity.y).toBe(hub.y);
expect(entity.x).toBeGreaterThan(hub.x!);
});
it.each([
{ name: "self", via: { hub: "hub" } },
{ name: "mutual", via: { hub: "child", child: "hub" } },
] as { name: string; via: Record<string, string> }[])(
"links a loop of parent devices to their source: $name",
({ via }) => {
const structure: MQTTExplorerStructure = {
...STRUCTURE,
devices: STRUCTURE.devices.map((device) => ({
...device,
via_device_id: via[device.device_id] ?? device.via_device_id,
})),
};
const data = chartData({ hiddenCategories: [] }, true, structure);
expect(data.links).toContainEqual(
expect.objectContaining({ source: "source:origin:Z2M", target: HUB })
);
// The tree only places the nodes it reaches from the broker
expect(data.nodes.filter((node) => node.x === undefined)).toEqual([]);
}
);
it("places the items of a device with two subentry sources apart", () => {
const structure: MQTTExplorerStructure = {
...STRUCTURE,
sources: [
{ id: "subentry:a", type: "subentry", title: "A", sw_version: null },
{ id: "subentry:b", type: "subentry", title: "B", sw_version: null },
],
devices: [
{ ...STRUCTURE.devices[0], sources: ["subentry:a", "subentry:b"] },
],
entities: STRUCTURE.entities.map((entity) => ({
...entity,
source: "subentry:a",
device_id: "hub",
})),
artifacts: [],
};
const data = chartData({ hiddenCategories: [] }, true, structure);
const places = data.nodes.map((node) => `${node.x},${node.y}`);
expect(new Set(places).size).toBe(places.length);
});
});
@@ -0,0 +1,82 @@
import { describe, expect, it } from "vitest";
import {
diffJsonPayloads,
prettyPrintJson,
} from "../../../../../../src/panels/config/integrations/integration-panels/mqtt/mqtt-payload";
describe("prettyPrintJson", () => {
it("indents JSON objects and arrays", () => {
expect(prettyPrintJson('{"a":1,"b":[1,2],"c":{}}')).toBe(
'{\n "a": 1,\n "b": [\n 1,\n 2\n ],\n "c": {}\n}'
);
expect(prettyPrintJson(" [ ] ")).toBe("[]");
});
it("matches JSON.stringify for regular payloads", () => {
const payload = '{"state": "ON", "list": [{"x": -1.5}, null, true]}';
expect(prettyPrintJson(payload)).toBe(
JSON.stringify(JSON.parse(payload), null, 2)
);
});
it("keeps big numbers, duplicate keys and escapes as received", () => {
expect(prettyPrintJson('{"id": 12345678901234567890}')).toBe(
'{\n "id": 12345678901234567890\n}'
);
expect(prettyPrintJson('{"a": 1, "a": 2}')).toBe(
'{\n "a": 1,\n "a": 2\n}'
);
expect(prettyPrintJson('{"s": "a, \\"{b}\\": [c]\\\\"}')).toBe(
'{\n "s": "a, \\"{b}\\": [c]\\\\"\n}'
);
});
it("returns undefined for payloads that aren't a JSON object or array", () => {
expect(prettyPrintJson("online")).toBeUndefined();
expect(prettyPrintJson("42")).toBeUndefined();
expect(prettyPrintJson("{not json")).toBeUndefined();
});
});
describe("diffJsonPayloads", () => {
it("compares full payloads when the root changes between object and array", () => {
expect(diffJsonPayloads("{}", "[]")).toBeUndefined();
expect(diffJsonPayloads('{"0": 1}', "[1]")).toBeUndefined();
});
it("lists changed, added and removed keys with dotted paths", () => {
expect(
diffJsonPayloads(
'{"power": 10, "energy": {"total": 1}, "old": true}',
'{"power": 12, "energy": {"total": 1, "today": 0.5}}'
)
).toEqual([
{ key: "power", type: "changed", oldValue: "10", newValue: "12" },
{ key: "energy.today", type: "added", newValue: "0.5" },
{ key: "old", type: "removed", oldValue: "true" },
]);
});
it("keeps dotted keys apart from nested objects", () => {
expect(
diffJsonPayloads('{"a.b": 1, "a": {"b": 2}}', '{"a.b": 3, "a": {"b": 2}}')
).toEqual([
{ key: '["a.b"]', type: "changed", oldValue: "1", newValue: "3" },
]);
});
it("keeps array indexes apart from numeric object keys", () => {
expect(diffJsonPayloads('{"a": [1]}', '{"a": {"0": 1}}')).toEqual([
{ key: 'a["0"]', type: "added", newValue: "1" },
{ key: "a[0]", type: "removed", oldValue: "1" },
]);
});
it("returns no changes for identical payloads", () => {
expect(diffJsonPayloads('{"a": 1}', '{"a": 1}')).toEqual([]);
});
it("can't compare payloads that aren't JSON", () => {
expect(diffJsonPayloads("online", "offline")).toBeUndefined();
});
});
@@ -6,54 +6,66 @@ import {
import type { LocationCondition } from "../../../../../../src/panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../../../../../src/types";
const HASS = {
states: {
"zone.home": {
entity_id: "zone.home",
state: "0",
attributes: { friendly_name: "Home" },
},
"zone.store_1": {
entity_id: "zone.store_1",
state: "0",
attributes: { friendly_name: "Store 1" },
},
"zone.store_2": {
entity_id: "zone.store_2",
state: "0",
attributes: { friendly_name: "Store 2" },
},
// Shares Store 2's name, so both are matched.
"zone.store_2_south": {
entity_id: "zone.store_2_south",
state: "0",
attributes: { friendly_name: "Store 2" },
},
// Renamed from "Store", so its ID no longer matches its name.
"zone.store": {
entity_id: "zone.store",
state: "0",
attributes: { friendly_name: "Shop" },
},
// Shares a zone's name but isn't a zone, so migration must ignore it.
"person.me": {
entity_id: "person.me",
state: "home",
attributes: { friendly_name: "Store 1" },
},
const STATES = {
"zone.home": {
entity_id: "zone.home",
state: "0",
attributes: { friendly_name: "Home" },
},
localize: (key: string) => key,
// Registered, but without a state (for example while zones reload).
entities: {
"zone.reloading": { entity_id: "zone.reloading" },
"zone.store_1": {
entity_id: "zone.store_1",
state: "0",
attributes: { friendly_name: "Store 1" },
},
} as unknown as HomeAssistant;
"zone.store_2": {
entity_id: "zone.store_2",
state: "0",
attributes: { friendly_name: "Store 2" },
},
// Shares Store 2's name, so both are matched.
"zone.store_2_south": {
entity_id: "zone.store_2_south",
state: "0",
attributes: { friendly_name: "Store 2" },
},
// Renamed from "Store", so its ID no longer matches its name.
"zone.store": {
entity_id: "zone.store",
state: "0",
attributes: { friendly_name: "Shop" },
},
// Shares a zone's name but isn't a zone, so migration must ignore it.
"person.me": {
entity_id: "person.me",
state: "home",
attributes: { friendly_name: "Store 1" },
},
} as unknown as HomeAssistant["states"];
// Registered, but without a state (for example while zones reload).
const ENTITIES = {
"zone.reloading": { entity_id: "zone.reloading" },
} as unknown as HomeAssistant["entities"];
const localize = (key: string) => key;
// Sets the values the editor consumes from contexts.
const provide = (
editor: HaCardConditionLocation,
states = STATES,
entities = ENTITIES
) => {
const el = editor as any;
el._states = states;
el._registries = { entities, devices: {}, areas: {}, floors: {} };
el._i18n = { localize };
};
const createEditor = (condition: LocationCondition) => {
const editor = document.createElement(
"ha-card-condition-location"
) as HaCardConditionLocation;
editor.hass = HASS;
provide(editor);
editor.condition = condition;
return editor;
};
@@ -79,8 +91,13 @@ const shown = (editor: HaCardConditionLocation): LocationCondition => {
const migrate = (
condition: Omit<LocationCondition, "condition">,
hass = HASS
) => migrateLocationCondition({ condition: "location", ...condition }, hass);
states = STATES
) =>
migrateLocationCondition(
{ condition: "location", ...condition },
states,
ENTITIES
);
const formChange = (value: Partial<LocationCondition>) => ({
detail: { value: { condition: "location", ...value } },
@@ -88,7 +105,9 @@ const formChange = (value: Partial<LocationCondition>) => ({
});
const validate = (condition: unknown) =>
(HaCardConditionLocation as any).validateUIConfig(condition, HASS);
(HaCardConditionLocation as any).validateUIConfig(condition, {
localize,
} as unknown as HomeAssistant);
describe("ha-card-condition-location", () => {
describe("value changes", () => {
@@ -155,24 +174,18 @@ describe("ha-card-condition-location", () => {
});
describe("passive zone warning", () => {
const hass = {
...HASS,
states: {
...HASS.states,
"zone.gym": {
entity_id: "zone.gym",
state: "0",
attributes: { friendly_name: "Gym", passive: true },
},
const states = {
...STATES,
"zone.gym": {
entity_id: "zone.gym",
state: "0",
attributes: { friendly_name: "Gym", passive: true },
},
entities: {},
devices: {},
areas: {},
} as unknown as HomeAssistant;
} as unknown as HomeAssistant["states"];
const passiveZones = (condition: Partial<LocationCondition>) => {
const editor = createEditor({ condition: "location", ...condition });
editor.hass = hass;
provide(editor, states, {});
open(editor);
return (editor as any)._passiveZones();
};
@@ -204,23 +217,20 @@ describe("ha-card-condition-location", () => {
});
it("keeps zones named home or not_home", () => {
const hass = {
...HASS,
states: {
...HASS.states,
"zone.lowercase_home": {
entity_id: "zone.lowercase_home",
state: "0",
attributes: { friendly_name: "home" },
},
"zone.not_home": {
entity_id: "zone.not_home",
state: "0",
attributes: { friendly_name: "not_home" },
},
const states = {
...STATES,
"zone.lowercase_home": {
entity_id: "zone.lowercase_home",
state: "0",
attributes: { friendly_name: "home" },
},
} as unknown as HomeAssistant;
expect(migrate({ locations: ["home", "not_home"] }, hass)).toEqual({
"zone.not_home": {
entity_id: "zone.not_home",
state: "0",
attributes: { friendly_name: "not_home" },
},
} as unknown as HomeAssistant["states"];
expect(migrate({ locations: ["home", "not_home"] }, states)).toEqual({
condition: "location",
match_mode: "active_zone",
target: {
@@ -292,17 +302,14 @@ describe("ha-card-condition-location", () => {
open(editor);
expect((editor as any)._data).toBe(first);
editor.hass = {
...HASS,
states: {
...HASS.states,
"zone.store_1": {
...HASS.states["zone.store_1"],
attributes: { friendly_name: "Shop 1" },
},
provide(editor, {
...STATES,
"zone.store_1": {
...STATES["zone.store_1"],
attributes: { friendly_name: "Shop 1" },
},
} as unknown as HomeAssistant;
(editor as any).willUpdate(new Map([["hass", HASS]]));
});
(editor as any).willUpdate(new Map([["_states", STATES]]));
expect((editor as any)._data).toEqual({
condition: "location",
match_mode: "active_zone",
@@ -310,38 +317,33 @@ describe("ha-card-condition-location", () => {
});
});
it("skips hass updates that change no zone", () => {
const store1 = { ...HASS.states["zone.store_1"] };
const hass = {
...HASS,
states: { ...HASS.states, "zone.store_1": store1 },
} as unknown as HomeAssistant;
it("skips state updates that change no zone", () => {
const store1 = { ...STATES["zone.store_1"] };
const states = { ...STATES, "zone.store_1": store1 };
const editor = createEditor({
condition: "location",
locations: ["Store 1"],
});
editor.hass = hass;
provide(editor, states);
open(editor);
const registries = (editor as any)._registries;
// Renamed in place, so only a new migration would see it.
store1.attributes = { friendly_name: "Shop 1" };
editor.hass = {
...hass,
states: {
...hass.states,
"person.me": { ...HASS.states["person.me"], state: "not_home" },
},
} as unknown as HomeAssistant;
(editor as any).willUpdate(new Map([["hass", hass]]));
provide(editor, {
...states,
"person.me": { ...STATES["person.me"], state: "not_home" },
});
(editor as any).willUpdate(new Map([["_states", states]]));
expect((editor as any)._data).toEqual({
condition: "location",
match_mode: "active_zone",
target: { entity_id: ["zone.store_1"] },
});
// A registry update redoes it.
editor.hass = { ...editor.hass, entities: {} } as HomeAssistant;
(editor as any).willUpdate(new Map([["hass", hass]]));
// An entity registry update redoes it.
provide(editor, (editor as any)._states, {});
(editor as any).willUpdate(new Map([["_registries", registries]]));
expect((editor as any)._data).toEqual({
condition: "location",
match_mode: "active_zone",
@@ -356,18 +358,15 @@ describe("ha-card-condition-location", () => {
});
open(editor);
editor.hass = {
...HASS,
states: {
...HASS.states,
"zone.reloading": {
entity_id: "zone.reloading",
state: "0",
attributes: { friendly_name: "Reloading" },
},
provide(editor, {
...STATES,
"zone.reloading": {
entity_id: "zone.reloading",
state: "0",
attributes: { friendly_name: "Reloading" },
},
} as unknown as HomeAssistant;
(editor as any).willUpdate(new Map([["hass", HASS]]));
} as unknown as HomeAssistant["states"]);
(editor as any).willUpdate(new Map([["_states", STATES]]));
expect((editor as any)._data).toEqual({
condition: "location",
match_mode: "active_zone",