mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-05 20:44:32 +00:00
Compare commits
130
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef7792e1fe | ||
|
|
29906d6f83 | ||
|
|
952c227370 | ||
|
|
173c60e57b | ||
|
|
ef134330f3 | ||
|
|
c75386ab33 | ||
|
|
61b433f912 | ||
|
|
16ed504c66 | ||
|
|
e9550ffe52 | ||
|
|
2c6cf8e45b | ||
|
|
0dcfc247a7 | ||
|
|
2ab1f187c5 | ||
|
|
56d6f1c571 | ||
|
|
f169ae79f5 | ||
|
|
599089a2d3 | ||
|
|
2af451338f | ||
|
|
2ba9a1fc61 | ||
|
|
96e525f7a3 | ||
|
|
c42dac197f | ||
|
|
8fbae6346d | ||
|
|
2a69518dba | ||
|
|
960bf08c84 | ||
|
|
6c2bc65f07 | ||
|
|
e52547e374 | ||
|
|
7474e3e342 | ||
|
|
8dbd1527d9 | ||
|
|
d9d849c843 | ||
|
|
4f73b43912 | ||
|
|
a6fb28dfef | ||
|
|
d4ad00c509 | ||
|
|
2fdef6883c | ||
|
|
598034b1d3 | ||
|
|
4ad7c7a96a | ||
|
|
14f66ca105 | ||
|
|
831dbeb975 | ||
|
|
aecf17aae4 | ||
|
|
037d3dad01 | ||
|
|
e80c2e55b5 | ||
|
|
581b6abdd8 | ||
|
|
4c43c7446a | ||
|
|
0f73094afd | ||
|
|
53f8e6c8cb | ||
|
|
5c9fc8723c | ||
|
|
8995004feb | ||
|
|
4fa5991889 | ||
|
|
9925c10d03 | ||
|
|
7fc68028ea | ||
|
|
6136ec4909 | ||
|
|
d8a366b3d4 | ||
|
|
03e5814a57 | ||
|
|
9421cda8cf | ||
|
|
25490642f9 | ||
|
|
b01892a128 | ||
|
|
7baeed0cf6 | ||
|
|
f1a9e2f69a | ||
|
|
fdfc00f3d7 | ||
|
|
ee33e4bfde | ||
|
|
39754807cc | ||
|
|
752251b1b6 | ||
|
|
95c613b098 | ||
|
|
a970c5c7f6 | ||
|
|
78f6a55e3c | ||
|
|
563b90c773 | ||
|
|
bf996a2521 | ||
|
|
f04ce740a1 | ||
|
|
4a455cd883 | ||
|
|
6ae0d2ac72 | ||
|
|
4b156e5666 | ||
|
|
ede6d92ab6 | ||
|
|
5a4e664597 | ||
|
|
40d2739a5f | ||
|
|
52f632e4c2 | ||
|
|
5ac2316f79 | ||
|
|
22ff94a5d6 | ||
|
|
7d2fa3cf5c | ||
|
|
b8f0213d16 | ||
|
|
d4e0da9e21 | ||
|
|
95c75bdd5b | ||
|
|
36d57f1bba | ||
|
|
95d4e7705f | ||
|
|
87babb1a3b | ||
|
|
2966588338 | ||
|
|
7e07d3b5c4 | ||
|
|
1b9d866977 | ||
|
|
0fc4a042c5 | ||
|
|
b865ca9357 | ||
|
|
f817d76b73 | ||
|
|
c695f577ff | ||
|
|
4cb82bf40b | ||
|
|
449e7f8501 | ||
|
|
7b0d350fb7 | ||
|
|
ed2cc613e1 | ||
|
|
79f193f0d8 | ||
|
|
149f24255b | ||
|
|
c1a82bfe7f | ||
|
|
5083578c1e | ||
|
|
5f11dc4580 | ||
|
|
27489f188e | ||
|
|
97fffc3b43 | ||
|
|
a30193b8ef | ||
|
|
cf063dc19f | ||
|
|
5db829b7be | ||
|
|
421f8b1986 | ||
|
|
a140eedc6e | ||
|
|
2933568658 | ||
|
|
29faeaf7fa | ||
|
|
95ba532ceb | ||
|
|
352ecb9d6d | ||
|
|
3f73049a3d | ||
|
|
50ad0c6cd0 | ||
|
|
78f95bbb06 | ||
|
|
6134056776 | ||
|
|
b79c6350ec | ||
|
|
8148041ddc | ||
|
|
4265624c0e | ||
|
|
ed4179de8f | ||
|
|
e407a1b2dd | ||
|
|
e851101a93 | ||
|
|
d43e1ef4cc | ||
|
|
f699019994 | ||
|
|
fe90b0339d | ||
|
|
3b5ba802f6 | ||
|
|
b0c6e7f564 | ||
|
|
658a23724e | ||
|
|
f859183628 | ||
|
|
53dc14f413 | ||
|
|
f2523095ff | ||
|
|
ef5c04b67f | ||
|
|
10ed6f709e | ||
|
|
c22de3bc7c |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: ha-frontend-components
|
||||
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
|
||||
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, loading states, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
|
||||
---
|
||||
|
||||
# HA Frontend Components
|
||||
@@ -91,6 +91,36 @@ html`
|
||||
`;
|
||||
```
|
||||
|
||||
## Loading States
|
||||
|
||||
Pick the indicator by what is loading, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/):
|
||||
|
||||
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
|
||||
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
|
||||
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
|
||||
|
||||
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
|
||||
|
||||
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
|
||||
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
|
||||
- Don't fade in the loaded content itself.
|
||||
|
||||
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
|
||||
|
||||
```ts
|
||||
html`
|
||||
<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label=${this._i18n.localize("ui.common.loading")}
|
||||
>
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
</div>
|
||||
</ha-fade-in>
|
||||
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
|
||||
`;
|
||||
```
|
||||
|
||||
## Shortcuts And Tooltips
|
||||
|
||||
Use `ShortcutManager` from `src/common/keyboard/shortcuts.ts` for keyboard shortcuts. It blocks shortcuts in input fields, can prevent shortcuts during text selection, and supports character and KeyCode shortcuts for non-latin keyboards. See `src/state/quick-bar-mixin.ts` for global shortcut examples.
|
||||
|
||||
@@ -12,3 +12,7 @@
|
||||
|
||||
demo/public/api/camera_proxy_stream/* binary
|
||||
demo/public/api/media_player_proxy/* binary
|
||||
|
||||
# Generated by `gh actions-lock`. Highlight it as YAML and don't auto-merge it:
|
||||
# on a conflict, restore it from the base branch and run `gh actions-lock`.
|
||||
.github/workflows/actions.lock linguist-language=YAML -merge
|
||||
@@ -51,8 +51,8 @@
|
||||
|
||||
- This PR fixes or closes issue: fixes #
|
||||
- This PR is related to issue or discussion:
|
||||
- Link to documentation pull request:
|
||||
- Link to developer documentation pull request:
|
||||
- Link to [documentation][docs-repository] pull request:
|
||||
- Link to [contributors documentation][contributors-repository] pull request:
|
||||
- Link to backend pull request:
|
||||
|
||||
## Checklist
|
||||
@@ -63,7 +63,8 @@
|
||||
for before merging your code.
|
||||
|
||||
AI tools are welcome, but contributors are responsible for *fully*
|
||||
understanding the code before submitting a PR.
|
||||
understanding the code before submitting a PR. Please follow our AI policy:
|
||||
https://contributors.home-assistant.io/start/ai-policy/
|
||||
-->
|
||||
|
||||
- [ ] I understand the code I am submitting and can explain how it works.
|
||||
@@ -105,4 +106,5 @@ To help with the load of incoming pull requests:
|
||||
Below, some useful links you could explore:
|
||||
-->
|
||||
[docs-repository]: https://github.com/home-assistant/home-assistant.io
|
||||
[contributors-repository]: https://github.com/home-assistant/contributors.home-assistant.io
|
||||
[perfect-pr]: https://contributors.home-assistant.io/start/pull-requests/#before-you-open-it
|
||||
@@ -0,0 +1,6 @@
|
||||
paths:
|
||||
.github/workflows/**/*.{yml,yaml}:
|
||||
ignore:
|
||||
# actionlint doesn't support `$/` self-repository actions yet, remove once it does:
|
||||
# https://github.com/rhysd/actionlint/issues/711
|
||||
- 'specifying action "\$/[^"]+" in invalid format because ref is missing'
|
||||
@@ -24,7 +24,7 @@ runs:
|
||||
|
||||
- name: Setup Node and install
|
||||
if: steps.dependencies.outputs.cache-hit != 'true'
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
cache: false
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Verify actions lockfile
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
- master
|
||||
paths:
|
||||
- ".github/actions/**"
|
||||
- ".github/workflows/**"
|
||||
pull_request:
|
||||
branches:
|
||||
- dev
|
||||
- master
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: Verify actions lockfile
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_ACTIONS_LOCK_VERSION: v0.4.1
|
||||
steps:
|
||||
- name: Check out files from GitHub
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install gh-actions-lock
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: gh extension install github/gh-actions-lock --pin "${GH_ACTIONS_LOCK_VERSION}"
|
||||
- name: Verify lockfile
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: gh actions-lock --verify
|
||||
@@ -0,0 +1,190 @@
|
||||
# This file is machine-generated by `gh actions-lock`.
|
||||
# Do not edit by hand; run `gh actions-lock` to update.
|
||||
# Docs: https://gh.io/actions-lockfile
|
||||
version: 'v0.0.3'
|
||||
workflows:
|
||||
'.github/workflows/actionlint.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
'.github/workflows/actions-lock.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
'.github/workflows/cast_deployment.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/ci.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/codeql-analysis.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
'.github/workflows/copilot-setup-steps.yml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/demo_deployment.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/dependency-review.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
'.github/workflows/design_deployment.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/design_preview.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/e2e.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/labeler.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
- 'actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13'
|
||||
'.github/workflows/lock.yaml':
|
||||
- 'dessant/lock-threads@89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
'.github/workflows/nightly.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/pull-request-standards.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
'.github/workflows/relative-ci.yaml':
|
||||
- 'relative-ci/agent-action@711f3a8fa1b928e6afde280011110c9b0a224a60'
|
||||
'.github/workflows/release-drafter.yaml':
|
||||
- 'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0'
|
||||
'.github/workflows/release.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
|
||||
- 'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361'
|
||||
- 'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
|
||||
- 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086'
|
||||
'.github/workflows/restrict-task-creation.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
'.github/workflows/stale.yaml':
|
||||
- 'actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93'
|
||||
'.github/workflows/sync-device-classes.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
'.github/workflows/sync-sensor-entity-constants.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
'.github/workflows/translations.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
dependencies:
|
||||
'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9':
|
||||
ref: 'v6.1.0'
|
||||
commit: 'sha1-55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
owner_id: 44036562
|
||||
repo_id: 215566462
|
||||
'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1':
|
||||
ref: 'v7.0.1'
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294':
|
||||
ref: 'v5.0.0'
|
||||
commit: 'sha1-a1d282b36b6f3519aa1f3fc636f609c47dddb294'
|
||||
owner_id: 44036562
|
||||
repo_id: 476372928
|
||||
'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333':
|
||||
ref: 'v8.0.2'
|
||||
commit: 'sha1-9000827ccba6bdab643e8b6fd33ac0654aef8333'
|
||||
owner_id: 44036562
|
||||
repo_id: 192626254
|
||||
'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3':
|
||||
ref: 'v9.0.0'
|
||||
commit: 'sha1-3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
owner_id: 44036562
|
||||
repo_id: 205262760
|
||||
'actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13':
|
||||
ref: 'v7.0.0'
|
||||
commit: 'sha1-bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13'
|
||||
owner_id: 44036562
|
||||
repo_id: 177139928
|
||||
'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1':
|
||||
ref: 'v7.1.0'
|
||||
commit: 'sha1-949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
owner_id: 44036562
|
||||
repo_id: 189476904
|
||||
'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0':
|
||||
ref: 'v7.1.0'
|
||||
commit: 'sha1-6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
|
||||
owner_id: 44036562
|
||||
repo_id: 192625525
|
||||
'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405':
|
||||
ref: 'v6.2.0'
|
||||
commit: 'sha1-a309ff8b426b58ec0e2a45f0f869d46889d02405'
|
||||
owner_id: 44036562
|
||||
repo_id: 192625525
|
||||
'actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93':
|
||||
ref: 'v11.0.0'
|
||||
commit: 'sha1-4391f3da665fdf50b6810c1a66712fb9ba21aa93'
|
||||
owner_id: 44036562
|
||||
repo_id: 200437066
|
||||
'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9':
|
||||
ref: 'v7.0.2'
|
||||
commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
owner_id: 44036562
|
||||
repo_id: 192625955
|
||||
'dessant/lock-threads@89ae32b08ed1a541efecbab17912962a5e38981c':
|
||||
ref: 'v6.0.2'
|
||||
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
owner_id: 7513068
|
||||
repo_id: 113918130
|
||||
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
|
||||
ref: 'v4.39.1'
|
||||
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
|
||||
ref: 'master'
|
||||
commit: 'sha1-86d4564712fa02543c808e3a693dd04f9d3f8361'
|
||||
owner_id: 13844975
|
||||
repo_id: 173703505
|
||||
'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716':
|
||||
ref: '2026.07.0'
|
||||
commit: 'sha1-9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
|
||||
owner_id: 13844975
|
||||
repo_id: 184234812
|
||||
'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1':
|
||||
ref: 'v8.1.1'
|
||||
commit: 'sha1-5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
owner_id: 18365890
|
||||
repo_id: 197176365
|
||||
'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086':
|
||||
ref: 'v1.14.3'
|
||||
commit: 'sha1-7245906fb61fa33a13554f9d5fb856fe61758086'
|
||||
owner_id: 647025
|
||||
repo_id: 178055147
|
||||
uses:
|
||||
- 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405'
|
||||
'relative-ci/agent-action@711f3a8fa1b928e6afde280011110c9b0a224a60':
|
||||
ref: 'v3.2.4'
|
||||
commit: 'sha1-711f3a8fa1b928e6afde280011110c9b0a224a60'
|
||||
owner_id: 43522883
|
||||
repo_id: 398376354
|
||||
'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0':
|
||||
ref: 'v7.10.0'
|
||||
commit: 'sha1-978bb0b30c5ee8cdd332ced253758157150d43f0'
|
||||
owner_id: 58292376
|
||||
repo_id: 139022359
|
||||
@@ -30,17 +30,17 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Build Cast
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-cast
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy to Netlify
|
||||
id: deploy
|
||||
uses: ./.github/actions/netlify-deploy
|
||||
uses: $/.github/actions/netlify-deploy
|
||||
with:
|
||||
dir: cast/dist
|
||||
alias: dev
|
||||
@@ -62,17 +62,17 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Build Cast
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-cast
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy to Netlify
|
||||
id: deploy
|
||||
uses: ./.github/actions/netlify-deploy
|
||||
uses: $/.github/actions/netlify-deploy
|
||||
with:
|
||||
dir: cast/dist
|
||||
auth-token: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Prepare dependencies
|
||||
uses: ./.github/actions/prepare-dependencies
|
||||
uses: $/.github/actions/prepare-dependencies
|
||||
|
||||
lint:
|
||||
name: Lint and check format
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
- name: Check for duplicate dependencies
|
||||
@@ -89,7 +89,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
- name: Build resources
|
||||
@@ -110,7 +110,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
# Read-only reuse of the rspack cache written by the nightly (see
|
||||
@@ -127,7 +127,7 @@ jobs:
|
||||
restore-keys: |
|
||||
rspack-cache-${{ runner.os }}-
|
||||
- name: Build Application
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-app
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -32,12 +32,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
languages: javascript-typescript
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
category: "/language:javascript-typescript"
|
||||
@@ -22,10 +22,45 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
# These steps mirror .github/actions/setup with node-modules-cache enabled.
|
||||
# Copilot runs this workflow in a context that can't resolve `$/`
|
||||
# self-repository actions, so the steps are inlined here.
|
||||
- name: Restore complete dependency tree
|
||||
id: dependency-cache
|
||||
continue-on-error: true
|
||||
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
node-modules-cache: true
|
||||
path: |
|
||||
node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
node-modules-v1-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
hashFiles('.nvmrc', 'package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'patches/**') }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-store
|
||||
if: steps.dependency-cache.outputs.cache-hit != 'true'
|
||||
run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Cache pnpm store
|
||||
if: steps.pnpm-store.outputs.path
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ${{ steps.pnpm-store.outputs.path }}
|
||||
key: pnpm-store-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: pnpm-store-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.dependency-cache.outputs.cache-hit != 'true'
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Skip fetching nightly translations
|
||||
run: echo "SKIP_FETCH_NIGHTLY_TRANSLATIONS=1" >> "$GITHUB_ENV"
|
||||
|
||||
@@ -31,17 +31,17 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Build Demo
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-demo
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy to Netlify
|
||||
id: deploy
|
||||
uses: ./.github/actions/netlify-deploy
|
||||
uses: $/.github/actions/netlify-deploy
|
||||
with:
|
||||
dir: demo/dist
|
||||
auth-token: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
@@ -62,17 +62,17 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Build Demo
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-demo
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy to Netlify
|
||||
id: deploy
|
||||
uses: ./.github/actions/netlify-deploy
|
||||
uses: $/.github/actions/netlify-deploy
|
||||
with:
|
||||
dir: demo/dist
|
||||
auth-token: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
|
||||
@@ -25,17 +25,17 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Build Gallery
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-gallery
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy to Netlify
|
||||
id: deploy
|
||||
uses: ./.github/actions/netlify-deploy
|
||||
uses: $/.github/actions/netlify-deploy
|
||||
with:
|
||||
dir: gallery/dist
|
||||
auth-token: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
|
||||
@@ -29,17 +29,17 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Build Gallery
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-gallery
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy preview to Netlify
|
||||
id: deploy
|
||||
uses: ./.github/actions/netlify-deploy
|
||||
uses: $/.github/actions/netlify-deploy
|
||||
with:
|
||||
dir: gallery/dist
|
||||
alias: deploy-preview-${{ github.event.number }}
|
||||
|
||||
+16
-16
@@ -32,13 +32,13 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare dependencies
|
||||
uses: ./.github/actions/prepare-dependencies
|
||||
uses: $/.github/actions/prepare-dependencies
|
||||
|
||||
prepare-container-dependencies:
|
||||
name: Prepare container dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
defaults:
|
||||
run:
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare dependencies
|
||||
uses: ./.github/actions/prepare-dependencies
|
||||
uses: $/.github/actions/prepare-dependencies
|
||||
with:
|
||||
node-modules-cache-key: node-modules-container-v1
|
||||
|
||||
@@ -66,12 +66,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
|
||||
- name: Build demo
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-demo-e2e
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -97,12 +97,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
|
||||
- name: Build e2e test app
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-e2e-test-app-e2e
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -128,12 +128,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
|
||||
- name: Build gallery
|
||||
uses: ./.github/actions/build
|
||||
uses: $/.github/actions/build
|
||||
with:
|
||||
target: build-gallery
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -155,7 +155,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -176,7 +176,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
node-modules-cache-key: node-modules-container-v1
|
||||
@@ -207,7 +207,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -230,7 +230,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
node-modules-cache-key: node-modules-container-v1
|
||||
@@ -261,7 +261,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -284,7 +284,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
node-modules-cache-key: node-modules-container-v1
|
||||
@@ -326,7 +326,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node with shared dependencies
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
node-modules-cache: true
|
||||
|
||||
|
||||
@@ -26,12 +26,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python ${{ env.PYTHON_VERSION }}
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
immutable: false
|
||||
|
||||
@@ -124,7 +124,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
immutable: false
|
||||
|
||||
|
||||
@@ -31,15 +31,15 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python ${{ env.PYTHON_VERSION }}
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
|
||||
- name: Verify version
|
||||
uses: home-assistant/actions/helpers/verify-version@cd6f3635a740c84d8a14f6121a90068b8ece6bf6 # master
|
||||
uses: home-assistant/actions/helpers/verify-version@86d4564712fa02543c808e3a693dd04f9d3f8361 # master
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
immutable: false
|
||||
cache: false
|
||||
@@ -85,7 +85,7 @@ jobs:
|
||||
key: compress-cache-${{ runner.os }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2
|
||||
uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
||||
with:
|
||||
skip-existing: true
|
||||
|
||||
@@ -146,7 +146,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
with:
|
||||
immutable: false
|
||||
cache: false
|
||||
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Regenerate device class constants
|
||||
run: ./script/gen_device_classes
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: ./.github/actions/setup
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
- name: Regenerate sensor entity constants
|
||||
run: ./script/gen_sensor_entity_constants
|
||||
|
||||
@@ -40,7 +40,7 @@ Never run `tsc` or `pnpm lint:types` with file arguments. When `tsc` receives fi
|
||||
Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching skill before detailed implementation or review. For reviews, load `ha-frontend-review` alongside all companions that apply to the changed code or behavior:
|
||||
|
||||
- `ha-frontend-contexts`: Lit contexts, `hass` migration, and rerender-sensitive state access.
|
||||
- `ha-frontend-components`: dialogs, forms, alerts, shortcuts, tooltips, panels, and Lovelace cards.
|
||||
- `ha-frontend-components`: dialogs, forms, alerts, loading states, shortcuts, tooltips, panels, and Lovelace cards.
|
||||
- `ha-frontend-events`: event handler typing, custom event dispatch, and event-map declarations.
|
||||
- `ha-frontend-types`: backend data contracts, optional schemas, shared types, assertions, and lifecycle types.
|
||||
- `ha-frontend-lit`: reactive fields, DOM queries, lifecycle behavior, and render-derived state.
|
||||
|
||||
@@ -284,6 +284,7 @@ module.exports.config = {
|
||||
name: "demo" + nameSuffix(latestBuild),
|
||||
entry: {
|
||||
main: path.resolve(paths.demo_dir, "src/entrypoint.ts"),
|
||||
embed: path.resolve(paths.demo_dir, "src/embed/entrypoint.ts"),
|
||||
...module.exports.mapWorkerEntry(),
|
||||
},
|
||||
outputPath: outputPath(paths.demo_output_root, latestBuild),
|
||||
@@ -291,6 +292,8 @@ module.exports.config = {
|
||||
defineOverlay: {
|
||||
__VERSION__: JSON.stringify(`DEMO-${env.version()}`),
|
||||
__DEMO__: true,
|
||||
// The embed sets the global to load static files from its own server.
|
||||
__STATIC_PATH__: '(globalThis.__HA_STATIC_PATH__ || "/static/")',
|
||||
},
|
||||
isProdBuild,
|
||||
latestBuild,
|
||||
|
||||
@@ -232,7 +232,11 @@ gulp.task(
|
||||
)
|
||||
);
|
||||
|
||||
const DEMO_PAGE_ENTRIES = { "index.html": ["main"] };
|
||||
const DEMO_PAGE_ENTRIES = {
|
||||
"index.html": ["main"],
|
||||
"components.html": ["embed"],
|
||||
"embed.js": ["embed"],
|
||||
};
|
||||
|
||||
gulp.task(
|
||||
"gen-pages-demo-dev",
|
||||
|
||||
@@ -214,16 +214,18 @@ const createRspackConfig = ({
|
||||
},
|
||||
},
|
||||
{
|
||||
// MapLibre's worker loads ESM plugins through `import(url)`, and the
|
||||
// page side builds a blob import from `new URL(url, import.meta.url)`
|
||||
// for a cross-origin worker. Neither path is taken here: the RTL
|
||||
// plugin is UMD and the worker is served from the page's origin.
|
||||
// Rspack's stubs for these fully dynamic requests are exactly what
|
||||
// should remain - rejecting, and free of syntax the legacy floor
|
||||
// cannot parse - so the warnings about them are noise.
|
||||
// MapLibre's worker loads ESM plugins through `import(url)`, which
|
||||
// is never taken here: the RTL plugin is UMD. Rspack's stub for that
|
||||
// fully dynamic request is exactly what should remain - rejecting,
|
||||
// and free of syntax the legacy floor cannot parse - so the warning
|
||||
// about it is noise. The page side builds a blob import from
|
||||
// `new URL(url, import.meta.url)` for a worker on another origin,
|
||||
// as in the demo embed. That is a URL, not an asset to bundle, and
|
||||
// the worker URL is absolute, so leave it as it is.
|
||||
test: /[\\/]maplibre-gl[\\/]dist[\\/]maplibre-gl(?:-worker)?\.mjs$/,
|
||||
parser: {
|
||||
exprContextCritical: false,
|
||||
url: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -246,7 +248,15 @@ const createRspackConfig = ({
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
// The demo embed reads its own URL at runtime to find its files.
|
||||
// Keep import.meta.url instead of replacing it with the source path.
|
||||
// Development builds wrap modules in eval(), which rejects import.meta.
|
||||
latestBuild &&
|
||||
isProdBuild && {
|
||||
test: path.resolve(paths.demo_dir, "src/embed/public-path.ts"),
|
||||
parser: { importMeta: false },
|
||||
},
|
||||
].filter(Boolean),
|
||||
},
|
||||
optimization: {
|
||||
minimizer: [
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ActionDetail } from "@material/mwc-list/mwc-list";
|
||||
import { mdiCast, mdiCastConnected, mdiViewDashboard } from "@mdi/js";
|
||||
import type { Auth, Connection } from "home-assistant-js-websocket";
|
||||
import type { TemplateResult, PropertyValues } from "lit";
|
||||
@@ -215,7 +214,7 @@ class HcCast extends LitElement {
|
||||
this.castManager.requestSession();
|
||||
}
|
||||
|
||||
private async _handlePickView(ev: CustomEvent<ActionDetail>) {
|
||||
private async _handlePickView(ev: CustomEvent<{ index: number }>) {
|
||||
const path = this.lovelaceViews?.[ev.detail.index]?.path ?? ev.detail.index;
|
||||
await ensureConnectedCastSession(this.castManager!, this.auth!);
|
||||
castSendShowLovelaceView(this.castManager, this.auth.data.hassUrl, path);
|
||||
|
||||
@@ -16,3 +16,10 @@
|
||||
|
||||
/frontend_latest/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Access-Control-Allow-Origin: *
|
||||
|
||||
/embed.js
|
||||
Access-Control-Allow-Origin: *
|
||||
|
||||
/static/*
|
||||
Access-Control-Allow-Origin: *
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createContext } from "@lit/context";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
|
||||
export const embedHassContext = createContext<HomeAssistant>("embedHass");
|
||||
@@ -0,0 +1,25 @@
|
||||
import "./public-path";
|
||||
import "./workers";
|
||||
// The provider must be defined first. Custom elements upgrade in the order
|
||||
// they are defined, and cards need a provider to request their context from.
|
||||
import "./ha-embed-provider";
|
||||
import "./ha-embed-card";
|
||||
// For custom cards, which can't load them themselves. The built-in cards only
|
||||
// load ha-list-item-button with the map card. The full app loads ha-select
|
||||
// with the more info dialog.
|
||||
import "../../../src/components/item/ha-list-item-button";
|
||||
import "../../../src/components/ha-select";
|
||||
import { fontStyles } from "../../../src/resources/roboto";
|
||||
|
||||
// Font faces only work in the document, not in the shadow root of the card.
|
||||
// Defining Roboto does not change the page unless it already uses Roboto.
|
||||
document.head.append(
|
||||
Object.assign(document.createElement("style"), {
|
||||
textContent: fontStyles.cssText,
|
||||
})
|
||||
);
|
||||
|
||||
// Custom cards use the helpers to create built-in cards. The dashboard panel
|
||||
// sets the same global in the full app.
|
||||
(window as any).loadCardHelpers = () =>
|
||||
import("../../../src/panels/lovelace/custom-card-helpers");
|
||||
@@ -0,0 +1,218 @@
|
||||
import { ContextEvent } from "@lit/context";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { createRef, ref } from "lit/directives/ref";
|
||||
import { consume } from "../../../src/common/decorators/consume";
|
||||
import { computeRTLDirection } from "../../../src/common/util/compute_rtl";
|
||||
import type { LovelaceCardConfig } from "../../../src/data/lovelace/config/card";
|
||||
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
|
||||
import { computeCardGridSize } from "../../../src/panels/lovelace/common/compute-card-grid-size";
|
||||
import "../../../src/panels/lovelace/cards/hui-card";
|
||||
import type { HuiCard } from "../../../src/panels/lovelace/cards/hui-card";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import { embedHassContext } from "./context";
|
||||
import { readScriptData } from "./script-data";
|
||||
import { embedThemeStyles } from "./theme-styles";
|
||||
|
||||
const pageProvider = (): HTMLElement =>
|
||||
document.querySelector("ha-embed-provider") ??
|
||||
document.body.appendChild(document.createElement("ha-embed-provider"));
|
||||
|
||||
// Looks past shadow roots, so a card inside another component still finds
|
||||
// the provider around that component.
|
||||
const insideProvider = (element: Element): boolean => {
|
||||
let current: Element | null = element;
|
||||
|
||||
while (current) {
|
||||
if (current.closest("ha-embed-provider")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const root = current.getRootNode();
|
||||
current = root instanceof ShadowRoot ? root.host : null;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders a Lovelace card. The card uses the provider with the ID in
|
||||
* `provider`, else the closest provider around it, else the first provider on
|
||||
* the page. If the page has no provider, the card adds an empty one.
|
||||
*
|
||||
* The card takes the columns and rows it would take in a section, so cards
|
||||
* in an element with `display: grid` and 12 columns lay out like a section.
|
||||
* It also sets `--column-size` and `--row-size` on itself.
|
||||
*/
|
||||
@customElement("ha-embed-card")
|
||||
export class HaEmbedCard extends LitElement {
|
||||
/**
|
||||
* The card configuration. Also read from a JSON or YAML script child, see
|
||||
* `readScriptData`.
|
||||
*/
|
||||
@property({ type: Object }) public config?: LovelaceCardConfig;
|
||||
|
||||
/** The ID of the `ha-embed-provider` to use. */
|
||||
@property() public provider?: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: embedHassContext, subscribe: true })
|
||||
private _hass?: HomeAssistant;
|
||||
|
||||
// A provider that is not an ancestor, which gets the context requests of the
|
||||
// card and its content. Context requests only reach ancestors by themselves.
|
||||
private _linkedProvider?: HTMLElement;
|
||||
|
||||
private _scriptRead = false;
|
||||
|
||||
private _card = createRef<HuiCard>();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.addEventListener("context-request", (ev) => {
|
||||
if (!this._linkedProvider) {
|
||||
return;
|
||||
}
|
||||
ev.stopPropagation();
|
||||
this._linkedProvider.dispatchEvent(
|
||||
new ContextEvent(
|
||||
ev.context,
|
||||
ev.contextTarget,
|
||||
ev.callback,
|
||||
ev.subscribe
|
||||
)
|
||||
);
|
||||
});
|
||||
// Cards fire their tap, hold and double tap actions for the app to handle
|
||||
this.addEventListener("hass-action", (ev) => {
|
||||
if (this._hass) {
|
||||
// The element that fired the action, so that fire-dom-event reaches
|
||||
// listeners inside custom cards, as in action-mixin
|
||||
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
|
||||
handleAction(node, this._hass, ev.detail.config, ev.detail.action);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
// Before super.connectedCallback(), which sends the context requests.
|
||||
this._linkedProvider = this.provider
|
||||
? (document.getElementById(this.provider) ?? undefined)
|
||||
: insideProvider(this)
|
||||
? undefined
|
||||
: pageProvider();
|
||||
super.connectedCallback();
|
||||
|
||||
// Only once, so that moving the card keeps a config set since
|
||||
if (this._scriptRead) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._scriptRead = true;
|
||||
|
||||
const config = readScriptData(this) as LovelaceCardConfig | undefined;
|
||||
if (config) {
|
||||
this.config = config;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._hass || !this.config) {
|
||||
return nothing;
|
||||
}
|
||||
return html`<div
|
||||
class=${classMap({ theme: true, dark: this._hass.themes.darkMode })}
|
||||
dir=${computeRTLDirection(this._hass)}
|
||||
>
|
||||
<hui-card
|
||||
${ref(this._card)}
|
||||
.hass=${this._hass}
|
||||
.config=${this.config}
|
||||
.layout=${"grid"}
|
||||
@card-updated=${this._updateSize}
|
||||
@card-visibility-changed=${this._updateSize}
|
||||
></hui-card>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
protected updated() {
|
||||
// The card element only exists once hui-card has updated
|
||||
this._card.value?.updateComplete.then(() => this._updateSize());
|
||||
}
|
||||
|
||||
// The size the card gets in a section, set on the host so that the page can
|
||||
// lay out cards in a grid of 12 columns, like a section
|
||||
private _updateSize = () => {
|
||||
const card = this._card.value;
|
||||
if (!card) {
|
||||
return;
|
||||
}
|
||||
const { rows, columns } = computeCardGridSize(card.getGridOptions());
|
||||
this.hidden = card.hidden;
|
||||
this.toggleAttribute("full-width", columns === "full");
|
||||
this.toggleAttribute("fit-rows", typeof rows === "number");
|
||||
this.style.setProperty(
|
||||
"--column-size",
|
||||
typeof columns === "number" ? String(columns) : null
|
||||
);
|
||||
this.style.setProperty(
|
||||
"--row-size",
|
||||
typeof rows === "number" ? String(rows) : null
|
||||
);
|
||||
};
|
||||
|
||||
static styles = [
|
||||
embedThemeStyles,
|
||||
css`
|
||||
/* The sizes of a card in a section, see hui-grid-section */
|
||||
:host {
|
||||
--row-gap: var(--ha-section-grid-row-gap, 8px);
|
||||
--row-height: var(--ha-section-grid-row-height, 56px);
|
||||
display: block;
|
||||
grid-row: span var(--row-size, 1);
|
||||
grid-column: span min(var(--column-size, 12), 12);
|
||||
}
|
||||
:host([full-width]) {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
:host([hidden]) {
|
||||
display: none;
|
||||
}
|
||||
:host([fit-rows]) .theme {
|
||||
height: calc(
|
||||
(var(--row-size, 1) * (var(--row-height) + var(--row-gap))) - var(
|
||||
--row-gap
|
||||
)
|
||||
);
|
||||
}
|
||||
/* The text styles the app sets on html and body, so that the card does
|
||||
not inherit the text styles of the page that embeds it. */
|
||||
.theme {
|
||||
color: var(--primary-text-color);
|
||||
font-family: var(--ha-font-family-body);
|
||||
font-size: var(--ha-font-size-m);
|
||||
font-weight: var(--ha-font-weight-body);
|
||||
line-height: normal;
|
||||
letter-spacing: normal;
|
||||
text-align: start;
|
||||
-moz-osx-font-smoothing: var(--ha-moz-osx-font-smoothing);
|
||||
-webkit-font-smoothing: var(--ha-font-smoothing);
|
||||
}
|
||||
/* What setDirectionStyles sets on the app for a right-to-left language,
|
||||
here only for the card */
|
||||
.theme[dir="rtl"] {
|
||||
--direction: rtl;
|
||||
--float-start: right;
|
||||
--float-end: left;
|
||||
--scale-direction: -1;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-embed-card": HaEmbedCard;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import { ContextProvider, provide } from "@lit/context";
|
||||
import type { HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { fireEvent } from "../../../src/common/dom/fire_event";
|
||||
import { listenMediaQuery } from "../../../src/common/dom/media_query";
|
||||
import type { AreaRegistryEntry } from "../../../src/data/area/area_registry";
|
||||
import type { CalendarEventApiData } from "../../../src/data/calendar";
|
||||
import { reducedMotionContext } from "../../../src/data/context";
|
||||
import type { EnergyInfo, EnergyPreferences } from "../../../src/data/energy";
|
||||
import { EMPTY_PREFERENCES } from "../../../src/data/energy";
|
||||
import type { EntityRegistryEntry } from "../../../src/data/entity/entity_registry";
|
||||
import type { EntityInput } from "../../../src/fake_data/entities/types";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import { provideHass } from "../../../src/fake_data/provide_hass";
|
||||
import type { DemoArea } from "../stubs/area_registry";
|
||||
import { toAreaRegistryEntry } from "../stubs/area_registry";
|
||||
import { mockAuth } from "../stubs/auth";
|
||||
import {
|
||||
FAMILY_EVENTS,
|
||||
mockCalendarEvents,
|
||||
WORK_EVENTS,
|
||||
} from "../stubs/calendar";
|
||||
import { extEntry, newEntry } from "../stubs/entity_registry";
|
||||
import { mockHistory } from "../stubs/history";
|
||||
import { mockIcons } from "../stubs/icons";
|
||||
import { mockLogbook } from "../stubs/logbook";
|
||||
import { mockMediaPlayer } from "../stubs/media_player";
|
||||
import { mockRecorder } from "../stubs/recorder";
|
||||
import { mockSensor } from "../stubs/sensor";
|
||||
import { mockExtractFromTarget } from "../stubs/target";
|
||||
import { mockTemplate } from "../stubs/template";
|
||||
import { mockTodo } from "../stubs/todo";
|
||||
import { mockWeather } from "../stubs/weather";
|
||||
import { embedHassContext } from "./context";
|
||||
import { readScriptData } from "./script-data";
|
||||
|
||||
/** The data of a provider, as set by its script child. */
|
||||
interface EmbedProviderData {
|
||||
entities?: EntityInput[];
|
||||
areas?: DemoArea[];
|
||||
calendars?: Record<string, CalendarEventApiData[]>;
|
||||
energy?: Partial<EnergyPreferences>;
|
||||
}
|
||||
|
||||
const SAMPLE_CALENDAR_EVENTS = [FAMILY_EVENTS, WORK_EVENTS];
|
||||
|
||||
// "living_room" becomes "Living room"
|
||||
const areaName = (areaId: string) => {
|
||||
const name = areaId.replaceAll("_", " ");
|
||||
|
||||
return name.charAt(0).toUpperCase() + name.slice(1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Holds a mocked Home Assistant backend for all `ha-embed-card` elements
|
||||
* inside it. Cards in the same provider share their entities.
|
||||
*/
|
||||
@customElement("ha-embed-provider")
|
||||
export class HaEmbedProvider extends LitElement {
|
||||
@provide({ context: embedHassContext })
|
||||
@property({ attribute: false })
|
||||
public hass!: MockHomeAssistant;
|
||||
|
||||
/**
|
||||
* All entities of the backend. Each change replaces all entities.
|
||||
* Also read from a JSON or YAML script child, see `readScriptData`. The
|
||||
* script holds either the list of entities or an object with `entities`,
|
||||
* `areas`, `calendars` and `energy`.
|
||||
*/
|
||||
@property({ type: Array }) public entities: EntityInput[] = [];
|
||||
|
||||
/** All areas. Without them, an area for each `area_id` of the entities. */
|
||||
@property({ attribute: false }) public areas?: DemoArea[];
|
||||
|
||||
/**
|
||||
* Events of calendar entities by entity ID. Calendars without events here
|
||||
* get sample events around today.
|
||||
*/
|
||||
@property({ attribute: false }) public calendars?: Record<
|
||||
string,
|
||||
CalendarEventApiData[]
|
||||
>;
|
||||
|
||||
/** Energy preferences. Without them, energy is not set up. */
|
||||
@property({ attribute: false }) public energy?: Partial<EnergyPreferences>;
|
||||
|
||||
/** Light or dark mode of the cards. Without it, the browser setting. */
|
||||
@property({ attribute: "color-scheme" }) public colorScheme?:
|
||||
"light" | "dark";
|
||||
|
||||
private _reducedMotion = new ContextProvider(this, {
|
||||
context: reducedMotionContext,
|
||||
initialValue: false,
|
||||
});
|
||||
|
||||
private _prefersDark = matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
|
||||
private _unsubMediaQueries: (() => void)[] = [];
|
||||
|
||||
private _scriptRead = false;
|
||||
|
||||
private _applyColorScheme() {
|
||||
const dark = this.colorScheme
|
||||
? this.colorScheme === "dark"
|
||||
: this._prefersDark;
|
||||
if (this.hass.themes.darkMode !== dark) {
|
||||
this.hass.updateHass({
|
||||
themes: { ...this.hass.themes, darkMode: dark },
|
||||
selectedTheme: { ...this.hass.selectedTheme!, dark },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
// Set up in the constructor so that the contexts exist before the
|
||||
// child cards connect and request them.
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null);
|
||||
hass.updateTranslations("lovelace");
|
||||
mockIcons(hass);
|
||||
mockAuth(hass);
|
||||
mockHistory(hass);
|
||||
mockRecorder(hass);
|
||||
mockTemplate(hass);
|
||||
mockSensor(hass);
|
||||
mockMediaPlayer(hass);
|
||||
mockTodo(hass);
|
||||
mockWeather(hass);
|
||||
mockLogbook(hass);
|
||||
hass.updateHass({
|
||||
config: {
|
||||
...hass.config,
|
||||
components: [...hass.config.components, "logbook"],
|
||||
},
|
||||
});
|
||||
mockCalendarEvents(hass, (entityId, currentHass) => {
|
||||
if (!(entityId in currentHass.states)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const calendarIds = Object.keys(currentHass.states).filter((id) =>
|
||||
id.startsWith("calendar.")
|
||||
);
|
||||
|
||||
return (
|
||||
this.calendars?.[entityId] ??
|
||||
SAMPLE_CALENDAR_EVENTS[
|
||||
calendarIds.indexOf(entityId) % SAMPLE_CALENDAR_EVENTS.length
|
||||
]
|
||||
);
|
||||
});
|
||||
hass.mockWS("config/area_registry/list", (_msg, currentHass) =>
|
||||
Object.values(currentHass.areas)
|
||||
);
|
||||
// The registry of the entities, without settings such as calendar colors
|
||||
const registryEntries = (currentHass: MockHomeAssistant) =>
|
||||
Object.values(currentHass.entities).map(
|
||||
(entity): EntityRegistryEntry => ({
|
||||
...newEntry({
|
||||
entity_id: entity.entity_id,
|
||||
platform: entity.platform ?? "demo",
|
||||
unique_id: entity.entity_id,
|
||||
}),
|
||||
area_id: entity.area_id ?? null,
|
||||
device_id: entity.device_id ?? null,
|
||||
})
|
||||
);
|
||||
hass.mockWS("config/entity_registry/list", (_msg, currentHass) =>
|
||||
registryEntries(currentHass)
|
||||
);
|
||||
hass.mockWS(
|
||||
"config/entity_registry/get",
|
||||
(msg: { entity_id: string }, currentHass: MockHomeAssistant) => {
|
||||
const entry = registryEntries(currentHass).find(
|
||||
(item) => item.entity_id === msg.entity_id
|
||||
);
|
||||
if (!entry) {
|
||||
throw new Error(`Entity not found: ${msg.entity_id}`);
|
||||
}
|
||||
return extEntry(entry);
|
||||
}
|
||||
);
|
||||
mockExtractFromTarget(hass);
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
|
||||
...EMPTY_PREFERENCES,
|
||||
...this.energy,
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
this._applyColorScheme();
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._unsubMediaQueries = [
|
||||
listenMediaQuery("(prefers-color-scheme: dark)", (matches) => {
|
||||
this._prefersDark = matches;
|
||||
this._applyColorScheme();
|
||||
}),
|
||||
listenMediaQuery("(prefers-reduced-motion: reduce)", (matches) =>
|
||||
this._reducedMotion.setValue(matches)
|
||||
),
|
||||
];
|
||||
|
||||
// Only once, so that moving the provider keeps the current entities
|
||||
if (this._scriptRead) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._scriptRead = true;
|
||||
|
||||
const data = readScriptData(this) as
|
||||
EntityInput[] | EmbedProviderData | undefined;
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
this.entities = data;
|
||||
} else if (data) {
|
||||
this.entities = data.entities ?? [];
|
||||
this.areas = data.areas;
|
||||
this.calendars = data.calendars;
|
||||
this.energy = data.energy;
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unsubMediaQueries.forEach((unsub) => unsub());
|
||||
this._unsubMediaQueries = [];
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
if (changedProps.has("colorScheme")) {
|
||||
this._applyColorScheme();
|
||||
}
|
||||
|
||||
if (changedProps.has("entities") || changedProps.has("areas")) {
|
||||
const areas: DemoArea[] =
|
||||
this.areas ??
|
||||
[
|
||||
...new Set(
|
||||
this.entities
|
||||
.map((entity) => entity.area_id)
|
||||
.filter((areaId) => areaId !== undefined)
|
||||
),
|
||||
].map((areaId) => ({ area_id: areaId, name: areaName(areaId) }));
|
||||
|
||||
const areasById: Record<string, AreaRegistryEntry> = {};
|
||||
areas.forEach((area) => {
|
||||
areasById[area.area_id] = toAreaRegistryEntry(area);
|
||||
});
|
||||
// Before the entities, so that their names can include the area
|
||||
this.hass.updateHass({ areas: areasById });
|
||||
|
||||
// Entities that services changed keep their state when only the areas
|
||||
// change
|
||||
if (changedProps.has("entities")) {
|
||||
this.hass.addEntities(this.entities, true);
|
||||
} else {
|
||||
this.hass.updateFormatFunctions();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>) {
|
||||
const oldHass = changedProps.get("hass");
|
||||
// The first update holds the initial entities. They are not changes.
|
||||
if (!oldHass) {
|
||||
return;
|
||||
}
|
||||
// Other updates, such as loaded translations, keep the same states object.
|
||||
if (oldHass.states !== this.hass.states) {
|
||||
fireEvent(this, "states-changed", { states: this.hass.states });
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`<slot></slot>`;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-embed-provider": HaEmbedProvider;
|
||||
}
|
||||
interface HASSDomEvents {
|
||||
"states-changed": { states: HassEntities };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
declare global {
|
||||
var __HA_STATIC_PATH__: string | undefined;
|
||||
}
|
||||
declare let __webpack_public_path__: string;
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
// Load chunks and static files from the server that hosts this script, so
|
||||
// that other sites can embed the cards. Only the modern production build keeps
|
||||
// `import.meta.url` (see build-scripts/rspack.cjs). The legacy and development
|
||||
// builds only run on the demo site, where the default paths are correct.
|
||||
// `new URL(path, import.meta.url)` in one expression is an asset reference for
|
||||
// the bundler, so the script URL goes into a variable first.
|
||||
if (__BUILD__ === "modern" && !__DEV__) {
|
||||
const scriptUrl = import.meta.url;
|
||||
__webpack_public_path__ = new URL(".", scriptUrl).href;
|
||||
globalThis.__HA_STATIC_PATH__ = new URL("../static/", scriptUrl).href;
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,17 @@
|
||||
import { load } from "js-yaml";
|
||||
|
||||
/**
|
||||
* Parses the data in a `<script type="application/json">` or
|
||||
* `<script type="text/yaml">` child of the element.
|
||||
*/
|
||||
export const readScriptData = (element: HTMLElement): unknown => {
|
||||
const script = element.querySelector<HTMLScriptElement>(
|
||||
':scope > script[type="application/json"], :scope > script[type="text/yaml"]'
|
||||
);
|
||||
if (!script) {
|
||||
return undefined;
|
||||
}
|
||||
return script.type === "text/yaml"
|
||||
? load(script.textContent!)
|
||||
: JSON.parse(script.textContent!);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { unsafeCSS } from "lit";
|
||||
import { hex2rgb } from "../../../src/common/color/convert-color";
|
||||
import { darkColorVariables } from "../../../src/resources/theme/color";
|
||||
import { darkSemanticVariables } from "../../../src/resources/theme/semantic.globals";
|
||||
import { themeStyles } from "../../../src/resources/theme/theme";
|
||||
|
||||
// The theme styles set variables on `html`, next to fonts and other page
|
||||
// styles. Only the variables, media queries, and keyframes are copied, and
|
||||
// `html` becomes `selector`. This keeps the theme inside the card, so that it
|
||||
// does not change the page that embeds the card.
|
||||
const scopeThemeStyles = (cssText: string, selector: string): string => {
|
||||
// A style element in a separate document parses the CSS without applying it.
|
||||
const doc = document.implementation.createHTMLDocument("");
|
||||
const style = doc.createElement("style");
|
||||
style.textContent = cssText;
|
||||
doc.head.append(style);
|
||||
|
||||
const convert = (rules: CSSRuleList): string =>
|
||||
Array.from(rules, (rule) => {
|
||||
if (rule instanceof CSSStyleRule) {
|
||||
if (rule.selectorText !== "html") {
|
||||
return "";
|
||||
}
|
||||
const variables = Array.from(rule.style)
|
||||
.filter((name) => name.startsWith("--"))
|
||||
.map((name) => `${name}:${rule.style.getPropertyValue(name)};`);
|
||||
return `${selector}{${variables.join("")}}`;
|
||||
}
|
||||
if (rule instanceof CSSMediaRule) {
|
||||
return `@media ${rule.conditionText}{${convert(rule.cssRules)}}`;
|
||||
}
|
||||
if (rule instanceof CSSKeyframesRule) {
|
||||
return rule.cssText;
|
||||
}
|
||||
return "";
|
||||
}).join("");
|
||||
|
||||
return convert(style.sheet!.cssRules);
|
||||
};
|
||||
|
||||
const darkTheme = {
|
||||
...darkSemanticVariables,
|
||||
...darkColorVariables,
|
||||
};
|
||||
|
||||
// Like processTheme in apply_themes_on_element, each hex color also sets its
|
||||
// `--rgb-` variable, else those keep their light theme values
|
||||
const darkVariables = Object.entries(darkTheme).flatMap(([name, value]) => {
|
||||
const variable = `--${name}:${value};`;
|
||||
|
||||
if (!value.startsWith("#") || `rgb-${name}` in darkTheme) {
|
||||
return [variable];
|
||||
}
|
||||
|
||||
return [variable, `--rgb-${name}:${hex2rgb(value).join(",")};`];
|
||||
});
|
||||
|
||||
export const embedThemeStyles = unsafeCSS(
|
||||
scopeThemeStyles(themeStyles, ".theme") +
|
||||
`.theme.dark{${darkVariables.join("")}}`
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
// Browsers only start a worker from a script on the page's own origin, and
|
||||
// the workers of the cards, such as the markdown worker, are served next to
|
||||
// this script. A worker from another origin starts from a blob instead, which
|
||||
// loads the real worker script. The demo serves its scripts with CORS.
|
||||
const pageWorker = globalThis.Worker;
|
||||
|
||||
globalThis.Worker = class extends pageWorker {
|
||||
constructor(scriptUrl: string | URL, options?: WorkerOptions) {
|
||||
const url = new URL(scriptUrl, location.href);
|
||||
|
||||
if (url.origin === location.origin) {
|
||||
super(scriptUrl, options);
|
||||
return;
|
||||
}
|
||||
|
||||
const source =
|
||||
options?.type === "module"
|
||||
? `import ${JSON.stringify(url.href)};`
|
||||
: `importScripts(${JSON.stringify(url.href)});`;
|
||||
const blobUrl = URL.createObjectURL(
|
||||
new Blob([source], { type: "text/javascript" })
|
||||
);
|
||||
|
||||
try {
|
||||
super(blobUrl, options);
|
||||
} finally {
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export {};
|
||||
@@ -36,6 +36,7 @@ import { mockHardware } from "./stubs/hardware";
|
||||
import { mockHassioSupervisor } from "./stubs/hassio_supervisor";
|
||||
import { mockIntegration } from "./stubs/integration";
|
||||
import { mockLabelRegistry } from "./stubs/label_registry";
|
||||
import { mockLogbook } from "./stubs/logbook";
|
||||
import { automationPlatformDomains } from "./stubs/automation_platform_domains";
|
||||
import { mockIcons } from "./stubs/icons";
|
||||
import { mockHistory } from "./stubs/history";
|
||||
@@ -50,6 +51,7 @@ import { mockTemplate } from "./stubs/template";
|
||||
import { mockTodo } from "./stubs/todo";
|
||||
import { mockTranslations } from "./stubs/translations";
|
||||
import { mockUsagePrediction } from "./stubs/usage_prediction";
|
||||
import { mockWeather } from "./stubs/weather";
|
||||
|
||||
// WS command / REST path prefixes whose mocks live in the lazily imported
|
||||
// config-panel chunk (see ./stubs/config-panel). Must stay in sync with it.
|
||||
@@ -75,6 +77,7 @@ const CONFIG_PANEL_COMMANDS = [
|
||||
"get_conditions_for_target",
|
||||
"get_services_for_target",
|
||||
"extract_from_target",
|
||||
"explain_target",
|
||||
"script/config",
|
||||
"config/automation/config",
|
||||
"config/script/config",
|
||||
@@ -190,7 +193,9 @@ export class HaDemo extends HomeAssistantAppEl {
|
||||
mockSystemLog(hass);
|
||||
mockTemplate(hass);
|
||||
mockEvents(hass);
|
||||
mockLogbook(hass);
|
||||
mockMediaPlayer(hass);
|
||||
mockWeather(hass);
|
||||
mockFrontend(hass);
|
||||
mockHardware(hass);
|
||||
mockHassioSupervisor(hass);
|
||||
|
||||
@@ -0,0 +1,762 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home Assistant card components</title>
|
||||
<%= renderTemplate("../../../src/html/_header.html.template") %>
|
||||
<meta name="referrer" content="same-origin" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, shrink-to-fit=no"
|
||||
/>
|
||||
<meta name="theme-color" content="#03a9f4" />
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page-background: #fafafa;
|
||||
--page-text: #212121;
|
||||
--page-code-background: #e5e5e5;
|
||||
--page-divider: #dddddd;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-scheme="light"]) {
|
||||
color-scheme: dark;
|
||||
--page-background: #111111;
|
||||
--page-text: #e1e1e1;
|
||||
--page-code-background: #1c1c1c;
|
||||
--page-divider: #333333;
|
||||
}
|
||||
}
|
||||
:root[data-scheme="dark"] {
|
||||
color-scheme: dark;
|
||||
--page-background: #111111;
|
||||
--page-text: #e1e1e1;
|
||||
--page-code-background: #1c1c1c;
|
||||
--page-divider: #333333;
|
||||
}
|
||||
html {
|
||||
background-color: var(--page-background);
|
||||
color: var(--page-text);
|
||||
}
|
||||
body {
|
||||
font-family: Roboto, Noto, sans-serif;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
padding: 0 16px 64px;
|
||||
}
|
||||
main {
|
||||
max-width: 880px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
h1 {
|
||||
margin: 32px 0 8px;
|
||||
}
|
||||
h2 {
|
||||
margin: 48px 0 8px;
|
||||
}
|
||||
pre {
|
||||
background: var(--page-code-background);
|
||||
border-radius: 8px;
|
||||
padding: 12px 16px;
|
||||
overflow-x: auto;
|
||||
font-size: 13px;
|
||||
}
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
text-align: start;
|
||||
vertical-align: top;
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--page-divider);
|
||||
}
|
||||
.cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.single {
|
||||
max-width: 400px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.log {
|
||||
height: 160px;
|
||||
overflow-y: auto;
|
||||
margin: 0;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
padding: 6px 12px;
|
||||
margin-inline-end: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Home Assistant card components</h1>
|
||||
<p>
|
||||
Embed working Home Assistant dashboard cards in any page. The cards run
|
||||
against a mocked backend in the browser. No Home Assistant server is
|
||||
necessary.
|
||||
</p>
|
||||
<p>There are two components:</p>
|
||||
<ul>
|
||||
<li>
|
||||
<code><ha-embed-provider></code> holds the mocked backend and
|
||||
its entities.
|
||||
</li>
|
||||
<li>
|
||||
<code><ha-embed-card></code> renders one card. It uses the
|
||||
backend of a provider.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
All cards in the same provider share their entities. When you change
|
||||
an entity in one card, the other cards show the change.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Color scheme of this page and its cards:
|
||||
<button data-scheme="">Auto</button>
|
||||
<button data-scheme="light">Light</button>
|
||||
<button data-scheme="dark">Dark</button>
|
||||
</p>
|
||||
|
||||
<h2>Use on your site</h2>
|
||||
<p>
|
||||
Load the script from the demo site. The script loads all other files
|
||||
from the demo site too.
|
||||
</p>
|
||||
<pre><code><script type="module" src="https://demo.home-assistant.io/embed.js"></script></code></pre>
|
||||
|
||||
<h2>One card</h2>
|
||||
<p>
|
||||
Put the entities in a script tag inside the provider. Put the card
|
||||
configuration in a script tag inside the card. Both take JSON with
|
||||
<code>type="application/json"</code> or YAML with
|
||||
<code>type="text/yaml"</code>. The card configuration is the same as in
|
||||
a dashboard. YAML needs its indentation. If your site minifies HTML,
|
||||
make sure the minifier keeps the whitespace in script tags, or use
|
||||
JSON.
|
||||
</p>
|
||||
<pre><code><ha-embed-provider>
|
||||
<script type="text/yaml">
|
||||
- entity_id: light.kitchen
|
||||
state: "on"
|
||||
attributes:
|
||||
friendly_name: Kitchen
|
||||
supported_color_modes: [brightness]
|
||||
color_mode: brightness
|
||||
brightness: 180
|
||||
</script>
|
||||
<ha-embed-card>
|
||||
<script type="text/yaml">
|
||||
type: tile
|
||||
entity: light.kitchen
|
||||
tap_action:
|
||||
action: toggle
|
||||
features:
|
||||
- type: light-brightness
|
||||
</script>
|
||||
</ha-embed-card>
|
||||
</ha-embed-provider></code></pre>
|
||||
<ha-embed-provider>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
- entity_id: light.kitchen
|
||||
state: "on"
|
||||
attributes:
|
||||
friendly_name: Kitchen
|
||||
supported_color_modes: [brightness]
|
||||
color_mode: brightness
|
||||
brightness: 180
|
||||
</script><!-- htmlmin:ignore -->
|
||||
<div class="single">
|
||||
<ha-embed-card>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
type: tile
|
||||
entity: light.kitchen
|
||||
tap_action:
|
||||
action: toggle
|
||||
features:
|
||||
- type: light-brightness
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-card>
|
||||
</div>
|
||||
</ha-embed-provider>
|
||||
<p>
|
||||
The <code>entities</code> attribute of the provider and the
|
||||
<code>config</code> attribute of the card also take JSON.
|
||||
</p>
|
||||
|
||||
<h2>Cards with shared state</h2>
|
||||
<p>
|
||||
These three cards are in one provider. Turn on a light in one card. The
|
||||
other cards update. The log below shows the events of the provider.
|
||||
</p>
|
||||
<ha-embed-provider id="shared">
|
||||
<script type="application/json">
|
||||
[
|
||||
{
|
||||
"entity_id": "light.living_room",
|
||||
"state": "off",
|
||||
"attributes": {
|
||||
"friendly_name": "Living room",
|
||||
"supported_color_modes": ["brightness"],
|
||||
"color_mode": "brightness",
|
||||
"brightness": 255
|
||||
}
|
||||
},
|
||||
{
|
||||
"entity_id": "switch.coffee_maker",
|
||||
"state": "on",
|
||||
"attributes": {
|
||||
"friendly_name": "Coffee maker",
|
||||
"device_class": "outlet"
|
||||
}
|
||||
},
|
||||
{
|
||||
"entity_id": "climate.hallway",
|
||||
"state": "heat",
|
||||
"attributes": {
|
||||
"friendly_name": "Hallway",
|
||||
"current_temperature": 19.5,
|
||||
"temperature": 21,
|
||||
"min_temp": 7,
|
||||
"max_temp": 30,
|
||||
"target_temp_step": 0.5,
|
||||
"hvac_modes": ["heat", "off"],
|
||||
"hvac_action": "heating",
|
||||
"supported_features": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"entity_id": "sensor.outside_temperature",
|
||||
"state": "12.3",
|
||||
"attributes": {
|
||||
"friendly_name": "Outside temperature",
|
||||
"device_class": "temperature",
|
||||
"state_class": "measurement",
|
||||
"unit_of_measurement": "°C"
|
||||
}
|
||||
}
|
||||
]
|
||||
</script>
|
||||
<div class="cards">
|
||||
<ha-embed-card>
|
||||
<script type="application/json">
|
||||
{
|
||||
"type": "tile",
|
||||
"entity": "light.living_room",
|
||||
"tap_action": { "action": "toggle" }
|
||||
}
|
||||
</script>
|
||||
</ha-embed-card>
|
||||
<ha-embed-card>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
type: entities
|
||||
title: Living room
|
||||
entities:
|
||||
- light.living_room
|
||||
- switch.coffee_maker
|
||||
- sensor.outside_temperature
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-card>
|
||||
<ha-embed-card>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
type: thermostat
|
||||
entity: climate.hallway
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-card>
|
||||
</div>
|
||||
</ha-embed-provider>
|
||||
<pre class="log" id="log"><code>Use the cards to see events here.</code></pre>
|
||||
|
||||
<h2>Cards outside a provider</h2>
|
||||
<p>
|
||||
A card does not have to be inside a provider. A card outside a provider
|
||||
uses the first provider on the page. Put one provider with all entities
|
||||
at the top of the page, and put the cards anywhere below it. If the
|
||||
page has no provider, the card adds an empty provider to the page.
|
||||
</p>
|
||||
<p>
|
||||
To use a different provider, set the <code>provider</code> attribute of
|
||||
the card to the ID of the provider.
|
||||
</p>
|
||||
<pre><code><ha-embed-provider id="living-room">…</ha-embed-provider>
|
||||
|
||||
<p>Some text about the coffee maker.</p>
|
||||
|
||||
<ha-embed-card provider="living-room">
|
||||
<script type="text/yaml">
|
||||
type: tile
|
||||
entity: switch.coffee_maker
|
||||
</script>
|
||||
</ha-embed-card></code></pre>
|
||||
<p>
|
||||
These two cards are not inside a provider. The first card uses the
|
||||
first provider on this page, the kitchen light at the top. The second
|
||||
card uses the provider with the ID <code>shared</code> above.
|
||||
</p>
|
||||
<div class="cards">
|
||||
<ha-embed-card>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
type: tile
|
||||
entity: light.kitchen
|
||||
tap_action:
|
||||
action: toggle
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-card>
|
||||
<ha-embed-card provider="shared">
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
type: tile
|
||||
entity: switch.coffee_maker
|
||||
tap_action:
|
||||
action: toggle
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-card>
|
||||
</div>
|
||||
|
||||
<h2>Light and dark mode</h2>
|
||||
<p>
|
||||
The cards follow the light or dark mode of the browser. To choose the
|
||||
mode, set the <code>color-scheme</code> attribute of the provider to
|
||||
<code>light</code> or <code>dark</code>. Use this when your site has its
|
||||
own switch for dark mode. The buttons at the top of this page do this.
|
||||
The cards keep their styles inside. They do not change the styles of
|
||||
your page.
|
||||
</p>
|
||||
<pre><code><ha-embed-provider color-scheme="dark">…</ha-embed-provider></code></pre>
|
||||
|
||||
<h2>Change entities from the page</h2>
|
||||
<p>
|
||||
Set the <code>entities</code> property to change entities from
|
||||
JavaScript. The new list replaces all entities. To change one entity,
|
||||
start from the current states.
|
||||
</p>
|
||||
<p>
|
||||
<button id="set-temperature">Set a random outside temperature</button>
|
||||
<button id="toggle-coffee">Toggle the coffee maker</button>
|
||||
</p>
|
||||
<pre><code>const provider = document.querySelector("ha-embed-provider");
|
||||
provider.entities = Object.values(provider.hass.states).map((entity) =>
|
||||
entity.entity_id === "sensor.outside_temperature"
|
||||
? { ...entity, state: "18.1" }
|
||||
: entity
|
||||
);</code></pre>
|
||||
<p>
|
||||
To use the actions of an entity, call a service. The provider updates
|
||||
the state and the cards.
|
||||
</p>
|
||||
<pre><code>provider.hass.callService("switch", "toggle", {
|
||||
entity_id: "switch.coffee_maker",
|
||||
});</code></pre>
|
||||
|
||||
<h2>Listen to changes</h2>
|
||||
<p>
|
||||
The provider fires a <code>states-changed</code> event when the state
|
||||
of one or more entities changes. The event has the states of all
|
||||
entities. The event bubbles.
|
||||
</p>
|
||||
<pre><code>provider.addEventListener("states-changed", (ev) => {
|
||||
const { states } = ev.detail;
|
||||
console.log(states["light.living_room"].state);
|
||||
});</code></pre>
|
||||
<p>
|
||||
Read the current state of all entities with
|
||||
<code>provider.hass.states</code>.
|
||||
</p>
|
||||
|
||||
<h2>Areas, calendars and energy</h2>
|
||||
<p>
|
||||
Some cards need data that is not an entity. To set it, put an object in
|
||||
the script tag of the provider instead of the list. The object has the
|
||||
list in <code>entities</code>, and any of these keys:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<code>areas</code>: a list of areas, each with an
|
||||
<code>area_id</code> and a <code>name</code>. Without it, each
|
||||
<code>area_id</code> of the entities becomes an area.
|
||||
</li>
|
||||
<li>
|
||||
<code>calendars</code>: the events of calendar entities, by entity
|
||||
ID. Each event has a <code>summary</code>, a <code>start</code> and
|
||||
an <code>end</code>. Calendars without events here get sample events
|
||||
around today.
|
||||
</li>
|
||||
<li>
|
||||
<code>energy</code>: the energy settings, the same as the
|
||||
<code>energy/get_prefs</code> response. Without it, energy is not
|
||||
set up.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
Weather entities get a forecast made up from their condition and
|
||||
temperature, or their <code>forecast</code> attribute when they have
|
||||
one. Set <code>supported_features</code> to show forecasts.
|
||||
</p>
|
||||
<pre><code><ha-embed-provider>
|
||||
<script type="text/yaml">
|
||||
entities:
|
||||
- entity_id: calendar.family
|
||||
state: "off"
|
||||
attributes:
|
||||
friendly_name: Family
|
||||
areas:
|
||||
- area_id: kitchen
|
||||
name: Kitchen
|
||||
calendars:
|
||||
calendar.family:
|
||||
- summary: Dentist
|
||||
start: "2026-11-02T15:30:00+00:00"
|
||||
end: "2026-11-02T16:15:00+00:00"
|
||||
</script>
|
||||
…
|
||||
</ha-embed-provider></code></pre>
|
||||
<p>This calendar card uses the sample events.</p>
|
||||
<ha-embed-provider>
|
||||
<script type="application/json">
|
||||
{
|
||||
"entities": [
|
||||
{
|
||||
"entity_id": "calendar.family",
|
||||
"state": "off",
|
||||
"attributes": { "friendly_name": "Family" }
|
||||
}
|
||||
]
|
||||
}
|
||||
</script>
|
||||
<div class="single">
|
||||
<ha-embed-card
|
||||
config='{ "type": "calendar", "entities": ["calendar.family"], "initial_view": "listWeek" }'
|
||||
></ha-embed-card>
|
||||
</div>
|
||||
</ha-embed-provider>
|
||||
|
||||
<h2>Custom cards</h2>
|
||||
<p>
|
||||
Custom cards work too. Load the script of the custom card on the page,
|
||||
and use <code>custom:</code> and the element name as the card type.
|
||||
The custom card gets the same mocked backend as the other cards.
|
||||
<code>window.loadCardHelpers()</code> is available to create built-in
|
||||
cards.
|
||||
</p>
|
||||
<p>
|
||||
The mocked backend only knows a part of the Home Assistant API. History
|
||||
and statistics are made up from the current state of each entity.
|
||||
Templates are not rendered, they come back as they are. The logbook is
|
||||
empty. Other requests get an error. From another site, the script of
|
||||
the custom card needs CORS headers, like the embed script.
|
||||
</p>
|
||||
<pre><code><script type="module" src="https://example.com/embed-demo-custom-card.js"></script>
|
||||
<ha-embed-card>
|
||||
<script type="text/yaml">
|
||||
type: custom:embed-demo-custom-card
|
||||
entity: light.office
|
||||
</script>
|
||||
</ha-embed-card></code></pre>
|
||||
<ha-embed-provider>
|
||||
<script type="application/json">
|
||||
[
|
||||
{
|
||||
"entity_id": "light.office",
|
||||
"state": "on",
|
||||
"attributes": {
|
||||
"friendly_name": "Office",
|
||||
"supported_color_modes": ["brightness"],
|
||||
"color_mode": "brightness",
|
||||
"brightness": 120
|
||||
}
|
||||
}
|
||||
]
|
||||
</script>
|
||||
<div class="single">
|
||||
<ha-embed-card
|
||||
config='{ "type": "custom:embed-demo-custom-card", "entity": "light.office" }'
|
||||
></ha-embed-card>
|
||||
</div>
|
||||
</ha-embed-provider>
|
||||
<p>This is the code of the custom card:</p>
|
||||
<pre><code>class EmbedDemoCustomCard extends HTMLElement {
|
||||
setConfig(config) {
|
||||
if (!config.entity) {
|
||||
throw new Error("Set an entity");
|
||||
}
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
set hass(hass) {
|
||||
this._hass = hass;
|
||||
this._render();
|
||||
}
|
||||
|
||||
getCardSize() {
|
||||
return 3;
|
||||
}
|
||||
|
||||
async _render() {
|
||||
if (!this.shadowRoot) {
|
||||
this.attachShadow({ mode: "open" }).innerHTML = `
|
||||
<style>
|
||||
ha-card { padding: 16px; }
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--accent-color);
|
||||
color: var(--text-accent-color, #fff);
|
||||
font-size: 12px;
|
||||
}
|
||||
.tile { margin: 12px 0; }
|
||||
</style>
|
||||
<ha-card>
|
||||
<span class="badge">Custom card</span>
|
||||
<p>
|
||||
This is a custom card. It is not part of Home Assistant. The page
|
||||
defines it, and it creates the tile card below with the card
|
||||
helpers.
|
||||
</p>
|
||||
<div class="tile"></div>
|
||||
<button>Toggle from the custom card</button>
|
||||
</ha-card>`;
|
||||
this.shadowRoot.querySelector("button").addEventListener("click", () =>
|
||||
this._hass.callService("homeassistant", "toggle", {
|
||||
entity_id: this._config.entity,
|
||||
})
|
||||
);
|
||||
}
|
||||
// Keep the promise, so that a second update does not create a second tile.
|
||||
if (!this._tile) {
|
||||
this._tile = window.loadCardHelpers().then((helpers) => {
|
||||
const tile = helpers.createCardElement({
|
||||
type: "tile",
|
||||
entity: this._config.entity,
|
||||
});
|
||||
this.shadowRoot.querySelector(".tile").append(tile);
|
||||
return tile;
|
||||
});
|
||||
}
|
||||
(await this._tile).hass = this._hass;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("embed-demo-custom-card", EmbedDemoCustomCard);</code></pre>
|
||||
<script type="module">
|
||||
class EmbedDemoCustomCard extends HTMLElement {
|
||||
setConfig(config) {
|
||||
if (!config.entity) {
|
||||
throw new Error("Set an entity");
|
||||
}
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
set hass(hass) {
|
||||
this._hass = hass;
|
||||
this._render();
|
||||
}
|
||||
|
||||
getCardSize() {
|
||||
return 3;
|
||||
}
|
||||
|
||||
async _render() {
|
||||
if (!this.shadowRoot) {
|
||||
this.attachShadow({ mode: "open" }).innerHTML = `
|
||||
<style>
|
||||
ha-card { padding: 16px; }
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--accent-color);
|
||||
color: var(--text-accent-color, #fff);
|
||||
font-size: 12px;
|
||||
}
|
||||
.tile { margin: 12px 0; }
|
||||
</style>
|
||||
<ha-card>
|
||||
<span class="badge">Custom card</span>
|
||||
<p>
|
||||
This is a custom card. It is not part of Home Assistant. The page
|
||||
defines it, and it creates the tile card below with the card
|
||||
helpers.
|
||||
</p>
|
||||
<div class="tile"></div>
|
||||
<button>Toggle from the custom card</button>
|
||||
</ha-card>`;
|
||||
this.shadowRoot.querySelector("button").addEventListener("click", () =>
|
||||
this._hass.callService("homeassistant", "toggle", {
|
||||
entity_id: this._config.entity,
|
||||
})
|
||||
);
|
||||
}
|
||||
// Keep the promise, so that a second update does not create a second tile.
|
||||
if (!this._tile) {
|
||||
this._tile = window.loadCardHelpers().then((helpers) => {
|
||||
const tile = helpers.createCardElement({
|
||||
type: "tile",
|
||||
entity: this._config.entity,
|
||||
});
|
||||
this.shadowRoot.querySelector(".tile").append(tile);
|
||||
return tile;
|
||||
});
|
||||
}
|
||||
(await this._tile).hass = this._hass;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("embed-demo-custom-card", EmbedDemoCustomCard);
|
||||
</script>
|
||||
|
||||
<h2>Reference</h2>
|
||||
<h3><code><ha-embed-provider></code></h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>entities</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
A list of entities. Each entity has an <code>entity_id</code>, a
|
||||
<code>state</code>, and <code>attributes</code>. The optional keys
|
||||
<code>area_id</code>, <code>device_id</code>, and
|
||||
<code>platform</code> set the entity registry entry. A new list
|
||||
replaces all entities. A JSON or YAML script child sets the first
|
||||
list.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>color-scheme</code></td>
|
||||
<td>Attribute and property (<code>colorScheme</code>)</td>
|
||||
<td>
|
||||
<code>light</code> or <code>dark</code>. Without it, the cards
|
||||
follow the browser setting.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>hass</code></td>
|
||||
<td>Property, read-only</td>
|
||||
<td>The mocked Home Assistant object that the cards use.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>states-changed</code></td>
|
||||
<td>Event</td>
|
||||
<td>
|
||||
Fires when the state of one or more entities changes. The detail
|
||||
has <code>states</code>, the states of all entities by entity ID.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h3><code><ha-embed-card></code></h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>config</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The card configuration, the same as in a dashboard. A JSON or YAML
|
||||
script child sets the first configuration.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>provider</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The ID of the provider to use. Without it, the card uses the
|
||||
provider around it, else the first provider on the page.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>
|
||||
The mocked backend knows the actions of lights, switches, climate,
|
||||
covers, fans, locks, media players, and more. Actions that open dialogs,
|
||||
such as <code>more-info</code>, do nothing.
|
||||
</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
var shared = document.getElementById("shared");
|
||||
var log = document.getElementById("log");
|
||||
var first = true;
|
||||
shared.addEventListener("states-changed", function (ev) {
|
||||
var states = ev.detail.states;
|
||||
var line =
|
||||
new Date().toLocaleTimeString() +
|
||||
" " +
|
||||
Object.keys(states)
|
||||
.map(function (entityId) {
|
||||
return entityId + "=" + states[entityId].state;
|
||||
})
|
||||
.join(", ");
|
||||
if (first) {
|
||||
log.textContent = "";
|
||||
first = false;
|
||||
}
|
||||
log.textContent = line + "\n" + log.textContent;
|
||||
});
|
||||
document
|
||||
.getElementById("set-temperature")
|
||||
.addEventListener("click", function () {
|
||||
var states = shared.hass.states;
|
||||
shared.entities = Object.keys(states).map(function (entityId) {
|
||||
var entity = states[entityId];
|
||||
return {
|
||||
entity_id: entityId,
|
||||
state:
|
||||
entityId === "sensor.outside_temperature"
|
||||
? (Math.random() * 30 - 5).toFixed(1)
|
||||
: entity.state,
|
||||
attributes: entity.attributes,
|
||||
};
|
||||
});
|
||||
});
|
||||
document
|
||||
.querySelectorAll("button[data-scheme]")
|
||||
.forEach(function (button) {
|
||||
button.addEventListener("click", function () {
|
||||
var scheme = button.getAttribute("data-scheme");
|
||||
if (scheme) {
|
||||
document.documentElement.setAttribute("data-scheme", scheme);
|
||||
} else {
|
||||
document.documentElement.removeAttribute("data-scheme");
|
||||
}
|
||||
document
|
||||
.querySelectorAll("ha-embed-provider")
|
||||
.forEach(function (provider) {
|
||||
if (scheme) {
|
||||
provider.setAttribute("color-scheme", scheme);
|
||||
} else {
|
||||
provider.removeAttribute("color-scheme");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
document
|
||||
.getElementById("toggle-coffee")
|
||||
.addEventListener("click", function () {
|
||||
shared.hass.callService("switch", "toggle", {
|
||||
entity_id: "switch.coffee_maker",
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<%= renderTemplate("../../../src/html/_js_base.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_script_loader.html.template") %>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
import "<%= latestEntryJS[0] %>";
|
||||
@@ -12,6 +12,20 @@ export interface DemoArea {
|
||||
|
||||
let areas: AreaRegistryEntry[] = [];
|
||||
|
||||
export const toAreaRegistryEntry = (area: DemoArea): AreaRegistryEntry => ({
|
||||
area_id: area.area_id,
|
||||
name: area.name,
|
||||
floor_id: area.floor_id ?? null,
|
||||
icon: area.icon ?? null,
|
||||
temperature_entity_id: area.temperature_entity_id ?? null,
|
||||
humidity_entity_id: area.humidity_entity_id ?? null,
|
||||
aliases: [],
|
||||
labels: [],
|
||||
picture: null,
|
||||
created_at: 0,
|
||||
modified_at: 0,
|
||||
});
|
||||
|
||||
export const mockAreaRegistry = (
|
||||
hass: MockHomeAssistant,
|
||||
data: DemoArea[] = []
|
||||
@@ -25,19 +39,7 @@ export const setDemoAreas = (
|
||||
hass: MockHomeAssistant,
|
||||
demoAreas: DemoArea[] = []
|
||||
) => {
|
||||
areas = demoAreas.map((area) => ({
|
||||
area_id: area.area_id,
|
||||
name: area.name,
|
||||
floor_id: area.floor_id ?? null,
|
||||
icon: area.icon ?? null,
|
||||
temperature_entity_id: area.temperature_entity_id ?? null,
|
||||
humidity_entity_id: area.humidity_entity_id ?? null,
|
||||
aliases: [],
|
||||
labels: [],
|
||||
picture: null,
|
||||
created_at: 0,
|
||||
modified_at: 0,
|
||||
}));
|
||||
areas = demoAreas.map(toAreaRegistryEntry);
|
||||
const areasById: Record<string, AreaRegistryEntry> = {};
|
||||
areas.forEach((area) => {
|
||||
areasById[area.area_id] = area;
|
||||
|
||||
@@ -2,14 +2,14 @@ import type { HassServiceTarget } from "home-assistant-js-websocket";
|
||||
import { ensureArray } from "../../../src/common/array/ensure-array";
|
||||
import { computeDomain } from "../../../src/common/entity/compute_domain";
|
||||
import type { ConditionDescriptions } from "../../../src/data/condition";
|
||||
import type { ExtractFromTargetResult } from "../../../src/data/target";
|
||||
import type { TriggerDescriptions } from "../../../src/data/trigger";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import { getLabelIds } from "./label_registry";
|
||||
import {
|
||||
conditionDescriptions,
|
||||
triggerDescriptions,
|
||||
} from "./automation_platforms_data";
|
||||
import { explainTarget } from "./explain_target";
|
||||
import { expandTarget, mockExtractFromTarget } from "./target";
|
||||
|
||||
type Descriptions = TriggerDescriptions | ConditionDescriptions;
|
||||
|
||||
@@ -20,109 +20,6 @@ interface EntityFilter {
|
||||
supported_features?: number[];
|
||||
}
|
||||
|
||||
// Expands a target to its areas, devices and entities, like core does
|
||||
const expandTarget = (
|
||||
hass: MockHomeAssistant,
|
||||
target: HassServiceTarget,
|
||||
primaryEntitiesOnly = true
|
||||
) => {
|
||||
const missing = {
|
||||
floors: [] as string[],
|
||||
areas: [] as string[],
|
||||
devices: [] as string[],
|
||||
labels: [] as string[],
|
||||
};
|
||||
const knownLabelIds = getLabelIds();
|
||||
const floorIds = ensureArray(target.floor_id ?? []);
|
||||
const labelIds = ensureArray(target.label_id ?? []);
|
||||
missing.floors.push(...floorIds.filter((id) => !(id in hass.floors)));
|
||||
// Like core, unknown labels are reported, but still expanded
|
||||
missing.labels.push(...labelIds.filter((id) => !knownLabelIds.includes(id)));
|
||||
const hasLabel = (labels?: string[]) =>
|
||||
labelIds.some((labelId) => labels?.includes(labelId));
|
||||
|
||||
// Unknown areas and devices are reported, but still referenced
|
||||
const areaIds = new Set(ensureArray(target.area_id ?? []));
|
||||
missing.areas.push(...[...areaIds].filter((id) => !(id in hass.areas)));
|
||||
for (const area of Object.values(hass.areas)) {
|
||||
if (
|
||||
(area.floor_id && floorIds.includes(area.floor_id)) ||
|
||||
hasLabel(area.labels)
|
||||
) {
|
||||
areaIds.add(area.area_id);
|
||||
}
|
||||
}
|
||||
|
||||
// A targeted or labeled device includes its child devices
|
||||
const deviceIds = new Set<string>();
|
||||
const addDevice = (deviceId: string) => {
|
||||
deviceIds.add(deviceId);
|
||||
for (const device of Object.values(hass.devices)) {
|
||||
if (device.parent_device_id === deviceId) {
|
||||
deviceIds.add(device.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const deviceId of ensureArray(target.device_id ?? [])) {
|
||||
if (!(deviceId in hass.devices)) {
|
||||
missing.devices.push(deviceId);
|
||||
}
|
||||
addDevice(deviceId);
|
||||
}
|
||||
for (const device of Object.values(hass.devices)) {
|
||||
if (hasLabel(device.labels)) {
|
||||
addDevice(device.id);
|
||||
}
|
||||
}
|
||||
|
||||
// A child device without its own area is in the area of its parent device
|
||||
const deviceArea = (deviceId: string) => {
|
||||
const device = hass.devices[deviceId];
|
||||
return (
|
||||
device?.area_id ??
|
||||
(device?.parent_device_id
|
||||
? hass.devices[device.parent_device_id]?.area_id
|
||||
: undefined)
|
||||
);
|
||||
};
|
||||
const areaDeviceIds = new Set<string>();
|
||||
for (const device of Object.values(hass.devices)) {
|
||||
const areaId = deviceArea(device.id);
|
||||
if (areaId && areaIds.has(areaId)) {
|
||||
areaDeviceIds.add(device.id);
|
||||
}
|
||||
}
|
||||
|
||||
const entityIds = new Set(ensureArray(target.entity_id ?? []));
|
||||
for (const entity of Object.values(hass.entities)) {
|
||||
// The display registry keeps the entities of a previous demo, and like
|
||||
// core, hidden entities are never included indirectly
|
||||
if (!(entity.entity_id in hass.states) || entity.hidden) {
|
||||
continue;
|
||||
}
|
||||
const primary = !primaryEntitiesOnly || !entity.entity_category;
|
||||
if (
|
||||
hasLabel(entity.labels) ||
|
||||
(primary &&
|
||||
((entity.device_id && deviceIds.has(entity.device_id)) ||
|
||||
(entity.area_id && areaIds.has(entity.area_id)) ||
|
||||
// An entity with its own area is not in the area of its device
|
||||
(!entity.area_id &&
|
||||
entity.device_id &&
|
||||
areaDeviceIds.has(entity.device_id))))
|
||||
) {
|
||||
entityIds.add(entity.entity_id);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
areas: [...areaIds],
|
||||
devices: [...new Set([...deviceIds, ...areaDeviceIds])],
|
||||
entities: [...entityIds],
|
||||
missing,
|
||||
};
|
||||
};
|
||||
|
||||
const matchesFilter = (
|
||||
hass: MockHomeAssistant,
|
||||
entityId: string,
|
||||
@@ -228,27 +125,20 @@ export const mockAutomationPlatforms = (hass: MockHomeAssistant) => {
|
||||
);
|
||||
mockForTarget(hass, "get_triggers_for_target", triggerDescriptions);
|
||||
mockForTarget(hass, "get_conditions_for_target", conditionDescriptions);
|
||||
mockExtractFromTarget(hass);
|
||||
hass.mockWS(
|
||||
"extract_from_target",
|
||||
"explain_target",
|
||||
(
|
||||
msg: { target: HassServiceTarget; primary_entities_only?: boolean },
|
||||
currentHass: MockHomeAssistant
|
||||
): ExtractFromTargetResult => {
|
||||
const { areas, devices, entities, missing } = expandTarget(
|
||||
currentHass,
|
||||
) =>
|
||||
explainTarget(
|
||||
msg.target,
|
||||
(target, primaryEntitiesOnly) =>
|
||||
expandTarget(currentHass, target, primaryEntitiesOnly),
|
||||
Object.keys(currentHass.states),
|
||||
msg.primary_entities_only ?? true
|
||||
);
|
||||
return {
|
||||
missing_areas: missing.areas,
|
||||
missing_devices: missing.devices,
|
||||
missing_floors: missing.floors,
|
||||
missing_labels: missing.labels,
|
||||
referenced_areas: areas,
|
||||
referenced_devices: devices,
|
||||
referenced_entities: entities,
|
||||
};
|
||||
}
|
||||
)
|
||||
);
|
||||
hass.mockWS(
|
||||
"get_services_for_target",
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { CalendarEventApiData } from "../../../src/data/calendar";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
// Sample events relative to today, so demos always show something in the
|
||||
// current week and month.
|
||||
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
|
||||
const day = (offset: number): Date => {
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
date.setDate(date.getDate() + offset);
|
||||
|
||||
return date;
|
||||
};
|
||||
|
||||
const isoDate = (date: Date) =>
|
||||
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
|
||||
const at = (offset: number, hours: number, minutes = 0) => {
|
||||
const date = day(offset);
|
||||
date.setHours(hours, minutes);
|
||||
|
||||
return date.toISOString();
|
||||
};
|
||||
|
||||
const allDay = (offset: number, days = 1) => ({
|
||||
start: isoDate(day(offset)),
|
||||
end: isoDate(day(offset + days)),
|
||||
all_day: true,
|
||||
});
|
||||
|
||||
export const FAMILY_EVENTS: CalendarEventApiData[] = [
|
||||
{ summary: "School run", start: at(0, 8), end: at(0, 8, 30) },
|
||||
{
|
||||
summary: "Dentist",
|
||||
start: at(0, 15, 30),
|
||||
end: at(0, 16, 15),
|
||||
location: "Main Street 12",
|
||||
},
|
||||
{ summary: "Grandma's birthday", ...allDay(1) },
|
||||
{ summary: "Football practice", start: at(2, 17), end: at(2, 18, 30) },
|
||||
{
|
||||
summary: "Dinner with friends",
|
||||
start: at(3, 19),
|
||||
end: at(3, 22),
|
||||
status: "tentative",
|
||||
},
|
||||
{ summary: "Summer cabin", ...allDay(5, 3) },
|
||||
{ summary: "Parent-teacher meeting", start: at(9, 18), end: at(9, 19) },
|
||||
{ summary: "Football practice", start: at(9, 17), end: at(9, 18, 30) },
|
||||
{ summary: "Swimming lessons", start: at(12, 10), end: at(12, 11) },
|
||||
{ summary: "Car service", start: at(-3, 9), end: at(-3, 11) },
|
||||
{ summary: "Book club", start: at(-6, 19), end: at(-6, 21) },
|
||||
];
|
||||
|
||||
export const WORK_EVENTS: CalendarEventApiData[] = [
|
||||
{ summary: "Stand-up", start: at(0, 9), end: at(0, 9, 15) },
|
||||
{ summary: "Sprint planning", start: at(2, 10), end: at(2, 12) },
|
||||
{ summary: "Team lunch", start: at(4, 12), end: at(4, 13) },
|
||||
{ summary: "Conference", ...allDay(8, 2) },
|
||||
{ summary: "Quarterly review", start: at(-2, 14), end: at(-2, 15, 30) },
|
||||
];
|
||||
|
||||
const toTime = (value: CalendarEventApiData["start"]) =>
|
||||
new Date(
|
||||
typeof value === "string"
|
||||
? value
|
||||
: "dateTime" in value
|
||||
? value.dateTime
|
||||
: value.date
|
||||
).getTime();
|
||||
|
||||
const inRange = (
|
||||
events: CalendarEventApiData[],
|
||||
start: string | null,
|
||||
end: string | null
|
||||
): CalendarEventApiData[] => {
|
||||
const startTime = start ? new Date(start).getTime() : -Infinity;
|
||||
const endTime = end ? new Date(end).getTime() : Infinity;
|
||||
|
||||
return events.filter(
|
||||
(event) => toTime(event.end) > startTime && toTime(event.start) < endTime
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Answers event requests of calendar entities with the events of
|
||||
* `getEvents`. A calendar without events gets `null`, like a calendar whose
|
||||
* integration fails to return them.
|
||||
*/
|
||||
export const mockCalendarEvents = (
|
||||
hass: MockHomeAssistant,
|
||||
getEvents: (
|
||||
entityId: string,
|
||||
currentHass: MockHomeAssistant
|
||||
) => CalendarEventApiData[] | null | undefined
|
||||
) => {
|
||||
hass.mockWS("calendar/event/subscribe", (msg, currentHass, onChange) => {
|
||||
const events = getEvents(msg.entity_id, currentHass);
|
||||
onChange?.({ events: events ? inRange(events, msg.start, msg.end) : null });
|
||||
|
||||
return () => undefined;
|
||||
});
|
||||
// Home Assistant before 2026.5 has no event subscription, so cards that
|
||||
// support it ask the REST API instead.
|
||||
hass.mockAPI(/^calendars\/[^/?]+\?/, (currentHass, _method, path) => {
|
||||
const url = new URL(path, location.origin);
|
||||
const entityId = url.pathname.slice(url.pathname.lastIndexOf("/") + 1);
|
||||
const events = getEvents(entityId, currentHass);
|
||||
|
||||
if (!events) {
|
||||
return Promise.reject(new Error("Calendar not found"));
|
||||
}
|
||||
|
||||
return inRange(
|
||||
events,
|
||||
url.searchParams.get("start"),
|
||||
url.searchParams.get("end")
|
||||
);
|
||||
});
|
||||
};
|
||||
@@ -59,6 +59,10 @@ const REGISTRY_ENTRIES = [
|
||||
export const infraredFixtures: ConnectivityFixtures = {
|
||||
components: ["infrared"],
|
||||
manifests: [
|
||||
manifest("infrared", "Infrared", {
|
||||
config_flow: false,
|
||||
integration_type: "entity",
|
||||
}),
|
||||
manifest("broadlink", "Broadlink", {
|
||||
integration_type: "hub",
|
||||
iot_class: "local_polling",
|
||||
|
||||
@@ -42,7 +42,13 @@ const REGISTRY_ENTRIES = [
|
||||
export const radioFrequencyFixtures: ConnectivityFixtures = {
|
||||
components: ["radio_frequency"],
|
||||
commands: ["radio_frequency/"],
|
||||
manifests: [manifest("esphome", "ESPHome", { integration_type: "device" })],
|
||||
manifests: [
|
||||
manifest("radio_frequency", "Radio frequency", {
|
||||
config_flow: false,
|
||||
integration_type: "entity",
|
||||
}),
|
||||
manifest("esphome", "ESPHome", { integration_type: "device" }),
|
||||
],
|
||||
configEntries: [
|
||||
{ type: "device", entry: configEntry(ENTRY_ID, "esphome", "RF Bridge") },
|
||||
],
|
||||
|
||||
+20
-20
@@ -11,7 +11,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.solar_production",
|
||||
state: "88.6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Solar",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -20,7 +20,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.battery_input",
|
||||
state: "4",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Battery Input",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -29,7 +29,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.battery_output",
|
||||
state: "3",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Battery Output",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -38,7 +38,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_consumption_tarif_1",
|
||||
state: "88.6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Grid consumption low tariff",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -47,7 +47,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_consumption_tarif_2",
|
||||
state: "88.6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Grid consumption high tariff",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -56,7 +56,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_production_tarif_1",
|
||||
state: "88.6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Returned to grid low tariff",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -65,7 +65,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_production_tarif_2",
|
||||
state: "88.6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Returned to grid high tariff",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -74,7 +74,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_consumption_tarif_1_cost",
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
unit_of_measurement: "EUR",
|
||||
},
|
||||
},
|
||||
@@ -82,7 +82,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_consumption_tarif_2_cost",
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
unit_of_measurement: "EUR",
|
||||
},
|
||||
},
|
||||
@@ -90,7 +90,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_production_tarif_1_compensation",
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
unit_of_measurement: "EUR",
|
||||
},
|
||||
},
|
||||
@@ -98,7 +98,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_production_tarif_2_compensation",
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
unit_of_measurement: "EUR",
|
||||
},
|
||||
},
|
||||
@@ -138,7 +138,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_gas_cost",
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
unit_of_measurement: "EUR",
|
||||
},
|
||||
},
|
||||
@@ -146,7 +146,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_gas",
|
||||
state: "4",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Gas",
|
||||
unit_of_measurement: "m³",
|
||||
},
|
||||
@@ -155,7 +155,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_water",
|
||||
state: "4000",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Water",
|
||||
unit_of_measurement: "L",
|
||||
},
|
||||
@@ -164,7 +164,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_car",
|
||||
state: "4",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Electric car",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -173,7 +173,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_ac",
|
||||
state: "3",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Air conditioning",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -182,7 +182,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_washing_machine",
|
||||
state: "6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Washing machine",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -191,7 +191,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_dryer",
|
||||
state: "5.5",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Dryer",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -200,7 +200,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_heat_pump",
|
||||
state: "6",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Heat pump",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
@@ -209,7 +209,7 @@ export const energyEntities = () =>
|
||||
entity_id: "sensor.energy_boiler",
|
||||
state: "7",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
state_class: "total_increasing",
|
||||
friendly_name: "Boiler",
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
let entries: EntityRegistryEntry[] = [];
|
||||
|
||||
const newEntry = (
|
||||
export const newEntry = (
|
||||
entry: Pick<EntityRegistryEntry, "entity_id" | "platform" | "unique_id">
|
||||
): EntityRegistryEntry => {
|
||||
const now = Date.now() / 1000;
|
||||
@@ -43,7 +43,9 @@ const displayFields = (entry: EntityRegistryEntry) => ({
|
||||
hidden: entry.hidden_by !== null,
|
||||
});
|
||||
|
||||
const extEntry = (entry: EntityRegistryEntry): ExtEntityRegistryEntry => ({
|
||||
export const extEntry = (
|
||||
entry: EntityRegistryEntry
|
||||
): ExtEntityRegistryEntry => ({
|
||||
...entry,
|
||||
capabilities: {},
|
||||
aliases: [],
|
||||
@@ -56,6 +58,16 @@ export const mockEntityRegistry = (
|
||||
entries = [...data];
|
||||
// A new array, so subscribers see the registry changed after an update
|
||||
hass.mockWS("config/entity_registry/list", () => [...entries]);
|
||||
hass.mockWS(
|
||||
"config/entity_registry/get",
|
||||
(msg: { entity_id: string }): ExtEntityRegistryEntry => {
|
||||
const entry = entries.find((e) => e.entity_id === msg.entity_id);
|
||||
if (!entry) {
|
||||
throw new Error(`Entity not found: ${msg.entity_id}`);
|
||||
}
|
||||
return extEntry(entry);
|
||||
}
|
||||
);
|
||||
hass.mockWS(
|
||||
"config/entity_registry/get_entries",
|
||||
(msg: { entity_ids: string[] }) => {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { HassServiceTarget } from "home-assistant-js-websocket";
|
||||
import { ensureArray } from "../../../src/common/array/ensure-array";
|
||||
import type {
|
||||
TargetExplanation,
|
||||
HassServiceTargetWithExclude,
|
||||
TargetItem,
|
||||
TargetType,
|
||||
} from "../../../src/data/target";
|
||||
|
||||
const TYPES: TargetType[] = ["entity", "device", "area", "floor", "label"];
|
||||
|
||||
const items = (target?: HassServiceTarget): TargetItem[] =>
|
||||
TYPES.flatMap((type) => {
|
||||
const ids = target?.[`${type}_id`];
|
||||
return ids ? ensureArray(ids).map((id) => ({ type, id: String(id) })) : [];
|
||||
});
|
||||
|
||||
/** What one target item resolves to, and the areas and devices it reaches. */
|
||||
export interface ResolvedTargetItem {
|
||||
areas: string[];
|
||||
devices: string[];
|
||||
entities: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Like core's explain_target: resolves each item of the target and of its
|
||||
* `exclude` on its own with `resolve`, and tells what each exclude takes out
|
||||
* of each included item. Like core, `entity_id: all` is every entity in
|
||||
* `entityIds`, and excludes resolve every entity, not only the primary ones.
|
||||
*/
|
||||
export const explainTarget = (
|
||||
target: HassServiceTargetWithExclude,
|
||||
resolve: (
|
||||
target: HassServiceTarget,
|
||||
primaryEntitiesOnly: boolean
|
||||
) => ResolvedTargetItem,
|
||||
entityIds: string[],
|
||||
primaryEntitiesOnly = true
|
||||
): TargetExplanation => {
|
||||
const single = ({ type, id }: TargetItem): HassServiceTarget => ({
|
||||
[`${type}_id`]: [id],
|
||||
});
|
||||
const includes = items(target).map((item) => {
|
||||
if (item.type === "entity" && item.id === "all") {
|
||||
return {
|
||||
...item,
|
||||
entities: entityIds,
|
||||
referenced_areas: [],
|
||||
referenced_devices: [],
|
||||
};
|
||||
}
|
||||
const { areas, devices, entities } = resolve(
|
||||
single(item),
|
||||
primaryEntitiesOnly
|
||||
);
|
||||
return {
|
||||
...item,
|
||||
entities,
|
||||
referenced_areas: areas,
|
||||
referenced_devices: devices,
|
||||
};
|
||||
});
|
||||
return {
|
||||
includes,
|
||||
excludes: items(target.exclude).map((item) => {
|
||||
const excluded = new Set(resolve(single(item), false).entities);
|
||||
return {
|
||||
...item,
|
||||
removed: includes
|
||||
.map(({ type, id, entities }) => ({
|
||||
type,
|
||||
id,
|
||||
entities: entities.filter((entityId) => excluded.has(entityId)),
|
||||
}))
|
||||
.filter((include) => include.entities.length > 0),
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { LogbookStreamMessage } from "../../../src/data/logbook";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
/**
|
||||
* Answers logbook subscriptions with an empty logbook. No entries come from
|
||||
* an automation or script trace.
|
||||
*/
|
||||
export const mockLogbook = (hass: MockHomeAssistant) => {
|
||||
hass.mockWS("logbook/event_stream", (_msg, _currentHass, onChange) => {
|
||||
onChange?.({ events: [] } satisfies LogbookStreamMessage);
|
||||
|
||||
return () => undefined;
|
||||
});
|
||||
hass.mockWS("trace/contexts", () => ({}));
|
||||
};
|
||||
@@ -149,6 +149,7 @@ const repositories: RepositoryBase[] = [
|
||||
const repositoryInfo = (repository: RepositoryBase): RepositoryInfo => ({
|
||||
...repository,
|
||||
additional_info: `# ${repository.name}\n\n${repository.description}\n\nThis is a demo. Installing is not available.`,
|
||||
beta: false,
|
||||
default_branch: "main",
|
||||
issues: 12,
|
||||
releases: [repository.available_version],
|
||||
|
||||
@@ -372,7 +372,9 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
const entityState = hass.states[id];
|
||||
const state = entityState ? Number(entityState.state) : 1;
|
||||
statistics[id] =
|
||||
entityState && "last_reset" in entityState.attributes
|
||||
entityState &&
|
||||
(entityState.attributes.state_class === "total" ||
|
||||
entityState.attributes.state_class === "total_increasing")
|
||||
? generateSumStatistics(
|
||||
start,
|
||||
end,
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { HassServiceTarget } from "home-assistant-js-websocket";
|
||||
import { ensureArray } from "../../../src/common/array/ensure-array";
|
||||
import type { ExtractFromTargetResult } from "../../../src/data/target";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import { getLabelIds } from "./label_registry";
|
||||
|
||||
// Expands a target to its areas, devices and entities, like core does
|
||||
export const expandTarget = (
|
||||
hass: MockHomeAssistant,
|
||||
target: HassServiceTarget,
|
||||
primaryEntitiesOnly = true
|
||||
) => {
|
||||
const missing = {
|
||||
floors: [] as string[],
|
||||
areas: [] as string[],
|
||||
devices: [] as string[],
|
||||
labels: [] as string[],
|
||||
};
|
||||
const knownLabelIds = getLabelIds();
|
||||
const floorIds = ensureArray(target.floor_id ?? []);
|
||||
const labelIds = ensureArray(target.label_id ?? []);
|
||||
missing.floors.push(...floorIds.filter((id) => !(id in hass.floors)));
|
||||
// Like core, unknown labels are reported, but still expanded
|
||||
missing.labels.push(...labelIds.filter((id) => !knownLabelIds.includes(id)));
|
||||
const hasLabel = (labels?: string[]) =>
|
||||
labelIds.some((labelId) => labels?.includes(labelId));
|
||||
|
||||
// Unknown areas and devices are reported, but still referenced
|
||||
const areaIds = new Set(ensureArray(target.area_id ?? []));
|
||||
missing.areas.push(...[...areaIds].filter((id) => !(id in hass.areas)));
|
||||
for (const area of Object.values(hass.areas)) {
|
||||
if (
|
||||
(area.floor_id && floorIds.includes(area.floor_id)) ||
|
||||
hasLabel(area.labels)
|
||||
) {
|
||||
areaIds.add(area.area_id);
|
||||
}
|
||||
}
|
||||
|
||||
// A targeted or labeled device includes its child devices
|
||||
const deviceIds = new Set<string>();
|
||||
const addDevice = (deviceId: string) => {
|
||||
deviceIds.add(deviceId);
|
||||
for (const device of Object.values(hass.devices)) {
|
||||
if (device.parent_device_id === deviceId) {
|
||||
deviceIds.add(device.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const deviceId of ensureArray(target.device_id ?? [])) {
|
||||
if (!(deviceId in hass.devices)) {
|
||||
missing.devices.push(deviceId);
|
||||
}
|
||||
addDevice(deviceId);
|
||||
}
|
||||
for (const device of Object.values(hass.devices)) {
|
||||
if (hasLabel(device.labels)) {
|
||||
addDevice(device.id);
|
||||
}
|
||||
}
|
||||
|
||||
// A child device without its own area is in the area of its parent device
|
||||
const deviceArea = (deviceId: string) => {
|
||||
const device = hass.devices[deviceId];
|
||||
return (
|
||||
device?.area_id ??
|
||||
(device?.parent_device_id
|
||||
? hass.devices[device.parent_device_id]?.area_id
|
||||
: undefined)
|
||||
);
|
||||
};
|
||||
const areaDeviceIds = new Set<string>();
|
||||
for (const device of Object.values(hass.devices)) {
|
||||
const areaId = deviceArea(device.id);
|
||||
if (areaId && areaIds.has(areaId)) {
|
||||
areaDeviceIds.add(device.id);
|
||||
}
|
||||
}
|
||||
|
||||
const entityIds = new Set(ensureArray(target.entity_id ?? []));
|
||||
for (const entity of Object.values(hass.entities)) {
|
||||
// The display registry keeps the entities of a previous demo, and like
|
||||
// core, hidden entities are never included indirectly
|
||||
if (!(entity.entity_id in hass.states) || entity.hidden) {
|
||||
continue;
|
||||
}
|
||||
const primary = !primaryEntitiesOnly || !entity.entity_category;
|
||||
if (
|
||||
hasLabel(entity.labels) ||
|
||||
(primary &&
|
||||
((entity.device_id && deviceIds.has(entity.device_id)) ||
|
||||
(entity.area_id && areaIds.has(entity.area_id)) ||
|
||||
// An entity with its own area is not in the area of its device
|
||||
(!entity.area_id &&
|
||||
entity.device_id &&
|
||||
areaDeviceIds.has(entity.device_id))))
|
||||
) {
|
||||
entityIds.add(entity.entity_id);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
areas: [...areaIds],
|
||||
devices: [...new Set([...deviceIds, ...areaDeviceIds])],
|
||||
entities: [...entityIds],
|
||||
missing,
|
||||
};
|
||||
};
|
||||
|
||||
export const mockExtractFromTarget = (hass: MockHomeAssistant) =>
|
||||
hass.mockWS(
|
||||
"extract_from_target",
|
||||
(
|
||||
msg: { target: HassServiceTarget; primary_entities_only?: boolean },
|
||||
currentHass: MockHomeAssistant
|
||||
): ExtractFromTargetResult => {
|
||||
const { areas, devices, entities, missing } = expandTarget(
|
||||
currentHass,
|
||||
msg.target,
|
||||
msg.primary_entities_only ?? true
|
||||
);
|
||||
return {
|
||||
missing_areas: missing.areas,
|
||||
missing_devices: missing.devices,
|
||||
missing_floors: missing.floors,
|
||||
missing_labels: missing.labels,
|
||||
referenced_areas: areas,
|
||||
referenced_devices: devices,
|
||||
referenced_entities: entities,
|
||||
};
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,133 @@
|
||||
import type {
|
||||
ForecastAttribute,
|
||||
ModernForecastType,
|
||||
} from "../../../src/data/weather";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
const HOUR = 3600000;
|
||||
|
||||
const CONDITIONS = [
|
||||
"partlycloudy",
|
||||
"rainy",
|
||||
"cloudy",
|
||||
"sunny",
|
||||
"pouring",
|
||||
"partlycloudy",
|
||||
"sunny",
|
||||
];
|
||||
|
||||
// Daily changes around the current temperature, so the forecast looks real.
|
||||
const TEMPERATURE_CHANGES = [0, -1.5, -3, -1, 1.5, 2.5, 1];
|
||||
|
||||
const PRECIPITATION = new Map([
|
||||
["rainy", 2.4],
|
||||
["pouring", 9.1],
|
||||
]);
|
||||
|
||||
const forecastEntry = (
|
||||
datetime: Date,
|
||||
temperature: number,
|
||||
condition: string
|
||||
): ForecastAttribute => ({
|
||||
datetime: datetime.toISOString(),
|
||||
condition,
|
||||
temperature: Math.round(temperature * 10) / 10,
|
||||
precipitation: PRECIPITATION.get(condition) ?? 0,
|
||||
precipitation_probability: PRECIPITATION.has(condition) ? 80 : 10,
|
||||
});
|
||||
|
||||
const generateForecast = (
|
||||
forecastType: ModernForecastType,
|
||||
temperature: number,
|
||||
condition: string
|
||||
): ForecastAttribute[] => {
|
||||
const conditions = [condition, ...CONDITIONS.slice(1)];
|
||||
const now = new Date();
|
||||
|
||||
if (forecastType === "hourly") {
|
||||
now.setMinutes(0, 0, 0);
|
||||
|
||||
return Array.from({ length: 24 }, (_, hour) => {
|
||||
const datetime = new Date(now.getTime() + (hour + 1) * HOUR);
|
||||
|
||||
// Warmest mid-afternoon and coldest before dawn
|
||||
const change =
|
||||
3 * Math.sin(((datetime.getHours() - 9) / 24) * 2 * Math.PI) -
|
||||
3 * Math.sin(((now.getHours() - 9) / 24) * 2 * Math.PI);
|
||||
|
||||
return forecastEntry(
|
||||
datetime,
|
||||
temperature + change,
|
||||
conditions[Math.floor(hour / 6)]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
now.setHours(12, 0, 0, 0);
|
||||
|
||||
if (forecastType === "twice_daily") {
|
||||
return conditions.flatMap((dayCondition, day) => {
|
||||
const datetime = new Date(now.getTime() + day * 24 * HOUR);
|
||||
const dayTemperature = temperature + TEMPERATURE_CHANGES[day];
|
||||
|
||||
return [
|
||||
{
|
||||
...forecastEntry(datetime, dayTemperature, dayCondition),
|
||||
is_daytime: true,
|
||||
},
|
||||
{
|
||||
...forecastEntry(
|
||||
new Date(datetime.getTime() + 12 * HOUR),
|
||||
dayTemperature - 6,
|
||||
dayCondition
|
||||
),
|
||||
is_daytime: false,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
return conditions.map((dayCondition, day) => {
|
||||
const dayTemperature = temperature + TEMPERATURE_CHANGES[day];
|
||||
|
||||
return {
|
||||
...forecastEntry(
|
||||
new Date(now.getTime() + day * 24 * HOUR),
|
||||
dayTemperature,
|
||||
dayCondition
|
||||
),
|
||||
templow: Math.round((dayTemperature - 6) * 10) / 10,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Answers forecast subscriptions of weather entities. An entity with a
|
||||
* `forecast` attribute gets that forecast. Other entities get a forecast made
|
||||
* up from their condition and temperature.
|
||||
*/
|
||||
export const mockWeather = (hass: MockHomeAssistant) => {
|
||||
hass.mockWS(
|
||||
"weather/subscribe_forecast",
|
||||
(
|
||||
msg: { entity_id: string; forecast_type: ModernForecastType },
|
||||
currentHass,
|
||||
onChange
|
||||
) => {
|
||||
const stateObj = currentHass.states[msg.entity_id];
|
||||
onChange?.({
|
||||
type: msg.forecast_type,
|
||||
forecast: stateObj
|
||||
? (stateObj.attributes.forecast ??
|
||||
generateForecast(
|
||||
msg.forecast_type,
|
||||
Number(stateObj.attributes.temperature ?? 15),
|
||||
stateObj.state
|
||||
))
|
||||
: null,
|
||||
});
|
||||
|
||||
return () => undefined;
|
||||
}
|
||||
);
|
||||
};
|
||||
@@ -1,68 +1,14 @@
|
||||
import {
|
||||
FAMILY_EVENTS,
|
||||
mockCalendarEvents,
|
||||
WORK_EVENTS,
|
||||
} from "../../../demo/src/stubs/calendar";
|
||||
import { mockEntityRegistry } from "../../../demo/src/stubs/entity_registry";
|
||||
import type { CalendarEventApiData } from "../../../src/data/calendar";
|
||||
import { CalendarEntityFeature } from "../../../src/data/calendar";
|
||||
import type { EntityRegistryEntry } from "../../../src/data/entity/entity_registry";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
// Sample calendars with events relative to today, so demos always show
|
||||
// something in the current week and month.
|
||||
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
|
||||
const day = (offset: number): Date => {
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
date.setDate(date.getDate() + offset);
|
||||
return date;
|
||||
};
|
||||
|
||||
const isoDate = (date: Date) =>
|
||||
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
|
||||
const at = (offset: number, hours: number, minutes = 0) => {
|
||||
const date = day(offset);
|
||||
date.setHours(hours, minutes);
|
||||
return date.toISOString();
|
||||
};
|
||||
|
||||
const allDay = (offset: number, days = 1) => ({
|
||||
start: isoDate(day(offset)),
|
||||
end: isoDate(day(offset + days)),
|
||||
all_day: true,
|
||||
});
|
||||
|
||||
const FAMILY_EVENTS: CalendarEventApiData[] = [
|
||||
{ summary: "School run", start: at(0, 8), end: at(0, 8, 30) },
|
||||
{
|
||||
summary: "Dentist",
|
||||
start: at(0, 15, 30),
|
||||
end: at(0, 16, 15),
|
||||
location: "Main Street 12",
|
||||
},
|
||||
{ summary: "Grandma's birthday", ...allDay(1) },
|
||||
{ summary: "Football practice", start: at(2, 17), end: at(2, 18, 30) },
|
||||
{
|
||||
summary: "Dinner with friends",
|
||||
start: at(3, 19),
|
||||
end: at(3, 22),
|
||||
status: "tentative",
|
||||
},
|
||||
{ summary: "Summer cabin", ...allDay(5, 3) },
|
||||
{ summary: "Parent-teacher meeting", start: at(9, 18), end: at(9, 19) },
|
||||
{ summary: "Football practice", start: at(9, 17), end: at(9, 18, 30) },
|
||||
{ summary: "Swimming lessons", start: at(12, 10), end: at(12, 11) },
|
||||
{ summary: "Car service", start: at(-3, 9), end: at(-3, 11) },
|
||||
{ summary: "Book club", start: at(-6, 19), end: at(-6, 21) },
|
||||
];
|
||||
|
||||
const WORK_EVENTS: CalendarEventApiData[] = [
|
||||
{ summary: "Stand-up", start: at(0, 9), end: at(0, 9, 15) },
|
||||
{ summary: "Sprint planning", start: at(2, 10), end: at(2, 12) },
|
||||
{ summary: "Team lunch", start: at(4, 12), end: at(4, 13) },
|
||||
{ summary: "Conference", ...allDay(8, 2) },
|
||||
{ summary: "Quarterly review", start: at(-2, 14), end: at(-2, 15, 30) },
|
||||
];
|
||||
|
||||
const EVENTS: Record<string, CalendarEventApiData[] | null> = {
|
||||
"calendar.family": FAMILY_EVENTS,
|
||||
"calendar.work": WORK_EVENTS,
|
||||
@@ -79,8 +25,8 @@ export const CALENDAR_ENTITIES = [
|
||||
friendly_name: "Family",
|
||||
message: "School run",
|
||||
all_day: false,
|
||||
start_time: at(0, 8),
|
||||
end_time: at(0, 8, 30),
|
||||
start_time: FAMILY_EVENTS[0].start,
|
||||
end_time: FAMILY_EVENTS[0].end,
|
||||
location: "",
|
||||
description: "",
|
||||
supported_features:
|
||||
@@ -96,8 +42,8 @@ export const CALENDAR_ENTITIES = [
|
||||
friendly_name: "Work",
|
||||
message: "Stand-up",
|
||||
all_day: false,
|
||||
start_time: at(0, 9),
|
||||
end_time: at(0, 9, 15),
|
||||
start_time: WORK_EVENTS[0].start,
|
||||
end_time: WORK_EVENTS[0].end,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -145,20 +91,7 @@ export const mockCalendars = (hass: MockHomeAssistant) => {
|
||||
registryEntry("calendar.empty"),
|
||||
registryEntry("calendar.holidays"),
|
||||
]);
|
||||
hass.mockWS("calendar/event/subscribe", (msg, _hass, onChange) => {
|
||||
const start = new Date(msg.start).getTime();
|
||||
const end = new Date(msg.end).getTime();
|
||||
const events = EVENTS[msg.entity_id];
|
||||
onChange?.({
|
||||
events:
|
||||
events?.filter(
|
||||
(event) =>
|
||||
new Date(event.end as string).getTime() > start &&
|
||||
new Date(event.start as string).getTime() < end
|
||||
) ?? null,
|
||||
});
|
||||
return () => undefined;
|
||||
});
|
||||
mockCalendarEvents(hass, (entityId) => EVENTS[entityId]);
|
||||
// Changes made in the event dialogs are accepted but not stored
|
||||
hass.mockWS("calendar/event/create", () => null);
|
||||
hass.mockWS("calendar/event/update", () => null);
|
||||
|
||||
@@ -48,6 +48,36 @@ export const createMediaPlayerEntities = () => [
|
||||
group_members: ["media_player.playing", "media_player.stream_playing"],
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "media_player.music_all_features",
|
||||
state: "playing",
|
||||
attributes: {
|
||||
friendly_name: "Playing The Music (all features)",
|
||||
media_content_type: "music",
|
||||
media_title: "I Wanna Be A Hippy (Flamman & Abraxas Radio Mix)",
|
||||
media_artist: "Technohead",
|
||||
// Pause + Seek + Volume Set + Volume Mute + Previous Track + Next Track + On + Off +
|
||||
// Play Media + Volume Step + Select Source + Stop + Clear + Play + Shuffle Set +
|
||||
// Sound Mode + Browse Media + Repeat Set + Grouping
|
||||
supported_features: 1048511,
|
||||
entity_picture: "/images/album_cover.jpg",
|
||||
media_duration: 300,
|
||||
media_position: 0,
|
||||
media_position_updated_at: new Date(
|
||||
// 23 seconds in
|
||||
new Date().getTime() - 23000
|
||||
).toISOString(),
|
||||
volume_level: 0.5,
|
||||
is_volume_muted: false,
|
||||
shuffle: false,
|
||||
repeat: "off",
|
||||
source_list: ["AirPlay", "Blu-Ray", "TV", "USB", "iPod (USB)"],
|
||||
source: "AirPlay",
|
||||
sound_mode_list: ["Movie", "Music", "Game", "Pure Audio"],
|
||||
sound_mode: "Music",
|
||||
group_members: ["media_player.playing", "media_player.stream_playing"],
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "media_player.stream_playing",
|
||||
state: "playing",
|
||||
|
||||
@@ -50,6 +50,18 @@ With no cursor yet, <kbd>↓</kbd> and <kbd>Enter</kbd> start from the `value`
|
||||
row, or from the top match while searching. With one item in the list,
|
||||
<kbd>Enter</kbd> picks it whether or not the cursor has moved.
|
||||
|
||||
## Screen readers
|
||||
|
||||
DOM focus stays in the search field, so screen readers do not hear the list
|
||||
change. While searching, a visually hidden `role="status"` message says how
|
||||
many items match the search and names it, so a new search with the same count
|
||||
is still read out. It is cleared as soon as the list changes and filled in once
|
||||
typing pauses for half a second, so it doesn't talk over each typed character
|
||||
or describe the previous search. When nothing matches, it reads a not
|
||||
found label that takes the search, or says there are no results for it. Section
|
||||
titles, placeholder rows, "Add custom item", the additional items and rows that
|
||||
`isSearchResult` rejects are not counted.
|
||||
|
||||
## Implementation
|
||||
|
||||
Without `sections`, the component filters the items from `getItems` itself as the
|
||||
@@ -79,6 +91,7 @@ means supplying one.
|
||||
| allowCustomValue | Boolean | false | Offers the typed string as an item. |
|
||||
| customValueLabel | String | - | Label for that custom item. |
|
||||
| notFoundLabel | String/Function | - | Shown when a search matches nothing. |
|
||||
| isSearchResult | Function | - | Whether a row from `getItems` counts as a match for screen readers. The quick bar leaves out its "Ask Assist" row. |
|
||||
| emptyLabel | String | - | Shown when there are no items at all. |
|
||||
| noSort | Boolean | false | Keeps the order `getItems` returned. |
|
||||
| clearable | Boolean | false | Adjusts search field padding for a clear affordance. |
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { ContextProvider } from "@lit/context";
|
||||
import { IntlMessageFormat } from "intl-messageformat";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import type { LocalizeFunc } from "../../../../src/common/translations/localize";
|
||||
import "../../../../src/components/ha-card";
|
||||
import "../../../../src/components/ha-picker-combo-box";
|
||||
import type { PickerComboBoxItem } from "../../../../src/components/ha-picker-combo-box";
|
||||
@@ -19,13 +21,26 @@ import type {
|
||||
} from "../../../../src/types";
|
||||
import { THEME_COMPARISON_PANELS } from "../../components/demo-theme-comparison";
|
||||
|
||||
// The English strings, plurals included, so searching a demo announces the
|
||||
// same count and search as the real picker.
|
||||
const LOCALIZE_KEYS: Record<string, string> = {
|
||||
"ui.common.search": "Search",
|
||||
"ui.components.combo-box.no_match": "No matching items found",
|
||||
"ui.components.combo-box.no_items": "No items available",
|
||||
"ui.components.combo-box.result_count":
|
||||
"{count} {count, plural,\n one {result}\n other {results}\n} for {term}",
|
||||
"ui.components.combo-box.no_results": "No results for {term}",
|
||||
};
|
||||
|
||||
const localize = (key: string) => LOCALIZE_KEYS[key] ?? key;
|
||||
const localize: LocalizeFunc = (key, values) => {
|
||||
const message = LOCALIZE_KEYS[key];
|
||||
if (message === undefined) {
|
||||
return key;
|
||||
}
|
||||
return new IntlMessageFormat(message, "en").format<string>(
|
||||
values as Record<string, string | number>
|
||||
) as string;
|
||||
};
|
||||
|
||||
const DEMO_I18N: HomeAssistantInternationalization = {
|
||||
localize,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { customElement, state } from "lit/decorators";
|
||||
import { mockConfigEntries } from "../../../../demo/src/stubs/config_entries";
|
||||
import { mockDeviceRegistry } from "../../../../demo/src/stubs/device_registry";
|
||||
import { mockEntityRegistry } from "../../../../demo/src/stubs/entity_registry";
|
||||
import { explainTarget } from "../../../../demo/src/stubs/explain_target";
|
||||
import { mockHassioSupervisor } from "../../../../demo/src/stubs/hassio_supervisor";
|
||||
import { ensureArray } from "../../../../src/common/array/ensure-array";
|
||||
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
|
||||
@@ -225,6 +226,20 @@ class DemoHaTargetPickerExclusions
|
||||
hass.updateHass({ areas, entities: ENTITY_REGISTRY });
|
||||
hass.mockWS("config/device_registry/list_composite_splits", () => ({}));
|
||||
hass.mockWS("extract_from_target", extractFromTarget);
|
||||
hass.mockWS("explain_target", ({ target }: { target: HassServiceTarget }) =>
|
||||
explainTarget(
|
||||
target,
|
||||
(single) => {
|
||||
const resolved = extractFromTarget({ target: single });
|
||||
return {
|
||||
areas: resolved.referenced_areas,
|
||||
devices: resolved.referenced_devices,
|
||||
entities: resolved.referenced_entities,
|
||||
};
|
||||
},
|
||||
Object.keys(hass.states)
|
||||
)
|
||||
);
|
||||
hass.mockWS("auth/sign_path", (params) => params);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,13 @@ const CONFIGS = [
|
||||
entity: "media_player.music_playing",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Playing Music (all features)",
|
||||
config: {
|
||||
type: "media-control",
|
||||
entity: "media_player.music_all_features",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Playing Stream",
|
||||
config: {
|
||||
|
||||
@@ -201,6 +201,50 @@ const ENTITIES = [
|
||||
supported_features: FanEntityFeature.SET_SPEED,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "fan.on_off_fan",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Bathroom fan",
|
||||
device_class: "fan",
|
||||
percentage: 100,
|
||||
percentage_step: 100,
|
||||
supported_features: FanEntityFeature.SET_SPEED,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "fan.six_speed_fan",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Kitchen fan",
|
||||
device_class: "fan",
|
||||
percentage: 50,
|
||||
percentage_step: 100 / 6,
|
||||
supported_features: FanEntityFeature.SET_SPEED,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "fan.ten_speed_fan",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Living room fan",
|
||||
device_class: "fan",
|
||||
percentage: 70,
|
||||
percentage_step: 10,
|
||||
supported_features: FanEntityFeature.SET_SPEED,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "fan.eleven_speed_fan",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Office fan",
|
||||
device_class: "fan",
|
||||
percentage: 45,
|
||||
percentage_step: 100 / 11,
|
||||
supported_features: FanEntityFeature.SET_SPEED,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const CONFIGS = [
|
||||
@@ -410,6 +454,55 @@ const CONFIGS = [
|
||||
features: [{ type: "fan-speed" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan speed feature (5 speeds, slider style)",
|
||||
config: {
|
||||
type: "tile",
|
||||
entity: "fan.five_speed_fan",
|
||||
features: [{ type: "fan-speed", style: "slider" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan speed feature (off/on, slider style falls back to buttons)",
|
||||
config: {
|
||||
type: "tile",
|
||||
entity: "fan.on_off_fan",
|
||||
features: [{ type: "fan-speed", style: "slider" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan speed feature (6 speeds, slider by default)",
|
||||
config: {
|
||||
type: "tile",
|
||||
entity: "fan.six_speed_fan",
|
||||
features: [{ type: "fan-speed" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan speed feature (6 speeds, buttons style)",
|
||||
config: {
|
||||
type: "tile",
|
||||
entity: "fan.six_speed_fan",
|
||||
features: [{ type: "fan-speed", style: "buttons" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan speed feature (10 speeds, buttons style)",
|
||||
config: {
|
||||
type: "tile",
|
||||
entity: "fan.ten_speed_fan",
|
||||
features: [{ type: "fan-speed", style: "buttons" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading:
|
||||
"Fan speed feature (11 speeds, buttons style falls back to slider)",
|
||||
config: {
|
||||
type: "tile",
|
||||
entity: "fan.eleven_speed_fan",
|
||||
features: [{ type: "fan-speed", style: "buttons" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan speed feature (half width)",
|
||||
config: {
|
||||
@@ -430,6 +523,27 @@ const CONFIGS = [
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading:
|
||||
"Fan speed feature (half width, buttons fall back to a slider when they do not fit)",
|
||||
config: {
|
||||
type: "grid",
|
||||
columns: 2,
|
||||
square: false,
|
||||
cards: [
|
||||
{
|
||||
type: "tile",
|
||||
entity: "fan.six_speed_fan",
|
||||
features: [{ type: "fan-speed", style: "buttons" }],
|
||||
},
|
||||
{
|
||||
type: "tile",
|
||||
entity: "fan.ten_speed_fan",
|
||||
features: [{ type: "fan-speed", style: "buttons" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Fan oscillate feature",
|
||||
config: {
|
||||
|
||||
+27
-27
@@ -40,7 +40,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.0.8",
|
||||
"@babel/runtime": "8.0.10",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
@@ -54,17 +54,17 @@
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "7.8.2",
|
||||
"@formatjs/intl-displaynames": "7.3.15",
|
||||
"@formatjs/intl-durationformat": "0.11.1",
|
||||
"@formatjs/intl-getcanonicallocales": "3.2.12",
|
||||
"@formatjs/intl-listformat": "8.3.15",
|
||||
"@formatjs/intl-locale": "5.3.12",
|
||||
"@formatjs/intl-numberformat": "9.4.3",
|
||||
"@formatjs/intl-pluralrules": "6.3.16",
|
||||
"@formatjs/intl-relativetimeformat": "12.3.16",
|
||||
"@formatjs/intl-datetimeformat": "8.0.1",
|
||||
"@formatjs/intl-displaynames": "8.0.1",
|
||||
"@formatjs/intl-durationformat": "0.12.2",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.0",
|
||||
"@formatjs/intl-listformat": "9.0.1",
|
||||
"@formatjs/intl-locale": "5.4.2",
|
||||
"@formatjs/intl-numberformat": "10.0.1",
|
||||
"@formatjs/intl-pluralrules": "7.0.1",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.1",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.4",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lit-labs/motion": "1.1.0",
|
||||
"@lit-labs/observers": "2.1.0",
|
||||
@@ -78,11 +78,11 @@
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
"@swc/helpers": "0.5.23",
|
||||
"@tsparticles/engine": "4.4.0",
|
||||
"@tsparticles/preset-links": "4.4.0",
|
||||
"@versatiles/style": "7.0.1",
|
||||
"@tsparticles/engine": "4.5.0",
|
||||
"@tsparticles/preset-links": "4.5.0",
|
||||
"@versatiles/style": "7.1.0",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.201.1",
|
||||
"@vvo/tzdb": "6.202.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
"barcode-detector": "3.2.3",
|
||||
"cally": "0.9.2",
|
||||
@@ -100,8 +100,8 @@
|
||||
"element-internals-polyfill": "3.0.2",
|
||||
"fullcalendar": "7.1.3",
|
||||
"fuse.js": "7.5.0",
|
||||
"hls.js": "1.7.3",
|
||||
"home-assistant-js-websocket": "9.8.0",
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.8.1",
|
||||
"idb-keyval": "6.3.0",
|
||||
"intl-messageformat": "12.1.4",
|
||||
"js-yaml": "5.5.0",
|
||||
@@ -110,7 +110,7 @@
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.16.0",
|
||||
"marked": "18.1.1",
|
||||
"marked": "18.1.2",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
@@ -137,7 +137,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.0.9",
|
||||
"@babel/core": "8.0.10",
|
||||
"@babel/helper-compilation-targets": "8.0.7",
|
||||
"@babel/helper-define-polyfill-provider": "1.0.0",
|
||||
"@babel/plugin-transform-class-properties": "8.0.1",
|
||||
@@ -153,8 +153,8 @@
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.64.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.2.9",
|
||||
"@rspack/dev-server": "2.2.1",
|
||||
"@rspack/core": "2.3.0",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
"@types/chromecast-caf-sender": "1.0.11",
|
||||
@@ -173,11 +173,11 @@
|
||||
"@vitest/coverage-v8": "5.0.5",
|
||||
"babel-loader": "10.1.1",
|
||||
"babel-plugin-polyfill-corejs3": "1.0.0",
|
||||
"browserslist": "4.29.4",
|
||||
"browserslist": "4.29.5",
|
||||
"browserslist-useragent-regexp": "4.1.4",
|
||||
"core-js-compat": "3.51.0",
|
||||
"del": "9.0.1",
|
||||
"eslint": "10.13.0",
|
||||
"eslint": "10.14.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.17.1",
|
||||
@@ -188,7 +188,7 @@
|
||||
"fancy-log": "2.0.0",
|
||||
"fs-extra": "11.4.1",
|
||||
"generate-license-file": "4.2.5",
|
||||
"glob": "13.0.6",
|
||||
"glob": "14.0.3",
|
||||
"globals": "17.13.0",
|
||||
"gulp": "5.0.1",
|
||||
"gulp-json-transform": "0.5.0",
|
||||
@@ -214,7 +214,7 @@
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.72.0",
|
||||
"typescript-eslint": "8.72.1",
|
||||
"vite": "8.3.5",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.0.5",
|
||||
@@ -222,8 +222,8 @@
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "[email protected]5.0",
|
||||
"packageManager": "[email protected]6.1",
|
||||
"volta": {
|
||||
"node": "24.22.1"
|
||||
"node": "24.22.2"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
diff --git a/modular/sortable.core.esm.js b/modular/sortable.core.esm.js
|
||||
index 8b5e49b011713c8859c669069fbe85ce53974e1d..6a0afc92787157b8a31c38cc5f67dfa526090a00 100644
|
||||
index cb433ff25353f4836d2ffc813356f945f42acc6b..0a86ad22d05390a5b9ef002905fcd5926852b956 100644
|
||||
--- a/modular/sortable.core.esm.js
|
||||
+++ b/modular/sortable.core.esm.js
|
||||
@@ -1781,11 +1781,16 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
@@ -1777,11 +1777,16 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
}
|
||||
if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
|
||||
capture();
|
||||
@@ -24,7 +24,7 @@ index 8b5e49b011713c8859c669069fbe85ce53974e1d..6a0afc92787157b8a31c38cc5f67dfa5
|
||||
}
|
||||
parentEl = el; // actualization
|
||||
|
||||
@@ -1802,7 +1807,12 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
@@ -1798,7 +1803,12 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
targetRect = getRect(target);
|
||||
if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {
|
||||
capture();
|
||||
@@ -38,7 +38,16 @@ index 8b5e49b011713c8859c669069fbe85ce53974e1d..6a0afc92787157b8a31c38cc5f67dfa5
|
||||
parentEl = el; // actualization
|
||||
|
||||
changed();
|
||||
@@ -1849,10 +1859,15 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
@@ -1818,7 +1828,7 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
pastFirstInvertThresh = false;
|
||||
isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;
|
||||
}
|
||||
- direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);
|
||||
+ direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target, _isRtl(el, vertical));
|
||||
var sibling;
|
||||
if (direction !== 0) {
|
||||
// Check if target is beside dragEl in respective direction (ignoring hidden elements)
|
||||
@@ -1845,10 +1855,15 @@ Sortable.prototype = /** @lends Sortable.prototype */{
|
||||
_silent = true;
|
||||
setTimeout(_unsilent, 30);
|
||||
capture();
|
||||
@@ -58,3 +67,53 @@ index 8b5e49b011713c8859c669069fbe85ce53974e1d..6a0afc92787157b8a31c38cc5f67dfa5
|
||||
}
|
||||
|
||||
// Undo chrome's scroll adjustment (has no effect on other browsers)
|
||||
@@ -2242,19 +2257,48 @@ function _disableDraggable(el) {
|
||||
function _unsilent() {
|
||||
_silent = false;
|
||||
}
|
||||
+// Horizontal RTL lists run from right to left. Mirroring the x axis lets the
|
||||
+// checks below keep assuming that the list runs from left to right.
|
||||
+function _isRtl(el, vertical) {
|
||||
+ return !vertical && css(el, 'direction') === 'rtl';
|
||||
+}
|
||||
+function _mirrorX(rect) {
|
||||
+ return {
|
||||
+ left: -rect.right,
|
||||
+ right: -rect.left,
|
||||
+ top: rect.top,
|
||||
+ bottom: rect.bottom,
|
||||
+ width: rect.width,
|
||||
+ height: rect.height
|
||||
+ };
|
||||
+}
|
||||
function _ghostIsFirst(evt, vertical, sortable) {
|
||||
var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));
|
||||
var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);
|
||||
+ if (_isRtl(sortable.el, vertical)) {
|
||||
+ evt = { clientX: -evt.clientX, clientY: evt.clientY };
|
||||
+ firstElRect = _mirrorX(firstElRect);
|
||||
+ childContainingRect = _mirrorX(childContainingRect);
|
||||
+ }
|
||||
var spacer = 10;
|
||||
return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;
|
||||
}
|
||||
function _ghostIsLast(evt, vertical, sortable) {
|
||||
var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));
|
||||
var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);
|
||||
+ if (_isRtl(sortable.el, vertical)) {
|
||||
+ evt = { clientX: -evt.clientX, clientY: evt.clientY };
|
||||
+ lastElRect = _mirrorX(lastElRect);
|
||||
+ childContainingRect = _mirrorX(childContainingRect);
|
||||
+ }
|
||||
var spacer = 10;
|
||||
return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;
|
||||
}
|
||||
-function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
|
||||
+function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget, rtl) {
|
||||
+ if (rtl) {
|
||||
+ evt = { clientX: -evt.clientX, clientY: evt.clientY };
|
||||
+ targetRect = _mirrorX(targetRect);
|
||||
+ }
|
||||
var mouseOnAxis = vertical ? evt.clientY : evt.clientX,
|
||||
targetLength = vertical ? targetRect.height : targetRect.width,
|
||||
targetS1 = vertical ? targetRect.top : targetRect.left,
|
||||
Generated
+972
-939
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -26,7 +26,7 @@ overrides:
|
||||
lit-html: 3.3.3
|
||||
clean-css: 5.3.3
|
||||
"@lit/reactive-element": 2.1.2
|
||||
tslib: 2.8.1
|
||||
tslib: 2.9.1
|
||||
|
||||
patchedDependencies:
|
||||
"@material/[email protected]": patches/@[email protected]
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<svg width="94" height="28" viewBox="0 0 94 28" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="94" height="28" rx="8" fill="white"/>
|
||||
<rect x="0.5" y="0.5" width="93" height="27" rx="7.5" stroke="black" stroke-opacity="0.12"/>
|
||||
<rect x="8" y="8" width="18" height="12" rx="3" fill="black" fill-opacity="0.12"/>
|
||||
<rect x="28" y="8" width="18" height="12" rx="3" fill="black" fill-opacity="0.12"/>
|
||||
<rect x="48" y="8" width="18" height="12" rx="3" fill="black" fill-opacity="0.32"/>
|
||||
<rect x="68" y="8" width="18" height="12" rx="3" fill="black" fill-opacity="0.12"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 582 B |
@@ -0,0 +1,8 @@
|
||||
<svg width="94" height="28" viewBox="0 0 94 28" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="94" height="28" rx="8" fill="#1C1C1C"/>
|
||||
<rect x="0.5" y="0.5" width="93" height="27" rx="7.5" stroke="white" stroke-opacity="0.24"/>
|
||||
<rect x="8" y="8" width="18" height="12" rx="3" fill="white" fill-opacity="0.24"/>
|
||||
<rect x="28" y="8" width="18" height="12" rx="3" fill="white" fill-opacity="0.24"/>
|
||||
<rect x="48" y="8" width="18" height="12" rx="3" fill="white" fill-opacity="0.48"/>
|
||||
<rect x="68" y="8" width="18" height="12" rx="3" fill="white" fill-opacity="0.24"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 584 B |
+18
-1
@@ -13,6 +13,9 @@
|
||||
"enabledManagers": ["npm", "nvm", "custom.regex", "github-actions"],
|
||||
"minimumReleaseAge": "3 days",
|
||||
"postUpdateOptions": ["pnpmDedupe"],
|
||||
"constraints": {
|
||||
"ghActionsLock": "v0.4.1"
|
||||
},
|
||||
"lockFileMaintenance": {
|
||||
"description": ["Run after patch releases but before next beta"],
|
||||
"enabled": true,
|
||||
@@ -59,12 +62,26 @@
|
||||
"datasourceTemplate": "github-releases",
|
||||
"extractVersionTemplate": "^v(?<version>.+)$"
|
||||
},
|
||||
{
|
||||
"description": "Keep gh-actions-lock in CI and Renovate's lockfile generator on the same version",
|
||||
"customType": "regex",
|
||||
"managerFilePatterns": [
|
||||
"/^\\.github/workflows/actions-lock\\.yaml$/",
|
||||
"/^renovate\\.json$/"
|
||||
],
|
||||
"matchStrings": [
|
||||
"GH_ACTIONS_LOCK_VERSION: (?<currentValue>v\\d+\\.\\d+\\.\\d+)",
|
||||
"\"ghActionsLock\": \"(?<currentValue>v\\d+\\.\\d+\\.\\d+)\""
|
||||
],
|
||||
"depNameTemplate": "github/gh-actions-lock",
|
||||
"datasourceTemplate": "github-releases"
|
||||
},
|
||||
{
|
||||
"description": "Keep Playwright CI container image up to date",
|
||||
"customType": "regex",
|
||||
"managerFilePatterns": ["/^\\.github/workflows/e2e\\.yaml$/"],
|
||||
"matchStrings": [
|
||||
"mcr\\.microsoft\\.com/playwright:(?<currentValue>v\\d+\\.\\d+\\.\\d+-noble)"
|
||||
"mcr\\.microsoft\\.com/playwright:(?<currentValue>v\\d+\\.\\d+\\.\\d+-noble)(?:@(?<currentDigest>sha256:[a-f0-9]{64}))?"
|
||||
],
|
||||
"depNameTemplate": "mcr.microsoft.com/playwright",
|
||||
"datasourceTemplate": "docker",
|
||||
|
||||
@@ -4,8 +4,8 @@ import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import "../components/ha-icon-next";
|
||||
import "../components/ha-list";
|
||||
import "../components/ha-list-item";
|
||||
import "../components/item/ha-list-item-button";
|
||||
import "../components/list/ha-list-base";
|
||||
import type { AuthProvider } from "../data/auth";
|
||||
|
||||
declare global {
|
||||
@@ -32,21 +32,19 @@ export class HaPickAuthProvider extends LitElement {
|
||||
>${this._localize("ui.panel.page-authorize.pick_auth_provider")}</span
|
||||
>
|
||||
</h3>
|
||||
<ha-list>
|
||||
<ha-list-base>
|
||||
${this.authProviders.map(
|
||||
(provider) => html`
|
||||
<ha-list-item
|
||||
hasMeta
|
||||
role="button"
|
||||
<ha-list-item-button
|
||||
.auth_provider=${provider}
|
||||
@click=${this._handlePick}
|
||||
>
|
||||
${provider.name}
|
||||
<ha-icon-next slot="meta"></ha-icon-next>
|
||||
</ha-list-item>
|
||||
<span slot="headline">${provider.name}</span>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>
|
||||
`
|
||||
)}
|
||||
</ha-list>
|
||||
</ha-list-base>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -80,9 +78,9 @@ export class HaPickAuthProvider extends LitElement {
|
||||
background: var(--card-background-color);
|
||||
padding: 0 15px;
|
||||
}
|
||||
ha-list {
|
||||
ha-list-base {
|
||||
margin: 16px -16px 0;
|
||||
--mdc-list-side-padding: 24px;
|
||||
--ha-row-item-padding-inline: 24px;
|
||||
}
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Return a copy of the list with the value in it, without adding duplicates
|
||||
* @param values - The current list
|
||||
* @param value - The value to add
|
||||
*/
|
||||
export const arrayWith = <T>(
|
||||
values: readonly T[] | undefined,
|
||||
value: T
|
||||
): T[] => (values?.includes(value) ? [...values] : [...(values ?? []), value]);
|
||||
|
||||
/**
|
||||
* Return a copy of the list without the value
|
||||
* @param values - The current list
|
||||
* @param value - The value to remove
|
||||
*/
|
||||
export const arrayWithout = <T>(
|
||||
values: readonly T[] | undefined,
|
||||
value: T
|
||||
): T[] => (values ?? []).filter((v) => v !== value);
|
||||
@@ -144,7 +144,8 @@ export class MediaProgressController implements ReactiveController {
|
||||
return;
|
||||
}
|
||||
slider.valueFormatter = formatMediaTime;
|
||||
if (slider.matches(":state(dragging)")) {
|
||||
// matches(":state(dragging)") throws before Chromium 125.
|
||||
if (slider.customStates.has("dragging")) {
|
||||
return;
|
||||
}
|
||||
slider.value = this.progress ?? 0;
|
||||
|
||||
@@ -26,8 +26,10 @@ export interface QueryParamsControllerOptions {
|
||||
* Called when the page of the host is navigated to while the host is
|
||||
* connected, like a second link to an open page or coming back to it. Read
|
||||
* the URL with `searchParams()` and apply it, then `write()` the state back.
|
||||
* Gets the `popstate` or `location-changed` event, or nothing when the host
|
||||
* is connected again.
|
||||
*/
|
||||
navigated: () => void;
|
||||
navigated: (ev?: Event) => void;
|
||||
/**
|
||||
* The path of the host's page, for a page that can first be connected on
|
||||
* a sub-path it sends on to itself, like an add link. Defaults to the path
|
||||
@@ -159,7 +161,7 @@ export class QueryParamsController<
|
||||
}
|
||||
// Leaving the page gets here too, before the router swaps the page
|
||||
if (this._isActive()) {
|
||||
this._options.navigated();
|
||||
this._options.navigated(ev);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// The attributes that hold the address of a link or an image
|
||||
const URL_ATTRIBUTES = [
|
||||
export const URL_ATTRIBUTES = [
|
||||
["a", "href"],
|
||||
["img", "src"],
|
||||
["source", "src"],
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { computeCssColor } from "../color/compute-color";
|
||||
import { computeDomain } from "./compute_domain";
|
||||
import { stateColorCss } from "./state_color";
|
||||
|
||||
export const ALERT_DOMAINS = [
|
||||
"alarm_control_panel",
|
||||
@@ -8,8 +10,6 @@ export const ALERT_DOMAINS = [
|
||||
"lock",
|
||||
];
|
||||
|
||||
export const DEFAULT_ALERT_COLOR = "red";
|
||||
|
||||
export const computeAlertActiveStates = (entityId: string): string[] => {
|
||||
switch (computeDomain(entityId)) {
|
||||
case "alarm_control_panel":
|
||||
@@ -25,3 +25,16 @@ export const computeAlertActiveStates = (entityId: string): string[] => {
|
||||
|
||||
export const isAlertActive = (stateObj: HassEntity): boolean =>
|
||||
computeAlertActiveStates(stateObj.entity_id).includes(stateObj.state);
|
||||
|
||||
export const computeAlertColor = (
|
||||
stateObj: HassEntity,
|
||||
color: string
|
||||
): string | undefined => {
|
||||
if (color === "none") {
|
||||
return undefined;
|
||||
}
|
||||
if (color === "state") {
|
||||
return stateColorCss(stateObj);
|
||||
}
|
||||
return computeCssColor(color);
|
||||
};
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "../../data/entity/entity_attributes";
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { TimeZone } from "../../data/translation";
|
||||
import type { WeatherEntity } from "../../data/weather";
|
||||
import { getWeatherUnit } from "../../data/weather";
|
||||
import type { HomeAssistant, ValuePart } from "../../types";
|
||||
@@ -115,6 +116,24 @@ export const computeAttributeValueToParts = (
|
||||
}
|
||||
}
|
||||
|
||||
// Date only, which is timezone agnostic, so parse and format it as
|
||||
// local time to keep the same calendar day
|
||||
if (isDate(attributeValue)) {
|
||||
const date = new Date(`${attributeValue}T00:00`);
|
||||
if (checkValidDate(date)) {
|
||||
return [
|
||||
{
|
||||
type: "value",
|
||||
value: formatDate(
|
||||
date,
|
||||
{ ...locale, time_zone: TimeZone.local },
|
||||
config
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Value was not a timestamp, so only do date formatting
|
||||
const date = new Date(attributeValue);
|
||||
if (checkValidDate(date)) {
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
// other one is built in the browser. The attribution comes from the TileJSON,
|
||||
// deliberately: it follows whoever serves the tiles.
|
||||
const SHIPPED_STYLES = {
|
||||
light: "/static/map/light.json",
|
||||
dark: "/static/map/dark.json",
|
||||
light: `${__STATIC_PATH__}map/light.json`,
|
||||
dark: `${__STATIC_PATH__}map/dark.json`,
|
||||
} as const;
|
||||
|
||||
// MapLibre needs WebGL2 even for raster, so the fallback stays a Leaflet layer.
|
||||
@@ -28,7 +28,7 @@ const RASTER_TILE_URL = `${MAP_TILES_PATH}/raster/{z}/{x}/{y}.png?token={token}`
|
||||
// policy strips again unless the tiles ask for it back.
|
||||
const DEMO_RASTER_TILE_URL = "https://tile.openstreetmap.org/{z}/{x}/{y}.png";
|
||||
const OSM_ATTRIBUTION =
|
||||
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
|
||||
'<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';
|
||||
|
||||
// Browsers keep about 16 live WebGL contexts and drop the oldest, which a
|
||||
// dashboard full of map cards hits. A transient loss is restored, hence a grace.
|
||||
@@ -92,8 +92,12 @@ const useDemoUpstream = (style: StyleSpecification): StyleSpecification => {
|
||||
return style;
|
||||
};
|
||||
|
||||
// The origin that serves the frontend's files: the page, except for the demo
|
||||
// embed on another site
|
||||
const filesBase = () => new URL(__STATIC_PATH__, location.href);
|
||||
|
||||
// MapLibre rejects a relative sprite URL
|
||||
const absoluteSprite = (url: string) => new URL(url, location.href).href;
|
||||
const absoluteSprite = (url: string) => new URL(url, filesBase()).href;
|
||||
|
||||
// Shared only while in flight, or a style that failed once would never be
|
||||
// fetched again. Text rather than a parsed style: MapLibre mutates what it
|
||||
@@ -125,7 +129,7 @@ export const loadStyle = async (
|
||||
).buildMapStyle(
|
||||
mapStyle.palette,
|
||||
mapStyle.options ?? {},
|
||||
mapStyle.baseColors
|
||||
mapStyle.styleOptions
|
||||
);
|
||||
|
||||
if (typeof style.sprite === "string") {
|
||||
@@ -141,14 +145,15 @@ export const loadStyle = async (
|
||||
|
||||
// Global to MapLibre; set once before the first map is created. Absolute,
|
||||
// because on Cast the page is not served from the instance. The URL comes
|
||||
// from the build: the worker is an entry of its own, next to the app.
|
||||
// from the build: the worker is an entry of its own, next to the app. MapLibre
|
||||
// starts a worker from another origin itself.
|
||||
let workerUrlSet = false;
|
||||
export const ensureWorkerUrl = (setUrl: typeof setWorkerUrl) => {
|
||||
if (workerUrlSet) {
|
||||
return;
|
||||
}
|
||||
workerUrlSet = true;
|
||||
setUrl(new URL(__MAPLIBRE_WORKER_URL__, location.href).href);
|
||||
setUrl(new URL(__MAPLIBRE_WORKER_URL__, filesBase()).href);
|
||||
};
|
||||
|
||||
const createVectorLayer = async (
|
||||
|
||||
@@ -16,7 +16,7 @@ import { finalizeMapStyle } from "./map-style-transforms";
|
||||
*/
|
||||
// Versioned: /static is served with a month of max-age, so a cached manifest
|
||||
// could otherwise pair a new build with the sprite sheet of an old one.
|
||||
const STYLE_URLS_PATH = `/static/map/urls.json?v=${__VERSION__}`;
|
||||
const STYLE_URLS_PATH = `${__STATIC_PATH__}map/urls.json?v=${__VERSION__}`;
|
||||
|
||||
let urls: Promise<OsmOptions["urls"]> | undefined;
|
||||
|
||||
@@ -35,7 +35,7 @@ const styleUrls = () => {
|
||||
export const buildMapStyle = async (
|
||||
palette: MapPalette,
|
||||
options: Record<string, unknown>,
|
||||
baseColors?: Record<string, string>
|
||||
styleOptions?: Record<string, unknown>
|
||||
): Promise<StyleSpecification> => {
|
||||
const [{ osm }, resolvedUrls] = await Promise.all([
|
||||
import("@versatiles/style"),
|
||||
@@ -50,13 +50,9 @@ export const buildMapStyle = async (
|
||||
// The builder throws on an option it does not know and on a color it cannot
|
||||
// parse. Those come from a card config or a theme, so one typo would
|
||||
// otherwise drop the whole card to raster tiles. Step back to the style as it
|
||||
// ships - colors included, or the default would come out as the builder's
|
||||
// unpainted cartography - and only then to the bare palette.
|
||||
const attempts = [
|
||||
options,
|
||||
...(baseColors ? [{ colors: baseColors }] : []),
|
||||
{},
|
||||
];
|
||||
// comes - colors and adjustments included, or the default would come out as
|
||||
// the builder's unpainted cartography - and only then to the bare palette.
|
||||
const attempts = [options, ...(styleOptions ? [styleOptions] : []), {}];
|
||||
let style: StyleSpecification | undefined;
|
||||
for (const attempt of attempts) {
|
||||
try {
|
||||
|
||||
@@ -78,7 +78,7 @@ const POSITIONS: Record<
|
||||
bottomright: "bottom-right",
|
||||
};
|
||||
|
||||
const MAPLIBRE_CSS_URL = "/static/map/maplibre-gl.css";
|
||||
const MAPLIBRE_CSS_URL = `${__STATIC_PATH__}map/maplibre-gl.css`;
|
||||
// Fully hidden behind the globe, not MapLibre's faint ghost
|
||||
const MARKER_OPTIONS = { opacityWhenCovered: 0 };
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// The vector cartographies the map can draw. Each is a light and a dark
|
||||
// palette; the theme mode picks the half.
|
||||
// palette; the theme mode picks the half, unless the style only has one.
|
||||
//
|
||||
// Only the default pair is generated at build time (build-scripts/gulp/
|
||||
// map-assets.js); everything else is built in the browser from the same
|
||||
// builder, against the tiles and glyphs core's proxy already serves.
|
||||
|
||||
import { HA_MAP_COLORS, HA_MAP_COLORS_DARK } from "./ha-map-palette";
|
||||
import { NEON_MAP_COLORS_DARK, NEON_MAP_OPTIONS } from "./neon-map-palette";
|
||||
|
||||
/** Style ids, in the order the card editor offers them */
|
||||
export const MAP_STYLES = [
|
||||
@@ -15,6 +16,7 @@ export const MAP_STYLES = [
|
||||
"muted",
|
||||
"gray",
|
||||
"toner",
|
||||
"neon",
|
||||
] as const;
|
||||
|
||||
export type MapStyle = (typeof MAP_STYLES)[number];
|
||||
@@ -26,13 +28,19 @@ type VersatilesPalette = "colorful" | "natural" | "muted" | "gray" | "toner";
|
||||
|
||||
export type MapPalette = VersatilesPalette | `${VersatilesPalette}-dark`;
|
||||
|
||||
/** A cartography plus the colors painted over it; only the default has any */
|
||||
/**
|
||||
* A cartography plus what is painted over it; the VersaTiles palettes have
|
||||
* nothing. The color sets say which halves a style has: both, or neither, and
|
||||
* the theme mode picks; only one, and that is the half the map draws.
|
||||
*/
|
||||
const STYLE_PALETTES: Record<
|
||||
MapStyle,
|
||||
{
|
||||
palette: VersatilesPalette;
|
||||
colors?: Record<string, string>;
|
||||
colorsDark?: Record<string, string>;
|
||||
/** Builder options the style comes with, by option group */
|
||||
options?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
> = {
|
||||
default: {
|
||||
@@ -40,6 +48,11 @@ const STYLE_PALETTES: Record<
|
||||
colors: HA_MAP_COLORS,
|
||||
colorsDark: HA_MAP_COLORS_DARK,
|
||||
},
|
||||
neon: {
|
||||
palette: "colorful",
|
||||
colorsDark: NEON_MAP_COLORS_DARK,
|
||||
options: NEON_MAP_OPTIONS,
|
||||
},
|
||||
colorful: { palette: "colorful" },
|
||||
natural: { palette: "natural" },
|
||||
muted: { palette: "muted" },
|
||||
@@ -96,11 +109,12 @@ export interface ResolvedMapStyle {
|
||||
/** Fetched rather than built: the default, while nothing was added to it */
|
||||
shipped?: "light" | "dark";
|
||||
/**
|
||||
* The style's own colors, without what the theme or the card painted over
|
||||
* them. What to fall back on when the builder rejects an adjustment, so a
|
||||
* bad value costs the adjustments rather than the cartography.
|
||||
* The style as it comes: its colors and its own adjustments, without what
|
||||
* the theme or the card painted over them. What to fall back on when the
|
||||
* builder rejects an adjustment, so a bad value costs the card's adjustments
|
||||
* rather than the style.
|
||||
*/
|
||||
baseColors?: Record<string, string>;
|
||||
styleOptions?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const isStyle = (value: unknown): value is MapStyle =>
|
||||
@@ -110,9 +124,31 @@ export const isCustomMapStyle = (
|
||||
style: MapStyleConfig | undefined
|
||||
): style is CustomMapStyleConfig => typeof style === "object" && style !== null;
|
||||
|
||||
export const paletteFor = (style: MapStyle, darkMode: boolean): MapPalette => {
|
||||
const toStyle = (style: MapStyleConfig | undefined): MapStyle => {
|
||||
const named = isCustomMapStyle(style) ? style.base : style;
|
||||
return isStyle(named) ? named : DEFAULT_MAP_STYLE;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the map comes out dark: the theme mode's answer, unless the style
|
||||
* only has the one half. What the map's own chrome and the theme tokens have
|
||||
* to follow, rather than the theme mode.
|
||||
*/
|
||||
export const isDarkMapStyle = (
|
||||
style: MapStyleConfig | undefined,
|
||||
darkMode: boolean
|
||||
): boolean => {
|
||||
const { colors, colorsDark } = STYLE_PALETTES[toStyle(style)];
|
||||
if (Boolean(colors) !== Boolean(colorsDark)) {
|
||||
return Boolean(colorsDark);
|
||||
}
|
||||
return darkMode;
|
||||
};
|
||||
|
||||
/** The half to draw; `dark` is the map's, from isDarkMapStyle */
|
||||
export const paletteFor = (style: MapStyle, dark: boolean): MapPalette => {
|
||||
const { palette } = STYLE_PALETTES[style];
|
||||
return darkMode ? `${palette}-dark` : palette;
|
||||
return dark ? `${palette}-dark` : palette;
|
||||
};
|
||||
|
||||
// An allowlist, not a passthrough: the builder also takes the tile, glyph and
|
||||
@@ -198,19 +234,33 @@ export const resolveMapStyle = (
|
||||
themeColors?: Record<string, string>
|
||||
): ResolvedMapStyle => {
|
||||
const custom = isCustomMapStyle(style) ? style : undefined;
|
||||
const named = custom ? custom.base : style;
|
||||
const mapStyle = isStyle(named) ? named : DEFAULT_MAP_STYLE;
|
||||
const mapStyle = toStyle(style);
|
||||
// A dark-only style picks the dark half of everything, not just the palette.
|
||||
const dark = isDarkMapStyle(style, darkMode);
|
||||
|
||||
const palette = paletteFor(mapStyle, darkMode);
|
||||
const options = custom ? builderOptions(custom, darkMode) : {};
|
||||
const palette = paletteFor(mapStyle, dark);
|
||||
const options = custom ? builderOptions(custom, dark) : {};
|
||||
// Before the colors below are merged in, so it answers whether the card
|
||||
// asked for anything of its own.
|
||||
const cardAdjusted = Object.keys(options).length > 0;
|
||||
|
||||
// The style's own adjustments go under the card's, group by group, so a
|
||||
// card that sets one recolor value keeps the style's others.
|
||||
const {
|
||||
colors,
|
||||
colorsDark,
|
||||
options: styleOptions,
|
||||
} = STYLE_PALETTES[mapStyle];
|
||||
for (const [group, values] of Object.entries(styleOptions ?? {})) {
|
||||
options[group] = {
|
||||
...values,
|
||||
...(options[group] as Record<string, unknown> | undefined),
|
||||
};
|
||||
}
|
||||
|
||||
// Bottom up: the style's colors, what the theme repaints, then what the card
|
||||
// names - so a card that sets one color keeps the rest of the look.
|
||||
const { colors, colorsDark } = STYLE_PALETTES[mapStyle];
|
||||
const styleColors = (darkMode ? colorsDark : colors) ?? colors;
|
||||
const styleColors = dark ? colorsDark : colors;
|
||||
if (styleColors || themeColors) {
|
||||
options.colors = {
|
||||
...styleColors,
|
||||
@@ -223,11 +273,19 @@ export const resolveMapStyle = (
|
||||
return { palette };
|
||||
}
|
||||
|
||||
const base = styleColors ? { baseColors: styleColors } : {};
|
||||
const own = styleColors || styleOptions;
|
||||
const base = own
|
||||
? {
|
||||
styleOptions: {
|
||||
...styleOptions,
|
||||
...(styleColors && { colors: styleColors }),
|
||||
},
|
||||
}
|
||||
: {};
|
||||
|
||||
// Anything added on top of the shipped default has to be built here.
|
||||
const untouched = !themeColors && !cardAdjusted;
|
||||
return mapStyle === DEFAULT_MAP_STYLE && untouched
|
||||
? { palette, options, ...base, shipped: darkMode ? "dark" : "light" }
|
||||
? { palette, options, ...base, shipped: dark ? "dark" : "light" }
|
||||
: { palette, options, ...base };
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { isAndroidDevice } from "../../util/is_android";
|
||||
import { isIosDevice } from "../../util/is_ios";
|
||||
|
||||
export const navigationUrl = (latitude: number, longitude: number): string => {
|
||||
const point = `${latitude},${longitude}`;
|
||||
if (isIosDevice()) {
|
||||
return `https://maps.apple.com/?daddr=${point}`;
|
||||
}
|
||||
if (isAndroidDevice()) {
|
||||
return `geo:${point}?q=${point}`;
|
||||
}
|
||||
return `https://www.openstreetmap.org/directions?to=${encodeURIComponent(point)}#map=15/${latitude}/${longitude}`;
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
// The "neon" style: the VersaTiles "colorful" cartography repainted as a night
|
||||
// map, glowing roads on near-black ground. A dark set and no light one, which
|
||||
// is what makes the style dark whatever the theme mode.
|
||||
|
||||
export const NEON_MAP_COLORS_DARK = {
|
||||
background: "#07021a",
|
||||
land: "#07021a",
|
||||
water: "#13215e",
|
||||
labelWater: "#00e5ff",
|
||||
glacier: "#1b2a6b",
|
||||
natureWood: "#0d1f2e",
|
||||
natureGrass: "#101a33",
|
||||
naturePark: "#12203a",
|
||||
natureLeisure: "#111a30",
|
||||
natureAgriculture: "#0d1528",
|
||||
natureWetland: "#0e2440",
|
||||
natureSand: "#1a1230",
|
||||
natureRock: "#140c28",
|
||||
areaResidential: "#0c0524",
|
||||
areaCommercial: "#140430",
|
||||
areaIndustrial: "#10062a",
|
||||
areaWaste: "#160a2e",
|
||||
areaBurial: "#0d0a26",
|
||||
siteParking: "#0f0728",
|
||||
siteSports: "#0a1c2c",
|
||||
siteEducation: "#160a34",
|
||||
siteHospital: "#2a0a2a",
|
||||
siteDanger: "#ff1744",
|
||||
sitePrison: "#1c0a28",
|
||||
siteConstruction: "#3a1d5c",
|
||||
building: "#160a33",
|
||||
buildingBg: "#8a2be2",
|
||||
roadStreet: "#00e5ff",
|
||||
roadStreetBg: "#062b52",
|
||||
roadSecondary: "#8f7bff",
|
||||
roadSecondaryBg: "#241058",
|
||||
roadTrunk: "#ff6ec7",
|
||||
roadTrunkBg: "#4a0f38",
|
||||
roadMotorway: "#ff2d95",
|
||||
roadMotorwayBg: "#5c0033",
|
||||
transitRail: "#7b2cff",
|
||||
transitSubway: "#b14cff",
|
||||
transitCycle: "#00ffa3",
|
||||
transitFoot: "#2e2a55",
|
||||
boundary: "#39ff14",
|
||||
boundaryDisputed: "#1f7a0d",
|
||||
label: "#ff9ad5",
|
||||
labelHalo: "rgba(7,2,26,0.9)",
|
||||
labelSymbol: "#ff9ad5",
|
||||
labelPoi: "#00e5ff",
|
||||
labelShield: "#12002a",
|
||||
labelHousenumber: "rgba(0,229,255,0.35)",
|
||||
};
|
||||
|
||||
/** Builder options the style comes with, under whatever a card adds */
|
||||
export const NEON_MAP_OPTIONS = {
|
||||
recolor: { saturate: 0.35, contrast: 1.15 },
|
||||
text: {
|
||||
transform: "uppercase",
|
||||
letterSpacing: 0.12,
|
||||
haloWidth: 2,
|
||||
haloBlur: 0,
|
||||
},
|
||||
};
|
||||
@@ -1,14 +0,0 @@
|
||||
import type {
|
||||
ListItem,
|
||||
RequestSelectedDetail,
|
||||
} from "@material/mwc-list/mwc-list-item";
|
||||
|
||||
export const shouldHandleRequestSelectedEvent = (
|
||||
ev: CustomEvent<RequestSelectedDetail>
|
||||
): boolean => {
|
||||
if (!ev.detail.selected || ev.detail.source !== "property") {
|
||||
return false;
|
||||
}
|
||||
(ev.currentTarget as ListItem).selected = false;
|
||||
return true;
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SYSTEM_LOG_LEVELS, type SystemLogLevel } from "../../data/system_log";
|
||||
import {
|
||||
decodeQueryParams,
|
||||
hasQueryParams,
|
||||
@@ -17,7 +18,7 @@ export const logSearchQueryParamConfig = {
|
||||
// `raw` shows the full Home Assistant Core log instead of the errors.
|
||||
export const logsQueryParamConfig = {
|
||||
string: ["provider", "search", "filter"],
|
||||
list: ["integration"],
|
||||
list: ["integration", "level"],
|
||||
boolean: [{ key: "raw", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
@@ -28,13 +29,19 @@ export interface LogsState {
|
||||
search: string;
|
||||
// Only apply to the Home Assistant Core log
|
||||
integrations: string[];
|
||||
// Only apply to the Home Assistant Core errors, not the raw log
|
||||
levels: SystemLogLevel[];
|
||||
raw: boolean;
|
||||
}
|
||||
|
||||
const isLevel = (level: string): level is SystemLogLevel =>
|
||||
(SYSTEM_LOG_LEVELS as readonly string[]).includes(level);
|
||||
|
||||
export const DEFAULT_LOGS_STATE: LogsState = {
|
||||
provider: DEFAULT_LOG_PROVIDER,
|
||||
search: "",
|
||||
integrations: [],
|
||||
levels: [],
|
||||
raw: false,
|
||||
};
|
||||
|
||||
@@ -53,6 +60,7 @@ export const logsQueryParams = (state: LogsState): LogsQueryParams => ({
|
||||
search: state.search,
|
||||
integration:
|
||||
state.provider === DEFAULT_LOG_PROVIDER ? state.integrations : undefined,
|
||||
level: state.provider === DEFAULT_LOG_PROVIDER ? state.levels : undefined,
|
||||
raw: state.provider === DEFAULT_LOG_PROVIDER && state.raw,
|
||||
});
|
||||
|
||||
@@ -71,6 +79,7 @@ export const logsLinkFromUrl = (
|
||||
provider,
|
||||
search: params.search ?? params.filter ?? "",
|
||||
integrations: core ? (params.integration?.filter(Boolean) ?? []) : [],
|
||||
levels: core ? (params.level?.filter(isLevel) ?? []) : [],
|
||||
raw: core && !!params.raw,
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import { provide, type ContextType } from "@lit/context";
|
||||
import { mdiCommentTextOutline } from "@mdi/js";
|
||||
import type { HassServiceTarget } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
@@ -17,9 +17,14 @@ import { getEntityTarget } from "../../panels/config/automation/target/get_entit
|
||||
import "../../panels/config/automation/target/ha-automation-row-targets";
|
||||
import "../ha-svg-icon";
|
||||
import "../ha-tooltip";
|
||||
import { targetExpandGroupContext } from "../target-picker/target-expand-group-context";
|
||||
|
||||
@customElement("ha-automation-condition-summary")
|
||||
export class HaAutomationConditionSummary extends LitElement {
|
||||
// Triggers and conditions don't expand the groups their targets name.
|
||||
@provide({ context: targetExpandGroupContext })
|
||||
protected _targetExpandGroup = false;
|
||||
|
||||
@property() public label = "";
|
||||
|
||||
@property({ attribute: false }) public condition?: Condition;
|
||||
|
||||
@@ -67,3 +67,88 @@ export const itemTooltipPosition: TooltipPositionCallback = (
|
||||
|
||||
return [x, y];
|
||||
};
|
||||
|
||||
const ECHARTS_TOOLTIP_GAP_PX = 20;
|
||||
export const WINDOW_MARGIN_PX = 8;
|
||||
|
||||
const fitInto = (
|
||||
pos: number,
|
||||
size: number,
|
||||
alternatives: number[],
|
||||
min: number,
|
||||
max: number
|
||||
) =>
|
||||
size > max - min
|
||||
? min
|
||||
: ([pos, ...alternatives].find((p) => p >= min && p + size <= max) ??
|
||||
Math.max(min, Math.min(pos, max - size)));
|
||||
|
||||
/**
|
||||
* ECharts' default placement (or the chart-confined one), moved into the
|
||||
* window when it would leave it. The other side of the cursor is tried before
|
||||
* clamping, below first vertically. A tooltip taller than the window starts at
|
||||
* its top. A confined tooltip stays in the chart, leaving it only as far as the
|
||||
* window needs.
|
||||
*/
|
||||
export const windowTooltipPosition =
|
||||
(
|
||||
getChartRect: () => DOMRect | undefined,
|
||||
confine: boolean
|
||||
): TooltipPositionCallback =>
|
||||
(point, _params, _dom, _rect, size) => {
|
||||
const [cursorX, cursorY] = point;
|
||||
const [viewW, viewH] = size.viewSize;
|
||||
const [tipW, tipH] = size.contentSize;
|
||||
|
||||
const right = cursorX + ECHARTS_TOOLTIP_GAP_PX;
|
||||
const left = cursorX - ECHARTS_TOOLTIP_GAP_PX - tipW;
|
||||
const below = cursorY + ECHARTS_TOOLTIP_GAP_PX;
|
||||
const above = cursorY - ECHARTS_TOOLTIP_GAP_PX - tipH;
|
||||
let x = right + tipW + 2 > viewW ? left : right;
|
||||
let y = below + tipH > viewH ? above : below;
|
||||
if (confine) {
|
||||
x = Math.max(0, Math.min(x, viewW - tipW));
|
||||
y = Math.max(0, Math.min(y, viewH - tipH));
|
||||
}
|
||||
|
||||
const rect = getChartRect();
|
||||
if (!rect?.height) {
|
||||
return [x, y];
|
||||
}
|
||||
const fit = (
|
||||
pos: number,
|
||||
tipSize: number,
|
||||
alternatives: number[],
|
||||
windowMin: number,
|
||||
windowMax: number,
|
||||
viewSize: number
|
||||
) => {
|
||||
if (!confine) {
|
||||
return fitInto(pos, tipSize, alternatives, windowMin, windowMax);
|
||||
}
|
||||
const min = Math.max(0, windowMin);
|
||||
const max = Math.min(viewSize, windowMax);
|
||||
return tipSize > max - min
|
||||
? fitInto(pos, tipSize, [], windowMin, windowMax)
|
||||
: fitInto(pos, tipSize, alternatives, min, max);
|
||||
};
|
||||
const { clientWidth, clientHeight } = document.documentElement;
|
||||
return [
|
||||
fit(
|
||||
x,
|
||||
tipW,
|
||||
[right, left],
|
||||
WINDOW_MARGIN_PX - rect.left,
|
||||
clientWidth - WINDOW_MARGIN_PX - rect.left,
|
||||
viewW
|
||||
),
|
||||
fit(
|
||||
y,
|
||||
tipH,
|
||||
[below, above],
|
||||
WINDOW_MARGIN_PX - rect.top,
|
||||
clientHeight - WINDOW_MARGIN_PX - rect.top,
|
||||
viewH
|
||||
),
|
||||
];
|
||||
};
|
||||
@@ -68,6 +68,7 @@ import { ZOOM_SLIDER_HEIGHT } from "./ha-chart-zoom-slider";
|
||||
import { formatTimeLabel } from "./axis-label";
|
||||
import type { ChartSonification } from "./chart-sonification";
|
||||
import { canSonifyChart, sonifyChart } from "./chart-sonification";
|
||||
import { windowTooltipPosition } from "./chart-tooltip-position";
|
||||
import { downSampleLineData } from "./down-sample";
|
||||
import { wrapLitTooltipFormatter } from "./lit-tooltip-formatter";
|
||||
|
||||
@@ -89,6 +90,8 @@ export const DEFAULT_CHART_WIDTH = 500;
|
||||
// is short enough for a whole screenful; on a desktop that would cover the page.
|
||||
const VISIBILITY_ROOT_MARGIN_NARROW = "100%";
|
||||
const VISIBILITY_ROOT_MARGIN = "300px";
|
||||
|
||||
export type ZoomSliderMode = "auto" | "always" | "never";
|
||||
const DEFERRED_PROPS = [
|
||||
"options",
|
||||
"data",
|
||||
@@ -163,9 +166,10 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
@property({ attribute: "small-controls", type: Boolean })
|
||||
public smallControls?: boolean;
|
||||
|
||||
// For charts zoomed from outside, like the synced History charts
|
||||
@property({ attribute: "hide-zoom-controls", type: Boolean })
|
||||
public hideZoomControls = false;
|
||||
// "auto" shows the zoom slider once zoomed. "never" hides every zoom
|
||||
// control, for charts zoomed from outside like the synced History charts.
|
||||
@property({ attribute: "zoom-slider" })
|
||||
public zoomSlider: ZoomSliderMode = "auto";
|
||||
|
||||
// For charts sized to their content, like timelines, which grow to fit the
|
||||
// zoom slider instead of giving up plot height
|
||||
@@ -617,7 +621,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
>
|
||||
${
|
||||
(this._isZoomed || this._isGraphRoamed) &&
|
||||
!this.hideZoomControls &&
|
||||
this.zoomSlider !== "never" &&
|
||||
!showZoomSlider
|
||||
? html`<ha-icon-button
|
||||
class="zoom-reset"
|
||||
@@ -1064,9 +1068,12 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
private _showZoomSlider() {
|
||||
const [start, end] = this._zoomRange;
|
||||
return (
|
||||
!this.hideZoomControls &&
|
||||
this.zoomSlider !== "never" &&
|
||||
this._hasZoomableXAxis() &&
|
||||
(this._zoomSliderHeld || start !== 0 || end !== 100)
|
||||
(this.zoomSlider === "always" ||
|
||||
this._zoomSliderHeld ||
|
||||
start !== 0 ||
|
||||
end !== 100)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1246,9 +1253,19 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
const processTooltip = (tooltip: HaTooltipOption): TooltipOption => {
|
||||
const next = convertHaTooltipFormatter(tooltip);
|
||||
if (isMobile) {
|
||||
next.appendTo = undefined;
|
||||
}
|
||||
if (next.position === undefined) {
|
||||
// ECharts confines after the position callback, which would undo the
|
||||
// window fit, so the callback confines itself
|
||||
next.position = windowTooltipPosition(
|
||||
() => this._chartContainer?.getBoundingClientRect(),
|
||||
isMobile || next.confine === true
|
||||
);
|
||||
next.confine = false;
|
||||
} else if (isMobile) {
|
||||
// mobile charts are full width so we need to confine the tooltip to the chart
|
||||
next.confine = true;
|
||||
next.appendTo = undefined;
|
||||
}
|
||||
if (isMobile || this._touchInput) {
|
||||
next.triggerOn = "click";
|
||||
@@ -2306,6 +2323,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
--ha-assist-chip-trailing-space: var(--ha-space-2);
|
||||
--ha-assist-chip-icon-label-space: var(--ha-space-1);
|
||||
}
|
||||
.zoom-reset {
|
||||
margin-inline-end: var(--ha-space-3);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,8 +31,14 @@ export interface NetworkNode {
|
||||
color?: string;
|
||||
borderColor?: string;
|
||||
borderWidth?: number;
|
||||
opacity?: number;
|
||||
};
|
||||
label?: {
|
||||
position?: "left" | "right" | "top" | "bottom";
|
||||
show?: boolean;
|
||||
fontWeight?: "normal" | "bold";
|
||||
fontSize?: number;
|
||||
};
|
||||
label?: { position: "left" | "right" | "top" | "bottom" };
|
||||
fixed?: boolean;
|
||||
/**
|
||||
* Distance from the center, where 0 is the center and 1 is the edge
|
||||
@@ -51,6 +57,7 @@ export interface NetworkLink {
|
||||
width?: number;
|
||||
color?: string;
|
||||
type?: "solid" | "dashed" | "dotted";
|
||||
opacity?: number;
|
||||
};
|
||||
symbolSize?: number | number[];
|
||||
symbol?: string;
|
||||
@@ -286,9 +293,8 @@ export class HaNetworkGraph extends LitElement {
|
||||
return node.name ?? "";
|
||||
},
|
||||
rich: {
|
||||
primary: {
|
||||
fontSize: 12,
|
||||
},
|
||||
// inherits the node label font, so a node can override it
|
||||
primary: {},
|
||||
secondary: {
|
||||
fontSize: 12,
|
||||
color: getComputedStyle(document.body).getPropertyValue(
|
||||
@@ -648,7 +654,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
ha-icon-button,
|
||||
::slotted(ha-icon-button) {
|
||||
margin-right: 12px;
|
||||
margin-inline-end: var(--ha-space-3);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface Node {
|
||||
color?: string;
|
||||
passThrough?: boolean;
|
||||
entityId?: string;
|
||||
// Nodes of one group take a single position when ordering their children
|
||||
group?: string;
|
||||
}
|
||||
export interface Link {
|
||||
source: string;
|
||||
@@ -46,6 +48,46 @@ const NODE_SIZE = 30;
|
||||
const LABEL_MIN_MARGIN = 5;
|
||||
const BIDI_MARKS = /[\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
|
||||
|
||||
// Links without a value take the remaining capacity of their nodes, in order.
|
||||
export const fillSankeyLinkValues = (
|
||||
nodes: Node[],
|
||||
rawLinks: Link[]
|
||||
): ProcessedLink[] => {
|
||||
const accountedIn = new Map<string, number>();
|
||||
const accountedOut = new Map<string, number>();
|
||||
const links: ProcessedLink[] = [];
|
||||
rawLinks.forEach((link) => {
|
||||
const sourceNode = nodes.find((n) => n.id === link.source);
|
||||
const targetNode = nodes.find((n) => n.id === link.target);
|
||||
if (!sourceNode || !targetNode) {
|
||||
return;
|
||||
}
|
||||
const sourceAccounted = accountedOut.get(sourceNode.id) || 0;
|
||||
const targetAccounted = accountedIn.get(targetNode.id) || 0;
|
||||
|
||||
// if no value is provided, we infer it from the remaining capacity of the source and target nodes
|
||||
const sourceRemaining = sourceNode.value - sourceAccounted;
|
||||
const targetRemaining = targetNode.value - targetAccounted;
|
||||
// ensure the value is not greater than the remaining capacity of the nodes
|
||||
const value = Math.min(
|
||||
link.value ?? sourceRemaining,
|
||||
sourceRemaining,
|
||||
targetRemaining
|
||||
);
|
||||
|
||||
accountedIn.set(targetNode.id, targetAccounted + value);
|
||||
accountedOut.set(sourceNode.id, sourceAccounted + value);
|
||||
|
||||
if (value > 0) {
|
||||
links.push({
|
||||
...link,
|
||||
value,
|
||||
});
|
||||
}
|
||||
});
|
||||
return links;
|
||||
};
|
||||
|
||||
@customElement("ha-sankey-chart")
|
||||
export class HaSankeyChart extends LitElement {
|
||||
@property({ attribute: false }) public data: SankeyChartData = {
|
||||
@@ -190,7 +232,7 @@ export class HaSankeyChart extends LitElement {
|
||||
);
|
||||
}
|
||||
});
|
||||
const links = this._processLinks(filteredNodes, data.links);
|
||||
const links = fillSankeyLinkValues(filteredNodes, data.links);
|
||||
const sectionWidth = width / indexes.length;
|
||||
const labelSpace = sectionWidth - NODE_SIZE - LABEL_DISTANCE;
|
||||
// Two-line values can wrap the unit onto a third line; keep that text inside the chart.
|
||||
@@ -304,60 +346,31 @@ export class HaSankeyChart extends LitElement {
|
||||
|
||||
private _createData = memoizeOne(this._computeData);
|
||||
|
||||
private _processLinks(nodes: Node[], rawLinks: Link[]) {
|
||||
const accountedIn = new Map<string, number>();
|
||||
const accountedOut = new Map<string, number>();
|
||||
const links: ProcessedLink[] = [];
|
||||
rawLinks.forEach((link) => {
|
||||
const sourceNode = nodes.find((n) => n.id === link.source);
|
||||
const targetNode = nodes.find((n) => n.id === link.target);
|
||||
if (!sourceNode || !targetNode) {
|
||||
return;
|
||||
}
|
||||
const sourceAccounted = accountedOut.get(sourceNode.id) || 0;
|
||||
const targetAccounted = accountedIn.get(targetNode.id) || 0;
|
||||
|
||||
// if no value is provided, we infer it from the remaining capacity of the source and target nodes
|
||||
const sourceRemaining = sourceNode.value - sourceAccounted;
|
||||
const targetRemaining = targetNode.value - targetAccounted;
|
||||
// ensure the value is not greater than the remaining capacity of the nodes
|
||||
const value = Math.min(
|
||||
link.value ?? sourceRemaining,
|
||||
sourceRemaining,
|
||||
targetRemaining
|
||||
);
|
||||
|
||||
accountedIn.set(targetNode.id, targetAccounted + value);
|
||||
accountedOut.set(sourceNode.id, sourceAccounted + value);
|
||||
|
||||
if (value > 0) {
|
||||
links.push({
|
||||
...link,
|
||||
value,
|
||||
});
|
||||
}
|
||||
});
|
||||
return links;
|
||||
}
|
||||
|
||||
private _findParentIndex(id: string, links: Link[], sections: Node[][]) {
|
||||
const parents = links.filter((l) => l.target === id).map((l) => l.source);
|
||||
if (parents.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
const countedGroups = new Set<string>();
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
for (const parent of parents) {
|
||||
let offset = 0;
|
||||
for (let i = sections.length - 1; i >= 0; i--) {
|
||||
const section = sections[i];
|
||||
const index = section.findIndex((n) => n.id === parent);
|
||||
if (index !== -1) {
|
||||
sum += offset + index;
|
||||
const positions = [...new Set(sections[i].map((n) => n.group ?? n.id))];
|
||||
const node = sections[i].find((n) => n.id === parent);
|
||||
if (node) {
|
||||
if (node.group !== undefined) {
|
||||
if (countedGroups.has(node.group)) {
|
||||
break;
|
||||
}
|
||||
countedGroups.add(node.group);
|
||||
}
|
||||
sum += offset + positions.indexOf(node.group ?? node.id);
|
||||
count++;
|
||||
break;
|
||||
}
|
||||
offset += section.length;
|
||||
offset += positions.length;
|
||||
}
|
||||
}
|
||||
return count > 0 ? sum / count : -1;
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../types";
|
||||
import { MIN_TIME_BETWEEN_UPDATES } from "./ha-chart-base";
|
||||
import type { ZoomSliderMode } from "./ha-chart-base";
|
||||
import { sideTooltipPosition } from "./chart-tooltip-position";
|
||||
import "./ha-chart-tooltip-marker";
|
||||
import {
|
||||
@@ -105,8 +106,8 @@ export class StateHistoryChartLine extends LitElement {
|
||||
@property({ attribute: "expand-legend", type: Boolean })
|
||||
public expandLegend?: boolean;
|
||||
|
||||
@property({ attribute: "hide-zoom-controls", type: Boolean })
|
||||
public hideZoomControls = false;
|
||||
@property({ attribute: "zoom-slider" })
|
||||
public zoomSlider: ZoomSliderMode = "auto";
|
||||
|
||||
@state() private _chartData: LineSeriesOption[] = [];
|
||||
|
||||
@@ -159,7 +160,7 @@ export class StateHistoryChartLine extends LitElement {
|
||||
@dataset-unhidden=${this._datasetUnhidden}
|
||||
@chart-zoom=${this._handleDataZoom}
|
||||
.expandLegend=${this.expandLegend}
|
||||
.hideZoomControls=${this.hideZoomControls}
|
||||
.zoomSlider=${this.zoomSlider}
|
||||
.clickLabelForMoreInfo=${this.clickForMoreInfo}
|
||||
@legend-label-click=${this._handleLegendLabelClick}
|
||||
></ha-chart-base>
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../types";
|
||||
import { DEFAULT_CHART_WIDTH, MIN_TIME_BETWEEN_UPDATES } from "./ha-chart-base";
|
||||
import type { ZoomSliderMode } from "./ha-chart-base";
|
||||
import { itemTooltipPosition } from "./chart-tooltip-position";
|
||||
import "./ha-chart-tooltip-marker";
|
||||
import type { HaECOption, HaECSeries } from "../../resources/echarts/echarts";
|
||||
@@ -68,8 +69,8 @@ export class StateHistoryChartTimeline extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public chartIndex?;
|
||||
|
||||
@property({ attribute: "hide-zoom-controls", type: Boolean })
|
||||
public hideZoomControls = false;
|
||||
@property({ attribute: "zoom-slider" })
|
||||
public zoomSlider: ZoomSliderMode = "auto";
|
||||
|
||||
@state() private _chartData: CustomSeriesOption[] = [];
|
||||
|
||||
@@ -105,7 +106,7 @@ export class StateHistoryChartTimeline extends LitElement {
|
||||
grow-for-zoom-slider
|
||||
@chart-click=${this._handleChartClick}
|
||||
@chart-zoom=${this._handleDataZoom}
|
||||
.hideZoomControls=${this.hideZoomControls}
|
||||
.zoomSlider=${this.zoomSlider}
|
||||
></ha-chart-base>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ export class StateHistoryCharts extends LitElement {
|
||||
@chart-zoom-with-index=${this._handleTimelineSync}
|
||||
.height=${this.virtualize ? undefined : this.height}
|
||||
.expandLegend=${this.expandLegend}
|
||||
?hide-zoom-controls=${this.syncCharts}
|
||||
.zoomSlider=${this.syncCharts ? "never" : "auto"}
|
||||
></state-history-chart-line>
|
||||
</div> `;
|
||||
}
|
||||
@@ -237,7 +237,7 @@ export class StateHistoryCharts extends LitElement {
|
||||
.clickForMoreInfo=${this.clickForMoreInfo}
|
||||
@y-width-changed=${this._yWidthChanged}
|
||||
@chart-zoom-with-index=${this._handleTimelineSync}
|
||||
?hide-zoom-controls=${this.syncCharts}
|
||||
.zoomSlider=${this.syncCharts ? "never" : "auto"}
|
||||
></state-history-chart-timeline>
|
||||
</div> `;
|
||||
};
|
||||
|
||||
@@ -352,6 +352,7 @@ export class HaChipBase extends HaButton {
|
||||
}
|
||||
.container {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
|
||||
@@ -12,11 +12,11 @@ import { haStyleDialog } from "../../resources/styles";
|
||||
import "../ha-button";
|
||||
import "../ha-dialog-footer";
|
||||
import "../ha-icon-button";
|
||||
import "../ha-list";
|
||||
import "../ha-list-item";
|
||||
import "../ha-sortable";
|
||||
import "../ha-svg-icon";
|
||||
import "../ha-dialog";
|
||||
import "../item/ha-list-item-base";
|
||||
import "../list/ha-list-base";
|
||||
import type {
|
||||
DataTableColumnContainer,
|
||||
DataTableColumnData,
|
||||
@@ -139,7 +139,7 @@ export class DialogDataTableSettings extends LitElement {
|
||||
draggable-selector=".draggable"
|
||||
handle-selector=".handle"
|
||||
>
|
||||
<ha-list>
|
||||
<ha-list-base>
|
||||
${repeat(
|
||||
columns,
|
||||
(col) => col.key,
|
||||
@@ -152,23 +152,23 @@ export class DialogDataTableSettings extends LitElement {
|
||||
col.defaultHidden)
|
||||
: col.defaultHidden);
|
||||
|
||||
return html`<ha-list-item
|
||||
hasMeta
|
||||
return html`<ha-list-item-base
|
||||
class=${classMap({
|
||||
hidden: !isVisible,
|
||||
draggable: canMove && isVisible,
|
||||
})}
|
||||
graphic="icon"
|
||||
noninteractive
|
||||
>${col.title || col.label || col.key}
|
||||
>
|
||||
<span slot="headline"
|
||||
>${col.title || col.label || col.key}</span
|
||||
>
|
||||
${
|
||||
canMove && isVisible
|
||||
? html`<ha-svg-icon
|
||||
class="handle"
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
slot="graphic"
|
||||
slot="start"
|
||||
></ha-svg-icon>`
|
||||
: nothing
|
||||
: html`<span class="handle-spacer" slot="start"></span>`
|
||||
}
|
||||
<ha-icon-button
|
||||
tabindex="0"
|
||||
@@ -176,7 +176,7 @@ export class DialogDataTableSettings extends LitElement {
|
||||
.disabled=${!canHide}
|
||||
.hidden=${!isVisible}
|
||||
.path=${isVisible ? mdiEye : mdiEyeOff}
|
||||
slot="meta"
|
||||
slot="end"
|
||||
.label=${localize(
|
||||
`ui.components.data-table.settings.${isVisible ? "hide" : "show"}`,
|
||||
{ title: typeof col.title === "string" ? col.title : "" }
|
||||
@@ -184,10 +184,10 @@ export class DialogDataTableSettings extends LitElement {
|
||||
.column=${col.key}
|
||||
@click=${this._toggle}
|
||||
></ha-icon-button>
|
||||
</ha-list-item>`;
|
||||
</ha-list-item-base>`;
|
||||
}
|
||||
)}
|
||||
</ha-list>
|
||||
</ha-list-base>
|
||||
</ha-sortable>
|
||||
<ha-dialog-footer slot="footer">
|
||||
<ha-button
|
||||
@@ -326,8 +326,8 @@ export class DialogDataTableSettings extends LitElement {
|
||||
--dialog-z-index: 10;
|
||||
--dialog-content-padding: 0 8px;
|
||||
}
|
||||
ha-list-item {
|
||||
--mdc-list-side-padding: 12px;
|
||||
ha-list-item-base {
|
||||
--ha-row-item-padding-inline: 12px;
|
||||
overflow: visible;
|
||||
}
|
||||
.hidden {
|
||||
@@ -345,6 +345,11 @@ export class DialogDataTableSettings extends LitElement {
|
||||
display: block;
|
||||
margin: -12px;
|
||||
}
|
||||
.handle-spacer {
|
||||
display: block;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { TZDate } from "@date-fns/tz";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { ActionDetail } from "@material/mwc-list";
|
||||
import { mdiCalendarToday } from "@mdi/js";
|
||||
import "cally";
|
||||
import type { HassConfig } from "home-assistant-js-websocket/dist/types";
|
||||
@@ -17,6 +16,7 @@ import {
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type {
|
||||
HASSDomCurrentTargetEvent,
|
||||
HASSDomEvent,
|
||||
HASSDomTargetEvent,
|
||||
} from "../../common/dom/fire_event";
|
||||
@@ -32,8 +32,8 @@ import type { HaBaseTimeInput } from "../ha-base-time-input";
|
||||
import "../ha-icon-button";
|
||||
import "../ha-icon-button-next";
|
||||
import "../ha-icon-button-prev";
|
||||
import "../ha-list";
|
||||
import "../ha-list-item";
|
||||
import "../item/ha-list-item-button";
|
||||
import "../list/ha-list-base";
|
||||
import "../ha-time-input";
|
||||
import type { HaTimeInput } from "../ha-time-input";
|
||||
import type { DateRangePickerRanges } from "./ha-date-range-picker";
|
||||
@@ -166,11 +166,19 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-list @action=${this._setDateRange} activatable>
|
||||
${Object.keys(this.ranges!).map(
|
||||
(name) => html`<ha-list-item>${name}</ha-list-item>`
|
||||
<ha-list-base>
|
||||
${Object.entries(this.ranges!).map(
|
||||
([name, range], index) => html`
|
||||
<ha-list-item-button
|
||||
.range=${range}
|
||||
.index=${index}
|
||||
@click=${this._setDateRange}
|
||||
>
|
||||
<span slot="headline">${name}</span>
|
||||
</ha-list-item-button>
|
||||
`
|
||||
)}
|
||||
</ha-list>
|
||||
</ha-list-base>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -343,11 +351,12 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
this._saveDateRangePreset(chip.range, chip.index);
|
||||
}
|
||||
|
||||
private _setDateRange(ev: HASSDomEvent<ActionDetail>) {
|
||||
const dateRange: [Date, Date] = Object.values(this.ranges!)[
|
||||
ev.detail.index
|
||||
];
|
||||
this._saveDateRangePreset(dateRange, ev.detail.index);
|
||||
private _setDateRange(
|
||||
ev: HASSDomCurrentTargetEvent<
|
||||
HTMLElement & { range: [Date, Date]; index: number }
|
||||
>
|
||||
) {
|
||||
this._saveDateRangePreset(ev.currentTarget.range, ev.currentTarget.index);
|
||||
}
|
||||
|
||||
private _saveDateRangePreset(range: [Date, Date], index: number) {
|
||||
|
||||
@@ -161,7 +161,8 @@ export abstract class HaDeviceAutomationPicker<
|
||||
return html`<ha-generic-picker
|
||||
.label=${this.label}
|
||||
.value=${value}
|
||||
.disabled=${!this._automations || this._automations.length === 0}
|
||||
.disabled=${this._automations?.length === 0}
|
||||
.loading=${this._automations === undefined}
|
||||
.getItems=${this._getItems(
|
||||
value,
|
||||
this._automations,
|
||||
|
||||
@@ -29,9 +29,9 @@ import type {
|
||||
} from "../../common/translations/localize";
|
||||
import { formattersContext, registriesContext } from "../../data/context";
|
||||
import type { HomeAssistantFormatters, ValueChangedEvent } from "../../types";
|
||||
import "../chips/ha-assist-chip";
|
||||
import "../chips/ha-chip-set";
|
||||
import "../chips/ha-input-chip";
|
||||
import "../ha-button";
|
||||
import "../ha-button-toggle-group";
|
||||
import "../ha-combo-box-item";
|
||||
import "../ha-generic-picker";
|
||||
@@ -121,6 +121,8 @@ export class HaEntityNamePicker extends LitElement {
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
@query("ha-button.add") private _addButton?: HTMLElement;
|
||||
|
||||
private _editIndex?: number;
|
||||
|
||||
connectedCallback(): void {
|
||||
@@ -159,7 +161,7 @@ export class HaEntityNamePicker extends LitElement {
|
||||
return html`
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
${this.label ? html`<label id="label">${this.label}</label>` : nothing}
|
||||
${
|
||||
this.allowCustom
|
||||
? html`
|
||||
@@ -264,7 +266,9 @@ export class HaEntityNamePicker extends LitElement {
|
||||
handle-selector="button.primary.action"
|
||||
filter=".add"
|
||||
>
|
||||
<ha-chip-set>
|
||||
<ha-chip-set
|
||||
aria-labelledby=${ifDefined(this.label ? "label" : undefined)}
|
||||
>
|
||||
${repeat(
|
||||
this._items,
|
||||
(item) => item,
|
||||
@@ -290,22 +294,16 @@ export class HaEntityNamePicker extends LitElement {
|
||||
`;
|
||||
}
|
||||
)}
|
||||
${
|
||||
this.disabled
|
||||
? nothing
|
||||
: html`
|
||||
<ha-assist-chip
|
||||
@click=${this._addItem}
|
||||
.disabled=${this.disabled}
|
||||
label=${this._localize(
|
||||
"ui.components.entity.entity-name-picker.add"
|
||||
)}
|
||||
class="add"
|
||||
>
|
||||
<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon>
|
||||
</ha-assist-chip>
|
||||
`
|
||||
}
|
||||
<ha-button
|
||||
class="add"
|
||||
size="s"
|
||||
appearance="filled"
|
||||
.disabled=${this.disabled}
|
||||
@click=${this._addItem}
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
|
||||
${this._localize("ui.common.add")}
|
||||
</ha-button>
|
||||
</ha-chip-set>
|
||||
</ha-sortable>
|
||||
${this._renderRestoreButton()}
|
||||
@@ -373,6 +371,10 @@ export class HaEntityNamePicker extends LitElement {
|
||||
const idx = parseInt((ev.target as HTMLElement).dataset.idx || "", 10);
|
||||
value.splice(idx, 1);
|
||||
this._setValue(value);
|
||||
if (!value.length) {
|
||||
await this.updateComplete;
|
||||
this._addButton?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private _pickerValueChanged(ev: ValueChangedEvent<string>): void {
|
||||
@@ -629,7 +631,7 @@ export class HaEntityNamePicker extends LitElement {
|
||||
|
||||
label {
|
||||
display: block;
|
||||
font-weight: 500;
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
}
|
||||
|
||||
.content {
|
||||
@@ -722,7 +724,8 @@ export class HaEntityNamePicker extends LitElement {
|
||||
|
||||
ha-input-helper-text {
|
||||
display: block;
|
||||
margin: var(--ha-space-2) 0 0;
|
||||
padding: 0;
|
||||
margin: var(--ha-space-1) 0 0;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -189,6 +189,10 @@ export class HaStatisticPicker extends LitElement {
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
@state() private _loadFailed = false;
|
||||
|
||||
private _statisticIdsRequest = 0;
|
||||
|
||||
@property({ attribute: "can-edit", type: Boolean }) public canEdit?: boolean;
|
||||
|
||||
public willUpdate(changedProps: PropertyValues<this>) {
|
||||
@@ -201,11 +205,36 @@ export class HaStatisticPicker extends LitElement {
|
||||
}
|
||||
|
||||
private async _getStatisticIds() {
|
||||
this.statisticIds = await getStatisticIds(this._api, this.statisticTypes);
|
||||
// Changing the statistic types starts a new request, and only the latest
|
||||
// one may update the picker
|
||||
const request = ++this._statisticIdsRequest;
|
||||
this._loadFailed = false;
|
||||
|
||||
let statisticIds: StatisticsMetaData[];
|
||||
try {
|
||||
statisticIds = await getStatisticIds(this._api, this.statisticTypes);
|
||||
} catch {
|
||||
if (request === this._statisticIdsRequest) {
|
||||
this._loadFailed = true;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (request !== this._statisticIdsRequest) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.statisticIds = statisticIds;
|
||||
this._picker?.requestUpdate();
|
||||
this._valueRenderer = this._makeValueRenderer();
|
||||
}
|
||||
|
||||
private _retryGetStatisticIds(ev: Event) {
|
||||
ev.stopPropagation();
|
||||
this._getStatisticIds();
|
||||
}
|
||||
|
||||
private _getItems = () =>
|
||||
this._getStatisticsItems(
|
||||
this._states,
|
||||
@@ -589,6 +618,12 @@ export class HaStatisticPicker extends LitElement {
|
||||
.rowRenderer=${this._rowRenderer}
|
||||
.getItems=${this._getItems}
|
||||
.getAdditionalItems=${this._getAdditionalItems}
|
||||
.loading=${!this._loadFailed && this.statisticIds === undefined}
|
||||
.loadError=${
|
||||
this._loadFailed
|
||||
? this._i18n.localize("ui.components.statistic-picker.load_failed")
|
||||
: undefined
|
||||
}
|
||||
.hideClearIcon=${this.hideClearIcon}
|
||||
.searchFn=${this._searchFn}
|
||||
.valueRenderer=${this._valueRenderer}
|
||||
@@ -598,6 +633,7 @@ export class HaStatisticPicker extends LitElement {
|
||||
"ui.components.statistic-picker.unknown"
|
||||
)}
|
||||
@value-changed=${this._valueChanged}
|
||||
@picker-retry=${this._retryGetStatisticIds}
|
||||
>
|
||||
</ha-generic-picker>
|
||||
`;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { customElement, property, state } from "lit/decorators";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { computeCssColor } from "../../common/color/compute-color";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import { computeStateDomain } from "../../common/entity/compute_state_domain";
|
||||
@@ -21,8 +22,10 @@ import { CLIMATE_HVAC_ACTION_TO_MODE } from "../../data/climate";
|
||||
import {
|
||||
brandsAccessTokenContext,
|
||||
connectionContext,
|
||||
uiContext,
|
||||
} from "../../data/context";
|
||||
import { isBrandUrl } from "../../util/brands-url";
|
||||
import type { HomeAssistantUI } from "../../types";
|
||||
import { darkBrandUrl, isBrandUrl } from "../../util/brands-url";
|
||||
import "../ha-state-icon";
|
||||
|
||||
@customElement("state-badge")
|
||||
@@ -56,6 +59,13 @@ export class StateBadge extends LitElement {
|
||||
// @ts-ignore read in willUpdate through changedProps only
|
||||
private _brandsAccessToken?: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: uiContext, subscribe: true })
|
||||
@transform<HomeAssistantUI, boolean | undefined>({
|
||||
transformer: (ui) => ui?.themes?.darkMode,
|
||||
})
|
||||
private _darkMode?: boolean;
|
||||
|
||||
@state() private _iconStyle: Record<string, string | undefined> = {};
|
||||
|
||||
connectedCallback(): void {
|
||||
@@ -141,7 +151,9 @@ export class StateBadge extends LitElement {
|
||||
!changedProps.has("stateColor") &&
|
||||
!changedProps.has("color") &&
|
||||
!changedProps.has("_connection") &&
|
||||
!changedProps.has("_brandsAccessToken")
|
||||
!changedProps.has("_brandsAccessToken") &&
|
||||
// Brand images have a dark variant, so the picture changes with the theme
|
||||
!changedProps.has("_darkMode")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -217,15 +229,17 @@ export class StateBadge extends LitElement {
|
||||
// Sign the image URL via the connection context so brand images
|
||||
// (/api/brands/...) get their access token. Without a way to sign, a brands
|
||||
// request would be rejected (and logged/blocked by core), so skip it until
|
||||
// we can sign.
|
||||
// we can sign. In dark mode, brand images (e.g. the integration icon of an
|
||||
// update entity) use their dark-optimized variant.
|
||||
private _resolveImageUrl(url: string | undefined): string {
|
||||
if (!url) {
|
||||
return "";
|
||||
}
|
||||
const themedUrl = this._darkMode ? darkBrandUrl(url) : url;
|
||||
if (this._connection) {
|
||||
return this._connection.hassUrl(url);
|
||||
return this._connection.hassUrl(themedUrl);
|
||||
}
|
||||
return isBrandUrl(url) ? "" : url;
|
||||
return isBrandUrl(themedUrl) ? "" : themedUrl;
|
||||
}
|
||||
|
||||
protected getClass() {
|
||||
|
||||
@@ -58,6 +58,10 @@ export class HaAnsiToHtml extends LitElement {
|
||||
// The hidden lines each expand row shows when clicked.
|
||||
private _expandGaps = new WeakMap<HTMLElement, HTMLDivElement[]>();
|
||||
|
||||
public get hasLines(): boolean {
|
||||
return !!this._pre?.childElementCount;
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`<pre class=${classMap({ wrap: !this.wrapDisabled })}></pre>`;
|
||||
}
|
||||
|
||||
@@ -245,15 +245,15 @@ export class HaAreasFloorsDisplayEditor extends LitElement {
|
||||
const newOrder: string[] = [];
|
||||
|
||||
for (const floorId of floorIds) {
|
||||
const isOnFloor = (areaId: string) =>
|
||||
(this._areas[areaId]?.floor_id ?? UNASSIGNED_FLOOR) === floorId;
|
||||
if ((currentFloorId ?? UNASSIGNED_FLOOR) === floorId) {
|
||||
newHidden.push(...(value.hidden ?? []));
|
||||
// Reordering returns the hidden areas of every floor, not just this one
|
||||
newHidden.push(...(value.hidden ?? []).filter(isOnFloor));
|
||||
newOrder.push(...(value.order ?? []));
|
||||
continue;
|
||||
}
|
||||
const hidden = oldHidden.filter((areaId) => {
|
||||
const id = this._areas[areaId]?.floor_id ?? UNASSIGNED_FLOOR;
|
||||
return id === floorId;
|
||||
});
|
||||
const hidden = oldHidden.filter(isOnFloor);
|
||||
if (hidden?.length) {
|
||||
newHidden.push(...hidden);
|
||||
}
|
||||
|
||||
@@ -26,10 +26,7 @@ import "./ha-sortable";
|
||||
|
||||
type ClockDatePartSection = "weekday" | "day" | "month" | "year" | "separator";
|
||||
|
||||
type ClockDateSeparatorPart = Extract<
|
||||
ClockCardDatePart,
|
||||
"separator-dash" | "separator-slash" | "separator-dot" | "separator-new-line"
|
||||
>;
|
||||
type ClockDateSeparatorPart = Extract<ClockCardDatePart, `separator-${string}`>;
|
||||
|
||||
const CLOCK_DATE_PART_SECTION_ORDER: readonly ClockDatePartSection[] = [
|
||||
"day",
|
||||
@@ -43,6 +40,7 @@ const CLOCK_DATE_SEPARATOR_VALUES: Record<ClockDateSeparatorPart, string> = {
|
||||
"separator-dash": "-",
|
||||
"separator-slash": "/",
|
||||
"separator-dot": ".",
|
||||
"separator-comma": ",",
|
||||
"separator-new-line": "",
|
||||
};
|
||||
|
||||
|
||||
@@ -5,10 +5,12 @@ import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { mainWindow } from "../common/dom/get_main_window";
|
||||
import { formatNumber } from "../common/number/format_number";
|
||||
import { blankBeforeUnit } from "../common/translations/blank_before_unit";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import type { FrontendLocaleData } from "../data/translation";
|
||||
|
||||
declare global {
|
||||
@@ -43,6 +45,8 @@ export class HaControlSlider extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public locale?: FrontendLocaleData;
|
||||
|
||||
@state() @consumeLocalize() private _localize?: LocalizeFunc;
|
||||
|
||||
@property({ type: Boolean, reflect: true })
|
||||
public disabled = false;
|
||||
|
||||
@@ -139,12 +143,28 @@ export class HaControlSlider extends LitElement {
|
||||
this.setupListeners();
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>) {
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
if (changedProps.has("value") || changedProps.has("roundValue")) {
|
||||
const valuenow = this._displayedValue(this.value ?? 0);
|
||||
this.setAttribute("aria-valuenow", valuenow.toString());
|
||||
this.setAttribute("aria-valuetext", this._formatValue(valuenow));
|
||||
if (
|
||||
changedProps.has("value") ||
|
||||
changedProps.has("roundValue") ||
|
||||
changedProps.has("_localize")
|
||||
) {
|
||||
// An unknown value must not be announced as the minimum.
|
||||
if (this.value == null) {
|
||||
this.removeAttribute("aria-valuenow");
|
||||
} else {
|
||||
this.setAttribute(
|
||||
"aria-valuenow",
|
||||
this._displayedValue(this.value).toString()
|
||||
);
|
||||
}
|
||||
const valuetext = this._ariaValueText();
|
||||
if (valuetext) {
|
||||
this.setAttribute("aria-valuetext", valuetext);
|
||||
} else {
|
||||
this.removeAttribute("aria-valuetext");
|
||||
}
|
||||
}
|
||||
if (changedProps.has("min")) {
|
||||
this.setAttribute("aria-valuemin", this.min.toString());
|
||||
@@ -312,6 +332,13 @@ export class HaControlSlider extends LitElement {
|
||||
return Math.max(Math.min(1, (x - offset) / total), 0);
|
||||
};
|
||||
|
||||
private _ariaValueText() {
|
||||
if (this.value == null) {
|
||||
return this._localize?.("state.default.unknown");
|
||||
}
|
||||
return this._formatValue(this._displayedValue(this.value));
|
||||
}
|
||||
|
||||
private _formatValue(value: number) {
|
||||
const formattedValue = formatNumber(value, this.locale);
|
||||
|
||||
@@ -349,7 +376,8 @@ export class HaControlSlider extends LitElement {
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const valuenow = this._displayedValue(this.value ?? 0);
|
||||
const valuenow =
|
||||
this.value != null ? this._displayedValue(this.value) : undefined;
|
||||
return html`
|
||||
<div
|
||||
class="container${classMap({
|
||||
@@ -365,8 +393,8 @@ export class HaControlSlider extends LitElement {
|
||||
role="slider"
|
||||
tabindex="0"
|
||||
aria-label=${ifDefined(this.label)}
|
||||
aria-valuenow=${valuenow.toString()}
|
||||
aria-valuetext=${this._formatValue(valuenow)}
|
||||
aria-valuenow=${ifDefined(valuenow?.toString())}
|
||||
aria-valuetext=${ifDefined(this._ariaValueText() || undefined)}
|
||||
aria-valuemin=${ifDefined(
|
||||
this.min != null ? this.min.toString() : undefined
|
||||
)}
|
||||
@@ -395,7 +423,7 @@ export class HaControlSlider extends LitElement {
|
||||
class=${classMap({
|
||||
"slider-track-bar": true,
|
||||
[this.mode ?? "start"]: true,
|
||||
"show-handle": this.showHandle,
|
||||
"show-handle": this.showHandle && this.value != null,
|
||||
})}
|
||||
></div>
|
||||
`
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import { mdiPlus } from "@mdi/js";
|
||||
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
@@ -26,6 +28,10 @@ import "./chips/ha-input-chip";
|
||||
import "./ha-combo-box-item";
|
||||
import "./ha-domain-icon";
|
||||
import "./ha-generic-picker";
|
||||
import type { HaGenericPicker } from "./ha-generic-picker";
|
||||
import "./ha-button";
|
||||
import "./ha-svg-icon";
|
||||
import "./ha-input-helper-text";
|
||||
import type {
|
||||
PickerComboBoxItem,
|
||||
PickerComboBoxSearchFn,
|
||||
@@ -82,6 +88,8 @@ export class HaEntityTypePicker extends LitElement {
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: ContextType<typeof statesContext>;
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
private _titlesLoaded = false;
|
||||
|
||||
protected willUpdate() {
|
||||
@@ -237,40 +245,13 @@ export class HaEntityTypePicker extends LitElement {
|
||||
const localize = this._i18n?.localize;
|
||||
const value = this.value ?? [];
|
||||
const chipLabels = localize ? this._chipLabels(localize, value) : undefined;
|
||||
|
||||
const addLabel = localize?.("ui.common.add");
|
||||
return html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
${
|
||||
value.length && chipLabels
|
||||
? html`
|
||||
<ha-chip-set>
|
||||
${repeat(
|
||||
value,
|
||||
(key) => key,
|
||||
(key) => {
|
||||
const label = chipLabels.get(key)!;
|
||||
return html`
|
||||
<ha-input-chip
|
||||
data-key=${key}
|
||||
.label=${label}
|
||||
.disabled=${this.disabled}
|
||||
@remove=${this._removeItem}
|
||||
selected
|
||||
>
|
||||
${this._renderIcon(key, "icon")} ${label}
|
||||
</ha-input-chip>
|
||||
`;
|
||||
}
|
||||
)}
|
||||
</ha-chip-set>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${this.label ? html`<label id="label">${this.label}</label>` : nothing}
|
||||
<ha-generic-picker
|
||||
.helper=${this.helper}
|
||||
.label=${this.label}
|
||||
.disabled=${this.disabled}
|
||||
.value=${""}
|
||||
.addButtonLabel=${localize?.("ui.components.entity-type-picker.add")}
|
||||
.getItems=${this._getItems}
|
||||
.rowRenderer=${this._rowRenderer}
|
||||
.searchFn=${this._searchFn}
|
||||
@@ -278,10 +259,53 @@ export class HaEntityTypePicker extends LitElement {
|
||||
.emptyLabel=${localize?.("ui.components.entity-type-picker.no_types")}
|
||||
no-sort
|
||||
@value-changed=${this._itemAdded}
|
||||
></ha-generic-picker>
|
||||
>
|
||||
<ha-chip-set
|
||||
slot="field"
|
||||
aria-labelledby=${ifDefined(this.label ? "label" : undefined)}
|
||||
>
|
||||
${repeat(
|
||||
value,
|
||||
(key) => key,
|
||||
(key) => {
|
||||
const label = chipLabels?.get(key) ?? key;
|
||||
return html`
|
||||
<ha-input-chip
|
||||
data-key=${key}
|
||||
.label=${label}
|
||||
.disabled=${this.disabled}
|
||||
@remove=${this._removeItem}
|
||||
selected
|
||||
>
|
||||
${this._renderIcon(key, "icon")} ${label}
|
||||
</ha-input-chip>
|
||||
`;
|
||||
}
|
||||
)}
|
||||
<ha-button
|
||||
size="s"
|
||||
appearance="filled"
|
||||
.disabled=${this.disabled}
|
||||
@click=${this._openPicker}
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
|
||||
${addLabel}
|
||||
</ha-button>
|
||||
</ha-chip-set>
|
||||
</ha-generic-picker>
|
||||
${
|
||||
this.helper
|
||||
? html`<ha-input-helper-text>${this.helper}</ha-input-helper-text>`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _openPicker(ev: Event) {
|
||||
ev.stopPropagation();
|
||||
this._picker?.open();
|
||||
}
|
||||
|
||||
private _itemAdded(ev: CustomEvent<{ value?: string }>) {
|
||||
ev.stopPropagation();
|
||||
const key = ev.detail.value;
|
||||
@@ -320,7 +344,15 @@ export class HaEntityTypePicker extends LitElement {
|
||||
width: 100%;
|
||||
}
|
||||
ha-chip-set {
|
||||
padding: var(--ha-space-2) 0;
|
||||
background-color: var(--mdc-text-field-fill-color);
|
||||
border-bottom: 1px solid var(--ha-color-border-neutral-normal);
|
||||
border-top-right-radius: var(--ha-border-radius-sm);
|
||||
border-top-left-radius: var(--ha-border-radius-sm);
|
||||
padding: var(--ha-space-3);
|
||||
}
|
||||
ha-input-helper-text {
|
||||
padding: 0;
|
||||
margin-top: var(--ha-space-1);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { SelectedDetail } from "@material/mwc-list";
|
||||
import { mdiFilterVariantRemove } from "@mdi/js";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
@@ -12,6 +11,11 @@ import {
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { arrayWith, arrayWithout } from "../common/array/array-with";
|
||||
import type {
|
||||
HASSDomCurrentTargetEvent,
|
||||
HASSDomEvent,
|
||||
} from "../common/dom/fire_event";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { deepEqual } from "../common/util/deep-equal";
|
||||
import type { Blueprints } from "../data/blueprint";
|
||||
@@ -19,11 +23,12 @@ import { fetchBlueprints } from "../data/blueprint";
|
||||
import { apiContext } from "../data/context";
|
||||
import type { RelatedResult } from "../data/search";
|
||||
import { findRelated } from "../data/search";
|
||||
import { haStyleScrollbar } from "../resources/styles";
|
||||
import "./ha-check-list-item";
|
||||
import "./ha-expansion-panel";
|
||||
import "./ha-icon-button";
|
||||
import "./ha-list";
|
||||
import "./item/ha-list-item-option";
|
||||
import type { HaListItemOption } from "./item/ha-list-item-option";
|
||||
import "./list/ha-list-selectable";
|
||||
import type { HaListSelectable } from "./list/ha-list-selectable";
|
||||
|
||||
@customElement("ha-filter-blueprints")
|
||||
export class HaFilterBlueprints extends LitElement {
|
||||
@@ -88,23 +93,30 @@ export class HaFilterBlueprints extends LitElement {
|
||||
${
|
||||
this._blueprints
|
||||
? html`
|
||||
<ha-list
|
||||
@selected=${this._blueprintsSelected}
|
||||
<ha-list-selectable
|
||||
multi
|
||||
class="ha-scrollbar"
|
||||
aria-label=${this._localize(
|
||||
"ui.panel.config.blueprint.caption"
|
||||
)}
|
||||
@ha-list-item-selected=${this._handleItemToggled}
|
||||
@ha-list-item-deselected=${this._handleItemToggled}
|
||||
>
|
||||
${Object.entries(this._blueprints).map(
|
||||
([id, blueprint]) =>
|
||||
"error" in blueprint
|
||||
? nothing
|
||||
: html`<ha-check-list-item
|
||||
: html`<ha-list-item-option
|
||||
appearance="checkbox"
|
||||
selection-position="end"
|
||||
.value=${id}
|
||||
.selected=${(this.value || []).includes(id)}
|
||||
.selected=${this.value?.includes(id) ?? false}
|
||||
>
|
||||
${blueprint.metadata.name || id}
|
||||
</ha-check-list-item>`
|
||||
<span slot="headline"
|
||||
>${blueprint.metadata.name || id}</span
|
||||
>
|
||||
</ha-list-item-option>`
|
||||
)}
|
||||
</ha-list>
|
||||
</ha-list-selectable>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
@@ -126,28 +138,20 @@ export class HaFilterBlueprints extends LitElement {
|
||||
this.expanded = ev.detail.expanded;
|
||||
}
|
||||
|
||||
private async _blueprintsSelected(
|
||||
ev: CustomEvent<SelectedDetail<Set<number>>>
|
||||
private _handleItemToggled(
|
||||
ev: HASSDomEvent<number> & HASSDomCurrentTargetEvent<HaListSelectable>
|
||||
) {
|
||||
const blueprints = this._blueprints!;
|
||||
|
||||
if (!ev.detail.index.size) {
|
||||
fireEvent(this, "data-table-filter-changed", {
|
||||
value: [],
|
||||
items: undefined,
|
||||
});
|
||||
this.value = [];
|
||||
const blueprintId = (
|
||||
ev.currentTarget.items[ev.detail] as HaListItemOption | undefined
|
||||
)?.value;
|
||||
if (!blueprintId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const value: string[] = [];
|
||||
|
||||
for (const index of ev.detail.index) {
|
||||
const blueprintId = Object.keys(blueprints)[index];
|
||||
value.push(blueprintId);
|
||||
}
|
||||
|
||||
this.value = value;
|
||||
this.value =
|
||||
ev.type === "ha-list-item-selected"
|
||||
? arrayWith(this.value, blueprintId)
|
||||
: arrayWithout(this.value, blueprintId);
|
||||
}
|
||||
|
||||
private async _findRelated() {
|
||||
@@ -202,10 +206,14 @@ export class HaFilterBlueprints extends LitElement {
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
haStyleScrollbar,
|
||||
filterPanelStyles,
|
||||
css`
|
||||
ha-list {
|
||||
ha-list-selectable {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
ha-list-selectable::part(base) {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user