mirror of
https://github.com/home-assistant/frontend.git
synced 2025-11-08 02:19:43 +00:00
Compare commits
307 Commits
copilot/ad
...
logs-front
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1afcfcd32 | ||
|
|
29e6ada90e | ||
|
|
ff1745fccc | ||
|
|
59aaf86104 | ||
|
|
52bc692c79 | ||
|
|
29de405912 | ||
|
|
a723171ef2 | ||
|
|
cfe193cf60 | ||
|
|
a8e6557b09 | ||
|
|
a517aabdd8 | ||
|
|
10c8828aa5 | ||
|
|
5801ce944c | ||
|
|
79ad9dbf44 | ||
|
|
9814533d47 | ||
|
|
bdb6c684c0 | ||
|
|
0046167f5c | ||
|
|
5266f0d761 | ||
|
|
cc5c0d04c4 | ||
|
|
7f3d5f557f | ||
|
|
9b48cd7737 | ||
|
|
11c6f6ec78 | ||
|
|
cb0f59b26d | ||
|
|
c89fc35578 | ||
|
|
f03cd9c239 | ||
|
|
19a4e37933 | ||
|
|
76514babd5 | ||
|
|
b6abbdafb8 | ||
|
|
d35e6c0092 | ||
|
|
5c2ee54dec | ||
|
|
1dfca76c81 | ||
|
|
fd7f028fbf | ||
|
|
3f7283b1af | ||
|
|
d35323ac52 | ||
|
|
06475382e8 | ||
|
|
b60dd7f15d | ||
|
|
b77e65fabd | ||
|
|
cea691a04e | ||
|
|
50df2a34cd | ||
|
|
e6c0a84994 | ||
|
|
b03fa4bdc5 | ||
|
|
058cecc124 | ||
|
|
a5f058a7eb | ||
|
|
655c2ff3c2 | ||
|
|
e1b0a3e737 | ||
|
|
d59d436080 | ||
|
|
0fe0bf12f2 | ||
|
|
f5a3877f47 | ||
|
|
31d04f5338 | ||
|
|
4f7d223aa7 | ||
|
|
484c60073d | ||
|
|
0e1ab1a60c | ||
|
|
cef11e0c18 | ||
|
|
55e75e80d2 | ||
|
|
126a78ec8a | ||
|
|
063af39f0f | ||
|
|
132c4c8201 | ||
|
|
4c08e960f1 | ||
|
|
a8020256de | ||
|
|
2ea57c33ae | ||
|
|
db1408666c | ||
|
|
260288a061 | ||
|
|
45fd685913 | ||
|
|
896d76b218 | ||
|
|
cec24117dc | ||
|
|
34006d268b | ||
|
|
54c03d91df | ||
|
|
52a56a1c4e | ||
|
|
e49feeb4aa | ||
|
|
a0c30e433a | ||
|
|
354ce027eb | ||
|
|
5c224a942d | ||
|
|
0efa4f81d4 | ||
|
|
3ad2f35f29 | ||
|
|
7a21d5f7bc | ||
|
|
33226587e6 | ||
|
|
bd2673f311 | ||
|
|
cecadde497 | ||
|
|
494b8811d0 | ||
|
|
4e0a49b3da | ||
|
|
3145fed5dc | ||
|
|
3dd040fdc7 | ||
|
|
e3abe9736c | ||
|
|
fe41e72774 | ||
|
|
7078ef52d4 | ||
|
|
f1c9802ee3 | ||
|
|
35697e3f94 | ||
|
|
8ea7ad3026 | ||
|
|
73747fbedc | ||
|
|
aaa92bd354 | ||
|
|
5f75fc5bcb | ||
|
|
5fa44548c3 | ||
|
|
1945c11621 | ||
|
|
930575d292 | ||
|
|
0147dbab00 | ||
|
|
13ace24b83 | ||
|
|
616333591a | ||
|
|
8f5875c30f | ||
|
|
517cd49f35 | ||
|
|
25d9fc94b2 | ||
|
|
7b188759e3 | ||
|
|
76772d1098 | ||
|
|
6052745ca0 | ||
|
|
89b9780345 | ||
|
|
a607edca96 | ||
|
|
52eb3d8063 | ||
|
|
1361fc36bf | ||
|
|
505ef2bd11 | ||
|
|
c0cc66c1ab | ||
|
|
7cfbc521c7 | ||
|
|
e064ce56cc | ||
|
|
8d688aa3a9 | ||
|
|
d122483449 | ||
|
|
f17bbc3f79 | ||
|
|
c88f8fcce0 | ||
|
|
8efabde916 | ||
|
|
e821e1ec83 | ||
|
|
dc7516da94 | ||
|
|
a545a377a7 | ||
|
|
3634dbcbbf | ||
|
|
75af4f939e | ||
|
|
453a2ac7f3 | ||
|
|
8fbd0226fc | ||
|
|
2a8d935601 | ||
|
|
a6328fb6d7 | ||
|
|
a78b61006f | ||
|
|
d506aa23b6 | ||
|
|
48b4df43ab | ||
|
|
8cdcd9cb55 | ||
|
|
a1e2ac1d99 | ||
|
|
8ecddbc42c | ||
|
|
6f70ef52a5 | ||
|
|
7dff02d7c8 | ||
|
|
8bbd7a6a06 | ||
|
|
5c73a06f76 | ||
|
|
9943dae82c | ||
|
|
70bf049df0 | ||
|
|
f9d9fbb7f0 | ||
|
|
9cb84d3f37 | ||
|
|
c1bcf27cf8 | ||
|
|
164ec2a9b5 | ||
|
|
20001a551c | ||
|
|
b7f85bf733 | ||
|
|
b303e9441b | ||
|
|
8f4bd0f620 | ||
|
|
596346bf59 | ||
|
|
769cea92aa | ||
|
|
f825016514 | ||
|
|
c6fd45bd6a | ||
|
|
6c4f4af75c | ||
|
|
cd5c3ef2f6 | ||
|
|
636a6fa02e | ||
|
|
21b83426d6 | ||
|
|
c139ec22f9 | ||
|
|
a6ef3a26da | ||
|
|
221ca56121 | ||
|
|
4e6e3629a8 | ||
|
|
fe94ae0243 | ||
|
|
8a1a22d4bd | ||
|
|
153a578986 | ||
|
|
04bb10d0a2 | ||
|
|
35e52de2c1 | ||
|
|
b0862fddaa | ||
|
|
77735f5310 | ||
|
|
e388756533 | ||
|
|
e9ca9bb781 | ||
|
|
e48918442c | ||
|
|
52f37f41f0 | ||
|
|
4687006fec | ||
|
|
aca4ca3066 | ||
|
|
3a2c00622a | ||
|
|
699c25a6c3 | ||
|
|
1ad226d608 | ||
|
|
992a4cd98a | ||
|
|
fd217f8ea5 | ||
|
|
dede14e578 | ||
|
|
fa7aca67e5 | ||
|
|
6abdfa6d5c | ||
|
|
0a70e2abda | ||
|
|
1ec589e9b6 | ||
|
|
2d2b5633c4 | ||
|
|
76df75c306 | ||
|
|
027ded61c2 | ||
|
|
a718589ba0 | ||
|
|
5b5dc9d853 | ||
|
|
2a49b5e15a | ||
|
|
fa4dd1c5ea | ||
|
|
37a3af2e8b | ||
|
|
fbfcef1573 | ||
|
|
4eecd37aaf | ||
|
|
c798521ab8 | ||
|
|
e432f0a8ee | ||
|
|
e3a1d0abe2 | ||
|
|
8080ba696c | ||
|
|
7bd8f321a4 | ||
|
|
4e958302b4 | ||
|
|
8a42d15bde | ||
|
|
ef0da0a7ee | ||
|
|
ae053c20b0 | ||
|
|
5f71938d60 | ||
|
|
82ac26b326 | ||
|
|
80b92b9813 | ||
|
|
904a083f61 | ||
|
|
d75ee09d55 | ||
|
|
a8e0d506b6 | ||
|
|
01dd731622 | ||
|
|
dc20702d36 | ||
|
|
f32ca9be29 | ||
|
|
8c4c4157a8 | ||
|
|
c8419d4c3d | ||
|
|
089316b8ae | ||
|
|
8d03ac5f64 | ||
|
|
e0e1f6f920 | ||
|
|
d4c98cae3a | ||
|
|
46d0eb4f44 | ||
|
|
07812f8d84 | ||
|
|
96f54d348f | ||
|
|
6084ab116f | ||
|
|
6b7acd8d3b | ||
|
|
e35b155c66 | ||
|
|
437d02c12f | ||
|
|
9cd74fbff8 | ||
|
|
33a7aacd83 | ||
|
|
39546615bb | ||
|
|
be51cbc944 | ||
|
|
77874aa2d7 | ||
|
|
4808463d5f | ||
|
|
5fb3cab247 | ||
|
|
d1093b187f | ||
|
|
fd7f0d3841 | ||
|
|
36aa74e4a5 | ||
|
|
938128d1c3 | ||
|
|
2a5d4ac578 | ||
|
|
be63ff7702 | ||
|
|
132c68bf20 | ||
|
|
16499bbd6b | ||
|
|
c7eddfed8f | ||
|
|
150842e431 | ||
|
|
9eb5360a68 | ||
|
|
e9e32c7d91 | ||
|
|
c83d760e82 | ||
|
|
489b7f9227 | ||
|
|
ad2ba63155 | ||
|
|
29bc894dbd | ||
|
|
3e749ec085 | ||
|
|
ee2ec00069 | ||
|
|
0aa2941868 | ||
|
|
46cd1d5156 | ||
|
|
07a5c41fd4 | ||
|
|
4ad3c553d5 | ||
|
|
d40cc448a5 | ||
|
|
e2f3f9d348 | ||
|
|
98d44950f8 | ||
|
|
8ae9edb1ef | ||
|
|
84c4396c13 | ||
|
|
2b937a30e3 | ||
|
|
b7815bfd86 | ||
|
|
d94fa03411 | ||
|
|
0a7007ef9e | ||
|
|
dd12136dee | ||
|
|
6e2f89fe3d | ||
|
|
092085b9af | ||
|
|
1c06eb8661 | ||
|
|
c7e87b06b5 | ||
|
|
38c738c199 | ||
|
|
e899587307 | ||
|
|
c9feb0b75f | ||
|
|
10718c35d1 | ||
|
|
4dc6a37bad | ||
|
|
ac49fc7aba | ||
|
|
e4f008800b | ||
|
|
0b0ffd7bab | ||
|
|
dfa77526a2 | ||
|
|
9a3bd6c613 | ||
|
|
1161de5746 | ||
|
|
9df8e20391 | ||
|
|
11047a9c95 | ||
|
|
18fa66f61c | ||
|
|
758a048f34 | ||
|
|
ee0fc360b0 | ||
|
|
4012f95ec1 | ||
|
|
0336ce4606 | ||
|
|
9ba36ab7e2 | ||
|
|
fe7a08a1b0 | ||
|
|
87a8f9cedc | ||
|
|
01df7e20ca | ||
|
|
d181219522 | ||
|
|
6ae24b8135 | ||
|
|
8e009f24f9 | ||
|
|
53031f44ac | ||
|
|
af5a988457 | ||
|
|
bab0391a19 | ||
|
|
444123c47e | ||
|
|
f123d34046 | ||
|
|
1b40f99f68 | ||
|
|
b314b3ed2b | ||
|
|
59b8932969 | ||
|
|
107af753ec | ||
|
|
1f0acb3046 | ||
|
|
431e533929 | ||
|
|
02c845cbc6 | ||
|
|
628111ed20 | ||
|
|
e825a9c02f | ||
|
|
7a35bddf36 | ||
|
|
ad69270af8 | ||
|
|
404edf9483 | ||
|
|
a166b4e9b6 | ||
|
|
7a285f11db |
4
.github/workflows/cast_deployment.yaml
vendored
4
.github/workflows/cast_deployment.yaml
vendored
@@ -26,7 +26,7 @@ jobs:
|
||||
ref: dev
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
ref: master
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
|
||||
12
.github/workflows/ci.yaml
vendored
12
.github/workflows/ci.yaml
vendored
@@ -26,7 +26,7 @@ jobs:
|
||||
- name: Check out files from GitHub
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -60,7 +60,7 @@ jobs:
|
||||
- name: Check out files from GitHub
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
- name: Check out files from GitHub
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -89,7 +89,7 @@ jobs:
|
||||
env:
|
||||
IS_TEST: "true"
|
||||
- name: Upload bundle stats
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: frontend-bundle-stats
|
||||
path: build/stats/*.json
|
||||
@@ -102,7 +102,7 @@ jobs:
|
||||
- name: Check out files from GitHub
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -113,7 +113,7 @@ jobs:
|
||||
env:
|
||||
IS_TEST: "true"
|
||||
- name: Upload bundle stats
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: supervisor-bundle-stats
|
||||
path: build/stats/*.json
|
||||
|
||||
6
.github/workflows/codeql-analysis.yml
vendored
6
.github/workflows/codeql-analysis.yml
vendored
@@ -36,14 +36,14 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@f443b600d91635bebf5b0d9ebc620189c0d6fba5 # v4.30.8
|
||||
uses: github/codeql-action/init@0499de31b99561a6d14a36a5f662c2a54f91beee # v4.31.2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@f443b600d91635bebf5b0d9ebc620189c0d6fba5 # v4.30.8
|
||||
uses: github/codeql-action/autobuild@0499de31b99561a6d14a36a5f662c2a54f91beee # v4.31.2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
@@ -57,4 +57,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@f443b600d91635bebf5b0d9ebc620189c0d6fba5 # v4.30.8
|
||||
uses: github/codeql-action/analyze@0499de31b99561a6d14a36a5f662c2a54f91beee # v4.31.2
|
||||
|
||||
4
.github/workflows/demo_deployment.yaml
vendored
4
.github/workflows/demo_deployment.yaml
vendored
@@ -27,7 +27,7 @@ jobs:
|
||||
ref: dev
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
ref: master
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
|
||||
2
.github/workflows/design_deployment.yaml
vendored
2
.github/workflows/design_deployment.yaml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
|
||||
2
.github/workflows/design_preview.yaml
vendored
2
.github/workflows/design_preview.yaml
vendored
@@ -24,7 +24,7 @@ jobs:
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
|
||||
6
.github/workflows/nightly.yaml
vendored
6
.github/workflows/nightly.yaml
vendored
@@ -28,7 +28,7 @@ jobs:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -57,14 +57,14 @@ jobs:
|
||||
run: tar -czvf translations.tar.gz translations
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: wheels
|
||||
path: dist/home_assistant_frontend*.whl
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload translations
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: translations
|
||||
path: translations.tar.gz
|
||||
|
||||
2
.github/workflows/relative-ci.yaml
vendored
2
.github/workflows/relative-ci.yaml
vendored
@@ -17,7 +17,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Send bundle stats and build information to RelativeCI
|
||||
uses: relative-ci/agent-action@1707825cbfcc7452b2913d273414705415ae64d4 # v3.0.1
|
||||
uses: relative-ci/agent-action@8504826a02078b05756e4c07e380023cc2c4274a # v3.1.0
|
||||
with:
|
||||
key: ${{ secrets[format('RELATIVE_CI_KEY_{0}_{1}', matrix.bundle, matrix.build)] }}
|
||||
token: ${{ github.token }}
|
||||
|
||||
8
.github/workflows/release.yaml
vendored
8
.github/workflows/release.yaml
vendored
@@ -34,7 +34,7 @@ jobs:
|
||||
uses: home-assistant/actions/helpers/verify-version@master
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
|
||||
# home-assistant/wheels doesn't support SHA pinning
|
||||
- name: Build wheels
|
||||
uses: home-assistant/wheels@2025.09.1
|
||||
uses: home-assistant/wheels@2025.10.0
|
||||
with:
|
||||
abi: cp313
|
||||
tag: musllinux_1_2
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
- name: Checkout the repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
@@ -122,7 +122,7 @@ jobs:
|
||||
- name: Checkout the repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: yarn
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -5,6 +5,7 @@
|
||||
build/
|
||||
dist/
|
||||
/hass_frontend/
|
||||
/logs/dist/
|
||||
/translations/
|
||||
|
||||
# yarn
|
||||
|
||||
@@ -18,16 +18,16 @@ module.exports.sourceMapURL = () => {
|
||||
module.exports.ignorePackages = () => [];
|
||||
|
||||
// Files from NPM packages that we should replace with empty file
|
||||
module.exports.emptyPackages = ({ isHassioBuild }) =>
|
||||
module.exports.emptyPackages = ({ isHassioBuild, isLandingPageBuild }) =>
|
||||
[
|
||||
require.resolve("@vaadin/vaadin-material-styles/typography.js"),
|
||||
require.resolve("@vaadin/vaadin-material-styles/font-icons.js"),
|
||||
// Icons in supervisor conflict with icons in HA so we don't load.
|
||||
isHassioBuild &&
|
||||
(isHassioBuild || isLandingPageBuild) &&
|
||||
require.resolve(
|
||||
path.resolve(paths.root_dir, "src/components/ha-icon.ts")
|
||||
),
|
||||
isHassioBuild &&
|
||||
(isHassioBuild || isLandingPageBuild) &&
|
||||
require.resolve(
|
||||
path.resolve(paths.root_dir, "src/components/ha-icon-picker.ts")
|
||||
),
|
||||
@@ -327,6 +327,20 @@ module.exports.config = {
|
||||
};
|
||||
},
|
||||
|
||||
logs({ isProdBuild, latestBuild, isStatsBuild }) {
|
||||
return {
|
||||
name: "logs" + nameSuffix(latestBuild),
|
||||
entry: {
|
||||
entrypoint: path.resolve(paths.logs_dir, "src/entrypoint.ts"),
|
||||
},
|
||||
outputPath: outputPath(paths.logs_output_root, latestBuild),
|
||||
publicPath: publicPath(latestBuild),
|
||||
isProdBuild,
|
||||
latestBuild,
|
||||
isStatsBuild,
|
||||
};
|
||||
},
|
||||
|
||||
landingPage({ isProdBuild, latestBuild }) {
|
||||
return {
|
||||
name: "landing-page" + nameSuffix(latestBuild),
|
||||
@@ -337,6 +351,7 @@ module.exports.config = {
|
||||
publicPath: publicPath(latestBuild),
|
||||
isProdBuild,
|
||||
latestBuild,
|
||||
isLandingPageBuild: true,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -39,6 +39,13 @@ gulp.task(
|
||||
)
|
||||
);
|
||||
|
||||
gulp.task(
|
||||
"clean-logs",
|
||||
gulp.parallel("clean-translations", async () =>
|
||||
deleteSync([paths.logs_output_root, paths.build_dir])
|
||||
)
|
||||
);
|
||||
|
||||
gulp.task(
|
||||
"clean-landing-page",
|
||||
gulp.parallel("clean-translations", async () =>
|
||||
|
||||
@@ -245,6 +245,24 @@ gulp.task(
|
||||
)
|
||||
);
|
||||
|
||||
const LOGS_PAGE_ENTRIES = { "index.html": ["entrypoint"] };
|
||||
|
||||
gulp.task(
|
||||
"gen-pages-logs-dev",
|
||||
genPagesDevTask(LOGS_PAGE_ENTRIES, paths.logs_dir, paths.logs_output_root)
|
||||
);
|
||||
|
||||
gulp.task(
|
||||
"gen-pages-logs-prod",
|
||||
genPagesProdTask(
|
||||
LOGS_PAGE_ENTRIES,
|
||||
paths.logs_dir,
|
||||
paths.logs_output_root,
|
||||
paths.logs_output_latest,
|
||||
paths.logs_output_es5
|
||||
)
|
||||
);
|
||||
|
||||
const LANDING_PAGE_PAGE_ENTRIES = { "index.html": ["entrypoint"] };
|
||||
|
||||
gulp.task(
|
||||
|
||||
@@ -202,6 +202,16 @@ gulp.task("copy-static-gallery", async () => {
|
||||
copyMdiIcons(paths.gallery_output_static);
|
||||
});
|
||||
|
||||
gulp.task("copy-static-logs", async () => {
|
||||
// Copy app static files
|
||||
fs.copySync(polyPath("public/static"), paths.logs_output_static);
|
||||
|
||||
copyFonts(paths.logs_output_static);
|
||||
copyTranslations(paths.logs_output_static);
|
||||
copyLocaleData(paths.logs_output_static);
|
||||
copyMdiIcons(paths.logs_output_static);
|
||||
});
|
||||
|
||||
gulp.task("copy-static-landing-page", async () => {
|
||||
// Copy landing-page static files
|
||||
fs.copySync(
|
||||
|
||||
@@ -7,6 +7,7 @@ import "./download-translations.js";
|
||||
import "./entry-html.js";
|
||||
import "./fetch-nightly-translations.js";
|
||||
import "./gallery.js";
|
||||
import "./logs.js";
|
||||
import "./gather-static.js";
|
||||
import "./gen-icons-json.js";
|
||||
import "./hassio.js";
|
||||
|
||||
39
build-scripts/gulp/logs.js
Normal file
39
build-scripts/gulp/logs.js
Normal file
@@ -0,0 +1,39 @@
|
||||
import gulp from "gulp";
|
||||
import "./clean.js";
|
||||
import "./entry-html.js";
|
||||
import "./gather-static.js";
|
||||
import "./gen-icons-json.js";
|
||||
import "./translations.js";
|
||||
import "./rspack.js";
|
||||
|
||||
gulp.task(
|
||||
"develop-logs",
|
||||
gulp.series(
|
||||
async function setEnv() {
|
||||
process.env.NODE_ENV = "development";
|
||||
},
|
||||
"clean-logs",
|
||||
gulp.parallel(
|
||||
"gen-icons-json",
|
||||
"gen-pages-logs-dev",
|
||||
"build-translations",
|
||||
"build-locale-data"
|
||||
),
|
||||
"copy-static-logs",
|
||||
"rspack-dev-server-logs"
|
||||
)
|
||||
);
|
||||
|
||||
gulp.task(
|
||||
"build-logs",
|
||||
gulp.series(
|
||||
async function setEnv() {
|
||||
process.env.NODE_ENV = "production";
|
||||
},
|
||||
"clean-logs",
|
||||
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
|
||||
"copy-static-logs",
|
||||
"rspack-prod-logs",
|
||||
"gen-pages-logs-prod"
|
||||
)
|
||||
);
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
createGalleryConfig,
|
||||
createHassioConfig,
|
||||
createLandingPageConfig,
|
||||
createLogsConfig,
|
||||
} from "../rspack.cjs";
|
||||
|
||||
const bothBuilds = (createConfigFunc, params) => [
|
||||
@@ -204,6 +205,25 @@ gulp.task("rspack-prod-gallery", () =>
|
||||
)
|
||||
);
|
||||
|
||||
gulp.task("rspack-dev-server-logs", () =>
|
||||
runDevServer({
|
||||
compiler: rspack(
|
||||
createLogsConfig({ isProdBuild: false, latestBuild: true })
|
||||
),
|
||||
contentBase: paths.logs_output_root,
|
||||
port: 5647,
|
||||
})
|
||||
);
|
||||
|
||||
gulp.task("rspack-prod-logs", () =>
|
||||
prodBuild(
|
||||
bothBuilds(createLogsConfig, {
|
||||
isProdBuild: true,
|
||||
isStatsBuild: env.isStatsBuild(),
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
gulp.task("rspack-watch-landing-page", () => {
|
||||
// This command will run forever because we don't close compiler
|
||||
rspack(
|
||||
|
||||
@@ -59,5 +59,11 @@ module.exports = {
|
||||
hassio_output_es5: path.resolve(__dirname, "../hassio/build/frontend_es5"),
|
||||
hassio_publicPath: "/api/hassio/app",
|
||||
|
||||
logs_dir: path.resolve(__dirname, "../logs"),
|
||||
logs_output_root: path.resolve(__dirname, "../logs/dist"),
|
||||
logs_output_static: path.resolve(__dirname, "../logs/dist/static"),
|
||||
logs_output_latest: path.resolve(__dirname, "../logs/dist/frontend_latest"),
|
||||
logs_output_es5: path.resolve(__dirname, "../logs/dist/frontend_es5"),
|
||||
|
||||
translations_src: path.resolve(__dirname, "../src/translations"),
|
||||
};
|
||||
|
||||
@@ -41,6 +41,7 @@ const createRspackConfig = ({
|
||||
isStatsBuild,
|
||||
isTestBuild,
|
||||
isHassioBuild,
|
||||
isLandingPageBuild,
|
||||
dontHash,
|
||||
}) => {
|
||||
if (!dontHash) {
|
||||
@@ -168,7 +169,9 @@ const createRspackConfig = ({
|
||||
},
|
||||
}),
|
||||
new rspack.NormalModuleReplacementPlugin(
|
||||
new RegExp(bundle.emptyPackages({ isHassioBuild }).join("|")),
|
||||
new RegExp(
|
||||
bundle.emptyPackages({ isHassioBuild, isLandingPageBuild }).join("|")
|
||||
),
|
||||
path.resolve(paths.root_dir, "src/util/empty.js")
|
||||
),
|
||||
!isProdBuild && new LogStartCompilePlugin(),
|
||||
@@ -299,6 +302,11 @@ const createHassioConfig = ({
|
||||
const createGalleryConfig = ({ isProdBuild, latestBuild }) =>
|
||||
createRspackConfig(bundle.config.gallery({ isProdBuild, latestBuild }));
|
||||
|
||||
const createLogsConfig = ({ isProdBuild, latestBuild, isStatsBuild }) =>
|
||||
createRspackConfig(
|
||||
bundle.config.logs({ isProdBuild, latestBuild, isStatsBuild })
|
||||
);
|
||||
|
||||
const createLandingPageConfig = ({ isProdBuild, latestBuild }) =>
|
||||
createRspackConfig(bundle.config.landingPage({ isProdBuild, latestBuild }));
|
||||
|
||||
@@ -308,6 +316,7 @@ module.exports = {
|
||||
createCastConfig,
|
||||
createHassioConfig,
|
||||
createGalleryConfig,
|
||||
createLogsConfig,
|
||||
createRspackConfig,
|
||||
createLandingPageConfig,
|
||||
};
|
||||
|
||||
@@ -16,9 +16,9 @@ import {
|
||||
} from "../../../../src/common/auth/token_storage";
|
||||
import { atLeastVersion } from "../../../../src/common/config/version";
|
||||
import { toggleAttribute } from "../../../../src/common/dom/toggle_attribute";
|
||||
import "../../../../src/components/ha-button";
|
||||
import "../../../../src/components/ha-icon";
|
||||
import "../../../../src/components/ha-list";
|
||||
import "../../../../src/components/ha-button";
|
||||
import "../../../../src/components/ha-list-item";
|
||||
import "../../../../src/components/ha-svg-icon";
|
||||
import {
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
import { isStrategyDashboard } from "../../../../src/data/lovelace/config/types";
|
||||
import type { LovelaceViewConfig } from "../../../../src/data/lovelace/config/view";
|
||||
import "../../../../src/layouts/hass-loading-screen";
|
||||
import { generateDefaultViewConfig } from "../../../../src/panels/lovelace/common/generate-lovelace-config";
|
||||
import "./hc-layout";
|
||||
|
||||
@customElement("hc-cast")
|
||||
@@ -96,7 +95,9 @@ class HcCast extends LitElement {
|
||||
<ha-list @action=${this._handlePickView} activatable>
|
||||
${(
|
||||
this.lovelaceViews ?? [
|
||||
generateDefaultViewConfig({}, {}, {}, {}, () => ""),
|
||||
{
|
||||
title: "Home",
|
||||
},
|
||||
]
|
||||
).map(
|
||||
(view, idx) => html`
|
||||
|
||||
@@ -5,14 +5,14 @@ subtitle: Dialogs provide important prompts in a user flow.
|
||||
|
||||
# Material Design 3
|
||||
|
||||
Our dialogs are based on the latest version of Material Design. Please note that we have made some well-considered adjustments to these guideliness. Specs and guidelines can be found on its [website](https://m3.material.io/components/dialogs/overview).
|
||||
Our dialogs are based on the latest version of Material Design. Please note that we have made some well-considered adjustments to these guidelines. Specs and guidelines can be found on its [website](https://m3.material.io/components/dialogs/overview).
|
||||
|
||||
# Guidelines
|
||||
|
||||
## Design
|
||||
|
||||
- Dialogs have a max width of 560px. Alert and confirmation dialogs got a fixed width of 320px. If you need more width, consider a dedicated page instead.
|
||||
- The close X-icon is on the top left, on all screen sizes. Except for alert and confirmation dialogs, they only have buttons and no X-icon. This is different compared to the Material guideliness.
|
||||
- Dialogs have a max width of 560px. Alert and confirmation dialogs have a fixed width of 320px. If you need more width, consider a dedicated page instead.
|
||||
- The close X-icon is on the top left, on all screen sizes. Except for alert and confirmation dialogs, they only have buttons and no X-icon. This is different compared to the Material guidelines.
|
||||
- Dialogs can't be closed with ESC or clicked outside of the dialog when there is a form that the user needs to fill out. Instead it will animate "no" by a little shake.
|
||||
- Extra icon buttons are on the top right, for example help, settings and expand dialog. More than 2 icon buttons, they will be in an overflow menu.
|
||||
- The submit button is grouped with a cancel button at the bottom right, on all screen sizes. Fullscreen mobile dialogs have them sticky at the bottom.
|
||||
@@ -26,7 +26,7 @@ Our dialogs are based on the latest version of Material Design. Please note that
|
||||
|
||||
- A best practice is to always use a title, even if it is optional by Material guidelines.
|
||||
- People mainly read the title and a button. Put the most important information in those two.
|
||||
- Try to avoid user generated content in the title, this could make the title unreadable long.
|
||||
- Try to avoid user generated content in the title, this could make the title unreadably long.
|
||||
- If users become unsure, they read the description. Make sure this explains what will happen.
|
||||
- Strive for minimalism.
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ const SENSOR_DEVICE_CLASSES = [
|
||||
"pm1",
|
||||
"pm10",
|
||||
"pm25",
|
||||
"pm4",
|
||||
"power_factor",
|
||||
"power",
|
||||
"precipitation",
|
||||
|
||||
@@ -46,22 +46,9 @@ class HassioIngressView extends LitElement {
|
||||
|
||||
private _fetchDataTimeout?: number;
|
||||
|
||||
private _messageListener = (ev: MessageEvent) => {
|
||||
if (this._addon?.webui_ha_aware && ev.data?.type === "toggle-sidebar") {
|
||||
this._toggleMenu();
|
||||
}
|
||||
};
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
window.addEventListener("message", this._messageListener);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
|
||||
window.removeEventListener("message", this._messageListener);
|
||||
|
||||
if (this._sessionKeepAlive) {
|
||||
clearInterval(this._sessionKeepAlive);
|
||||
this._sessionKeepAlive = undefined;
|
||||
@@ -96,25 +83,17 @@ class HassioIngressView extends LitElement {
|
||||
</hass-subpage>`;
|
||||
}
|
||||
|
||||
// If webui_ha_aware is true, or if narrow or sidebar is always hidden,
|
||||
// don't render the header and just render the iframe
|
||||
if (
|
||||
this._addon.webui_ha_aware ||
|
||||
this.narrow ||
|
||||
this.hass.dockedSidebar === "always_hidden"
|
||||
) {
|
||||
return iframe;
|
||||
}
|
||||
|
||||
return html`<div class="header">
|
||||
<ha-icon-button
|
||||
.label=${this.hass.localize("ui.sidebar.sidebar_toggle")}
|
||||
.path=${mdiMenu}
|
||||
@click=${this._toggleMenu}
|
||||
></ha-icon-button>
|
||||
<div class="main-title">${this._addon.name}</div>
|
||||
</div>
|
||||
${iframe}`;
|
||||
return html`${this.narrow || this.hass.dockedSidebar === "always_hidden"
|
||||
? html`<div class="header">
|
||||
<ha-icon-button
|
||||
.label=${this.hass.localize("ui.sidebar.sidebar_toggle")}
|
||||
.path=${mdiMenu}
|
||||
@click=${this._toggleMenu}
|
||||
></ha-icon-button>
|
||||
<div class="main-title">${this._addon.name}</div>
|
||||
</div>
|
||||
${iframe}`
|
||||
: iframe}`;
|
||||
}
|
||||
|
||||
protected async firstUpdated(): Promise<void> {
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import "@material/mwc-linear-progress";
|
||||
import { type PropertyValues, css, html, nothing } from "lit";
|
||||
import { mdiOpenInNew } from "@mdi/js";
|
||||
import { css, html, nothing, type PropertyValues } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { extractSearchParam } from "../../src/common/url/search-params";
|
||||
import "../../src/components/ha-alert";
|
||||
import "../../src/components/ha-button";
|
||||
import "../../src/components/ha-fade-in";
|
||||
import "../../src/components/ha-spinner";
|
||||
import { haStyle } from "../../src/resources/styles";
|
||||
import "../../src/onboarding/onboarding-welcome-links";
|
||||
import "./components/landing-page-network";
|
||||
import "./components/landing-page-logs";
|
||||
import { extractSearchParam } from "../../src/common/url/search-params";
|
||||
import { onBoardingStyles } from "../../src/onboarding/styles";
|
||||
import "../../src/components/ha-svg-icon";
|
||||
import { makeDialogManager } from "../../src/dialogs/make-dialog-manager";
|
||||
import { LandingPageBaseElement } from "./landing-page-base-element";
|
||||
import "../../src/onboarding/onboarding-welcome-links";
|
||||
import { onBoardingStyles } from "../../src/onboarding/styles";
|
||||
import { haStyle } from "../../src/resources/styles";
|
||||
import "./components/landing-page-logs";
|
||||
import "./components/landing-page-network";
|
||||
import {
|
||||
getSupervisorNetworkInfo,
|
||||
pingSupervisor,
|
||||
type NetworkInfo,
|
||||
} from "./data/supervisor";
|
||||
import { LandingPageBaseElement } from "./landing-page-base-element";
|
||||
|
||||
export const ASSUME_CORE_START_SECONDS = 60;
|
||||
const SCHEDULE_CORE_CHECK_SECONDS = 1;
|
||||
@@ -94,16 +97,21 @@ class HaLandingPage extends LandingPageBaseElement {
|
||||
<ha-language-picker
|
||||
.value=${this.language}
|
||||
.label=${""}
|
||||
button-style
|
||||
native-name
|
||||
@value-changed=${this._languageChanged}
|
||||
inline-arrow
|
||||
></ha-language-picker>
|
||||
<a
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
variant="neutral"
|
||||
href="https://www.home-assistant.io/getting-started/onboarding/"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
>${this.localize("ui.panel.page-onboarding.help")}</a
|
||||
>
|
||||
${this.localize("ui.panel.page-onboarding.help")}
|
||||
<ha-svg-icon slot="end" .path=${mdiOpenInNew}></ha-svg-icon>
|
||||
</ha-button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -218,26 +226,8 @@ class HaLandingPage extends LandingPageBaseElement {
|
||||
ha-alert p {
|
||||
text-align: unset;
|
||||
}
|
||||
ha-language-picker {
|
||||
display: block;
|
||||
width: 200px;
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
overflow: hidden;
|
||||
--ha-select-height: 40px;
|
||||
--mdc-select-fill-color: none;
|
||||
--mdc-select-label-ink-color: var(--primary-text-color, #212121);
|
||||
--mdc-select-ink-color: var(--primary-text-color, #212121);
|
||||
--mdc-select-idle-line-color: transparent;
|
||||
--mdc-select-hover-line-color: transparent;
|
||||
--mdc-select-dropdown-icon-color: var(--primary-text-color, #212121);
|
||||
--mdc-shape-small: 0;
|
||||
}
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: var(--primary-text-color);
|
||||
margin-right: 16px;
|
||||
margin-inline-end: 16px;
|
||||
margin-inline-start: initial;
|
||||
.footer ha-svg-icon {
|
||||
--mdc-icon-size: var(--ha-space-5);
|
||||
}
|
||||
ha-fade-in {
|
||||
min-height: calc(100vh - 64px - 88px);
|
||||
|
||||
9
logs/.dockerignore
Normal file
9
logs/.dockerignore
Normal file
@@ -0,0 +1,9 @@
|
||||
dist/
|
||||
src/
|
||||
node_modules/
|
||||
*.md
|
||||
.git/
|
||||
.gitignore
|
||||
docker-compose.yaml
|
||||
backend/ha-logs-proxy
|
||||
backend/README.md
|
||||
47
logs/Dockerfile
Normal file
47
logs/Dockerfile
Normal file
@@ -0,0 +1,47 @@
|
||||
ARG BUILD_FROM
|
||||
FROM $BUILD_FROM AS base
|
||||
|
||||
# Install dependencies
|
||||
RUN apk add --no-cache \
|
||||
bash \
|
||||
jq \
|
||||
curl \
|
||||
go
|
||||
|
||||
# Install Home Assistant CLI
|
||||
ARG BUILD_ARCH
|
||||
ARG CLI_VERSION
|
||||
RUN curl -Lso /usr/bin/ha \
|
||||
"https://github.com/home-assistant/cli/releases/download/${CLI_VERSION}/ha_${BUILD_ARCH}" \
|
||||
&& chmod a+x /usr/bin/ha
|
||||
|
||||
# Build Go backend
|
||||
WORKDIR /app
|
||||
COPY backend/go.mod backend/go.sum* ./
|
||||
RUN go mod download || true
|
||||
|
||||
COPY backend/*.go ./
|
||||
RUN CGO_ENABLED=0 go build -o ha-logs-proxy .
|
||||
|
||||
# Final stage
|
||||
FROM $BUILD_FROM
|
||||
|
||||
# Install runtime dependencies
|
||||
RUN apk add --no-cache \
|
||||
bash \
|
||||
jq \
|
||||
curl
|
||||
|
||||
# Copy HA CLI from base
|
||||
COPY --from=base /usr/bin/ha /usr/bin/ha
|
||||
|
||||
# Copy Go backend
|
||||
COPY --from=base /app/ha-logs-proxy /usr/bin/ha-logs-proxy
|
||||
|
||||
WORKDIR /root
|
||||
|
||||
# Expose port for backend (5642 = LOGB)
|
||||
EXPOSE 5642
|
||||
|
||||
# Default command
|
||||
CMD ["/usr/bin/ha-logs-proxy"]
|
||||
113
logs/README.md
Normal file
113
logs/README.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# Home Assistant CLI Docker Container
|
||||
|
||||
A simple multi-architecture Docker container with the Home Assistant CLI installed.
|
||||
|
||||
## Development Usage
|
||||
|
||||
The CLI container is integrated into the `script/develop-logs` workflow. Both flags are required:
|
||||
|
||||
```bash
|
||||
# Start dev server with CLI container (requires remote_api add-on)
|
||||
script/develop-logs -c http://192.168.1.2 -t your_token_here
|
||||
```
|
||||
|
||||
When started with credentials, the container runs a Go backend that proxies HA CLI logs commands. The backend API is available at `http://localhost:5642`.
|
||||
|
||||
**Frontend Features:**
|
||||
- Dropdown menu to select log provider (core, supervisor, host, audio, dns, multicast)
|
||||
- Follow mode with WebSocket streaming (`ha core logs --follow`)
|
||||
- Manual refresh to fetch latest logs
|
||||
- Download logs as text file
|
||||
- Line wrapping toggle
|
||||
- Auto-scroll to bottom when following
|
||||
- Error display with retry
|
||||
|
||||
**API Endpoints:**
|
||||
|
||||
```bash
|
||||
# List all endpoints
|
||||
curl http://localhost:5642/api/logs
|
||||
|
||||
# Get static logs
|
||||
curl http://localhost:5642/api/logs/core
|
||||
curl http://localhost:5642/api/logs/supervisor
|
||||
|
||||
# Health check
|
||||
curl http://localhost:5642/health
|
||||
|
||||
# WebSocket streaming (requires websocat or browser)
|
||||
websocat ws://localhost:5642/api/logs/core/follow
|
||||
```
|
||||
|
||||
You can also execute HA CLI commands directly:
|
||||
|
||||
```bash
|
||||
docker exec -it ha-cli-dev ha info
|
||||
docker exec -it ha-cli-dev ha supervisor info
|
||||
```
|
||||
|
||||
Stop everything with Ctrl+C (both the dev server and backend will stop automatically).
|
||||
|
||||
### Getting API Token
|
||||
|
||||
1. Install the [remote_api add-on](https://github.com/home-assistant/addons/tree/master/remote_api) in Home Assistant
|
||||
2. Check the add-on logs for the generated token
|
||||
3. Use the token with the `-t` flag
|
||||
|
||||
## Build
|
||||
|
||||
### Local Build (Single Architecture)
|
||||
|
||||
```bash
|
||||
docker build \
|
||||
--build-arg BUILD_FROM=alpine:3.22 \
|
||||
--build-arg BUILD_ARCH=amd64 \
|
||||
--build-arg CLI_VERSION=4.42.0 \
|
||||
-t ha-cli:local \
|
||||
.
|
||||
```
|
||||
|
||||
### Multi-Architecture Build
|
||||
|
||||
The `build.yaml` configuration is designed for use with Home Assistant's build system. For local multi-arch builds, use Docker Buildx:
|
||||
|
||||
```bash
|
||||
docker buildx build \
|
||||
--platform linux/amd64,linux/arm64,linux/arm/v7 \
|
||||
--build-arg BUILD_FROM=alpine:3.22 \
|
||||
--build-arg CLI_VERSION=4.42.0 \
|
||||
-t ha-cli:latest \
|
||||
.
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Run CLI Commands
|
||||
|
||||
```bash
|
||||
docker run --rm ha-cli:local ha help
|
||||
docker run --rm ha-cli:local ha supervisor info
|
||||
```
|
||||
|
||||
### Interactive Shell
|
||||
|
||||
```bash
|
||||
docker run -it --rm ha-cli:local
|
||||
# Then run: ha <command>
|
||||
```
|
||||
|
||||
### With Docker Compose
|
||||
|
||||
```bash
|
||||
docker compose run --rm ha-cli ha help
|
||||
```
|
||||
|
||||
## Update CLI Version
|
||||
|
||||
Edit the `CLI_VERSION` in `build.yaml` or pass it as a build argument:
|
||||
|
||||
```bash
|
||||
docker build --build-arg CLI_VERSION=4.43.0 ...
|
||||
```
|
||||
|
||||
Check for latest versions at: https://github.com/home-assistant/cli/releases
|
||||
1
logs/backend/.gitignore
vendored
Normal file
1
logs/backend/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
ha-logs-proxy
|
||||
108
logs/backend/README.md
Normal file
108
logs/backend/README.md
Normal file
@@ -0,0 +1,108 @@
|
||||
# HA Logs Proxy Backend
|
||||
|
||||
A Go backend that proxies Home Assistant CLI logs commands through a secure HTTP API.
|
||||
|
||||
## Features
|
||||
|
||||
- Only allows `logs` commands (security-restricted)
|
||||
- GET endpoints for static logs
|
||||
- WebSocket endpoints for streaming logs (follow mode)
|
||||
- CORS enabled for frontend integration
|
||||
- Simple JSON API
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### GET /api/logs
|
||||
|
||||
List all available endpoints.
|
||||
|
||||
### GET /api/logs/core
|
||||
|
||||
Get Home Assistant core logs.
|
||||
|
||||
### GET /api/logs/supervisor
|
||||
|
||||
Get Supervisor logs.
|
||||
|
||||
### GET /api/logs/host
|
||||
|
||||
Get host system logs.
|
||||
|
||||
### GET /api/logs/audio
|
||||
|
||||
Get audio logs.
|
||||
|
||||
### GET /api/logs/dns
|
||||
|
||||
Get DNS logs.
|
||||
|
||||
### GET /api/logs/multicast
|
||||
|
||||
Get multicast logs.
|
||||
|
||||
### GET /health
|
||||
|
||||
Health check endpoint.
|
||||
|
||||
**Response format (all log endpoints):**
|
||||
|
||||
```json
|
||||
{
|
||||
"output": "log content here...",
|
||||
"error": "error message if any"
|
||||
}
|
||||
```
|
||||
|
||||
### WS /api/logs/*/follow
|
||||
|
||||
WebSocket endpoints for streaming logs in real-time.
|
||||
|
||||
Available endpoints:
|
||||
- `WS /api/logs/core/follow` - Stream core logs
|
||||
- `WS /api/logs/supervisor/follow` - Stream supervisor logs
|
||||
- `WS /api/logs/host/follow` - Stream host logs
|
||||
- `WS /api/logs/audio/follow` - Stream audio logs
|
||||
- `WS /api/logs/dns/follow` - Stream DNS logs
|
||||
- `WS /api/logs/multicast/follow` - Stream multicast logs
|
||||
|
||||
Each WebSocket message contains a single log line as plain text. The connection streams output from `ha {component} logs --follow` command.
|
||||
|
||||
## Running Locally
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go run main.go
|
||||
```
|
||||
|
||||
The server starts on port 5642 (LOGB) by default. Override with `PORT` environment variable:
|
||||
|
||||
```bash
|
||||
PORT=3000 go run main.go
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
go build -o ha-logs-proxy
|
||||
./ha-logs-proxy
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
# List endpoints
|
||||
curl http://localhost:5642/api/logs
|
||||
|
||||
# Get core logs
|
||||
curl http://localhost:5642/api/logs/core
|
||||
|
||||
# Get supervisor logs
|
||||
curl http://localhost:5642/api/logs/supervisor
|
||||
|
||||
# Health check
|
||||
curl http://localhost:5642/health
|
||||
```
|
||||
|
||||
## Docker Integration
|
||||
|
||||
The backend is designed to run in the same container as the HA CLI, sharing access to the `ha` command.
|
||||
5
logs/backend/go.mod
Normal file
5
logs/backend/go.mod
Normal file
@@ -0,0 +1,5 @@
|
||||
module github.com/home-assistant/frontend/logs/backend
|
||||
|
||||
go 1.24
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3
|
||||
2
logs/backend/go.sum
Normal file
2
logs/backend/go.sum
Normal file
@@ -0,0 +1,2 @@
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
372
logs/backend/main.go
Normal file
372
logs/backend/main.go
Normal file
@@ -0,0 +1,372 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type LogsResponse struct {
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true // Allow all origins (CORS)
|
||||
},
|
||||
}
|
||||
|
||||
func executeHACommand(args []string) (string, error) {
|
||||
cmd := exec.Command("ha", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
return string(output), err
|
||||
}
|
||||
|
||||
func streamHACommandToWS(conn *websocket.Conn, args []string) error {
|
||||
cmd := exec.Command("ha", args...)
|
||||
|
||||
// Get stdout pipe
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Start command
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Read and send output line by line
|
||||
scanner := bufio.NewScanner(stdout)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
|
||||
cmd.Process.Kill()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for command to finish
|
||||
if err := cmd.Wait(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
func handleCoreLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Execute ha core logs command
|
||||
output, err := executeHACommand([]string{"core", "logs"})
|
||||
|
||||
response := LogsResponse{
|
||||
Output: output,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.Error = err.Error()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
log.Printf("Error encoding response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSupervisorLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
output, err := executeHACommand([]string{"supervisor", "logs"})
|
||||
|
||||
response := LogsResponse{
|
||||
Output: output,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.Error = err.Error()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func handleHostLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
output, err := executeHACommand([]string{"host", "logs"})
|
||||
|
||||
response := LogsResponse{
|
||||
Output: output,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.Error = err.Error()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func handleAudioLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
output, err := executeHACommand([]string{"audio", "logs"})
|
||||
|
||||
response := LogsResponse{
|
||||
Output: output,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.Error = err.Error()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func handleDNSLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
output, err := executeHACommand([]string{"dns", "logs"})
|
||||
|
||||
response := LogsResponse{
|
||||
Output: output,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.Error = err.Error()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func handleMulticastLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
output, err := executeHACommand([]string{"multicast", "logs"})
|
||||
|
||||
response := LogsResponse{
|
||||
Output: output,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.Error = err.Error()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func handleCoreLogsFollow(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
log.Println("Client connected to core logs follow")
|
||||
|
||||
if err := streamHACommandToWS(conn, []string{"core", "logs", "--follow"}); err != nil {
|
||||
log.Printf("Error streaming core logs: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Client disconnected from core logs follow")
|
||||
}
|
||||
|
||||
func handleSupervisorLogsFollow(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
log.Println("Client connected to supervisor logs follow")
|
||||
|
||||
if err := streamHACommandToWS(conn, []string{"supervisor", "logs", "--follow"}); err != nil {
|
||||
log.Printf("Error streaming supervisor logs: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Client disconnected from supervisor logs follow")
|
||||
}
|
||||
|
||||
func handleHostLogsFollow(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
log.Println("Client connected to host logs follow")
|
||||
|
||||
if err := streamHACommandToWS(conn, []string{"host", "logs", "--follow"}); err != nil {
|
||||
log.Printf("Error streaming host logs: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Client disconnected from host logs follow")
|
||||
}
|
||||
|
||||
func handleAudioLogsFollow(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
log.Println("Client connected to audio logs follow")
|
||||
|
||||
if err := streamHACommandToWS(conn, []string{"audio", "logs", "--follow"}); err != nil {
|
||||
log.Printf("Error streaming audio logs: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Client disconnected from audio logs follow")
|
||||
}
|
||||
|
||||
func handleDNSLogsFollow(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
log.Println("Client connected to dns logs follow")
|
||||
|
||||
if err := streamHACommandToWS(conn, []string{"dns", "logs", "--follow"}); err != nil {
|
||||
log.Printf("Error streaming dns logs: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Client disconnected from dns logs follow")
|
||||
}
|
||||
|
||||
func handleMulticastLogsFollow(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
log.Println("Client connected to multicast logs follow")
|
||||
|
||||
if err := streamHACommandToWS(conn, []string{"multicast", "logs", "--follow"}); err != nil {
|
||||
log.Printf("Error streaming multicast logs: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Client disconnected from multicast logs follow")
|
||||
}
|
||||
|
||||
func listEndpoints(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
endpoints := map[string]string{
|
||||
"core": "/api/logs/core",
|
||||
"supervisor": "/api/logs/supervisor",
|
||||
"host": "/api/logs/host",
|
||||
"audio": "/api/logs/audio",
|
||||
"dns": "/api/logs/dns",
|
||||
"multicast": "/api/logs/multicast",
|
||||
"health": "/health",
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
json.NewEncoder(w).Encode(endpoints)
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := os.Getenv("PORT")
|
||||
if port == "" {
|
||||
port = "5642"
|
||||
}
|
||||
|
||||
// Register handlers
|
||||
http.HandleFunc("/api/logs", listEndpoints)
|
||||
http.HandleFunc("/api/logs/core", handleCoreLogs)
|
||||
http.HandleFunc("/api/logs/supervisor", handleSupervisorLogs)
|
||||
http.HandleFunc("/api/logs/host", handleHostLogs)
|
||||
http.HandleFunc("/api/logs/audio", handleAudioLogs)
|
||||
http.HandleFunc("/api/logs/dns", handleDNSLogs)
|
||||
http.HandleFunc("/api/logs/multicast", handleMulticastLogs)
|
||||
|
||||
// WebSocket follow endpoints
|
||||
http.HandleFunc("/api/logs/core/follow", handleCoreLogsFollow)
|
||||
http.HandleFunc("/api/logs/supervisor/follow", handleSupervisorLogsFollow)
|
||||
http.HandleFunc("/api/logs/host/follow", handleHostLogsFollow)
|
||||
http.HandleFunc("/api/logs/audio/follow", handleAudioLogsFollow)
|
||||
http.HandleFunc("/api/logs/dns/follow", handleDNSLogsFollow)
|
||||
http.HandleFunc("/api/logs/multicast/follow", handleMulticastLogsFollow)
|
||||
|
||||
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("OK"))
|
||||
})
|
||||
|
||||
log.Printf("Starting HA Logs Proxy on port %s", port)
|
||||
log.Printf("Available endpoints:")
|
||||
log.Printf(" GET /api/logs - List all endpoints")
|
||||
log.Printf(" GET /api/logs/core - Core logs")
|
||||
log.Printf(" GET /api/logs/supervisor - Supervisor logs")
|
||||
log.Printf(" GET /api/logs/host - Host logs")
|
||||
log.Printf(" GET /api/logs/audio - Audio logs")
|
||||
log.Printf(" GET /api/logs/dns - DNS logs")
|
||||
log.Printf(" GET /api/logs/multicast - Multicast logs")
|
||||
log.Printf(" WS /api/logs/*/follow - Stream logs (WebSocket)")
|
||||
log.Printf(" GET /health - Health check")
|
||||
|
||||
if err := http.ListenAndServe(":"+port, nil); err != nil {
|
||||
log.Fatalf("Server failed to start: %v", err)
|
||||
}
|
||||
}
|
||||
19
logs/build.yaml
Normal file
19
logs/build.yaml
Normal file
@@ -0,0 +1,19 @@
|
||||
---
|
||||
image: ghcr.io/home-assistant/{arch}-hassio-cli
|
||||
build_from:
|
||||
aarch64: ghcr.io/home-assistant/aarch64-base:3.22
|
||||
armhf: ghcr.io/home-assistant/armhf-base:3.22
|
||||
armv7: ghcr.io/home-assistant/armv7-base:3.22
|
||||
amd64: ghcr.io/home-assistant/amd64-base:3.22
|
||||
i386: ghcr.io/home-assistant/i386-base:3.22
|
||||
args:
|
||||
CLI_VERSION: 4.42.0
|
||||
cosign:
|
||||
enabled: true
|
||||
repository_name: home-assistant/cli
|
||||
repository_owner: home-assistant
|
||||
labels:
|
||||
org.opencontainers.image.title: Home Assistant CLI
|
||||
org.opencontainers.image.description: Home Assistant CLI for container environments
|
||||
org.opencontainers.image.source: https://github.com/home-assistant/cli
|
||||
org.opencontainers.image.licenses: Apache-2.0
|
||||
16
logs/docker-compose.yaml
Normal file
16
logs/docker-compose.yaml
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
services:
|
||||
ha-cli:
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
BUILD_FROM: alpine:3.22
|
||||
BUILD_ARCH: amd64
|
||||
CLI_VERSION: 4.42.0
|
||||
image: ha-cli:local
|
||||
ports:
|
||||
- "5642:5642"
|
||||
environment:
|
||||
- PORT=5642
|
||||
stdin_open: true
|
||||
tty: true
|
||||
34
logs/src/auto-theme.ts
Normal file
34
logs/src/auto-theme.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { darkSemanticColorStyles } from "../../src/resources/theme/color/semantic.globals";
|
||||
import { darkColorStyles } from "../../src/resources/theme/color/color.globals";
|
||||
|
||||
const mql = matchMedia("(prefers-color-scheme: dark)");
|
||||
|
||||
function applyTheme(dark: boolean) {
|
||||
const el = document.documentElement;
|
||||
if (dark) {
|
||||
el.setAttribute("dark", "");
|
||||
} else {
|
||||
el.removeAttribute("dark");
|
||||
}
|
||||
}
|
||||
|
||||
// Add dark theme styles wrapped in media query
|
||||
// This runs after append-ha-style has loaded the base theme
|
||||
const styleElement = document.createElement("style");
|
||||
styleElement.id = "auto-theme-dark";
|
||||
styleElement.textContent = `
|
||||
@media (prefers-color-scheme: dark) {
|
||||
${darkSemanticColorStyles.cssText}
|
||||
${darkColorStyles.cssText}
|
||||
}
|
||||
`;
|
||||
// Append to head to ensure it comes after base styles
|
||||
document.head.appendChild(styleElement);
|
||||
|
||||
// Apply theme on initial load
|
||||
applyTheme(mql.matches);
|
||||
|
||||
// Listen for theme changes
|
||||
mql.addEventListener("change", (e) => {
|
||||
applyTheme(e.matches);
|
||||
});
|
||||
8
logs/src/entrypoint.ts
Normal file
8
logs/src/entrypoint.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import "./logs-app";
|
||||
|
||||
// Load base styles first, then apply theme
|
||||
import("../../src/resources/append-ha-style").then(() => {
|
||||
import("./auto-theme");
|
||||
});
|
||||
|
||||
document.body.appendChild(document.createElement("logs-app"));
|
||||
37
logs/src/html/index.html.template
Normal file
37
logs/src/html/index.html.template
Normal file
@@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, shrink-to-fit=no"
|
||||
/>
|
||||
<meta name="theme-color" content="#03a9f4" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<title>Home Assistant Logs</title>
|
||||
<% for (const entry of latestEntryJS) { %>
|
||||
<script type="module" src="<%= entry %>"></script>
|
||||
<% } %>
|
||||
<style>
|
||||
html {
|
||||
background-color: var(--primary-background-color, #fafafa);
|
||||
color: var(--primary-text-color, #212121);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html {
|
||||
background-color: var(--primary-background-color, #111111);
|
||||
color: var(--primary-text-color, #e1e1e1);
|
||||
}
|
||||
}
|
||||
body {
|
||||
font-family: Roboto, Noto, sans-serif;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-weight: 400;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
24
logs/src/logs-app.ts
Normal file
24
logs/src/logs-app.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { LitElement, css, html } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
import "./logs-viewer";
|
||||
|
||||
@customElement("logs-app")
|
||||
class LogsApp extends LitElement {
|
||||
render() {
|
||||
return html`<logs-viewer></logs-viewer>`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
min-height: 100vh;
|
||||
background-color: var(--primary-background-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"logs-app": LogsApp;
|
||||
}
|
||||
}
|
||||
538
logs/src/logs-viewer.ts
Normal file
538
logs/src/logs-viewer.ts
Normal file
@@ -0,0 +1,538 @@
|
||||
import {
|
||||
mdiArrowCollapseDown,
|
||||
mdiChevronDown,
|
||||
mdiCircle,
|
||||
mdiDownload,
|
||||
mdiRefresh,
|
||||
mdiWrap,
|
||||
mdiWrapDisabled,
|
||||
} from "@mdi/js";
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
// eslint-disable-next-line import/extensions
|
||||
import { IntersectionController } from "@lit-labs/observers/intersection-controller.js";
|
||||
import "../../src/components/ha-ansi-to-html";
|
||||
import type { HaAnsiToHtml } from "../../src/components/ha-ansi-to-html";
|
||||
import "../../src/components/ha-button";
|
||||
import "../../src/components/ha-button-menu";
|
||||
import "../../src/components/ha-card";
|
||||
import "../../src/components/ha-icon-button";
|
||||
import "../../src/components/ha-list-item";
|
||||
import "../../src/components/ha-spinner";
|
||||
import "../../src/components/ha-svg-icon";
|
||||
|
||||
// Data types
|
||||
interface LogProvider {
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@customElement("logs-viewer")
|
||||
export class LogsViewer extends LitElement {
|
||||
@property({ type: Boolean }) public narrow = false;
|
||||
|
||||
@state() private _selectedLogProvider?: string;
|
||||
|
||||
@state() private _logProviders: LogProvider[] = [];
|
||||
|
||||
@state() private _loading = false;
|
||||
|
||||
@state() private _wrapLines = true;
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
@state() private _newLogsIndicator?: boolean;
|
||||
|
||||
@query(".error-log") private _logElement?: HTMLElement;
|
||||
|
||||
@query("#scroll-top-marker") private _scrollTopMarkerElement?: HTMLElement;
|
||||
|
||||
@query("#scroll-bottom-marker")
|
||||
private _scrollBottomMarkerElement?: HTMLElement;
|
||||
|
||||
@query("ha-ansi-to-html") private _ansiToHtmlElement?: HaAnsiToHtml;
|
||||
|
||||
@state() private _scrolledToBottomController =
|
||||
new IntersectionController<boolean>(this, {
|
||||
callback(this: IntersectionController<boolean>, entries) {
|
||||
return entries[0].isIntersecting;
|
||||
},
|
||||
});
|
||||
|
||||
@state() private _scrolledToTopController =
|
||||
new IntersectionController<boolean>(this, {});
|
||||
|
||||
private _ws: WebSocket | null = null;
|
||||
|
||||
private _apiUrl = `http://${window.location.hostname}:5642`;
|
||||
|
||||
private async _fetchLogs(): Promise<void> {
|
||||
if (!this._selectedLogProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._loading = true;
|
||||
this._error = undefined;
|
||||
|
||||
// Stop any existing websocket
|
||||
this._stopFollowing();
|
||||
|
||||
// Clear existing logs
|
||||
this._ansiToHtmlElement?.clear();
|
||||
|
||||
try {
|
||||
// First, fetch the latest logs
|
||||
const response = await fetch(
|
||||
`${this._apiUrl}/api/logs/${this._selectedLogProvider}`
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
const logText = data.output || "";
|
||||
|
||||
// Parse and display initial logs
|
||||
if (logText.trim()) {
|
||||
this._ansiToHtmlElement?.parseTextToColoredPre(logText);
|
||||
|
||||
// Add divider line
|
||||
this._ansiToHtmlElement?.parseLineToColoredPre(
|
||||
"--- Live logs start here ---"
|
||||
);
|
||||
}
|
||||
|
||||
this._loading = false;
|
||||
|
||||
// Scroll to bottom after loading
|
||||
this._scrollToBottom();
|
||||
|
||||
// Start streaming
|
||||
this._startFollowing();
|
||||
} catch (err) {
|
||||
this._error = `Error loading logs: ${err}`;
|
||||
this._loading = false;
|
||||
// eslint-disable-next-line
|
||||
console.error("Error fetching logs:", err);
|
||||
}
|
||||
}
|
||||
|
||||
private async _fetchLogProviders(): Promise<void> {
|
||||
try {
|
||||
const response = await fetch(`${this._apiUrl}/api/logs`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const providers = await response.json();
|
||||
|
||||
// Define the order (matching backend registration order)
|
||||
const order = ["core", "supervisor", "host", "audio", "dns", "multicast"];
|
||||
|
||||
// Convert object to array of providers, filter out health endpoint, and sort
|
||||
this._logProviders = Object.entries(providers)
|
||||
.filter(([key]) => key !== "health")
|
||||
.map(([key]) => ({
|
||||
key,
|
||||
name: key.charAt(0).toUpperCase() + key.slice(1),
|
||||
}))
|
||||
.sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key));
|
||||
|
||||
// Set default provider once loaded
|
||||
if (this._logProviders.length > 0 && !this._selectedLogProvider) {
|
||||
this._selectedLogProvider = this._logProviders[0].key;
|
||||
await this._fetchLogs();
|
||||
}
|
||||
} catch (err) {
|
||||
this._error = `Failed to load log providers: ${err}`;
|
||||
// eslint-disable-next-line
|
||||
console.error("Error fetching log providers:", err);
|
||||
}
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._fetchLogProviders();
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._stopFollowing();
|
||||
}
|
||||
|
||||
protected firstUpdated() {
|
||||
this._scrolledToBottomController.observe(this._scrollBottomMarkerElement!);
|
||||
this._scrolledToTopController.observe(this._scrollTopMarkerElement!);
|
||||
}
|
||||
|
||||
protected updated() {
|
||||
if (this._newLogsIndicator && this._scrolledToBottomController.value) {
|
||||
this._newLogsIndicator = false;
|
||||
}
|
||||
}
|
||||
|
||||
private _selectProvider(ev: Event) {
|
||||
const target = ev.currentTarget as any;
|
||||
this._selectedLogProvider = target.provider;
|
||||
this._fetchLogs();
|
||||
}
|
||||
|
||||
private _refresh() {
|
||||
this._fetchLogs();
|
||||
}
|
||||
|
||||
private _toggleLineWrap() {
|
||||
this._wrapLines = !this._wrapLines;
|
||||
}
|
||||
|
||||
private _scrollToBottom(): void {
|
||||
if (this._logElement) {
|
||||
this._newLogsIndicator = false;
|
||||
this._logElement.scrollTo(0, this._logElement.scrollHeight);
|
||||
}
|
||||
}
|
||||
|
||||
private _startFollowing() {
|
||||
if (!this._selectedLogProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._stopFollowing();
|
||||
this._error = undefined;
|
||||
|
||||
const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsUrl = `${wsProtocol}//${window.location.hostname}:5642/api/logs/${this._selectedLogProvider}/follow`;
|
||||
|
||||
try {
|
||||
this._ws = new WebSocket(wsUrl);
|
||||
|
||||
this._ws.onopen = () => {
|
||||
// eslint-disable-next-line
|
||||
console.log("WebSocket connected");
|
||||
};
|
||||
|
||||
this._ws.onmessage = (event) => {
|
||||
const scrolledToBottom = this._scrolledToBottomController.value;
|
||||
|
||||
// Add the new line to the display
|
||||
this._ansiToHtmlElement?.parseLineToColoredPre(event.data);
|
||||
|
||||
// Auto-scroll if user is at bottom
|
||||
if (scrolledToBottom && this._logElement) {
|
||||
this._scrollToBottom();
|
||||
} else {
|
||||
this._newLogsIndicator = true;
|
||||
}
|
||||
};
|
||||
|
||||
this._ws.onerror = (error) => {
|
||||
// eslint-disable-next-line
|
||||
console.error("WebSocket error:", error);
|
||||
this._error = "WebSocket connection error";
|
||||
};
|
||||
|
||||
this._ws.onclose = () => {
|
||||
// eslint-disable-next-line
|
||||
console.log("WebSocket disconnected");
|
||||
};
|
||||
} catch (err) {
|
||||
this._error = `Failed to start following logs: ${err}`;
|
||||
// eslint-disable-next-line
|
||||
console.error("Error starting WebSocket:", err);
|
||||
}
|
||||
}
|
||||
|
||||
private _stopFollowing() {
|
||||
if (this._ws) {
|
||||
this._ws.close();
|
||||
this._ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
private _downloadLogs() {
|
||||
if (!this._selectedLogProvider || !this._ansiToHtmlElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the text content from the logs
|
||||
const logText =
|
||||
this._ansiToHtmlElement.shadowRoot?.querySelector("pre")?.textContent ||
|
||||
"";
|
||||
|
||||
if (!logText.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create blob from log text
|
||||
const blob = new Blob([logText], { type: "text/plain" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
// Create download link and trigger it
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${this._selectedLogProvider}-logs-${Date.now()}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
|
||||
// Cleanup
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
render() {
|
||||
const currentProvider = this._logProviders.find(
|
||||
(p) => p.key === this._selectedLogProvider
|
||||
);
|
||||
|
||||
return html`
|
||||
<div class="container">
|
||||
<div class="toolbar">
|
||||
<ha-button-menu>
|
||||
<ha-button slot="trigger" appearance="filled">
|
||||
<ha-svg-icon slot="end" .path=${mdiChevronDown}></ha-svg-icon>
|
||||
${currentProvider?.name || "Select Provider"}
|
||||
</ha-button>
|
||||
${this._logProviders.map(
|
||||
(provider) => html`
|
||||
<ha-list-item
|
||||
?selected=${provider.key === this._selectedLogProvider}
|
||||
.provider=${provider.key}
|
||||
@click=${this._selectProvider}
|
||||
>
|
||||
${provider.name}
|
||||
</ha-list-item>
|
||||
`
|
||||
)}
|
||||
</ha-button-menu>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div class="error-log-intro">
|
||||
<ha-card outlined>
|
||||
<div class="header">
|
||||
<h1 class="card-header">${currentProvider?.name || "Logs"}</h1>
|
||||
<div class="action-buttons">
|
||||
<ha-icon-button
|
||||
.path=${mdiDownload}
|
||||
@click=${this._downloadLogs}
|
||||
.label=${"Download logs"}
|
||||
.disabled=${!this._ansiToHtmlElement}
|
||||
></ha-icon-button>
|
||||
<ha-icon-button
|
||||
.path=${this._wrapLines ? mdiWrapDisabled : mdiWrap}
|
||||
@click=${this._toggleLineWrap}
|
||||
.label=${this._wrapLines ? "Full width" : "Wrap lines"}
|
||||
></ha-icon-button>
|
||||
<ha-icon-button
|
||||
.path=${mdiRefresh}
|
||||
@click=${this._refresh}
|
||||
.label=${"Refresh"}
|
||||
.disabled=${!this._selectedLogProvider}
|
||||
></ha-icon-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-content error-log">
|
||||
<div id="scroll-top-marker"></div>
|
||||
${this._loading
|
||||
? html`<div>Loading logs...</div>`
|
||||
: this._error
|
||||
? html`<div class="error">${this._error}</div>`
|
||||
: nothing}
|
||||
<ha-ansi-to-html
|
||||
?wrap-disabled=${!this._wrapLines}
|
||||
></ha-ansi-to-html>
|
||||
<div id="scroll-bottom-marker"></div>
|
||||
</div>
|
||||
<ha-button
|
||||
class="new-logs-indicator ${classMap({
|
||||
visible:
|
||||
(this._newLogsIndicator &&
|
||||
!this._scrolledToBottomController.value) ||
|
||||
false,
|
||||
})}"
|
||||
size="small"
|
||||
appearance="filled"
|
||||
@click=${this._scrollToBottom}
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${mdiArrowCollapseDown}
|
||||
slot="start"
|
||||
></ha-svg-icon>
|
||||
Scroll down
|
||||
<ha-svg-icon
|
||||
.path=${mdiArrowCollapseDown}
|
||||
slot="end"
|
||||
></ha-svg-icon>
|
||||
</ha-button>
|
||||
${this._ws && !this._error
|
||||
? html`<div class="live-indicator">
|
||||
<ha-svg-icon .path=${mdiCircle}></ha-svg-icon>
|
||||
Live
|
||||
</div>`
|
||||
: nothing}
|
||||
</ha-card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles: CSSResultGroup = css`
|
||||
:host {
|
||||
display: block;
|
||||
direction: var(--direction);
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
padding: var(--ha-space-2) var(--ha-space-4);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
|
||||
.content {
|
||||
direction: ltr;
|
||||
}
|
||||
|
||||
.error-log-intro {
|
||||
text-align: center;
|
||||
margin: 0 var(--ha-space-4);
|
||||
}
|
||||
|
||||
ha-card {
|
||||
padding-top: var(--ha-space-2);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 0 var(--ha-space-4);
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
color: var(--ha-card-header-color, var(--primary-text-color));
|
||||
font-family: var(--ha-card-header-font-family, inherit);
|
||||
font-size: var(--ha-card-header-font-size, var(--ha-font-size-2xl));
|
||||
letter-spacing: -0.012em;
|
||||
line-height: var(--ha-line-height-expanded);
|
||||
display: block;
|
||||
margin-block-start: 0px;
|
||||
font-weight: var(--ha-font-weight-normal);
|
||||
white-space: nowrap;
|
||||
max-width: calc(100% - 150px);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.error-log {
|
||||
position: relative;
|
||||
font-family: var(--ha-font-family-code);
|
||||
clear: both;
|
||||
text-align: start;
|
||||
padding-top: var(--ha-space-4);
|
||||
padding-bottom: var(--ha-space-4);
|
||||
overflow-y: scroll;
|
||||
min-height: var(--error-log-card-height, calc(100vh - 244px));
|
||||
max-height: var(--error-log-card-height, calc(100vh - 244px));
|
||||
border-top: 1px solid var(--divider-color);
|
||||
direction: ltr;
|
||||
}
|
||||
|
||||
.error-log > div {
|
||||
padding: 0 var(--ha-space-4);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--error-color);
|
||||
padding: var(--ha-space-4);
|
||||
}
|
||||
|
||||
.new-logs-indicator {
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
bottom: var(--ha-space-1);
|
||||
left: var(--ha-space-1);
|
||||
height: 0;
|
||||
transition: height 0.4s ease-out;
|
||||
}
|
||||
|
||||
.new-logs-indicator.visible {
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
@keyframes breathe {
|
||||
from {
|
||||
opacity: 0.8;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.live-indicator {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
inset-inline-end: var(--ha-space-4);
|
||||
border-top-right-radius: var(--ha-space-2);
|
||||
border-top-left-radius: var(--ha-space-2);
|
||||
background-color: var(--primary-color);
|
||||
color: var(--text-primary-color);
|
||||
padding: var(--ha-space-1) var(--ha-space-2);
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.live-indicator ha-svg-icon {
|
||||
animation: breathe 1s cubic-bezier(0.5, 0, 1, 1) infinite alternate;
|
||||
height: 14px;
|
||||
width: 14px;
|
||||
}
|
||||
|
||||
@media all and (max-width: 870px) {
|
||||
.error-log {
|
||||
min-height: var(--error-log-card-height, calc(100vh - 190px));
|
||||
max-height: var(--error-log-card-height, calc(100vh - 190px));
|
||||
}
|
||||
|
||||
ha-button-menu {
|
||||
max-width: 50%;
|
||||
}
|
||||
|
||||
ha-button {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
ha-button::part(label) {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
ha-list-item[selected] {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"logs-viewer": LogsViewer;
|
||||
}
|
||||
}
|
||||
69
package.json
69
package.json
@@ -28,13 +28,13 @@
|
||||
"dependencies": {
|
||||
"@babel/runtime": "7.28.4",
|
||||
"@braintree/sanitize-url": "7.1.1",
|
||||
"@codemirror/autocomplete": "6.19.0",
|
||||
"@codemirror/commands": "6.9.0",
|
||||
"@codemirror/autocomplete": "6.19.1",
|
||||
"@codemirror/commands": "6.10.0",
|
||||
"@codemirror/language": "6.11.3",
|
||||
"@codemirror/legacy-modes": "6.5.2",
|
||||
"@codemirror/search": "6.5.11",
|
||||
"@codemirror/state": "6.5.2",
|
||||
"@codemirror/view": "6.38.5",
|
||||
"@codemirror/view": "6.38.6",
|
||||
"@date-fns/tz": "1.4.1",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "6.18.2",
|
||||
@@ -52,8 +52,8 @@
|
||||
"@fullcalendar/list": "6.1.19",
|
||||
"@fullcalendar/luxon3": "6.1.19",
|
||||
"@fullcalendar/timegrid": "6.1.19",
|
||||
"@home-assistant/webawesome": "3.0.0-beta.6.ha.4",
|
||||
"@lezer/highlight": "1.2.1",
|
||||
"@home-assistant/webawesome": "3.0.0-beta.6.ha.7",
|
||||
"@lezer/highlight": "1.2.3",
|
||||
"@lit-labs/motion": "1.0.9",
|
||||
"@lit-labs/observers": "2.0.6",
|
||||
"@lit-labs/virtualizer": "2.1.1",
|
||||
@@ -81,7 +81,7 @@
|
||||
"@material/mwc-top-app-bar": "0.27.0",
|
||||
"@material/mwc-top-app-bar-fixed": "0.27.0",
|
||||
"@material/top-app-bar": "=14.0.0-canary.53b3cad2f.0",
|
||||
"@material/web": "2.4.0",
|
||||
"@material/web": "2.4.1",
|
||||
"@mdi/js": "7.4.47",
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"@thomasloven/round-slider": "0.6.0",
|
||||
"@tsparticles/engine": "3.9.1",
|
||||
"@tsparticles/preset-links": "3.2.0",
|
||||
"@vaadin/combo-box": "24.9.2",
|
||||
"@vaadin/vaadin-themable-mixin": "24.9.2",
|
||||
"@vaadin/combo-box": "24.9.4",
|
||||
"@vaadin/vaadin-themable-mixin": "24.9.4",
|
||||
"@vibrant/color": "4.0.0",
|
||||
"@vue/web-component-wrapper": "1.3.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
@@ -111,7 +111,7 @@
|
||||
"fuse.js": "7.1.0",
|
||||
"google-timezones-json": "1.2.0",
|
||||
"gulp-zopfli-green": "6.0.2",
|
||||
"hls.js": "1.6.13",
|
||||
"hls.js": "1.6.14",
|
||||
"home-assistant-js-websocket": "9.5.0",
|
||||
"idb-keyval": "6.2.2",
|
||||
"intl-messageformat": "10.7.18",
|
||||
@@ -122,7 +122,7 @@
|
||||
"lit": "3.3.1",
|
||||
"lit-html": "3.3.1",
|
||||
"luxon": "3.7.2",
|
||||
"marked": "16.4.0",
|
||||
"marked": "16.4.1",
|
||||
"memoize-one": "6.0.0",
|
||||
"node-vibrant": "4.0.3",
|
||||
"object-hash": "3.0.0",
|
||||
@@ -148,17 +148,17 @@
|
||||
"xss": "1.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "7.28.4",
|
||||
"@babel/core": "7.28.5",
|
||||
"@babel/helper-define-polyfill-provider": "0.6.5",
|
||||
"@babel/plugin-transform-runtime": "7.28.3",
|
||||
"@babel/preset-env": "7.28.3",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.21.5",
|
||||
"@lokalise/node-api": "15.3.0",
|
||||
"@octokit/auth-oauth-device": "8.0.2",
|
||||
"@octokit/plugin-retry": "8.0.2",
|
||||
"@octokit/rest": "22.0.0",
|
||||
"@rsdoctor/rspack-plugin": "1.3.1",
|
||||
"@rspack/core": "1.5.8",
|
||||
"@babel/plugin-transform-runtime": "7.28.5",
|
||||
"@babel/preset-env": "7.28.5",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.21.6",
|
||||
"@lokalise/node-api": "15.3.1",
|
||||
"@octokit/auth-oauth-device": "8.0.3",
|
||||
"@octokit/plugin-retry": "8.0.3",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@rsdoctor/rspack-plugin": "1.3.7",
|
||||
"@rspack/core": "1.6.0",
|
||||
"@rspack/dev-server": "1.1.4",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "6.0.22",
|
||||
@@ -167,30 +167,30 @@
|
||||
"@types/culori": "4.0.1",
|
||||
"@types/html-minifier-terser": "7.0.2",
|
||||
"@types/js-yaml": "4.0.9",
|
||||
"@types/leaflet": "1.9.20",
|
||||
"@types/leaflet": "1.9.21",
|
||||
"@types/leaflet-draw": "1.0.13",
|
||||
"@types/leaflet.markercluster": "1.5.6",
|
||||
"@types/lodash.merge": "4.6.9",
|
||||
"@types/luxon": "3.7.1",
|
||||
"@types/mocha": "10.0.10",
|
||||
"@types/qrcode": "1.5.5",
|
||||
"@types/sortablejs": "1.15.8",
|
||||
"@types/qrcode": "1.5.6",
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "6.1.13",
|
||||
"@types/ua-parser-js": "0.7.39",
|
||||
"@types/webspeechapi": "0.0.29",
|
||||
"@vitest/coverage-v8": "3.2.4",
|
||||
"@vitest/coverage-v8": "4.0.6",
|
||||
"babel-loader": "10.0.0",
|
||||
"babel-plugin-template-html-minifier": "4.1.0",
|
||||
"browserslist-useragent-regexp": "4.1.3",
|
||||
"del": "8.0.1",
|
||||
"eslint": "9.37.0",
|
||||
"eslint": "9.39.1",
|
||||
"eslint-config-airbnb-base": "15.0.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.10",
|
||||
"eslint-plugin-import": "2.32.0",
|
||||
"eslint-plugin-lit": "2.1.1",
|
||||
"eslint-plugin-lit-a11y": "5.1.1",
|
||||
"eslint-plugin-unused-imports": "4.2.0",
|
||||
"eslint-plugin-unused-imports": "4.3.0",
|
||||
"eslint-plugin-wc": "3.0.2",
|
||||
"fancy-log": "2.0.0",
|
||||
"fs-extra": "11.3.2",
|
||||
@@ -201,9 +201,9 @@
|
||||
"gulp-rename": "2.1.0",
|
||||
"html-minifier-terser": "7.2.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "27.0.0",
|
||||
"jsdom": "27.1.0",
|
||||
"jszip": "3.10.1",
|
||||
"lint-staged": "16.2.3",
|
||||
"lint-staged": "16.2.6",
|
||||
"lit-analyzer": "2.0.3",
|
||||
"lodash.merge": "4.6.2",
|
||||
"lodash.template": "4.5.0",
|
||||
@@ -213,13 +213,13 @@
|
||||
"rspack-manifest-plugin": "5.1.0",
|
||||
"serve": "14.2.5",
|
||||
"sinon": "21.0.0",
|
||||
"tar": "7.5.1",
|
||||
"tar": "7.5.2",
|
||||
"terser-webpack-plugin": "5.3.14",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "8.46.0",
|
||||
"typescript-eslint": "8.46.3",
|
||||
"vite-tsconfig-paths": "5.1.4",
|
||||
"vitest": "3.2.4",
|
||||
"vitest": "4.0.6",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "patch:workbox-build@npm%3A7.1.1#~/.yarn/patches/workbox-build-npm-7.1.1-a854f3faae.patch"
|
||||
@@ -231,9 +231,12 @@
|
||||
"clean-css": "5.3.3",
|
||||
"@lit/reactive-element": "2.1.1",
|
||||
"@fullcalendar/daygrid": "6.1.19",
|
||||
"globals": "16.4.0",
|
||||
"globals": "16.5.0",
|
||||
"tslib": "2.8.1",
|
||||
"@material/mwc-list@^0.27.0": "patch:@material/mwc-list@npm%3A0.27.0#~/.yarn/patches/@material-mwc-list-npm-0.27.0-5344fc9de4.patch"
|
||||
},
|
||||
"packageManager": "yarn@4.10.3"
|
||||
"packageManager": "yarn@4.10.3",
|
||||
"volta": {
|
||||
"node": "22.21.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "home-assistant-frontend"
|
||||
version = "20250924.0"
|
||||
version = "20251029.0"
|
||||
license = "Apache-2.0"
|
||||
license-files = ["LICENSE*"]
|
||||
description = "The Home Assistant frontend"
|
||||
|
||||
96
script/develop-logs
Executable file
96
script/develop-logs
Executable file
@@ -0,0 +1,96 @@
|
||||
#!/bin/sh
|
||||
# Run the logs frontend development server
|
||||
|
||||
# Stop on errors
|
||||
set -e
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Parse command line arguments
|
||||
SUPERVISOR_ENDPOINT=""
|
||||
SUPERVISOR_API_TOKEN=""
|
||||
|
||||
while getopts "c:t:h" opt; do
|
||||
case $opt in
|
||||
c)
|
||||
SUPERVISOR_ENDPOINT="$OPTARG"
|
||||
;;
|
||||
t)
|
||||
SUPERVISOR_API_TOKEN="$OPTARG"
|
||||
;;
|
||||
h)
|
||||
echo "Usage: $0 -c SUPERVISOR_ENDPOINT -t SUPERVISOR_API_TOKEN"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " -c SUPERVISOR_ENDPOINT (e.g., http://192.168.1.2) [required]"
|
||||
echo " -t SUPERVISOR_API_TOKEN (from remote_api add-on) [required]"
|
||||
echo " -h Show this help message"
|
||||
echo ""
|
||||
echo "Example:"
|
||||
echo " $0 -c http://192.168.1.2 -t your_token_here"
|
||||
exit 0
|
||||
;;
|
||||
\?)
|
||||
echo "Invalid option: -$OPTARG" >&2
|
||||
echo "Use -h for help"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Validate that both -c and -t are provided
|
||||
if [ -z "$SUPERVISOR_ENDPOINT" ] || [ -z "$SUPERVISOR_API_TOKEN" ]; then
|
||||
echo "Error: Both -c and -t are required" >&2
|
||||
echo "Use -h for help"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Cleanup function
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "Shutting down..."
|
||||
echo "Stopping HA CLI container..."
|
||||
docker stop ha-cli-dev 2>/dev/null || true
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Set up trap to cleanup on exit
|
||||
trap cleanup INT TERM EXIT
|
||||
|
||||
# Run HA CLI container
|
||||
echo "Starting HA CLI container..."
|
||||
|
||||
# Build the container if needed
|
||||
if ! docker images | grep -q "ha-cli:local"; then
|
||||
echo "Building HA CLI container..."
|
||||
(cd logs && docker compose build)
|
||||
fi
|
||||
|
||||
# Clean up any existing container
|
||||
docker stop ha-cli-dev 2>/dev/null || true
|
||||
|
||||
# Run the container in background (not detached, so it shares stdout)
|
||||
docker run \
|
||||
--name ha-cli-dev \
|
||||
--rm \
|
||||
-p 5642:5642 \
|
||||
-e SUPERVISOR_ENDPOINT="$SUPERVISOR_ENDPOINT" \
|
||||
-e SUPERVISOR_API_TOKEN="$SUPERVISOR_API_TOKEN" \
|
||||
-e PORT=5642 \
|
||||
ha-cli:local &
|
||||
|
||||
# Store the docker process ID
|
||||
DOCKER_PID=$!
|
||||
|
||||
# Wait a moment for container to start
|
||||
sleep 2
|
||||
echo ""
|
||||
echo "HA Logs Backend API: http://localhost:5642"
|
||||
echo " GET /api/logs - List endpoints"
|
||||
echo " GET /api/logs/core - Core logs"
|
||||
echo " GET /api/logs/supervisor - Supervisor logs"
|
||||
echo " GET /health - Health check"
|
||||
echo ""
|
||||
|
||||
# Run gulp (this will block until Ctrl+C)
|
||||
./node_modules/.bin/gulp develop-logs
|
||||
@@ -1,4 +1,5 @@
|
||||
/* eslint-disable lit/prefer-static-styles */
|
||||
import { mdiOpenInNew } from "@mdi/js";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
@@ -6,6 +7,8 @@ import punycode from "punycode";
|
||||
import { applyThemesOnElement } from "../common/dom/apply_themes_on_element";
|
||||
import { extractSearchParamsObject } from "../common/url/search-params";
|
||||
import "../components/ha-alert";
|
||||
import "../components/ha-button";
|
||||
import "../components/ha-svg-icon";
|
||||
import type { AuthProvider, AuthUrlSearchParams } from "../data/auth";
|
||||
import { fetchAuthProviders } from "../data/auth";
|
||||
import { litLocalizeLiteMixin } from "../mixins/lit-localize-lite-mixin";
|
||||
@@ -133,25 +136,8 @@ export class HaAuthorize extends litLocalizeLiteMixin(LitElement) {
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
ha-language-picker {
|
||||
width: 200px;
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
overflow: hidden;
|
||||
--ha-select-height: 40px;
|
||||
--mdc-select-fill-color: none;
|
||||
--mdc-select-label-ink-color: var(--primary-text-color, #212121);
|
||||
--mdc-select-ink-color: var(--primary-text-color, #212121);
|
||||
--mdc-select-idle-line-color: transparent;
|
||||
--mdc-select-hover-line-color: transparent;
|
||||
--mdc-select-dropdown-icon-color: var(--primary-text-color, #212121);
|
||||
--mdc-shape-small: 0;
|
||||
}
|
||||
.footer a {
|
||||
text-decoration: none;
|
||||
color: var(--primary-text-color);
|
||||
margin-right: 16px;
|
||||
margin-inline-end: 16px;
|
||||
margin-inline-start: initial;
|
||||
.footer ha-svg-icon {
|
||||
--mdc-icon-size: var(--ha-space-5);
|
||||
}
|
||||
h1 {
|
||||
font-size: var(--ha-font-size-3xl);
|
||||
@@ -205,16 +191,21 @@ export class HaAuthorize extends litLocalizeLiteMixin(LitElement) {
|
||||
<ha-language-picker
|
||||
.value=${this.language}
|
||||
.label=${""}
|
||||
button-style
|
||||
native-name
|
||||
@value-changed=${this._languageChanged}
|
||||
inline-arrow
|
||||
></ha-language-picker>
|
||||
<a
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
variant="neutral"
|
||||
href="https://www.home-assistant.io/docs/authentication/"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
>${this.localize("ui.panel.page-authorize.help")}</a
|
||||
>
|
||||
${this.localize("ui.panel.page-authorize.help")}
|
||||
<ha-svg-icon slot="end" .path=${mdiOpenInNew}></ha-svg-icon>
|
||||
</ha-button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,11 @@ import { getEntityContext } from "./context/get_entity_context";
|
||||
|
||||
const DEFAULT_SEPARATOR = " ";
|
||||
|
||||
export const DEFAULT_ENTITY_NAME = [
|
||||
{ type: "device" },
|
||||
{ type: "entity" },
|
||||
] satisfies EntityNameItem[];
|
||||
|
||||
export type EntityNameItem =
|
||||
| {
|
||||
type: "entity" | "device" | "area" | "floor";
|
||||
@@ -24,14 +29,14 @@ export interface EntityNameOptions {
|
||||
|
||||
export const computeEntityNameDisplay = (
|
||||
stateObj: HassEntity,
|
||||
name: EntityNameItem | EntityNameItem[],
|
||||
name: EntityNameItem | EntityNameItem[] | undefined,
|
||||
entities: HomeAssistant["entities"],
|
||||
devices: HomeAssistant["devices"],
|
||||
areas: HomeAssistant["areas"],
|
||||
floors: HomeAssistant["floors"],
|
||||
options?: EntityNameOptions
|
||||
) => {
|
||||
let items = ensureArray(name);
|
||||
let items = ensureArray(name || DEFAULT_ENTITY_NAME);
|
||||
|
||||
const separator = options?.separator ?? DEFAULT_SEPARATOR;
|
||||
|
||||
|
||||
@@ -8,10 +8,10 @@ interface AreaContext {
|
||||
}
|
||||
export const getAreaContext = (
|
||||
area: AreaRegistryEntry,
|
||||
hass: HomeAssistant
|
||||
hassFloors: HomeAssistant["floors"]
|
||||
): AreaContext => {
|
||||
const floorId = area.floor_id;
|
||||
const floor = floorId ? hass.floors[floorId] : undefined;
|
||||
const floor = floorId ? hassFloors[floorId] : undefined;
|
||||
|
||||
return {
|
||||
area: area,
|
||||
|
||||
@@ -9,9 +9,9 @@ type EntityCategory = "none" | "config" | "diagnostic";
|
||||
export interface EntityFilter {
|
||||
domain?: string | string[];
|
||||
device_class?: string | string[];
|
||||
device?: string | string[];
|
||||
area?: string | string[];
|
||||
floor?: string | string[];
|
||||
device?: string | null | (string | null)[];
|
||||
area?: string | null | (string | null)[];
|
||||
floor?: string | null | (string | null)[];
|
||||
label?: string | string[];
|
||||
entity_category?: EntityCategory | EntityCategory[];
|
||||
hidden_platform?: string | string[];
|
||||
@@ -19,6 +19,18 @@ export interface EntityFilter {
|
||||
|
||||
export type EntityFilterFunc = (entityId: string) => boolean;
|
||||
|
||||
const normalizeFilterArray = <T>(
|
||||
value: T | null | T[] | (T | null)[] | undefined
|
||||
): Set<T | null> | undefined => {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return new Set([null]);
|
||||
}
|
||||
return new Set(ensureArray(value));
|
||||
};
|
||||
|
||||
export const generateEntityFilter = (
|
||||
hass: HomeAssistant,
|
||||
filter: EntityFilter
|
||||
@@ -29,11 +41,9 @@ export const generateEntityFilter = (
|
||||
const deviceClasses = filter.device_class
|
||||
? new Set(ensureArray(filter.device_class))
|
||||
: undefined;
|
||||
const floors = filter.floor ? new Set(ensureArray(filter.floor)) : undefined;
|
||||
const areas = filter.area ? new Set(ensureArray(filter.area)) : undefined;
|
||||
const devices = filter.device
|
||||
? new Set(ensureArray(filter.device))
|
||||
: undefined;
|
||||
const floors = normalizeFilterArray(filter.floor);
|
||||
const areas = normalizeFilterArray(filter.area);
|
||||
const devices = normalizeFilterArray(filter.device);
|
||||
const entityCategories = filter.entity_category
|
||||
? new Set(ensureArray(filter.entity_category))
|
||||
: undefined;
|
||||
@@ -73,23 +83,20 @@ export const generateEntityFilter = (
|
||||
}
|
||||
|
||||
if (floors) {
|
||||
if (!floor || !floors.has(floor.floor_id)) {
|
||||
const floorId = floor?.floor_id ?? null;
|
||||
if (!floors.has(floorId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (areas) {
|
||||
if (!area) {
|
||||
return false;
|
||||
}
|
||||
if (!areas.has(area.area_id)) {
|
||||
const areaId = area?.area_id ?? null;
|
||||
if (!areas.has(areaId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (devices) {
|
||||
if (!device) {
|
||||
return false;
|
||||
}
|
||||
if (!devices.has(device.id)) {
|
||||
const deviceId = device?.id ?? null;
|
||||
if (!devices.has(deviceId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +214,7 @@ const FIXED_DOMAIN_ATTRIBUTE_STATES = {
|
||||
"pm1",
|
||||
"pm10",
|
||||
"pm25",
|
||||
"pm4",
|
||||
"power_factor",
|
||||
"power",
|
||||
"pressure",
|
||||
|
||||
116
src/common/util/swipe-gesture-recognizer.ts
Normal file
116
src/common/util/swipe-gesture-recognizer.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
export interface SwipeGestureResult {
|
||||
velocity: number;
|
||||
delta: number;
|
||||
isSwipe: boolean;
|
||||
isDownwardSwipe: boolean;
|
||||
}
|
||||
|
||||
export interface SwipeGestureConfig {
|
||||
velocitySwipeThreshold?: number;
|
||||
movementTimeThreshold?: number;
|
||||
}
|
||||
|
||||
const VELOCITY_SWIPE_THRESHOLD = 0.5; // px/ms
|
||||
const MOVEMENT_TIME_THRESHOLD = 100; // ms
|
||||
|
||||
/**
|
||||
* Recognizes swipe gestures and calculates velocity for touch interactions.
|
||||
* Tracks touch movement and provides velocity-based and position-based gesture detection.
|
||||
*/
|
||||
export class SwipeGestureRecognizer {
|
||||
private _startY = 0;
|
||||
|
||||
private _delta = 0;
|
||||
|
||||
private _startTime = 0;
|
||||
|
||||
private _lastY = 0;
|
||||
|
||||
private _lastTime = 0;
|
||||
|
||||
private _velocityThreshold: number;
|
||||
|
||||
private _movementTimeThreshold: number;
|
||||
|
||||
constructor(config: SwipeGestureConfig = {}) {
|
||||
this._velocityThreshold =
|
||||
config.velocitySwipeThreshold ?? VELOCITY_SWIPE_THRESHOLD; // px/ms
|
||||
this._movementTimeThreshold =
|
||||
config.movementTimeThreshold ?? MOVEMENT_TIME_THRESHOLD; // ms
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize gesture tracking with starting touch position
|
||||
*/
|
||||
public start(clientY: number): void {
|
||||
const now = Date.now();
|
||||
this._startY = clientY;
|
||||
this._startTime = now;
|
||||
this._lastY = clientY;
|
||||
this._lastTime = now;
|
||||
this._delta = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update gesture state during movement
|
||||
* Returns the current delta (negative when dragging down)
|
||||
*/
|
||||
public move(clientY: number): number {
|
||||
const now = Date.now();
|
||||
this._delta = this._startY - clientY;
|
||||
this._lastY = clientY;
|
||||
this._lastTime = now;
|
||||
return this._delta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate final gesture result when touch ends
|
||||
*/
|
||||
public end(): SwipeGestureResult {
|
||||
const velocity = this.getVelocity();
|
||||
const hasSignificantVelocity = Math.abs(velocity) > this._velocityThreshold;
|
||||
|
||||
return {
|
||||
velocity,
|
||||
delta: this._delta,
|
||||
isSwipe: hasSignificantVelocity,
|
||||
isDownwardSwipe: velocity > 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current drag delta (negative when dragging down)
|
||||
*/
|
||||
public getDelta(): number {
|
||||
return this._delta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate velocity based on recent movement
|
||||
* Returns 0 if no recent movement detected
|
||||
* Positive velocity means downward swipe
|
||||
*/
|
||||
public getVelocity(): number {
|
||||
const now = Date.now();
|
||||
const timeSinceLastMove = now - this._lastTime;
|
||||
|
||||
// Only consider velocity if the last movement was recent
|
||||
if (timeSinceLastMove >= this._movementTimeThreshold) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const timeDelta = this._lastTime - this._startTime;
|
||||
return timeDelta > 0 ? (this._lastY - this._startY) / timeDelta : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset all tracking state
|
||||
*/
|
||||
public reset(): void {
|
||||
this._startY = 0;
|
||||
this._delta = 0;
|
||||
this._startTime = 0;
|
||||
this._lastY = 0;
|
||||
this._lastTime = 0;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { showConfirmationDialog } from "../../dialogs/generic/show-dialog-box";
|
||||
import "./ha-progress-button";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { Appearance } from "../ha-button";
|
||||
|
||||
@customElement("ha-call-service-button")
|
||||
class HaCallServiceButton extends LitElement {
|
||||
@@ -25,12 +26,14 @@ class HaCallServiceButton extends LitElement {
|
||||
|
||||
@property() public confirmation?;
|
||||
|
||||
@property() public appearance: Appearance = "plain";
|
||||
|
||||
public render(): TemplateResult {
|
||||
return html`
|
||||
<ha-progress-button
|
||||
.progress=${this.progress}
|
||||
.disabled=${this.disabled}
|
||||
appearance="plain"
|
||||
.appearance=${this.appearance}
|
||||
@click=${this._buttonTapped}
|
||||
tabindex="0"
|
||||
>
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import type { LineSeriesOption } from "echarts";
|
||||
|
||||
export function downSampleLineData(
|
||||
data: LineSeriesOption["data"],
|
||||
chartWidth: number,
|
||||
export function downSampleLineData<
|
||||
T extends [number, number] | NonNullable<LineSeriesOption["data"]>[number],
|
||||
>(
|
||||
data: T[] | undefined,
|
||||
maxDetails: number,
|
||||
minX?: number,
|
||||
maxX?: number
|
||||
) {
|
||||
if (!data || data.length < 10) {
|
||||
return data;
|
||||
): T[] {
|
||||
if (!data) {
|
||||
return [];
|
||||
}
|
||||
const width = chartWidth * window.devicePixelRatio;
|
||||
if (data.length <= width) {
|
||||
if (data.length <= maxDetails) {
|
||||
return data;
|
||||
}
|
||||
const min = minX ?? getPointData(data[0]!)[0];
|
||||
const max = maxX ?? getPointData(data[data.length - 1]!)[0];
|
||||
const step = Math.floor((max - min) / width);
|
||||
const step = Math.ceil((max - min) / Math.floor(maxDetails));
|
||||
const frames = new Map<
|
||||
number,
|
||||
{
|
||||
@@ -47,7 +48,7 @@ export function downSampleLineData(
|
||||
}
|
||||
|
||||
// Convert frames back to points
|
||||
const result: typeof data = [];
|
||||
const result: T[] = [];
|
||||
for (const [_i, frame] of frames) {
|
||||
// Use min/max points to preserve visual accuracy
|
||||
// The order of the data must be preserved so max may be before min
|
||||
|
||||
@@ -22,7 +22,7 @@ import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { listenMediaQuery } from "../../common/dom/media_query";
|
||||
import { themesContext } from "../../data/context";
|
||||
import type { Themes } from "../../data/ws-themes";
|
||||
import type { ECOption } from "../../resources/echarts";
|
||||
import type { ECOption } from "../../resources/echarts/echarts";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { isMac } from "../../util/is_mac";
|
||||
import "../chips/ha-assist-chip";
|
||||
@@ -88,9 +88,21 @@ export class HaChartBase extends LitElement {
|
||||
|
||||
private _lastTapTime?: number;
|
||||
|
||||
private _shouldResizeChart = false;
|
||||
|
||||
private _resizeAnimationDuration?: number;
|
||||
|
||||
// @ts-ignore
|
||||
private _resizeController = new ResizeController(this, {
|
||||
callback: () => this.chart?.resize(),
|
||||
callback: () => {
|
||||
if (this.chart) {
|
||||
if (!this.chart.getZr().animation.isFinished()) {
|
||||
this._shouldResizeChart = true;
|
||||
} else {
|
||||
this.chart.resize();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
private _loading = false;
|
||||
@@ -195,6 +207,16 @@ export class HaChartBase extends LitElement {
|
||||
}
|
||||
if (changedProps.has("options")) {
|
||||
chartOptions = { ...chartOptions, ...this._createOptions() };
|
||||
if (
|
||||
this._compareCustomLegendOptions(
|
||||
changedProps.get("options"),
|
||||
this.options
|
||||
)
|
||||
) {
|
||||
// custom legend changes may require a resize to layout properly
|
||||
this._shouldResizeChart = true;
|
||||
this._resizeAnimationDuration = 250;
|
||||
}
|
||||
} else if (this._isTouchDevice && changedProps.has("_isZoomed")) {
|
||||
chartOptions.dataZoom = this._getDataZoomConfig();
|
||||
}
|
||||
@@ -286,7 +308,7 @@ export class HaChartBase extends LitElement {
|
||||
itemStyle = {
|
||||
color: dataset?.color as string,
|
||||
...(dataset?.itemStyle as { borderColor?: string }),
|
||||
itemStyle,
|
||||
...itemStyle,
|
||||
};
|
||||
const color = itemStyle?.color as string;
|
||||
const borderColor = itemStyle?.borderColor as string;
|
||||
@@ -346,7 +368,7 @@ export class HaChartBase extends LitElement {
|
||||
if (this.chart) {
|
||||
this.chart.dispose();
|
||||
}
|
||||
const echarts = (await import("../../resources/echarts")).default;
|
||||
const echarts = (await import("../../resources/echarts/echarts")).default;
|
||||
|
||||
if (this.extraComponents?.length) {
|
||||
echarts.use(this.extraComponents);
|
||||
@@ -366,6 +388,7 @@ export class HaChartBase extends LitElement {
|
||||
if (!this.options?.dataZoom) {
|
||||
this.chart.getZr().on("dblclick", this._handleClickZoom);
|
||||
}
|
||||
this.chart.on("finished", this._handleChartRenderFinished);
|
||||
if (this._isTouchDevice) {
|
||||
this.chart.getZr().on("click", (e: ECElementEvent) => {
|
||||
if (!e.zrByTouch) {
|
||||
@@ -497,6 +520,7 @@ export class HaChartBase extends LitElement {
|
||||
);
|
||||
}
|
||||
});
|
||||
this.requestUpdate("_hiddenDatasets");
|
||||
}
|
||||
|
||||
private _getDataZoomConfig(): DataZoomComponentOption | undefined {
|
||||
@@ -630,6 +654,13 @@ export class HaChartBase extends LitElement {
|
||||
textBorderWidth: 2,
|
||||
},
|
||||
},
|
||||
pie: {
|
||||
label: {
|
||||
color: style.getPropertyValue("--primary-text-color"),
|
||||
textBorderColor: style.getPropertyValue("--primary-background-color"),
|
||||
textBorderWidth: 2,
|
||||
},
|
||||
},
|
||||
sankey: {
|
||||
label: {
|
||||
color: style.getPropertyValue("--primary-text-color"),
|
||||
@@ -805,7 +836,7 @@ export class HaChartBase extends LitElement {
|
||||
sampling: undefined,
|
||||
data: downSampleLineData(
|
||||
data as LineSeriesOption["data"],
|
||||
this.clientWidth,
|
||||
this.clientWidth * window.devicePixelRatio,
|
||||
minX,
|
||||
maxX
|
||||
),
|
||||
@@ -945,6 +976,36 @@ export class HaChartBase extends LitElement {
|
||||
});
|
||||
}
|
||||
|
||||
private _handleChartRenderFinished = () => {
|
||||
if (this._shouldResizeChart) {
|
||||
this.chart?.resize({
|
||||
animation:
|
||||
this._reducedMotion ||
|
||||
typeof this._resizeAnimationDuration !== "number"
|
||||
? undefined
|
||||
: { duration: this._resizeAnimationDuration },
|
||||
});
|
||||
this._shouldResizeChart = false;
|
||||
this._resizeAnimationDuration = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
private _compareCustomLegendOptions(
|
||||
oldOptions: ECOption | undefined,
|
||||
newOptions: ECOption | undefined
|
||||
): boolean {
|
||||
const oldLegends = ensureArray(
|
||||
oldOptions?.legend || []
|
||||
) as LegendComponentOption[];
|
||||
const newLegends = ensureArray(
|
||||
newOptions?.legend || []
|
||||
) as LegendComponentOption[];
|
||||
return (
|
||||
oldLegends.some((l) => l.show && l.type === "custom") !==
|
||||
newLegends.some((l) => l.show && l.type === "custom")
|
||||
);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { TopLevelFormatterParams } from "echarts/types/dist/shared";
|
||||
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { listenMediaQuery } from "../../common/dom/media_query";
|
||||
import type { ECOption } from "../../resources/echarts";
|
||||
import type { ECOption } from "../../resources/echarts/echarts";
|
||||
import "./ha-chart-base";
|
||||
import type { HaChartBase } from "./ha-chart-base";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { LitElement, html, css } from "lit";
|
||||
import type { EChartsType } from "echarts/core";
|
||||
import type { CallbackDataParams } from "echarts/types/dist/shared";
|
||||
import type { SankeySeriesOption } from "echarts/types/dist/echarts";
|
||||
import { SankeyChart } from "echarts/charts";
|
||||
import type { CallbackDataParams } from "echarts/types/src/util/types";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { ResizeController } from "@lit-labs/observers/resize-controller";
|
||||
import SankeyChart from "../../resources/echarts/components/sankey/install";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { ECOption } from "../../resources/echarts";
|
||||
import type { ECOption } from "../../resources/echarts/echarts";
|
||||
import { measureTextWidth } from "../../util/text";
|
||||
import { filterXSS } from "../../common/util/xss";
|
||||
import "./ha-chart-base";
|
||||
@@ -39,7 +39,7 @@ type ProcessedLink = Link & {
|
||||
|
||||
const OVERFLOW_MARGIN = 5;
|
||||
const FONT_SIZE = 12;
|
||||
const NODE_GAP = 8;
|
||||
const NODE_GAP = 6;
|
||||
const LABEL_DISTANCE = 5;
|
||||
|
||||
@customElement("ha-sankey-chart")
|
||||
@@ -164,6 +164,7 @@ export class HaSankeyChart extends LitElement {
|
||||
lineStyle: {
|
||||
color: "gradient",
|
||||
opacity: 0.4,
|
||||
curveness: 0.5,
|
||||
},
|
||||
layoutIterations: 0,
|
||||
label: {
|
||||
|
||||
@@ -11,7 +11,7 @@ import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import type { LineChartEntity, LineChartState } from "../../data/history";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { MIN_TIME_BETWEEN_UPDATES } from "./ha-chart-base";
|
||||
import type { ECOption } from "../../resources/echarts";
|
||||
import type { ECOption } from "../../resources/echarts/echarts";
|
||||
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
|
||||
import {
|
||||
getNumberFormatOptions,
|
||||
@@ -87,6 +87,8 @@ export class StateHistoryChartLine extends LitElement {
|
||||
|
||||
private _previousYAxisLabelValue = 0;
|
||||
|
||||
private _yAxisMaximumFractionDigits = 0;
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<ha-chart-base
|
||||
@@ -757,8 +759,12 @@ export class StateHistoryChartLine extends LitElement {
|
||||
Math.log10(Math.abs(value - this._previousYAxisLabelValue || 1))
|
||||
)
|
||||
);
|
||||
this._yAxisMaximumFractionDigits = Math.max(
|
||||
this._yAxisMaximumFractionDigits,
|
||||
maximumFractionDigits
|
||||
);
|
||||
const label = formatNumber(value, this.hass.locale, {
|
||||
maximumFractionDigits,
|
||||
maximumFractionDigits: this._yAxisMaximumFractionDigits,
|
||||
});
|
||||
const width = measureTextWidth(label, 12) + 5;
|
||||
if (width > this._yWidth) {
|
||||
|
||||
@@ -15,8 +15,8 @@ import type { TimelineEntity } from "../../data/history";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { MIN_TIME_BETWEEN_UPDATES } from "./ha-chart-base";
|
||||
import { computeTimelineColor } from "./timeline-color";
|
||||
import type { ECOption } from "../../resources/echarts";
|
||||
import echarts from "../../resources/echarts";
|
||||
import type { ECOption } from "../../resources/echarts/echarts";
|
||||
import echarts from "../../resources/echarts/echarts";
|
||||
import { luminosity } from "../../common/color/rgb";
|
||||
import { hex2rgb } from "../../common/color/convert-color";
|
||||
import { measureTextWidth } from "../../util/text";
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
getStatisticMetadata,
|
||||
statisticsHaveType,
|
||||
} from "../../data/recorder";
|
||||
import type { ECOption } from "../../resources/echarts";
|
||||
import type { ECOption } from "../../resources/echarts/echarts";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { CustomLegendOption } from "./ha-chart-base";
|
||||
import "./ha-chart-base";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { styles as elevatedStyles } from "@material/web/chips/internal/elevated-styles";
|
||||
import { FilterChip } from "@material/web/chips/internal/filter-chip";
|
||||
import { styles } from "@material/web/chips/internal/filter-styles";
|
||||
import { styles as selectableStyles } from "@material/web/chips/internal/selectable-styles";
|
||||
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles";
|
||||
import { styles as trailingIconStyles } from "@material/web/chips/internal/trailing-icon-styles";
|
||||
import { styles as elevatedStyles } from "@material/web/chips/internal/elevated-styles";
|
||||
import { css, html } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
|
||||
@@ -30,6 +30,7 @@ export class HaFilterChip extends FilterChip {
|
||||
var(--rgb-primary-text-color),
|
||||
0.15
|
||||
);
|
||||
border-radius: var(--ha-border-radius-md);
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mdiDrag, mdiEye, mdiEyeOff } from "@mdi/js";
|
||||
import { mdiDragHorizontalVariant, mdiEye, mdiEyeOff } from "@mdi/js";
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
@@ -129,7 +129,7 @@ export class DialogDataTableSettings extends LitElement {
|
||||
${canMove && isVisible
|
||||
? html`<ha-svg-icon
|
||||
class="handle"
|
||||
.path=${mdiDrag}
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
slot="graphic"
|
||||
></ha-svg-icon>`
|
||||
: nothing}
|
||||
|
||||
@@ -5,24 +5,18 @@ import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { computeAreaName } from "../../common/entity/compute_area_name";
|
||||
import {
|
||||
computeDeviceName,
|
||||
computeDeviceNameDisplay,
|
||||
} from "../../common/entity/compute_device_name";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import { computeDeviceName } from "../../common/entity/compute_device_name";
|
||||
import { getDeviceContext } from "../../common/entity/context/get_device_context";
|
||||
import { getConfigEntries, type ConfigEntry } from "../../data/config_entries";
|
||||
import {
|
||||
getDeviceEntityDisplayLookup,
|
||||
type DeviceEntityDisplayLookup,
|
||||
getDevices,
|
||||
type DevicePickerItem,
|
||||
type DeviceRegistryEntry,
|
||||
} from "../../data/device_registry";
|
||||
import { domainToName } from "../../data/integration";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { brandsUrl } from "../../util/brands-url";
|
||||
import "../ha-generic-picker";
|
||||
import type { HaGenericPicker } from "../ha-generic-picker";
|
||||
import type { PickerComboBoxItem } from "../ha-picker-combo-box";
|
||||
|
||||
export type HaDevicePickerDeviceFilterFunc = (
|
||||
device: DeviceRegistryEntry
|
||||
@@ -30,11 +24,6 @@ export type HaDevicePickerDeviceFilterFunc = (
|
||||
|
||||
export type HaDevicePickerEntityFilterFunc = (entity: HassEntity) => boolean;
|
||||
|
||||
interface DevicePickerItem extends PickerComboBoxItem {
|
||||
domain?: string;
|
||||
domain_name?: string;
|
||||
}
|
||||
|
||||
@customElement("ha-device-picker")
|
||||
export class HaDevicePicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@@ -104,6 +93,8 @@ export class HaDevicePicker extends LitElement {
|
||||
|
||||
@state() private _configEntryLookup: Record<string, ConfigEntry> = {};
|
||||
|
||||
private _getDevicesMemoized = memoizeOne(getDevices);
|
||||
|
||||
protected firstUpdated(_changedProperties: PropertyValues): void {
|
||||
super.firstUpdated(_changedProperties);
|
||||
this._loadConfigEntries();
|
||||
@@ -117,162 +108,18 @@ export class HaDevicePicker extends LitElement {
|
||||
}
|
||||
|
||||
private _getItems = () =>
|
||||
this._getDevices(
|
||||
this.hass.devices,
|
||||
this.hass.entities,
|
||||
this._getDevicesMemoized(
|
||||
this.hass,
|
||||
this._configEntryLookup,
|
||||
this.includeDomains,
|
||||
this.excludeDomains,
|
||||
this.includeDeviceClasses,
|
||||
this.deviceFilter,
|
||||
this.entityFilter,
|
||||
this.excludeDevices
|
||||
this.excludeDevices,
|
||||
this.value
|
||||
);
|
||||
|
||||
private _getDevices = memoizeOne(
|
||||
(
|
||||
haDevices: HomeAssistant["devices"],
|
||||
haEntities: HomeAssistant["entities"],
|
||||
configEntryLookup: Record<string, ConfigEntry>,
|
||||
includeDomains: this["includeDomains"],
|
||||
excludeDomains: this["excludeDomains"],
|
||||
includeDeviceClasses: this["includeDeviceClasses"],
|
||||
deviceFilter: this["deviceFilter"],
|
||||
entityFilter: this["entityFilter"],
|
||||
excludeDevices: this["excludeDevices"]
|
||||
): DevicePickerItem[] => {
|
||||
const devices = Object.values(haDevices);
|
||||
const entities = Object.values(haEntities);
|
||||
|
||||
let deviceEntityLookup: DeviceEntityDisplayLookup = {};
|
||||
|
||||
if (
|
||||
includeDomains ||
|
||||
excludeDomains ||
|
||||
includeDeviceClasses ||
|
||||
entityFilter
|
||||
) {
|
||||
deviceEntityLookup = getDeviceEntityDisplayLookup(entities);
|
||||
}
|
||||
|
||||
let inputDevices = devices.filter(
|
||||
(device) => device.id === this.value || !device.disabled_by
|
||||
);
|
||||
|
||||
if (includeDomains) {
|
||||
inputDevices = inputDevices.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) =>
|
||||
includeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (excludeDomains) {
|
||||
inputDevices = inputDevices.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return true;
|
||||
}
|
||||
return entities.every(
|
||||
(entity) =>
|
||||
!excludeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (excludeDevices) {
|
||||
inputDevices = inputDevices.filter(
|
||||
(device) => !excludeDevices!.includes(device.id)
|
||||
);
|
||||
}
|
||||
|
||||
if (includeDeviceClasses) {
|
||||
inputDevices = inputDevices.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
stateObj.attributes.device_class &&
|
||||
includeDeviceClasses.includes(stateObj.attributes.device_class)
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (entityFilter) {
|
||||
inputDevices = inputDevices.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return devEntities.some((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return entityFilter(stateObj);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (deviceFilter) {
|
||||
inputDevices = inputDevices.filter(
|
||||
(device) =>
|
||||
// We always want to include the device of the current value
|
||||
device.id === this.value || deviceFilter!(device)
|
||||
);
|
||||
}
|
||||
|
||||
const outputDevices = inputDevices.map<DevicePickerItem>((device) => {
|
||||
const deviceName = computeDeviceNameDisplay(
|
||||
device,
|
||||
this.hass,
|
||||
deviceEntityLookup[device.id]
|
||||
);
|
||||
|
||||
const { area } = getDeviceContext(device, this.hass);
|
||||
|
||||
const areaName = area ? computeAreaName(area) : undefined;
|
||||
|
||||
const configEntry = device.primary_config_entry
|
||||
? configEntryLookup?.[device.primary_config_entry]
|
||||
: undefined;
|
||||
|
||||
const domain = configEntry?.domain;
|
||||
const domainName = domain
|
||||
? domainToName(this.hass.localize, domain)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: device.id,
|
||||
label: "",
|
||||
primary:
|
||||
deviceName ||
|
||||
this.hass.localize("ui.components.device-picker.unnamed_device"),
|
||||
secondary: areaName,
|
||||
domain: configEntry?.domain,
|
||||
domain_name: domainName,
|
||||
search_labels: [deviceName, areaName, domain, domainName].filter(
|
||||
Boolean
|
||||
) as string[],
|
||||
sorting_label: deviceName || "zzz",
|
||||
};
|
||||
});
|
||||
|
||||
return outputDevices;
|
||||
}
|
||||
);
|
||||
|
||||
private _valueRenderer = memoizeOne(
|
||||
(configEntriesLookup: Record<string, ConfigEntry>) => (value: string) => {
|
||||
const deviceId = value;
|
||||
|
||||
1
src/components/entity/const.ts
Normal file
1
src/components/entity/const.ts
Normal file
@@ -0,0 +1 @@
|
||||
export const ANY_STATE_VALUE = "__ANY_STATE_IGNORE_ATTRIBUTES__";
|
||||
@@ -1,13 +1,13 @@
|
||||
import { mdiDrag } from "@mdi/js";
|
||||
import { mdiDragHorizontalVariant } from "@mdi/js";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { isValidEntityId } from "../../common/entity/valid_entity_id";
|
||||
import type { HaEntityPickerEntityFilterFunc } from "../../data/entity";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../types";
|
||||
import "../ha-sortable";
|
||||
import "./ha-entity-picker";
|
||||
import type { HaEntityPickerEntityFilterFunc } from "./ha-entity-picker";
|
||||
|
||||
@customElement("ha-entities-picker")
|
||||
class HaEntitiesPicker extends LitElement {
|
||||
@@ -118,7 +118,7 @@ class HaEntitiesPicker extends LitElement {
|
||||
? html`
|
||||
<ha-svg-icon
|
||||
class="entity-handle"
|
||||
.path=${mdiDrag}
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
></ha-svg-icon>
|
||||
`
|
||||
: nothing}
|
||||
@@ -147,6 +147,7 @@ class HaEntitiesPicker extends LitElement {
|
||||
.createDomains=${this.createDomains}
|
||||
.required=${this.required && !currentEntities.length}
|
||||
@value-changed=${this._addEntity}
|
||||
.addButton=${currentEntities.length > 0}
|
||||
></ha-entity-picker>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, html, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
@@ -8,8 +7,6 @@ import type { HomeAssistant, ValueChangedEvent } from "../../types";
|
||||
import "../ha-combo-box";
|
||||
import type { HaComboBox } from "../ha-combo-box";
|
||||
|
||||
export type HaEntityPickerEntityFilterFunc = (entityId: HassEntity) => boolean;
|
||||
|
||||
interface AttributeOption {
|
||||
value: string;
|
||||
label: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import "@material/mwc-menu/mwc-menu-surface";
|
||||
import { mdiDrag, mdiPlus } from "@mdi/js";
|
||||
import { mdiDragHorizontalVariant, mdiPlus } from "@mdi/js";
|
||||
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit";
|
||||
import type { IFuseOptions } from "fuse.js";
|
||||
import Fuse from "fuse.js";
|
||||
@@ -20,11 +20,13 @@ import "../chips/ha-chip-set";
|
||||
import "../chips/ha-input-chip";
|
||||
import "../ha-combo-box";
|
||||
import type { HaComboBox } from "../ha-combo-box";
|
||||
import "../ha-input-helper-text";
|
||||
import "../ha-sortable";
|
||||
|
||||
interface EntityNameOption {
|
||||
primary: string;
|
||||
secondary?: string;
|
||||
field_label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
@@ -41,6 +43,23 @@ const KNOWN_TYPES = new Set(["entity", "device", "area", "floor"]);
|
||||
|
||||
const UNIQUE_TYPES = new Set(["entity", "device", "area", "floor"]);
|
||||
|
||||
const formatOptionValue = (item: EntityNameItem) => {
|
||||
if (item.type === "text" && item.text) {
|
||||
return item.text;
|
||||
}
|
||||
return `___${item.type}___`;
|
||||
};
|
||||
|
||||
const parseOptionValue = (value: string): EntityNameItem => {
|
||||
if (value.startsWith("___") && value.endsWith("___")) {
|
||||
const type = value.slice(3, -3);
|
||||
if (KNOWN_TYPES.has(type)) {
|
||||
return { type: type as EntityNameType };
|
||||
}
|
||||
}
|
||||
return { type: "text", text: value };
|
||||
};
|
||||
|
||||
@customElement("ha-entity-name-picker")
|
||||
export class HaEntityNamePicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@@ -68,8 +87,8 @@ export class HaEntityNamePicker extends LitElement {
|
||||
|
||||
private _editIndex?: number;
|
||||
|
||||
private _validOptions = memoizeOne((entityId?: string) => {
|
||||
const options = new Set<string>();
|
||||
private _validTypes = memoizeOne((entityId?: string) => {
|
||||
const options = new Set<string>(["text"]);
|
||||
if (!entityId) {
|
||||
return options;
|
||||
}
|
||||
@@ -101,33 +120,43 @@ export class HaEntityNamePicker extends LitElement {
|
||||
return [];
|
||||
}
|
||||
|
||||
const options = this._validOptions(entityId);
|
||||
const types = this._validTypes(entityId);
|
||||
|
||||
const items = (
|
||||
["entity", "device", "area", "floor"] as const
|
||||
).map<EntityNameOption>((name) => {
|
||||
const stateObj = this.hass.states[entityId];
|
||||
const isValid = options.has(name);
|
||||
const isValid = types.has(name);
|
||||
const primary = this.hass.localize(
|
||||
`ui.components.entity.entity-name-picker.types.${name}`
|
||||
);
|
||||
const secondary =
|
||||
stateObj && isValid
|
||||
(stateObj && isValid
|
||||
? this.hass.formatEntityName(stateObj, { type: name })
|
||||
: this.hass.localize(
|
||||
`ui.components.entity.entity-name-picker.types.${name}_missing` as LocalizeKeys
|
||||
) || "-";
|
||||
)) || "-";
|
||||
|
||||
return {
|
||||
primary,
|
||||
secondary,
|
||||
value: name,
|
||||
field_label: primary,
|
||||
value: formatOptionValue({ type: name }),
|
||||
};
|
||||
});
|
||||
|
||||
return items;
|
||||
});
|
||||
|
||||
private _customNameOption = memoizeOne((text: string) => ({
|
||||
primary: this.hass.localize(
|
||||
"ui.components.entity.entity-name-picker.custom_name"
|
||||
),
|
||||
secondary: `"${text}"`,
|
||||
field_label: text,
|
||||
value: formatOptionValue({ type: "text", text }),
|
||||
}));
|
||||
|
||||
private _formatItem = (item: EntityNameItem) => {
|
||||
if (item.type === "text") {
|
||||
return `"${item.text}"`;
|
||||
@@ -141,9 +170,9 @@ export class HaEntityNamePicker extends LitElement {
|
||||
};
|
||||
|
||||
protected render() {
|
||||
const value = this._value;
|
||||
const value = this._items;
|
||||
const options = this._getOptions(this.entityId);
|
||||
const validOptions = this._validOptions(this.entityId);
|
||||
const validTypes = this._validTypes(this.entityId);
|
||||
|
||||
return html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
@@ -157,12 +186,11 @@ export class HaEntityNamePicker extends LitElement {
|
||||
>
|
||||
<ha-chip-set>
|
||||
${repeat(
|
||||
this._value,
|
||||
this._items,
|
||||
(item) => item,
|
||||
(item: EntityNameItem, idx) => {
|
||||
const label = this._formatItem(item);
|
||||
const isValid =
|
||||
item.type === "text" || validOptions.has(item.type);
|
||||
const isValid = validTypes.has(item.type);
|
||||
return html`
|
||||
<ha-input-chip
|
||||
data-idx=${idx}
|
||||
@@ -173,7 +201,10 @@ export class HaEntityNamePicker extends LitElement {
|
||||
.disabled=${this.disabled}
|
||||
class=${!isValid ? "invalid" : ""}
|
||||
>
|
||||
<ha-svg-icon slot="icon" .path=${mdiDrag}></ha-svg-icon>
|
||||
<ha-svg-icon
|
||||
slot="icon"
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
></ha-svg-icon>
|
||||
<span>${label}</span>
|
||||
</ha-input-chip>
|
||||
`;
|
||||
@@ -207,14 +238,13 @@ export class HaEntityNamePicker extends LitElement {
|
||||
.hass=${this.hass}
|
||||
.value=${""}
|
||||
.autofocus=${this.autofocus}
|
||||
.disabled=${this.disabled || !this.entityId}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required && !value.length}
|
||||
.helper=${this.helper}
|
||||
.items=${options}
|
||||
allow-custom-value
|
||||
item-id-path="value"
|
||||
item-value-path="value"
|
||||
item-label-path="primary"
|
||||
item-label-path="field_label"
|
||||
.renderer=${rowRenderer}
|
||||
@opened-changed=${this._openedChanged}
|
||||
@value-changed=${this._comboBoxValueChanged}
|
||||
@@ -223,9 +253,20 @@ export class HaEntityNamePicker extends LitElement {
|
||||
</ha-combo-box>
|
||||
</mwc-menu-surface>
|
||||
</div>
|
||||
${this._renderHelper()}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderHelper() {
|
||||
return this.helper
|
||||
? html`
|
||||
<ha-input-helper-text .disabled=${this.disabled}>
|
||||
${this.helper}
|
||||
</ha-input-helper-text>
|
||||
`
|
||||
: nothing;
|
||||
}
|
||||
|
||||
private _onClosed(ev) {
|
||||
ev.stopPropagation();
|
||||
this._opened = false;
|
||||
@@ -254,13 +295,16 @@ export class HaEntityNamePicker extends LitElement {
|
||||
this._opened = true;
|
||||
}
|
||||
|
||||
private get _value(): EntityNameItem[] {
|
||||
private get _items(): EntityNameItem[] {
|
||||
return this._toItems(this.value);
|
||||
}
|
||||
|
||||
private _toItems = memoizeOne((value?: typeof this.value) => {
|
||||
if (typeof value === "string") {
|
||||
return [{ type: "text", text: value } as const];
|
||||
if (value === "") {
|
||||
return [];
|
||||
}
|
||||
return [{ type: "text", text: value } satisfies EntityNameItem];
|
||||
}
|
||||
return value ? ensureArray(value) : [];
|
||||
});
|
||||
@@ -268,7 +312,7 @@ export class HaEntityNamePicker extends LitElement {
|
||||
private _toValue = memoizeOne(
|
||||
(items: EntityNameItem[]): typeof this.value => {
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
return undefined;
|
||||
}
|
||||
if (items.length === 1) {
|
||||
const item = items[0];
|
||||
@@ -284,20 +328,21 @@ export class HaEntityNamePicker extends LitElement {
|
||||
const options = this._comboBox.items || [];
|
||||
|
||||
const initialItem =
|
||||
this._editIndex != null ? this._value[this._editIndex] : undefined;
|
||||
this._editIndex != null ? this._items[this._editIndex] : undefined;
|
||||
|
||||
const initialValue = initialItem
|
||||
? initialItem.type === "text"
|
||||
? initialItem.text
|
||||
: initialItem.type
|
||||
: "";
|
||||
const initialValue = initialItem ? formatOptionValue(initialItem) : "";
|
||||
|
||||
const filteredItems = this._filterSelectedOptions(options, initialValue);
|
||||
|
||||
if (initialItem?.type === "text" && initialItem.text) {
|
||||
filteredItems.push(this._customNameOption(initialItem.text));
|
||||
}
|
||||
|
||||
this._comboBox.filteredItems = filteredItems;
|
||||
this._comboBox.setInputValue(initialValue);
|
||||
} else {
|
||||
this._opened = false;
|
||||
this._comboBox.setInputValue("");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,15 +350,16 @@ export class HaEntityNamePicker extends LitElement {
|
||||
options: EntityNameOption[],
|
||||
current?: string
|
||||
) => {
|
||||
const value = this._value;
|
||||
const items = this._items;
|
||||
|
||||
const types = value.map((item) => item.type) as string[];
|
||||
const excludedValues = new Set(
|
||||
items
|
||||
.filter((item) => UNIQUE_TYPES.has(item.type))
|
||||
.map((item) => formatOptionValue(item))
|
||||
);
|
||||
|
||||
const filteredOptions = options.filter(
|
||||
(option) =>
|
||||
!UNIQUE_TYPES.has(option.value) ||
|
||||
!types.includes(option.value) ||
|
||||
option.value === current
|
||||
(option) => !excludedValues.has(option.value) || option.value === current
|
||||
);
|
||||
return filteredOptions;
|
||||
};
|
||||
@@ -324,20 +370,14 @@ export class HaEntityNamePicker extends LitElement {
|
||||
const options = this._comboBox.items || [];
|
||||
|
||||
const currentItem =
|
||||
this._editIndex != null ? this._value[this._editIndex] : undefined;
|
||||
this._editIndex != null ? this._items[this._editIndex] : undefined;
|
||||
|
||||
const currentValue = currentItem
|
||||
? currentItem.type === "text"
|
||||
? currentItem.text
|
||||
: currentItem.type
|
||||
: "";
|
||||
const currentValue = currentItem ? formatOptionValue(currentItem) : "";
|
||||
|
||||
this._comboBox.filteredItems = this._filterSelectedOptions(
|
||||
options,
|
||||
currentValue
|
||||
);
|
||||
let filteredItems = this._filterSelectedOptions(options, currentValue);
|
||||
|
||||
if (!filter) {
|
||||
this._comboBox.filteredItems = filteredItems;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -349,16 +389,16 @@ export class HaEntityNamePicker extends LitElement {
|
||||
ignoreDiacritics: true,
|
||||
};
|
||||
|
||||
const fuse = new Fuse(this._comboBox.filteredItems, fuseOptions);
|
||||
const filteredItems = fuse.search(filter).map((result) => result.item);
|
||||
|
||||
const fuse = new Fuse(filteredItems, fuseOptions);
|
||||
filteredItems = fuse.search(filter).map((result) => result.item);
|
||||
filteredItems.push(this._customNameOption(input));
|
||||
this._comboBox.filteredItems = filteredItems;
|
||||
}
|
||||
|
||||
private async _moveItem(ev: CustomEvent) {
|
||||
ev.stopPropagation();
|
||||
const { oldIndex, newIndex } = ev.detail;
|
||||
const value = this._value;
|
||||
const value = this._items;
|
||||
const newValue = value.concat();
|
||||
const element = newValue.splice(oldIndex, 1)[0];
|
||||
newValue.splice(newIndex, 0, element);
|
||||
@@ -369,7 +409,7 @@ export class HaEntityNamePicker extends LitElement {
|
||||
|
||||
private async _removeItem(ev) {
|
||||
ev.stopPropagation();
|
||||
const value = [...this._value];
|
||||
const value = [...this._items];
|
||||
const idx = parseInt(ev.target.dataset.idx, 10);
|
||||
value.splice(idx, 1);
|
||||
this._setValue(value);
|
||||
@@ -385,11 +425,9 @@ export class HaEntityNamePicker extends LitElement {
|
||||
return;
|
||||
}
|
||||
|
||||
const item: EntityNameItem = KNOWN_TYPES.has(value as any)
|
||||
? { type: value as EntityNameType }
|
||||
: { type: "text", text: value };
|
||||
const item: EntityNameItem = parseOptionValue(value);
|
||||
|
||||
const newValue = [...this._value];
|
||||
const newValue = [...this._items];
|
||||
|
||||
if (this._editIndex != null) {
|
||||
newValue[this._editIndex] = item;
|
||||
@@ -483,6 +521,11 @@ export class HaEntityNamePicker extends LitElement {
|
||||
.sortable-drag {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
ha-input-helper-text {
|
||||
display: block;
|
||||
margin: var(--ha-space-2) 0 0;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { mdiPlus, mdiShape } from "@mdi/js";
|
||||
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing, type PropertyValues } from "lit";
|
||||
import { customElement, property, query } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import { computeEntityNameList } from "../../common/entity/compute_entity_name_display";
|
||||
import { computeStateName } from "../../common/entity/compute_state_name";
|
||||
import { isValidEntityId } from "../../common/entity/valid_entity_id";
|
||||
import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import type { HaEntityPickerEntityFilterFunc } from "../../data/entity";
|
||||
import {
|
||||
getEntities,
|
||||
type EntityComboBoxItem,
|
||||
} from "../../data/entity_registry";
|
||||
import { domainToName } from "../../data/integration";
|
||||
import {
|
||||
isHelperDomain,
|
||||
@@ -20,21 +22,11 @@ import type { HomeAssistant } from "../../types";
|
||||
import "../ha-combo-box-item";
|
||||
import "../ha-generic-picker";
|
||||
import type { HaGenericPicker } from "../ha-generic-picker";
|
||||
import type {
|
||||
PickerComboBoxItem,
|
||||
PickerComboBoxSearchFn,
|
||||
} from "../ha-picker-combo-box";
|
||||
import type { PickerComboBoxSearchFn } from "../ha-picker-combo-box";
|
||||
import type { PickerValueRenderer } from "../ha-picker-field";
|
||||
import "../ha-svg-icon";
|
||||
import "./state-badge";
|
||||
|
||||
interface EntityComboBoxItem extends PickerComboBoxItem {
|
||||
domain_name?: string;
|
||||
stateObj?: HassEntity;
|
||||
}
|
||||
|
||||
export type HaEntityPickerEntityFilterFunc = (entity: HassEntity) => boolean;
|
||||
|
||||
const CREATE_ID = "___create-new-entity___";
|
||||
|
||||
@customElement("ha-entity-picker")
|
||||
@@ -121,6 +113,9 @@ export class HaEntityPicker extends LitElement {
|
||||
@property({ attribute: "hide-clear-icon", type: Boolean })
|
||||
public hideClearIcon = false;
|
||||
|
||||
@property({ attribute: "add-button", type: Boolean })
|
||||
public addButton = false;
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
protected firstUpdated(changedProperties: PropertyValues): void {
|
||||
@@ -255,8 +250,10 @@ export class HaEntityPicker extends LitElement {
|
||||
}
|
||||
);
|
||||
|
||||
private _getEntitiesMemoized = memoizeOne(getEntities);
|
||||
|
||||
private _getItems = () =>
|
||||
this._getEntities(
|
||||
this._getEntitiesMemoized(
|
||||
this.hass,
|
||||
this.includeDomains,
|
||||
this.excludeDomains,
|
||||
@@ -264,128 +261,10 @@ export class HaEntityPicker extends LitElement {
|
||||
this.includeDeviceClasses,
|
||||
this.includeUnitOfMeasurement,
|
||||
this.includeEntities,
|
||||
this.excludeEntities
|
||||
this.excludeEntities,
|
||||
this.value
|
||||
);
|
||||
|
||||
private _getEntities = memoizeOne(
|
||||
(
|
||||
hass: this["hass"],
|
||||
includeDomains: this["includeDomains"],
|
||||
excludeDomains: this["excludeDomains"],
|
||||
entityFilter: this["entityFilter"],
|
||||
includeDeviceClasses: this["includeDeviceClasses"],
|
||||
includeUnitOfMeasurement: this["includeUnitOfMeasurement"],
|
||||
includeEntities: this["includeEntities"],
|
||||
excludeEntities: this["excludeEntities"]
|
||||
): EntityComboBoxItem[] => {
|
||||
let items: EntityComboBoxItem[] = [];
|
||||
|
||||
let entityIds = Object.keys(hass.states);
|
||||
|
||||
if (includeEntities) {
|
||||
entityIds = entityIds.filter((entityId) =>
|
||||
includeEntities.includes(entityId)
|
||||
);
|
||||
}
|
||||
|
||||
if (excludeEntities) {
|
||||
entityIds = entityIds.filter(
|
||||
(entityId) => !excludeEntities.includes(entityId)
|
||||
);
|
||||
}
|
||||
|
||||
if (includeDomains) {
|
||||
entityIds = entityIds.filter((eid) =>
|
||||
includeDomains.includes(computeDomain(eid))
|
||||
);
|
||||
}
|
||||
|
||||
if (excludeDomains) {
|
||||
entityIds = entityIds.filter(
|
||||
(eid) => !excludeDomains.includes(computeDomain(eid))
|
||||
);
|
||||
}
|
||||
|
||||
const isRTL = computeRTL(hass);
|
||||
|
||||
items = entityIds.map<EntityComboBoxItem>((entityId) => {
|
||||
const stateObj = hass.states[entityId];
|
||||
|
||||
const friendlyName = computeStateName(stateObj); // Keep this for search
|
||||
|
||||
const [entityName, deviceName, areaName] = computeEntityNameList(
|
||||
stateObj,
|
||||
[{ type: "entity" }, { type: "device" }, { type: "area" }],
|
||||
hass.entities,
|
||||
hass.devices,
|
||||
hass.areas,
|
||||
hass.floors
|
||||
);
|
||||
|
||||
const domainName = domainToName(hass.localize, computeDomain(entityId));
|
||||
|
||||
const primary = entityName || deviceName || entityId;
|
||||
const secondary = [areaName, entityName ? deviceName : undefined]
|
||||
.filter(Boolean)
|
||||
.join(isRTL ? " ◂ " : " ▸ ");
|
||||
const a11yLabel = [deviceName, entityName].filter(Boolean).join(" - ");
|
||||
|
||||
return {
|
||||
id: entityId,
|
||||
primary: primary,
|
||||
secondary: secondary,
|
||||
domain_name: domainName,
|
||||
sorting_label: [deviceName, entityName].filter(Boolean).join("_"),
|
||||
search_labels: [
|
||||
entityName,
|
||||
deviceName,
|
||||
areaName,
|
||||
domainName,
|
||||
friendlyName,
|
||||
entityId,
|
||||
].filter(Boolean) as string[],
|
||||
a11y_label: a11yLabel,
|
||||
stateObj: stateObj,
|
||||
};
|
||||
});
|
||||
|
||||
if (includeDeviceClasses) {
|
||||
items = items.filter(
|
||||
(item) =>
|
||||
// We always want to include the entity of the current value
|
||||
item.id === this.value ||
|
||||
(item.stateObj?.attributes.device_class &&
|
||||
includeDeviceClasses.includes(
|
||||
item.stateObj.attributes.device_class
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
if (includeUnitOfMeasurement) {
|
||||
items = items.filter(
|
||||
(item) =>
|
||||
// We always want to include the entity of the current value
|
||||
item.id === this.value ||
|
||||
(item.stateObj?.attributes.unit_of_measurement &&
|
||||
includeUnitOfMeasurement.includes(
|
||||
item.stateObj.attributes.unit_of_measurement
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
if (entityFilter) {
|
||||
items = items.filter(
|
||||
(item) =>
|
||||
// We always want to include the entity of the current value
|
||||
item.id === this.value ||
|
||||
(item.stateObj && entityFilter!(item.stateObj))
|
||||
);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
);
|
||||
|
||||
protected render() {
|
||||
const placeholder =
|
||||
this.placeholder ??
|
||||
@@ -405,7 +284,7 @@ export class HaEntityPicker extends LitElement {
|
||||
.searchLabel=${this.searchLabel}
|
||||
.notFoundLabel=${notFoundLabel}
|
||||
.placeholder=${placeholder}
|
||||
.value=${this.value}
|
||||
.value=${this.addButton ? undefined : this.value}
|
||||
.rowRenderer=${this._rowRenderer}
|
||||
.getItems=${this._getItems}
|
||||
.getAdditionalItems=${this._getAdditionalItems}
|
||||
@@ -413,6 +292,9 @@ export class HaEntityPicker extends LitElement {
|
||||
.searchFn=${this._searchFn}
|
||||
.valueRenderer=${this._valueRenderer}
|
||||
@value-changed=${this._valueChanged}
|
||||
.addButtonLabel=${this.addButton
|
||||
? this.hass.localize("ui.components.entity.entity-picker.add")
|
||||
: undefined}
|
||||
>
|
||||
</ha-generic-picker>
|
||||
`;
|
||||
|
||||
@@ -1,23 +1,39 @@
|
||||
import { mdiDrag } from "@mdi/js";
|
||||
import "@material/mwc-menu/mwc-menu-surface";
|
||||
import { mdiDragHorizontalVariant, mdiPlus } from "@mdi/js";
|
||||
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit";
|
||||
import type { IFuseOptions } from "fuse.js";
|
||||
import Fuse from "fuse.js";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { ensureArray } from "../../common/array/ensure-array";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { stopPropagation } from "../../common/dom/stop_propagation";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import {
|
||||
STATE_DISPLAY_SPECIAL_CONTENT,
|
||||
STATE_DISPLAY_SPECIAL_CONTENT_DOMAINS,
|
||||
} from "../../state-display/state-display";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../types";
|
||||
import "../ha-combo-box";
|
||||
import "../ha-sortable";
|
||||
import "../chips/ha-input-chip";
|
||||
import "../chips/ha-assist-chip";
|
||||
import "../chips/ha-chip-set";
|
||||
import "../chips/ha-input-chip";
|
||||
import "../ha-combo-box";
|
||||
import type { HaComboBox } from "../ha-combo-box";
|
||||
import "../ha-sortable";
|
||||
|
||||
interface StateContentOption {
|
||||
primary: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const rowRenderer: ComboBoxLitRenderer<StateContentOption> = (item) => html`
|
||||
<ha-combo-box-item type="button">
|
||||
<span slot="headline">${item.primary}</span>
|
||||
</ha-combo-box-item>
|
||||
`;
|
||||
|
||||
const HIDDEN_ATTRIBUTES = [
|
||||
"access_token",
|
||||
@@ -74,7 +90,7 @@ const HIDDEN_ATTRIBUTES = [
|
||||
];
|
||||
|
||||
@customElement("ha-entity-state-content-picker")
|
||||
class HaEntityStatePicker extends LitElement {
|
||||
export class HaStateContentPicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public entityId?: string;
|
||||
@@ -95,26 +111,28 @@ class HaEntityStatePicker extends LitElement {
|
||||
|
||||
@property() public helper?: string;
|
||||
|
||||
@state() private _opened = false;
|
||||
@query(".container", true) private _container?: HTMLDivElement;
|
||||
|
||||
@query("ha-combo-box", true) private _comboBox!: HaComboBox;
|
||||
|
||||
protected shouldUpdate(changedProps: PropertyValues) {
|
||||
return !(!changedProps.has("_opened") && this._opened);
|
||||
}
|
||||
@state() private _opened = false;
|
||||
|
||||
private options = memoizeOne(
|
||||
private _editIndex?: number;
|
||||
|
||||
private _options = memoizeOne(
|
||||
(entityId?: string, stateObj?: HassEntity, allowName?: boolean) => {
|
||||
const domain = entityId ? computeDomain(entityId) : undefined;
|
||||
return [
|
||||
{
|
||||
label: this.hass.localize("ui.components.state-content-picker.state"),
|
||||
primary: this.hass.localize(
|
||||
"ui.components.state-content-picker.state"
|
||||
),
|
||||
value: "state",
|
||||
},
|
||||
...(allowName
|
||||
? [
|
||||
{
|
||||
label: this.hass.localize(
|
||||
primary: this.hass.localize(
|
||||
"ui.components.state-content-picker.name"
|
||||
),
|
||||
value: "name",
|
||||
@@ -122,13 +140,13 @@ class HaEntityStatePicker extends LitElement {
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: this.hass.localize(
|
||||
primary: this.hass.localize(
|
||||
"ui.components.state-content-picker.last_changed"
|
||||
),
|
||||
value: "last_changed",
|
||||
},
|
||||
{
|
||||
label: this.hass.localize(
|
||||
primary: this.hass.localize(
|
||||
"ui.components.state-content-picker.last_updated"
|
||||
),
|
||||
value: "last_updated",
|
||||
@@ -137,7 +155,7 @@ class HaEntityStatePicker extends LitElement {
|
||||
? STATE_DISPLAY_SPECIAL_CONTENT.filter((content) =>
|
||||
STATE_DISPLAY_SPECIAL_CONTENT_DOMAINS[domain]?.includes(content)
|
||||
).map((content) => ({
|
||||
label: this.hass.localize(
|
||||
primary: this.hass.localize(
|
||||
`ui.components.state-content-picker.${content}`
|
||||
),
|
||||
value: content,
|
||||
@@ -146,105 +164,201 @@ class HaEntityStatePicker extends LitElement {
|
||||
...Object.keys(stateObj?.attributes ?? {})
|
||||
.filter((a) => !HIDDEN_ATTRIBUTES.includes(a))
|
||||
.map((attribute) => ({
|
||||
primary: this.hass.formatEntityAttributeName(stateObj!, attribute),
|
||||
value: attribute,
|
||||
label: this.hass.formatEntityAttributeName(stateObj!, attribute),
|
||||
})),
|
||||
];
|
||||
] satisfies StateContentOption[];
|
||||
}
|
||||
);
|
||||
|
||||
private _filter = "";
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const value = this._value;
|
||||
|
||||
const stateObj = this.entityId
|
||||
? this.hass.states[this.entityId]
|
||||
: undefined;
|
||||
|
||||
const options = this.options(this.entityId, stateObj, this.allowName);
|
||||
const optionItems = options.filter(
|
||||
(option) => !this._value.includes(option.value)
|
||||
);
|
||||
const options = this._options(this.entityId, stateObj, this.allowName);
|
||||
|
||||
return html`
|
||||
${value?.length
|
||||
? html`
|
||||
<ha-sortable
|
||||
no-style
|
||||
@item-moved=${this._moveItem}
|
||||
.disabled=${this.disabled}
|
||||
handle-selector="button.primary.action"
|
||||
>
|
||||
<ha-chip-set>
|
||||
${repeat(
|
||||
this._value,
|
||||
(item) => item,
|
||||
(item, idx) => {
|
||||
const label =
|
||||
options.find((option) => option.value === item)?.label ||
|
||||
item;
|
||||
return html`
|
||||
<ha-input-chip
|
||||
.idx=${idx}
|
||||
@remove=${this._removeItem}
|
||||
.label=${label}
|
||||
selected
|
||||
>
|
||||
<ha-svg-icon slot="icon" .path=${mdiDrag}></ha-svg-icon>
|
||||
${label}
|
||||
</ha-input-chip>
|
||||
`;
|
||||
}
|
||||
)}
|
||||
</ha-chip-set>
|
||||
</ha-sortable>
|
||||
`
|
||||
: nothing}
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<div class="container ${this.disabled ? "disabled" : ""}">
|
||||
<ha-sortable
|
||||
no-style
|
||||
@item-moved=${this._moveItem}
|
||||
.disabled=${this.disabled}
|
||||
handle-selector="button.primary.action"
|
||||
filter=".add"
|
||||
>
|
||||
<ha-chip-set>
|
||||
${repeat(
|
||||
this._value,
|
||||
(item) => item,
|
||||
(item: string, idx) => {
|
||||
const label = options.find((o) => o.value === item)?.primary;
|
||||
const isValid = !!label;
|
||||
return html`
|
||||
<ha-input-chip
|
||||
data-idx=${idx}
|
||||
@remove=${this._removeItem}
|
||||
@click=${this._editItem}
|
||||
.label=${label || item}
|
||||
.selected=${!this.disabled}
|
||||
.disabled=${this.disabled}
|
||||
class=${!isValid ? "invalid" : ""}
|
||||
>
|
||||
<ha-svg-icon
|
||||
slot="icon"
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
></ha-svg-icon>
|
||||
</ha-input-chip>
|
||||
`;
|
||||
}
|
||||
)}
|
||||
${this.disabled
|
||||
? nothing
|
||||
: html`
|
||||
<ha-assist-chip
|
||||
@click=${this._addItem}
|
||||
.disabled=${this.disabled}
|
||||
label=${this.hass.localize(
|
||||
"ui.components.entity.entity-state-content-picker.add"
|
||||
)}
|
||||
class="add"
|
||||
>
|
||||
<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon>
|
||||
</ha-assist-chip>
|
||||
`}
|
||||
</ha-chip-set>
|
||||
</ha-sortable>
|
||||
|
||||
<ha-combo-box
|
||||
item-value-path="value"
|
||||
item-label-path="label"
|
||||
.hass=${this.hass}
|
||||
.label=${this.label}
|
||||
.helper=${this.helper}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required && !value.length}
|
||||
.value=${""}
|
||||
.items=${optionItems}
|
||||
allow-custom-value
|
||||
@filter-changed=${this._filterChanged}
|
||||
@value-changed=${this._comboBoxValueChanged}
|
||||
@opened-changed=${this._openedChanged}
|
||||
></ha-combo-box>
|
||||
<mwc-menu-surface
|
||||
.open=${this._opened}
|
||||
@closed=${this._onClosed}
|
||||
@opened=${this._onOpened}
|
||||
@input=${stopPropagation}
|
||||
.anchor=${this._container}
|
||||
>
|
||||
<ha-combo-box
|
||||
.hass=${this.hass}
|
||||
.value=${""}
|
||||
.autofocus=${this.autofocus}
|
||||
.disabled=${this.disabled || !this.entityId}
|
||||
.required=${this.required && !value.length}
|
||||
.helper=${this.helper}
|
||||
.items=${options}
|
||||
allow-custom-value
|
||||
item-id-path="value"
|
||||
item-value-path="value"
|
||||
item-label-path="primary"
|
||||
.renderer=${rowRenderer}
|
||||
@opened-changed=${this._openedChanged}
|
||||
@value-changed=${this._comboBoxValueChanged}
|
||||
@filter-changed=${this._filterChanged}
|
||||
>
|
||||
</ha-combo-box>
|
||||
</mwc-menu-surface>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _onClosed(ev) {
|
||||
ev.stopPropagation();
|
||||
this._opened = false;
|
||||
this._editIndex = undefined;
|
||||
}
|
||||
|
||||
private async _onOpened(ev) {
|
||||
if (!this._opened) {
|
||||
return;
|
||||
}
|
||||
ev.stopPropagation();
|
||||
this._opened = true;
|
||||
await this._comboBox?.focus();
|
||||
await this._comboBox?.open();
|
||||
}
|
||||
|
||||
private async _addItem(ev) {
|
||||
ev.stopPropagation();
|
||||
this._opened = true;
|
||||
}
|
||||
|
||||
private async _editItem(ev) {
|
||||
ev.stopPropagation();
|
||||
const idx = parseInt(ev.currentTarget.dataset.idx, 10);
|
||||
this._editIndex = idx;
|
||||
this._opened = true;
|
||||
}
|
||||
|
||||
private get _value() {
|
||||
return !this.value ? [] : ensureArray(this.value);
|
||||
}
|
||||
|
||||
private _toValue = memoizeOne((value: string[]): typeof this.value => {
|
||||
if (value.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (value.length === 1) {
|
||||
return value[0];
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
||||
private _openedChanged(ev: ValueChangedEvent<boolean>) {
|
||||
this._opened = ev.detail.value;
|
||||
this._comboBox.filteredItems = this._comboBox.items;
|
||||
const open = ev.detail.value;
|
||||
if (open) {
|
||||
const options = this._comboBox.items || [];
|
||||
|
||||
const initialValue =
|
||||
this._editIndex != null ? this._value[this._editIndex] : "";
|
||||
const filteredItems = this._filterSelectedOptions(options, initialValue);
|
||||
|
||||
this._comboBox.filteredItems = filteredItems;
|
||||
this._comboBox.setInputValue(initialValue);
|
||||
} else {
|
||||
this._opened = false;
|
||||
}
|
||||
}
|
||||
|
||||
private _filterChanged(ev?: CustomEvent): void {
|
||||
this._filter = ev?.detail.value || "";
|
||||
private _filterSelectedOptions = (
|
||||
options: StateContentOption[],
|
||||
current?: string
|
||||
) => {
|
||||
const value = this._value;
|
||||
|
||||
const filteredItems = this._comboBox.items?.filter((item) => {
|
||||
const label = item.label || item.value;
|
||||
return label.toLowerCase().includes(this._filter?.toLowerCase());
|
||||
});
|
||||
return options.filter(
|
||||
(option) => !value.includes(option.value) || option.value === current
|
||||
);
|
||||
};
|
||||
|
||||
if (this._filter) {
|
||||
filteredItems?.unshift({ label: this._filter, value: this._filter });
|
||||
private _filterChanged(ev: ValueChangedEvent<string>) {
|
||||
const input = ev.detail.value;
|
||||
const filter = input?.toLowerCase() || "";
|
||||
const options = this._comboBox.items || [];
|
||||
|
||||
const currentValue =
|
||||
this._editIndex != null ? this._value[this._editIndex] : "";
|
||||
|
||||
this._comboBox.filteredItems = this._filterSelectedOptions(
|
||||
options,
|
||||
currentValue
|
||||
);
|
||||
|
||||
if (!filter) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fuseOptions: IFuseOptions<StateContentOption> = {
|
||||
keys: ["primary", "secondary", "value"],
|
||||
isCaseSensitive: false,
|
||||
minMatchCharLength: Math.min(filter.length, 2),
|
||||
threshold: 0.2,
|
||||
ignoreDiacritics: true,
|
||||
};
|
||||
|
||||
const fuse = new Fuse(this._comboBox.filteredItems, fuseOptions);
|
||||
const filteredItems = fuse.search(filter).map((result) => result.item);
|
||||
|
||||
this._comboBox.filteredItems = filteredItems;
|
||||
}
|
||||
|
||||
@@ -257,43 +371,40 @@ class HaEntityStatePicker extends LitElement {
|
||||
newValue.splice(newIndex, 0, element);
|
||||
this._setValue(newValue);
|
||||
await this.updateComplete;
|
||||
this._filterChanged();
|
||||
this._filterChanged({ detail: { value: "" } } as ValueChangedEvent<string>);
|
||||
}
|
||||
|
||||
private async _removeItem(ev) {
|
||||
ev.stopPropagation();
|
||||
const value: string[] = [...this._value];
|
||||
value.splice(ev.target.idx, 1);
|
||||
const value = [...this._value];
|
||||
const idx = parseInt(ev.target.dataset.idx, 10);
|
||||
value.splice(idx, 1);
|
||||
this._setValue(value);
|
||||
await this.updateComplete;
|
||||
this._filterChanged();
|
||||
this._filterChanged({ detail: { value: "" } } as ValueChangedEvent<string>);
|
||||
}
|
||||
|
||||
private _comboBoxValueChanged(ev: CustomEvent): void {
|
||||
private _comboBoxValueChanged(ev: ValueChangedEvent<string>): void {
|
||||
ev.stopPropagation();
|
||||
const newValue = ev.detail.value;
|
||||
const value = ev.detail.value;
|
||||
|
||||
if (this.disabled || newValue === "") {
|
||||
if (this.disabled || value === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentValue = this._value;
|
||||
const newValue = [...this._value];
|
||||
|
||||
if (currentValue.includes(newValue)) {
|
||||
return;
|
||||
if (this._editIndex != null) {
|
||||
newValue[this._editIndex] = value;
|
||||
} else {
|
||||
newValue.push(value);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
this._filterChanged();
|
||||
this._comboBox.setInputValue("");
|
||||
}, 0);
|
||||
|
||||
this._setValue([...currentValue, newValue]);
|
||||
this._setValue(newValue);
|
||||
}
|
||||
|
||||
private _setValue(value: string[]) {
|
||||
const newValue =
|
||||
value.length === 0 ? undefined : value.length === 1 ? value[0] : value;
|
||||
const newValue = this._toValue(value);
|
||||
this.value = newValue;
|
||||
fireEvent(this, "value-changed", {
|
||||
value: newValue,
|
||||
@@ -303,10 +414,64 @@ class HaEntityStatePicker extends LitElement {
|
||||
static styles = css`
|
||||
:host {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.container {
|
||||
position: relative;
|
||||
background-color: var(--mdc-text-field-fill-color, whitesmoke);
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
border-end-end-radius: var(--ha-border-radius-square);
|
||||
border-end-start-radius: var(--ha-border-radius-square);
|
||||
}
|
||||
.container:after {
|
||||
display: block;
|
||||
content: "";
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 1px;
|
||||
width: 100%;
|
||||
background-color: var(
|
||||
--mdc-text-field-idle-line-color,
|
||||
rgba(0, 0, 0, 0.42)
|
||||
);
|
||||
transform:
|
||||
height 180ms ease-in-out,
|
||||
background-color 180ms ease-in-out;
|
||||
}
|
||||
.container.disabled:after {
|
||||
background-color: var(
|
||||
--mdc-text-field-disabled-line-color,
|
||||
rgba(0, 0, 0, 0.42)
|
||||
);
|
||||
}
|
||||
.container:focus-within:after {
|
||||
height: 2px;
|
||||
background-color: var(--mdc-theme-primary);
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin: 0 0 var(--ha-space-2);
|
||||
}
|
||||
|
||||
.add {
|
||||
order: 1;
|
||||
}
|
||||
|
||||
mwc-menu-surface {
|
||||
--mdc-menu-min-width: 100%;
|
||||
}
|
||||
|
||||
ha-chip-set {
|
||||
padding: 8px 0;
|
||||
padding: var(--ha-space-2) var(--ha-space-2);
|
||||
}
|
||||
|
||||
.invalid {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.sortable-fallback {
|
||||
@@ -326,6 +491,6 @@ class HaEntityStatePicker extends LitElement {
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-entity-state-content-picker": HaEntityStatePicker;
|
||||
"ha-entity-state-content-picker": HaStateContentPicker;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, html, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
@@ -9,8 +8,6 @@ import type { HomeAssistant, ValueChangedEvent } from "../../types";
|
||||
import "../ha-combo-box";
|
||||
import type { HaComboBox } from "../ha-combo-box";
|
||||
|
||||
export type HaEntityPickerEntityFilterFunc = (entityId: HassEntity) => boolean;
|
||||
|
||||
interface StateOption {
|
||||
value: string;
|
||||
label: string;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { customElement, property } from "lit/decorators";
|
||||
import { keyed } from "lit/directives/keyed";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { ANY_STATE_VALUE } from "./const";
|
||||
import { ensureArray } from "../../common/array/ensure-array";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import "./ha-entity-state-picker";
|
||||
@@ -57,6 +58,7 @@ export class HaEntityStatesPicker extends LitElement {
|
||||
|
||||
const value = this.value || [];
|
||||
const hide = [...(this.hideStates || []), ...value];
|
||||
const hideValue = value.includes(ANY_STATE_VALUE);
|
||||
|
||||
return html`
|
||||
${repeat(
|
||||
@@ -84,7 +86,7 @@ export class HaEntityStatesPicker extends LitElement {
|
||||
`
|
||||
)}
|
||||
<div>
|
||||
${this.disabled && value.length
|
||||
${(this.disabled && value.length) || hideValue
|
||||
? nothing
|
||||
: keyed(
|
||||
value.length,
|
||||
|
||||
@@ -46,7 +46,7 @@ export class HaAnalytics extends LitElement {
|
||||
</span>
|
||||
<ha-switch
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${baseEnabled}
|
||||
.checked=${!!baseEnabled}
|
||||
.preference=${"base"}
|
||||
.disabled=${loading}
|
||||
name="base"
|
||||
@@ -70,7 +70,7 @@ export class HaAnalytics extends LitElement {
|
||||
<ha-switch
|
||||
.id="switch-${preference}"
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${this.analytics?.preferences[preference]}
|
||||
.checked=${!!this.analytics?.preferences[preference]}
|
||||
.preference=${preference}
|
||||
name=${preference}
|
||||
>
|
||||
@@ -102,7 +102,7 @@ export class HaAnalytics extends LitElement {
|
||||
</span>
|
||||
<ha-switch
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${this.analytics?.preferences.diagnostics}
|
||||
.checked=${!!this.analytics?.preferences.diagnostics}
|
||||
.preference=${"diagnostics"}
|
||||
.disabled=${loading}
|
||||
name="diagnostics"
|
||||
|
||||
@@ -8,21 +8,13 @@ import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { computeAreaName } from "../common/entity/compute_area_name";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import { computeFloorName } from "../common/entity/compute_floor_name";
|
||||
import { stringCompare } from "../common/string/compare";
|
||||
import { computeRTL } from "../common/util/compute_rtl";
|
||||
import type { AreaRegistryEntry } from "../data/area_registry";
|
||||
import type {
|
||||
DeviceEntityDisplayLookup,
|
||||
DeviceRegistryEntry,
|
||||
} from "../data/device_registry";
|
||||
import { getDeviceEntityDisplayLookup } from "../data/device_registry";
|
||||
import type { EntityRegistryDisplayEntry } from "../data/entity_registry";
|
||||
import {
|
||||
getFloorAreaLookup,
|
||||
type FloorRegistryEntry,
|
||||
} from "../data/floor_registry";
|
||||
getAreasAndFloors,
|
||||
type AreaFloorValue,
|
||||
type FloorComboBoxItem,
|
||||
} from "../data/area_floor";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../types";
|
||||
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
|
||||
import "./ha-combo-box-item";
|
||||
@@ -30,24 +22,12 @@ import "./ha-floor-icon";
|
||||
import "./ha-generic-picker";
|
||||
import type { HaGenericPicker } from "./ha-generic-picker";
|
||||
import "./ha-icon-button";
|
||||
import type { PickerComboBoxItem } from "./ha-picker-combo-box";
|
||||
import type { PickerValueRenderer } from "./ha-picker-field";
|
||||
import "./ha-svg-icon";
|
||||
import "./ha-tree-indicator";
|
||||
|
||||
const SEPARATOR = "________";
|
||||
|
||||
interface FloorComboBoxItem extends PickerComboBoxItem {
|
||||
type: "floor" | "area";
|
||||
floor?: FloorRegistryEntry;
|
||||
area?: AreaRegistryEntry;
|
||||
}
|
||||
|
||||
interface AreaFloorValue {
|
||||
id: string;
|
||||
type: "floor" | "area";
|
||||
}
|
||||
|
||||
@customElement("ha-area-floor-picker")
|
||||
export class HaAreaFloorPicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@@ -154,243 +134,6 @@ export class HaAreaFloorPicker extends LitElement {
|
||||
`;
|
||||
};
|
||||
|
||||
private _getAreasAndFloors = memoizeOne(
|
||||
(
|
||||
haFloors: HomeAssistant["floors"],
|
||||
haAreas: HomeAssistant["areas"],
|
||||
haDevices: HomeAssistant["devices"],
|
||||
haEntities: HomeAssistant["entities"],
|
||||
includeDomains: this["includeDomains"],
|
||||
excludeDomains: this["excludeDomains"],
|
||||
includeDeviceClasses: this["includeDeviceClasses"],
|
||||
deviceFilter: this["deviceFilter"],
|
||||
entityFilter: this["entityFilter"],
|
||||
excludeAreas: this["excludeAreas"],
|
||||
excludeFloors: this["excludeFloors"]
|
||||
): FloorComboBoxItem[] => {
|
||||
const floors = Object.values(haFloors);
|
||||
const areas = Object.values(haAreas);
|
||||
const devices = Object.values(haDevices);
|
||||
const entities = Object.values(haEntities);
|
||||
|
||||
let deviceEntityLookup: DeviceEntityDisplayLookup = {};
|
||||
let inputDevices: DeviceRegistryEntry[] | undefined;
|
||||
let inputEntities: EntityRegistryDisplayEntry[] | undefined;
|
||||
|
||||
if (
|
||||
includeDomains ||
|
||||
excludeDomains ||
|
||||
includeDeviceClasses ||
|
||||
deviceFilter ||
|
||||
entityFilter
|
||||
) {
|
||||
deviceEntityLookup = getDeviceEntityDisplayLookup(entities);
|
||||
inputDevices = devices;
|
||||
inputEntities = entities.filter((entity) => entity.area_id);
|
||||
|
||||
if (includeDomains) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) =>
|
||||
includeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
});
|
||||
inputEntities = inputEntities!.filter((entity) =>
|
||||
includeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
}
|
||||
|
||||
if (excludeDomains) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return true;
|
||||
}
|
||||
return entities.every(
|
||||
(entity) =>
|
||||
!excludeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
});
|
||||
inputEntities = inputEntities!.filter(
|
||||
(entity) =>
|
||||
!excludeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
}
|
||||
|
||||
if (includeDeviceClasses) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
stateObj.attributes.device_class &&
|
||||
includeDeviceClasses.includes(stateObj.attributes.device_class)
|
||||
);
|
||||
});
|
||||
});
|
||||
inputEntities = inputEntities!.filter((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
return (
|
||||
stateObj.attributes.device_class &&
|
||||
includeDeviceClasses.includes(stateObj.attributes.device_class)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (deviceFilter) {
|
||||
inputDevices = inputDevices!.filter((device) =>
|
||||
deviceFilter!(device)
|
||||
);
|
||||
}
|
||||
|
||||
if (entityFilter) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return entityFilter(stateObj);
|
||||
});
|
||||
});
|
||||
inputEntities = inputEntities!.filter((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return entityFilter!(stateObj);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let outputAreas = areas;
|
||||
|
||||
let areaIds: string[] | undefined;
|
||||
|
||||
if (inputDevices) {
|
||||
areaIds = inputDevices
|
||||
.filter((device) => device.area_id)
|
||||
.map((device) => device.area_id!);
|
||||
}
|
||||
|
||||
if (inputEntities) {
|
||||
areaIds = (areaIds ?? []).concat(
|
||||
inputEntities
|
||||
.filter((entity) => entity.area_id)
|
||||
.map((entity) => entity.area_id!)
|
||||
);
|
||||
}
|
||||
|
||||
if (areaIds) {
|
||||
outputAreas = outputAreas.filter((area) =>
|
||||
areaIds!.includes(area.area_id)
|
||||
);
|
||||
}
|
||||
|
||||
if (excludeAreas) {
|
||||
outputAreas = outputAreas.filter(
|
||||
(area) => !excludeAreas!.includes(area.area_id)
|
||||
);
|
||||
}
|
||||
|
||||
if (excludeFloors) {
|
||||
outputAreas = outputAreas.filter(
|
||||
(area) => !area.floor_id || !excludeFloors!.includes(area.floor_id)
|
||||
);
|
||||
}
|
||||
|
||||
const floorAreaLookup = getFloorAreaLookup(outputAreas);
|
||||
const unassisgnedAreas = Object.values(outputAreas).filter(
|
||||
(area) => !area.floor_id || !floorAreaLookup[area.floor_id]
|
||||
);
|
||||
|
||||
// @ts-ignore
|
||||
const floorAreaEntries: [
|
||||
FloorRegistryEntry | undefined,
|
||||
AreaRegistryEntry[],
|
||||
][] = Object.entries(floorAreaLookup)
|
||||
.map(([floorId, floorAreas]) => {
|
||||
const floor = floors.find((fl) => fl.floor_id === floorId)!;
|
||||
return [floor, floorAreas] as const;
|
||||
})
|
||||
.sort(([floorA], [floorB]) => {
|
||||
if (floorA.level !== floorB.level) {
|
||||
return (floorA.level ?? 0) - (floorB.level ?? 0);
|
||||
}
|
||||
return stringCompare(floorA.name, floorB.name);
|
||||
});
|
||||
|
||||
const items: FloorComboBoxItem[] = [];
|
||||
|
||||
floorAreaEntries.forEach(([floor, floorAreas]) => {
|
||||
if (floor) {
|
||||
const floorName = computeFloorName(floor);
|
||||
|
||||
const areaSearchLabels = floorAreas
|
||||
.map((area) => {
|
||||
const areaName = computeAreaName(area) || area.area_id;
|
||||
return [area.area_id, areaName, ...area.aliases];
|
||||
})
|
||||
.flat();
|
||||
|
||||
items.push({
|
||||
id: this._formatValue({ id: floor.floor_id, type: "floor" }),
|
||||
type: "floor",
|
||||
primary: floorName,
|
||||
floor: floor,
|
||||
search_labels: [
|
||||
floor.floor_id,
|
||||
floorName,
|
||||
...floor.aliases,
|
||||
...areaSearchLabels,
|
||||
],
|
||||
});
|
||||
}
|
||||
items.push(
|
||||
...floorAreas.map((area) => {
|
||||
const areaName = computeAreaName(area) || area.area_id;
|
||||
return {
|
||||
id: this._formatValue({ id: area.area_id, type: "area" }),
|
||||
type: "area" as const,
|
||||
primary: areaName,
|
||||
area: area,
|
||||
icon: area.icon || undefined,
|
||||
search_labels: [area.area_id, areaName, ...area.aliases],
|
||||
};
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
items.push(
|
||||
...unassisgnedAreas.map((area) => {
|
||||
const areaName = computeAreaName(area) || area.area_id;
|
||||
return {
|
||||
id: this._formatValue({ id: area.area_id, type: "area" }),
|
||||
type: "area" as const,
|
||||
primary: areaName,
|
||||
icon: area.icon || undefined,
|
||||
search_labels: [area.area_id, areaName, ...area.aliases],
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return items;
|
||||
}
|
||||
);
|
||||
|
||||
private _rowRenderer: ComboBoxLitRenderer<FloorComboBoxItem> = (
|
||||
item,
|
||||
{ index },
|
||||
@@ -445,12 +188,16 @@ export class HaAreaFloorPicker extends LitElement {
|
||||
`;
|
||||
};
|
||||
|
||||
private _getAreasAndFloorsMemoized = memoizeOne(getAreasAndFloors);
|
||||
|
||||
private _getItems = () =>
|
||||
this._getAreasAndFloors(
|
||||
this._getAreasAndFloorsMemoized(
|
||||
this.hass.states,
|
||||
this.hass.floors,
|
||||
this.hass.areas,
|
||||
this.hass.devices,
|
||||
this.hass.entities,
|
||||
this._formatValue,
|
||||
this.includeDomains,
|
||||
this.excludeDomains,
|
||||
this.includeDeviceClasses,
|
||||
|
||||
@@ -87,6 +87,8 @@ export class HaAreaPicker extends LitElement {
|
||||
|
||||
@property({ type: Boolean }) public required = false;
|
||||
|
||||
@property({ attribute: "add-button-label" }) public addButtonLabel?: string;
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
public async open() {
|
||||
@@ -107,7 +109,7 @@ export class HaAreaPicker extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
const { floor } = getAreaContext(area, this.hass);
|
||||
const { floor } = getAreaContext(area, this.hass.floors);
|
||||
|
||||
const areaName = area ? computeAreaName(area) : undefined;
|
||||
const floorName = floor ? computeFloorName(floor) : undefined;
|
||||
@@ -279,7 +281,7 @@ export class HaAreaPicker extends LitElement {
|
||||
}
|
||||
|
||||
const items = outputAreas.map<PickerComboBoxItem>((area) => {
|
||||
const { floor } = getAreaContext(area, this.hass);
|
||||
const { floor } = getAreaContext(area, this.hass.floors);
|
||||
const floorName = floor ? computeFloorName(floor) : undefined;
|
||||
const areaName = computeAreaName(area);
|
||||
return {
|
||||
@@ -375,6 +377,7 @@ export class HaAreaPicker extends LitElement {
|
||||
.getItems=${this._getItems}
|
||||
.getAdditionalItems=${this._getAdditionalItems}
|
||||
.valueRenderer=${valueRenderer}
|
||||
.addButtonLabel=${this.addButtonLabel}
|
||||
@value-changed=${this._valueChanged}
|
||||
>
|
||||
</ha-generic-picker>
|
||||
|
||||
@@ -44,7 +44,7 @@ export class HaAreasDisplayEditor extends LitElement {
|
||||
);
|
||||
|
||||
const items: DisplayItem[] = areas.map((area) => {
|
||||
const { floor } = getAreaContext(area, this.hass!);
|
||||
const { floor } = getAreaContext(area, this.hass.floors);
|
||||
return {
|
||||
value: area.area_id,
|
||||
label: area.name,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mdiDrag, mdiTextureBox } from "@mdi/js";
|
||||
import { mdiDragHorizontalVariant, mdiTextureBox } from "@mdi/js";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
@@ -105,7 +105,7 @@ export class HaAreasFloorsDisplayEditor extends LitElement {
|
||||
<ha-svg-icon
|
||||
class="handle"
|
||||
slot="icons"
|
||||
.path=${mdiDrag}
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
></ha-svg-icon>
|
||||
`}
|
||||
<ha-items-display-editor
|
||||
@@ -138,7 +138,7 @@ export class HaAreasFloorsDisplayEditor extends LitElement {
|
||||
);
|
||||
const groupedItems: Record<string, DisplayItem[]> = areas.reduce(
|
||||
(acc, area) => {
|
||||
const { floor } = getAreaContext(area, this.hass!);
|
||||
const { floor } = getAreaContext(area, this.hass.floors);
|
||||
const floorId = floor?.floor_id ?? UNASSIGNED_FLOOR;
|
||||
|
||||
if (!acc[floorId]) {
|
||||
|
||||
@@ -118,7 +118,7 @@ export class HaAutomationRow extends LitElement {
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
padding: 0 8px;
|
||||
padding: var(--ha-space-0) var(--ha-space-2);
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
@@ -134,12 +134,12 @@ export class HaAutomationRow extends LitElement {
|
||||
.expand-button {
|
||||
transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
|
||||
color: var(--ha-color-on-neutral-quiet);
|
||||
margin-left: -8px;
|
||||
margin-left: calc(var(--ha-space-2) * -1);
|
||||
}
|
||||
:host([building-block]) .leading-icon-wrapper {
|
||||
background-color: var(--ha-color-fill-neutral-loud-resting);
|
||||
border-radius: var(--ha-border-radius-md);
|
||||
padding: 4px;
|
||||
padding: var(--ha-space-1);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
@@ -149,7 +149,7 @@ export class HaAutomationRow extends LitElement {
|
||||
color: var(--ha-color-on-neutral-quiet);
|
||||
}
|
||||
:host([building-block]) ::slotted([slot="leading-icon"]) {
|
||||
--mdc-icon-size: 20px;
|
||||
--mdc-icon-size: var(--ha-space-5);
|
||||
color: var(--white-color);
|
||||
transform: rotate(-45deg);
|
||||
}
|
||||
@@ -170,7 +170,7 @@ export class HaAutomationRow extends LitElement {
|
||||
::slotted([slot="header"]) {
|
||||
flex: 1;
|
||||
overflow-wrap: anywhere;
|
||||
margin: 0 12px;
|
||||
margin: var(--ha-space-0) var(--ha-space-3);
|
||||
}
|
||||
:host([sort-selected]) .row {
|
||||
outline: solid;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { css, html, LitElement, type PropertyValues } from "lit";
|
||||
import "@home-assistant/webawesome/dist/components/drawer/drawer";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { css, html, LitElement, type PropertyValues } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { SwipeGestureRecognizer } from "../common/util/swipe-gesture-recognizer";
|
||||
import { haStyleScrollbar } from "../resources/styles";
|
||||
|
||||
export const BOTTOM_SHEET_ANIMATION_DURATION_MS = 300;
|
||||
|
||||
@@ -8,8 +10,17 @@ export const BOTTOM_SHEET_ANIMATION_DURATION_MS = 300;
|
||||
export class HaBottomSheet extends LitElement {
|
||||
@property({ type: Boolean }) public open = false;
|
||||
|
||||
@property({ type: Boolean, reflect: true, attribute: "flexcontent" })
|
||||
public flexContent = false;
|
||||
|
||||
@state() private _drawerOpen = false;
|
||||
|
||||
@query("#drawer") private _drawer!: HTMLElement;
|
||||
|
||||
private _gestureRecognizer = new SwipeGestureRecognizer();
|
||||
|
||||
private _isDragging = false;
|
||||
|
||||
private _handleAfterHide() {
|
||||
this.open = false;
|
||||
const ev = new Event("closed", {
|
||||
@@ -29,42 +40,186 @@ export class HaBottomSheet extends LitElement {
|
||||
render() {
|
||||
return html`
|
||||
<wa-drawer
|
||||
id="drawer"
|
||||
placement="bottom"
|
||||
.open=${this._drawerOpen}
|
||||
@wa-after-hide=${this._handleAfterHide}
|
||||
without-header
|
||||
@touchstart=${this._handleTouchStart}
|
||||
>
|
||||
<slot></slot>
|
||||
<slot name="header"></slot>
|
||||
<div id="body" class="body ha-scrollbar">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</wa-drawer>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
wa-drawer {
|
||||
--wa-color-surface-raised: var(
|
||||
--ha-bottom-sheet-surface-background,
|
||||
var(--ha-dialog-surface-background, var(--mdc-theme-surface, #fff)),
|
||||
);
|
||||
--spacing: 0;
|
||||
--size: auto;
|
||||
--show-duration: ${BOTTOM_SHEET_ANIMATION_DURATION_MS}ms;
|
||||
--hide-duration: ${BOTTOM_SHEET_ANIMATION_DURATION_MS}ms;
|
||||
private _handleTouchStart = (ev: TouchEvent) => {
|
||||
// Check if any element inside drawer in the composed path has scrollTop > 0
|
||||
for (const path of ev.composedPath()) {
|
||||
const el = path as HTMLElement;
|
||||
if (el === this._drawer) {
|
||||
break;
|
||||
}
|
||||
if (el.scrollTop > 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
wa-drawer::part(dialog) {
|
||||
border-top-left-radius: var(
|
||||
--ha-bottom-sheet-border-radius,
|
||||
var(--ha-dialog-border-radius, var(--ha-border-radius-2xl))
|
||||
);
|
||||
border-top-right-radius: var(
|
||||
--ha-bottom-sheet-border-radius,
|
||||
var(--ha-dialog-border-radius, var(--ha-border-radius-2xl))
|
||||
);
|
||||
max-height: 90vh;
|
||||
padding-bottom: var(--safe-area-inset-bottom);
|
||||
padding-left: var(--safe-area-inset-left);
|
||||
padding-right: var(--safe-area-inset-right);
|
||||
|
||||
this._startResizing(ev.touches[0].clientY);
|
||||
};
|
||||
|
||||
private _startResizing(clientY: number) {
|
||||
// register event listeners for drag handling
|
||||
document.addEventListener("touchmove", this._handleTouchMove, {
|
||||
passive: false,
|
||||
});
|
||||
document.addEventListener("touchend", this._handleTouchEnd);
|
||||
document.addEventListener("touchcancel", this._handleTouchEnd);
|
||||
|
||||
this._gestureRecognizer.start(clientY);
|
||||
}
|
||||
|
||||
private _handleTouchMove = (ev: TouchEvent) => {
|
||||
const currentY = ev.touches[0].clientY;
|
||||
const delta = this._gestureRecognizer.move(currentY);
|
||||
|
||||
if (delta < 0) {
|
||||
ev.preventDefault();
|
||||
this._isDragging = true;
|
||||
requestAnimationFrame(() => {
|
||||
if (this._isDragging) {
|
||||
this.style.setProperty(
|
||||
"--dialog-transform",
|
||||
`translateY(${delta * -1}px)`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
`;
|
||||
};
|
||||
|
||||
private _animateSnapBack() {
|
||||
// Add transition for smooth animation
|
||||
this.style.setProperty(
|
||||
"--dialog-transition",
|
||||
`transform ${BOTTOM_SHEET_ANIMATION_DURATION_MS}ms ease-out`
|
||||
);
|
||||
|
||||
// Reset transform to snap back
|
||||
this.style.removeProperty("--dialog-transform");
|
||||
|
||||
// Remove transition after animation completes
|
||||
setTimeout(() => {
|
||||
this.style.removeProperty("--dialog-transition");
|
||||
}, BOTTOM_SHEET_ANIMATION_DURATION_MS);
|
||||
}
|
||||
|
||||
private _handleTouchEnd = () => {
|
||||
this._unregisterResizeHandlers();
|
||||
|
||||
this._isDragging = false;
|
||||
|
||||
const result = this._gestureRecognizer.end();
|
||||
|
||||
// If velocity exceeds threshold, use velocity direction to determine action
|
||||
if (result.isSwipe) {
|
||||
if (result.isDownwardSwipe) {
|
||||
// Downward swipe - close the bottom sheet
|
||||
this._drawerOpen = false;
|
||||
} else {
|
||||
// Upward swipe - keep open and animate back
|
||||
this._animateSnapBack();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// If velocity is below threshold, use position-based logic
|
||||
// Get the drawer height to calculate 50% threshold
|
||||
const drawerBody = this._drawer.shadowRoot?.querySelector(
|
||||
'[part="body"]'
|
||||
) as HTMLElement;
|
||||
const drawerHeight = drawerBody?.offsetHeight || 0;
|
||||
|
||||
// delta is negative when dragging down
|
||||
// Close if dragged down past 50% of the drawer height
|
||||
if (
|
||||
drawerHeight > 0 &&
|
||||
result.delta < 0 &&
|
||||
Math.abs(result.delta) > drawerHeight * 0.5
|
||||
) {
|
||||
this._drawerOpen = false;
|
||||
} else {
|
||||
this._animateSnapBack();
|
||||
}
|
||||
};
|
||||
|
||||
private _unregisterResizeHandlers = () => {
|
||||
document.removeEventListener("touchmove", this._handleTouchMove);
|
||||
document.removeEventListener("touchend", this._handleTouchEnd);
|
||||
document.removeEventListener("touchcancel", this._handleTouchEnd);
|
||||
};
|
||||
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unregisterResizeHandlers();
|
||||
this._isDragging = false;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
haStyleScrollbar,
|
||||
css`
|
||||
wa-drawer {
|
||||
--wa-color-surface-raised: transparent;
|
||||
--spacing: 0;
|
||||
--size: var(--ha-bottom-sheet-height, auto);
|
||||
--show-duration: ${BOTTOM_SHEET_ANIMATION_DURATION_MS}ms;
|
||||
--hide-duration: ${BOTTOM_SHEET_ANIMATION_DURATION_MS}ms;
|
||||
}
|
||||
wa-drawer::part(dialog) {
|
||||
max-height: var(--ha-bottom-sheet-max-height, 90vh);
|
||||
align-items: center;
|
||||
transform: var(--dialog-transform);
|
||||
transition: var(--dialog-transition);
|
||||
}
|
||||
wa-drawer::part(body) {
|
||||
max-width: var(--ha-bottom-sheet-max-width);
|
||||
width: 100%;
|
||||
border-top-left-radius: var(
|
||||
--ha-bottom-sheet-border-radius,
|
||||
var(--ha-dialog-border-radius, var(--ha-border-radius-2xl))
|
||||
);
|
||||
border-top-right-radius: var(
|
||||
--ha-bottom-sheet-border-radius,
|
||||
var(--ha-dialog-border-radius, var(--ha-border-radius-2xl))
|
||||
);
|
||||
background-color: var(
|
||||
--ha-bottom-sheet-surface-background,
|
||||
var(--ha-dialog-surface-background, var(--mdc-theme-surface, #fff)),
|
||||
);
|
||||
padding: var(
|
||||
--ha-bottom-sheet-padding,
|
||||
0 var(--safe-area-inset-right) var(--safe-area-inset-bottom)
|
||||
var(--safe-area-inset-left)
|
||||
);
|
||||
}
|
||||
:host([flexcontent]) wa-drawer::part(body) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
:host([flexcontent]) .body {
|
||||
flex: 1;
|
||||
max-width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(
|
||||
--ha-bottom-sheet-padding,
|
||||
0 var(--safe-area-inset-right) var(--safe-area-inset-bottom)
|
||||
var(--safe-area-inset-left)
|
||||
);
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -31,6 +31,9 @@ export class HaButtonToggleGroup extends LitElement {
|
||||
@property({ type: Boolean, reflect: true, attribute: "no-wrap" })
|
||||
public nowrap = false;
|
||||
|
||||
@property({ type: Boolean, reflect: true, attribute: "full-width" })
|
||||
public fullWidth = false;
|
||||
|
||||
@property() public variant:
|
||||
| "brand"
|
||||
| "neutral"
|
||||
@@ -38,6 +41,13 @@ export class HaButtonToggleGroup extends LitElement {
|
||||
| "warning"
|
||||
| "danger" = "brand";
|
||||
|
||||
@property({ attribute: "active-variant" }) public activeVariant?:
|
||||
| "brand"
|
||||
| "neutral"
|
||||
| "success"
|
||||
| "warning"
|
||||
| "danger";
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<wa-button-group childSelector="ha-button">
|
||||
@@ -46,7 +56,9 @@ export class HaButtonToggleGroup extends LitElement {
|
||||
html`<ha-button
|
||||
iconTag="ha-svg-icon"
|
||||
class="icon"
|
||||
.variant=${this.variant}
|
||||
.variant=${this.active !== button.value || !this.activeVariant
|
||||
? this.variant
|
||||
: this.activeVariant}
|
||||
.size=${this.size}
|
||||
.value=${button.value}
|
||||
@click=${this._handleClick}
|
||||
@@ -78,6 +90,19 @@ export class HaButtonToggleGroup extends LitElement {
|
||||
:host([no-wrap]) wa-button-group::part(base) {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
wa-button-group {
|
||||
padding: var(--ha-button-toggle-group-padding);
|
||||
}
|
||||
|
||||
:host([full-width]) wa-button-group,
|
||||
:host([full-width]) wa-button-group::part(base) {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:host([full-width]) ha-button {
|
||||
flex: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ export class HaButton extends Button {
|
||||
line-height: 1;
|
||||
|
||||
transition: background-color 0.15s ease-in-out;
|
||||
text-wrap: wrap;
|
||||
}
|
||||
|
||||
:host([size="small"]) .button {
|
||||
|
||||
@@ -86,7 +86,8 @@ export class HaCameraStream extends LitElement {
|
||||
const streams = this._streams(
|
||||
this._capabilities?.frontend_stream_types,
|
||||
this._hlsStreams,
|
||||
this._webRtcStreams
|
||||
this._webRtcStreams,
|
||||
this.muted
|
||||
);
|
||||
return html`${repeat(
|
||||
streams,
|
||||
@@ -190,7 +191,8 @@ export class HaCameraStream extends LitElement {
|
||||
(
|
||||
supportedTypes?: StreamType[],
|
||||
hlsStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean }
|
||||
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
muted?: boolean
|
||||
): Stream[] => {
|
||||
if (__DEMO__) {
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
@@ -220,9 +222,10 @@ export class HaCameraStream extends LitElement {
|
||||
if (
|
||||
hlsStreams.hasVideo &&
|
||||
hlsStreams.hasAudio &&
|
||||
!webRtcStreams.hasAudio
|
||||
!webRtcStreams.hasAudio &&
|
||||
!muted
|
||||
) {
|
||||
// webRTC stream is missing audio, use HLS
|
||||
// webRTC stream is missing audio and audio is not muted, use HLS
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
if (webRtcStreams.hasVideo) {
|
||||
|
||||
@@ -44,26 +44,26 @@ export class HaCard extends LitElement {
|
||||
font-size: var(--ha-card-header-font-size, var(--ha-font-size-2xl));
|
||||
letter-spacing: -0.012em;
|
||||
line-height: var(--ha-line-height-expanded);
|
||||
padding: 12px 16px 16px;
|
||||
padding: var(--ha-space-3) var(--ha-space-4) var(--ha-space-4);
|
||||
display: block;
|
||||
margin-block-start: 0px;
|
||||
margin-block-end: 0px;
|
||||
margin-block-start: var(--ha-space-0);
|
||||
margin-block-end: var(--ha-space-0);
|
||||
font-weight: var(--ha-font-weight-normal);
|
||||
}
|
||||
|
||||
:host ::slotted(.card-content:not(:first-child)),
|
||||
slot:not(:first-child)::slotted(.card-content) {
|
||||
padding-top: 0px;
|
||||
margin-top: -8px;
|
||||
padding-top: var(--ha-space-0);
|
||||
margin-top: calc(var(--ha-space-2) * -1);
|
||||
}
|
||||
|
||||
:host ::slotted(.card-content) {
|
||||
padding: 16px;
|
||||
padding: var(--ha-space-4);
|
||||
}
|
||||
|
||||
:host ::slotted(.card-actions) {
|
||||
border-top: 1px solid var(--divider-color, #e8e8e8);
|
||||
padding: 8px;
|
||||
padding: var(--ha-space-2);
|
||||
}
|
||||
`;
|
||||
|
||||
|
||||
@@ -239,6 +239,7 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
this._loadedCodeMirror.crosshairCursor(),
|
||||
this._loadedCodeMirror.highlightSelectionMatches(),
|
||||
this._loadedCodeMirror.highlightActiveLine(),
|
||||
this._loadedCodeMirror.dropCursor(),
|
||||
this._loadedCodeMirror.indentationMarkers({
|
||||
thickness: 0,
|
||||
activeThickness: 1,
|
||||
|
||||
@@ -6,6 +6,9 @@ export class HaDialogHeader extends LitElement {
|
||||
@property({ type: String, attribute: "subtitle-position" })
|
||||
public subtitlePosition: "above" | "below" = "below";
|
||||
|
||||
@property({ type: Boolean, reflect: true, attribute: "show-border" })
|
||||
public showBorder = false;
|
||||
|
||||
protected render() {
|
||||
const titleSlot = html`<div class="header-title">
|
||||
<slot name="title"></slot>
|
||||
@@ -49,12 +52,16 @@ export class HaDialogHeader extends LitElement {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
padding: 4px;
|
||||
padding: 0 var(--ha-space-1);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.header-content {
|
||||
flex: 1;
|
||||
padding: 10px 4px;
|
||||
padding: 10px var(--ha-space-1);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
min-height: var(--ha-space-12);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -63,7 +70,7 @@ export class HaDialogHeader extends LitElement {
|
||||
.header-title {
|
||||
height: var(
|
||||
--ha-dialog-header-title-height,
|
||||
calc(var(--ha-font-size-xl) + 4px)
|
||||
calc(var(--ha-font-size-xl) + var(--ha-space-1))
|
||||
);
|
||||
font-size: var(--ha-font-size-xl);
|
||||
line-height: var(--ha-line-height-condensed);
|
||||
@@ -76,19 +83,19 @@ export class HaDialogHeader extends LitElement {
|
||||
}
|
||||
@media all and (min-width: 450px) and (min-height: 500px) {
|
||||
.header-bar {
|
||||
padding: 16px;
|
||||
padding: 0 var(--ha-space-2);
|
||||
}
|
||||
}
|
||||
.header-navigation-icon {
|
||||
flex: none;
|
||||
min-width: 8px;
|
||||
min-width: var(--ha-space-2);
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
||||
.header-action-items {
|
||||
flex: none;
|
||||
min-width: 8px;
|
||||
min-width: var(--ha-space-2);
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
@@ -49,6 +49,7 @@ export class HaExpansionPanel extends LitElement {
|
||||
tabindex=${this.noCollapse ? -1 : 0}
|
||||
aria-expanded=${this.expanded}
|
||||
aria-controls="sect1"
|
||||
part="summary"
|
||||
>
|
||||
${this.leftChevron ? chevronIcon : nothing}
|
||||
<slot name="leading-icon"></slot>
|
||||
@@ -170,6 +171,11 @@ export class HaExpansionPanel extends LitElement {
|
||||
margin-left: 8px;
|
||||
margin-inline-start: 8px;
|
||||
margin-inline-end: initial;
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
}
|
||||
|
||||
#summary:focus-visible ha-svg-icon.summary-icon {
|
||||
background-color: var(--ha-color-fill-neutral-normal-active);
|
||||
}
|
||||
|
||||
:host([left-chevron]) .summary-icon,
|
||||
|
||||
@@ -248,7 +248,7 @@ export class HaFilterDevices extends LitElement {
|
||||
}
|
||||
search-input-outlined {
|
||||
display: block;
|
||||
padding: 0 8px;
|
||||
padding: var(--ha-space-1) var(--ha-space-2) 0;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -199,7 +199,7 @@ export class HaFilterDomains extends LitElement {
|
||||
}
|
||||
search-input-outlined {
|
||||
display: block;
|
||||
padding: 0 8px;
|
||||
padding: var(--ha-space-1) var(--ha-space-2) 0;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -264,7 +264,7 @@ export class HaFilterEntities extends LitElement {
|
||||
}
|
||||
search-input-outlined {
|
||||
display: block;
|
||||
padding: 0 8px;
|
||||
padding: var(--ha-space-1) var(--ha-space-2) 0;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -217,7 +217,7 @@ export class HaFilterIntegrations extends LitElement {
|
||||
}
|
||||
search-input-outlined {
|
||||
display: block;
|
||||
padding: 0 8px;
|
||||
padding: var(--ha-space-1) var(--ha-space-2) 0;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -256,7 +256,7 @@ export class HaFilterLabels extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
search-input-outlined {
|
||||
display: block;
|
||||
padding: 0 8px;
|
||||
padding: var(--ha-space-1) var(--ha-space-2) 0;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -148,7 +148,7 @@ export class HaForm extends LitElement implements HaFormElement {
|
||||
.value=${getValue(this.data, item)}
|
||||
.label=${this._computeLabel(item, this.data)}
|
||||
.disabled=${item.disabled || this.disabled || false}
|
||||
.placeholder=${item.required ? "" : item.default}
|
||||
.placeholder=${item.required ? undefined : item.default}
|
||||
.helper=${this._computeHelper(item)}
|
||||
.localizeValue=${this.localizeValue}
|
||||
.required=${item.required || false}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit";
|
||||
import type { ComboBoxLightOpenedChangedEvent } from "@vaadin/combo-box/vaadin-combo-box-light";
|
||||
import "@home-assistant/webawesome/dist/components/popover/popover";
|
||||
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
|
||||
import { mdiPlaylistPlus } from "@mdi/js";
|
||||
import { css, html, LitElement, nothing, type CSSResultGroup } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { tinykeys } from "tinykeys";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import "./ha-bottom-sheet";
|
||||
import "./ha-button";
|
||||
import "./ha-combo-box-item";
|
||||
import "./ha-icon-button";
|
||||
import "./ha-input-helper-text";
|
||||
import "./ha-picker-combo-box";
|
||||
import type {
|
||||
@@ -15,12 +18,12 @@ import type {
|
||||
PickerComboBoxSearchFn,
|
||||
} from "./ha-picker-combo-box";
|
||||
import "./ha-picker-field";
|
||||
import type { HaPickerField, PickerValueRenderer } from "./ha-picker-field";
|
||||
import type { PickerValueRenderer } from "./ha-picker-field";
|
||||
import "./ha-svg-icon";
|
||||
|
||||
@customElement("ha-generic-picker")
|
||||
export class HaGenericPicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
// eslint-disable-next-line lit/no-native-attributes
|
||||
@property({ type: Boolean }) public autofocus = false;
|
||||
@@ -53,7 +56,7 @@ export class HaGenericPicker extends LitElement {
|
||||
public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[];
|
||||
|
||||
@property({ attribute: false })
|
||||
public rowRenderer?: ComboBoxLitRenderer<PickerComboBoxItem>;
|
||||
public rowRenderer?: RenderItemFunction<PickerComboBoxItem>;
|
||||
|
||||
@property({ attribute: false })
|
||||
public valueRenderer?: PickerValueRenderer;
|
||||
@@ -64,58 +67,142 @@ export class HaGenericPicker extends LitElement {
|
||||
@property({ attribute: "not-found-label", type: String })
|
||||
public notFoundLabel?: string;
|
||||
|
||||
@query("ha-picker-field") private _field?: HaPickerField;
|
||||
@property({ attribute: "popover-placement" })
|
||||
public popoverPlacement:
|
||||
| "bottom"
|
||||
| "top"
|
||||
| "left"
|
||||
| "right"
|
||||
| "top-start"
|
||||
| "top-end"
|
||||
| "right-start"
|
||||
| "right-end"
|
||||
| "bottom-start"
|
||||
| "bottom-end"
|
||||
| "left-start"
|
||||
| "left-end" = "bottom-start";
|
||||
|
||||
/** If set picker shows an add button instead of textbox when value isn't set */
|
||||
@property({ attribute: "add-button-label" }) public addButtonLabel?: string;
|
||||
|
||||
@query(".container") private _containerElement?: HTMLDivElement;
|
||||
|
||||
@query("ha-picker-combo-box") private _comboBox?: HaPickerComboBox;
|
||||
|
||||
@state() private _opened = false;
|
||||
|
||||
@state() private _pickerWrapperOpen = false;
|
||||
|
||||
@state() private _popoverWidth = 0;
|
||||
|
||||
@state() private _openedNarrow = false;
|
||||
|
||||
private _narrow = false;
|
||||
|
||||
// helper to set new value after closing picker, to avoid flicker
|
||||
private _newValue?: string;
|
||||
|
||||
private _unsubscribeTinyKeys?: () => void;
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
${this.label
|
||||
? html`<label ?disabled=${this.disabled}>${this.label}</label>`
|
||||
: nothing}
|
||||
<div class="container">
|
||||
${!this._opened
|
||||
<div id="picker">
|
||||
<slot name="field">
|
||||
${this.addButtonLabel && !this.value
|
||||
? html`<ha-button
|
||||
size="small"
|
||||
appearance="filled"
|
||||
@click=${this.open}
|
||||
.disabled=${this.disabled}
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${mdiPlaylistPlus}
|
||||
slot="start"
|
||||
></ha-svg-icon>
|
||||
${this.addButtonLabel}
|
||||
</ha-button>`
|
||||
: html`<ha-picker-field
|
||||
type="button"
|
||||
class=${this._opened ? "opened" : ""}
|
||||
compact
|
||||
aria-label=${ifDefined(this.label)}
|
||||
@click=${this.open}
|
||||
@clear=${this._clear}
|
||||
.placeholder=${this.placeholder}
|
||||
.value=${this.value}
|
||||
.required=${this.required}
|
||||
.disabled=${this.disabled}
|
||||
.hideClearIcon=${this.hideClearIcon}
|
||||
.valueRenderer=${this.valueRenderer}
|
||||
>
|
||||
</ha-picker-field>`}
|
||||
</slot>
|
||||
</div>
|
||||
${!this._openedNarrow && (this._pickerWrapperOpen || this._opened)
|
||||
? html`
|
||||
<ha-picker-field
|
||||
type="button"
|
||||
compact
|
||||
aria-label=${ifDefined(this.label)}
|
||||
@click=${this.open}
|
||||
@clear=${this._clear}
|
||||
.placeholder=${this.placeholder}
|
||||
.value=${this.value}
|
||||
.required=${this.required}
|
||||
.disabled=${this.disabled}
|
||||
.hideClearIcon=${this.hideClearIcon}
|
||||
.valueRenderer=${this.valueRenderer}
|
||||
<wa-popover
|
||||
.open=${this._pickerWrapperOpen}
|
||||
style="--body-width: ${this._popoverWidth}px;"
|
||||
without-arrow
|
||||
distance="-4"
|
||||
.placement=${this.popoverPlacement}
|
||||
for="picker"
|
||||
auto-size="vertical"
|
||||
auto-size-padding="16"
|
||||
@wa-after-show=${this._dialogOpened}
|
||||
@wa-after-hide=${this._hidePicker}
|
||||
trap-focus
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label=${this.label || "Select option"}
|
||||
>
|
||||
</ha-picker-field>
|
||||
${this._renderComboBox()}
|
||||
</wa-popover>
|
||||
`
|
||||
: html`
|
||||
<ha-picker-combo-box
|
||||
.hass=${this.hass}
|
||||
.autofocus=${this.autofocus}
|
||||
.allowCustomValue=${this.allowCustomValue}
|
||||
.label=${this.searchLabel ??
|
||||
this.hass.localize("ui.common.search")}
|
||||
.value=${this.value}
|
||||
hide-clear-icon
|
||||
@opened-changed=${this._openedChanged}
|
||||
@value-changed=${this._valueChanged}
|
||||
.rowRenderer=${this.rowRenderer}
|
||||
.notFoundLabel=${this.notFoundLabel}
|
||||
.getItems=${this.getItems}
|
||||
.getAdditionalItems=${this.getAdditionalItems}
|
||||
.searchFn=${this.searchFn}
|
||||
></ha-picker-combo-box>
|
||||
`}
|
||||
: this._pickerWrapperOpen || this._opened
|
||||
? html`<ha-bottom-sheet
|
||||
flexcontent
|
||||
.open=${this._pickerWrapperOpen}
|
||||
@wa-after-show=${this._dialogOpened}
|
||||
@closed=${this._hidePicker}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label=${this.label || "Select option"}
|
||||
>
|
||||
${this._renderComboBox(true)}
|
||||
</ha-bottom-sheet>`
|
||||
: nothing}
|
||||
</div>
|
||||
${this._renderHelper()}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderComboBox(dialogMode = false) {
|
||||
if (!this._opened) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
<ha-picker-combo-box
|
||||
.hass=${this.hass}
|
||||
.allowCustomValue=${this.allowCustomValue}
|
||||
.label=${this.searchLabel ??
|
||||
(this.hass?.localize("ui.common.search") || "Search")}
|
||||
.value=${this.value}
|
||||
@value-changed=${this._valueChanged}
|
||||
.rowRenderer=${this.rowRenderer}
|
||||
.notFoundLabel=${this.notFoundLabel}
|
||||
.getItems=${this.getItems}
|
||||
.getAdditionalItems=${this.getAdditionalItems}
|
||||
.searchFn=${this.searchFn}
|
||||
.mode=${dialogMode ? "dialog" : "popover"}
|
||||
></ha-picker-combo-box>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderHelper() {
|
||||
return this.helper
|
||||
? html`<ha-input-helper-text .disabled=${this.disabled}
|
||||
@@ -124,13 +211,33 @@ export class HaGenericPicker extends LitElement {
|
||||
: nothing;
|
||||
}
|
||||
|
||||
private _dialogOpened = () => {
|
||||
this._opened = true;
|
||||
requestAnimationFrame(() => {
|
||||
this._comboBox?.focus();
|
||||
});
|
||||
};
|
||||
|
||||
private _hidePicker(ev) {
|
||||
ev.stopPropagation();
|
||||
if (this._newValue) {
|
||||
fireEvent(this, "value-changed", { value: this._newValue });
|
||||
this._newValue = undefined;
|
||||
}
|
||||
|
||||
this._opened = false;
|
||||
this._pickerWrapperOpen = false;
|
||||
this._unsubscribeTinyKeys?.();
|
||||
}
|
||||
|
||||
private _valueChanged(ev: CustomEvent) {
|
||||
ev.stopPropagation();
|
||||
const value = ev.detail.value;
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
fireEvent(this, "value-changed", { value });
|
||||
this._pickerWrapperOpen = false;
|
||||
this._newValue = value;
|
||||
}
|
||||
|
||||
private _clear(e) {
|
||||
@@ -143,25 +250,45 @@ export class HaGenericPicker extends LitElement {
|
||||
fireEvent(this, "value-changed", { value });
|
||||
}
|
||||
|
||||
public async open() {
|
||||
public async open(ev?: Event) {
|
||||
ev?.stopPropagation();
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
this._opened = true;
|
||||
await this.updateComplete;
|
||||
this._comboBox?.focus();
|
||||
this._comboBox?.open();
|
||||
this._openedNarrow = this._narrow;
|
||||
this._popoverWidth = this._containerElement?.offsetWidth || 250;
|
||||
this._pickerWrapperOpen = true;
|
||||
this._unsubscribeTinyKeys = tinykeys(this, {
|
||||
Escape: this._handleEscClose,
|
||||
});
|
||||
}
|
||||
|
||||
private async _openedChanged(ev: ComboBoxLightOpenedChangedEvent) {
|
||||
const opened = ev.detail.value;
|
||||
if (this._opened && !opened) {
|
||||
this._opened = false;
|
||||
await this.updateComplete;
|
||||
this._field?.focus();
|
||||
}
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._handleResize();
|
||||
window.addEventListener("resize", this._handleResize);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
window.removeEventListener("resize", this._handleResize);
|
||||
this._unsubscribeTinyKeys?.();
|
||||
}
|
||||
|
||||
private _handleResize = () => {
|
||||
this._narrow =
|
||||
window.matchMedia("(max-width: 870px)").matches ||
|
||||
window.matchMedia("(max-height: 500px)").matches;
|
||||
|
||||
if (!this._openedNarrow && this._pickerWrapperOpen) {
|
||||
this._popoverWidth = this._containerElement?.offsetWidth || 250;
|
||||
}
|
||||
};
|
||||
|
||||
private _handleEscClose = (ev: KeyboardEvent) => {
|
||||
ev.stopPropagation();
|
||||
};
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
css`
|
||||
@@ -178,7 +305,45 @@ export class HaGenericPicker extends LitElement {
|
||||
}
|
||||
ha-input-helper-text {
|
||||
display: block;
|
||||
margin: 8px 0 0;
|
||||
margin: var(--ha-space-2) 0 0;
|
||||
}
|
||||
|
||||
wa-popover {
|
||||
--wa-space-l: var(--ha-space-0);
|
||||
}
|
||||
|
||||
wa-popover::part(body) {
|
||||
width: max(var(--body-width), 250px);
|
||||
max-width: max(var(--body-width), 250px);
|
||||
max-height: 500px;
|
||||
height: 70vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@media (max-height: 1000px) {
|
||||
wa-popover::part(body) {
|
||||
max-height: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 1000px) {
|
||||
wa-popover::part(body) {
|
||||
max-height: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
ha-bottom-sheet {
|
||||
--ha-bottom-sheet-height: 90vh;
|
||||
--ha-bottom-sheet-height: calc(100dvh - var(--ha-space-12));
|
||||
--ha-bottom-sheet-max-height: var(--ha-bottom-sheet-height);
|
||||
--ha-bottom-sheet-max-width: 600px;
|
||||
--ha-bottom-sheet-padding: var(--ha-space-0);
|
||||
--ha-bottom-sheet-surface-background: var(--card-background-color);
|
||||
--ha-bottom-sheet-border-radius: var(--ha-border-radius-2xl);
|
||||
}
|
||||
|
||||
ha-picker-field.opened {
|
||||
--mdc-text-field-idle-line-color: var(--primary-color);
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ResizeController } from "@lit-labs/observers/resize-controller";
|
||||
import { mdiDrag, mdiEye, mdiEyeOff } from "@mdi/js";
|
||||
import { mdiDragHorizontalVariant, mdiEye, mdiEyeOff } from "@mdi/js";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
@@ -178,7 +178,7 @@ export class HaItemDisplayEditor extends LitElement {
|
||||
? this._dragHandleKeydown
|
||||
: undefined}
|
||||
class="handle"
|
||||
.path=${mdiDrag}
|
||||
.path=${mdiDragHorizontalVariant}
|
||||
slot="end"
|
||||
></ha-svg-icon>
|
||||
`
|
||||
|
||||
@@ -2,19 +2,19 @@ import { mdiLabel, mdiPlus } from "@mdi/js";
|
||||
import type { HassEntity, UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, html } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import {
|
||||
customElement,
|
||||
property,
|
||||
query,
|
||||
queryAssignedElements,
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import type {
|
||||
DeviceEntityDisplayLookup,
|
||||
DeviceRegistryEntry,
|
||||
} from "../data/device_registry";
|
||||
import { getDeviceEntityDisplayLookup } from "../data/device_registry";
|
||||
import type { EntityRegistryDisplayEntry } from "../data/entity_registry";
|
||||
import type { LabelRegistryEntry } from "../data/label_registry";
|
||||
import {
|
||||
createLabelRegistryEntry,
|
||||
getLabels,
|
||||
subscribeLabelRegistry,
|
||||
} from "../data/label_registry";
|
||||
import { showAlertDialog } from "../dialogs/generic/show-dialog-box";
|
||||
@@ -90,6 +90,9 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
|
||||
|
||||
@state() private _labels?: LabelRegistryEntry[];
|
||||
|
||||
@queryAssignedElements({ flatten: true })
|
||||
private _slotNodes?: NodeListOf<HTMLElement>;
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
public async open() {
|
||||
@@ -137,201 +140,22 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
);
|
||||
|
||||
private _getLabels = memoizeOne(
|
||||
(
|
||||
labels: LabelRegistryEntry[] | undefined,
|
||||
haAreas: HomeAssistant["areas"],
|
||||
haDevices: HomeAssistant["devices"],
|
||||
haEntities: HomeAssistant["entities"],
|
||||
includeDomains: this["includeDomains"],
|
||||
excludeDomains: this["excludeDomains"],
|
||||
includeDeviceClasses: this["includeDeviceClasses"],
|
||||
deviceFilter: this["deviceFilter"],
|
||||
entityFilter: this["entityFilter"],
|
||||
excludeLabels: this["excludeLabels"]
|
||||
): PickerComboBoxItem[] => {
|
||||
if (!labels || labels.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: NO_LABELS,
|
||||
primary: this.hass.localize("ui.components.label-picker.no_labels"),
|
||||
icon_path: mdiLabel,
|
||||
},
|
||||
];
|
||||
}
|
||||
private _getLabelsMemoized = memoizeOne(getLabels);
|
||||
|
||||
const devices = Object.values(haDevices);
|
||||
const entities = Object.values(haEntities);
|
||||
|
||||
let deviceEntityLookup: DeviceEntityDisplayLookup = {};
|
||||
let inputDevices: DeviceRegistryEntry[] | undefined;
|
||||
let inputEntities: EntityRegistryDisplayEntry[] | undefined;
|
||||
|
||||
if (
|
||||
includeDomains ||
|
||||
excludeDomains ||
|
||||
includeDeviceClasses ||
|
||||
deviceFilter ||
|
||||
entityFilter
|
||||
) {
|
||||
deviceEntityLookup = getDeviceEntityDisplayLookup(entities);
|
||||
inputDevices = devices;
|
||||
inputEntities = entities.filter((entity) => entity.labels.length > 0);
|
||||
|
||||
if (includeDomains) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) =>
|
||||
includeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
});
|
||||
inputEntities = inputEntities!.filter((entity) =>
|
||||
includeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
}
|
||||
|
||||
if (excludeDomains) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return true;
|
||||
}
|
||||
return entities.every(
|
||||
(entity) =>
|
||||
!excludeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
});
|
||||
inputEntities = inputEntities!.filter(
|
||||
(entity) =>
|
||||
!excludeDomains.includes(computeDomain(entity.entity_id))
|
||||
);
|
||||
}
|
||||
|
||||
if (includeDeviceClasses) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
stateObj.attributes.device_class &&
|
||||
includeDeviceClasses.includes(stateObj.attributes.device_class)
|
||||
);
|
||||
});
|
||||
});
|
||||
inputEntities = inputEntities!.filter((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
return (
|
||||
stateObj.attributes.device_class &&
|
||||
includeDeviceClasses.includes(stateObj.attributes.device_class)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (deviceFilter) {
|
||||
inputDevices = inputDevices!.filter((device) =>
|
||||
deviceFilter!(device)
|
||||
);
|
||||
}
|
||||
|
||||
if (entityFilter) {
|
||||
inputDevices = inputDevices!.filter((device) => {
|
||||
const devEntities = deviceEntityLookup[device.id];
|
||||
if (!devEntities || !devEntities.length) {
|
||||
return false;
|
||||
}
|
||||
return deviceEntityLookup[device.id].some((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return entityFilter(stateObj);
|
||||
});
|
||||
});
|
||||
inputEntities = inputEntities!.filter((entity) => {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
if (!stateObj) {
|
||||
return false;
|
||||
}
|
||||
return entityFilter!(stateObj);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let outputLabels = labels;
|
||||
const usedLabels = new Set<string>();
|
||||
|
||||
let areaIds: string[] | undefined;
|
||||
|
||||
if (inputDevices) {
|
||||
areaIds = inputDevices
|
||||
.filter((device) => device.area_id)
|
||||
.map((device) => device.area_id!);
|
||||
|
||||
inputDevices.forEach((device) => {
|
||||
device.labels.forEach((label) => usedLabels.add(label));
|
||||
});
|
||||
}
|
||||
|
||||
if (inputEntities) {
|
||||
areaIds = (areaIds ?? []).concat(
|
||||
inputEntities
|
||||
.filter((entity) => entity.area_id)
|
||||
.map((entity) => entity.area_id!)
|
||||
);
|
||||
inputEntities.forEach((entity) => {
|
||||
entity.labels.forEach((label) => usedLabels.add(label));
|
||||
});
|
||||
}
|
||||
|
||||
if (areaIds) {
|
||||
areaIds.forEach((areaId) => {
|
||||
const area = haAreas[areaId];
|
||||
area.labels.forEach((label) => usedLabels.add(label));
|
||||
});
|
||||
}
|
||||
|
||||
if (excludeLabels) {
|
||||
outputLabels = outputLabels.filter(
|
||||
(label) => !excludeLabels!.includes(label.label_id)
|
||||
);
|
||||
}
|
||||
|
||||
if (inputDevices || inputEntities) {
|
||||
outputLabels = outputLabels.filter((label) =>
|
||||
usedLabels.has(label.label_id)
|
||||
);
|
||||
}
|
||||
|
||||
const items = outputLabels.map<PickerComboBoxItem>((label) => ({
|
||||
id: label.label_id,
|
||||
primary: label.name,
|
||||
icon: label.icon || undefined,
|
||||
icon_path: label.icon ? undefined : mdiLabel,
|
||||
sorting_label: label.name,
|
||||
search_labels: [label.name, label.label_id, label.description].filter(
|
||||
(v): v is string => Boolean(v)
|
||||
),
|
||||
}));
|
||||
|
||||
return items;
|
||||
private _getItems = () => {
|
||||
if (!this._labels || this._labels.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: NO_LABELS,
|
||||
primary: this.hass.localize("ui.components.label-picker.no_labels"),
|
||||
icon_path: mdiLabel,
|
||||
},
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
private _getItems = () =>
|
||||
this._getLabels(
|
||||
return this._getLabelsMemoized(
|
||||
this.hass,
|
||||
this._labels,
|
||||
this.hass.areas,
|
||||
this.hass.devices,
|
||||
this.hass.entities,
|
||||
this.includeDomains,
|
||||
this.excludeDomains,
|
||||
this.includeDeviceClasses,
|
||||
@@ -339,6 +163,7 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
|
||||
this.entityFilter,
|
||||
this.excludeLabels
|
||||
);
|
||||
};
|
||||
|
||||
private _allLabelNames = memoizeOne((labels?: LabelRegistryEntry[]) => {
|
||||
if (!labels) {
|
||||
@@ -395,12 +220,14 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
|
||||
|
||||
return html`
|
||||
<ha-generic-picker
|
||||
.disabled=${this.disabled}
|
||||
.hass=${this.hass}
|
||||
.autofocus=${this.autofocus}
|
||||
.label=${this.label}
|
||||
.notFoundLabel=${this.hass.localize(
|
||||
"ui.components.label-picker.no_match"
|
||||
)}
|
||||
.addButtonLabel=${this.hass.localize("ui.components.label-picker.add")}
|
||||
.placeholder=${placeholder}
|
||||
.value=${this.value}
|
||||
.getItems=${this._getItems}
|
||||
@@ -408,6 +235,7 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
|
||||
.valueRenderer=${valueRenderer}
|
||||
@value-changed=${this._valueChanged}
|
||||
>
|
||||
<slot .slot=${this._slotNodes?.length ? "field" : undefined}></slot>
|
||||
</ha-generic-picker>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mdiPlaylistPlus } from "@mdi/js";
|
||||
import type { HassEntity, UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
@@ -123,36 +124,6 @@ export class HaLabelsPicker extends SubscribeMixin(LitElement) {
|
||||
);
|
||||
return html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
${labels?.length
|
||||
? html`<ha-chip-set>
|
||||
${repeat(
|
||||
labels,
|
||||
(label) => label?.label_id,
|
||||
(label) => {
|
||||
const color = label?.color
|
||||
? computeCssColor(label.color)
|
||||
: undefined;
|
||||
return html`
|
||||
<ha-input-chip
|
||||
.item=${label}
|
||||
@remove=${this._removeItem}
|
||||
@click=${this._openDetail}
|
||||
.label=${label?.name}
|
||||
selected
|
||||
style=${color ? `--color: ${color}` : ""}
|
||||
>
|
||||
${label?.icon
|
||||
? html`<ha-icon
|
||||
slot="icon"
|
||||
.icon=${label.icon}
|
||||
></ha-icon>`
|
||||
: nothing}
|
||||
</ha-input-chip>
|
||||
`;
|
||||
}
|
||||
)}
|
||||
</ha-chip-set>`
|
||||
: nothing}
|
||||
<ha-label-picker
|
||||
.hass=${this.hass}
|
||||
.helper=${this.helper}
|
||||
@@ -162,6 +133,47 @@ export class HaLabelsPicker extends SubscribeMixin(LitElement) {
|
||||
.excludeLabels=${this.value}
|
||||
@value-changed=${this._labelChanged}
|
||||
>
|
||||
<ha-chip-set>
|
||||
${labels?.length
|
||||
? repeat(
|
||||
labels,
|
||||
(label) => label?.label_id,
|
||||
(label) => {
|
||||
const color = label?.color
|
||||
? computeCssColor(label.color)
|
||||
: undefined;
|
||||
return html`
|
||||
<ha-input-chip
|
||||
.item=${label}
|
||||
@remove=${this._removeItem}
|
||||
@click=${this._openDetail}
|
||||
.disabled=${this.disabled}
|
||||
.label=${label?.name}
|
||||
selected
|
||||
style=${color ? `--color: ${color}` : ""}
|
||||
>
|
||||
${label?.icon
|
||||
? html`<ha-icon
|
||||
slot="icon"
|
||||
.icon=${label.icon}
|
||||
></ha-icon>`
|
||||
: nothing}
|
||||
</ha-input-chip>
|
||||
`;
|
||||
}
|
||||
)
|
||||
: nothing}
|
||||
<ha-button
|
||||
id="picker"
|
||||
size="small"
|
||||
appearance="filled"
|
||||
@click=${this._openPicker}
|
||||
.disabled=${this.disabled}
|
||||
>
|
||||
<ha-svg-icon .path=${mdiPlaylistPlus} slot="start"></ha-svg-icon>
|
||||
${this.hass.localize("ui.components.label-picker.add")}
|
||||
</ha-button>
|
||||
</ha-chip-set>
|
||||
</ha-label-picker>
|
||||
`;
|
||||
}
|
||||
@@ -203,9 +215,25 @@ export class HaLabelsPicker extends SubscribeMixin(LitElement) {
|
||||
}, 0);
|
||||
}
|
||||
|
||||
private _openPicker(ev: Event) {
|
||||
ev.stopPropagation();
|
||||
this.labelPicker.open();
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-chip-set {
|
||||
margin-bottom: 8px;
|
||||
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);
|
||||
}
|
||||
.placeholder {
|
||||
color: var(--mdc-text-field-label-ink-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: var(--ha-space-8);
|
||||
}
|
||||
ha-input-chip {
|
||||
--md-input-chip-selected-container-color: var(--color, var(--grey-color));
|
||||
|
||||
@@ -1,56 +1,59 @@
|
||||
import { mdiMenuDown } from "@mdi/js";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { stopPropagation } from "../common/dom/stop_propagation";
|
||||
import { formatLanguageCode } from "../common/language/format_language";
|
||||
import { caseInsensitiveStringCompare } from "../common/string/compare";
|
||||
import type { FrontendLocaleData } from "../data/translation";
|
||||
import { translationMetadata } from "../resources/translations-metadata";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import "./ha-list-item";
|
||||
import "./ha-select";
|
||||
import type { HaSelect } from "./ha-select";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../types";
|
||||
import "./ha-button";
|
||||
import "./ha-generic-picker";
|
||||
import type { HaGenericPicker } from "./ha-generic-picker";
|
||||
import type { PickerComboBoxItem } from "./ha-picker-combo-box";
|
||||
|
||||
export const getLanguageOptions = (
|
||||
languages: string[],
|
||||
nativeName: boolean,
|
||||
noSort: boolean,
|
||||
locale?: FrontendLocaleData
|
||||
) => {
|
||||
let options: { label: string; value: string }[] = [];
|
||||
): PickerComboBoxItem[] => {
|
||||
let options: PickerComboBoxItem[] = [];
|
||||
|
||||
if (nativeName) {
|
||||
const translations = translationMetadata.translations;
|
||||
options = languages.map((lang) => {
|
||||
let label = translations[lang]?.nativeName;
|
||||
if (!label) {
|
||||
let primary = translations[lang]?.nativeName;
|
||||
if (!primary) {
|
||||
try {
|
||||
// this will not work if Intl.DisplayNames is polyfilled, it will return in the language of the user
|
||||
label = new Intl.DisplayNames(lang, {
|
||||
primary = new Intl.DisplayNames(lang, {
|
||||
type: "language",
|
||||
fallback: "code",
|
||||
}).of(lang)!;
|
||||
} catch (_err) {
|
||||
label = lang;
|
||||
primary = lang;
|
||||
}
|
||||
}
|
||||
return {
|
||||
value: lang,
|
||||
label,
|
||||
id: lang,
|
||||
primary,
|
||||
search_labels: [primary],
|
||||
};
|
||||
});
|
||||
} else if (locale) {
|
||||
options = languages.map((lang) => ({
|
||||
value: lang,
|
||||
label: formatLanguageCode(lang, locale),
|
||||
id: lang,
|
||||
primary: formatLanguageCode(lang, locale),
|
||||
search_labels: [formatLanguageCode(lang, locale)],
|
||||
}));
|
||||
}
|
||||
|
||||
if (!noSort && locale) {
|
||||
options.sort((a, b) =>
|
||||
caseInsensitiveStringCompare(a.label, b.label, locale.language)
|
||||
caseInsensitiveStringCompare(a.primary, b.primary, locale.language)
|
||||
);
|
||||
}
|
||||
return options;
|
||||
@@ -73,6 +76,9 @@ export class HaLanguagePicker extends LitElement {
|
||||
@property({ attribute: "native-name", type: Boolean })
|
||||
public nativeName = false;
|
||||
|
||||
@property({ type: Boolean, attribute: "button-style" })
|
||||
public buttonStyle = false;
|
||||
|
||||
@property({ attribute: "no-sort", type: Boolean }) public noSort = false;
|
||||
|
||||
@property({ attribute: "inline-arrow", type: Boolean })
|
||||
@@ -80,115 +86,90 @@ export class HaLanguagePicker extends LitElement {
|
||||
|
||||
@state() _defaultLanguages: string[] = [];
|
||||
|
||||
@query("ha-select") private _select!: HaSelect;
|
||||
@query("ha-generic-picker", true) public genericPicker!: HaGenericPicker;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues) {
|
||||
super.firstUpdated(changedProps);
|
||||
this._computeDefaultLanguageOptions();
|
||||
}
|
||||
|
||||
protected updated(changedProperties: PropertyValues) {
|
||||
super.updated(changedProperties);
|
||||
|
||||
const localeChanged =
|
||||
changedProperties.has("hass") &&
|
||||
this.hass &&
|
||||
changedProperties.get("hass") &&
|
||||
changedProperties.get("hass").locale.language !==
|
||||
this.hass.locale.language;
|
||||
if (
|
||||
changedProperties.has("languages") ||
|
||||
changedProperties.has("value") ||
|
||||
localeChanged
|
||||
) {
|
||||
this._select.layoutOptions();
|
||||
if (!this.disabled && this._select.value !== this.value) {
|
||||
fireEvent(this, "value-changed", { value: this._select.value });
|
||||
}
|
||||
if (!this.value) {
|
||||
return;
|
||||
}
|
||||
const languageOptions = this._getLanguagesOptions(
|
||||
this.languages ?? this._defaultLanguages,
|
||||
this.nativeName,
|
||||
this.noSort,
|
||||
this.hass?.locale
|
||||
);
|
||||
const selectedItemIndex = languageOptions.findIndex(
|
||||
(option) => option.value === this.value
|
||||
);
|
||||
if (selectedItemIndex === -1) {
|
||||
this.value = undefined;
|
||||
}
|
||||
if (localeChanged) {
|
||||
this._select.select(selectedItemIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _getLanguagesOptions = memoizeOne(getLanguageOptions);
|
||||
|
||||
private _computeDefaultLanguageOptions() {
|
||||
this._defaultLanguages = Object.keys(translationMetadata.translations);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const languageOptions = this._getLanguagesOptions(
|
||||
private _getItems = () =>
|
||||
this._getLanguagesOptions(
|
||||
this.languages ?? this._defaultLanguages,
|
||||
this.nativeName,
|
||||
this.noSort,
|
||||
this.hass?.locale
|
||||
);
|
||||
|
||||
private _getLanguageName = (lang?: string) =>
|
||||
this._getItems().find((language) => language.id === lang)?.primary;
|
||||
|
||||
private _valueRenderer = (value) =>
|
||||
html`<span slot="headline"
|
||||
>${this._getLanguageName(value) ?? value}</span
|
||||
> `;
|
||||
|
||||
protected render() {
|
||||
const value =
|
||||
this.value ??
|
||||
(this.required && !this.disabled
|
||||
? languageOptions[0]?.value
|
||||
: this.value);
|
||||
(this.required && !this.disabled ? this._getItems()[0].id : this.value);
|
||||
|
||||
return html`
|
||||
<ha-select
|
||||
.label=${this.label ??
|
||||
<ha-generic-picker
|
||||
.hass=${this.hass}
|
||||
.autofocus=${this.autofocus}
|
||||
popover-placement="bottom-end"
|
||||
.notFoundLabel=${this.hass?.localize(
|
||||
"ui.components.language-picker.no_match"
|
||||
)}
|
||||
.placeholder=${this.label ??
|
||||
(this.hass?.localize("ui.components.language-picker.language") ||
|
||||
"Language")}
|
||||
.value=${value || ""}
|
||||
.required=${this.required}
|
||||
.value=${value}
|
||||
.valueRenderer=${this._valueRenderer}
|
||||
.disabled=${this.disabled}
|
||||
@selected=${this._changed}
|
||||
@closed=${stopPropagation}
|
||||
fixedMenuPosition
|
||||
naturalMenuWidth
|
||||
.inlineArrow=${this.inlineArrow}
|
||||
.getItems=${this._getItems}
|
||||
@value-changed=${this._changed}
|
||||
hide-clear-icon
|
||||
>
|
||||
${languageOptions.length === 0
|
||||
? html`<ha-list-item value=""
|
||||
>${this.hass?.localize(
|
||||
"ui.components.language-picker.no_languages"
|
||||
) || "No languages"}</ha-list-item
|
||||
>`
|
||||
: languageOptions.map(
|
||||
(option) => html`
|
||||
<ha-list-item .value=${option.value}
|
||||
>${option.label}</ha-list-item
|
||||
>
|
||||
`
|
||||
)}
|
||||
</ha-select>
|
||||
${this.buttonStyle
|
||||
? html`<ha-button
|
||||
slot="field"
|
||||
.disabled=${this.disabled}
|
||||
@click=${this._openPicker}
|
||||
appearance="plain"
|
||||
variant="neutral"
|
||||
>
|
||||
${this._getLanguageName(value)}
|
||||
<ha-svg-icon slot="end" .path=${mdiMenuDown}></ha-svg-icon>
|
||||
</ha-button>`
|
||||
: nothing}
|
||||
</ha-generic-picker>
|
||||
`;
|
||||
}
|
||||
|
||||
private _openPicker(ev: Event) {
|
||||
ev.stopPropagation();
|
||||
this.genericPicker.open();
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-select {
|
||||
ha-generic-picker {
|
||||
width: 100%;
|
||||
min-width: 200px;
|
||||
display: block;
|
||||
}
|
||||
`;
|
||||
|
||||
private _changed(ev): void {
|
||||
const target = ev.target as HaSelect;
|
||||
if (this.disabled || target.value === "" || target.value === this.value) {
|
||||
return;
|
||||
}
|
||||
this.value = target.value;
|
||||
private _changed(ev: ValueChangedEvent<string>): void {
|
||||
ev.stopPropagation();
|
||||
this.value = ev.detail.value;
|
||||
fireEvent(this, "value-changed", { value: this.value });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ export class HaMarkdown extends LitElement {
|
||||
}
|
||||
ha-alert {
|
||||
display: block;
|
||||
margin: 4px 0;
|
||||
margin: var(--ha-space-1) 0;
|
||||
}
|
||||
a {
|
||||
color: var(--primary-color);
|
||||
@@ -75,7 +75,7 @@ export class HaMarkdown extends LitElement {
|
||||
padding: 0;
|
||||
}
|
||||
pre {
|
||||
padding: 16px;
|
||||
padding: var(--ha-space-4);
|
||||
overflow: auto;
|
||||
line-height: var(--ha-line-height-condensed);
|
||||
font-family: var(--ha-font-family-code);
|
||||
@@ -95,7 +95,7 @@ export class HaMarkdown extends LitElement {
|
||||
hr {
|
||||
border-color: var(--divider-color);
|
||||
border-bottom: none;
|
||||
margin: 16px 0;
|
||||
margin: var(--ha-space-4) 0;
|
||||
}
|
||||
` as CSSResultGroup;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import type { LitVirtualizer } from "@lit-labs/virtualizer";
|
||||
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
|
||||
import { mdiMagnify } from "@mdi/js";
|
||||
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit";
|
||||
import Fuse from "fuse.js";
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import {
|
||||
customElement,
|
||||
eventOptions,
|
||||
property,
|
||||
query,
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { tinykeys } from "tinykeys";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { caseInsensitiveStringCompare } from "../common/string/compare";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { HaFuse } from "../resources/fuse";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../types";
|
||||
import "./ha-combo-box";
|
||||
import type { HaComboBox } from "./ha-combo-box";
|
||||
import { haStyleScrollbar } from "../resources/styles";
|
||||
import { loadVirtualizer } from "../resources/virtualizer";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import "./ha-combo-box-item";
|
||||
import "./ha-icon";
|
||||
import "./ha-textfield";
|
||||
import type { HaTextField } from "./ha-textfield";
|
||||
|
||||
export interface PickerComboBoxItem {
|
||||
id: string;
|
||||
@@ -33,10 +42,13 @@ export interface PickerComboBoxItemWithLabel extends PickerComboBoxItem {
|
||||
|
||||
const NO_MATCHING_ITEMS_FOUND_ID = "___no_matching_items_found___";
|
||||
|
||||
const DEFAULT_ROW_RENDERER: ComboBoxLitRenderer<PickerComboBoxItem> = (
|
||||
const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = (
|
||||
item
|
||||
) => html`
|
||||
<ha-combo-box-item type="button" compact>
|
||||
<ha-combo-box-item
|
||||
.type=${item.id === NO_MATCHING_ITEMS_FOUND_ID ? "text" : "button"}
|
||||
compact
|
||||
>
|
||||
${item.icon
|
||||
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
|
||||
: item.icon_path
|
||||
@@ -57,7 +69,7 @@ export type PickerComboBoxSearchFn<T extends PickerComboBoxItem> = (
|
||||
|
||||
@customElement("ha-picker-combo-box")
|
||||
export class HaPickerComboBox extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
// eslint-disable-next-line lit/no-native-attributes
|
||||
@property({ type: Boolean }) public autofocus = false;
|
||||
@@ -73,7 +85,7 @@ export class HaPickerComboBox extends LitElement {
|
||||
|
||||
@property() public value?: string;
|
||||
|
||||
@property() public helper?: string;
|
||||
@state() private _listScrolled = false;
|
||||
|
||||
@property({ attribute: false, type: Array })
|
||||
public getItems?: () => PickerComboBoxItem[];
|
||||
@@ -82,10 +94,7 @@ export class HaPickerComboBox extends LitElement {
|
||||
public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[];
|
||||
|
||||
@property({ attribute: false })
|
||||
public rowRenderer?: ComboBoxLitRenderer<PickerComboBoxItem>;
|
||||
|
||||
@property({ attribute: "hide-clear-icon", type: Boolean })
|
||||
public hideClearIcon = false;
|
||||
public rowRenderer?: RenderItemFunction<PickerComboBoxItem>;
|
||||
|
||||
@property({ attribute: "not-found-label", type: String })
|
||||
public notFoundLabel?: string;
|
||||
@@ -93,33 +102,77 @@ export class HaPickerComboBox extends LitElement {
|
||||
@property({ attribute: false })
|
||||
public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>;
|
||||
|
||||
@state() private _opened = false;
|
||||
@property({ reflect: true }) public mode: "popover" | "dialog" = "popover";
|
||||
|
||||
@query("ha-combo-box", true) public comboBox!: HaComboBox;
|
||||
@query("lit-virtualizer") private _virtualizerElement?: LitVirtualizer;
|
||||
|
||||
public async open() {
|
||||
await this.updateComplete;
|
||||
await this.comboBox?.open();
|
||||
@query("ha-textfield") private _searchFieldElement?: HaTextField;
|
||||
|
||||
@state() private _items: PickerComboBoxItemWithLabel[] = [];
|
||||
|
||||
private _allItems: PickerComboBoxItemWithLabel[] = [];
|
||||
|
||||
private _selectedItemIndex = -1;
|
||||
|
||||
static shadowRootOptions = {
|
||||
...LitElement.shadowRootOptions,
|
||||
delegatesFocus: true,
|
||||
};
|
||||
|
||||
private _removeKeyboardShortcuts?: () => void;
|
||||
|
||||
protected firstUpdated() {
|
||||
this._registerKeyboardShortcuts();
|
||||
}
|
||||
|
||||
public async focus() {
|
||||
await this.updateComplete;
|
||||
await this.comboBox?.focus();
|
||||
public willUpdate() {
|
||||
if (!this.hasUpdated) {
|
||||
loadVirtualizer();
|
||||
this._allItems = this._getItems();
|
||||
this._items = this._allItems;
|
||||
}
|
||||
}
|
||||
|
||||
private _initialItems = false;
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._removeKeyboardShortcuts?.();
|
||||
}
|
||||
|
||||
private _items: PickerComboBoxItemWithLabel[] = [];
|
||||
protected render() {
|
||||
return html`<ha-textfield
|
||||
.label=${this.label ??
|
||||
this.hass?.localize("ui.common.search") ??
|
||||
"Search"}
|
||||
@input=${this._filterChanged}
|
||||
></ha-textfield>
|
||||
<lit-virtualizer
|
||||
@scroll=${this._onScrollList}
|
||||
tabindex="0"
|
||||
scroller
|
||||
.items=${this._items}
|
||||
.renderItem=${this._renderItem}
|
||||
style="min-height: 36px;"
|
||||
class=${this._listScrolled ? "scrolled" : ""}
|
||||
@focus=${this._focusList}
|
||||
>
|
||||
</lit-virtualizer> `;
|
||||
}
|
||||
|
||||
private _defaultNotFoundItem = memoizeOne(
|
||||
(
|
||||
label: this["notFoundLabel"],
|
||||
localize: LocalizeFunc
|
||||
localize?: LocalizeFunc
|
||||
): PickerComboBoxItemWithLabel => ({
|
||||
id: NO_MATCHING_ITEMS_FOUND_ID,
|
||||
primary: label || localize("ui.components.combo-box.no_match"),
|
||||
primary:
|
||||
label ||
|
||||
(localize && localize("ui.components.combo-box.no_match")) ||
|
||||
"No matching items found",
|
||||
icon_path: mdiMagnify,
|
||||
a11y_label: label || localize("ui.components.combo-box.no_match"),
|
||||
a11y_label:
|
||||
label ||
|
||||
(localize && localize("ui.components.combo-box.no_match")) ||
|
||||
"No matching items found",
|
||||
})
|
||||
);
|
||||
|
||||
@@ -144,13 +197,13 @@ export class HaPickerComboBox extends LitElement {
|
||||
caseInsensitiveStringCompare(
|
||||
entityA.sorting_label!,
|
||||
entityB.sorting_label!,
|
||||
this.hass.locale.language
|
||||
this.hass?.locale.language ?? navigator.language
|
||||
)
|
||||
);
|
||||
|
||||
if (!sortedItems.length) {
|
||||
sortedItems.push(
|
||||
this._defaultNotFoundItem(this.notFoundLabel, this.hass.localize)
|
||||
this._defaultNotFoundItem(this.notFoundLabel, this.hass?.localize)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -159,99 +212,73 @@ export class HaPickerComboBox extends LitElement {
|
||||
return sortedItems;
|
||||
};
|
||||
|
||||
protected shouldUpdate(changedProps: PropertyValues) {
|
||||
if (
|
||||
changedProps.has("value") ||
|
||||
changedProps.has("label") ||
|
||||
changedProps.has("disabled")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return !(!changedProps.has("_opened") && this._opened);
|
||||
}
|
||||
private _renderItem = (item: PickerComboBoxItem, index: number) => {
|
||||
const renderer = this.rowRenderer || DEFAULT_ROW_RENDERER;
|
||||
return html`<div
|
||||
id=${`list-item-${index}`}
|
||||
class="combo-box-row ${this._value === item.id ? "current-value" : ""}"
|
||||
.value=${item.id}
|
||||
.index=${index}
|
||||
@click=${this._valueSelected}
|
||||
>
|
||||
${item.id === NO_MATCHING_ITEMS_FOUND_ID
|
||||
? DEFAULT_ROW_RENDERER(item, index)
|
||||
: renderer(item, index)}
|
||||
</div>`;
|
||||
};
|
||||
|
||||
public willUpdate(changedProps: PropertyValues) {
|
||||
if (changedProps.has("_opened") && this._opened) {
|
||||
this._items = this._getItems();
|
||||
if (this._initialItems) {
|
||||
this.comboBox.filteredItems = this._items;
|
||||
}
|
||||
this._initialItems = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-combo-box
|
||||
item-id-path="id"
|
||||
item-value-path="id"
|
||||
item-label-path="a11y_label"
|
||||
clear-initial-value
|
||||
.hass=${this.hass}
|
||||
.value=${this._value}
|
||||
.label=${this.label}
|
||||
.helper=${this.helper}
|
||||
.allowCustomValue=${this.allowCustomValue}
|
||||
.filteredItems=${this._items}
|
||||
.renderer=${this.rowRenderer || DEFAULT_ROW_RENDERER}
|
||||
.required=${this.required}
|
||||
.disabled=${this.disabled}
|
||||
.hideClearIcon=${this.hideClearIcon}
|
||||
@opened-changed=${this._openedChanged}
|
||||
@value-changed=${this._valueChanged}
|
||||
@filter-changed=${this._filterChanged}
|
||||
>
|
||||
</ha-combo-box>
|
||||
`;
|
||||
@eventOptions({ passive: true })
|
||||
private _onScrollList(ev) {
|
||||
const top = ev.target.scrollTop ?? 0;
|
||||
this._listScrolled = top > 0;
|
||||
}
|
||||
|
||||
private get _value() {
|
||||
return this.value || "";
|
||||
}
|
||||
|
||||
private _openedChanged(ev: ValueChangedEvent<boolean>) {
|
||||
private _valueSelected = (ev: Event) => {
|
||||
ev.stopPropagation();
|
||||
if (ev.detail.value !== this._opened) {
|
||||
this._opened = ev.detail.value;
|
||||
fireEvent(this, "opened-changed", { value: this._opened });
|
||||
}
|
||||
}
|
||||
|
||||
private _valueChanged(ev: ValueChangedEvent<string | undefined>) {
|
||||
ev.stopPropagation();
|
||||
// Clear the input field to prevent showing the old value next time
|
||||
this.comboBox.setTextFieldValue("");
|
||||
const newValue = ev.detail.value?.trim();
|
||||
const value = (ev.currentTarget as any).value as string;
|
||||
const newValue = value?.trim();
|
||||
|
||||
if (newValue === NO_MATCHING_ITEMS_FOUND_ID) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (newValue !== this._value) {
|
||||
this._setValue(newValue);
|
||||
}
|
||||
}
|
||||
fireEvent(this, "value-changed", { value: newValue });
|
||||
};
|
||||
|
||||
private _fuseIndex = memoizeOne((states: PickerComboBoxItem[]) =>
|
||||
Fuse.createIndex(["search_labels"], states)
|
||||
);
|
||||
|
||||
private _filterChanged(ev: CustomEvent): void {
|
||||
if (!this._opened) return;
|
||||
private _filterChanged = (ev: Event) => {
|
||||
const textfield = ev.target as HaTextField;
|
||||
const searchString = textfield.value.trim();
|
||||
|
||||
const target = ev.target as HaComboBox;
|
||||
const searchString = ev.detail.value.trim() as string;
|
||||
if (!searchString) {
|
||||
this._items = this._allItems;
|
||||
return;
|
||||
}
|
||||
|
||||
const index = this._fuseIndex(this._items);
|
||||
const fuse = new HaFuse(this._items, { shouldSort: false }, index);
|
||||
const index = this._fuseIndex(this._allItems);
|
||||
const fuse = new HaFuse(
|
||||
this._allItems,
|
||||
{
|
||||
shouldSort: false,
|
||||
minMatchCharLength: Math.min(searchString.length, 2),
|
||||
},
|
||||
index
|
||||
);
|
||||
|
||||
const results = fuse.multiTermsSearch(searchString);
|
||||
let filteredItems = this._items as PickerComboBoxItem[];
|
||||
let filteredItems = this._allItems as PickerComboBoxItem[];
|
||||
if (results) {
|
||||
const items = results.map((result) => result.item);
|
||||
if (items.length === 0) {
|
||||
items.push(
|
||||
this._defaultNotFoundItem(this.notFoundLabel, this.hass.localize)
|
||||
this._defaultNotFoundItem(this.notFoundLabel, this.hass?.localize)
|
||||
);
|
||||
}
|
||||
const additionalItems = this._getAdditionalItems(searchString);
|
||||
@@ -260,17 +287,279 @@ export class HaPickerComboBox extends LitElement {
|
||||
}
|
||||
|
||||
if (this.searchFn) {
|
||||
filteredItems = this.searchFn(searchString, filteredItems, this._items);
|
||||
filteredItems = this.searchFn(
|
||||
searchString,
|
||||
filteredItems,
|
||||
this._allItems
|
||||
);
|
||||
}
|
||||
|
||||
target.filteredItems = filteredItems;
|
||||
this._items = filteredItems as PickerComboBoxItemWithLabel[];
|
||||
this._selectedItemIndex = -1;
|
||||
if (this._virtualizerElement) {
|
||||
this._virtualizerElement.scrollTo(0, 0);
|
||||
}
|
||||
};
|
||||
|
||||
private _registerKeyboardShortcuts() {
|
||||
this._removeKeyboardShortcuts = tinykeys(this, {
|
||||
ArrowUp: this._selectPreviousItem,
|
||||
ArrowDown: this._selectNextItem,
|
||||
Home: this._selectFirstItem,
|
||||
End: this._selectLastItem,
|
||||
Enter: this._pickSelectedItem,
|
||||
});
|
||||
}
|
||||
|
||||
private _setValue(value: string | undefined) {
|
||||
setTimeout(() => {
|
||||
fireEvent(this, "value-changed", { value });
|
||||
}, 0);
|
||||
private _focusList() {
|
||||
if (this._selectedItemIndex === -1) {
|
||||
this._selectNextItem();
|
||||
}
|
||||
}
|
||||
|
||||
private _selectNextItem = (ev?: KeyboardEvent) => {
|
||||
ev?.stopPropagation();
|
||||
ev?.preventDefault();
|
||||
if (!this._virtualizerElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._searchFieldElement?.focus();
|
||||
|
||||
const items = this._virtualizerElement.items as PickerComboBoxItem[];
|
||||
|
||||
const maxItems = items.length - 1;
|
||||
|
||||
if (maxItems === -1) {
|
||||
this._resetSelectedItem();
|
||||
return;
|
||||
}
|
||||
|
||||
const nextIndex =
|
||||
maxItems === this._selectedItemIndex
|
||||
? this._selectedItemIndex
|
||||
: this._selectedItemIndex + 1;
|
||||
|
||||
if (!items[nextIndex]) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (items[nextIndex].id === NO_MATCHING_ITEMS_FOUND_ID) {
|
||||
// Skip titles, padding and empty search
|
||||
if (nextIndex === maxItems) {
|
||||
return;
|
||||
}
|
||||
this._selectedItemIndex = nextIndex + 1;
|
||||
} else {
|
||||
this._selectedItemIndex = nextIndex;
|
||||
}
|
||||
|
||||
this._scrollToSelectedItem();
|
||||
};
|
||||
|
||||
private _selectPreviousItem = (ev: KeyboardEvent) => {
|
||||
ev.stopPropagation();
|
||||
ev.preventDefault();
|
||||
if (!this._virtualizerElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._selectedItemIndex > 0) {
|
||||
const nextIndex = this._selectedItemIndex - 1;
|
||||
|
||||
const items = this._virtualizerElement.items as PickerComboBoxItem[];
|
||||
|
||||
if (!items[nextIndex]) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (items[nextIndex]?.id === NO_MATCHING_ITEMS_FOUND_ID) {
|
||||
// Skip titles, padding and empty search
|
||||
if (nextIndex === 0) {
|
||||
return;
|
||||
}
|
||||
this._selectedItemIndex = nextIndex - 1;
|
||||
} else {
|
||||
this._selectedItemIndex = nextIndex;
|
||||
}
|
||||
|
||||
this._scrollToSelectedItem();
|
||||
}
|
||||
};
|
||||
|
||||
private _selectFirstItem = (ev: KeyboardEvent) => {
|
||||
ev.stopPropagation();
|
||||
if (!this._virtualizerElement || !this._virtualizerElement.items.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextIndex = 0;
|
||||
|
||||
if (
|
||||
(this._virtualizerElement.items[nextIndex] as PickerComboBoxItem)?.id ===
|
||||
NO_MATCHING_ITEMS_FOUND_ID
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof this._virtualizerElement.items[nextIndex] === "string") {
|
||||
this._selectedItemIndex = nextIndex + 1;
|
||||
} else {
|
||||
this._selectedItemIndex = nextIndex;
|
||||
}
|
||||
|
||||
this._scrollToSelectedItem();
|
||||
};
|
||||
|
||||
private _selectLastItem = (ev: KeyboardEvent) => {
|
||||
ev.stopPropagation();
|
||||
if (!this._virtualizerElement || !this._virtualizerElement.items.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextIndex = this._virtualizerElement.items.length - 1;
|
||||
|
||||
if (
|
||||
(this._virtualizerElement.items[nextIndex] as PickerComboBoxItem)?.id ===
|
||||
NO_MATCHING_ITEMS_FOUND_ID
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof this._virtualizerElement.items[nextIndex] === "string") {
|
||||
this._selectedItemIndex = nextIndex - 1;
|
||||
} else {
|
||||
this._selectedItemIndex = nextIndex;
|
||||
}
|
||||
|
||||
this._scrollToSelectedItem();
|
||||
};
|
||||
|
||||
private _scrollToSelectedItem = () => {
|
||||
this._virtualizerElement
|
||||
?.querySelector(".selected")
|
||||
?.classList.remove("selected");
|
||||
|
||||
this._virtualizerElement?.scrollToIndex(this._selectedItemIndex, "end");
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
this._virtualizerElement
|
||||
?.querySelector(`#list-item-${this._selectedItemIndex}`)
|
||||
?.classList.add("selected");
|
||||
});
|
||||
};
|
||||
|
||||
private _pickSelectedItem = (ev: KeyboardEvent) => {
|
||||
ev.stopPropagation();
|
||||
const firstItem = this._virtualizerElement?.items[0] as PickerComboBoxItem;
|
||||
|
||||
if (
|
||||
this._virtualizerElement?.items.length === 1 &&
|
||||
firstItem.id !== NO_MATCHING_ITEMS_FOUND_ID
|
||||
) {
|
||||
fireEvent(this, "value-changed", {
|
||||
value: firstItem.id,
|
||||
});
|
||||
}
|
||||
|
||||
if (this._selectedItemIndex === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if filter button is focused
|
||||
ev.preventDefault();
|
||||
|
||||
const item = this._virtualizerElement?.items[
|
||||
this._selectedItemIndex
|
||||
] as PickerComboBoxItem;
|
||||
if (item && item.id !== NO_MATCHING_ITEMS_FOUND_ID) {
|
||||
fireEvent(this, "value-changed", { value: item.id });
|
||||
}
|
||||
};
|
||||
|
||||
private _resetSelectedItem() {
|
||||
this._virtualizerElement
|
||||
?.querySelector(".selected")
|
||||
?.classList.remove("selected");
|
||||
this._selectedItemIndex = -1;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
haStyleScrollbar,
|
||||
css`
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-top: var(--ha-space-3);
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
ha-textfield {
|
||||
padding: 0 var(--ha-space-3);
|
||||
margin-bottom: var(--ha-space-3);
|
||||
}
|
||||
|
||||
:host([mode="dialog"]) ha-textfield {
|
||||
padding: 0 var(--ha-space-4);
|
||||
}
|
||||
|
||||
ha-combo-box-item {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
ha-combo-box-item.selected {
|
||||
background-color: var(--ha-color-fill-neutral-quiet-hover);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
ha-combo-box-item.selected {
|
||||
background-color: var(--ha-color-fill-neutral-normal-hover);
|
||||
}
|
||||
}
|
||||
|
||||
lit-virtualizer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
lit-virtualizer:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
lit-virtualizer.scrolled {
|
||||
border-top: 1px solid var(--ha-color-border-neutral-quiet);
|
||||
}
|
||||
|
||||
.bottom-padding {
|
||||
height: max(var(--safe-area-inset-bottom, 0px), var(--ha-space-8));
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.combo-box-row {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
min-height: 36px;
|
||||
}
|
||||
.combo-box-row.current-value {
|
||||
background-color: var(--ha-color-fill-primary-quiet-resting);
|
||||
}
|
||||
|
||||
.combo-box-row.selected {
|
||||
background-color: var(--ha-color-fill-neutral-quiet-hover);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.combo-box-row.selected {
|
||||
background-color: var(--ha-color-fill-neutral-normal-hover);
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -137,7 +137,7 @@ export class HaSelect extends SelectBase {
|
||||
height: var(--ha-select-height, 56px);
|
||||
}
|
||||
.mdc-select--filled .mdc-floating-label {
|
||||
inset-inline-start: 12px;
|
||||
inset-inline-start: var(--ha-space-4);
|
||||
inset-inline-end: initial;
|
||||
direction: var(--direction);
|
||||
}
|
||||
@@ -147,7 +147,7 @@ export class HaSelect extends SelectBase {
|
||||
direction: var(--direction);
|
||||
}
|
||||
.mdc-select .mdc-select__anchor {
|
||||
padding-inline-start: 12px;
|
||||
padding-inline-start: var(--ha-space-4);
|
||||
padding-inline-end: 0px;
|
||||
direction: var(--direction);
|
||||
}
|
||||
@@ -158,7 +158,10 @@ export class HaSelect extends SelectBase {
|
||||
padding-inline-end: var(--select-selected-text-padding-end, 0px);
|
||||
}
|
||||
:host([clearable]) .mdc-select__selected-text-container {
|
||||
padding-inline-end: var(--select-selected-text-padding-end, 12px);
|
||||
padding-inline-end: var(
|
||||
--select-selected-text-padding-end,
|
||||
var(--ha-space-4)
|
||||
);
|
||||
}
|
||||
ha-icon-button {
|
||||
position: absolute;
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { BackgroundSelector } from "../../data/selector";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import "../ha-picture-upload";
|
||||
import "../ha-alert";
|
||||
import type { HaPictureUpload } from "../ha-picture-upload";
|
||||
import { URL_PREFIX } from "../../data/image_upload";
|
||||
|
||||
@customElement("ha-selector-background")
|
||||
export class HaBackgroundSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property() public value?: any;
|
||||
|
||||
@property({ attribute: false }) public selector!: BackgroundSelector;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@property({ type: Boolean }) public required = true;
|
||||
|
||||
@state() private yamlBackground = false;
|
||||
|
||||
protected updated(changedProps) {
|
||||
super.updated(changedProps);
|
||||
|
||||
if (changedProps.has("value")) {
|
||||
this.yamlBackground = !!this.value && !this.value.startsWith(URL_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<div>
|
||||
${this.yamlBackground
|
||||
? html`
|
||||
<div class="value">
|
||||
<img
|
||||
src=${this.value}
|
||||
alt=${this.hass.localize(
|
||||
"ui.components.picture-upload.current_image_alt"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<ha-alert alert-type="info">
|
||||
${this.hass.localize(
|
||||
`ui.components.selectors.background.yaml_info`
|
||||
)}
|
||||
<ha-button slot="action" @click=${this._clearValue}>
|
||||
${this.hass.localize(
|
||||
`ui.components.picture-upload.clear_picture`
|
||||
)}
|
||||
</ha-button>
|
||||
</ha-alert>
|
||||
`
|
||||
: html`
|
||||
<ha-picture-upload
|
||||
.hass=${this.hass}
|
||||
.value=${this.value?.startsWith(URL_PREFIX) ? this.value : null}
|
||||
.original=${!!this.selector.background?.original}
|
||||
.cropOptions=${this.selector.background?.crop}
|
||||
select-media
|
||||
@change=${this._pictureChanged}
|
||||
></ha-picture-upload>
|
||||
`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _pictureChanged(ev) {
|
||||
const value = (ev.target as HaPictureUpload).value;
|
||||
|
||||
fireEvent(this, "value-changed", { value: value ?? undefined });
|
||||
}
|
||||
|
||||
private _clearValue() {
|
||||
fireEvent(this, "value-changed", { value: undefined });
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
ha-picture-upload {
|
||||
background-color: var(--primary-background-color);
|
||||
border-radius: var(--file-upload-image-border-radius);
|
||||
}
|
||||
div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
ha-button {
|
||||
white-space: nowrap;
|
||||
--mdc-theme-primary: var(--primary-color);
|
||||
}
|
||||
.value {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 200px;
|
||||
margin-bottom: 4px;
|
||||
border-radius: var(--file-upload-image-border-radius);
|
||||
transition: opacity 0.3s;
|
||||
opacity: var(--picture-opacity, 1);
|
||||
}
|
||||
img:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-selector-background": HaBackgroundSelector;
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@ export class HaDeviceSelector extends LitElement {
|
||||
|
||||
@property() public helper?: string;
|
||||
|
||||
@property() public placeholder?: string;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@property({ type: Boolean }) public required = true;
|
||||
@@ -102,6 +104,7 @@ export class HaDeviceSelector extends LitElement {
|
||||
.entityFilter=${this.selector.device?.entity
|
||||
? this._filterEntities
|
||||
: undefined}
|
||||
.placeholder=${this.placeholder}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required}
|
||||
allow-custom-entity
|
||||
|
||||
@@ -29,6 +29,8 @@ export class HaEntitySelector extends LitElement {
|
||||
|
||||
@property() public helper?: string;
|
||||
|
||||
@property() public placeholder?: any;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@property({ type: Boolean }) public required = true;
|
||||
@@ -69,6 +71,7 @@ export class HaEntitySelector extends LitElement {
|
||||
.excludeEntities=${this.selector.entity?.exclude_entities}
|
||||
.entityFilter=${this._filterEntities}
|
||||
.createDomains=${this._createDomains}
|
||||
.placeholder=${this.placeholder}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required}
|
||||
allow-custom-entity
|
||||
@@ -86,6 +89,7 @@ export class HaEntitySelector extends LitElement {
|
||||
.reorder=${this.selector.entity.reorder ?? false}
|
||||
.entityFilter=${this._filterEntities}
|
||||
.createDomains=${this._createDomains}
|
||||
.placeholder=${this.placeholder}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required}
|
||||
></ha-entities-picker>
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { ImageSelector } from "../../data/selector";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import "../ha-icon-button";
|
||||
import "../ha-textarea";
|
||||
import "../ha-textfield";
|
||||
import "../ha-picture-upload";
|
||||
import "../ha-radio";
|
||||
import "../ha-formfield";
|
||||
import type { HaPictureUpload } from "../ha-picture-upload";
|
||||
import { URL_PREFIX } from "../../data/image_upload";
|
||||
|
||||
@customElement("ha-selector-image")
|
||||
export class HaImageSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property() public value?: any;
|
||||
|
||||
@property() public name?: string;
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@property() public placeholder?: string;
|
||||
|
||||
@property() public helper?: string;
|
||||
|
||||
@property({ attribute: false }) public selector!: ImageSelector;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@property({ type: Boolean }) public required = true;
|
||||
|
||||
@state() private showUpload = false;
|
||||
|
||||
protected firstUpdated(changedProps): void {
|
||||
super.firstUpdated(changedProps);
|
||||
|
||||
if (!this.value || this.value.startsWith(URL_PREFIX)) {
|
||||
this.showUpload = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<div>
|
||||
<label>
|
||||
${this.hass.localize(
|
||||
"ui.components.selectors.image.select_image_with_label",
|
||||
{
|
||||
label:
|
||||
this.label ||
|
||||
this.hass.localize("ui.components.selectors.image.image"),
|
||||
}
|
||||
)}
|
||||
<ha-formfield
|
||||
.label=${this.hass.localize("ui.components.selectors.image.upload")}
|
||||
>
|
||||
<ha-radio
|
||||
name="mode"
|
||||
value="upload"
|
||||
.checked=${this.showUpload}
|
||||
@change=${this._radioGroupPicked}
|
||||
></ha-radio>
|
||||
</ha-formfield>
|
||||
<ha-formfield
|
||||
.label=${this.hass.localize("ui.components.selectors.image.url")}
|
||||
>
|
||||
<ha-radio
|
||||
name="mode"
|
||||
value="url"
|
||||
.checked=${!this.showUpload}
|
||||
@change=${this._radioGroupPicked}
|
||||
></ha-radio>
|
||||
</ha-formfield>
|
||||
</label>
|
||||
${!this.showUpload
|
||||
? html`
|
||||
<ha-textfield
|
||||
.name=${this.name}
|
||||
.value=${this.value || ""}
|
||||
.placeholder=${this.placeholder || ""}
|
||||
.helper=${this.helper}
|
||||
helperPersistent
|
||||
.disabled=${this.disabled}
|
||||
@input=${this._handleChange}
|
||||
.label=${this.label || ""}
|
||||
.required=${this.required}
|
||||
></ha-textfield>
|
||||
`
|
||||
: html`
|
||||
<ha-picture-upload
|
||||
.hass=${this.hass}
|
||||
.value=${this.value?.startsWith(URL_PREFIX) ? this.value : null}
|
||||
.original=${this.selector.image?.original}
|
||||
.cropOptions=${this.selector.image?.crop}
|
||||
select-media
|
||||
@change=${this._pictureChanged}
|
||||
></ha-picture-upload>
|
||||
`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _radioGroupPicked(ev): void {
|
||||
this.showUpload = ev.target.value === "upload";
|
||||
}
|
||||
|
||||
private _pictureChanged(ev) {
|
||||
const value = (ev.target as HaPictureUpload).value;
|
||||
|
||||
fireEvent(this, "value-changed", { value: value ?? undefined });
|
||||
}
|
||||
|
||||
private _handleChange(ev) {
|
||||
let value = ev.target.value;
|
||||
if (this.value === value) {
|
||||
return;
|
||||
}
|
||||
if (value === "" && !this.required) {
|
||||
value = undefined;
|
||||
}
|
||||
|
||||
fireEvent(this, "value-changed", { value });
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
ha-textarea,
|
||||
ha-textfield {
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-selector-image": HaImageSelector;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user