mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-23 21:28:49 +00:00
Compare commits
160
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2bec6001a | ||
|
|
e0423fd81e | ||
|
|
f08e3b299e | ||
|
|
089ddb9ade | ||
|
|
50c911fe2f | ||
|
|
bf16d4e5a1 | ||
|
|
608ad23071 | ||
|
|
0d84bb01ec | ||
|
|
ff95b531b7 | ||
|
|
921b7362a5 | ||
|
|
fb20d72938 | ||
|
|
4a1328970f | ||
|
|
f441726c3c | ||
|
|
731fd30b07 | ||
|
|
b6660a23ed | ||
|
|
f3990796ba | ||
|
|
4fb7eefb27 | ||
|
|
214762a052 | ||
|
|
a75f7265ff | ||
|
|
3a5c534def | ||
|
|
ebd2842493 | ||
|
|
177eaff888 | ||
|
|
02a580815b | ||
|
|
b9c454e99b | ||
|
|
b5d65cd8e0 | ||
|
|
ec2f78471c | ||
|
|
9eb51a8c06 | ||
|
|
d32d637ba3 | ||
|
|
113f90eb8d | ||
|
|
c66d41d84b | ||
|
|
76d225f5ce | ||
|
|
6eef60dc57 | ||
|
|
b2efa6f989 | ||
|
|
98cc0046f4 | ||
|
|
e37bce3277 | ||
|
|
26c8e6db15 | ||
|
|
160cfc7828 | ||
|
|
46db541153 | ||
|
|
4d8eca2229 | ||
|
|
7fff78c391 | ||
|
|
b2405df91b | ||
|
|
01dac9b1e7 | ||
|
|
ca5eed92b8 | ||
|
|
9758bcd750 | ||
|
|
16103b7759 | ||
|
|
3bd7c6363b | ||
|
|
0ec07be0c5 | ||
|
|
848d75c5d3 | ||
|
|
b88233031e | ||
|
|
50ebbf9a49 | ||
|
|
f09e39fcbe | ||
|
|
300ffc051f | ||
|
|
c4dfc3910f | ||
|
|
5a528df3e3 | ||
|
|
cd87fc7ca1 | ||
|
|
203bbb194f | ||
|
|
cdc875fc13 | ||
|
|
3ba51a8ef2 | ||
|
|
52702f4a2b | ||
|
|
e31b404177 | ||
|
|
9338b91f18 | ||
|
|
b41693b8d2 | ||
|
|
407cf9e6a4 | ||
|
|
02aacd0c51 | ||
|
|
f80d578deb | ||
|
|
67297d7806 | ||
|
|
46204a1955 | ||
|
|
04ab43929e | ||
|
|
10b7f5ffb6 | ||
|
|
cce6a720f3 | ||
|
|
c8f6a9ef77 | ||
|
|
94bd98d78d | ||
|
|
0904c2a547 | ||
|
|
2fd66939e7 | ||
|
|
5e340cb4e5 | ||
|
|
8b2dc28d0f | ||
|
|
8d933e85d4 | ||
|
|
b93869e668 | ||
|
|
bfd511deaf | ||
|
|
eeec2d4662 | ||
|
|
500249d996 | ||
|
|
a4157a490d | ||
|
|
d24ec6d34f | ||
|
|
bef72ec5da | ||
|
|
87add82ad0 | ||
|
|
eb70761886 | ||
|
|
74a2d3636b | ||
|
|
f03740c446 | ||
|
|
4873df0df6 | ||
|
|
d08b734afd | ||
|
|
4d1fc1225d | ||
|
|
18bcddaa20 | ||
|
|
ca576fadf5 | ||
|
|
aea1ac4ac8 | ||
|
|
6e1fe2846e | ||
|
|
17202283b4 | ||
|
|
0c8323c4f6 | ||
|
|
a2a523d5e5 | ||
|
|
b379c0d311 | ||
|
|
4dc975ec23 | ||
|
|
84294d7a8f | ||
|
|
e5838446c8 | ||
|
|
53f000e492 | ||
|
|
c452e8e4ff | ||
|
|
e80b07893d | ||
|
|
c801a52e67 | ||
|
|
8ac2712e31 | ||
|
|
f7f15ae4a8 | ||
|
|
e66733186e | ||
|
|
1e7bdbbcc8 | ||
|
|
7292db76bf | ||
|
|
9d997fbe4c | ||
|
|
05d11c25c2 | ||
|
|
ec14a9fe39 | ||
|
|
fc640e236d | ||
|
|
c2db01285c | ||
|
|
f2d0da08ed | ||
|
|
502dcdc1a6 | ||
|
|
0d31ae5624 | ||
|
|
f57384a265 | ||
|
|
4fe20d7712 | ||
|
|
14a4c05130 | ||
|
|
2d6ebd26d9 | ||
|
|
5ba1190cdd | ||
|
|
81cf8050e4 | ||
|
|
1a10982a5e | ||
|
|
fb8ac756ce | ||
|
|
2c072ab254 | ||
|
|
31ca8c298b | ||
|
|
1a5d8884ad | ||
|
|
9a95c9dea9 | ||
|
|
5db5f9075d | ||
|
|
6ce043a8e4 | ||
|
|
d81a9f29b2 | ||
|
|
c39734f350 | ||
|
|
e65584e724 | ||
|
|
6641a43e43 | ||
|
|
2706bd89a1 | ||
|
|
bd434eeb0d | ||
|
|
16f01e1081 | ||
|
|
050251db23 | ||
|
|
13128609de | ||
|
|
0f70813ada | ||
|
|
5762da9d22 | ||
|
|
33f709cd21 | ||
|
|
1f77e4cd59 | ||
|
|
77170b447f | ||
|
|
e2bb744202 | ||
|
|
0eec83448a | ||
|
|
1864f6f802 | ||
|
|
9a19cc3bf6 | ||
|
|
ec51fb4f8d | ||
|
|
6a1a9bfb1b | ||
|
|
16807d2765 | ||
|
|
9caad65c91 | ||
|
|
af523f1087 | ||
|
|
349d5f7125 | ||
|
|
de64bd3c59 | ||
|
|
5253eef284 | ||
|
|
b1164739c3 |
No files matched your search
@@ -1,6 +1,7 @@
|
||||
FROM mcr.microsoft.com/devcontainers/python:3.14
|
||||
|
||||
ENV \
|
||||
COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
|
||||
DEBIAN_FRONTEND=noninteractive \
|
||||
DEVCONTAINER=true \
|
||||
PATH=$PATH:./node_modules/.bin
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
name: Verify actions lockfile
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_ACTIONS_LOCK_VERSION: v0.4.1
|
||||
GH_ACTIONS_LOCK_VERSION: v0.5.1
|
||||
steps:
|
||||
- name: Check out files from GitHub
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
@@ -18,7 +18,7 @@ workflows:
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/codeql-analysis.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
'.github/workflows/copilot-setup-steps.yml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
@@ -64,13 +64,13 @@ workflows:
|
||||
'.github/workflows/relative-ci.yaml':
|
||||
- 'relative-ci/agent-action@711f3a8fa1b928e6afde280011110c9b0a224a60'
|
||||
'.github/workflows/release-drafter.yaml':
|
||||
- 'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0'
|
||||
- 'release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea'
|
||||
'.github/workflows/release.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
|
||||
- 'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361'
|
||||
- 'home-assistant/actions@2026.11.0'
|
||||
- 'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
|
||||
- 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086'
|
||||
'.github/workflows/restrict-task-creation.yaml':
|
||||
@@ -82,12 +82,12 @@ workflows:
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
- 'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1'
|
||||
'.github/workflows/sync-sensor-entity-constants.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
- 'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1'
|
||||
'.github/workflows/translations.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
dependencies:
|
||||
@@ -151,14 +151,14 @@ dependencies:
|
||||
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
owner_id: 7513068
|
||||
repo_id: 113918130
|
||||
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
|
||||
ref: 'v4.39.1'
|
||||
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
|
||||
ref: 'v4.39.3'
|
||||
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
|
||||
ref: 'master'
|
||||
commit: 'sha1-86d4564712fa02543c808e3a693dd04f9d3f8361'
|
||||
'home-assistant/actions@2026.11.0':
|
||||
ref: '2026.11.0'
|
||||
commit: 'sha1-07f46fd2e19967768b5fd3000f91f857452b767c'
|
||||
owner_id: 13844975
|
||||
repo_id: 173703505
|
||||
'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716':
|
||||
@@ -166,9 +166,9 @@ dependencies:
|
||||
commit: 'sha1-9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
|
||||
owner_id: 13844975
|
||||
repo_id: 184234812
|
||||
'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1':
|
||||
ref: 'v8.1.1'
|
||||
commit: 'sha1-5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1':
|
||||
ref: 'v8.1.3'
|
||||
commit: 'sha1-3ffccacd46053766916f087ce41d627c0b8cf2d1'
|
||||
owner_id: 18365890
|
||||
repo_id: 197176365
|
||||
'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086':
|
||||
@@ -183,8 +183,8 @@ dependencies:
|
||||
commit: 'sha1-711f3a8fa1b928e6afde280011110c9b0a224a60'
|
||||
owner_id: 43522883
|
||||
repo_id: 398376354
|
||||
'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0':
|
||||
ref: 'v7.10.0'
|
||||
commit: 'sha1-978bb0b30c5ee8cdd332ced253758157150d43f0'
|
||||
'release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea':
|
||||
ref: 'v7.11.0'
|
||||
commit: 'sha1-d1a19e60e81a7e650d00a7de9277f87e439117ea'
|
||||
owner_id: 58292376
|
||||
repo_id: 139022359
|
||||
@@ -32,12 +32,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
languages: javascript-typescript
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
category: "/language:javascript-typescript"
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
name: Prepare container dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001
|
||||
defaults:
|
||||
run:
|
||||
@@ -155,7 +155,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -207,7 +207,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -261,7 +261,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
|
||||
@@ -19,6 +19,6 @@ jobs:
|
||||
pull-requests: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0 # v7.10.0
|
||||
- uses: release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea # v7.11.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
|
||||
- name: Verify version
|
||||
uses: home-assistant/actions/helpers/verify-version@86d4564712fa02543c808e3a693dd04f9d3f8361 # master
|
||||
uses: home-assistant/actions/helpers/verify-version@2026.11.0
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
run: pnpm exec prettier --write src/data/device_classes.ts
|
||||
|
||||
- name: Create pull request
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3
|
||||
with:
|
||||
branch: chore/sync-device-classes
|
||||
commit-message: Update device class constants
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
run: pnpm exec prettier --write src/data/sensor_entity_constants.ts
|
||||
|
||||
- name: Create pull request
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3
|
||||
with:
|
||||
branch: chore/sync-sensor-entity-constants
|
||||
commit-message: Update sensor entity constants
|
||||
|
||||
@@ -157,6 +157,99 @@ async function pollProcess(lokaliseApi, projectId, processId) {
|
||||
}
|
||||
/* eslint-enable no-await-in-loop */
|
||||
|
||||
const DRAFTS_ACCEPTED_KEYS = [
|
||||
// Written per language rather than translated from English, so an English edit doesn't make them outdated
|
||||
"ui.components.rooms.keywords",
|
||||
];
|
||||
|
||||
async function exportTranslations(lokaliseApi, projectId) {
|
||||
const exportProcess = await lokaliseApi.files().async_download(projectId, {
|
||||
format: "json",
|
||||
original_filenames: false,
|
||||
replace_breaks: false,
|
||||
json_unescaped_slashes: true,
|
||||
export_empty_as: "skip",
|
||||
filter_data: ["verified"],
|
||||
});
|
||||
|
||||
const finishedProcess = await pollProcess(
|
||||
lokaliseApi,
|
||||
projectId,
|
||||
exportProcess.process_id
|
||||
);
|
||||
|
||||
const bundleUrl = finishedProcess.details.download_url;
|
||||
|
||||
console.log(`Downloading translations from: ${bundleUrl}`);
|
||||
|
||||
const response = await fetch(bundleUrl);
|
||||
|
||||
if (response.status !== 200 && response.status !== 0) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
console.log(`Extracting translations...`);
|
||||
|
||||
const contents = await JSZip.loadAsync(await response.arrayBuffer());
|
||||
|
||||
const files = {};
|
||||
await Promise.all(
|
||||
Object.keys(contents.files).map(async (filename) => {
|
||||
const file = contents.file(filename);
|
||||
if (!file) {
|
||||
// no file, probably a directory
|
||||
return;
|
||||
}
|
||||
files[filename.split("/").splice(-1)[0]] = await file.async("string");
|
||||
})
|
||||
);
|
||||
return files;
|
||||
}
|
||||
|
||||
async function fetchDrafts(lokaliseApi, projectId) {
|
||||
const english = JSON.parse(
|
||||
await fs.readFile("src/translations/en.json", { encoding })
|
||||
);
|
||||
const keyNames = DRAFTS_ACCEPTED_KEYS.flatMap((key) => {
|
||||
const keys = key.split(".");
|
||||
const drafts = keys.reduce((obj, part) => obj?.[part], english) ?? {};
|
||||
return Object.keys(drafts).map((name) => [...keys, name].join("::"));
|
||||
});
|
||||
if (!keyNames.length) {
|
||||
return [];
|
||||
}
|
||||
const { items } = await lokaliseApi.keys().list({
|
||||
project_id: projectId,
|
||||
filter_keys: keyNames.join(","),
|
||||
include_translations: 1,
|
||||
limit: keyNames.length,
|
||||
});
|
||||
return items.flatMap((key) =>
|
||||
key.translations
|
||||
.filter(({ translation }) => translation)
|
||||
.map(({ language_iso, translation }) => ({
|
||||
filename: `${language_iso}.json`,
|
||||
path: key.key_name.web.split("::"),
|
||||
translation,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
function acceptDrafts(files, drafts) {
|
||||
const data = {};
|
||||
drafts.forEach(({ filename, path: keyPath, translation }) => {
|
||||
data[filename] ??= files[filename] ? JSON.parse(files[filename]) : {};
|
||||
const parent = keyPath.slice(0, -1).reduce((obj, part) => {
|
||||
obj[part] ??= {};
|
||||
return obj[part];
|
||||
}, data[filename]);
|
||||
parent[keyPath.at(-1)] = translation;
|
||||
});
|
||||
Object.entries(data).forEach(([filename, content]) => {
|
||||
files[filename] = JSON.stringify(content, null, 2);
|
||||
});
|
||||
}
|
||||
|
||||
gulp.task("fetch-lokalise", async function () {
|
||||
let apiKey;
|
||||
try {
|
||||
@@ -193,52 +286,24 @@ gulp.task("fetch-lokalise", async function () {
|
||||
await Promise.all(
|
||||
projects.map(async ([project, projectId]) => {
|
||||
try {
|
||||
const exportProcess = await lokaliseApi
|
||||
.files()
|
||||
.async_download(projectId, {
|
||||
format: "json",
|
||||
original_filenames: false,
|
||||
replace_breaks: false,
|
||||
json_unescaped_slashes: true,
|
||||
export_empty_as: "skip",
|
||||
filter_data: ["verified"],
|
||||
});
|
||||
|
||||
const finishedProcess = await pollProcess(
|
||||
lokaliseApi,
|
||||
projectId,
|
||||
exportProcess.process_id
|
||||
);
|
||||
|
||||
const bundleUrl = finishedProcess.details.download_url;
|
||||
|
||||
console.log(`Downloading translations from: ${bundleUrl}`);
|
||||
|
||||
const response = await fetch(bundleUrl);
|
||||
|
||||
if (response.status !== 200 && response.status !== 0) {
|
||||
throw new Error(response.statusText);
|
||||
const [files, drafts] = await Promise.all([
|
||||
exportTranslations(lokaliseApi, projectId),
|
||||
project === "frontend"
|
||||
? fetchDrafts(lokaliseApi, projectId)
|
||||
: undefined,
|
||||
]);
|
||||
if (drafts) {
|
||||
acceptDrafts(files, drafts);
|
||||
}
|
||||
|
||||
console.log(`Extracting translations...`);
|
||||
|
||||
const contents = await JSZip.loadAsync(await response.arrayBuffer());
|
||||
|
||||
await mkdirPromise;
|
||||
await Promise.all(
|
||||
Object.keys(contents.files).map(async (filename) => {
|
||||
const file = contents.file(filename);
|
||||
if (!file) {
|
||||
// no file, probably a directory
|
||||
return;
|
||||
}
|
||||
const content = await file.async("nodebuffer");
|
||||
await fs.writeFile(
|
||||
path.join(inDir, project, filename.split("/").splice(-1)[0]),
|
||||
content,
|
||||
{ flag: "w", encoding }
|
||||
);
|
||||
})
|
||||
Object.entries(files).map(([filename, content]) =>
|
||||
fs.writeFile(path.join(inDir, project, filename), content, {
|
||||
flag: "w",
|
||||
encoding,
|
||||
})
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
@@ -50,7 +50,9 @@ const convertToJSON = async (
|
||||
const encodedData = localeData.match(
|
||||
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
|
||||
)?.groups?.data;
|
||||
localeData = firstBlock.match(dataRegex)?.groups?.data;
|
||||
localeData =
|
||||
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
|
||||
firstBlock.match(dataRegex)?.groups?.data;
|
||||
if (!localeData && !encodedData) {
|
||||
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@
|
||||
The easiest way to get your Home Assistant installation served over
|
||||
HTTPS is by signing up for
|
||||
<a href="https://www.nabucasa.com" target="_blank"
|
||||
>Home Assistant Cloud by Nabu Casa</a
|
||||
>Home Assistant Link by Nabu Casa</a
|
||||
>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
|
||||
:host {
|
||||
display: block;
|
||||
height: 100vh;
|
||||
background-color: #f2f4f9;
|
||||
background-color: var(--primary-background-color, #f2f4f9);
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
}
|
||||
.container {
|
||||
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
|
||||
object-fit: cover;
|
||||
}
|
||||
.status {
|
||||
color: #1d2126;
|
||||
color: var(--primary-text-color, #1d2126);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 7.1 KiB |
@@ -1,7 +1,6 @@
|
||||
import type { DemoConfig } from "../types";
|
||||
import { demoEntitiesArsaboo } from "./entities";
|
||||
import { demoLovelaceArsaboo } from "./lovelace";
|
||||
import { demoThemeArsaboo } from "./theme";
|
||||
|
||||
export const demoArsaboo: DemoConfig = {
|
||||
authorName: "Arsaboo",
|
||||
@@ -9,5 +8,5 @@ export const demoArsaboo: DemoConfig = {
|
||||
name: "ARS Home",
|
||||
lovelace: demoLovelaceArsaboo,
|
||||
entities: demoEntitiesArsaboo,
|
||||
theme: demoThemeArsaboo,
|
||||
theme: { theme: "default", dark: false },
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
export const demoThemeArsaboo = () => ({});
|
||||
@@ -13,8 +13,13 @@ import type { EntityInput } from "../../../src/fake_data/entities/types";
|
||||
import type { DemoAutomation, DemoConfig, DemoTheme } from "./types";
|
||||
|
||||
export const applyDemoTheme = (hass: MockHomeAssistant, theme: DemoTheme) => {
|
||||
if (typeof theme === "function") {
|
||||
hass.mockTheme(theme());
|
||||
if ("vars" in theme) {
|
||||
// Like a theme with only one mode in core, so the app keeps that mode
|
||||
// when it applies the theme again
|
||||
hass.mockTheme(
|
||||
{ modes: theme.dark ? { dark: theme.vars } : { light: theme.vars } },
|
||||
{ theme: "fake-data", dark: theme.dark }
|
||||
);
|
||||
return;
|
||||
}
|
||||
hass.mockTheme(null, getDemoTheme(theme));
|
||||
|
||||
@@ -48,6 +48,8 @@ class DemoHomeDashboardStrategy extends ReactiveElement {
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
static getConfigElement = HomeDashboardStrategy.getConfigElement;
|
||||
}
|
||||
|
||||
class DemoHomeOverviewViewStrategy extends ReactiveElement {
|
||||
|
||||
+924
-1061
File diff suppressed because it is too large.
Load diff
@@ -1,28 +1,33 @@
|
||||
export const demoThemeJimpower = () => ({
|
||||
"text-primary-color": "var(--primary-text-color)",
|
||||
"primary-color": "#5294E2",
|
||||
"label-badge-red": "var(--accent-color)",
|
||||
"light-primary-color": "var(--accent-color)",
|
||||
"primary-background-color": "#383C45",
|
||||
"primary-text-color": "#FFFFFF",
|
||||
"secondary-background-color": "#383C45",
|
||||
"disabled-text-color": "#7F848E",
|
||||
"paper-grey-200": "#414A59",
|
||||
"label-badge-background-color": "#2E333A",
|
||||
"sidebar-icon-color": "var(--state-icon-color)",
|
||||
"table-row-background-color": "#353840",
|
||||
"paper-grey-50": "var(--primary-text-color)",
|
||||
"switch-checked-color": "var(--accent-color)",
|
||||
"secondary-text-color": "#5294E2",
|
||||
"error-color": "#E45E65",
|
||||
"divider-color": "rgba(0, 0, 0, .12)",
|
||||
"success-color": "#39E949",
|
||||
"switch-unchecked-button-color": "var(--disabled-text-color)",
|
||||
"label-badge-border-color": "green",
|
||||
"card-background-color": "#434954",
|
||||
"label-badge-text-color": "var(--primary-text-color)",
|
||||
"switch-unchecked-track-color": "var(--disabled-text-color)",
|
||||
"dark-primary-color": "var(--accent-color)",
|
||||
"accent-color": "#E45E65",
|
||||
"table-row-alternative-background-color": "#3E424B",
|
||||
});
|
||||
import { generateColorPalette } from "../../../../src/common/color/palette";
|
||||
import type { DemoCustomTheme } from "../types";
|
||||
|
||||
const primaryColor = "#5294E2";
|
||||
|
||||
export const demoThemeJimpower: DemoCustomTheme = {
|
||||
dark: true,
|
||||
vars: {
|
||||
...Object.fromEntries(generateColorPalette(primaryColor, "primary")),
|
||||
"text-primary-color": "var(--primary-text-color)",
|
||||
"primary-color": primaryColor,
|
||||
"label-badge-red": "var(--accent-color)",
|
||||
"light-primary-color": "var(--accent-color)",
|
||||
"primary-background-color": "#383C45",
|
||||
"primary-text-color": "#FFFFFF",
|
||||
"secondary-background-color": "#383C45",
|
||||
"disabled-text-color": "#7F848E",
|
||||
"label-badge-background-color": "#2E333A",
|
||||
"sidebar-icon-color": "var(--state-icon-color)",
|
||||
"table-row-background-color": "#353840",
|
||||
"secondary-text-color": "#5294E2",
|
||||
"error-color": "#E45E65",
|
||||
"success-color": "#39E949",
|
||||
"card-background-color": "#434954",
|
||||
"label-badge-text-color": "var(--primary-text-color)",
|
||||
"dark-primary-color": "var(--accent-color)",
|
||||
"accent-color": "#E45E65",
|
||||
"table-row-alternative-background-color": "#3E424B",
|
||||
"ha-card-border-radius": "20px",
|
||||
"ha-card-box-shadow": "3px 3px rgba(0, 0, 0, 0.4)",
|
||||
"ha-card-border-color": "rgba(100, 100, 100, 0.3)",
|
||||
},
|
||||
};
|
||||
@@ -1,29 +1,31 @@
|
||||
import { generateColorPalette } from "../../../../src/common/color/palette";
|
||||
import type { DemoCustomTheme } from "../types";
|
||||
|
||||
const primaryColor = "#2980b9";
|
||||
|
||||
// https://community.home-assistant.io/t/slate-a-new-dark-theme/86410
|
||||
export const demoThemeKernehed = () => ({
|
||||
"text-primary-color": "var(--primary-text-color)",
|
||||
"primary-color": "#2980b9",
|
||||
"label-badge-red": "var(--accent-color)",
|
||||
"primary-text-color": "#FFFFFF",
|
||||
"light-primary-color": "var(--accent-color)",
|
||||
"primary-background-color": "#222222",
|
||||
"sidebar-icon-color": "#777777",
|
||||
"secondary-background-color": "#222222",
|
||||
"disabled-text-color": "#777777",
|
||||
"paper-grey-200": "#222222",
|
||||
"label-badge-background-color": "#222222",
|
||||
"table-row-background-color": "#292929",
|
||||
"paper-grey-50": "var(--primary-text-color)",
|
||||
"switch-checked-color": "var(--accent-color)",
|
||||
"secondary-text-color": "#b58e31",
|
||||
"error-color": "#b58e31",
|
||||
"divider-color": "rgba(0, 0, 0, .12)",
|
||||
"success-color": "#2980b9",
|
||||
"switch-unchecked-button-color": "var(--disabled-text-color)",
|
||||
"label-badge-border-color": "green",
|
||||
"card-background-color": "#292929",
|
||||
"label-badge-text-color": "var(--primary-text-color)",
|
||||
"switch-unchecked-track-color": "var(--disabled-text-color)",
|
||||
"dark-primary-color": "var(--accent-color)",
|
||||
"accent-color": "#2980b9",
|
||||
"table-row-alternative-background-color": "#292929",
|
||||
});
|
||||
export const demoThemeKernehed: DemoCustomTheme = {
|
||||
dark: true,
|
||||
vars: {
|
||||
...Object.fromEntries(generateColorPalette(primaryColor, "primary")),
|
||||
"text-primary-color": "var(--primary-text-color)",
|
||||
"primary-color": primaryColor,
|
||||
"label-badge-red": "var(--accent-color)",
|
||||
"primary-text-color": "#FFFFFF",
|
||||
"light-primary-color": "var(--accent-color)",
|
||||
"primary-background-color": "#222222",
|
||||
"sidebar-icon-color": "#777777",
|
||||
"secondary-background-color": "#222222",
|
||||
"disabled-text-color": "#777777",
|
||||
"label-badge-background-color": "#222222",
|
||||
"table-row-background-color": "#292929",
|
||||
"secondary-text-color": "#b58e31",
|
||||
"error-color": "#b58e31",
|
||||
"success-color": "#2980b9",
|
||||
"card-background-color": "#292929",
|
||||
"label-badge-text-color": "var(--primary-text-color)",
|
||||
"dark-primary-color": "var(--accent-color)",
|
||||
"accent-color": "#2980b9",
|
||||
"table-row-alternative-background-color": "#292929",
|
||||
},
|
||||
};
|
||||
@@ -1,18 +1,23 @@
|
||||
export const demoThemeTeachingbirds = () => ({
|
||||
"paper-grey-50": "var(--primary-text-color)",
|
||||
"divider-color": "rgba(255, 255, 255, 0.12)",
|
||||
"primary-color": "#389638",
|
||||
"light-primary-color": "#6f956f",
|
||||
"label-badge-red": "var(--primary-color)",
|
||||
"switch-unchecked-track-color": "var(--primary-text-color)",
|
||||
"card-background-color": "#4e4e4e",
|
||||
"label-badge-text-color": "var(--text-primary-color)",
|
||||
"primary-background-color": "#303030",
|
||||
"sidebar-icon-color": "#d3d3d3",
|
||||
"secondary-background-color": "#2b2b2b",
|
||||
"switch-checked-color": "var(--primary-color)",
|
||||
"secondary-text-color": "#389638",
|
||||
"disabled-text-color": "#545454",
|
||||
"paper-grey-200": "#191919",
|
||||
"label-badge-background-color": "var(--secondary-background-color)",
|
||||
});
|
||||
import { generateColorPalette } from "../../../../src/common/color/palette";
|
||||
import type { DemoCustomTheme } from "../types";
|
||||
|
||||
const primaryColor = "#389638";
|
||||
|
||||
export const demoThemeTeachingbirds: DemoCustomTheme = {
|
||||
dark: true,
|
||||
vars: {
|
||||
...Object.fromEntries(generateColorPalette(primaryColor, "primary")),
|
||||
"divider-color": "rgba(255, 255, 255, 0.12)",
|
||||
"primary-color": primaryColor,
|
||||
"light-primary-color": "#6f956f",
|
||||
"label-badge-red": "var(--primary-color)",
|
||||
"card-background-color": "#4e4e4e",
|
||||
"label-badge-text-color": "var(--text-primary-color)",
|
||||
"primary-background-color": "#303030",
|
||||
"sidebar-icon-color": "#d3d3d3",
|
||||
"secondary-background-color": "#2b2b2b",
|
||||
"secondary-text-color": "#389638",
|
||||
"disabled-text-color": "#545454",
|
||||
"label-badge-background-color": "var(--secondary-background-color)",
|
||||
},
|
||||
};
|
||||
@@ -7,7 +7,13 @@ import type { ThemeSettings } from "../../../src/types";
|
||||
import type { DemoArea } from "../stubs/area_registry";
|
||||
import type { DemoFloor } from "../stubs/floor_registry";
|
||||
|
||||
export type DemoTheme = ThemeSettings | (() => Record<string, string> | null);
|
||||
export interface DemoCustomTheme {
|
||||
/** The vars are applied on top of the default dark or light theme */
|
||||
dark: boolean;
|
||||
vars: Record<string, string>;
|
||||
}
|
||||
|
||||
export type DemoTheme = ThemeSettings | DemoCustomTheme;
|
||||
|
||||
export interface DemoAutomation {
|
||||
config: ManualAutomationConfig & { id: string; alias: string };
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
/* eslint-disable */
|
||||
import { LitElement } from "lit";
|
||||
import "./card-tools";
|
||||
|
||||
class CardModder extends LitElement {
|
||||
setConfig(config) {
|
||||
if (!window.cardTools)
|
||||
throw new Error(
|
||||
`Can't find card-tools. See https://github.com/thomasloven/lovelace-card-tools`
|
||||
);
|
||||
window.cardTools.checkVersion(0.2);
|
||||
|
||||
if (!config || !config.card) {
|
||||
throw new Error("Card config incorrect");
|
||||
}
|
||||
if (Array.isArray(config.card)) {
|
||||
throw new Error("It says 'card', not 'cardS'. Remove the dash.");
|
||||
}
|
||||
this._config = config;
|
||||
this.card = window.cardTools.createCard(config.card);
|
||||
this.templated = [];
|
||||
this.attempts = 0;
|
||||
}
|
||||
|
||||
render() {
|
||||
return window.cardTools.litHtml`
|
||||
<div id="root">${this.card}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
firstUpdated() {
|
||||
this._cardMod();
|
||||
}
|
||||
|
||||
_cardMod() {
|
||||
if (!this._config.style) return;
|
||||
|
||||
let target = null;
|
||||
target = target || this.card.querySelector("ha-card");
|
||||
target =
|
||||
target ||
|
||||
(this.card.shadowRoot && this.card.shadowRoot.querySelector("ha-card"));
|
||||
target =
|
||||
target ||
|
||||
(this.card.firstChild &&
|
||||
this.card.firstChild.shadowRoot &&
|
||||
this.card.firstChild.shadowRoot.querySelector("ha-card"));
|
||||
if (!target && !this.attempts)
|
||||
// Try twice
|
||||
setTimeout(() => this._cardMod(), 100);
|
||||
this.attempts++;
|
||||
target = target || this.card;
|
||||
|
||||
for (var k in this._config.style) {
|
||||
if (window.cardTools.hasTemplate(this._config.style[k]))
|
||||
this.templated.push(k);
|
||||
this.card.style.setProperty(k, "");
|
||||
target.style.setProperty(
|
||||
k,
|
||||
window.cardTools.parseTemplate(this._config.style[k])
|
||||
);
|
||||
}
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
set hass(hass) {
|
||||
if (this.card) this.card.hass = hass;
|
||||
if (this.templated)
|
||||
this.templated.forEach((k) => {
|
||||
this.target.style.setProperty(
|
||||
k,
|
||||
window.cardTools.parseTemplate(this._config.style[k], "")
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
getCardSize() {
|
||||
if (this._config && this._config.report_size)
|
||||
return this._config.report_size;
|
||||
if (this.card)
|
||||
return typeof this.card.getCardSize === "function"
|
||||
? this.card.getCardSize()
|
||||
: 1;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("card-modder", CardModder);
|
||||
@@ -1,198 +0,0 @@
|
||||
/* eslint-disable */
|
||||
import { html, LitElement } from "lit";
|
||||
|
||||
if (!window.cardTools) {
|
||||
const version = 0.2;
|
||||
const CUSTOM_TYPE_PREFIX = "custom:";
|
||||
|
||||
let cardTools = {};
|
||||
|
||||
cardTools.v = version;
|
||||
|
||||
cardTools.checkVersion = (v) => {
|
||||
if (version < v) {
|
||||
throw new Error(
|
||||
`Old version of card-tools found. Get the latest version of card-tools.js from https://github.com/thomasloven/lovelace-card-tools`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
cardTools.LitElement = LitElement;
|
||||
|
||||
cardTools.litHtml = html;
|
||||
|
||||
cardTools.hass = () => {
|
||||
return document.querySelector("home-assistant").hass;
|
||||
};
|
||||
|
||||
cardTools.fireEvent = (ev, detail) => {
|
||||
ev = new Event(ev, {
|
||||
bubbles: true,
|
||||
cancelable: false,
|
||||
composed: true,
|
||||
});
|
||||
ev.detail = detail || {};
|
||||
document.querySelector("ha-demo").dispatchEvent(ev);
|
||||
};
|
||||
|
||||
cardTools.createThing = (thing, config) => {
|
||||
const _createThing = (tag, config) => {
|
||||
const element = document.createElement(tag);
|
||||
try {
|
||||
element.setConfig(config);
|
||||
} catch (err) {
|
||||
console.error(tag, err);
|
||||
return _createError(err.message, config);
|
||||
}
|
||||
return element;
|
||||
};
|
||||
|
||||
const _createError = (error, config) => {
|
||||
return _createThing("hui-error-card", {
|
||||
type: "error",
|
||||
error,
|
||||
config,
|
||||
});
|
||||
};
|
||||
|
||||
if (!config || typeof config !== "object" || !config.type)
|
||||
return _createError(`No ${thing} type configured`, config);
|
||||
let tag = config.type;
|
||||
if (config.error) {
|
||||
const err = config.error;
|
||||
delete config.error;
|
||||
return _createError(err, config);
|
||||
}
|
||||
if (tag.startsWith(CUSTOM_TYPE_PREFIX))
|
||||
tag = tag.substr(CUSTOM_TYPE_PREFIX.length);
|
||||
else tag = `hui-${tag}-${thing}`;
|
||||
|
||||
if (customElements.get(tag)) return _createThing(tag, config);
|
||||
|
||||
// If element doesn't exist (yet) create an error
|
||||
const element = _createError(
|
||||
`Custom element doesn't exist: ${tag}.`,
|
||||
config
|
||||
);
|
||||
element.style.display = "None";
|
||||
const time = setTimeout(() => {
|
||||
element.style.display = "";
|
||||
}, 2000);
|
||||
// Remove error if element is defined later
|
||||
customElements.whenDefined(tag).then(() => {
|
||||
clearTimeout(timer);
|
||||
cardTools.fireEvent("rebuild-view");
|
||||
});
|
||||
|
||||
return element;
|
||||
};
|
||||
|
||||
cardTools.createCard = (config) => {
|
||||
return cardTools.createThing("card", config);
|
||||
};
|
||||
|
||||
cardTools.createElement = (config) => {
|
||||
return cardTools.createThing("element", config);
|
||||
};
|
||||
|
||||
cardTools.createEntityRow = (config) => {
|
||||
const SPECIAL_TYPES = new Set([
|
||||
"call-service",
|
||||
"divider",
|
||||
"section",
|
||||
"weblink",
|
||||
]);
|
||||
const DEFAULT_ROWS = {
|
||||
alert: "toggle",
|
||||
automation: "toggle",
|
||||
climate: "toggle",
|
||||
cover: "cover",
|
||||
fan: "toggle",
|
||||
group: "group",
|
||||
input_boolean: "toggle",
|
||||
input_number: "input-number",
|
||||
input_select: "input-select",
|
||||
input_text: "input-text",
|
||||
light: "toggle",
|
||||
media_player: "media-player",
|
||||
lock: "lock",
|
||||
scene: "scene",
|
||||
script: "script",
|
||||
sensor: "sensor",
|
||||
timer: "timer",
|
||||
switch: "toggle",
|
||||
vacuum: "toggle",
|
||||
};
|
||||
|
||||
if (
|
||||
!config ||
|
||||
typeof config !== "object" ||
|
||||
(!config.entity && !config.type)
|
||||
) {
|
||||
Object.assign(config, { error: "Invalid config given" });
|
||||
return cardTools.createThing("", config);
|
||||
}
|
||||
|
||||
const type = config.type || "default";
|
||||
if (SPECIAL_TYPES.has(type) || type.startsWith(CUSTOM_TYPE_PREFIX))
|
||||
return cardTools.createThing("row", config);
|
||||
|
||||
const domain = config.entity.split(".", 1)[0];
|
||||
Object.assign(config, { type: DEFAULT_ROWS[domain] || "simple" });
|
||||
return cardTools.createThing("entity-row", config);
|
||||
};
|
||||
|
||||
cardTools.deviceID = (() => {
|
||||
const ID_STORAGE_KEY = "lovelace-player-device-id";
|
||||
if (window["fully"] && typeof fully.getDeviceId === "function")
|
||||
return fully.getDeviceId();
|
||||
if (!localStorage[ID_STORAGE_KEY]) {
|
||||
const s4 = () => {
|
||||
return Math.floor((1 + Math.random()) * 100000)
|
||||
.toString(16)
|
||||
.substring(1);
|
||||
};
|
||||
localStorage[ID_STORAGE_KEY] = `${s4()}${s4()}-${s4()}${s4()}`;
|
||||
}
|
||||
return localStorage[ID_STORAGE_KEY];
|
||||
})();
|
||||
|
||||
cardTools.moreInfo = (entity) => {
|
||||
cardTools.fireEvent("hass-more-info", { entityId: entity });
|
||||
};
|
||||
|
||||
cardTools.longpress = (element) => {
|
||||
customElements.whenDefined("action-handler").then(() => {
|
||||
const longpress = document.body.querySelector("action-handler");
|
||||
longpress.bind(element);
|
||||
});
|
||||
return element;
|
||||
};
|
||||
|
||||
cardTools.hasTemplate = (text) => {
|
||||
return /\[\[\s+.*\s+\]\]/.test(text);
|
||||
};
|
||||
|
||||
cardTools.parseTemplate = (text, error) => {
|
||||
const _parse = (str) => {
|
||||
try {
|
||||
str = str.replace(/^\[\[\s+|\s+\]\]$/g, "");
|
||||
const parts = str.split(".");
|
||||
let v = cardTools.hass().states[`${parts[0]}.${parts[1]}`];
|
||||
parts.shift();
|
||||
parts.shift();
|
||||
parts.forEach((item) => (v = v[item]));
|
||||
return v;
|
||||
} catch (err) {
|
||||
return error || `[[ Template matching failed ${str} ]]`;
|
||||
}
|
||||
};
|
||||
text = text.replace(/(\[\[\s.*?\s\]\])/g, (str, p1, offset, s) =>
|
||||
_parse(str)
|
||||
);
|
||||
return text;
|
||||
};
|
||||
|
||||
window.cardTools = cardTools;
|
||||
cardTools.fireEvent("rebuild-view");
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
const pipelines: AssistPipeline[] = [
|
||||
{
|
||||
id: "01home_assistant_cloud",
|
||||
name: "Home Assistant Cloud",
|
||||
name: "Home Assistant Link",
|
||||
language: "en",
|
||||
conversation_engine: "conversation.home_assistant",
|
||||
conversation_language: "en",
|
||||
|
||||
@@ -78,7 +78,7 @@ const backupConfig: BackupConfig = {
|
||||
const agentsInfo: BackupAgentsInfo = {
|
||||
agents: [
|
||||
{ agent_id: "backup.local", name: "This device" },
|
||||
{ agent_id: "cloud.cloud", name: "Home Assistant Cloud" },
|
||||
{ agent_id: "cloud.cloud", name: "Home Assistant Link" },
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
|
||||
const prefs: EnergyPreferences = {
|
||||
energy_sources: [
|
||||
{
|
||||
type: "grid",
|
||||
@@ -21,7 +21,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "grid",
|
||||
@@ -34,7 +33,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid_return",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "solar",
|
||||
@@ -48,6 +46,23 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_energy_to: "sensor.battery_input",
|
||||
stat_rate: "sensor.power_battery",
|
||||
},
|
||||
{
|
||||
type: "battery",
|
||||
name: "Powerwall",
|
||||
stat_energy_from_grid: "sensor.powerwall_from_grid",
|
||||
stat_energy_from_solar: "sensor.powerwall_from_solar",
|
||||
stat_energy_to_home: "sensor.powerwall_to_home",
|
||||
stat_energy_to_grid: "sensor.powerwall_to_grid",
|
||||
stat_rate: "sensor.powerwall_power",
|
||||
power_config: {
|
||||
stat_rate_from_grid: "sensor.powerwall_power_from_grid",
|
||||
stat_rate_from_solar: "sensor.powerwall_power_from_solar",
|
||||
stat_rate_to_home: "sensor.powerwall_power_to_home",
|
||||
stat_rate_to_grid: "sensor.powerwall_power_to_grid",
|
||||
},
|
||||
stat_soc: "sensor.powerwall_battery_level",
|
||||
capacity: 13.5,
|
||||
},
|
||||
{
|
||||
type: "gas",
|
||||
stat_energy_from: "sensor.energy_gas",
|
||||
@@ -105,16 +120,17 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
}));
|
||||
};
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
hass.mockWS("energy/validate", () => ({
|
||||
energy_sources: Array.from({ length: 6 }, () => []),
|
||||
device_consumption: Array.from({ length: 6 }, () => []),
|
||||
device_consumption_water: Array.from({ length: 2 }, () => []),
|
||||
device_consumption_gas: Array.from({ length: 2 }, () => []),
|
||||
energy_sources: prefs.energy_sources.map(() => []),
|
||||
device_consumption: prefs.device_consumption.map(() => []),
|
||||
device_consumption_water: prefs.device_consumption_water.map(() => []),
|
||||
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -1,3 +1,30 @@
|
||||
// Live power of the battery measured per direction, in W
|
||||
const powerwallPower = {
|
||||
from_grid: 50,
|
||||
from_solar: 150,
|
||||
to_home: 0,
|
||||
to_grid: 0,
|
||||
};
|
||||
|
||||
const powerEntity = (entityId: string, power: number) => ({
|
||||
entity_id: entityId,
|
||||
state: String(power),
|
||||
attributes: {
|
||||
state_class: "measurement",
|
||||
unit_of_measurement: "W",
|
||||
},
|
||||
});
|
||||
|
||||
const powerwallEnergyEntity = (entityId: string, friendlyName: string) => ({
|
||||
entity_id: entityId,
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
friendly_name: friendlyName,
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
});
|
||||
|
||||
export const energyEntities = () =>
|
||||
Object.values({
|
||||
"sensor.grid_fossil_fuel_percentage": {
|
||||
@@ -34,6 +61,31 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
},
|
||||
"sensor.powerwall_from_grid": powerwallEnergyEntity(
|
||||
"sensor.powerwall_from_grid",
|
||||
"Powerwall charged from grid"
|
||||
),
|
||||
"sensor.powerwall_from_solar": powerwallEnergyEntity(
|
||||
"sensor.powerwall_from_solar",
|
||||
"Powerwall charged from solar"
|
||||
),
|
||||
"sensor.powerwall_to_home": powerwallEnergyEntity(
|
||||
"sensor.powerwall_to_home",
|
||||
"Powerwall discharged to home"
|
||||
),
|
||||
"sensor.powerwall_to_grid": powerwallEnergyEntity(
|
||||
"sensor.powerwall_to_grid",
|
||||
"Powerwall discharged to grid"
|
||||
),
|
||||
"sensor.powerwall_battery_level": {
|
||||
entity_id: "sensor.powerwall_battery_level",
|
||||
state: "62",
|
||||
attributes: {
|
||||
device_class: "battery",
|
||||
friendly_name: "Powerwall battery level",
|
||||
unit_of_measurement: "%",
|
||||
},
|
||||
},
|
||||
"sensor.energy_consumption_tarif_1": {
|
||||
entity_id: "sensor.energy_consumption_tarif_1",
|
||||
state: "88.6",
|
||||
@@ -134,6 +186,29 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "W",
|
||||
},
|
||||
},
|
||||
"sensor.powerwall_power_from_grid": powerEntity(
|
||||
"sensor.powerwall_power_from_grid",
|
||||
powerwallPower.from_grid
|
||||
),
|
||||
"sensor.powerwall_power_from_solar": powerEntity(
|
||||
"sensor.powerwall_power_from_solar",
|
||||
powerwallPower.from_solar
|
||||
),
|
||||
"sensor.powerwall_power_to_home": powerEntity(
|
||||
"sensor.powerwall_power_to_home",
|
||||
powerwallPower.to_home
|
||||
),
|
||||
"sensor.powerwall_power_to_grid": powerEntity(
|
||||
"sensor.powerwall_power_to_grid",
|
||||
powerwallPower.to_grid
|
||||
),
|
||||
"sensor.powerwall_power": powerEntity(
|
||||
"sensor.powerwall_power",
|
||||
powerwallPower.to_home +
|
||||
powerwallPower.to_grid -
|
||||
powerwallPower.from_grid -
|
||||
powerwallPower.from_solar
|
||||
),
|
||||
"sensor.energy_gas_cost": {
|
||||
entity_id: "sensor.energy_gas_cost",
|
||||
state: "2",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ValidSystemDataKey } from "../../../src/data/frontend";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import type { ThemeSettings } from "../../../src/types";
|
||||
|
||||
@@ -57,14 +58,40 @@ export const mockFrontend = (hass: MockHomeAssistant) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
return () => {};
|
||||
});
|
||||
// System data saved during this session, per key. Core starts from the
|
||||
// system data of the mock hass.
|
||||
const systemData: Partial<Record<ValidSystemDataKey, unknown>> = {
|
||||
core: hass.systemData,
|
||||
};
|
||||
const systemDataCallbacks: Partial<
|
||||
Record<ValidSystemDataKey, Set<(data: { value: unknown }) => void>>
|
||||
> = {};
|
||||
hass.mockWS(
|
||||
"frontend/subscribe_system_data",
|
||||
(_msg, currentHass, onChange) => {
|
||||
onChange?.({
|
||||
value: currentHass.systemData,
|
||||
});
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
return () => {};
|
||||
({ key }: { key: ValidSystemDataKey }, _currentHass, onChange) => {
|
||||
onChange?.({ value: systemData[key] ?? null });
|
||||
if (!onChange) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
return () => {};
|
||||
}
|
||||
const callbacks = (systemDataCallbacks[key] ??= new Set());
|
||||
callbacks.add(onChange);
|
||||
return () => {
|
||||
callbacks.delete(onChange);
|
||||
};
|
||||
}
|
||||
);
|
||||
hass.mockWS(
|
||||
"frontend/get_system_data",
|
||||
({ key }: { key: ValidSystemDataKey }) => ({
|
||||
value: systemData[key] ?? null,
|
||||
})
|
||||
);
|
||||
hass.mockWS(
|
||||
"frontend/set_system_data",
|
||||
({ key, value }: { key: ValidSystemDataKey; value: unknown }) => {
|
||||
systemData[key] = value;
|
||||
systemDataCallbacks[key]?.forEach((callback) => callback({ value }));
|
||||
}
|
||||
);
|
||||
hass.mockWS("labs/subscribe", (_msg, _currentHass, onChange) => {
|
||||
@@ -77,7 +104,6 @@ export const mockFrontend = (hass: MockHomeAssistant) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
return () => {};
|
||||
});
|
||||
hass.mockWS("frontend/get_system_data", () => ({ value: null }));
|
||||
hass.mockWS("repairs/list_issues", () => ({ issues: [] }));
|
||||
hass.mockWS("frontend/get_themes", (_msg, currentHass) => currentHass.themes);
|
||||
};
|
||||
@@ -351,6 +351,26 @@ const statisticsFunctions: Record<
|
||||
const derivedCosts: Record<string, { source: string; price: number }> = {
|
||||
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
|
||||
};
|
||||
// Battery directions as a share of the meter the energy also passes, so they
|
||||
// never exceed it
|
||||
const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
|
||||
"sensor.powerwall_from_grid": {
|
||||
source: "sensor.energy_consumption_tarif_1",
|
||||
share: 0.4,
|
||||
},
|
||||
"sensor.powerwall_from_solar": {
|
||||
source: "sensor.solar_production",
|
||||
share: 0.3,
|
||||
},
|
||||
"sensor.powerwall_to_home": {
|
||||
source: "sensor.energy_consumption_tarif_2",
|
||||
share: 0.5,
|
||||
},
|
||||
"sensor.powerwall_to_grid": {
|
||||
source: "sensor.energy_production_tarif_2",
|
||||
share: 0.3,
|
||||
},
|
||||
};
|
||||
|
||||
export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
mockHass.mockWS(
|
||||
@@ -375,15 +395,22 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
return cache[id];
|
||||
};
|
||||
|
||||
const scaleStats = (source: string, factor: number) => {
|
||||
let sum = 0;
|
||||
return getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * factor;
|
||||
sum += change;
|
||||
return { ...statistic, change, state: sum, sum };
|
||||
});
|
||||
};
|
||||
|
||||
statistic_ids.forEach((id: string) => {
|
||||
if (id in derivedCosts) {
|
||||
const { source, price } = derivedCosts[id];
|
||||
let cost = 0;
|
||||
statistics[id] = getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * price;
|
||||
cost += change;
|
||||
return { ...statistic, change, state: cost, sum: cost };
|
||||
});
|
||||
statistics[id] = scaleStats(source, price);
|
||||
} else if (id in derivedBatteryFlows) {
|
||||
const { source, share } = derivedBatteryFlows[id];
|
||||
statistics[id] = scaleStats(source, share);
|
||||
} else if (id in statisticsFunctions) {
|
||||
statistics[id] = getStats(id);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactiveElement } from "lit";
|
||||
import { ContextSubscriptionController } from "../../../src/common/decorators/consume";
|
||||
import { uiContext } from "../../../src/data/context";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
// A demo that provides its own hass hides the gallery theme from its children,
|
||||
// so pass the gallery light or dark mode on to it.
|
||||
export const followGalleryTheme = (
|
||||
host: ReactiveElement,
|
||||
hass: MockHomeAssistant
|
||||
) =>
|
||||
new ContextSubscriptionController(host, uiContext, (ui) => {
|
||||
if (ui) {
|
||||
hass.updateHass({
|
||||
themes: ui.themes,
|
||||
selectedTheme: ui.selectedTheme,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -86,6 +86,7 @@ const mql = matchMedia("(prefers-color-scheme: dark)");
|
||||
const galleryLocalize = (key: string) =>
|
||||
(
|
||||
({
|
||||
"ui.common.loading": "Loading",
|
||||
"ui.sidebar.sidebar_toggle": "Toggle sidebar",
|
||||
"ui.notification_drawer.title": "Notifications",
|
||||
"ui.sidebar.external_app_configuration": "App configuration",
|
||||
|
||||
@@ -284,7 +284,9 @@ export class DemoHaAdaptiveDialog extends LitElement {
|
||||
<p>
|
||||
The header title can be set using the <code>header-title</code>
|
||||
attribute or by providing custom content in the
|
||||
<code>headerTitle</code> slot.
|
||||
<code>headerTitle</code> slot. When you use the slot, set the
|
||||
<code>accessibleLabel</code> property so screen readers announce the
|
||||
dialog's name.
|
||||
</p>
|
||||
|
||||
<h4>Header subtitle</h4>
|
||||
|
||||
@@ -66,13 +66,14 @@ Check the [webawesome documentation](https://webawesome.com/docs/components/butt
|
||||
|
||||
**Properties/Attributes**
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | ---------------------------------------------- | -------- | --------------------------------------------------------------------------------- |
|
||||
| appearance | "accent"/"filled"/"outlined"/"plain" | "accent" | Sets the button appearance. |
|
||||
| variants | "brand"/"danger"/"neutral"/"warning"/"success" | "brand" | Sets the button color variant. "brand" is default. |
|
||||
| size | "xs"/"s"/"m"/"l"/"xl" | "m" | Sets the button size. |
|
||||
| loading | Boolean | false | Shows a loading indicator instead of the buttons label and disable buttons click. |
|
||||
| disabled | Boolean | false | Disables the button and prevents user interaction. |
|
||||
| Name | Type | Default | Description |
|
||||
| ------------ | ---------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
|
||||
| appearance | "accent"/"filled"/"outlined"/"plain" | "accent" | Sets the button appearance. |
|
||||
| variants | "brand"/"danger"/"neutral"/"warning"/"success" | "brand" | Sets the button color variant. "brand" is default. |
|
||||
| size | "xs"/"s"/"m"/"l"/"xl" | "m" | Sets the button size. |
|
||||
| loading | Boolean | false | Shows a loading indicator instead of the buttons label and disable buttons click. |
|
||||
| disabled | Boolean | false | Disables the button and prevents user interaction. |
|
||||
| aria-pressed | "true"/"false" | - | Makes it a toggle button and tells screen readers whether it is pressed. Leave unset for a regular button. |
|
||||
|
||||
**CSS Custom Properties**
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ This component is based on the webawesome input component.
|
||||
|
||||
**Slots**
|
||||
|
||||
- `start`: Content placed before the input (usually for icons or prefixes).
|
||||
- `end`: Content placed after the input (usually for icons or suffixes).
|
||||
- `start`: Content placed before the input, usually an icon. Use `input-prefix` for text.
|
||||
- `end`: Content placed after the input, usually an icon. Use `input-suffix` for text.
|
||||
- `label`: Custom label content. Overrides the `label` property.
|
||||
- `hint`: Custom hint content. Overrides the `hint` property.
|
||||
- `clear-icon`: Custom clear icon.
|
||||
@@ -56,6 +56,8 @@ This component is based on the webawesome input component.
|
||||
| auto-validate | Boolean | false | Validates the input on blur instead of on form submit. |
|
||||
| invalid | Boolean | false | Marks the input as invalid. |
|
||||
| inset-label | Boolean | false | Uses an inset label style where the label stays inside the input. |
|
||||
| input-prefix | String | - | Fixed text shown before the value. With a label, the label is inset above the prefix. |
|
||||
| input-suffix | String | - | Fixed text shown after the value. |
|
||||
| validation-message | String | "" | Custom validation message shown when the input is invalid. |
|
||||
| input-id | String | - | Sets the native input's `id` and associated label `for` on the inner `wa-input`. Defaults to `"input"`. |
|
||||
| pattern | String | - | A regular expression pattern to validate input against. |
|
||||
|
||||
@@ -136,14 +136,14 @@ export class DemoHaInput extends LitElement {
|
||||
></ha-input>
|
||||
</div>
|
||||
|
||||
<h3>With slots</h3>
|
||||
<h3>Prefix, suffix and slots</h3>
|
||||
<div class="row">
|
||||
<ha-input label="With prefix">
|
||||
<span slot="start">$</span>
|
||||
</ha-input>
|
||||
<ha-input label="With suffix">
|
||||
<span slot="end">kg</span>
|
||||
</ha-input>
|
||||
<ha-input
|
||||
label="With prefix"
|
||||
input-prefix="update."
|
||||
value="living_room"
|
||||
></ha-input>
|
||||
<ha-input label="With suffix" input-suffix="kg"></ha-input>
|
||||
<ha-input label="With icon">
|
||||
<ha-svg-icon
|
||||
.path=${mdiMagnify}
|
||||
|
||||
@@ -117,11 +117,17 @@ shared slots/attributes below.
|
||||
|
||||
**Attributes**
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------------- | ------- | ------- | --------------------------------------- |
|
||||
| `headline` | String | — | Primary text. Overridden by the slot. |
|
||||
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
|
||||
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
|
||||
| Name | Type | Default | Description |
|
||||
| ---------------------- | ------- | ------- | -------------------------------------------------- |
|
||||
| `headline` | String | — | Primary text. Overridden by the slot. |
|
||||
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
|
||||
| `wrap-headline` | Boolean | `false` | Wrap the headline instead of truncating it. |
|
||||
| `wrap-supporting-text` | Boolean | `false` | Wrap the supporting text instead of truncating it. |
|
||||
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
|
||||
|
||||
The headline and the supporting text stay on one line and are truncated with an
|
||||
ellipsis by default. Set `wrap-headline` or `wrap-supporting-text` on rows whose
|
||||
text has to stay readable in full, like settings with a description.
|
||||
|
||||
**CSS parts**
|
||||
|
||||
@@ -189,6 +195,51 @@ Subclasses customize the row by overriding `_renderStart()`,
|
||||
- `control` — the inner `<a>` or `<button>`.
|
||||
- `ripple` — the ripple effect element.
|
||||
|
||||
### `<ha-list-item-switch>`
|
||||
|
||||
Row with a switch at the end, for settings that turn something on or off. The
|
||||
whole row is the label of the switch: clicking anywhere on it toggles the
|
||||
switch. For screen readers, the headline names the switch and the supporting
|
||||
text describes it, so don't set `accessibleLabel` yourself.
|
||||
|
||||
The switch is its own tab stop, so the row doesn't join the roving tabindex of
|
||||
a parent list. The row can also be used on its own, outside a list; it then has
|
||||
no role.
|
||||
|
||||
Everything in the row is part of the label, so there is no `end` slot, and
|
||||
the `start` slot is for icons and avatars only. For a row with other controls
|
||||
next to the switch or inside its text, like an `ha-icon-button` or a link, use
|
||||
`ha-list-item-base` with an `ha-switch` in the `end` slot and set its
|
||||
`accessibleLabel`.
|
||||
|
||||
The row inherits the slots and attributes of `ha-list-item-base`, except
|
||||
`interactive`, which it doesn't use.
|
||||
|
||||
```html
|
||||
<ha-list-item-switch checked>
|
||||
<span slot="headline">Advanced mode</span>
|
||||
<span slot="supporting-text">Shows advanced settings and options.</span>
|
||||
</ha-list-item-switch>
|
||||
```
|
||||
|
||||
**Attributes**
|
||||
|
||||
- `checked` (Boolean, default `false`, reflected) — whether the switch is on.
|
||||
- `haptic` (Boolean, default `false`) — vibrates on toggle. Only set it when
|
||||
the change is applied right away, not when the user still has to save.
|
||||
|
||||
**Events**
|
||||
|
||||
- `change` — the switch was toggled. Read the new state from `checked` on the
|
||||
row.
|
||||
|
||||
**CSS parts**
|
||||
|
||||
- `switch` — the `ha-switch`. It only shows the state; the row handles
|
||||
input.
|
||||
- `base`, `start`, `content`, `headline`, `supporting-text` — as on
|
||||
`ha-row-item`. There is no `end` part.
|
||||
|
||||
### `<ha-list-item-option>`
|
||||
|
||||
Selectable row. Host role is `option`; reflects `aria-selected`. Designed to
|
||||
@@ -199,6 +250,9 @@ sit inside `<ha-list-selectable>`, which owns selection state and toggles
|
||||
|
||||
- `selected` (Boolean, default `false`, reflected) — set by the parent
|
||||
`ha-list-selectable`.
|
||||
- `indeterminate` (Boolean, default `false`, reflected) — draws the checkbox
|
||||
as mixed, for a row that stands for a partly selected set. Screen readers
|
||||
hear it as "Partly selected" through `aria-description`.
|
||||
- `value` (String) — value identifying the option.
|
||||
- `appearance` (`"line"` | `"checkbox"`, default `"line"`) — `"line"`
|
||||
highlights the row; `"checkbox"` renders a decorative `<ha-checkbox>`.
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import type { HASSDomTargetEvent } from "../../../../src/common/dom/fire_event";
|
||||
import "../../../../src/components/ha-card";
|
||||
import "../../../../src/components/ha-icon-button";
|
||||
import "../../../../src/components/ha-icon-next";
|
||||
@@ -21,6 +22,8 @@ import "../../../../src/components/ha-svg-icon";
|
||||
import "../../../../src/components/item/ha-list-item-base";
|
||||
import "../../../../src/components/item/ha-list-item-button";
|
||||
import "../../../../src/components/item/ha-list-item-option";
|
||||
import "../../../../src/components/item/ha-list-item-switch";
|
||||
import type { HaListItemSwitch } from "../../../../src/components/item/ha-list-item-switch";
|
||||
import "../../../../src/components/list/ha-list-base";
|
||||
import "../../../../src/components/list/ha-list-nav";
|
||||
import "../../../../src/components/list/ha-list-selectable";
|
||||
@@ -93,6 +96,12 @@ export class DemoHaList extends LitElement {
|
||||
|
||||
@state() private _tree = new Set<string>();
|
||||
|
||||
@state() private _switches: Record<string, boolean> = {
|
||||
wifi: true,
|
||||
advanced: false,
|
||||
standalone: false,
|
||||
};
|
||||
|
||||
private _options = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon"];
|
||||
|
||||
protected render(): TemplateResult {
|
||||
@@ -191,6 +200,20 @@ export class DemoHaList extends LitElement {
|
||||
<ha-list-item-base headline="Disabled row" disabled>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
headline="Truncated by default, a long headline stays on one line and ends with an ellipsis"
|
||||
supporting-text="Long supporting text is truncated as well, so every row in the list keeps the same height"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
wrap-headline
|
||||
wrap-supporting-text
|
||||
headline="With wrap-headline, a long headline wraps onto as many lines as it needs"
|
||||
supporting-text="With wrap-supporting-text, long supporting text wraps too, which suits settings with a description"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
@@ -271,6 +294,56 @@ export class DemoHaList extends LitElement {
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
<h2>ha-list-item-switch</h2>
|
||||
<p>
|
||||
Row with a switch. The whole row is the label of the switch, so clicking
|
||||
anywhere on it toggles the switch.
|
||||
</p>
|
||||
|
||||
<ha-card header="In a list">
|
||||
<ha-list-base aria-label="Switch items">
|
||||
<ha-list-item-switch
|
||||
wrap-supporting-text
|
||||
.checked=${this._switches.wifi}
|
||||
data-switch="wifi"
|
||||
@change=${this._onSwitchChange}
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiWifi}></ha-svg-icon>
|
||||
<span slot="headline">Wi-Fi</span>
|
||||
<span slot="supporting-text"
|
||||
>Connect to known networks automatically.</span
|
||||
>
|
||||
</ha-list-item-switch>
|
||||
<ha-list-item-switch
|
||||
.checked=${this._switches.advanced}
|
||||
data-switch="advanced"
|
||||
@change=${this._onSwitchChange}
|
||||
>
|
||||
<span slot="headline">Advanced mode</span>
|
||||
</ha-list-item-switch>
|
||||
<ha-list-item-switch
|
||||
disabled
|
||||
checked
|
||||
headline="Disabled"
|
||||
supporting-text="Can't be changed"
|
||||
></ha-list-item-switch>
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
<ha-card header="Without a list">
|
||||
<ha-list-item-switch
|
||||
wrap-headline
|
||||
.checked=${this._switches.standalone}
|
||||
data-switch="standalone"
|
||||
@change=${this._onSwitchChange}
|
||||
>
|
||||
<span slot="headline">A row on its own, without a list role</span>
|
||||
</ha-list-item-switch>
|
||||
<p class="card-text">
|
||||
State: <code>${JSON.stringify(this._switches)}</code>
|
||||
</p>
|
||||
</ha-card>
|
||||
|
||||
<h2>ha-list-selectable + ha-list-item-option</h2>
|
||||
<p>
|
||||
Selectable list (<code>role="listbox"</code>). Items must be
|
||||
@@ -489,6 +562,13 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
|
||||
this._buttonClicks++;
|
||||
};
|
||||
|
||||
private _onSwitchChange = (ev: HASSDomTargetEvent<HaListItemSwitch>) => {
|
||||
this._switches = {
|
||||
...this._switches,
|
||||
[ev.target.dataset.switch!]: ev.target.checked,
|
||||
};
|
||||
};
|
||||
|
||||
private _withIndex(
|
||||
value: number | Set<number>,
|
||||
index: number,
|
||||
|
||||
@@ -924,7 +924,7 @@ class DemoHaSelector extends LitElement implements ProvideHassElement {
|
||||
providers: [
|
||||
{
|
||||
engine_id: "stt.cloud",
|
||||
name: "Home Assistant Cloud",
|
||||
name: "Home Assistant Link",
|
||||
supported_languages: ["en-US"],
|
||||
deprecated: false,
|
||||
},
|
||||
@@ -934,7 +934,7 @@ class DemoHaSelector extends LitElement implements ProvideHassElement {
|
||||
providers: [
|
||||
{
|
||||
engine_id: "tts.cloud",
|
||||
name: "Home Assistant Cloud",
|
||||
name: "Home Assistant Link",
|
||||
supported_languages: ["en-US"],
|
||||
deprecated: false,
|
||||
},
|
||||
|
||||
@@ -2,3 +2,17 @@
|
||||
title: Spinner
|
||||
subtitle: Can be used to indicate an ongoing task.
|
||||
---
|
||||
|
||||
`ha-spinner` is `hac-spinner` from `@home-assistant/components`.
|
||||
|
||||
## Accessibility
|
||||
|
||||
`ha-spinner` is exposed to screen readers as a `progressbar` named with the translated "Loading". When the surrounding text does not already say what is in progress, name it with a translated `accessible-label`, like "Installing update", rather than its state.
|
||||
|
||||
```html
|
||||
<ha-spinner accessible-label="Installing update"></ha-spinner>
|
||||
```
|
||||
|
||||
If the spinner only decorates text that already says what is in progress, hide it with `aria-hidden="true"`.
|
||||
|
||||
For an action started from a button, use `ha-button` with `loading` instead of putting a spinner inside the button.
|
||||
@@ -23,8 +23,10 @@ export class DemoHaSpinner extends LitElement {
|
||||
<ha-spinner size="small"></ha-spinner>
|
||||
<ha-spinner size="medium"></ha-spinner>
|
||||
<ha-spinner size="large"></ha-spinner>
|
||||
<ha-spinner aria-label="Doing something..."></ha-spinner>
|
||||
<ha-spinner .ariaLabel=${"Doing something..."}></ha-spinner>
|
||||
<ha-spinner accessible-label="Doing something..."></ha-spinner>
|
||||
<ha-spinner
|
||||
.accessibleLabel=${"Doing something..."}
|
||||
></ha-spinner>
|
||||
</div>
|
||||
</ha-card>
|
||||
`
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
} from "../../../../src/data/history";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
import { followGalleryTheme } from "../../data/follow-gallery-theme";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const HOURS = 48;
|
||||
@@ -166,6 +167,7 @@ export class DemoStateHistoryCharts extends LitElement {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
followGalleryTheme(this, hass);
|
||||
hass.addEntities(ENTITIES);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import type { ChartSelectMode } from "../../../../src/components/chart/ha-chart-base";
|
||||
import "../../../../src/components/chart/statistics-chart";
|
||||
import "../../../../src/components/ha-button";
|
||||
import "../../../../src/components/ha-card";
|
||||
import type {
|
||||
Statistics,
|
||||
@@ -11,7 +13,9 @@ import type {
|
||||
} from "../../../../src/data/recorder";
|
||||
import { StatisticMeanType } from "../../../../src/data/recorder";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
import { followGalleryTheme } from "../../data/follow-gallery-theme";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const HOURS = 48;
|
||||
@@ -108,6 +112,64 @@ interface Example {
|
||||
height?: string;
|
||||
}
|
||||
|
||||
interface TimeRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface RangeExample {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
statistics: Statistics;
|
||||
statTypes: StatisticType[];
|
||||
chartType: "line" | "bar";
|
||||
unit: string;
|
||||
selectMode: ChartSelectMode;
|
||||
hint: string;
|
||||
}
|
||||
|
||||
const RANGE_EXAMPLES: RangeExample[] = [
|
||||
{
|
||||
id: "point",
|
||||
title: "Point selection",
|
||||
description:
|
||||
"With select-mode set to point, a click selects the hour that contains it, and everything outside fades. Dragging still zooms.",
|
||||
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
|
||||
statTypes: ["change"],
|
||||
chartType: "bar",
|
||||
unit: "kWh",
|
||||
selectMode: "point",
|
||||
hint: "Click on a bar to select its hour.",
|
||||
},
|
||||
{
|
||||
id: "range-bar",
|
||||
title: "Range selection on bars",
|
||||
description:
|
||||
"With select-mode set to range, dragging selects a time range instead of zooming, so several bars can be selected at once. A click still selects one bar.",
|
||||
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
|
||||
statTypes: ["change"],
|
||||
chartType: "bar",
|
||||
unit: "kWh",
|
||||
selectMode: "range",
|
||||
hint: "Click or drag on the chart to select one or more bars.",
|
||||
},
|
||||
{
|
||||
id: "range",
|
||||
title: "Range selection on lines",
|
||||
description: "The same on a line chart.",
|
||||
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM },
|
||||
statTypes: ["mean", "min", "max"],
|
||||
chartType: "line",
|
||||
unit: "°C",
|
||||
selectMode: "range",
|
||||
hint: "Click or drag on the chart to select a period.",
|
||||
},
|
||||
];
|
||||
|
||||
const formatRange = (range: TimeRange) =>
|
||||
`${new Date(range.start).toLocaleString()} to ${new Date(range.end).toLocaleString()}`;
|
||||
|
||||
const EXAMPLES: Example[] = [
|
||||
{
|
||||
title: "Sum as bars",
|
||||
@@ -159,17 +221,20 @@ const EXAMPLES: Example[] = [
|
||||
export class DemoStatisticsChart extends LitElement {
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@state() private _selections: Record<string, TimeRange | undefined> = {};
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
followGalleryTheme(this, hass);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
return EXAMPLES.map(
|
||||
return html`${EXAMPLES.map(
|
||||
(example) => html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
@@ -191,7 +256,66 @@ export class DemoStatisticsChart extends LitElement {
|
||||
</div>
|
||||
</ha-card>
|
||||
`
|
||||
);
|
||||
)}
|
||||
${RANGE_EXAMPLES.map((example) => this._renderRangeExample(example))}`;
|
||||
}
|
||||
|
||||
private _renderRangeExample(example: RangeExample) {
|
||||
const selection = this._selections[example.id];
|
||||
return html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
<p>${example.description}</p>
|
||||
<statistics-chart
|
||||
.statisticsData=${example.statistics}
|
||||
.metadata=${METADATA}
|
||||
.names=${NAMES}
|
||||
.statTypes=${example.statTypes}
|
||||
.chartType=${example.chartType}
|
||||
period="hour"
|
||||
.unit=${example.unit}
|
||||
.startTime=${START}
|
||||
.endTime=${END}
|
||||
.highlight=${selection}
|
||||
.clickForMoreInfo=${false}
|
||||
data-example=${example.id}
|
||||
.selectMode=${example.selectMode}
|
||||
hide-legend
|
||||
@chart-select=${this._rangeSelected}
|
||||
></statistics-chart>
|
||||
<div class="selection">
|
||||
${
|
||||
selection
|
||||
? html`
|
||||
<span>${formatRange(selection)}</span>
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
size="s"
|
||||
data-example=${example.id}
|
||||
@click=${this._clearSelection}
|
||||
>
|
||||
Clear
|
||||
</ha-button>
|
||||
`
|
||||
: html`<span class="hint">${example.hint}</span>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _rangeSelected(ev: HASSDomEvent<HASSDomEvents["chart-select"]>) {
|
||||
const id = (ev.currentTarget as HTMLElement).dataset.example!;
|
||||
this._selections = {
|
||||
...this._selections,
|
||||
[id]: ev.detail,
|
||||
};
|
||||
}
|
||||
|
||||
private _clearSelection(ev: Event) {
|
||||
const id = (ev.currentTarget as HTMLElement).dataset.example!;
|
||||
this._selections = { ...this._selections, [id]: undefined };
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
@@ -202,6 +326,20 @@ export class DemoStatisticsChart extends LitElement {
|
||||
p {
|
||||
margin-top: 0;
|
||||
}
|
||||
.selection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--ha-space-2);
|
||||
min-height: 48px;
|
||||
margin-top: var(--ha-space-2);
|
||||
padding: 0 var(--ha-space-2) 0 var(--ha-space-4);
|
||||
border-radius: var(--ha-border-radius-lg);
|
||||
background-color: var(--secondary-background-color);
|
||||
}
|
||||
.hint {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
title: Cloud account
|
||||
title: Home Assistant Link account
|
||||
---
|
||||
|
||||
The [Home Assistant Cloud](https://www.nabucasa.com/) account page, rendered from
|
||||
mocked cloud data. The controls at the top flip the mocked subscription, remote,
|
||||
The [Home Assistant Link](https://www.nabucasa.com/) account page, rendered from
|
||||
mocked Home Assistant Link data. The controls at the top flip the mocked subscription, remote,
|
||||
backup, onboarding, and feature state so every UI state can be previewed here
|
||||
without a real cloud account.
|
||||
without a real Home Assistant Link account.
|
||||
@@ -187,6 +187,139 @@ const ENTITIES = [
|
||||
current_tilt_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shade",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shade",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 60,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shutter",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shutter",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 40,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.awning",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Awning",
|
||||
device_class: "awning",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.curtain",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Curtain",
|
||||
device_class: "curtain",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.door",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Door",
|
||||
device_class: "door",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.gate",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Gate",
|
||||
device_class: "gate",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.window",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Window",
|
||||
device_class: "window",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.garage",
|
||||
state: "closed",
|
||||
attributes: {
|
||||
friendly_name: "Garage door",
|
||||
device_class: "garage",
|
||||
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unknown",
|
||||
state: "unknown",
|
||||
attributes: {
|
||||
friendly_name: "Unknown position",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unavailable",
|
||||
state: "unavailable",
|
||||
attributes: {
|
||||
friendly_name: "Unavailable",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@customElement("demo-more-info-cover")
|
||||
|
||||
@@ -250,7 +250,16 @@ class DemoMoreInfoUpdate extends LitElement {
|
||||
"update/release_notes",
|
||||
(msg: { type: string; entity_id: string }) => {
|
||||
if (msg.entity_id === "update.update16") {
|
||||
return LONG_TEXT;
|
||||
return {
|
||||
release_notes: LONG_TEXT,
|
||||
messages: [
|
||||
{
|
||||
severity: "warning",
|
||||
message:
|
||||
"Do not restart, remove power from, or otherwise interrupt the device while the update is in progress.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (msg.entity_id === "update.update17") {
|
||||
return Promise.reject({
|
||||
@@ -261,7 +270,7 @@ class DemoMoreInfoUpdate extends LitElement {
|
||||
if (msg.entity_id === "update.update18") {
|
||||
return undefined;
|
||||
}
|
||||
return null;
|
||||
return { release_notes: null, messages: [] };
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
+41
-41
@@ -40,7 +40,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.1.0",
|
||||
"@babel/runtime": "8.1.2",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
@@ -48,23 +48,23 @@
|
||||
"@codemirror/lang-python": "6.2.1",
|
||||
"@codemirror/lang-yaml": "6.1.3",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/lint": "6.9.7",
|
||||
"@codemirror/lint": "6.9.8",
|
||||
"@codemirror/search": "6.7.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "8.0.2",
|
||||
"@formatjs/intl-displaynames": "8.0.1",
|
||||
"@formatjs/intl-durationformat": "0.12.3",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.0",
|
||||
"@formatjs/intl-listformat": "9.0.1",
|
||||
"@formatjs/intl-locale": "5.4.2",
|
||||
"@formatjs/intl-numberformat": "10.0.2",
|
||||
"@formatjs/intl-pluralrules": "7.0.2",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.1",
|
||||
"@formatjs/intl-datetimeformat": "8.0.3",
|
||||
"@formatjs/intl-displaynames": "8.0.3",
|
||||
"@formatjs/intl-durationformat": "0.13.0",
|
||||
"@formatjs/intl-getcanonicallocales": "3.4.0",
|
||||
"@formatjs/intl-listformat": "9.1.0",
|
||||
"@formatjs/intl-locale": "5.5.0",
|
||||
"@formatjs/intl-numberformat": "10.1.0",
|
||||
"@formatjs/intl-pluralrules": "7.1.0",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.3",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/common": "1.5.6",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lit-labs/motion": "1.1.0",
|
||||
"@lit-labs/observers": "2.1.0",
|
||||
@@ -77,13 +77,13 @@
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
"@swc/helpers": "0.5.24",
|
||||
"@tsparticles/engine": "4.5.3",
|
||||
"@tsparticles/preset-links": "4.5.3",
|
||||
"@versatiles/style": "9.0.0",
|
||||
"@tsparticles/engine": "4.5.4",
|
||||
"@tsparticles/preset-links": "4.5.4",
|
||||
"@versatiles/style": "9.1.0",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.204.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
"barcode-detector": "3.2.3",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.11",
|
||||
"barcode-detector": "3.2.4",
|
||||
"cally": "0.9.2",
|
||||
"color-name": "2.1.1",
|
||||
"comlink": "4.4.2",
|
||||
@@ -97,19 +97,19 @@
|
||||
"echarts": "6.1.0",
|
||||
"echarts-extension-chart2music": "0.1.1",
|
||||
"element-internals-polyfill": "3.0.2",
|
||||
"fullcalendar": "7.1.4",
|
||||
"fullcalendar": "7.1.5",
|
||||
"fuse.js": "7.5.0",
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.8.1",
|
||||
"home-assistant-js-websocket": "9.9.0",
|
||||
"idb-keyval": "6.3.0",
|
||||
"intl-messageformat": "12.1.4",
|
||||
"intl-messageformat": "12.2.0",
|
||||
"js-yaml": "5.5.0",
|
||||
"leaflet": "1.9.4",
|
||||
"leaflet.markercluster": "1.5.3",
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.17.0",
|
||||
"marked": "18.1.3",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"marked": "18.2.1",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
@@ -136,12 +136,12 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.1.0",
|
||||
"@babel/core": "8.1.2",
|
||||
"@babel/helper-compilation-targets": "8.0.7",
|
||||
"@babel/helper-define-polyfill-provider": "1.0.0",
|
||||
"@babel/plugin-transform-class-properties": "8.0.1",
|
||||
"@babel/plugin-transform-private-methods": "8.0.1",
|
||||
"@babel/plugin-transform-runtime": "8.0.6",
|
||||
"@babel/plugin-transform-runtime": "8.1.2",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
@@ -151,9 +151,9 @@
|
||||
"@lokalise/node-api": "17.0.1",
|
||||
"@octokit/auth-oauth-device": "8.0.5",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.65.0",
|
||||
"@playwright/test": "1.65.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.1",
|
||||
"@rspack/core": "2.3.3",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
@@ -170,17 +170,17 @@
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "7.0.87",
|
||||
"@typescript/native": "npm:[email protected]",
|
||||
"@vitest/coverage-v8": "5.1.0",
|
||||
"@vitest/coverage-v8": "5.1.1",
|
||||
"babel-loader": "10.1.1",
|
||||
"babel-plugin-polyfill-corejs3": "1.0.0",
|
||||
"browserslist": "4.29.5",
|
||||
"browserslist": "4.29.6",
|
||||
"browserslist-useragent-regexp": "4.1.4",
|
||||
"core-js-compat": "3.51.0",
|
||||
"del": "9.0.1",
|
||||
"eslint": "10.14.0",
|
||||
"eslint": "10.15.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.18.0",
|
||||
"eslint-plugin-import-x": "4.18.1",
|
||||
"eslint-plugin-lit": "2.3.1",
|
||||
"eslint-plugin-lit-a11y": "5.1.3",
|
||||
"eslint-plugin-unused-imports": "4.4.1",
|
||||
@@ -188,42 +188,42 @@
|
||||
"fancy-log": "2.0.0",
|
||||
"fs-extra": "11.4.1",
|
||||
"generate-license-file": "4.2.5",
|
||||
"glob": "14.0.4",
|
||||
"glob": "14.0.6",
|
||||
"globals": "17.14.0",
|
||||
"gulp": "5.0.1",
|
||||
"gulp-json-transform": "0.5.0",
|
||||
"gulp-rename": "2.1.0",
|
||||
"html-minifier-terser": "7.2.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "31.0.0",
|
||||
"jsdom": "31.0.1",
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
"lint-staged": "17.6.0",
|
||||
"lint-staged": "17.6.1",
|
||||
"lit-analyzer": "2.0.3",
|
||||
"lodash.merge": "4.6.2",
|
||||
"lodash.template": "4.18.1",
|
||||
"map-stream": "0.0.7",
|
||||
"minify-literals": "2.2.0",
|
||||
"pinst": "3.0.0",
|
||||
"prettier": "3.9.10",
|
||||
"prettier": "3.10.1",
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.7",
|
||||
"serve": "14.2.8",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "7.5.22",
|
||||
"tar": "7.5.23",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.72.1",
|
||||
"vite": "8.3.6",
|
||||
"typescript-eslint": "8.73.0",
|
||||
"vite": "8.3.8",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.1.0",
|
||||
"vitest": "5.1.1",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "[email protected]8.0",
|
||||
"packageManager": "pnpm@12.21.0",
|
||||
"volta": {
|
||||
"node": "24.22.2"
|
||||
"node": "24.22.3"
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@custom-elements-manifest/analyzer": "0.11.0",
|
||||
"@rslib/core": "1.0.6",
|
||||
"@rslib/core": "1.0.7",
|
||||
"lit": "3.3.3",
|
||||
"typescript": "6.0.3"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { define } from "../../utils/registration/define";
|
||||
import { HacSpinner } from "./hac-spinner";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
// Registers <hac-spinner> in the global registry, as used by Home Assistant
|
||||
define(TAG_NAME, HacSpinner);
|
||||
|
||||
export { HacSpinner };
|
||||
@@ -0,0 +1,219 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { property } from "lit/decorators.js";
|
||||
|
||||
/**
|
||||
* @element hac-spinner
|
||||
*
|
||||
* @summary
|
||||
* Circular progress indicator for a task of unknown duration. Exposed to
|
||||
* assistive technology as an indeterminate `progressbar`.
|
||||
*
|
||||
* Set `aria-hidden="true"` when the spinner only decorates text that already
|
||||
* says what is in progress. It is passed on to the progressbar, because in
|
||||
* Chromium the host's `aria-hidden` alone doesn't keep the label out of a
|
||||
* parent's name.
|
||||
*
|
||||
* @csspart spinner - The `svg` element.
|
||||
* @csspart base - Same as `spinner`, kept for styles written for `ha-spinner`.
|
||||
* Temporary, like the legacy variables.
|
||||
*
|
||||
* @cssprop --hac-spinner-size - Diameter of the spinner. Overrides `size`.
|
||||
* @cssprop --hac-spinner-indicator-color - Color of the moving arc.
|
||||
* @cssprop --hac-spinner-track-color - Color of the track.
|
||||
* @cssprop --hac-spinner-track-width - Stroke width of the track and arc.
|
||||
*/
|
||||
export class HacSpinner extends LitElement {
|
||||
/** Preset diameter: 16, 28, 48 or 68 pixels. Defaults to 48 pixels. */
|
||||
@property({ reflect: true }) public size?:
|
||||
"tiny" | "small" | "medium" | "large";
|
||||
|
||||
/**
|
||||
* Accessible name. Name what is in progress, like "Installing update",
|
||||
* rather than its state. Defaults to "Loading".
|
||||
*/
|
||||
@property({ attribute: "accessible-label" })
|
||||
public accessibleLabel?: string;
|
||||
|
||||
/** Name used without `accessibleLabel`. Subclasses can translate it. */
|
||||
protected defaultLabel(): string {
|
||||
return "Loading";
|
||||
}
|
||||
|
||||
static get observedAttributes() {
|
||||
return [...super.observedAttributes, "aria-hidden"];
|
||||
}
|
||||
|
||||
public attributeChangedCallback(
|
||||
name: string,
|
||||
oldValue: string | null,
|
||||
newValue: string | null
|
||||
) {
|
||||
super.attributeChangedCallback(name, oldValue, newValue);
|
||||
if (name === "aria-hidden") {
|
||||
this.requestUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<svg
|
||||
part="spinner base"
|
||||
role="progressbar"
|
||||
aria-label=${this.accessibleLabel || this.defaultLabel()}
|
||||
aria-hidden=${this.getAttribute("aria-hidden") ?? nothing}
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<circle class="track" />
|
||||
<circle class="indicator" />
|
||||
</svg>
|
||||
`;
|
||||
}
|
||||
|
||||
/*
|
||||
* Fallback order: --hac-spinner-*, then the variables of ha-spinner
|
||||
* (--ha-spinner-*, --primary-color, --divider-color) so existing themes and
|
||||
* callers keep working, then the semantic tokens and their light values for
|
||||
* use outside Home Assistant. A size preset wins over --ha-spinner-size, as
|
||||
* it did in ha-spinner.
|
||||
*
|
||||
* --indicator-color, --track-color, --track-width and --speed are the
|
||||
* variables ha-spinner inherited from wa-spinner. They are set on the host
|
||||
* like they were there, so a rule on the element still overrides them but a
|
||||
* value from an ancestor doesn't leak in.
|
||||
*
|
||||
* The ha-spinner and wa-spinner variables are temporary, see "Theming" in
|
||||
* the README.
|
||||
*/
|
||||
static styles = css`
|
||||
:host {
|
||||
--indicator-color: var(
|
||||
--ha-spinner-indicator-color,
|
||||
var(--primary-color, var(--ha-color-fill-primary-loud-resting, #009ac7))
|
||||
);
|
||||
--track-color: var(
|
||||
--ha-spinner-divider-color,
|
||||
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
|
||||
);
|
||||
--track-width: 4px;
|
||||
--speed: 3.5s;
|
||||
--_size: var(
|
||||
--hac-spinner-size,
|
||||
var(--_preset-size, var(--ha-spinner-size, 48px))
|
||||
);
|
||||
box-sizing: border-box;
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
width: var(--_size);
|
||||
height: var(--_size);
|
||||
}
|
||||
|
||||
:host([hidden]) {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:host([size="tiny"]) {
|
||||
--_preset-size: 16px;
|
||||
}
|
||||
|
||||
:host([size="small"]) {
|
||||
--_preset-size: 28px;
|
||||
}
|
||||
|
||||
:host([size="medium"]) {
|
||||
--_preset-size: 48px;
|
||||
}
|
||||
|
||||
:host([size="large"]) {
|
||||
--_preset-size: 68px;
|
||||
}
|
||||
|
||||
svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
aspect-ratio: 1;
|
||||
animation: spin var(--speed) linear infinite;
|
||||
}
|
||||
|
||||
.track,
|
||||
.indicator {
|
||||
--_width: var(--hac-spinner-track-width, var(--track-width));
|
||||
--_radius: calc(var(--_size) / 2 - var(--_width) / 2);
|
||||
--_circumference: calc(var(--_radius) * 2 * 3.141592654);
|
||||
cx: calc(var(--_size) / 2);
|
||||
cy: calc(var(--_size) / 2);
|
||||
r: var(--_radius);
|
||||
fill: none;
|
||||
stroke-width: var(--_width);
|
||||
}
|
||||
|
||||
.track {
|
||||
stroke: var(--hac-spinner-track-color, var(--track-color));
|
||||
}
|
||||
|
||||
.indicator {
|
||||
stroke: var(--hac-spinner-indicator-color, var(--indicator-color));
|
||||
stroke-linecap: round;
|
||||
stroke-dasharray:
|
||||
calc(0.597 * var(--_circumference)), calc(0.796 * var(--_circumference));
|
||||
stroke-dashoffset: calc(-0.04 * var(--_circumference));
|
||||
animation: dash 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
svg,
|
||||
.indicator {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Keep the track and the arc apart in forced colors mode */
|
||||
@media (forced-colors: active) {
|
||||
svg {
|
||||
forced-color-adjust: none;
|
||||
}
|
||||
.track {
|
||||
stroke: GrayText;
|
||||
}
|
||||
.indicator {
|
||||
stroke: CanvasText;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes dash {
|
||||
0% {
|
||||
stroke-dasharray:
|
||||
calc(0.008 * var(--_circumference)),
|
||||
calc(1.194 * var(--_circumference));
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
50% {
|
||||
stroke-dasharray:
|
||||
calc(0.716 * var(--_circumference)),
|
||||
calc(1.194 * var(--_circumference));
|
||||
stroke-dashoffset: calc(-0.278 * var(--_circumference));
|
||||
}
|
||||
100% {
|
||||
stroke-dasharray:
|
||||
calc(0.716 * var(--_circumference)),
|
||||
calc(1.194 * var(--_circumference));
|
||||
stroke-dashoffset: calc(-0.987 * var(--_circumference));
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hac-spinner": HacSpinner;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Tag name of the element. */
|
||||
export const TAG_NAME = "hac-spinner";
|
||||
|
||||
/** Version of <hac-spinner>. */
|
||||
export const VERSION = "0.1.0";
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ElementDefinition } from "../../utils/registration/definition";
|
||||
import { HacSpinner } from "./hac-spinner";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
export { HacSpinner };
|
||||
|
||||
/**
|
||||
* The bundled <hac-spinner> for a scoped registry:
|
||||
* `ScopedElementsMixin(LitElement, [hacSpinner])` or
|
||||
* `createScopedElementRegistry([hacSpinner])`.
|
||||
*/
|
||||
export const hacSpinner: ElementDefinition<typeof HacSpinner> = {
|
||||
tagName: TAG_NAME,
|
||||
element: HacSpinner,
|
||||
};
|
||||
Generated
+1238
-1198
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 6.0 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 6.7 KiB |
+1
-1
@@ -14,7 +14,7 @@
|
||||
"minimumReleaseAge": "3 days",
|
||||
"postUpdateOptions": ["pnpmDedupe"],
|
||||
"constraints": {
|
||||
"ghActionsLock": "v0.4.1"
|
||||
"ghActionsLock": "v0.5.1"
|
||||
},
|
||||
"lockFileMaintenance": {
|
||||
"description": ["Run after patch releases but before next beta"],
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
interface EntityWithColorTemp {
|
||||
attributes?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const finiteRange = (
|
||||
min: unknown,
|
||||
max: unknown
|
||||
): { min: number; max: number } | undefined => {
|
||||
if (typeof min !== "number" || typeof max !== "number") {
|
||||
return undefined;
|
||||
}
|
||||
if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
|
||||
return undefined;
|
||||
}
|
||||
return { min, max };
|
||||
};
|
||||
|
||||
/**
|
||||
* Kelvin bounds reported by the given entity states.
|
||||
*
|
||||
* Several lights use the overlap of their ranges, because one
|
||||
* `color_temp_kelvin` value is sent to every target. When the ranges do not
|
||||
* overlap, the result spans the widest range so it still has a valid min and
|
||||
* max. Entities without a finite range are ignored. Returns undefined when
|
||||
* nothing reports a range, so the caller keeps the selector min and max.
|
||||
*/
|
||||
export const kelvinRangeFromEntityStates = (
|
||||
states: Readonly<Record<string, EntityWithColorTemp | undefined>> | undefined
|
||||
): { min: number; max: number } | undefined => {
|
||||
if (!states) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ranges: { min: number; max: number }[] = [];
|
||||
for (const state of Object.values(states)) {
|
||||
const range = finiteRange(
|
||||
state?.attributes?.min_color_temp_kelvin,
|
||||
state?.attributes?.max_color_temp_kelvin
|
||||
);
|
||||
if (range) {
|
||||
ranges.push(range);
|
||||
}
|
||||
}
|
||||
if (!ranges.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let min = Math.max(...ranges.map((range) => range.min));
|
||||
let max = Math.min(...ranges.map((range) => range.max));
|
||||
if (min > max) {
|
||||
min = Math.min(...ranges.map((range) => range.min));
|
||||
max = Math.max(...ranges.map((range) => range.max));
|
||||
}
|
||||
return { min, max };
|
||||
};
|
||||
@@ -79,7 +79,7 @@ export const generateColorPalette = (
|
||||
}
|
||||
|
||||
return steps.map((step) => {
|
||||
const name = `ha-color-${label}-${step}`;
|
||||
const name = `ha-color-${label}-${String(step).padStart(2, "0")}`;
|
||||
|
||||
// Base color at 50%
|
||||
if (step === 50) {
|
||||
|
||||
@@ -6,15 +6,17 @@ const isConditionObject = (c: unknown): c is VisibilityCondition =>
|
||||
typeof c === "object" && c !== null;
|
||||
|
||||
/**
|
||||
* Drop entries that are not condition objects, at any depth. Returns the
|
||||
* same array when every entry is valid.
|
||||
* Drop entries that are not condition objects, at any depth. A single
|
||||
* condition mapping is wrapped in an array. Returns the same array when it
|
||||
* is an array and every entry is valid.
|
||||
*/
|
||||
export const dropInvalidConditions = (
|
||||
conditions: VisibilityCondition[]
|
||||
conditions: VisibilityCondition | VisibilityCondition[]
|
||||
): VisibilityCondition[] => {
|
||||
let changed = false;
|
||||
const list = ensureArray(conditions);
|
||||
let changed = list !== conditions;
|
||||
const valid: VisibilityCondition[] = [];
|
||||
for (const c of conditions) {
|
||||
for (const c of list) {
|
||||
if (!isConditionObject(c)) {
|
||||
changed = true;
|
||||
continue;
|
||||
@@ -30,5 +32,5 @@ export const dropInvalidConditions = (
|
||||
}
|
||||
valid.push(c);
|
||||
}
|
||||
return changed ? valid : conditions;
|
||||
return changed ? valid : list;
|
||||
};
|
||||
@@ -89,10 +89,19 @@ export class LegendFitController {
|
||||
|
||||
private _fit() {
|
||||
const list = this._element;
|
||||
const rowWidth = list?.getBoundingClientRect().width;
|
||||
if (!list || !rowWidth) {
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
const style = getComputedStyle(list);
|
||||
const rowWidth = parseFloat(style.width);
|
||||
// Bounding rects include transforms, such as a dialog scaling in, which
|
||||
// never resize the list, so measure in layout pixels
|
||||
const scale = list.getBoundingClientRect().width / rowWidth;
|
||||
if (!rowWidth || !scale) {
|
||||
return;
|
||||
}
|
||||
const layoutWidth = (element: Element) =>
|
||||
element.getBoundingClientRect().width / scale;
|
||||
const children = Array.from(list.children);
|
||||
const more = children.find((child) =>
|
||||
child.classList.contains("legend-more")
|
||||
@@ -107,9 +116,7 @@ export class LegendFitController {
|
||||
}
|
||||
this._more = more;
|
||||
}
|
||||
const widths = children
|
||||
.filter((child) => child !== more)
|
||||
.map((child) => child.getBoundingClientRect().width);
|
||||
const widths = children.filter((child) => child !== more).map(layoutWidth);
|
||||
// Values resize the items on every state update. Fitting each item at its
|
||||
// widest since the last resize keeps the more button from flickering.
|
||||
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
|
||||
@@ -122,9 +129,9 @@ export class LegendFitController {
|
||||
}
|
||||
const fit = fitInRows(
|
||||
this._widths,
|
||||
more?.getBoundingClientRect().width ?? 0,
|
||||
more ? layoutWidth(more) : 0,
|
||||
rowWidth,
|
||||
parseFloat(getComputedStyle(list).columnGap) || 0,
|
||||
parseFloat(style.columnGap) || 0,
|
||||
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
|
||||
);
|
||||
if (fit !== this.fit) {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { ThemeVars } from "../../data/ws-themes";
|
||||
import {
|
||||
getThemeVariables,
|
||||
themeDefinesColor,
|
||||
themeDefinesPrimaryPalette,
|
||||
} from "../../data/ws-themes";
|
||||
import { darkColorVariables } from "../../resources/theme/color";
|
||||
import { darkSemanticVariables } from "../../resources/theme/semantic.globals";
|
||||
import { derivedStyles } from "../../resources/theme/theme";
|
||||
@@ -10,9 +15,9 @@ import {
|
||||
rgb2hex,
|
||||
rgb2lab,
|
||||
} from "../color/convert-color";
|
||||
import { hexBlend } from "../color/hex";
|
||||
import { cssColorToHex, hexBlend } from "../color/hex";
|
||||
import { labBrighten, labDarken } from "../color/lab";
|
||||
import { generateColorPalette } from "../color/palette";
|
||||
import { generateColorPalette, normalizeLuminance } from "../color/palette";
|
||||
import { rgbContrast } from "../color/rgb";
|
||||
|
||||
interface ProcessedTheme {
|
||||
@@ -56,78 +61,56 @@ export const applyThemesOnElement = (
|
||||
themeRules = { ...darkSemanticVariables, ...darkColorVariables };
|
||||
}
|
||||
|
||||
if (themeToApply === "default") {
|
||||
// Determine the primary and accent colors from the current settings.
|
||||
// Fallbacks are implicitly the HA default blue and orange or the
|
||||
// derived "darkStyles" values, depending on the light vs dark mode.
|
||||
const primaryColor = themeSettings?.primaryColor;
|
||||
const accentColor = themeSettings?.accentColor;
|
||||
const isDefaultTheme = themeToApply === "default";
|
||||
const customTheme =
|
||||
themeToApply && !isDefaultTheme ? themes.themes[themeToApply] : undefined;
|
||||
const customThemeRules = customTheme
|
||||
? getThemeVariables(customTheme, darkMode)
|
||||
: undefined;
|
||||
|
||||
if (darkMode && primaryColor) {
|
||||
themeRules["app-header-background-color"] = hexBlend(
|
||||
primaryColor,
|
||||
"#121212",
|
||||
8
|
||||
);
|
||||
}
|
||||
const primaryColor =
|
||||
isDefaultTheme ||
|
||||
(customThemeRules && !themeDefinesColor(customThemeRules, "primary"))
|
||||
? themeSettings?.primaryColor
|
||||
: undefined;
|
||||
const accentColor =
|
||||
isDefaultTheme ||
|
||||
(customThemeRules && !themeDefinesColor(customThemeRules, "accent"))
|
||||
? themeSettings?.accentColor
|
||||
: undefined;
|
||||
|
||||
if (primaryColor) {
|
||||
cacheKey = `${cacheKey}__primary_${primaryColor}`;
|
||||
const rgbPrimaryColor = hex2rgb(primaryColor);
|
||||
const labPrimaryColor = rgb2lab(rgbPrimaryColor);
|
||||
themeRules["primary-color"] = primaryColor;
|
||||
const rgbLightPrimaryColor = lab2rgb(labBrighten(labPrimaryColor));
|
||||
if (primaryColor) {
|
||||
cacheKey = `${cacheKey}__primary_${primaryColor}`;
|
||||
}
|
||||
if (accentColor) {
|
||||
cacheKey = `${cacheKey}__accent_${accentColor}`;
|
||||
}
|
||||
themeRules = {
|
||||
...themeRules,
|
||||
...getUserColorRules(primaryColor, accentColor, isDefaultTheme && darkMode),
|
||||
};
|
||||
|
||||
generateColorPalette(primaryColor, "primary").forEach(([key, color]) => {
|
||||
themeRules[key] = color;
|
||||
});
|
||||
|
||||
themeRules["light-primary-color"] = rgb2hex(rgbLightPrimaryColor);
|
||||
themeRules["dark-primary-color"] = lab2hex(labDarken(labPrimaryColor));
|
||||
themeRules["darker-primary-color"] = lab2hex(
|
||||
labDarken(labPrimaryColor, 2)
|
||||
);
|
||||
themeRules["text-primary-color"] =
|
||||
rgbContrast(rgbPrimaryColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
themeRules["text-light-primary-color"] =
|
||||
rgbContrast(rgbLightPrimaryColor, [33, 33, 33]) < 6
|
||||
? "#fff"
|
||||
: "#212121";
|
||||
themeRules["state-icon-color"] = themeRules["dark-primary-color"];
|
||||
}
|
||||
if (accentColor) {
|
||||
cacheKey = `${cacheKey}__accent_${accentColor}`;
|
||||
themeRules["accent-color"] = accentColor;
|
||||
const rgbAccentColor = hex2rgb(accentColor);
|
||||
themeRules["text-accent-color"] =
|
||||
rgbContrast(rgbAccentColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
}
|
||||
|
||||
// Nothing was changed
|
||||
if (element.__themes?.cacheKey === cacheKey) {
|
||||
return;
|
||||
}
|
||||
// Nothing was changed
|
||||
if (isDefaultTheme && element.__themes?.cacheKey === cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Custom theme logic (not relevant for default theme, since it would override
|
||||
// the derived calculations from above)
|
||||
if (
|
||||
themeToApply &&
|
||||
themeToApply !== "default" &&
|
||||
themes.themes[themeToApply]
|
||||
) {
|
||||
// Apply theme vars that are relevant for all modes (but extract the "modes" section first)
|
||||
const { modes, ...baseThemeRules } = themes.themes[themeToApply];
|
||||
themeRules = { ...themeRules, ...baseThemeRules };
|
||||
// Unparseable colors like `var(--x)` are skipped.
|
||||
const themePrimaryColor =
|
||||
customThemeRules?.["primary-color"] &&
|
||||
!themeDefinesPrimaryPalette(customThemeRules)
|
||||
? cssColorToHex(customThemeRules["primary-color"])
|
||||
: undefined;
|
||||
if (themePrimaryColor) {
|
||||
// Older themes often use a near black primary color for the header.
|
||||
themeRules = {
|
||||
...themeRules,
|
||||
...getPrimaryPaletteRules(normalizeLuminance(themePrimaryColor)),
|
||||
};
|
||||
}
|
||||
|
||||
// Apply theme vars for the specific mode if available
|
||||
if (modes) {
|
||||
if (darkMode) {
|
||||
themeRules = { ...themeRules, ...modes.dark };
|
||||
} else {
|
||||
themeRules = { ...themeRules, ...modes.light };
|
||||
}
|
||||
}
|
||||
if (customThemeRules) {
|
||||
themeRules = { ...themeRules, ...customThemeRules };
|
||||
}
|
||||
|
||||
if (!element.__themes?.keys && !Object.keys(themeRules).length) {
|
||||
@@ -154,6 +137,57 @@ export const applyThemesOnElement = (
|
||||
}
|
||||
};
|
||||
|
||||
const getPrimaryPaletteRules = (primaryColor: string): Partial<ThemeVars> => {
|
||||
const rules: Partial<ThemeVars> = {};
|
||||
const labPrimaryColor = rgb2lab(hex2rgb(primaryColor));
|
||||
|
||||
generateColorPalette(primaryColor, "primary").forEach(([key, color]) => {
|
||||
rules[key] = color;
|
||||
});
|
||||
|
||||
rules["light-primary-color"] = rgb2hex(lab2rgb(labBrighten(labPrimaryColor)));
|
||||
rules["dark-primary-color"] = lab2hex(labDarken(labPrimaryColor));
|
||||
rules["darker-primary-color"] = lab2hex(labDarken(labPrimaryColor, 2));
|
||||
return rules;
|
||||
};
|
||||
|
||||
const getUserColorRules = (
|
||||
primaryColor: string | undefined,
|
||||
accentColor: string | undefined,
|
||||
tintHeader: boolean
|
||||
): Partial<ThemeVars> => {
|
||||
const rules: Partial<ThemeVars> = {};
|
||||
|
||||
if (primaryColor) {
|
||||
if (tintHeader) {
|
||||
rules["app-header-background-color"] = hexBlend(
|
||||
primaryColor,
|
||||
"#121212",
|
||||
8
|
||||
);
|
||||
}
|
||||
|
||||
Object.assign(rules, getPrimaryPaletteRules(primaryColor));
|
||||
rules["primary-color"] = primaryColor;
|
||||
rules["text-primary-color"] =
|
||||
rgbContrast(hex2rgb(primaryColor), [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
rules["text-light-primary-color"] =
|
||||
rgbContrast(hex2rgb(rules["light-primary-color"]!), [33, 33, 33]) < 6
|
||||
? "#fff"
|
||||
: "#212121";
|
||||
rules["state-icon-color"] = rules["dark-primary-color"];
|
||||
}
|
||||
|
||||
if (accentColor) {
|
||||
rules["accent-color"] = accentColor;
|
||||
const rgbAccentColor = hex2rgb(accentColor);
|
||||
rules["text-accent-color"] =
|
||||
rgbContrast(rgbAccentColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
}
|
||||
|
||||
return rules;
|
||||
};
|
||||
|
||||
const processTheme = (
|
||||
cacheKey: string,
|
||||
theme: Partial<ThemeVars>
|
||||
|
||||
@@ -3,6 +3,7 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
|
||||
"ha-slider",
|
||||
"ha-control-switch",
|
||||
"ha-control-circular-slider",
|
||||
"ha-state-control-cover",
|
||||
"ha-hs-color-picker",
|
||||
"ha-map",
|
||||
// Charts pan and pinch-zoom on touch
|
||||
@@ -11,7 +12,12 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
|
||||
"ha-filter-chip",
|
||||
]);
|
||||
|
||||
const SWIPE_LOCKED_CLASSES = new Set(["volume-slider-container", "forecast"]);
|
||||
const SWIPE_LOCKED_CLASSES = new Set([
|
||||
"volume-slider-container",
|
||||
"forecast",
|
||||
// A zoomed in camera picture pans on touch
|
||||
"camera-player-zoomed",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Whether a touch inside a bottom sheet belongs to its content rather than to
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Some WebViews become visible after thawing without dispatching visibilitychange,
|
||||
// resume, or focus. Check visibility while waiting so reconnects cannot stay blocked.
|
||||
export const whenDocumentVisible = (callback: () => void): (() => void) => {
|
||||
const check = () => {
|
||||
if (!document.hidden) {
|
||||
cancel();
|
||||
callback();
|
||||
}
|
||||
};
|
||||
const interval = window.setInterval(check, 1000);
|
||||
const cancel = () => {
|
||||
window.clearInterval(interval);
|
||||
document.removeEventListener("visibilitychange", check);
|
||||
document.removeEventListener("resume", check);
|
||||
window.removeEventListener("focus", check);
|
||||
};
|
||||
document.addEventListener("visibilitychange", check);
|
||||
document.addEventListener("resume", check);
|
||||
window.addEventListener("focus", check);
|
||||
return cancel;
|
||||
};
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
TEMPERATURE_ATTRIBUTES,
|
||||
} from "../../data/entity/entity_attributes";
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
import { computeGroupMemberEntries } from "../../data/group";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { TimeZone } from "../../data/translation";
|
||||
import type { WeatherEntity } from "../../data/weather";
|
||||
@@ -182,6 +183,13 @@ export const computeAttributeValueToParts = (
|
||||
localize(
|
||||
`component.${registryEntry.platform}.entity.${domain}.${translationKey}.state_attributes.${attribute}.state.${attributeValue}`
|
||||
)) ||
|
||||
computeMemberAttributeValueDisplay(
|
||||
localize,
|
||||
stateObj,
|
||||
entities,
|
||||
attribute,
|
||||
attributeValue
|
||||
) ||
|
||||
(deviceClass &&
|
||||
localize(
|
||||
`component.${domain}.entity_component.${deviceClass}.state_attributes.${attribute}.state.${attributeValue}`
|
||||
@@ -193,6 +201,27 @@ export const computeAttributeValueToParts = (
|
||||
return [{ type: "value", value: formattedValue }];
|
||||
};
|
||||
|
||||
// A group has no translations for the values of its members, for example the
|
||||
// effects of a light group, so use the translation of a member.
|
||||
const computeMemberAttributeValueDisplay = (
|
||||
localize: LocalizeFunc,
|
||||
stateObj: HassEntity,
|
||||
entities: HomeAssistant["entities"],
|
||||
attribute: string,
|
||||
attributeValue: string
|
||||
): string | undefined => {
|
||||
const domain = computeStateDomain(stateObj);
|
||||
for (const member of computeGroupMemberEntries(stateObj, entities)) {
|
||||
const translation = localize(
|
||||
`component.${member.platform}.entity.${domain}.${member.translation_key}.state_attributes.${attribute}.state.${attributeValue}`
|
||||
);
|
||||
if (translation) {
|
||||
return translation;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const computeAttributeNameDisplay = (
|
||||
localize: LocalizeFunc,
|
||||
stateObj: HassEntity,
|
||||
|
||||
@@ -4,16 +4,23 @@ import {
|
||||
mdiArrowDown,
|
||||
mdiArrowExpandHorizontal,
|
||||
mdiArrowUp,
|
||||
mdiDoorClosed,
|
||||
mdiDoorOpen,
|
||||
mdiGate,
|
||||
mdiGateOpen,
|
||||
} from "@mdi/js";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
|
||||
export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorOpen;
|
||||
case "gate":
|
||||
return mdiGateOpen;
|
||||
case "curtain":
|
||||
return mdiArrowExpandHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowDown;
|
||||
default:
|
||||
return mdiArrowUp;
|
||||
}
|
||||
@@ -21,11 +28,14 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
|
||||
export const computeCloseIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorClosed;
|
||||
case "gate":
|
||||
return mdiGate;
|
||||
case "curtain":
|
||||
return mdiArrowCollapseHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowUp;
|
||||
default:
|
||||
return mdiArrowDown;
|
||||
}
|
||||
|
||||
@@ -163,21 +163,9 @@ export const findEntities = (
|
||||
return results;
|
||||
};
|
||||
|
||||
export const excludeEntities = (
|
||||
entityIds: string[],
|
||||
excludedEntityIds?: string[]
|
||||
): string[] => {
|
||||
if (!excludedEntityIds?.length) {
|
||||
return entityIds;
|
||||
}
|
||||
const excluded = new Set(excludedEntityIds);
|
||||
return entityIds.filter((entityId) => !excluded.has(entityId));
|
||||
};
|
||||
|
||||
export const findFilteredEntities = (
|
||||
sources: EntityFilterSources,
|
||||
filters: EntityFilter[],
|
||||
excludedEntityIds?: string[]
|
||||
filters: EntityFilter[]
|
||||
): string[] => {
|
||||
const filterFuncs = filters.map((filter) =>
|
||||
generateEntityFilter(
|
||||
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
|
||||
filter
|
||||
)
|
||||
);
|
||||
return excludeEntities(
|
||||
findEntities(Object.keys(sources.states), filterFuncs),
|
||||
excludedEntityIds
|
||||
);
|
||||
return findEntities(Object.keys(sources.states), filterFuncs);
|
||||
};
|
||||
@@ -161,6 +161,9 @@ export const getNumberFormatOptions = (
|
||||
return undefined;
|
||||
};
|
||||
|
||||
// Intl.NumberFormat throws a RangeError for more fraction digits than this.
|
||||
const MAX_FRACTION_DIGITS = 100;
|
||||
|
||||
/**
|
||||
* Generates default options for Intl.NumberFormat
|
||||
* @param num The number to be formatted
|
||||
@@ -185,7 +188,10 @@ export const getDefaultFormatOptions = (
|
||||
(options.minimumFractionDigits === undefined &&
|
||||
options.maximumFractionDigits === undefined)
|
||||
) {
|
||||
const digits = num.indexOf(".") > -1 ? num.split(".")[1].length : 0;
|
||||
const digits = Math.min(
|
||||
num.indexOf(".") > -1 ? num.split(".")[1].length : 0,
|
||||
MAX_FRACTION_DIGITS
|
||||
);
|
||||
defaultOptions.minimumFractionDigits = digits;
|
||||
defaultOptions.maximumFractionDigits = digits;
|
||||
}
|
||||
|
||||
@@ -1,2 +1,10 @@
|
||||
export const capitalizeFirstLetter = (str: string) =>
|
||||
str.charAt(0).toUpperCase() + str.slice(1);
|
||||
export const capitalizeFirstLetter = (str: string) => {
|
||||
// Take the first code point, not code unit, so letters outside the BMP
|
||||
// (stored as a surrogate pair) are uppercased too.
|
||||
const first = str.codePointAt(0);
|
||||
if (first === undefined) {
|
||||
return str;
|
||||
}
|
||||
const firstLetter = String.fromCodePoint(first);
|
||||
return firstLetter.toUpperCase() + str.slice(firstLetter.length);
|
||||
};
|
||||
@@ -1,11 +1,27 @@
|
||||
// Unanchored regex fragments, shared as the single source of truth for both
|
||||
// the boolean validators below and the HTML `pattern` attribute (the browser
|
||||
// anchors a pattern as `^(?:…)$`).
|
||||
const IPV4 =
|
||||
"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
|
||||
|
||||
const IPV6 =
|
||||
"(?:([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))";
|
||||
// Decimal octet 0-255 without leading zeros.
|
||||
const DEC_OCTET = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])";
|
||||
|
||||
const IPV4 = `(?:${DEC_OCTET}\\.){3}${DEC_OCTET}`;
|
||||
|
||||
// IPv6 grammar from RFC 3986, section 3.2.2.
|
||||
const H16 = "[0-9a-fA-F]{1,4}";
|
||||
const LS32 = `(?:${H16}:${H16}|${IPV4})`;
|
||||
|
||||
const IPV6 = `(?:${[
|
||||
`(?:${H16}:){6}${LS32}`,
|
||||
`::(?:${H16}:){5}${LS32}`,
|
||||
`(?:${H16})?::(?:${H16}:){4}${LS32}`,
|
||||
`(?:(?:${H16}:){0,1}${H16})?::(?:${H16}:){3}${LS32}`,
|
||||
`(?:(?:${H16}:){0,2}${H16})?::(?:${H16}:){2}${LS32}`,
|
||||
`(?:(?:${H16}:){0,3}${H16})?::${H16}:${LS32}`,
|
||||
`(?:(?:${H16}:){0,4}${H16})?::${LS32}`,
|
||||
`(?:(?:${H16}:){0,5}${H16})?::${H16}`,
|
||||
`(?:(?:${H16}:){0,6}${H16})?::`,
|
||||
].join("|")})`;
|
||||
|
||||
// CIDR prefix lengths: 0-32 for IPv4, 0-128 for IPv6.
|
||||
const IPV4_PREFIX = "(?:3[0-2]|[12]?[0-9])";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1
|
||||
export const slugify = (value: string, delimiter = "_") => {
|
||||
const a =
|
||||
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧхîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
|
||||
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghhiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
|
||||
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
|
||||
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
|
||||
const p = new RegExp(a.split("").join("|"), "g");
|
||||
const complex_cyrillic = {
|
||||
ж: "zh",
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { HTMLTemplateResult } from "lit";
|
||||
import { polyfillLocaleData } from "../../resources/polyfills/locale-data-polyfill";
|
||||
import type { Resources, TranslationDict } from "../../types";
|
||||
import { fireEvent } from "../dom/fire_event";
|
||||
import { NAME_PLACEHOLDERS } from "./name-placeholders";
|
||||
|
||||
// Exclude some patterns from key type checking for now
|
||||
// These are intended to be removed as errors are fixed
|
||||
@@ -140,7 +141,10 @@ export const computeLocalize = async <Keys extends string = LocalizeKeys>(
|
||||
}
|
||||
|
||||
try {
|
||||
return translatedMessage.format<string>(argObject) as string;
|
||||
return translatedMessage.format<string>({
|
||||
...NAME_PLACEHOLDERS,
|
||||
...argObject,
|
||||
}) as string;
|
||||
} catch (err: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("Translation error", key, language, err);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export const MARKETPLACE_NAME = "Marketplace";
|
||||
|
||||
export const NAME_PLACEHOLDERS = {
|
||||
marketplace: MARKETPLACE_NAME,
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import {
|
||||
createQueryString,
|
||||
type QueryParamConfig,
|
||||
type QueryParamValues,
|
||||
} from "./query-params";
|
||||
|
||||
export const energyEditorQueryParamConfig = {
|
||||
string: ["stat_energy_from", "stat_energy_to", "stat_consumption"],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type EnergyEditorQueryParams = QueryParamValues<
|
||||
typeof energyEditorQueryParamConfig
|
||||
>;
|
||||
|
||||
export const createEnergyEditorQueryString = (
|
||||
values: EnergyEditorQueryParams
|
||||
): string => createQueryString(values, energyEditorQueryParamConfig);
|
||||
@@ -82,7 +82,11 @@ export function decodeQueryParams(
|
||||
for (const key of config.date ?? []) {
|
||||
const value = getSearchParam(searchParams, key);
|
||||
if (value) {
|
||||
params[key] = new Date(value);
|
||||
const date = new Date(value);
|
||||
// Leave out dates that can't be parsed, like a missing value.
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
params[key] = date;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const { key, trueValue } of config.boolean ?? []) {
|
||||
|
||||
@@ -37,6 +37,7 @@ export const debounce = <T extends any[]>(
|
||||
|
||||
debouncedFunc.cancel = () => {
|
||||
clearTimeout(timeout);
|
||||
timeout = undefined;
|
||||
trailingArgs = undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -2,14 +2,17 @@ export const groupBy = <T>(
|
||||
list: T[],
|
||||
keySelector: (item: T) => string
|
||||
): Record<string, T[]> => {
|
||||
const result = {};
|
||||
// Group in a Map so keys like `constructor` or `__proto__` don't collide
|
||||
// with Object.prototype.
|
||||
const groups = new Map<string, T[]>();
|
||||
for (const item of list) {
|
||||
const key = keySelector(item);
|
||||
if (key in result) {
|
||||
result[key].push(item);
|
||||
const group = groups.get(key);
|
||||
if (group) {
|
||||
group.push(item);
|
||||
} else {
|
||||
result[key] = [item];
|
||||
groups.set(key, [item]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return Object.fromEntries(groups);
|
||||
};
|
||||
@@ -11,7 +11,8 @@
|
||||
* parseAnimationDuration("invalid") // Returns 0
|
||||
*/
|
||||
export const parseAnimationDuration = (duration: string): number => {
|
||||
const trimmed = duration.trim();
|
||||
// CSS units are case-insensitive, e.g. "3S" is the same as "3s".
|
||||
const trimmed = duration.trim().toLowerCase();
|
||||
|
||||
let value: number;
|
||||
let multiplier: number;
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78
|
||||
// Ignore everything else
|
||||
const parseOrThrow = (num) => {
|
||||
const parsed = parseFloat(num);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`${num} is not a number`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78 and 23%
|
||||
// Return null for everything else
|
||||
const NUMBER = String.raw`(\d+(?:\.\d*)?|\.\d+)`;
|
||||
const RATIO_REGEX = new RegExp(
|
||||
String.raw`^\s*${NUMBER}\s*(?:[x:]\s*${NUMBER}\s*)?$`
|
||||
);
|
||||
const PERCENTAGE_REGEX = new RegExp(String.raw`^\s*${NUMBER}\s*%\s*$`);
|
||||
|
||||
export default function parseAspectRatio(input: string) {
|
||||
if (!input) {
|
||||
// YAML loads an unquoted 16:9 as the base-60 number 969, so skip non-strings
|
||||
if (!input || typeof input !== "string") {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (input.endsWith("%")) {
|
||||
return { w: 100, h: parseOrThrow(input.slice(0, -1)) };
|
||||
}
|
||||
|
||||
const arr = input.replace(":", "x").split("x");
|
||||
if (arr.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return arr.length === 1
|
||||
? { w: parseOrThrow(arr[0]), h: 1 }
|
||||
: { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[1]) };
|
||||
} catch (_err: any) {
|
||||
// Ignore the error
|
||||
const percentage = PERCENTAGE_REGEX.exec(input);
|
||||
if (percentage) {
|
||||
return { w: 100, h: parseFloat(percentage[1]) };
|
||||
}
|
||||
|
||||
const ratio = RATIO_REGEX.exec(input);
|
||||
if (ratio) {
|
||||
return {
|
||||
w: parseFloat(ratio[1]),
|
||||
h: ratio[2] === undefined ? 1 : parseFloat(ratio[2]),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
// as much as it can, without ever going more than once per `wait` duration;
|
||||
// but if you'd like to disable the execution on the leading edge, pass
|
||||
// `false for leading`. To disable execution on the trailing edge, ditto.
|
||||
// The trailing call uses the arguments of the latest call.
|
||||
export const throttle = <T extends any[]>(
|
||||
func: (...args: T) => void,
|
||||
wait: number,
|
||||
@@ -13,12 +14,17 @@ export const throttle = <T extends any[]>(
|
||||
) => {
|
||||
let timeout: number | undefined;
|
||||
let previous = 0;
|
||||
const throttledFunc = (...args: T): void => {
|
||||
const later = () => {
|
||||
previous = leading === false ? 0 : Date.now();
|
||||
timeout = undefined;
|
||||
let pendingArgs: T | undefined;
|
||||
const later = () => {
|
||||
previous = leading === false ? 0 : Date.now();
|
||||
timeout = undefined;
|
||||
const args = pendingArgs;
|
||||
pendingArgs = undefined;
|
||||
if (args) {
|
||||
func(...args);
|
||||
};
|
||||
}
|
||||
};
|
||||
const throttledFunc = (...args: T): void => {
|
||||
const now = Date.now();
|
||||
if (!previous && leading === false) {
|
||||
previous = now;
|
||||
@@ -30,15 +36,20 @@ export const throttle = <T extends any[]>(
|
||||
timeout = undefined;
|
||||
}
|
||||
previous = now;
|
||||
pendingArgs = undefined;
|
||||
func(...args);
|
||||
} else if (!timeout && trailing !== false) {
|
||||
timeout = window.setTimeout(later, remaining);
|
||||
} else if (trailing !== false) {
|
||||
pendingArgs = args;
|
||||
if (!timeout) {
|
||||
timeout = window.setTimeout(later, remaining);
|
||||
}
|
||||
}
|
||||
};
|
||||
throttledFunc.cancel = () => {
|
||||
clearTimeout(timeout);
|
||||
timeout = undefined;
|
||||
previous = 0;
|
||||
pendingArgs = undefined;
|
||||
};
|
||||
return throttledFunc;
|
||||
};
|
||||
@@ -1,12 +1,18 @@
|
||||
import { mdiChevronUp } from "@mdi/js";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import "../ha-icon-button";
|
||||
|
||||
@customElement("ha-automation-row")
|
||||
export class HaAutomationRow extends LitElement {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: "left-chevron", type: Boolean })
|
||||
public leftChevron = false;
|
||||
|
||||
@@ -77,6 +83,9 @@ export class HaAutomationRow extends LitElement {
|
||||
<ha-icon-button
|
||||
class="expand-button"
|
||||
.path=${mdiChevronUp}
|
||||
.label=${this._localize(
|
||||
this.collapsed ? "ui.common.expand" : "ui.common.collapse"
|
||||
)}
|
||||
@click=${this._handleExpand}
|
||||
@keydown=${this._handleExpand}
|
||||
></ha-icon-button>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import type {
|
||||
CameraStreamStatus,
|
||||
CameraStreamType,
|
||||
} from "../../data/camera-streams";
|
||||
import "../ha-spinner";
|
||||
|
||||
/** Names of the protocols, the same in every language. */
|
||||
export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
|
||||
web_rtc: "WebRTC",
|
||||
hls: "HLS",
|
||||
mjpeg: "MJPEG",
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows over a camera stream how it is connected. A faster stream that still
|
||||
* connects in the background is shown next to the current one.
|
||||
*/
|
||||
@customElement("ha-camera-stream-badge")
|
||||
export class HaCameraStreamBadge extends LitElement {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: false }) public status?: CameraStreamStatus;
|
||||
|
||||
protected render() {
|
||||
const status = this.status;
|
||||
if (!status) {
|
||||
return nothing;
|
||||
}
|
||||
const connecting = status.connecting || !status.type;
|
||||
const label = connecting
|
||||
? this._localize("ui.components.camera-player.connecting")
|
||||
: CAMERA_STREAM_TYPE_NAMES[status.type!];
|
||||
|
||||
return html`
|
||||
<button
|
||||
type="button"
|
||||
aria-label=${this._ariaLabel(status)}
|
||||
class=${connecting ? "connecting" : "live"}
|
||||
>
|
||||
<span class="dot"></span>
|
||||
<span class="label">${label}</span>
|
||||
${
|
||||
status.upgrading
|
||||
? html`<span class="upgrading" aria-hidden="true">
|
||||
<ha-spinner></ha-spinner>
|
||||
${CAMERA_STREAM_TYPE_NAMES[status.upgrading]}
|
||||
</span>`
|
||||
: nothing
|
||||
}
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
private _ariaLabel(status: CameraStreamStatus): string {
|
||||
if (status.connecting || !status.type) {
|
||||
return this._localize(
|
||||
"ui.components.camera-player.stream_info_connecting"
|
||||
);
|
||||
}
|
||||
if (status.upgrading) {
|
||||
return this._localize(
|
||||
"ui.components.camera-player.stream_info_upgrading",
|
||||
{
|
||||
type: CAMERA_STREAM_TYPE_NAMES[status.type],
|
||||
upgrading: CAMERA_STREAM_TYPE_NAMES[status.upgrading],
|
||||
}
|
||||
);
|
||||
}
|
||||
return this._localize("ui.components.camera-player.stream_info", {
|
||||
type: CAMERA_STREAM_TYPE_NAMES[status.type],
|
||||
});
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
/* Readable on a dark and on a bright picture */
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
height: 28px;
|
||||
padding-inline: var(--ha-space-2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: var(--ha-border-radius-pill);
|
||||
background-color: rgba(0, 0, 0, 0.45);
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
color: var(--ha-color-white);
|
||||
font-family: inherit;
|
||||
font-size: var(--ha-font-size-s);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: var(--wa-focus-ring-style) var(--wa-focus-ring-width)
|
||||
var(--ha-color-white);
|
||||
outline-offset: var(--wa-focus-ring-offset);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
background-color: var(--ha-color-green-60);
|
||||
}
|
||||
|
||||
.connecting .dot {
|
||||
background-color: rgba(255, 255, 255, 0.8);
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.upgrading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
padding-inline-start: var(--ha-space-1);
|
||||
border-inline-start: 1px solid rgba(255, 255, 255, 0.3);
|
||||
opacity: 0.7;
|
||||
--ha-spinner-indicator-color: var(--ha-color-white);
|
||||
--ha-spinner-size: 10px;
|
||||
--ha-spinner-divider-color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.connecting .dot {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-camera-stream-badge": HaCameraStreamBadge;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Zoom and pan of content that fills a viewport, applied as
|
||||
* `translate(x, y) scale(scale)` with the transform origin at the top left.
|
||||
*/
|
||||
export interface ZoomPan {
|
||||
scale: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface ZoomPanSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const ZOOM_PAN_IDENTITY: ZoomPan = { scale: 1, x: 0, y: 0 };
|
||||
|
||||
export const MAX_ZOOM = 5;
|
||||
|
||||
export const isZoomed = (zoomPan: ZoomPan): boolean => zoomPan.scale > 1;
|
||||
|
||||
/** Keeps the scale in range and the content covering the whole viewport. */
|
||||
export const clampZoomPan = (
|
||||
{ scale, x, y }: ZoomPan,
|
||||
{ width, height }: ZoomPanSize,
|
||||
maxScale = MAX_ZOOM
|
||||
): ZoomPan => {
|
||||
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
|
||||
if (clampedScale === 1) {
|
||||
return ZOOM_PAN_IDENTITY;
|
||||
}
|
||||
const minX = width - width * clampedScale;
|
||||
const minY = height - height * clampedScale;
|
||||
return {
|
||||
scale: clampedScale,
|
||||
x: Math.min(0, Math.max(minX, x)),
|
||||
y: Math.min(0, Math.max(minY, y)),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Zooms to a new scale while the point under the cursor or between the
|
||||
* fingers stays where it is. The point is relative to the viewport.
|
||||
*/
|
||||
export const zoomAtPoint = (
|
||||
zoomPan: ZoomPan,
|
||||
scale: number,
|
||||
point: { x: number; y: number },
|
||||
size: ZoomPanSize,
|
||||
maxScale = MAX_ZOOM
|
||||
): ZoomPan => {
|
||||
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
|
||||
const ratio = clampedScale / zoomPan.scale;
|
||||
return clampZoomPan(
|
||||
{
|
||||
scale: clampedScale,
|
||||
x: point.x - (point.x - zoomPan.x) * ratio,
|
||||
y: point.y - (point.y - zoomPan.y) * ratio,
|
||||
},
|
||||
size,
|
||||
maxScale
|
||||
);
|
||||
};
|
||||
|
||||
export const panBy = (
|
||||
zoomPan: ZoomPan,
|
||||
dx: number,
|
||||
dy: number,
|
||||
size: ZoomPanSize,
|
||||
maxScale = MAX_ZOOM
|
||||
): ZoomPan =>
|
||||
clampZoomPan(
|
||||
{ ...zoomPan, x: zoomPan.x + dx, y: zoomPan.y + dy },
|
||||
size,
|
||||
maxScale
|
||||
);
|
||||
@@ -19,6 +19,9 @@ interface MinMaxFrame {
|
||||
maxPoint: Point;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
lastPoint: Point;
|
||||
lastX: number;
|
||||
lastY: number;
|
||||
gapPoint: Point | undefined;
|
||||
}
|
||||
|
||||
@@ -68,6 +71,9 @@ function newFrame(
|
||||
maxPoint: point,
|
||||
maxX: x,
|
||||
maxY: y,
|
||||
lastPoint: point,
|
||||
lastX: x,
|
||||
lastY: y,
|
||||
gapPoint,
|
||||
};
|
||||
}
|
||||
@@ -174,6 +180,9 @@ export function downSampleLineData<
|
||||
if (!frame) {
|
||||
frames.set(frameIndex, newFrame(point, x, y, undefined));
|
||||
} else if (frame.hasValue) {
|
||||
frame.lastPoint = point;
|
||||
frame.lastX = x;
|
||||
frame.lastY = y;
|
||||
// Match the original strict-less / strict-greater comparisons so the
|
||||
// first occurrence wins on ties.
|
||||
if (y < frame.minY) {
|
||||
@@ -189,6 +198,9 @@ export function downSampleLineData<
|
||||
} else {
|
||||
// the frame held nothing but a marker so far
|
||||
frame.hasValue = true;
|
||||
frame.lastPoint = point;
|
||||
frame.lastX = x;
|
||||
frame.lastY = y;
|
||||
frame.minPoint = point;
|
||||
frame.minX = x;
|
||||
frame.minY = y;
|
||||
@@ -199,7 +211,13 @@ export function downSampleLineData<
|
||||
}
|
||||
|
||||
const result: T[] = [];
|
||||
for (const frame of frames.values()) {
|
||||
for (const [frameIndex, frame] of frames) {
|
||||
// A marker followed by a value in its own frame is a gap that closed
|
||||
// within one frame, which is about one device pixel: too narrow to show.
|
||||
// That value may be neither min nor max, so check the frame's last x.
|
||||
const keepGap =
|
||||
frame.gapPoint !== undefined &&
|
||||
Number(getPointData(frame.gapPoint)[0]) >= frame.lastX;
|
||||
if (frame.hasValue) {
|
||||
// The order of the data must be preserved so max may be before min
|
||||
if (frame.minX > frame.maxX) {
|
||||
@@ -209,18 +227,19 @@ export function downSampleLineData<
|
||||
if (frame.minX < frame.maxX) {
|
||||
result.push(frame.maxPoint as T);
|
||||
}
|
||||
}
|
||||
if (frame.gapPoint !== undefined) {
|
||||
// A marker followed by a value in its own frame is a gap that closed
|
||||
// within one frame, which is about one device pixel: too narrow to show.
|
||||
// The kept points are exactly min and max, so comparing against the
|
||||
// later of the two catches that without any work on the ingest path. A
|
||||
// marker-only frame compares against its own x and always passes.
|
||||
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
|
||||
result.push(frame.gapPoint as T);
|
||||
// Step lines hold the last value until the next point, so it must
|
||||
// survive when that point is more than a frame away.
|
||||
if (
|
||||
!keepGap &&
|
||||
!frames.has(frameIndex + 1) &&
|
||||
frame.lastY !== (frame.minX < frame.maxX ? frame.maxY : frame.minY)
|
||||
) {
|
||||
result.push(frame.lastPoint as T);
|
||||
}
|
||||
}
|
||||
if (keepGap) {
|
||||
result.push(frame.gapPoint as T);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
mdiRestart,
|
||||
} from "@mdi/js";
|
||||
import { differenceInMinutes } from "date-fns";
|
||||
import type { DataZoomComponentOption } from "echarts/components";
|
||||
import type {
|
||||
DataZoomComponentOption,
|
||||
MarkAreaComponentOption,
|
||||
} from "echarts/components";
|
||||
import type { EChartsType } from "echarts/core";
|
||||
import type {
|
||||
ECElementEvent,
|
||||
@@ -90,14 +93,29 @@ export const DEFAULT_CHART_WIDTH = 500;
|
||||
// is short enough for a whole screenful; on a desktop that would cover the page.
|
||||
const VISIBILITY_ROOT_MARGIN_NARROW = "100%";
|
||||
const VISIBILITY_ROOT_MARGIN = "300px";
|
||||
const CLICK_DRAG_TOLERANCE = 4;
|
||||
// The selection is shown by the mask, not by the brush
|
||||
const BRUSH_STYLE = {
|
||||
color: "rgba(0, 0, 0, 0)",
|
||||
borderColor: "rgba(0, 0, 0, 0)",
|
||||
};
|
||||
|
||||
export type ZoomSliderMode = "auto" | "always" | "never";
|
||||
|
||||
export type ChartSelectMode = "none" | "point" | "range";
|
||||
const DEFERRED_PROPS = [
|
||||
"options",
|
||||
"data",
|
||||
"_hiddenDatasets",
|
||||
"_isZoomed",
|
||||
"highlight",
|
||||
] as const;
|
||||
const MASK_OPACITY = 0.7;
|
||||
|
||||
export interface ChartTimeRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
type RawSeriesOption = Exclude<
|
||||
NonNullable<ECOption["series"]>,
|
||||
@@ -176,6 +194,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
@property({ attribute: "grow-for-zoom-slider", type: Boolean })
|
||||
public growForZoomSlider = false;
|
||||
|
||||
// "point" selects on click, "range" also selects on drag instead of zooming
|
||||
@property({ attribute: "select-mode" })
|
||||
public selectMode: ChartSelectMode = "none";
|
||||
|
||||
// Everything outside this time range fades
|
||||
@property({ attribute: false }) public highlight?: ChartTimeRange;
|
||||
|
||||
// Rounds a selection to the periods of the data, or drops it
|
||||
@property({ attribute: false }) public snapSelection?: (
|
||||
range: ChartTimeRange
|
||||
) => ChartTimeRange | undefined;
|
||||
|
||||
// extraComponents is not reactive and should not trigger updates
|
||||
public extraComponents?: any[];
|
||||
|
||||
@@ -201,6 +231,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
@state() private _isZoomed = false;
|
||||
|
||||
private _pointerDownX?: number;
|
||||
|
||||
private _selectingRange?: ChartTimeRange;
|
||||
|
||||
private _maskColor = "";
|
||||
|
||||
private _maskShown = false;
|
||||
|
||||
// Separate from _isZoomed, whose touch handling reruns graph layouts
|
||||
@state() private _isGraphRoamed = false;
|
||||
|
||||
@@ -454,6 +492,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!this.chart) {
|
||||
return;
|
||||
}
|
||||
if (changedProps.has("selectMode")) {
|
||||
this._updateSelectMode();
|
||||
}
|
||||
const themeChanged = changedProps.has("_themes") && this.hasUpdated;
|
||||
if (!themeChanged && !DEFERRED_PROPS.some((p) => changedProps.has(p))) {
|
||||
return;
|
||||
@@ -499,6 +540,8 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
) {
|
||||
this._disposeSonification();
|
||||
}
|
||||
} else if (changedProps.has("highlight")) {
|
||||
this._updateMask();
|
||||
}
|
||||
if (changedProps.has("options")) {
|
||||
chartOptions = { ...chartOptions, ...this._createOptions() };
|
||||
@@ -627,7 +670,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
class="zoom-reset"
|
||||
.path=${mdiRestart}
|
||||
@click=${this._handleZoomReset}
|
||||
title=${this._i18n.localize(
|
||||
.label=${this._i18n.localize(
|
||||
"ui.components.history_charts.zoom_reset"
|
||||
)}
|
||||
></ha-icon-button>`
|
||||
@@ -888,6 +931,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
const style = getComputedStyle(this);
|
||||
echarts.registerTheme("custom", this._createTheme(style));
|
||||
this._maskColor =
|
||||
style.getPropertyValue("--card-background-color").trim() ||
|
||||
style.getPropertyValue("--primary-background-color").trim();
|
||||
|
||||
this.chart = echarts.init(this._chartContainer!, "custom");
|
||||
this._dragToZoom = false;
|
||||
@@ -970,6 +1016,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
this._legendItemCount = this._getLegendItems()?.length;
|
||||
this._updateSankeyRoam();
|
||||
this._updateDragToZoom();
|
||||
if (this.selectMode !== "none") {
|
||||
this._updateSelectMode();
|
||||
}
|
||||
if (zoomStart !== 0 || zoomEnd !== 100) {
|
||||
this.zoom(zoomStart, zoomEnd, true);
|
||||
}
|
||||
@@ -1021,7 +1070,10 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
// A chart can switch type (e.g. pie and bar) without being rebuilt
|
||||
private _updateDragToZoom() {
|
||||
const active = !this._touchInput && this._hasZoomableXAxis();
|
||||
const active =
|
||||
!this._touchInput &&
|
||||
this._hasZoomableXAxis() &&
|
||||
this.selectMode !== "range";
|
||||
if (!this.chart || active === this._dragToZoom) {
|
||||
return;
|
||||
}
|
||||
@@ -1033,6 +1085,130 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
}
|
||||
|
||||
private _snapRange(range: ChartTimeRange) {
|
||||
return this.snapSelection ? this.snapSelection(range) : range;
|
||||
}
|
||||
|
||||
private _getMaskArea(): MarkAreaComponentOption | undefined {
|
||||
const range = this._selectingRange ?? this.highlight;
|
||||
if (!range) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
silent: true,
|
||||
z: 10,
|
||||
itemStyle: {
|
||||
color: this._maskColor,
|
||||
opacity: MASK_OPACITY,
|
||||
},
|
||||
data: [
|
||||
[{ xAxis: -Infinity }, { xAxis: range.start }],
|
||||
[{ xAxis: range.end }, { xAxis: Infinity }],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Only the first series carries the mask, merged in without resending data
|
||||
private _updateMask() {
|
||||
const maskArea = this._getMaskArea();
|
||||
if (maskArea) {
|
||||
this._maskShown = true;
|
||||
}
|
||||
this.chart?.setOption({
|
||||
series: [{ markArea: maskArea ?? { data: [] } }],
|
||||
});
|
||||
}
|
||||
|
||||
private _handleSelectPointerDown = (e: ECElementEvent) => {
|
||||
this._pointerDownX = e.offsetX;
|
||||
};
|
||||
|
||||
private _handleSelectClick = (e: ECElementEvent) => {
|
||||
const point = [e.offsetX, e.offsetY];
|
||||
// A drag that ends on the plot is not a click
|
||||
const dragged =
|
||||
this._pointerDownX !== undefined &&
|
||||
Math.abs(e.offsetX - this._pointerDownX) > CLICK_DRAG_TOLERANCE;
|
||||
if (dragged || !this.chart?.containPixel("grid", point)) {
|
||||
return;
|
||||
}
|
||||
const [x] = this.chart.convertFromPixel("grid", point) as number[];
|
||||
const selection = this._snapRange({ start: x, end: x });
|
||||
if (selection) {
|
||||
fireEvent(this, "chart-select", selection);
|
||||
}
|
||||
};
|
||||
|
||||
private _handleBrush = (e: any) => {
|
||||
const range = e.areas?.[0]?.coordRange as number[] | undefined;
|
||||
if (range) {
|
||||
this._selectingRange = this._snapRange({
|
||||
start: range[0],
|
||||
end: range[1],
|
||||
});
|
||||
this._updateMask();
|
||||
}
|
||||
};
|
||||
|
||||
private _handleBrushEnd = (e: any) => {
|
||||
const range = e.areas?.[0]?.coordRange as number[] | undefined;
|
||||
this.chart?.dispatchAction({ type: "brush", areas: [] });
|
||||
this._selectingRange = undefined;
|
||||
this._updateMask();
|
||||
const selection =
|
||||
range && this._snapRange({ start: range[0], end: range[1] });
|
||||
if (selection) {
|
||||
fireEvent(this, "chart-select", selection);
|
||||
}
|
||||
};
|
||||
|
||||
private _updateSelectMode() {
|
||||
if (!this.chart) {
|
||||
return;
|
||||
}
|
||||
const zr = this.chart.getZr();
|
||||
zr.off("mousedown", this._handleSelectPointerDown);
|
||||
zr.off("click", this._handleSelectClick);
|
||||
this.chart.off("brush", this._handleBrush);
|
||||
this.chart.off("brushEnd", this._handleBrushEnd);
|
||||
if (this.selectMode !== "none") {
|
||||
zr.on("mousedown", this._handleSelectPointerDown);
|
||||
zr.on("click", this._handleSelectClick);
|
||||
}
|
||||
const selectRange = this.selectMode === "range";
|
||||
if (selectRange) {
|
||||
this.chart.on("brush", this._handleBrush);
|
||||
this.chart.on("brushEnd", this._handleBrushEnd);
|
||||
this.chart.setOption({
|
||||
brush: {
|
||||
xAxisIndex: 0,
|
||||
// Only measures the range, the mask fades what is outside
|
||||
seriesIndex: [],
|
||||
transformable: false,
|
||||
brushStyle: BRUSH_STYLE,
|
||||
},
|
||||
});
|
||||
}
|
||||
const brushCursor = {
|
||||
type: "takeGlobalCursor",
|
||||
key: "brush",
|
||||
brushOption: {
|
||||
brushType: selectRange ? "lineX" : false,
|
||||
brushMode: "single",
|
||||
brushStyle: BRUSH_STYLE,
|
||||
},
|
||||
};
|
||||
// Brush and drag to zoom share the global cursor, the last one taken wins
|
||||
if (selectRange) {
|
||||
this._updateDragToZoom();
|
||||
this.chart.dispatchAction(brushCursor);
|
||||
} else {
|
||||
this.chart.dispatchAction(brushCursor);
|
||||
this._dragToZoom = false;
|
||||
this._updateDragToZoom();
|
||||
}
|
||||
}
|
||||
|
||||
private _hasZoomableXAxis() {
|
||||
const xAxis = ensureArray(this.options?.xAxis)?.[0] as
|
||||
XAXisOption | undefined;
|
||||
@@ -1475,7 +1651,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
private _getSeries() {
|
||||
const xAxis = (this.options?.xAxis?.[0] ?? this.options?.xAxis) as
|
||||
XAXisOption | undefined;
|
||||
const series = ensureArray(this.data).map((s) => {
|
||||
const maskArea = this._getMaskArea();
|
||||
if (maskArea) {
|
||||
this._maskShown = true;
|
||||
}
|
||||
const series = ensureArray(this.data).map((s, index) => {
|
||||
const data = this._hiddenDatasets.has(String(s.id ?? s.name))
|
||||
? undefined
|
||||
: s.data;
|
||||
@@ -1513,6 +1693,16 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
} as HaECSeriesItem;
|
||||
}
|
||||
}
|
||||
// ECharts merges series by id and would keep a mask left out here
|
||||
if (this._maskShown && (s.type === "line" || s.type === "bar")) {
|
||||
result = {
|
||||
...result,
|
||||
markArea:
|
||||
index === 0 && maskArea
|
||||
? maskArea
|
||||
: ((s as LineSeriesOption).markArea ?? { data: [] }),
|
||||
} as HaECSeriesItem;
|
||||
}
|
||||
return processSeriesTooltipFormatter(result);
|
||||
});
|
||||
return series as ECOption["series"];
|
||||
@@ -1762,7 +1952,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
// it, so a quick drag out would lose the release and its selection
|
||||
if (
|
||||
ev.type === "pointerdown" &&
|
||||
this._dragToZoom &&
|
||||
(this._dragToZoom || this.selectMode === "range") &&
|
||||
this._isZoomPress(ev)
|
||||
) {
|
||||
this.chart
|
||||
@@ -2337,6 +2527,7 @@ declare global {
|
||||
"dataset-hidden": { id: string };
|
||||
"dataset-unhidden": { id: string };
|
||||
"chart-click": ECElementEvent;
|
||||
"chart-select": ChartTimeRange;
|
||||
"legend-label-click": { id: string };
|
||||
"chart-zoom": {
|
||||
start: number;
|
||||
|
||||
@@ -76,6 +76,18 @@ export interface NetworkData {
|
||||
|
||||
const PHYSICS_DISABLE_THRESHOLD = 512;
|
||||
|
||||
const LAYOUT_ANIMATION_THRESHOLD = 100;
|
||||
|
||||
// Every event of a change of the legend selection, each with the whole
|
||||
// selection
|
||||
const LEGEND_SELECT_EVENTS = [
|
||||
"legendselectchanged",
|
||||
"legendselected",
|
||||
"legendunselected",
|
||||
"legendselectall",
|
||||
"legendinverseselect",
|
||||
];
|
||||
|
||||
const SELECTED_NODE_MAX_ZOOM = 2;
|
||||
|
||||
// Keeps neighbors clear of the search field, buttons and legend
|
||||
@@ -83,6 +95,10 @@ const SELECTED_NODE_FIT_MARGIN = 72;
|
||||
|
||||
const FOLLOW_ROAM = "follow-selected-node";
|
||||
|
||||
type Displayable = ReturnType<
|
||||
ReturnType<EChartsType["getZr"]>["storage"]["getDisplayList"]
|
||||
>[number];
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/consistent-type-imports
|
||||
let GraphChart: typeof import("echarts/lib/chart/graph/install");
|
||||
|
||||
@@ -124,8 +140,24 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
@state() private _showLabels = true;
|
||||
|
||||
// Not reactive: a new series option starts the layout again, so a drop only
|
||||
// reaches the option with the next render
|
||||
private _nodePositions: Record<string, { x: number; y: number }> = {};
|
||||
|
||||
// Dragged nodes stay where they are dropped, the force layout moves the others
|
||||
private _pinnedNodes: string[] = [];
|
||||
|
||||
// Names of the legend categories that are switched off. Not reactive: the
|
||||
// legend lays the graph out itself, only the layout animation threshold
|
||||
// needs a render
|
||||
private _hiddenCategories: string[] = [];
|
||||
|
||||
private _dragNode?: string;
|
||||
|
||||
private _dragMoved = false;
|
||||
|
||||
private _dragTarget?: Displayable;
|
||||
|
||||
private _followSelectedNode = false;
|
||||
|
||||
private _followedChart?: EChartsType;
|
||||
@@ -170,12 +202,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
this._showLabels,
|
||||
isMobile,
|
||||
hasHighlightedNodes,
|
||||
this.selectedNode
|
||||
this.selectedNode,
|
||||
this._nodePositions,
|
||||
this._pinnedNodes,
|
||||
this._fewVisibleNodes()
|
||||
)}
|
||||
.options=${this._createOptions(this.data?.categories)}
|
||||
height="100%"
|
||||
.extraComponents=${[GraphChart]}
|
||||
@chart-setup=${this._updateFollowing}
|
||||
@chart-setup=${this._handleChartSetup}
|
||||
>
|
||||
<slot name="search" slot="search"></slot>
|
||||
<slot name="button" slot="button"></slot>
|
||||
@@ -273,7 +308,10 @@ export class HaNetworkGraph extends LitElement {
|
||||
showLabels: boolean,
|
||||
isMobile: boolean,
|
||||
hasHighlightedNodes?: boolean,
|
||||
selectedNode?: string
|
||||
selectedNode?: string,
|
||||
nodePositions: Record<string, { x: number; y: number }> = {},
|
||||
pinnedNodes: string[] = [],
|
||||
fewVisibleNodes = true
|
||||
) => ({
|
||||
id: "network",
|
||||
type: "graph",
|
||||
@@ -311,14 +349,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
repulsion: [400, 600],
|
||||
edgeLength: [200, 350],
|
||||
gravity: 0.05,
|
||||
layoutAnimation: !reducedMotion && data.nodes.length < 100,
|
||||
layoutAnimation: !reducedMotion && fewVisibleNodes,
|
||||
},
|
||||
edgeSymbol: ["none", "arrow"],
|
||||
edgeSymbolSize: 10,
|
||||
data: this._getSeriesData(
|
||||
data.nodes,
|
||||
data.links,
|
||||
this._nodePositions,
|
||||
nodePositions,
|
||||
pinnedNodes,
|
||||
selectedNode
|
||||
),
|
||||
links: data.links.map((link) => ({
|
||||
@@ -334,11 +373,25 @@ export class HaNetworkGraph extends LitElement {
|
||||
deepEqual
|
||||
);
|
||||
|
||||
// The legend leaves the nodes of hidden categories out of the layout
|
||||
private _fewVisibleNodes() {
|
||||
const hidden = this._hiddenCategories;
|
||||
const visibleNodes = hidden.length
|
||||
? this.data.nodes.filter(
|
||||
(node) =>
|
||||
node.category === undefined ||
|
||||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
|
||||
).length
|
||||
: this.data.nodes.length;
|
||||
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
|
||||
}
|
||||
|
||||
private _getSeriesData = memoizeOne(
|
||||
(
|
||||
nodes: NetworkNode[],
|
||||
links: NetworkLink[],
|
||||
nodePositions: Record<string, { x: number; y: number }>,
|
||||
pinnedNodes: string[],
|
||||
selectedNode?: string
|
||||
) =>
|
||||
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
|
||||
@@ -355,7 +408,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
? { ...node.itemStyle, borderWidth: 3 }
|
||||
: node.itemStyle || {},
|
||||
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
|
||||
fixed: node.fixed,
|
||||
fixed: node.fixed || pinnedNodes.includes(node.id),
|
||||
x: node.x,
|
||||
y: node.y,
|
||||
} as NonNullable<GraphSeriesOption["data"]>[number];
|
||||
@@ -515,6 +568,141 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _handleChartSetup() {
|
||||
const chart = this._baseChart?.chart;
|
||||
chart?.on("mousedown", this._handleNodeMouseDown);
|
||||
chart?.getZr().on("dragstart", this._handleDragStart);
|
||||
chart?.getZr().on("drag", this._handleDrag);
|
||||
chart?.getZr().on("dragend", this._handleDragEnd);
|
||||
for (const event of LEGEND_SELECT_EVENTS) {
|
||||
chart?.on(event, this._handleLegendChange);
|
||||
}
|
||||
const legend = (
|
||||
chart?.getOption() as
|
||||
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
|
||||
)?.legend?.[0];
|
||||
this._setHiddenCategories(legend?.selected ?? {});
|
||||
// A recreated chart, e.g. after a theme change, lacks the drops since the
|
||||
// last render
|
||||
this.requestUpdate();
|
||||
this._updateFollowing();
|
||||
}
|
||||
|
||||
private _handleLegendChange = (params: unknown) => {
|
||||
const fewVisibleNodes = this._fewVisibleNodes();
|
||||
this._setHiddenCategories(
|
||||
(params as { selected: Record<string, boolean> }).selected
|
||||
);
|
||||
if (this._fewVisibleNodes() !== fewVisibleNodes) {
|
||||
// The new series option lays out again from where the nodes are now
|
||||
this._saveNodePositions();
|
||||
this.requestUpdate();
|
||||
}
|
||||
};
|
||||
|
||||
private _setHiddenCategories(selected: Record<string, boolean>) {
|
||||
this._hiddenCategories = Object.keys(selected).filter(
|
||||
(name) => !selected[name]
|
||||
);
|
||||
}
|
||||
|
||||
private _handleNodeMouseDown = (params: {
|
||||
dataType?: string;
|
||||
data?: unknown;
|
||||
}) => {
|
||||
this._dragNode =
|
||||
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
|
||||
this._dragMoved = false;
|
||||
};
|
||||
|
||||
// The dragged element gets the drag before the ECharts handler of its node
|
||||
private _handleDragStart = (ev: { target?: Displayable }) => {
|
||||
this._dragTarget?.off("drag", this._handleNodeDrag);
|
||||
this._dragTarget = ev.target;
|
||||
this._dragTarget?.on("drag", this._handleNodeDrag);
|
||||
};
|
||||
|
||||
// Without layout animation, the ECharts handler runs the whole force layout
|
||||
// on every move, which puts the node back before it reads its position. So
|
||||
// the node moves here, and the other nodes stay where they are.
|
||||
private _handleNodeDrag = (ev: { cancelBubble?: boolean }) => {
|
||||
const chart = this._baseChart?.chart;
|
||||
const series = this._getGraphSeries(chart);
|
||||
const node =
|
||||
this._dragNode === undefined
|
||||
? undefined
|
||||
: series?.getGraph().getNodeById(this._dragNode);
|
||||
if (
|
||||
!chart ||
|
||||
!node ||
|
||||
!series.forceLayout ||
|
||||
series.get(["force", "layoutAnimation"])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
ev.cancelBubble = true;
|
||||
const data = series.getData();
|
||||
const el = data.getItemGraphicEl(node.dataIndex);
|
||||
data.setItemLayout(node.dataIndex, [el.x, el.y]);
|
||||
// A new layout run starts from here, e.g. after a legend change
|
||||
if (series.preservedPoints) {
|
||||
series.preservedPoints[node.id] = [el.x, el.y];
|
||||
}
|
||||
series.forceLayout.setFixed(node.dataIndex);
|
||||
for (const edge of node.edges) {
|
||||
const source: number[] | undefined = edge.node1.getLayout();
|
||||
const target: number[] | undefined = edge.node2.getLayout();
|
||||
// The nodes of hidden legend categories have no layout
|
||||
if (source && target) {
|
||||
edge.setLayout([[...source], [...target]]);
|
||||
}
|
||||
}
|
||||
// @ts-ignore private method but no other way to draw the new layout
|
||||
chart.getViewOfSeriesModel(series).updateLayout(series);
|
||||
// The handlers of the chart miss the drag now
|
||||
chart.getZr().handler.trigger("drag", ev);
|
||||
};
|
||||
|
||||
private _handleDrag = () => {
|
||||
this._dragMoved = true;
|
||||
};
|
||||
|
||||
private _handleDragEnd = () => {
|
||||
const id = this._dragNode;
|
||||
const moved = this._dragMoved;
|
||||
this._dragNode = undefined;
|
||||
this._dragMoved = false;
|
||||
this._dragTarget?.off("drag", this._handleNodeDrag);
|
||||
this._dragTarget = undefined;
|
||||
// A click also ends a drag, which releases a pinned node in ECharts
|
||||
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
|
||||
return;
|
||||
}
|
||||
this._pinNodeInChart(id);
|
||||
if (!this._pinnedNodes.includes(id)) {
|
||||
this._pinnedNodes = [...this._pinnedNodes, id];
|
||||
}
|
||||
this._saveNodePositions();
|
||||
};
|
||||
|
||||
// A new series option would start the layout again, so the pin goes into
|
||||
// the running force layout, and into the item option that ECharts lays out
|
||||
// from again, e.g. on a legend change
|
||||
private _pinNodeInChart(id: string) {
|
||||
const series = this._getGraphSeries();
|
||||
const node = series?.getGraph().getNodeById(id);
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
series.forceLayout?.setFixed(node.dataIndex);
|
||||
const [x, y] = node.getLayout();
|
||||
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
|
||||
fixed: true,
|
||||
x,
|
||||
y,
|
||||
});
|
||||
}
|
||||
|
||||
private _updateFollowing() {
|
||||
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
|
||||
if (chart !== this._followedChart) {
|
||||
@@ -550,10 +738,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
if (!chart) {
|
||||
return;
|
||||
}
|
||||
const series: any = chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0);
|
||||
const series = this._getGraphSeries(chart);
|
||||
const node = series?.getGraph().getNodeById(this.selectedNode);
|
||||
const position: number[] | undefined = node?.getLayout();
|
||||
if (!position) {
|
||||
@@ -614,6 +799,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
private _togglePhysics() {
|
||||
this._saveNodePositions();
|
||||
this._pinnedNodes = [];
|
||||
this._physicsEnabled = !this._physicsEnabled;
|
||||
}
|
||||
|
||||
@@ -622,26 +808,30 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
|
||||
private _saveNodePositions() {
|
||||
const positions = {};
|
||||
if (this._baseChart?.chart) {
|
||||
this._baseChart.chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0)
|
||||
.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
// Nodes that are not drawn keep their earlier position
|
||||
const positions = { ...this._nodePositions };
|
||||
this._getGraphSeries()
|
||||
?.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
this._nodePositions = positions;
|
||||
}
|
||||
|
||||
private _getGraphSeries(chart = this._baseChart?.chart): any {
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return undefined;
|
||||
}
|
||||
// @ts-ignore private method but no other way to get the graph
|
||||
return chart.getModel().getSeriesByIndex(0);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { isComponentLoaded } from "../../common/config/is_component_loaded";
|
||||
@@ -49,7 +49,13 @@ import type {
|
||||
HomeAssistantUI,
|
||||
} from "../../types";
|
||||
import { getPeriodicAxisLabelConfig } from "./axis-label";
|
||||
import type { CustomLegendOption } from "./ha-chart-base";
|
||||
import type {
|
||||
ChartSelectMode,
|
||||
ChartTimeRange,
|
||||
CustomLegendOption,
|
||||
HaChartBase,
|
||||
ZoomSliderMode,
|
||||
} from "./ha-chart-base";
|
||||
import "./ha-chart-base";
|
||||
import { sideTooltipPosition } from "./chart-tooltip-position";
|
||||
import "./ha-chart-tooltip-marker";
|
||||
@@ -128,6 +134,16 @@ export class StatisticsChart extends LitElement {
|
||||
@property({ attribute: "expand-legend", type: Boolean })
|
||||
public expandLegend?: boolean;
|
||||
|
||||
@property({ attribute: "select-mode" })
|
||||
public selectMode: ChartSelectMode = "none";
|
||||
|
||||
@property({ attribute: "zoom-slider" })
|
||||
public zoomSlider: ZoomSliderMode = "auto";
|
||||
|
||||
@property({ attribute: false }) public highlight?: ChartTimeRange;
|
||||
|
||||
@query("ha-chart-base") private _chartBase?: HaChartBase;
|
||||
|
||||
@state() private _chartData: (LineSeriesOption | BarSeriesOption)[] = [];
|
||||
|
||||
@state() private _legendData: CustomLegendOption["data"];
|
||||
@@ -244,8 +260,12 @@ export class StatisticsChart extends LitElement {
|
||||
return html`
|
||||
<ha-chart-base
|
||||
.data=${this._chartData}
|
||||
.highlight=${this.highlight}
|
||||
.snapSelection=${this._snapSelection}
|
||||
.options=${this._chartOptions}
|
||||
.height=${this.height}
|
||||
.selectMode=${this.selectMode}
|
||||
.zoomSlider=${this.zoomSlider}
|
||||
style=${styleMap({ height: this.height })}
|
||||
@dataset-hidden=${this._datasetHidden}
|
||||
@dataset-unhidden=${this._datasetUnhidden}
|
||||
@@ -259,6 +279,39 @@ export class StatisticsChart extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
public resetZoom() {
|
||||
this._chartBase?.zoom(0, 100);
|
||||
}
|
||||
|
||||
// A click selects the period that contains it, a drag every period it
|
||||
// touches
|
||||
private _snapSelection = (
|
||||
range: ChartTimeRange
|
||||
): ChartTimeRange | undefined => {
|
||||
let start: number | undefined;
|
||||
let end: number | undefined;
|
||||
Object.entries(this.statisticsData ?? {}).forEach(
|
||||
([statisticId, values]) => {
|
||||
if (this._hiddenStats.has(statisticId)) {
|
||||
return;
|
||||
}
|
||||
values.forEach((value) => {
|
||||
const touched =
|
||||
range.start === range.end
|
||||
? value.start <= range.start && range.start < value.end
|
||||
: value.start < range.end && value.end > range.start;
|
||||
if (touched) {
|
||||
start = Math.min(start ?? value.start, value.start);
|
||||
end = Math.max(end ?? value.end, value.end);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
return start === undefined || end === undefined
|
||||
? undefined
|
||||
: { start, end };
|
||||
};
|
||||
|
||||
private _datasetHidden(ev: HASSDomEvent<HASSDomEvents["dataset-hidden"]>) {
|
||||
this._hiddenStats.add(ev.detail.id);
|
||||
this.requestUpdate("_hiddenStats");
|
||||
|
||||
@@ -35,24 +35,27 @@ function computeTimelineStateColor(
|
||||
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
|
||||
// Zone states for person/device_tracker don't have specific CSS color variables,
|
||||
// so they all fall back to the same --state-person-active-color.
|
||||
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
|
||||
// otherwise return undefined to get unique colors from the generic color handler.
|
||||
if (
|
||||
// Zone states would all share --state-person-active-color, so only an
|
||||
// exact state variable may color them, like states of uncolored domains.
|
||||
const isZoneState =
|
||||
(domain === "person" || domain === "device_tracker") &&
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
|
||||
) {
|
||||
return computeCssValue(
|
||||
`--state-${domain}-${slugify(state, "_")}-color`,
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const properties = stateColorProperties(stateObj, state);
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
|
||||
const properties = isZoneState
|
||||
? undefined
|
||||
: stateColorProperties(stateObj, state);
|
||||
|
||||
if (!properties) {
|
||||
return undefined;
|
||||
const stateKey = slugify(state, "_");
|
||||
const deviceClass = stateObj.attributes.device_class;
|
||||
return computeCssValue(
|
||||
[
|
||||
...(deviceClass
|
||||
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
|
||||
: []),
|
||||
`--state-${domain}-${stateKey}-color`,
|
||||
],
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const rgb = computeCssValue(properties, computedStyles);
|
||||
|
||||
@@ -572,6 +572,11 @@ export class HaDataTable extends LitElement {
|
||||
>
|
||||
<ha-checkbox
|
||||
class="mdc-data-table__row-checkbox"
|
||||
.accessibleLabel=${
|
||||
this._i18n?.localize?.(
|
||||
"ui.components.data-table.select_all"
|
||||
) ?? ""
|
||||
}
|
||||
@change=${this._handleHeaderRowCheckboxClick}
|
||||
.indeterminate=${
|
||||
!!this._checkedRows.length &&
|
||||
@@ -898,6 +903,7 @@ export class HaDataTable extends LitElement {
|
||||
>
|
||||
<ha-checkbox
|
||||
class="mdc-data-table__row-checkbox"
|
||||
.accessibleLabel=${this._rowCheckboxLabel(columns, row)}
|
||||
@click=${this._handleRowCheckboxClicked}
|
||||
.rowId=${row[this.id]}
|
||||
.disabled=${row.selectable === false}
|
||||
@@ -967,6 +973,23 @@ export class HaDataTable extends LitElement {
|
||||
`;
|
||||
};
|
||||
|
||||
private _rowCheckboxLabel(
|
||||
columns: DataTableColumnContainer,
|
||||
row: DataTableRowData
|
||||
): string {
|
||||
const mainKey = Object.keys(columns).find((key) => columns[key].main);
|
||||
const name = mainKey ? row[mainKey] : undefined;
|
||||
return (
|
||||
(typeof name === "string" && name
|
||||
? this._i18n?.localize?.("ui.components.data-table.select_row", {
|
||||
name,
|
||||
})
|
||||
: this._i18n?.localize?.(
|
||||
"ui.components.data-table.select_row_generic"
|
||||
)) ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
private _isColumnVisible(key: string, column: DataTableColumnData): boolean {
|
||||
if (column.hidden) {
|
||||
return false;
|
||||
@@ -1663,7 +1686,8 @@ export class HaDataTable extends LitElement {
|
||||
}
|
||||
|
||||
.mdc-data-table__row ~ .mdc-data-table__row {
|
||||
border-top: 1px solid var(--divider-color);
|
||||
border-top: var(--data-table-row-border-width, 1px) solid
|
||||
var(--divider-color);
|
||||
}
|
||||
|
||||
.mdc-data-table__row.clickable:not(
|
||||
|
||||
@@ -52,7 +52,7 @@ class StateInfo extends LitElement {
|
||||
${
|
||||
this.inDialog
|
||||
? html`<div class="time-ago">
|
||||
<ha-tooltip for="relative-time">
|
||||
<ha-tooltip for="relative-time" trigger="hover focus click">
|
||||
<div class="row">
|
||||
<span class="column-name">
|
||||
${this._localize(
|
||||
|
||||
@@ -60,6 +60,7 @@ export const ADAPTIVE_DIALOG_MEDIA_QUERY =
|
||||
* @attr {boolean} without-header - Hides the default header.
|
||||
* @attr {boolean} hide-close-button - Hides the default close button.
|
||||
* @attr {boolean} allow-mode-change - When set, the component can switch between dialog and bottom-sheet modes as the viewport changes.
|
||||
* @prop {string} accessibleLabel - Accessible name for dialogs that put their title in a slot.
|
||||
*
|
||||
* @event opened - Fired when the dialog/sheet is shown.
|
||||
* @event closed - Fired after the dialog/sheet is hidden.
|
||||
@@ -103,6 +104,9 @@ export class HaAdaptiveDialog extends LitElement {
|
||||
@property({ attribute: "header-title" })
|
||||
public headerTitle?: string;
|
||||
|
||||
@property({ attribute: false })
|
||||
public accessibleLabel?: string;
|
||||
|
||||
@property({ attribute: "header-subtitle" })
|
||||
public headerSubtitle?: string;
|
||||
|
||||
@@ -201,7 +205,8 @@ export class HaAdaptiveDialog extends LitElement {
|
||||
if (this.mode === "bottom-sheet") {
|
||||
return html`
|
||||
<ha-bottom-sheet
|
||||
.ariaLabelledBy=${this._defaultAriaLabelledBy}
|
||||
.accessibleLabel=${this.accessibleLabel ?? this.headerTitle}
|
||||
.ariaLabelledBy=${this.ariaLabelledBy}
|
||||
.ariaDescribedBy=${this.ariaDescribedBy}
|
||||
.flexContent=${this.flexContent}
|
||||
.open=${this.open}
|
||||
@@ -231,6 +236,7 @@ export class HaAdaptiveDialog extends LitElement {
|
||||
.ariaLabelledBy=${this.ariaLabelledBy}
|
||||
.ariaDescribedBy=${this.ariaDescribedBy}
|
||||
.headerTitle=${this.headerTitle}
|
||||
.accessibleLabel=${this.accessibleLabel}
|
||||
.headerSubtitle=${this.headerSubtitle}
|
||||
.headerSubtitlePosition=${this.headerSubtitlePosition}
|
||||
.flexContent=${this.flexContent}
|
||||
|
||||
@@ -3,13 +3,13 @@ import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import type { HASSDomCurrentTargetEvent } from "../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import type { Analytics, AnalyticsPreferences } from "../data/analytics";
|
||||
import { haStyle } from "../resources/styles";
|
||||
import "./ha-switch";
|
||||
import type { HaSwitch } from "./ha-switch";
|
||||
import "./ha-tooltip";
|
||||
import "./item/ha-row-item";
|
||||
import "./item/ha-list-item-switch";
|
||||
import type { HaListItemSwitch } from "./item/ha-list-item-switch";
|
||||
|
||||
const ADDITIONAL_PREFERENCES = ["usage", "statistics"] as const;
|
||||
|
||||
@@ -35,7 +35,12 @@ export class HaAnalytics extends LitElement {
|
||||
const baseEnabled = !loading && this.analytics!.preferences.base;
|
||||
|
||||
return html`
|
||||
<ha-row-item>
|
||||
<ha-list-item-switch
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${!!baseEnabled}
|
||||
.preference=${"base"}
|
||||
.disabled=${loading}
|
||||
>
|
||||
<span slot="headline"
|
||||
>${this._localize(
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.base.title`
|
||||
@@ -46,22 +51,15 @@ export class HaAnalytics extends LitElement {
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.base.description`
|
||||
)}</span
|
||||
>
|
||||
<ha-switch
|
||||
slot="end"
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${!!baseEnabled}
|
||||
.preference=${"base"}
|
||||
.disabled=${loading}
|
||||
name="base"
|
||||
>
|
||||
${this._localize(
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.base.title`
|
||||
)}
|
||||
</ha-switch>
|
||||
</ha-row-item>
|
||||
</ha-list-item-switch>
|
||||
${ADDITIONAL_PREFERENCES.map(
|
||||
(preference) => html`
|
||||
<ha-row-item>
|
||||
<ha-list-item-switch
|
||||
.id="switch-${preference}"
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${!!this.analytics?.preferences[preference]}
|
||||
.preference=${preference}
|
||||
>
|
||||
<span slot="headline"
|
||||
>${this._localize(
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.${preference}.title`
|
||||
@@ -72,18 +70,6 @@ export class HaAnalytics extends LitElement {
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.${preference}.description`
|
||||
)}</span
|
||||
>
|
||||
<ha-switch
|
||||
slot="end"
|
||||
.id="switch-${preference}"
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${!!this.analytics?.preferences[preference]}
|
||||
.preference=${preference}
|
||||
name=${preference}
|
||||
>
|
||||
${this._localize(
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.${preference}.title`
|
||||
)}
|
||||
</ha-switch>
|
||||
${
|
||||
baseEnabled
|
||||
? nothing
|
||||
@@ -96,10 +82,15 @@ export class HaAnalytics extends LitElement {
|
||||
)}
|
||||
</ha-tooltip>`
|
||||
}
|
||||
</ha-row-item>
|
||||
</ha-list-item-switch>
|
||||
`
|
||||
)}
|
||||
<ha-row-item>
|
||||
<ha-list-item-switch
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${!!this.analytics?.preferences.diagnostics}
|
||||
.preference=${"diagnostics"}
|
||||
.disabled=${loading}
|
||||
>
|
||||
<span slot="headline"
|
||||
>${this._localize(
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.diagnostics.title`
|
||||
@@ -110,25 +101,17 @@ export class HaAnalytics extends LitElement {
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.diagnostics.description`
|
||||
)}</span
|
||||
>
|
||||
<ha-switch
|
||||
slot="end"
|
||||
@change=${this._handleRowClick}
|
||||
.checked=${!!this.analytics?.preferences.diagnostics}
|
||||
.preference=${"diagnostics"}
|
||||
.disabled=${loading}
|
||||
name="diagnostics"
|
||||
>
|
||||
${this._localize(
|
||||
`ui.panel.${this.translationKeyPanel}.analytics.preferences.diagnostics.title`
|
||||
)}
|
||||
</ha-switch>
|
||||
</ha-row-item>
|
||||
</ha-list-item-switch>
|
||||
`;
|
||||
}
|
||||
|
||||
private _handleRowClick(ev: Event) {
|
||||
const target = ev.currentTarget as HaSwitch;
|
||||
const preference = (target as any).preference;
|
||||
private _handleRowClick(
|
||||
ev: HASSDomCurrentTargetEvent<
|
||||
HaListItemSwitch & { preference: keyof AnalyticsPreferences }
|
||||
>
|
||||
) {
|
||||
const target = ev.currentTarget;
|
||||
const preference = target.preference;
|
||||
const preferences = this.analytics ? { ...this.analytics.preferences } : {};
|
||||
|
||||
if (preferences[preference] === target.checked) {
|
||||
@@ -158,20 +141,7 @@ export class HaAnalytics extends LitElement {
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
/* The visible headline already names the row. Keep the switch's
|
||||
slotted label available to assistive technology without repeating it. */
|
||||
ha-switch::part(label) {
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
height: 1px;
|
||||
width: 1px;
|
||||
margin: -1px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
ha-row-item {
|
||||
ha-list-item-switch {
|
||||
--ha-row-item-padding-inline: 0;
|
||||
}
|
||||
`,
|
||||
|
||||
@@ -44,6 +44,9 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
@property({ attribute: "aria-describedby" })
|
||||
public ariaDescribedBy?: string;
|
||||
|
||||
@property({ attribute: false })
|
||||
public accessibleLabel?: string;
|
||||
|
||||
@property({ type: Boolean }) public open = false;
|
||||
|
||||
@property({ type: Boolean, reflect: true, attribute: "flexcontent" })
|
||||
@@ -212,6 +215,7 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
placement="bottom"
|
||||
.open=${this._drawerOpen}
|
||||
.lightDismiss=${!this.preventScrimClose}
|
||||
.label=${this.accessibleLabel ?? ""}
|
||||
.ariaLabelledby=${this.ariaLabelledBy}
|
||||
.ariaDescribedby=${this.ariaDescribedBy}
|
||||
@keydown=${this._handleKeyDown}
|
||||
@@ -239,6 +243,10 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
|
||||
private _handleTouchStart = (ev: TouchEvent) => {
|
||||
if (ev.touches.length > 1) {
|
||||
this._cancelResizing();
|
||||
return;
|
||||
}
|
||||
if (this.preventScrimClose) {
|
||||
return;
|
||||
}
|
||||
@@ -265,6 +273,10 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
|
||||
private _handleTouchMove = (ev: TouchEvent) => {
|
||||
if (ev.touches.length > 1) {
|
||||
this._cancelResizing();
|
||||
return;
|
||||
}
|
||||
const currentY = ev.touches[0].clientY;
|
||||
const delta = this._gestureRecognizer.move(currentY);
|
||||
|
||||
@@ -337,6 +349,18 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A second finger makes it a pinch, like zooming a camera picture, which
|
||||
* never moves the sheet. Puts the sheet back where it was.
|
||||
*/
|
||||
private _cancelResizing() {
|
||||
this._unregisterResizeHandlers();
|
||||
if (this._isDragging) {
|
||||
this._isDragging = false;
|
||||
this._animateSnapBack();
|
||||
}
|
||||
}
|
||||
|
||||
private _unregisterResizeHandlers = () => {
|
||||
document.removeEventListener("touchmove", this._handleTouchMove);
|
||||
document.removeEventListener("touchend", this._handleTouchEnd);
|
||||
|
||||
@@ -60,6 +60,7 @@ export class HaButtonToggleGroup extends LitElement {
|
||||
@click=${this._handleClick}
|
||||
.title=${button.label}
|
||||
.disabled=${this.disabled}
|
||||
.ariaPressed=${this.active === button.value ? "true" : "false"}
|
||||
.appearance=${this.active === button.value ? "accent" : "filled"}
|
||||
>
|
||||
${
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Button from "@home-assistant/webawesome/dist/components/button/button";
|
||||
import { css, type CSSResultGroup } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
import { css, type CSSResultGroup, type PropertyValues } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
|
||||
export type Appearance = "accent" | "filled" | "outlined" | "plain";
|
||||
|
||||
@@ -32,11 +32,26 @@ export type Appearance = "accent" | "filled" | "outlined" | "plain";
|
||||
* @attr {("accent"|"filled"|"outlined"|"plain")} appearance - Sets the button appearance.
|
||||
* @attr {boolean} loading - shows a loading indicator instead of the buttons label and disable buttons click.
|
||||
* @attr {boolean} disabled - Disables the button and prevents user interaction.
|
||||
* @attr {("true"|"false")} aria-pressed - Makes the button a toggle button and sets its pressed state, propagated to the underlying `<button>` element.
|
||||
*/
|
||||
@customElement("ha-button")
|
||||
export class HaButton extends Button {
|
||||
variant: "brand" | "neutral" | "success" | "warning" | "danger" = "brand";
|
||||
|
||||
@property({ attribute: "aria-pressed" })
|
||||
public override ariaPressed!: string | null;
|
||||
|
||||
protected override updated(changedProperties: PropertyValues<this>): void {
|
||||
super.updated(changedProperties);
|
||||
// The inner element gets focus, so it carries the state. Set it on every
|
||||
// update while pressed is in use, as the base class can render a new element.
|
||||
if (this.ariaPressed != null) {
|
||||
this.button.setAttribute("aria-pressed", this.ariaPressed);
|
||||
} else if (changedProperties.has("ariaPressed")) {
|
||||
this.button.removeAttribute("aria-pressed");
|
||||
}
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
Button.styles,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { repeat } from "lit/directives/repeat";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import {
|
||||
CameraEntityFeature,
|
||||
@@ -17,8 +17,16 @@ import {
|
||||
STREAM_TYPE_WEB_RTC,
|
||||
type CameraCapabilities,
|
||||
type CameraEntity,
|
||||
type StreamType,
|
||||
} from "../data/camera";
|
||||
import {
|
||||
computeCameraStreamStatus,
|
||||
MJPEG_STREAM,
|
||||
selectCameraStreams,
|
||||
type CameraStream,
|
||||
type CameraStreamStatus,
|
||||
type CameraStreamTracks,
|
||||
type CameraStreamType,
|
||||
} from "../data/camera-streams";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
@@ -26,17 +34,16 @@ import {
|
||||
formattersContext,
|
||||
} from "../data/context";
|
||||
import "./ha-hls-player";
|
||||
import type { HaHLSPlayer } from "./ha-hls-player";
|
||||
import "./ha-mjpeg-player";
|
||||
import type { HaMjpegPlayer } from "./ha-mjpeg-player";
|
||||
import "./ha-web-rtc-player";
|
||||
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
|
||||
|
||||
const MJPEG_STREAM = "mjpeg";
|
||||
|
||||
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
|
||||
|
||||
interface Stream {
|
||||
type: CameraStreamType;
|
||||
visible: boolean;
|
||||
}
|
||||
export type {
|
||||
CameraStreamStatus,
|
||||
CameraStreamType,
|
||||
} from "../data/camera-streams";
|
||||
|
||||
@customElement("ha-camera-stream")
|
||||
export class HaCameraStream extends LitElement {
|
||||
@@ -71,6 +78,13 @@ export class HaCameraStream extends LitElement {
|
||||
@property({ type: Boolean, attribute: "allow-exoplayer" })
|
||||
public allowExoPlayer = false;
|
||||
|
||||
/**
|
||||
* Shows an MJPEG stream in a player that can also open it picture in
|
||||
* picture, which copies its frames into a video while open.
|
||||
*/
|
||||
@property({ type: Boolean, attribute: "mjpeg-video" })
|
||||
public mjpegVideo = false;
|
||||
|
||||
// Video background image before its loaded
|
||||
@state() private _posterUrl?: string;
|
||||
|
||||
@@ -78,13 +92,30 @@ export class HaCameraStream extends LitElement {
|
||||
|
||||
@state() private _capabilities?: CameraCapabilities;
|
||||
|
||||
@state() private _hlsStreams?: { hasAudio: boolean; hasVideo: boolean };
|
||||
@state() private _hlsStreams?: CameraStreamTracks;
|
||||
|
||||
@state() private _webRtcStreams?: { hasAudio: boolean; hasVideo: boolean };
|
||||
@state() private _webRtcStreams?: CameraStreamTracks;
|
||||
|
||||
// Streams that played their first frame
|
||||
@state() private _loadedStreams: ReadonlySet<CameraStreamType> = new Set();
|
||||
|
||||
// The app plays the HLS stream in its own player, over the page
|
||||
@state() private _hlsInApp = false;
|
||||
|
||||
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
|
||||
|
||||
private _visibleStreamType?: Stream["type"];
|
||||
@query("ha-mjpeg-player") private _mjpegPlayer?: HaMjpegPlayer;
|
||||
|
||||
@query(
|
||||
"ha-hls-player:not(.hidden), ha-web-rtc-player:not(.hidden), ha-mjpeg-player"
|
||||
)
|
||||
private _visiblePlayer?: HaHLSPlayer | HaWebRtcPlayer | HaMjpegPlayer;
|
||||
|
||||
private _visibleStreamType?: CameraStreamType;
|
||||
|
||||
private _status?: CameraStreamStatus;
|
||||
|
||||
private _capabilitiesRequest = 0;
|
||||
|
||||
private _thumbnailApi = memoizeOne(
|
||||
(
|
||||
@@ -117,6 +148,17 @@ export class HaCameraStream extends LitElement {
|
||||
this._getCapabilities();
|
||||
this._getPosterUrl();
|
||||
}
|
||||
|
||||
const oldConnection = changedProps.get("_connection") as
|
||||
ContextType<typeof connectionContext> | undefined;
|
||||
if (
|
||||
oldConnection &&
|
||||
!oldConnection.connected &&
|
||||
this._connection.connected
|
||||
) {
|
||||
// An MJPEG stream doesn't come back on its own
|
||||
this._restartMjpeg();
|
||||
}
|
||||
}
|
||||
|
||||
/** The microphone track sent to the camera, only on WebRTC streams. */
|
||||
@@ -124,6 +166,22 @@ export class HaCameraStream extends LitElement {
|
||||
return this._webRtcPlayer?.microphoneTrack;
|
||||
}
|
||||
|
||||
/** The video of the shown stream. */
|
||||
public get videoElement(): HTMLVideoElement | undefined {
|
||||
return this._visiblePlayer?.videoElement;
|
||||
}
|
||||
|
||||
/** Opens the video of the shown stream picture in picture. */
|
||||
public async requestPictureInPicture() {
|
||||
const player = this._visiblePlayer;
|
||||
// An MJPEG stream first has to start copying its image into the video
|
||||
if (player && "requestPictureInPicture" in player) {
|
||||
await player.requestPictureInPicture();
|
||||
return;
|
||||
}
|
||||
await this.videoElement?.requestPictureInPicture();
|
||||
}
|
||||
|
||||
/** Toggles sending the microphone to the camera, only on WebRTC streams. */
|
||||
public async toggleMicrophone() {
|
||||
await this._webRtcPlayer?.toggleMicrophone();
|
||||
@@ -132,6 +190,10 @@ export class HaCameraStream extends LitElement {
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._connected = true;
|
||||
if (this.hasUpdated) {
|
||||
// The players start again when reattached, so their results do as well
|
||||
this._resetStreams();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
@@ -146,13 +208,33 @@ export class HaCameraStream extends LitElement {
|
||||
capabilities: this._capabilities,
|
||||
});
|
||||
}
|
||||
const visibleStreamType = this._currentStreams().find(
|
||||
(stream) => stream.visible
|
||||
)?.type;
|
||||
const streams = this._currentStreams();
|
||||
const visibleStreamType = streams.find((stream) => stream.visible)?.type;
|
||||
if (visibleStreamType !== this._visibleStreamType) {
|
||||
this._visibleStreamType = visibleStreamType;
|
||||
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
|
||||
}
|
||||
const status: CameraStreamStatus = {
|
||||
...computeCameraStreamStatus(
|
||||
streams,
|
||||
// Nothing plays while Home Assistant is disconnected
|
||||
this._connection.connected ? this._loadedStreams : new Set(),
|
||||
this._hlsStreams,
|
||||
this._webRtcStreams
|
||||
),
|
||||
inApp: visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp,
|
||||
};
|
||||
if (
|
||||
!this._status ||
|
||||
status.type !== this._status.type ||
|
||||
status.connecting !== this._status.connecting ||
|
||||
status.upgrading !== this._status.upgrading ||
|
||||
status.hasAudio !== this._status.hasAudio ||
|
||||
status.inApp !== this._status.inApp
|
||||
) {
|
||||
this._status = status;
|
||||
fireEvent(this, "camera-stream-status-changed", status);
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
@@ -167,19 +249,30 @@ export class HaCameraStream extends LitElement {
|
||||
)}`;
|
||||
}
|
||||
|
||||
private _renderStream(stream: Stream) {
|
||||
private _renderStream(stream: CameraStream) {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
if (stream.type === MJPEG_STREAM) {
|
||||
const mjpegPath = computeMJPEGStreamUrl(this.stateObj);
|
||||
const streamUrl = __DEMO__
|
||||
? this.stateObj.attributes.entity_picture
|
||||
: this._connected
|
||||
? computeMJPEGStreamUrl(this.stateObj)
|
||||
? // Like the other streams, as the frontend can be served elsewhere
|
||||
mjpegPath && this._connection.hassUrl(mjpegPath)
|
||||
: this._posterUrl;
|
||||
if (!streamUrl) {
|
||||
return nothing;
|
||||
}
|
||||
if (this.mjpegVideo) {
|
||||
return html`<ha-mjpeg-player
|
||||
.src=${streamUrl}
|
||||
.alt=${`Preview of the ${this._formatters?.formatEntityName(this.stateObj) ?? ""} camera.`}
|
||||
.aspectRatio=${this.aspectRatio}
|
||||
.fitMode=${this.fitMode}
|
||||
@load=${this._handleMjpegLoad}
|
||||
></ha-mjpeg-player>`;
|
||||
}
|
||||
return html`<img
|
||||
.src=${streamUrl}
|
||||
style=${styleMap({
|
||||
@@ -201,6 +294,8 @@ export class HaCameraStream extends LitElement {
|
||||
.entityid=${this.stateObj.entity_id}
|
||||
.posterUrl=${this._posterUrl}
|
||||
@streams=${this._handleHlsStreams}
|
||||
@load=${this._handleHlsLoad}
|
||||
@exoplayer-changed=${this._handleExoPlayerChanged}
|
||||
class=${stream.visible ? "" : "hidden"}
|
||||
.aspectRatio=${this.aspectRatio}
|
||||
.fitMode=${this.fitMode}
|
||||
@@ -216,6 +311,7 @@ export class HaCameraStream extends LitElement {
|
||||
.entityid=${this.stateObj.entity_id}
|
||||
.posterUrl=${this._posterUrl}
|
||||
@streams=${this._handleWebRtcStreams}
|
||||
@load=${this._handleWebRtcLoad}
|
||||
class=${stream.visible ? "" : "hidden"}
|
||||
.aspectRatio=${this.aspectRatio}
|
||||
.fitMode=${this.fitMode}
|
||||
@@ -229,15 +325,14 @@ export class HaCameraStream extends LitElement {
|
||||
return this._streams(
|
||||
this._capabilities?.frontend_stream_types,
|
||||
this._hlsStreams,
|
||||
this._webRtcStreams,
|
||||
this.muted
|
||||
this._webRtcStreams
|
||||
);
|
||||
}
|
||||
|
||||
private async _getCapabilities() {
|
||||
this._capabilities = undefined;
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
this._resetStreams();
|
||||
const request = ++this._capabilitiesRequest;
|
||||
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
|
||||
this._capabilities = {
|
||||
frontend_stream_types: [],
|
||||
@@ -245,10 +340,40 @@ export class HaCameraStream extends LitElement {
|
||||
};
|
||||
return;
|
||||
}
|
||||
this._capabilities = await fetchCameraCapabilities(
|
||||
const capabilities = await fetchCameraCapabilities(
|
||||
this._api,
|
||||
this.stateObj!.entity_id
|
||||
);
|
||||
if (request !== this._capabilitiesRequest) {
|
||||
return;
|
||||
}
|
||||
this._capabilities = capabilities;
|
||||
}
|
||||
|
||||
private _resetStreams() {
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
this._loadedStreams = new Set();
|
||||
this._hlsInApp = false;
|
||||
this._mjpegPlayer?.restart();
|
||||
}
|
||||
|
||||
private _restartMjpeg() {
|
||||
this._setLoaded(MJPEG_STREAM, false);
|
||||
this._mjpegPlayer?.restart();
|
||||
}
|
||||
|
||||
private _setLoaded(type: CameraStreamType, loaded: boolean) {
|
||||
if (this._loadedStreams.has(type) === loaded) {
|
||||
return;
|
||||
}
|
||||
const loadedStreams = new Set(this._loadedStreams);
|
||||
if (loaded) {
|
||||
loadedStreams.add(type);
|
||||
} else {
|
||||
loadedStreams.delete(type);
|
||||
}
|
||||
this._loadedStreams = loadedStreams;
|
||||
}
|
||||
|
||||
private async _getPosterUrl(): Promise<void> {
|
||||
@@ -266,98 +391,74 @@ export class HaCameraStream extends LitElement {
|
||||
}
|
||||
|
||||
private _handleImageLoad() {
|
||||
this._setLoaded(MJPEG_STREAM, true);
|
||||
fireEvent(this, "load");
|
||||
}
|
||||
|
||||
private _handleHlsStreams(ev: CustomEvent) {
|
||||
this._hlsStreams = ev.detail;
|
||||
private _handleMjpegLoad() {
|
||||
this._setLoaded(MJPEG_STREAM, true);
|
||||
}
|
||||
|
||||
private _handleWebRtcStreams(ev: CustomEvent) {
|
||||
private _handleHlsLoad() {
|
||||
this._setLoaded(STREAM_TYPE_HLS, true);
|
||||
}
|
||||
|
||||
private _handleExoPlayerChanged(
|
||||
ev: HASSDomEvent<HASSDomEvents["exoplayer-changed"]>
|
||||
) {
|
||||
this._hlsInApp = ev.detail.active;
|
||||
}
|
||||
|
||||
private _handleWebRtcLoad() {
|
||||
this._setLoaded(STREAM_TYPE_WEB_RTC, true);
|
||||
}
|
||||
|
||||
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
this._hlsStreams = ev.detail;
|
||||
if (!ev.detail.hasVideo) {
|
||||
this._setLoaded(STREAM_TYPE_HLS, false);
|
||||
}
|
||||
}
|
||||
|
||||
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
if (
|
||||
!ev.detail.hasVideo &&
|
||||
!ev.detail.hasAudio &&
|
||||
this._capabilities?.frontend_stream_types.length === 1 &&
|
||||
typeof RTCPeerConnection !== "undefined"
|
||||
) {
|
||||
// Without another stream type, keep the player to show why it failed.
|
||||
// Only a browser without WebRTC falls back to MJPEG.
|
||||
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
|
||||
return;
|
||||
}
|
||||
this._webRtcStreams = ev.detail;
|
||||
if (!ev.detail.hasVideo) {
|
||||
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
|
||||
}
|
||||
}
|
||||
|
||||
private _streams = memoizeOne(
|
||||
(
|
||||
supportedTypes?: StreamType[],
|
||||
hlsStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
muted?: boolean
|
||||
): Stream[] => {
|
||||
supportedTypes?: CameraCapabilities["frontend_stream_types"],
|
||||
hlsStreams?: CameraStreamTracks,
|
||||
webRtcStreams?: CameraStreamTracks
|
||||
): CameraStream[] => {
|
||||
if (__DEMO__) {
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
if (!supportedTypes) {
|
||||
return [];
|
||||
}
|
||||
if (supportedTypes.length === 0) {
|
||||
// doesn't support any stream type, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
if (supportedTypes.length === 1) {
|
||||
// only 1 stream type, no need to choose
|
||||
if (
|
||||
(supportedTypes[0] === STREAM_TYPE_HLS &&
|
||||
hlsStreams?.hasVideo === false) ||
|
||||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
|
||||
webRtcStreams?.hasVideo === false)
|
||||
) {
|
||||
// stream failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
return [{ type: supportedTypes[0], visible: true }];
|
||||
}
|
||||
if (hlsStreams && webRtcStreams) {
|
||||
// fully loaded
|
||||
if (
|
||||
hlsStreams.hasVideo &&
|
||||
hlsStreams.hasAudio &&
|
||||
!webRtcStreams.hasAudio &&
|
||||
!muted
|
||||
) {
|
||||
// webRTC stream is missing audio and audio is not muted, use HLS
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
if (webRtcStreams.hasVideo) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
// both streams failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
|
||||
if (hlsStreams?.hasVideo !== webRtcStreams?.hasVideo) {
|
||||
// one of the two streams is loaded, or errored
|
||||
// choose the one that has video or is still loading
|
||||
if (hlsStreams?.hasVideo) {
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
}
|
||||
if (hlsStreams?.hasVideo === false) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
if (webRtcStreams?.hasVideo) {
|
||||
return [
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: true },
|
||||
{ type: STREAM_TYPE_HLS, visible: false },
|
||||
];
|
||||
}
|
||||
if (webRtcStreams?.hasVideo === false) {
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
return selectCameraStreams({
|
||||
supportedTypes,
|
||||
hlsStreams,
|
||||
webRtcStreams,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
static styles = css`
|
||||
:host,
|
||||
img {
|
||||
img,
|
||||
ha-mjpeg-player {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@@ -389,6 +490,7 @@ declare global {
|
||||
load: undefined;
|
||||
"stream-type-changed": { type?: CameraStreamType };
|
||||
"camera-capabilities-changed": { capabilities?: CameraCapabilities };
|
||||
"camera-stream-status-changed": CameraStreamStatus;
|
||||
streams: {
|
||||
hasAudio: boolean;
|
||||
hasVideo: boolean;
|
||||
|
||||
@@ -33,6 +33,8 @@ class HaConfigNavigationList extends LitElement {
|
||||
return html`
|
||||
<ha-list-item-button
|
||||
.href=${externalApp ? undefined : page.path}
|
||||
.headline=${page.name}
|
||||
.supportingText=${this.hasSecondary ? page.description : undefined}
|
||||
@click=${externalApp ? this._handleExternalApp : undefined}
|
||||
>
|
||||
<ha-svg-icon
|
||||
@@ -43,14 +45,6 @@ class HaConfigNavigationList extends LitElement {
|
||||
.secondaryPath=${page.iconSecondaryPath}
|
||||
.viewBox=${page.iconViewBox}
|
||||
></ha-svg-icon>
|
||||
<span slot="headline">${page.name}</span>
|
||||
${
|
||||
this.hasSecondary
|
||||
? html`<span slot="supporting-text"
|
||||
>${page.description}</span
|
||||
>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
!this.narrow
|
||||
? html`<ha-icon-next slot="end"></ha-icon-next>`
|
||||
|
||||
@@ -387,7 +387,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyDown(e: KeyboardEvent) {
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
e.preventDefault();
|
||||
if (this._lastSlider) {
|
||||
this.shadowRoot?.getElementById(this._lastSlider)?.focus();
|
||||
@@ -439,7 +439,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyUp(e: KeyboardEvent) {
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
|
||||
e.preventDefault();
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
|
||||
Loaded 100 of 497 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user