mirror of
https://github.com/home-assistant/frontend.git
synced 2026-12-03 10:09:48 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0fe036f48 | ||
|
|
8823dce36c |
No files matched your search
@@ -1,43 +0,0 @@
|
||||
---
|
||||
name: ha-frontend-browser-checks
|
||||
description: Check a Home Assistant frontend change in a browser and show it in a pull request. Use when checking how a change looks or behaves at different screen sizes, in light and dark mode, right to left (RTL) or with long translations, or when taking before and after screenshots or recording a demo of a feature for a pull request.
|
||||
---
|
||||
|
||||
# HA Frontend Browser Checks
|
||||
|
||||
Use this skill to check a visible change in a browser and to show it in a pull request. Any browser tool you already have works if it can open a page, set its size, run a script in it, take screenshots and record video. Load `ha-frontend-testing` for the dev servers, and `ha-frontend-loading` for loading states.
|
||||
|
||||
Screenshots and recordings help reviewers see what changed, but they don't make a large change easy to review. [Keep pull requests small](https://contributors.home-assistant.io/start/pull-requests/#keep-it-small), and make sure you have reviewed and understood the change and can explain it, as the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks.
|
||||
|
||||
## Check Real Devices
|
||||
|
||||
Check the sizes the change affects rather than one fixed size, such as a phone, a tablet in both orientations, a laptop and a large desktop monitor. Include a small phone. Take each device's viewport in CSS pixels, its pixel ratio and touch support from the device presets your tools have, rather than from memory, and check the page really has that size once it's set.
|
||||
|
||||
## Check Light And Dark
|
||||
|
||||
When the change can look different in light and dark mode, such as a colour, border, background or image, check it in both. Switch the colour scheme in your browser tool, with the profile's theme following it, or pick light and dark in the profile. A fix for one mode only needs that mode.
|
||||
|
||||
## Check Right To Left (RTL)
|
||||
|
||||
Check layout, alignment, icons and anything with a direction in RTL. In the app, set your profile language to one written right to left, then set it back: many components take their direction from the language, so setting the page to RTL in your browser tool leaves them left to right. The gallery's RTL toggle checks styling only.
|
||||
|
||||
## Check Long Text
|
||||
|
||||
When a change adds or changes text, check it in a language with long words or long translations too, so labels, descriptions and buttons don't overflow or wrap badly. When the new string isn't translated yet, try a rough translation to check its length.
|
||||
|
||||
## Show It In The Pull Request
|
||||
|
||||
- When the change alters something that exists already, capture the same screen on `dev` and on your branch, in the same state, and put them side by side. Only a new screen, with nothing before it, needs just the after.
|
||||
- Keep the size of every capture fixed, screenshots as well as videos. Set the page size before you capture and don't change it in between, and capture the same area each time, so the subject sits in the same place in before and after. For a card or other part of the page, work out a fixed area around it for each size you test, and use that same area on both branches.
|
||||
- Say which device, size or mode each capture shows.
|
||||
- Make the change easy to see: capture the part of the screen it affects rather than a whole page where it's a few pixels.
|
||||
- Save captures outside the repository, so they can't be committed by accident.
|
||||
- Keep personal details out: use demo data, such as the demo or the Demo integration, and mask anything else before you capture, such as names, addresses, IP and MAC addresses, hostnames, serial numbers and tokens. Check each capture before you attach it.
|
||||
|
||||
Record a video when it shows the change better than a still, such as an animation, a drag, a loading sequence (hold the loading state as "Checking It" in `ha-frontend-loading` shows) or a flow across several screens. Keep each video short and small: GitHub limits upload sizes, and reviewers have to watch it. You can record it yourself with the tools you have; it doesn't need a person.
|
||||
|
||||
- Use the recording tools at hand: your browser tool's recorder for a page, or a desktop screen recorder for a window, such as a phone emulator, so the device frame shows.
|
||||
- Don't resize, zoom or take screenshots while recording, which redraw the page at another size and make the video jump.
|
||||
- Check the whole recording before you attach it. For a short clip, look at a frame every second or half second, not only the first and last, since the page can jump to another size partway through. Record again if it does. Take stills from the same frames, so they match the video.
|
||||
- Keep the window drawn on a screen. A hidden or minimised window records only a frame every few seconds.
|
||||
- Label each video, such as **Before** and **After**, and say what it shows and how you set it up. Say what you didn't record and why.
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: ha-frontend-components
|
||||
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
|
||||
description: Home Assistant frontend component patterns. Use when implementing or reviewing dialogs, ha-form, ha-alert, loading states, keyboard shortcuts, tooltips, panels, Lovelace cards, or ha-button usage.
|
||||
---
|
||||
|
||||
# HA Frontend Components
|
||||
@@ -93,7 +93,33 @@ html`
|
||||
|
||||
## Loading States
|
||||
|
||||
Load `ha-frontend-loading` for anything that shows while content loads: skeletons, spinners, loading buttons and fades.
|
||||
Pick the indicator by what is loading, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/):
|
||||
|
||||
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
|
||||
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
|
||||
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
|
||||
|
||||
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
|
||||
|
||||
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
|
||||
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
|
||||
- Don't fade in the loaded content itself.
|
||||
|
||||
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
|
||||
|
||||
```ts
|
||||
html`
|
||||
<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label=${this._i18n.localize("ui.common.loading")}
|
||||
>
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
</div>
|
||||
</ha-fade-in>
|
||||
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
|
||||
`;
|
||||
```
|
||||
|
||||
## Shortcuts And Tooltips
|
||||
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
---
|
||||
name: ha-frontend-loading
|
||||
description: Home Assistant frontend loading states. Use when adding, changing or reviewing anything that shows while content loads, such as a skeleton, spinner, loading button or loading fade, or when checking how a screen looks while it loads.
|
||||
---
|
||||
|
||||
# HA Frontend Loading
|
||||
|
||||
Use this skill for every loading state, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/). A loading state always ends in the content, an empty state, or an error.
|
||||
|
||||
## Pick The Indicator
|
||||
|
||||
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`, `ha-skeleton-log`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
|
||||
- Use `ha-skeleton-overlay` when the content renders before its data arrives, such as a card or badge, or when content reloads over what's already shown. See [Skeleton Overlay](#skeleton-overlay).
|
||||
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
|
||||
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
|
||||
|
||||
## The Wave
|
||||
|
||||
Every skeleton uses the same soft wave (`ha-skeleton`'s default `effect="sheen"`). It's one slanted wave across all the skeletons on the page, from the top corner of the content on the side text starts from to the opposite bottom corner, which each skeleton shows its slice of, on one shared clock. It flows from one skeleton into the next, starts its next sweep as soon as it leaves the content, and a skeleton added mid-sweep joins in rather than starting over. Reduced motion stops it.
|
||||
|
||||
Don't change the effect or speed (`--ha-skeleton-duration`) for one component.
|
||||
|
||||
## Showing A Skeleton
|
||||
|
||||
Make the skeleton the same shape and size as the content it stands for: one text skeleton per line of text, an icon skeleton per icon, a block per image or chart.
|
||||
|
||||
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
|
||||
|
||||
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
|
||||
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
|
||||
- Don't add your own fade to loaded content. `ha-skeleton-overlay` fades each part in over `--ha-animation-duration-fast`, which reduced motion makes instant.
|
||||
|
||||
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text.
|
||||
|
||||
```ts
|
||||
html`
|
||||
<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label=${this._i18n.localize("ui.common.loading")}
|
||||
>
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
</div>
|
||||
</ha-fade-in>
|
||||
<ha-fade-in .delay=${500}><ha-spinner></ha-spinner></ha-fade-in>
|
||||
`;
|
||||
```
|
||||
|
||||
## Skeleton Overlay
|
||||
|
||||
`ha-skeleton-overlay` reads a skeleton from the content it wraps, so it can't drift from it: each text line, icon, image, control and drawing gets its own piece, and the real parts are hidden underneath until loading ends. Prefer it to drawing a skeleton by hand whenever the content can render before its data.
|
||||
|
||||
```ts
|
||||
html`
|
||||
<ha-skeleton-overlay .loading=${this._loading}>
|
||||
<my-content></my-content>
|
||||
</ha-skeleton-overlay>
|
||||
`;
|
||||
```
|
||||
|
||||
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it.
|
||||
- Mark parts that shouldn't be read with `data-skeleton`: `none` leaves an element out and showing, `keep` leaves it showing but reads what's inside, and `text`, `round` or `block` force one piece of that kind. Skeletons the content draws itself are left alone.
|
||||
- Put your own skeleton in the `skeleton` slot to replace the reading altogether.
|
||||
- Call `refresh()` when the content changes without changing size.
|
||||
- It gives the skeleton the `progressbar` role and the translated label itself.
|
||||
|
||||
## Checking It
|
||||
|
||||
Check a loading state in the browser, not only by reading the code. These work on any setup: a dev server, the demo, or the gallery.
|
||||
|
||||
- **Hold the loading state.** Home Assistant's data comes over the WebSocket, which DevTools network throttling doesn't slow. Hold the replies back from the console instead, then open the screen from inside the app (not a reload, which drops the patch). Adjust the pattern to the messages the screen waits on:
|
||||
|
||||
```js
|
||||
const conn = document.querySelector("home-assistant").hass.connection;
|
||||
const slow = (type = "") => /^(recorder|history|logbook)\//.test(type);
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const send = conn.sendMessagePromise.bind(conn);
|
||||
conn.sendMessagePromise = async (msg) => {
|
||||
const result = await send(msg);
|
||||
if (slow(msg.type)) await wait(3000);
|
||||
return result;
|
||||
};
|
||||
const subscribe = conn.subscribeMessage.bind(conn);
|
||||
conn.subscribeMessage = (callback, msg, options) => {
|
||||
if (!slow(msg.type)) return subscribe(callback, msg, options);
|
||||
const due = Date.now() + 3000;
|
||||
const later = (message) =>
|
||||
setTimeout(() => callback(message), Math.max(0, due - Date.now()));
|
||||
return subscribe(later, msg, options);
|
||||
};
|
||||
```
|
||||
|
||||
- **Compare the skeleton with the content.** It should take the same space, so nothing moves when the content arrives. Measure the wrapper's height while loading and once loaded (`element.getBoundingClientRect().height` in the console), or take a screenshot of each at the same size and flick between them. Look for pieces that are missing, extra or in the wrong place, and fix those with `data-skeleton`.
|
||||
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
|
||||
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
|
||||
@@ -20,7 +20,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
|
||||
- Do not omit, reorder, or rewrite template sections.
|
||||
- Check the appropriate "Type of change" box based on the actual change.
|
||||
- Do not check checklist items on behalf of the user.
|
||||
- If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
|
||||
- If the PR includes UI changes, remind the user to add screenshots or a short video.
|
||||
- Explain what the change does for users, not only implementation details.
|
||||
- Use Markdown.
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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.5.1
|
||||
GH_ACTIONS_LOCK_VERSION: v0.4.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@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
|
||||
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
'.github/workflows/copilot-setup-steps.yml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
@@ -29,7 +29,7 @@ workflows:
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/dependency-review.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec'
|
||||
- 'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
'.github/workflows/design_deployment.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
@@ -64,13 +64,13 @@ workflows:
|
||||
'.github/workflows/relative-ci.yaml':
|
||||
- 'relative-ci/agent-action@711f3a8fa1b928e6afde280011110c9b0a224a60'
|
||||
'.github/workflows/release-drafter.yaml':
|
||||
- 'release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea'
|
||||
- 'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0'
|
||||
'.github/workflows/release.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
|
||||
- 'home-assistant/actions@2026.11.0'
|
||||
- 'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361'
|
||||
- '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@3ffccacd46053766916f087ce41d627c0b8cf2d1'
|
||||
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
'.github/workflows/sync-sensor-entity-constants.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1'
|
||||
- 'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
'.github/workflows/translations.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
dependencies:
|
||||
@@ -101,9 +101,9 @@ dependencies:
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec':
|
||||
ref: 'v5.0.1'
|
||||
commit: 'sha1-bbc44d14a204704ccc493733616cd1e93a0321ec'
|
||||
'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294':
|
||||
ref: 'v5.0.0'
|
||||
commit: 'sha1-a1d282b36b6f3519aa1f3fc636f609c47dddb294'
|
||||
owner_id: 44036562
|
||||
repo_id: 476372928
|
||||
'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333':
|
||||
@@ -151,14 +151,14 @@ dependencies:
|
||||
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
owner_id: 7513068
|
||||
repo_id: 113918130
|
||||
'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea':
|
||||
ref: 'v4.39.4'
|
||||
commit: 'sha1-1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
|
||||
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
|
||||
ref: 'v4.39.1'
|
||||
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/actions@2026.11.0':
|
||||
ref: '2026.11.0'
|
||||
commit: 'sha1-07f46fd2e19967768b5fd3000f91f857452b767c'
|
||||
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
|
||||
ref: 'master'
|
||||
commit: 'sha1-86d4564712fa02543c808e3a693dd04f9d3f8361'
|
||||
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@3ffccacd46053766916f087ce41d627c0b8cf2d1':
|
||||
ref: 'v8.1.3'
|
||||
commit: 'sha1-3ffccacd46053766916f087ce41d627c0b8cf2d1'
|
||||
'peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1':
|
||||
ref: 'v8.1.1'
|
||||
commit: 'sha1-5f6978faf089d4d20b00c7766989d076bb2fc7f1'
|
||||
owner_id: 18365890
|
||||
repo_id: 197176365
|
||||
'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086':
|
||||
@@ -183,8 +183,8 @@ dependencies:
|
||||
commit: 'sha1-711f3a8fa1b928e6afde280011110c9b0a224a60'
|
||||
owner_id: 43522883
|
||||
repo_id: 398376354
|
||||
'release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea':
|
||||
ref: 'v7.11.0'
|
||||
commit: 'sha1-d1a19e60e81a7e650d00a7de9277f87e439117ea'
|
||||
'release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0':
|
||||
ref: 'v7.10.0'
|
||||
commit: 'sha1-978bb0b30c5ee8cdd332ced253758157150d43f0'
|
||||
owner_id: 58292376
|
||||
repo_id: 139022359
|
||||
@@ -32,12 +32,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
languages: javascript-typescript
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
category: "/language:javascript-typescript"
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
contents: read # To compare the dependency graph between base and head
|
||||
steps:
|
||||
- name: Dependency review
|
||||
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1
|
||||
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
|
||||
with:
|
||||
license-check: false # Covered by pnpm lint:licenses
|
||||
fail-on-severity: high
|
||||
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
name: Prepare container dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
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.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
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.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
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.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
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@d1a19e60e81a7e650d00a7de9277f87e439117ea # v7.11.0
|
||||
- uses: release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0 # v7.10.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@2026.11.0
|
||||
uses: home-assistant/actions/helpers/verify-version@86d4564712fa02543c808e3a693dd04f9d3f8361 # master
|
||||
|
||||
- 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@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
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@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
with:
|
||||
branch: chore/sync-sensor-entity-constants
|
||||
commit-message: Update sensor entity constants
|
||||
|
||||
@@ -40,8 +40,7 @@ Never run `tsc` or `pnpm lint:types` with file arguments. When `tsc` receives fi
|
||||
Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching skill before detailed implementation or review. For reviews, load `ha-frontend-review` alongside all companions that apply to the changed code or behavior:
|
||||
|
||||
- `ha-frontend-contexts`: Lit contexts, `hass` migration, and rerender-sensitive state access.
|
||||
- `ha-frontend-components`: dialogs, forms, alerts, shortcuts, tooltips, panels, and Lovelace cards.
|
||||
- `ha-frontend-loading`: loading states, skeletons, spinners, loading fades, and checking how a screen looks while it loads.
|
||||
- `ha-frontend-components`: dialogs, forms, alerts, loading states, shortcuts, tooltips, panels, and Lovelace cards.
|
||||
- `ha-frontend-events`: event handler typing, custom event dispatch, and event-map declarations.
|
||||
- `ha-frontend-types`: backend data contracts, optional schemas, shared types, assertions, and lifecycle types.
|
||||
- `ha-frontend-lit`: reactive fields, DOM queries, lifecycle behavior, and render-derived state.
|
||||
@@ -53,11 +52,10 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
|
||||
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
|
||||
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
|
||||
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
|
||||
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
|
||||
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, remind the user to add screenshots or a short video.
|
||||
|
||||
## AI policy
|
||||
|
||||
|
||||
@@ -157,99 +157,6 @@ 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 {
|
||||
@@ -286,24 +193,52 @@ gulp.task("fetch-lokalise", async function () {
|
||||
await Promise.all(
|
||||
projects.map(async ([project, projectId]) => {
|
||||
try {
|
||||
const [files, drafts] = await Promise.all([
|
||||
exportTranslations(lokaliseApi, projectId),
|
||||
project === "frontend"
|
||||
? fetchDrafts(lokaliseApi, projectId)
|
||||
: undefined,
|
||||
]);
|
||||
if (drafts) {
|
||||
acceptDrafts(files, drafts);
|
||||
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());
|
||||
|
||||
await mkdirPromise;
|
||||
await Promise.all(
|
||||
Object.entries(files).map(([filename, content]) =>
|
||||
fs.writeFile(path.join(inDir, project, filename), content, {
|
||||
flag: "w",
|
||||
encoding,
|
||||
})
|
||||
)
|
||||
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 }
|
||||
);
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
@@ -198,7 +198,10 @@ async function fetchTranslations(currentArtifact: Artifact | null) {
|
||||
console.log("Unpacking downloaded translations...");
|
||||
const zip = await jszip.loadAsync(downloadResponse.data as ArrayBuffer);
|
||||
await deleteCurrent;
|
||||
await extract({ input: await zip.file(/.*/)[0].async("uint8array") });
|
||||
const extractStream = zip.file(/.*/)[0].nodeStream().pipe(extract());
|
||||
await new Promise((resolve, reject) => {
|
||||
extractStream.on("close", resolve).on("error", reject);
|
||||
});
|
||||
|
||||
// Record the artifact only after successful extraction, so a failed fetch
|
||||
// is retried by the next build instead of being considered current.
|
||||
|
||||
@@ -69,6 +69,10 @@ async function copyMapPanel(staticDir) {
|
||||
npmPath("leaflet/dist/leaflet.css"),
|
||||
staticPath("images/leaflet/")
|
||||
);
|
||||
copyFileDir(
|
||||
npmPath("leaflet.markercluster/dist/MarkerCluster.css"),
|
||||
staticPath("images/leaflet/")
|
||||
);
|
||||
fs.copySync(
|
||||
npmPath("leaflet/dist/images"),
|
||||
staticPath("images/leaflet/images/")
|
||||
|
||||
@@ -25,7 +25,13 @@ const NOTICE_FILES = [path.join(NODE_MODULES, "echarts/NOTICE")];
|
||||
// that the new version's license still matches. The build will fail if
|
||||
// the pinned version is no longer installed.
|
||||
const LICENSE_OVERRIDES = [
|
||||
// No entries currently needed.
|
||||
{
|
||||
// type-fest ships two license files (MIT for code, CC0 for types).
|
||||
// We use the MIT license since that covers the bundled code.
|
||||
packageName: "type-fest",
|
||||
version: "5.10.0",
|
||||
licenseFile: "license-mit",
|
||||
},
|
||||
];
|
||||
|
||||
// Locate the directory of an installed package matching an exact version.
|
||||
|
||||
@@ -50,9 +50,7 @@ const convertToJSON = async (
|
||||
const encodedData = localeData.match(
|
||||
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
|
||||
)?.groups?.data;
|
||||
localeData =
|
||||
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
|
||||
firstBlock.match(dataRegex)?.groups?.data;
|
||||
localeData = firstBlock.match(dataRegex)?.groups?.data;
|
||||
if (!localeData && !encodedData) {
|
||||
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
|
||||
}
|
||||
|
||||
@@ -508,8 +508,12 @@ const createRspackConfig = ({
|
||||
"@formatjs/intl-locale/should-polyfill.js",
|
||||
"@formatjs/intl-locale/polyfill-force":
|
||||
"@formatjs/intl-locale/polyfill-force.js",
|
||||
"@formatjs/intl-numberformat/should-polyfill":
|
||||
"@formatjs/intl-numberformat/should-polyfill.js",
|
||||
"@formatjs/intl-numberformat/polyfill-force":
|
||||
"@formatjs/intl-numberformat/polyfill-force.js",
|
||||
"@formatjs/intl-pluralrules/should-polyfill":
|
||||
"@formatjs/intl-pluralrules/should-polyfill.js",
|
||||
"@formatjs/intl-pluralrules/polyfill-force":
|
||||
"@formatjs/intl-pluralrules/polyfill-force.js",
|
||||
"@formatjs/intl-relativetimeformat/should-polyfill":
|
||||
|
||||
@@ -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 Link by Nabu Casa</a
|
||||
>Home Assistant Cloud by Nabu Casa</a
|
||||
>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
|
||||
:host {
|
||||
display: block;
|
||||
height: 100vh;
|
||||
background-color: var(--primary-background-color, #f2f4f9);
|
||||
background-color: #f2f4f9;
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
}
|
||||
.container {
|
||||
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
|
||||
object-fit: cover;
|
||||
}
|
||||
.status {
|
||||
color: var(--primary-text-color, #1d2126);
|
||||
color: #1d2126;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -73,8 +73,7 @@ class HcLovelace extends LitElement {
|
||||
|
||||
if (index !== undefined) {
|
||||
const title = getPanelTitleFromUrlPath(
|
||||
this.hass.localize,
|
||||
this.hass.panels,
|
||||
this.hass,
|
||||
this.urlPath || "lovelace"
|
||||
);
|
||||
|
||||
|
||||
@@ -355,8 +355,7 @@ export class HcMain extends HassElement {
|
||||
|
||||
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
|
||||
const title = getPanelTitleFromUrlPath(
|
||||
this.hass!.localize,
|
||||
this.hass!.panels,
|
||||
this.hass!,
|
||||
this._urlPath || "lovelace"
|
||||
);
|
||||
castContext.setApplicationState(title || "");
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.1 KiB |
@@ -1,6 +1,7 @@
|
||||
import type { DemoConfig } from "../types";
|
||||
import { demoEntitiesArsaboo } from "./entities";
|
||||
import { demoLovelaceArsaboo } from "./lovelace";
|
||||
import { demoThemeArsaboo } from "./theme";
|
||||
|
||||
export const demoArsaboo: DemoConfig = {
|
||||
authorName: "Arsaboo",
|
||||
@@ -8,5 +9,5 @@ export const demoArsaboo: DemoConfig = {
|
||||
name: "ARS Home",
|
||||
lovelace: demoLovelaceArsaboo,
|
||||
entities: demoEntitiesArsaboo,
|
||||
theme: { theme: "default", dark: false },
|
||||
theme: demoThemeArsaboo,
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export const demoThemeArsaboo = () => ({});
|
||||
@@ -13,13 +13,8 @@ import type { EntityInput } from "../../../src/fake_data/entities/types";
|
||||
import type { DemoAutomation, DemoConfig, DemoTheme } from "./types";
|
||||
|
||||
export const applyDemoTheme = (hass: MockHomeAssistant, theme: DemoTheme) => {
|
||||
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 }
|
||||
);
|
||||
if (typeof theme === "function") {
|
||||
hass.mockTheme(theme());
|
||||
return;
|
||||
}
|
||||
hass.mockTheme(null, getDemoTheme(theme));
|
||||
|
||||
@@ -48,8 +48,6 @@ class DemoHomeDashboardStrategy extends ReactiveElement {
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
static getConfigElement = HomeDashboardStrategy.getConfigElement;
|
||||
}
|
||||
|
||||
class DemoHomeOverviewViewStrategy extends ReactiveElement {
|
||||
|
||||
+1061
-924
File diff suppressed because it is too large.
Load diff
@@ -1,33 +1,28 @@
|
||||
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)",
|
||||
},
|
||||
};
|
||||
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",
|
||||
});
|
||||
@@ -1,31 +1,29 @@
|
||||
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: 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",
|
||||
},
|
||||
};
|
||||
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",
|
||||
});
|
||||
@@ -1,23 +1,18 @@
|
||||
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)",
|
||||
},
|
||||
};
|
||||
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)",
|
||||
});
|
||||
@@ -7,13 +7,7 @@ import type { ThemeSettings } from "../../../src/types";
|
||||
import type { DemoArea } from "../stubs/area_registry";
|
||||
import type { DemoFloor } from "../stubs/floor_registry";
|
||||
|
||||
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 type DemoTheme = ThemeSettings | (() => Record<string, string> | null);
|
||||
|
||||
export interface DemoAutomation {
|
||||
config: ManualAutomationConfig & { id: string; alias: string };
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/* 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);
|
||||
@@ -0,0 +1,198 @@
|
||||
/* 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");
|
||||
}
|
||||
@@ -207,7 +207,6 @@ export class HaEmbedProvider extends LitElement {
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
fixed_cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
this._applyColorScheme();
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
const pipelines: AssistPipeline[] = [
|
||||
{
|
||||
id: "01home_assistant_cloud",
|
||||
name: "Home Assistant Link",
|
||||
name: "Home Assistant Cloud",
|
||||
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 Link" },
|
||||
{ agent_id: "cloud.cloud", name: "Home Assistant Cloud" },
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
export const mockConfig = (hass: MockHomeAssistant) => {
|
||||
hass.mockWS<typeof validateConfig>("validate_config", () => ({
|
||||
actions: { valid: true, error: null, errors: [] },
|
||||
conditions: { valid: true, error: null, errors: [] },
|
||||
triggers: { valid: true, error: null, errors: [] },
|
||||
actions: { valid: true, error: null },
|
||||
conditions: { valid: true, error: null },
|
||||
triggers: { valid: true, error: null },
|
||||
}));
|
||||
};
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
const prefs: EnergyPreferences = {
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
|
||||
energy_sources: [
|
||||
{
|
||||
type: "grid",
|
||||
@@ -21,6 +21,7 @@ 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",
|
||||
@@ -33,6 +34,7 @@ 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",
|
||||
@@ -46,23 +48,6 @@ 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",
|
||||
@@ -120,20 +105,16 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
fixed_costs: [],
|
||||
};
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
fixed_cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
hass.mockWS("energy/validate", () => ({
|
||||
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(() => []),
|
||||
fixed_costs: prefs.fixed_costs.map(() => []),
|
||||
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 }, () => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -1,30 +1,3 @@
|
||||
// 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": {
|
||||
@@ -61,31 +34,6 @@ 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",
|
||||
@@ -186,29 +134,6 @@ 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,4 +1,3 @@
|
||||
import type { ValidSystemDataKey } from "../../../src/data/frontend";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import type { ThemeSettings } from "../../../src/types";
|
||||
|
||||
@@ -58,40 +57,14 @@ 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",
|
||||
({ 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 }));
|
||||
(_msg, currentHass, onChange) => {
|
||||
onChange?.({
|
||||
value: currentHass.systemData,
|
||||
});
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
return () => {};
|
||||
}
|
||||
);
|
||||
hass.mockWS("labs/subscribe", (_msg, _currentHass, onChange) => {
|
||||
@@ -104,6 +77,7 @@ 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);
|
||||
};
|
||||
@@ -22,14 +22,6 @@ const baseRepository = {
|
||||
status: "default" as const,
|
||||
};
|
||||
|
||||
// The names of the connectivity of the demo repositories. Home Assistant
|
||||
// translates them, the mocked hass has no backend translations.
|
||||
export const marketplaceBackendTranslations = {
|
||||
"component.homeassistant.integration_connectivity.mqtt.name": "MQTT",
|
||||
"component.homeassistant.integration_connectivity.network.name":
|
||||
"Local network",
|
||||
};
|
||||
|
||||
const repositories: RepositoryBase[] = [
|
||||
{
|
||||
...baseRepository,
|
||||
@@ -40,7 +32,6 @@ const repositories: RepositoryBase[] = [
|
||||
description: "Watch camera streams with low latency through WebRTC.",
|
||||
authors: ["@AlexxIT"],
|
||||
domain: "webrtc",
|
||||
connectivity: ["network"],
|
||||
config_flow: true,
|
||||
available_version: "v3.6.1",
|
||||
downloads: 98000,
|
||||
@@ -77,7 +68,6 @@ const repositories: RepositoryBase[] = [
|
||||
description: "Use the cameras and events of a Frigate NVR.",
|
||||
authors: ["@blakeblackshear", "@dermotduffy", "@NickM-27"],
|
||||
domain: "frigate",
|
||||
connectivity: ["network", "mqtt"],
|
||||
config_flow: true,
|
||||
available_version: "v5.9.0",
|
||||
installed: true,
|
||||
|
||||
@@ -351,26 +351,6 @@ 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(
|
||||
@@ -395,22 +375,15 @@ 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];
|
||||
statistics[id] = scaleStats(source, price);
|
||||
} else if (id in derivedBatteryFlows) {
|
||||
const { source, share } = derivedBatteryFlows[id];
|
||||
statistics[id] = scaleStats(source, share);
|
||||
let cost = 0;
|
||||
statistics[id] = getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * price;
|
||||
cost += change;
|
||||
return { ...statistic, change, state: cost, sum: cost };
|
||||
});
|
||||
} else if (id in statisticsFunctions) {
|
||||
statistics[id] = getStats(id);
|
||||
} else {
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
import { durationDataToSeconds } from "../../../src/common/datetime/duration_to_seconds";
|
||||
import type {
|
||||
TimerListMessage,
|
||||
TimerListTimer,
|
||||
} from "../../../src/data/timer_list";
|
||||
import { timerListTimerRemaining } from "../../../src/data/timer_list";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
export interface MockTimerListTimer {
|
||||
name?: string;
|
||||
// Seconds
|
||||
duration: number;
|
||||
remaining?: number;
|
||||
paused?: boolean;
|
||||
finished?: boolean;
|
||||
}
|
||||
|
||||
type ChangeEventType = Extract<
|
||||
TimerListMessage,
|
||||
{ type: "change" }
|
||||
>["event_type"];
|
||||
|
||||
// Keeps the timers in memory, so the timer list actions work in demos.
|
||||
// Returns a function that stops the mock.
|
||||
export const mockTimerList = (
|
||||
hass: MockHomeAssistant,
|
||||
lists: Record<string, MockTimerListTimer[]>
|
||||
) => {
|
||||
let nextId = 0;
|
||||
const listeners: Record<
|
||||
string,
|
||||
Set<(message: TimerListMessage) => void>
|
||||
> = {};
|
||||
|
||||
const createTimer = (
|
||||
duration: number,
|
||||
name?: string,
|
||||
remaining = duration,
|
||||
paused = false
|
||||
): TimerListTimer => ({
|
||||
timer_id: `timer-${nextId++}`,
|
||||
name: name ?? null,
|
||||
status: paused ? "paused" : "active",
|
||||
created_duration: duration,
|
||||
total_duration: duration,
|
||||
created_at: new Date().toISOString(),
|
||||
finishes_at: paused
|
||||
? null
|
||||
: new Date(Date.now() + remaining * 1000).toISOString(),
|
||||
paused_remaining: paused ? remaining : null,
|
||||
ended_at: null,
|
||||
remaining,
|
||||
});
|
||||
|
||||
const timers: Record<string, TimerListTimer[]> = Object.fromEntries(
|
||||
Object.entries(lists).map(([entityId, seeds]) => [
|
||||
entityId,
|
||||
seeds.map((seed) => {
|
||||
const timer = createTimer(
|
||||
seed.duration,
|
||||
seed.name,
|
||||
seed.remaining,
|
||||
seed.paused
|
||||
);
|
||||
return seed.finished
|
||||
? {
|
||||
...timer,
|
||||
status: "finished" as const,
|
||||
finishes_at: null,
|
||||
ended_at: timer.created_at,
|
||||
remaining: 0,
|
||||
}
|
||||
: timer;
|
||||
}),
|
||||
])
|
||||
);
|
||||
|
||||
const change = (
|
||||
entityId: string,
|
||||
timer: TimerListTimer,
|
||||
eventType: ChangeEventType
|
||||
) => {
|
||||
timers[entityId] = (timers[entityId] ?? []).filter(
|
||||
(item) => item.timer_id !== timer.timer_id
|
||||
);
|
||||
if (eventType !== "removed") {
|
||||
timers[entityId].push(timer);
|
||||
}
|
||||
listeners[entityId]?.forEach((listener) =>
|
||||
listener({ type: "change", event_type: eventType, timer })
|
||||
);
|
||||
hass.mockEntities[entityId].update({
|
||||
state: String(
|
||||
timers[entityId].filter((item) => item.status === "active").length
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const end = (
|
||||
entityId: string,
|
||||
timer: TimerListTimer,
|
||||
status: "finished" | "cancelled"
|
||||
) =>
|
||||
change(
|
||||
entityId,
|
||||
{
|
||||
...timer,
|
||||
status,
|
||||
finishes_at: null,
|
||||
paused_remaining: null,
|
||||
ended_at: new Date().toISOString(),
|
||||
remaining: 0,
|
||||
},
|
||||
status
|
||||
);
|
||||
|
||||
const setRemaining = (
|
||||
entityId: string,
|
||||
timer: TimerListTimer,
|
||||
remaining: number,
|
||||
paused: boolean,
|
||||
eventType: ChangeEventType
|
||||
) =>
|
||||
change(
|
||||
entityId,
|
||||
{
|
||||
...timer,
|
||||
status: paused ? "paused" : "active",
|
||||
finishes_at: paused
|
||||
? null
|
||||
: new Date(Date.now() + remaining * 1000).toISOString(),
|
||||
paused_remaining: paused ? remaining : null,
|
||||
total_duration: Math.max(timer.total_duration, Math.ceil(remaining)),
|
||||
remaining,
|
||||
},
|
||||
eventType
|
||||
);
|
||||
|
||||
const mockTimerService = (
|
||||
service: string,
|
||||
handler: (
|
||||
entityId: string,
|
||||
timer: TimerListTimer,
|
||||
data: Record<string, any>
|
||||
) => void
|
||||
) =>
|
||||
hass.mockService("timer_list", service, (data, target) => {
|
||||
const entityId: string = target!.entity_id;
|
||||
const timer = timers[entityId].find(
|
||||
(item) => item.timer_id === data!.timer_id
|
||||
);
|
||||
if (timer) {
|
||||
handler(entityId, timer, data!);
|
||||
}
|
||||
});
|
||||
|
||||
hass.mockService("timer_list", "create_timer", (data, target) =>
|
||||
change(
|
||||
target!.entity_id,
|
||||
createTimer(durationDataToSeconds(data!.duration), data!.name),
|
||||
"created"
|
||||
)
|
||||
);
|
||||
mockTimerService("pause_timer", (entityId, timer) =>
|
||||
setRemaining(
|
||||
entityId,
|
||||
timer,
|
||||
timerListTimerRemaining(timer),
|
||||
true,
|
||||
"paused"
|
||||
)
|
||||
);
|
||||
mockTimerService("unpause_timer", (entityId, timer) =>
|
||||
setRemaining(
|
||||
entityId,
|
||||
timer,
|
||||
timerListTimerRemaining(timer),
|
||||
false,
|
||||
"unpaused"
|
||||
)
|
||||
);
|
||||
mockTimerService("cancel_timer", (entityId, timer) =>
|
||||
end(entityId, timer, "cancelled")
|
||||
);
|
||||
mockTimerService("remove_timer", (entityId, timer) =>
|
||||
change(entityId, timer, "removed")
|
||||
);
|
||||
mockTimerService("add_time", (entityId, timer, data) =>
|
||||
setRemaining(
|
||||
entityId,
|
||||
timer,
|
||||
timerListTimerRemaining(timer) + durationDataToSeconds(data.duration),
|
||||
timer.status === "paused",
|
||||
"time_changed"
|
||||
)
|
||||
);
|
||||
|
||||
hass.mockWS("timer_list/item/subscribe", (msg, _hass, onChange) => {
|
||||
const entityId: string = msg.entity_id;
|
||||
listeners[entityId] ??= new Set();
|
||||
listeners[entityId].add(onChange!);
|
||||
onChange!({ type: "timers", timers: timers[entityId] ?? [] });
|
||||
return () => listeners[entityId].delete(onChange!);
|
||||
});
|
||||
|
||||
const interval = window.setInterval(() => {
|
||||
for (const [entityId, items] of Object.entries(timers)) {
|
||||
for (const timer of items) {
|
||||
if (timer.status === "active" && !timerListTimerRemaining(timer)) {
|
||||
end(entityId, timer, "finished");
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return () => window.clearInterval(interval);
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { LocalizeFunc } from "../../../src/common/translations/localize";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import { connectivityBackendTranslations } from "./connectivity/fixtures";
|
||||
import { marketplaceBackendTranslations } from "./marketplace";
|
||||
|
||||
export const mockTranslations = (
|
||||
hass: MockHomeAssistant,
|
||||
@@ -21,11 +20,7 @@ export const mockTranslations = (
|
||||
// this merges on top of them.
|
||||
(localizePromise ?? Promise.resolve()).then(() =>
|
||||
hass.addTranslations(
|
||||
Object.assign(
|
||||
{},
|
||||
...Object.values(connectivityBackendTranslations),
|
||||
marketplaceBackendTranslations
|
||||
)
|
||||
Object.assign({}, ...Object.values(connectivityBackendTranslations))
|
||||
)
|
||||
);
|
||||
};
|
||||
+1
-2
@@ -144,7 +144,6 @@ export default [
|
||||
"iframe-card",
|
||||
"markdown-card",
|
||||
"todo-list-card",
|
||||
"timer-list-card",
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -172,7 +171,7 @@ export default [
|
||||
},
|
||||
{
|
||||
header: "Inputs and values",
|
||||
pages: ["input-number", "input-text", "number", "timer", "timer-list"],
|
||||
pages: ["input-number", "input-text", "number", "timer"],
|
||||
},
|
||||
{
|
||||
header: "Time and schedules",
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { html, css, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import "../../../src/components/ha-switch";
|
||||
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import "./demo-card";
|
||||
import type { DemoCardConfig } from "./demo-card";
|
||||
@@ -16,16 +14,6 @@ class DemoCards extends LitElement {
|
||||
|
||||
@state() private _showConfig = false;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
// Handles card actions like the app's action mixin
|
||||
this.addEventListener("hass-action", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
|
||||
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<ha-demo-options>
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import type { MockTimerListTimer } from "../../../demo/src/stubs/timer_list";
|
||||
|
||||
export const TIMER_LIST_ENTITIES = [
|
||||
{
|
||||
entity_id: "timer_list.kitchen",
|
||||
state: "2",
|
||||
attributes: {
|
||||
friendly_name: "Kitchen timers",
|
||||
supported_features: 63,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "timer_list.empty",
|
||||
state: "0",
|
||||
attributes: {
|
||||
friendly_name: "Empty timer list",
|
||||
supported_features: 63,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "timer_list.read_only",
|
||||
state: "1",
|
||||
attributes: {
|
||||
friendly_name: "Read-only timers",
|
||||
supported_features: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "timer_list.unavailable",
|
||||
state: "unavailable",
|
||||
attributes: {
|
||||
friendly_name: "Unavailable timer list",
|
||||
supported_features: 63,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const TIMER_LIST_TIMERS: Record<string, MockTimerListTimer[]> = {
|
||||
"timer_list.kitchen": [
|
||||
{ name: "Eggs", duration: 360, finished: true },
|
||||
{ name: "Pasta", duration: 600, remaining: 425 },
|
||||
{ duration: 300, remaining: 40 },
|
||||
{ name: "Bread", duration: 2700, remaining: 1310, paused: true },
|
||||
],
|
||||
"timer_list.read_only": [
|
||||
{ name: "Laundry", duration: 5400, remaining: 3725 },
|
||||
],
|
||||
};
|
||||
@@ -86,7 +86,6 @@ 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,9 +284,7 @@ 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. When you use the slot, set the
|
||||
<code>accessibleLabel</code> property so screen readers announce the
|
||||
dialog's name.
|
||||
<code>headerTitle</code> slot.
|
||||
</p>
|
||||
|
||||
<h4>Header subtitle</h4>
|
||||
|
||||
@@ -61,6 +61,6 @@ The badge component is a small component that displays a number or status inform
|
||||
**CSS Custom Properties**
|
||||
|
||||
- `--ha-badge-size` (default `36px`)
|
||||
- `--ha-badge-border-radius` (default `calc(var(--ha-border-radius-lg) + 3px)`)
|
||||
- `--ha-badge-border-radius` (default `calc(var(--ha-badge-size, 36px) / 2)`)
|
||||
- `--ha-badge-font-size` (default `var(--ha-font-size-s)`)
|
||||
- `--ha-badge-icon-size` (default `18px`)
|
||||
@@ -66,14 +66,13 @@ 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. |
|
||||
| aria-pressed | "true"/"false" | - | Makes it a toggle button and tells screen readers whether it is pressed. Leave unset for a regular button. |
|
||||
| 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. |
|
||||
|
||||
**CSS Custom Properties**
|
||||
|
||||
|
||||
@@ -22,27 +22,20 @@ export class DemoHaCircularSlider extends LitElement {
|
||||
@state()
|
||||
private changingHigh?: number;
|
||||
|
||||
// A handle that passes the other one pushes it along, like the slider does
|
||||
private _lowChanged(ev) {
|
||||
this.low = ev.detail.value;
|
||||
this.high = Math.max(this.high, this.low);
|
||||
}
|
||||
|
||||
private _lowChanging(ev) {
|
||||
const value = ev.detail.value;
|
||||
this.changingLow = value;
|
||||
this.changingHigh = value != null && value > this.high ? value : undefined;
|
||||
this.changingLow = ev.detail.value;
|
||||
}
|
||||
|
||||
private _highChanged(ev) {
|
||||
this.high = ev.detail.value;
|
||||
this.low = Math.min(this.low, this.high);
|
||||
}
|
||||
|
||||
private _highChanging(ev) {
|
||||
const value = ev.detail.value;
|
||||
this.changingHigh = value;
|
||||
this.changingLow = value != null && value < this.low ? value : undefined;
|
||||
this.changingHigh = ev.detail.value;
|
||||
}
|
||||
|
||||
private _currentChanged(ev) {
|
||||
|
||||
@@ -29,8 +29,8 @@ This component is based on the webawesome input component.
|
||||
|
||||
**Slots**
|
||||
|
||||
- `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.
|
||||
- `start`: Content placed before the input (usually for icons or prefixes).
|
||||
- `end`: Content placed after the input (usually for icons or suffixes).
|
||||
- `label`: Custom label content. Overrides the `label` property.
|
||||
- `hint`: Custom hint content. Overrides the `hint` property.
|
||||
- `clear-icon`: Custom clear icon.
|
||||
@@ -56,8 +56,6 @@ 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>Prefix, suffix and slots</h3>
|
||||
<h3>With slots</h3>
|
||||
<div class="row">
|
||||
<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 prefix">
|
||||
<span slot="start">$</span>
|
||||
</ha-input>
|
||||
<ha-input label="With suffix">
|
||||
<span slot="end">kg</span>
|
||||
</ha-input>
|
||||
<ha-input label="With icon">
|
||||
<ha-svg-icon
|
||||
.path=${mdiMagnify}
|
||||
|
||||
@@ -117,17 +117,11 @@ 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. |
|
||||
| `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.
|
||||
| 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. |
|
||||
|
||||
**CSS parts**
|
||||
|
||||
@@ -195,51 +189,6 @@ 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
|
||||
@@ -250,9 +199,6 @@ 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,7 +14,6 @@ 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";
|
||||
@@ -22,8 +21,6 @@ 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";
|
||||
@@ -96,12 +93,6 @@ 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 {
|
||||
@@ -200,20 +191,6 @@ 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>
|
||||
|
||||
@@ -294,56 +271,6 @@ 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
|
||||
@@ -562,13 +489,6 @@ 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,
|
||||
|
||||
@@ -462,14 +462,6 @@ const SCHEMAS: {
|
||||
},
|
||||
},
|
||||
},
|
||||
select_search: {
|
||||
name: "Select (more than 12 options)",
|
||||
selector: {
|
||||
select: {
|
||||
options: Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`),
|
||||
},
|
||||
},
|
||||
},
|
||||
select_disabled_list: {
|
||||
name: "Select disabled option",
|
||||
selector: {
|
||||
@@ -640,10 +632,6 @@ const SCHEMAS: {
|
||||
},
|
||||
language: { name: "Language", selector: { language: {} } },
|
||||
navigation: { name: "Navigation", selector: { navigation: {} } },
|
||||
ui_condition: {
|
||||
name: "Dashboard conditions",
|
||||
selector: { ui_condition: {} },
|
||||
},
|
||||
numeric_threshold: {
|
||||
name: "Numeric threshold",
|
||||
selector: { numeric_threshold: {} },
|
||||
@@ -936,7 +924,7 @@ class DemoHaSelector extends LitElement implements ProvideHassElement {
|
||||
providers: [
|
||||
{
|
||||
engine_id: "stt.cloud",
|
||||
name: "Home Assistant Link",
|
||||
name: "Home Assistant Cloud",
|
||||
supported_languages: ["en-US"],
|
||||
deprecated: false,
|
||||
},
|
||||
@@ -946,7 +934,7 @@ class DemoHaSelector extends LitElement implements ProvideHassElement {
|
||||
providers: [
|
||||
{
|
||||
engine_id: "tts.cloud",
|
||||
name: "Home Assistant Link",
|
||||
name: "Home Assistant Cloud",
|
||||
supported_languages: ["en-US"],
|
||||
deprecated: false,
|
||||
},
|
||||
|
||||
@@ -2,17 +2,3 @@
|
||||
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,10 +23,8 @@ 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 accessible-label="Doing something..."></ha-spinner>
|
||||
<ha-spinner
|
||||
.accessibleLabel=${"Doing something..."}
|
||||
></ha-spinner>
|
||||
<ha-spinner aria-label="Doing something..."></ha-spinner>
|
||||
<ha-spinner .ariaLabel=${"Doing something..."}></ha-spinner>
|
||||
</div>
|
||||
</ha-card>
|
||||
`
|
||||
|
||||
@@ -10,7 +10,6 @@ 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;
|
||||
@@ -167,7 +166,6 @@ export class DemoStateHistoryCharts extends LitElement {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
followGalleryTheme(this, hass);
|
||||
hass.addEntities(ENTITIES);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import type { ChartSelectMode } from "../../../../src/components/chart/ha-chart-base";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import "../../../../src/components/chart/statistics-chart";
|
||||
import "../../../../src/components/ha-button";
|
||||
import "../../../../src/components/ha-card";
|
||||
import type {
|
||||
Statistics,
|
||||
@@ -13,9 +11,7 @@ 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;
|
||||
@@ -112,64 +108,6 @@ 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",
|
||||
@@ -221,20 +159,17 @@ 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 html`${EXAMPLES.map(
|
||||
return EXAMPLES.map(
|
||||
(example) => html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
@@ -256,66 +191,7 @@ 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`
|
||||
@@ -326,20 +202,6 @@ 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);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,13 +22,6 @@ const ENTITIES = [
|
||||
friendly_name: "Bed Light",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "light.living_room_ceiling_accent_lights",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Living Room Ceiling Accent Lights",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "person.paulus",
|
||||
state: "home",
|
||||
@@ -80,14 +73,6 @@ const CONFIGS = [
|
||||
entity: "person.paulus",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Long name",
|
||||
config: {
|
||||
type: "picture-entity",
|
||||
image: "/images/living_room.png",
|
||||
entity: "light.living_room_ceiling_accent_lights",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Hidden name",
|
||||
config: {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
---
|
||||
title: Timer list card
|
||||
---
|
||||
@@ -1,117 +0,0 @@
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
|
||||
import type { ShowDialogParams } from "../../../../src/dialogs/make-dialog-manager";
|
||||
import { showDialog } from "../../../../src/dialogs/make-dialog-manager";
|
||||
import { mockIcons } from "../../../../demo/src/stubs/icons";
|
||||
import { mockTimerList } from "../../../../demo/src/stubs/timer_list";
|
||||
import type { MockHomeAssistant } from "../../../../src/fake_data/provide_hass";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { TimerListCardConfig } from "../../../../src/panels/lovelace/cards/types";
|
||||
import type { DemoCardConfig } from "../../components/demo-card";
|
||||
import "../../components/demo-cards";
|
||||
import { TIMER_LIST_ENTITIES, TIMER_LIST_TIMERS } from "../../data/timer_list";
|
||||
|
||||
const CONFIGS = [
|
||||
{
|
||||
heading: "Timers",
|
||||
config: {
|
||||
type: "timer-list",
|
||||
entity: "timer_list.kitchen",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "With title, without the add timer button",
|
||||
config: {
|
||||
type: "timer-list",
|
||||
title: "Kitchen",
|
||||
entity: "timer_list.kitchen",
|
||||
hide_create: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "No timers",
|
||||
config: {
|
||||
type: "timer-list",
|
||||
entity: "timer_list.empty",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "No supported actions",
|
||||
config: {
|
||||
type: "timer-list",
|
||||
entity: "timer_list.read_only",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Unavailable",
|
||||
config: {
|
||||
type: "timer-list",
|
||||
entity: "timer_list.unavailable",
|
||||
},
|
||||
},
|
||||
] satisfies DemoCardConfig<TimerListCardConfig>[];
|
||||
|
||||
@customElement("demo-lovelace-timer-list-card")
|
||||
class DemoTimerListCard extends LitElement {
|
||||
@property({ attribute: false }) public hass?: MockHomeAssistant;
|
||||
|
||||
private _stopTimerList?: () => void;
|
||||
|
||||
public provideHass(el) {
|
||||
el.hass = this.hass;
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.addEventListener("show-dialog", this._dialogManager);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this.removeEventListener("show-dialog", this._dialogManager);
|
||||
this._stopTimerList?.();
|
||||
}
|
||||
|
||||
// Opens the dialog to start a timer
|
||||
private _dialogManager = (e: HASSDomEvent<ShowDialogParams<unknown>>) => {
|
||||
const { dialogTag, dialogImport, dialogParams, addHistory, parentElement } =
|
||||
e.detail;
|
||||
showDialog(
|
||||
this,
|
||||
dialogTag,
|
||||
dialogParams,
|
||||
dialogImport,
|
||||
parentElement,
|
||||
addHistory
|
||||
);
|
||||
};
|
||||
|
||||
protected render(): TemplateResult | typeof nothing {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
return html`<demo-cards
|
||||
.hass=${this.hass}
|
||||
.configs=${CONFIGS}
|
||||
></demo-cards>`;
|
||||
}
|
||||
|
||||
protected firstUpdated(changedProperties: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProperties);
|
||||
// Provided on this element, so the dialog it opens gets the mocks too
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
hass.updateTranslations("lovelace", "en");
|
||||
hass.addEntities(TIMER_LIST_ENTITIES);
|
||||
mockIcons(hass);
|
||||
this._stopTimerList = mockTimerList(hass, TIMER_LIST_TIMERS);
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"demo-lovelace-timer-list-card": DemoTimerListCard;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
title: Home Assistant Link account
|
||||
title: Cloud account
|
||||
---
|
||||
|
||||
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,
|
||||
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,
|
||||
backup, onboarding, and feature state so every UI state can be previewed here
|
||||
without a real Home Assistant Link account.
|
||||
without a real cloud account.
|
||||
@@ -54,29 +54,6 @@ lorem | ipsum
|
||||
`,
|
||||
})
|
||||
),
|
||||
mdContentwithDefaults({
|
||||
content: `
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
|
||||
</p>
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Configuration](#configuration)
|
||||
|
||||
## Installation
|
||||
|
||||
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
|
||||
|
||||
## Configuration
|
||||
|
||||
Add the integration from the integrations page.
|
||||
|
||||
[Back to the top](#installation)
|
||||
|
||||
[^marketplace]: Settings > Marketplace.
|
||||
[^restart]: Only needed the first time.
|
||||
`,
|
||||
}),
|
||||
];
|
||||
|
||||
@customElement("demo-misc-ha-markdown")
|
||||
|
||||
@@ -70,32 +70,6 @@ const ENTITIES = [
|
||||
CoverEntityFeature.CLOSE_TILT,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.tilt_only_closed",
|
||||
state: "closed",
|
||||
attributes: {
|
||||
friendly_name: "Tilt-only blind closed",
|
||||
device_class: "blind",
|
||||
assumed_state: true,
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN_TILT +
|
||||
CoverEntityFeature.STOP_TILT +
|
||||
CoverEntityFeature.CLOSE_TILT,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.tilt_only_open",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Tilt-only blind open",
|
||||
device_class: "blind",
|
||||
assumed_state: true,
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN_TILT +
|
||||
CoverEntityFeature.STOP_TILT +
|
||||
CoverEntityFeature.CLOSE_TILT,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.tilt_slider_half",
|
||||
state: "on",
|
||||
@@ -213,139 +187,6 @@ 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")
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
---
|
||||
title: Timer list
|
||||
---
|
||||
@@ -1,76 +0,0 @@
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
|
||||
import type { ShowDialogParams } from "../../../../src/dialogs/make-dialog-manager";
|
||||
import { showDialog } from "../../../../src/dialogs/make-dialog-manager";
|
||||
import { mockTimerList } from "../../../../demo/src/stubs/timer_list";
|
||||
import "../../../../src/components/ha-card";
|
||||
import "../../../../src/dialogs/more-info/more-info-content";
|
||||
import type { MockHomeAssistant } from "../../../../src/fake_data/provide_hass";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import "../../components/demo-more-infos";
|
||||
import { TIMER_LIST_ENTITIES, TIMER_LIST_TIMERS } from "../../data/timer_list";
|
||||
|
||||
@customElement("demo-more-info-timer-list")
|
||||
class DemoMoreInfoTimerList extends LitElement {
|
||||
@property({ attribute: false }) public hass!: MockHomeAssistant;
|
||||
|
||||
private _stopTimerList?: () => void;
|
||||
|
||||
public provideHass(el) {
|
||||
el.hass = this.hass;
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.addEventListener("show-dialog", this._dialogManager);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this.removeEventListener("show-dialog", this._dialogManager);
|
||||
this._stopTimerList?.();
|
||||
}
|
||||
|
||||
// Opens the dialog to start a timer
|
||||
private _dialogManager = (e: HASSDomEvent<ShowDialogParams<unknown>>) => {
|
||||
const { dialogTag, dialogImport, dialogParams, addHistory, parentElement } =
|
||||
e.detail;
|
||||
showDialog(
|
||||
this,
|
||||
dialogTag,
|
||||
dialogParams,
|
||||
dialogImport,
|
||||
parentElement,
|
||||
addHistory
|
||||
);
|
||||
};
|
||||
|
||||
protected render(): TemplateResult | typeof nothing {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
<demo-more-infos
|
||||
.hass=${this.hass}
|
||||
.entities=${TIMER_LIST_ENTITIES.map((ent) => ent.entity_id)}
|
||||
></demo-more-infos>
|
||||
`;
|
||||
}
|
||||
|
||||
protected firstUpdated(changedProperties: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProperties);
|
||||
// Provided on this element, so the dialog it opens gets the mocks too
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
hass.addEntities(TIMER_LIST_ENTITIES);
|
||||
this._stopTimerList = mockTimerList(hass, TIMER_LIST_TIMERS);
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"demo-more-info-timer-list": DemoMoreInfoTimerList;
|
||||
}
|
||||
}
|
||||
@@ -250,16 +250,7 @@ class DemoMoreInfoUpdate extends LitElement {
|
||||
"update/release_notes",
|
||||
(msg: { type: string; entity_id: string }) => {
|
||||
if (msg.entity_id === "update.update16") {
|
||||
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.",
|
||||
},
|
||||
],
|
||||
};
|
||||
return LONG_TEXT;
|
||||
}
|
||||
if (msg.entity_id === "update.update17") {
|
||||
return Promise.reject({
|
||||
@@ -270,7 +261,7 @@ class DemoMoreInfoUpdate extends LitElement {
|
||||
if (msg.entity_id === "update.update18") {
|
||||
return undefined;
|
||||
}
|
||||
return { release_notes: null, messages: [] };
|
||||
return null;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
+56
-57
@@ -40,31 +40,31 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.1.4",
|
||||
"@babel/runtime": "8.1.0",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.2",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
"@codemirror/lang-jinja": "6.0.1",
|
||||
"@codemirror/lang-python": "6.2.1",
|
||||
"@codemirror/lang-yaml": "6.1.3",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/lint": "6.9.8",
|
||||
"@codemirror/search": "6.7.3",
|
||||
"@codemirror/lint": "6.9.7",
|
||||
"@codemirror/search": "6.7.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.44.2",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "8.2.2",
|
||||
"@formatjs/intl-displaynames": "8.0.5",
|
||||
"@formatjs/intl-durationformat": "0.13.2",
|
||||
"@formatjs/intl-getcanonicallocales": "3.4.2",
|
||||
"@formatjs/intl-listformat": "9.1.2",
|
||||
"@formatjs/intl-locale": "5.5.2",
|
||||
"@formatjs/intl-numberformat": "10.1.2",
|
||||
"@formatjs/intl-pluralrules": "7.1.2",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.5",
|
||||
"@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",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.7",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lit-labs/motion": "1.1.0",
|
||||
"@lit-labs/observers": "2.1.0",
|
||||
@@ -77,14 +77,14 @@
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
"@swc/helpers": "0.5.24",
|
||||
"@tsparticles/engine": "4.5.4",
|
||||
"@tsparticles/preset-links": "4.5.4",
|
||||
"@versatiles/style": "9.1.3",
|
||||
"@tsparticles/engine": "4.5.3",
|
||||
"@tsparticles/preset-links": "4.5.3",
|
||||
"@versatiles/style": "9.0.0",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.208.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.11",
|
||||
"barcode-detector": "3.2.5",
|
||||
"cally": "0.10.1",
|
||||
"@vvo/tzdb": "6.204.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
"barcode-detector": "3.2.3",
|
||||
"cally": "0.9.2",
|
||||
"color-name": "2.1.1",
|
||||
"comlink": "4.4.2",
|
||||
"core-js": "3.51.0",
|
||||
@@ -97,22 +97,20 @@
|
||||
"echarts": "6.1.0",
|
||||
"echarts-extension-chart2music": "0.1.1",
|
||||
"element-internals-polyfill": "3.0.2",
|
||||
"fullcalendar": "7.1.5",
|
||||
"fullcalendar": "7.1.4",
|
||||
"fuse.js": "7.5.0",
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.9.0",
|
||||
"home-assistant-js-websocket": "9.8.1",
|
||||
"idb-keyval": "6.3.0",
|
||||
"intl-messageformat": "12.2.1",
|
||||
"intl-messageformat": "12.1.4",
|
||||
"js-yaml": "5.5.0",
|
||||
"leaflet": "1.9.4",
|
||||
"leaflet.markercluster": "2.0.0",
|
||||
"leaflet.markercluster": "1.5.3",
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"marked": "18.3.0",
|
||||
"marked-footnote": "1.4.0",
|
||||
"marked-gfm-heading-id": "4.1.4",
|
||||
"memoize-one": "7.0.0",
|
||||
"maplibre-gl": "6.17.0",
|
||||
"marked": "18.1.3",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
"object-hash": "3.0.0",
|
||||
@@ -124,7 +122,7 @@
|
||||
"sortablejs": "1.15.7",
|
||||
"stacktrace-js": "2.0.2",
|
||||
"superstruct": "2.0.2",
|
||||
"temporal-polyfill": "1.0.9",
|
||||
"temporal-polyfill": "1.0.8",
|
||||
"tinykeys": "4.0.1",
|
||||
"weekstart": "2.0.0",
|
||||
"workbox-cacheable-response": "7.4.1",
|
||||
@@ -138,25 +136,25 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.1.4",
|
||||
"@babel/core": "8.1.0",
|
||||
"@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.1.2",
|
||||
"@babel/preset-env": "8.1.4",
|
||||
"@babel/plugin-transform-runtime": "8.0.6",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@gfx/zopfli": "1.0.15",
|
||||
"@home-assistant/components": "workspace:*",
|
||||
"@html-eslint/eslint-plugin": "0.69.0",
|
||||
"@html-eslint/eslint-plugin": "0.68.0",
|
||||
"@lokalise/node-api": "17.0.1",
|
||||
"@octokit/auth-oauth-device": "8.0.5",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.65.1",
|
||||
"@playwright/test": "1.65.0",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.4",
|
||||
"@rspack/dev-server": "2.2.3",
|
||||
"@rspack/core": "2.3.1",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
"@types/chromecast-caf-sender": "1.0.11",
|
||||
@@ -164,24 +162,25 @@
|
||||
"@types/culori": "4.0.1",
|
||||
"@types/geojson": "7946.0.16",
|
||||
"@types/html-minifier-terser": "7.0.2",
|
||||
"@types/leaflet": "1.9.23",
|
||||
"@types/leaflet": "1.9.22",
|
||||
"@types/leaflet.markercluster": "1.5.6",
|
||||
"@types/lodash.merge": "4.6.9",
|
||||
"@types/node": "24.19.4",
|
||||
"@types/node": "24.19.2",
|
||||
"@types/qrcode": "1.5.6",
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "7.0.87",
|
||||
"@typescript/native": "npm:[email protected]",
|
||||
"@vitest/coverage-v8": "5.1.2",
|
||||
"@vitest/coverage-v8": "5.1.0",
|
||||
"babel-loader": "10.1.1",
|
||||
"babel-plugin-polyfill-corejs3": "1.0.0",
|
||||
"browserslist": "4.29.6",
|
||||
"browserslist": "4.29.5",
|
||||
"browserslist-useragent-regexp": "4.1.4",
|
||||
"core-js-compat": "3.51.0",
|
||||
"del": "9.0.1",
|
||||
"eslint": "10.16.0",
|
||||
"eslint-config-prettier": "10.1.9",
|
||||
"eslint": "10.14.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.18.1",
|
||||
"eslint-plugin-import-x": "4.18.0",
|
||||
"eslint-plugin-lit": "2.3.1",
|
||||
"eslint-plugin-lit-a11y": "5.1.3",
|
||||
"eslint-plugin-unused-imports": "4.4.1",
|
||||
@@ -189,42 +188,42 @@
|
||||
"fancy-log": "2.0.0",
|
||||
"fs-extra": "11.4.1",
|
||||
"generate-license-file": "4.2.5",
|
||||
"glob": "14.0.6",
|
||||
"glob": "14.0.4",
|
||||
"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.1",
|
||||
"jsdom": "31.0.0",
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
"lint-staged": "17.6.3",
|
||||
"lint-staged": "17.6.0",
|
||||
"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.10.1",
|
||||
"prettier": "3.9.10",
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.8",
|
||||
"serve": "14.2.7",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "8.0.2",
|
||||
"tar": "7.5.22",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.74.0",
|
||||
"vite": "8.4.0",
|
||||
"typescript-eslint": "8.72.1",
|
||||
"vite": "8.3.6",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.1.2",
|
||||
"vitest": "5.1.0",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "pnpm@12.24.0",
|
||||
"packageManager": "pnpm@12.18.0",
|
||||
"volta": {
|
||||
"node": "24.22.3"
|
||||
"node": "24.22.2"
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@custom-elements-manifest/analyzer": "0.11.0",
|
||||
"@rslib/core": "1.1.0",
|
||||
"@rslib/core": "1.0.6",
|
||||
"lit": "3.3.3",
|
||||
"typescript": "6.0.3"
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
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 };
|
||||
@@ -1,219 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
/** Tag name of the element. */
|
||||
export const TAG_NAME = "hac-spinner";
|
||||
|
||||
/** Version of <hac-spinner>. */
|
||||
export const VERSION = "0.1.0";
|
||||
@@ -1,15 +0,0 @@
|
||||
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
+1551
-1709
File diff suppressed because it is too large.
Load diff
@@ -18,8 +18,6 @@ trustPolicyExclude:
|
||||
- [email protected]
|
||||
# Pre-release published without provenance, used by workbox-build
|
||||
- "@trickfilm400/[email protected]"
|
||||
# Published without the trusted-publisher record; provenance still from vvo/tzdb release.yml
|
||||
- "@vvo/[email protected]"
|
||||
|
||||
# Dependency build scripts are denied unless listed here with true
|
||||
allowBuilds:
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.0 KiB After Width: | Height: | Size: 2.9 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 1.4 KiB |
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "home-assistant-frontend"
|
||||
version = "20261125.0"
|
||||
version = "20261028.0"
|
||||
license = "Apache-2.0"
|
||||
license-files = ["LICENSE*"]
|
||||
description = "The Home Assistant frontend"
|
||||
|
||||
+3
-3
@@ -14,7 +14,7 @@
|
||||
"minimumReleaseAge": "3 days",
|
||||
"postUpdateOptions": ["pnpmDedupe"],
|
||||
"constraints": {
|
||||
"ghActionsLock": "v0.5.1"
|
||||
"ghActionsLock": "v0.4.1"
|
||||
},
|
||||
"lockFileMaintenance": {
|
||||
"description": ["Run after patch releases but before next beta"],
|
||||
@@ -126,9 +126,9 @@
|
||||
"matchPackageNames": ["echarts", "zrender"]
|
||||
},
|
||||
{
|
||||
"description": "Group formatjs monorepo packages",
|
||||
"description": "Group formatjs monorepo package",
|
||||
"groupName": "formatjs",
|
||||
"matchPackageNames": ["@formatjs/**", "intl-messageformat"]
|
||||
"matchPackageNames": ["@formatjs/**"]
|
||||
},
|
||||
{
|
||||
"description": "Group Playwright package and CI container updates",
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
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}-${String(step).padStart(2, "0")}`;
|
||||
const name = `ha-color-${label}-${step}`;
|
||||
|
||||
// Base color at 50%
|
||||
if (step === 50) {
|
||||
|
||||
@@ -6,17 +6,15 @@ const isConditionObject = (c: unknown): c is VisibilityCondition =>
|
||||
typeof c === "object" && c !== null;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Drop entries that are not condition objects, at any depth. Returns the
|
||||
* same array when every entry is valid.
|
||||
*/
|
||||
export const dropInvalidConditions = (
|
||||
conditions: VisibilityCondition | VisibilityCondition[]
|
||||
conditions: VisibilityCondition[]
|
||||
): VisibilityCondition[] => {
|
||||
const list = ensureArray(conditions);
|
||||
let changed = list !== conditions;
|
||||
let changed = false;
|
||||
const valid: VisibilityCondition[] = [];
|
||||
for (const c of list) {
|
||||
for (const c of conditions) {
|
||||
if (!isConditionObject(c)) {
|
||||
changed = true;
|
||||
continue;
|
||||
@@ -32,5 +30,5 @@ export const dropInvalidConditions = (
|
||||
}
|
||||
valid.push(c);
|
||||
}
|
||||
return changed ? valid : list;
|
||||
return changed ? valid : conditions;
|
||||
};
|
||||
@@ -1,74 +0,0 @@
|
||||
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
|
||||
import type {
|
||||
ConditionContext,
|
||||
VisibilityCondition,
|
||||
} from "../../panels/lovelace/common/validate-condition";
|
||||
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
|
||||
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
|
||||
import { dropInvalidConditions } from "./sanitize";
|
||||
|
||||
export interface VisibilitySubscription {
|
||||
/** Pass each new hass object so client-side conditions check again. */
|
||||
update(hass: HomeAssistant): void;
|
||||
/** Close the subscriptions. `onChange` is not called again. */
|
||||
unsubscribe(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live visibility of a list of dashboard visibility conditions, for code
|
||||
* without a Lit host, such as custom cards and plugins. Conditions core
|
||||
* evaluates are subscribed to; the rest are checked locally. Reports
|
||||
* `unknown` until core replies.
|
||||
*/
|
||||
export const subscribeVisibility = (
|
||||
hass: HomeAssistant,
|
||||
conditions: VisibilityCondition[],
|
||||
onChange: (result: ConditionEvaluation, error?: string) => void,
|
||||
context: ConditionContext = {}
|
||||
): VisibilitySubscription => {
|
||||
// The controller only needs a host to register with and to re-render.
|
||||
const host: ReactiveControllerHost = {
|
||||
addController: () => undefined,
|
||||
removeController: () => undefined,
|
||||
requestUpdate: () => undefined,
|
||||
updateComplete: Promise.resolve(true),
|
||||
};
|
||||
|
||||
let active = true;
|
||||
|
||||
const controller = new ConditionEvaluatorController(host, {
|
||||
resubscribeDelay: 0,
|
||||
onResult: (result, error) => {
|
||||
if (active) {
|
||||
onChange(result, error);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const sanitized = dropInvalidConditions(conditions);
|
||||
const { entity_id: entityId } = context;
|
||||
|
||||
// Core-evaluated conditions never see the context, so fold its entity in
|
||||
// first, as the dashboard mixin does.
|
||||
const validConditions = entityId
|
||||
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
|
||||
: sanitized;
|
||||
const getContext = () => context;
|
||||
|
||||
controller.hostConnected();
|
||||
controller.observe(validConditions, hass, getContext);
|
||||
|
||||
return {
|
||||
update: (newHass) => {
|
||||
if (active) {
|
||||
controller.observe(validConditions, newHass, getContext);
|
||||
}
|
||||
},
|
||||
unsubscribe: () => {
|
||||
active = false;
|
||||
controller.hostDisconnected();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -244,7 +244,7 @@ export class ConditionEvaluatorController implements ReactiveController {
|
||||
return;
|
||||
}
|
||||
if (message.error !== undefined) {
|
||||
this._serverResults[subtree.id] = undefined;
|
||||
this._serverResults[subtree.id] = false;
|
||||
this._subtreeErrors[subtree.id] =
|
||||
typeof message.error === "string"
|
||||
? message.error
|
||||
@@ -265,7 +265,7 @@ export class ConditionEvaluatorController implements ReactiveController {
|
||||
if (generation !== this._generation) {
|
||||
return;
|
||||
}
|
||||
this._serverResults[subtree.id] = undefined;
|
||||
this._serverResults[subtree.id] = false;
|
||||
this._subtreeErrors[subtree.id] =
|
||||
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
|
||||
this._recompute();
|
||||
@@ -299,19 +299,18 @@ export class ConditionEvaluatorController implements ReactiveController {
|
||||
}
|
||||
};
|
||||
|
||||
// A failed subtree stays unknown, so it only hides the card when the
|
||||
// result depends on it (a true `or` sibling still wins).
|
||||
const value = this._split.evaluate(clientEvaluator, this._serverResults);
|
||||
const error = firstDefined(this._subtreeErrors);
|
||||
if (value === undefined && error !== undefined) {
|
||||
// Don't treat a server error as `false` that a client `not` would invert.
|
||||
if (error !== undefined) {
|
||||
this._setResult("hidden", error);
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this._split.evaluate(clientEvaluator, this._serverResults);
|
||||
const result: ConditionEvaluation =
|
||||
value === undefined ? "unknown" : value ? "visible" : "hidden";
|
||||
|
||||
this._setResult(result, error ?? firstDefined(this._subtreeTemplateErrors));
|
||||
this._setResult(result, firstDefined(this._subtreeTemplateErrors));
|
||||
}
|
||||
|
||||
private _setResult(
|
||||
|
||||
@@ -89,19 +89,10 @@ export class LegendFitController {
|
||||
|
||||
private _fit() {
|
||||
const list = this._element;
|
||||
if (!list) {
|
||||
const rowWidth = list?.getBoundingClientRect().width;
|
||||
if (!list || !rowWidth) {
|
||||
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")
|
||||
@@ -116,7 +107,9 @@ export class LegendFitController {
|
||||
}
|
||||
this._more = more;
|
||||
}
|
||||
const widths = children.filter((child) => child !== more).map(layoutWidth);
|
||||
const widths = children
|
||||
.filter((child) => child !== more)
|
||||
.map((child) => child.getBoundingClientRect().width);
|
||||
// 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) {
|
||||
@@ -129,9 +122,9 @@ export class LegendFitController {
|
||||
}
|
||||
const fit = fitInRows(
|
||||
this._widths,
|
||||
more ? layoutWidth(more) : 0,
|
||||
more?.getBoundingClientRect().width ?? 0,
|
||||
rowWidth,
|
||||
parseFloat(style.columnGap) || 0,
|
||||
parseFloat(getComputedStyle(list).columnGap) || 0,
|
||||
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
|
||||
);
|
||||
if (fit !== this.fit) {
|
||||
|
||||
@@ -209,16 +209,6 @@ const formatDurationMinuteMem = memoizeOne((locale: FrontendLocaleData) =>
|
||||
})
|
||||
);
|
||||
|
||||
// Splits a value into whole units and whole sub-units, e.g. 1.15 h into 1 h
|
||||
// and 9 min. The value is converted to sub-units and rounded before flooring,
|
||||
// as floating point math puts many of them just below a whole number:
|
||||
// (1.15 - 1) * 60 is 8.999999999999995.
|
||||
const splitDuration = (value: number, subUnits: number): [number, number] => {
|
||||
const total = Math.floor(round(value * subUnits, 6));
|
||||
const units = Math.floor(total / subUnits);
|
||||
return [units, total - units * subUnits];
|
||||
};
|
||||
|
||||
export const formatDuration = (
|
||||
locale: FrontendLocaleData,
|
||||
duration: string,
|
||||
@@ -232,7 +222,8 @@ export const formatDuration = (
|
||||
|
||||
switch (unit) {
|
||||
case "d": {
|
||||
const [days, hours] = splitDuration(value, 24);
|
||||
const days = Math.floor(value);
|
||||
const hours = Math.floor((value - days) * 24);
|
||||
const input = {
|
||||
days,
|
||||
hours,
|
||||
@@ -240,7 +231,8 @@ export const formatDuration = (
|
||||
return formatDurationDayMem(locale)(input);
|
||||
}
|
||||
case "h": {
|
||||
const [hours, minutes] = splitDuration(value, 60);
|
||||
const hours = Math.floor(value);
|
||||
const minutes = Math.floor((value - hours) * 60);
|
||||
const input = {
|
||||
hours,
|
||||
minutes,
|
||||
@@ -248,7 +240,8 @@ export const formatDuration = (
|
||||
return formatDurationHourMem(locale)(input);
|
||||
}
|
||||
case "min": {
|
||||
const [minutes, seconds] = splitDuration(value, 60);
|
||||
const minutes = Math.floor(value);
|
||||
const seconds = Math.floor((value - minutes) * 60);
|
||||
const input = {
|
||||
minutes,
|
||||
seconds,
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
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";
|
||||
@@ -15,9 +10,9 @@ import {
|
||||
rgb2hex,
|
||||
rgb2lab,
|
||||
} from "../color/convert-color";
|
||||
import { cssColorToHex, hexBlend } from "../color/hex";
|
||||
import { hexBlend } from "../color/hex";
|
||||
import { labBrighten, labDarken } from "../color/lab";
|
||||
import { generateColorPalette, normalizeLuminance } from "../color/palette";
|
||||
import { generateColorPalette } from "../color/palette";
|
||||
import { rgbContrast } from "../color/rgb";
|
||||
|
||||
interface ProcessedTheme {
|
||||
@@ -61,56 +56,78 @@ export const applyThemesOnElement = (
|
||||
themeRules = { ...darkSemanticVariables, ...darkColorVariables };
|
||||
}
|
||||
|
||||
const isDefaultTheme = themeToApply === "default";
|
||||
const customTheme =
|
||||
themeToApply && !isDefaultTheme ? themes.themes[themeToApply] : undefined;
|
||||
const customThemeRules = customTheme
|
||||
? getThemeVariables(customTheme, darkMode)
|
||||
: undefined;
|
||||
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 primaryColor =
|
||||
isDefaultTheme ||
|
||||
(customThemeRules && !themeDefinesColor(customThemeRules, "primary"))
|
||||
? themeSettings?.primaryColor
|
||||
: undefined;
|
||||
const accentColor =
|
||||
isDefaultTheme ||
|
||||
(customThemeRules && !themeDefinesColor(customThemeRules, "accent"))
|
||||
? themeSettings?.accentColor
|
||||
: undefined;
|
||||
if (darkMode && primaryColor) {
|
||||
themeRules["app-header-background-color"] = hexBlend(
|
||||
primaryColor,
|
||||
"#121212",
|
||||
8
|
||||
);
|
||||
}
|
||||
|
||||
if (primaryColor) {
|
||||
cacheKey = `${cacheKey}__primary_${primaryColor}`;
|
||||
}
|
||||
if (accentColor) {
|
||||
cacheKey = `${cacheKey}__accent_${accentColor}`;
|
||||
}
|
||||
themeRules = {
|
||||
...themeRules,
|
||||
...getUserColorRules(primaryColor, accentColor, isDefaultTheme && darkMode),
|
||||
};
|
||||
if (primaryColor) {
|
||||
cacheKey = `${cacheKey}__primary_${primaryColor}`;
|
||||
const rgbPrimaryColor = hex2rgb(primaryColor);
|
||||
const labPrimaryColor = rgb2lab(rgbPrimaryColor);
|
||||
themeRules["primary-color"] = primaryColor;
|
||||
const rgbLightPrimaryColor = lab2rgb(labBrighten(labPrimaryColor));
|
||||
|
||||
// Nothing was changed
|
||||
if (isDefaultTheme && element.__themes?.cacheKey === cacheKey) {
|
||||
return;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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)),
|
||||
};
|
||||
}
|
||||
// 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 };
|
||||
|
||||
if (customThemeRules) {
|
||||
themeRules = { ...themeRules, ...customThemeRules };
|
||||
// Apply theme vars for the specific mode if available
|
||||
if (modes) {
|
||||
if (darkMode) {
|
||||
themeRules = { ...themeRules, ...modes.dark };
|
||||
} else {
|
||||
themeRules = { ...themeRules, ...modes.light };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!element.__themes?.keys && !Object.keys(themeRules).length) {
|
||||
@@ -137,57 +154,6 @@ 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>
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
* How long after the full screen button the companion apps hide the page for
|
||||
* the change, and after that how long they keep it hidden. A later hide ends
|
||||
* streams as usual.
|
||||
*/
|
||||
export const FULLSCREEN_ENTER_TIME = 1000;
|
||||
|
||||
let enterStart = 0;
|
||||
|
||||
let enterId = 0;
|
||||
|
||||
// The last entering each stream let a hidden page through for
|
||||
const claimedEnters = new WeakMap<object, number>();
|
||||
|
||||
/**
|
||||
* Marks that the full screen button was pressed to enter full screen. The
|
||||
* companion apps hide the page for a moment then, which shouldn't end a
|
||||
* stream. Leaving full screen isn't marked, so locking the phone or leaving
|
||||
* the app right after it always ends the streams.
|
||||
*/
|
||||
export const startEnteringFullscreen = () => {
|
||||
enterId++;
|
||||
enterStart = Date.now();
|
||||
};
|
||||
|
||||
/** Ends it early, like when the browser denies full screen. */
|
||||
export const cancelEnteringFullscreen = () => {
|
||||
enterStart = 0;
|
||||
};
|
||||
|
||||
export const isEnteringFullscreen = () =>
|
||||
Date.now() - enterStart < FULLSCREEN_ENTER_TIME;
|
||||
|
||||
/**
|
||||
* Whether the page is hidden by entering full screen, which hides it only
|
||||
* once. Any later hiding is the user leaving, so each stream gets true only
|
||||
* once per entering.
|
||||
*/
|
||||
export const claimFullscreenEnterHide = (stream: object): boolean => {
|
||||
if (!isEnteringFullscreen() || claimedEnters.get(stream) === enterId) {
|
||||
return false;
|
||||
}
|
||||
claimedEnters.set(stream, enterId);
|
||||
// Counts from here, so the video still plays on when the page shows again
|
||||
enterStart = Date.now();
|
||||
return true;
|
||||
};
|
||||
@@ -1,623 +0,0 @@
|
||||
/**
|
||||
* Read a skeleton from rendered content, such as a dashboard card: where its
|
||||
* text lines, icons, images, controls and drawings are, inside shadow roots
|
||||
* too. The content stays the source of truth for layout, so the skeleton
|
||||
* can't drift from it.
|
||||
*
|
||||
* Any element can say how it's read with a `data-skeleton` attribute:
|
||||
* - `text`, `round` or `block`: one piece of that kind, the size of the element
|
||||
* - `none`: left out and left showing, such as a card's own chrome
|
||||
* - `keep`: left showing, but what's inside it is still read
|
||||
*
|
||||
* Skeletons a component already draws itself (`ha-skeleton` and its
|
||||
* variants) are left out and left showing, as `none`.
|
||||
*/
|
||||
|
||||
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
|
||||
|
||||
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
|
||||
|
||||
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
|
||||
|
||||
const isOverride = (value: string | null): value is SkeletonOverride =>
|
||||
value !== null && OVERRIDES.has(value);
|
||||
|
||||
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
|
||||
if (element.localName.startsWith("ha-skeleton")) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
const value = element.getAttribute("data-skeleton");
|
||||
|
||||
return isOverride(value) ? value : undefined;
|
||||
};
|
||||
|
||||
export interface SkeletonPiece {
|
||||
kind: SkeletonPieceKind;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
radius?: string;
|
||||
/* An SVG mask for a drawing, such as a gauge arc */
|
||||
mask?: string;
|
||||
/* Where that mask sits in the piece, when something cuts the drawing short:
|
||||
still the drawing's whole size and place, with the piece only its part */
|
||||
maskBox?: { x: number; y: number; width: number; height: number };
|
||||
/* The part sits on a dark overlay, such as a picture card's name bar */
|
||||
onDark?: boolean;
|
||||
/* A see-through bar laid over a picture, kept as it is */
|
||||
background?: string;
|
||||
}
|
||||
|
||||
export interface ExtractedSkeleton {
|
||||
pieces: SkeletonPiece[];
|
||||
/* The elements the pieces stand in for, hidden while loading */
|
||||
parts: (HTMLElement | SVGElement)[];
|
||||
/* Elements holding text: hide only the text colour, as the same element
|
||||
often draws a frame, such as a badge's pill, that has to stay */
|
||||
textParts: HTMLElement[];
|
||||
}
|
||||
|
||||
const ROUND_TAGS = new Set([
|
||||
"ha-tile-icon",
|
||||
"ha-state-icon",
|
||||
"ha-svg-icon",
|
||||
"ha-icon",
|
||||
"state-badge",
|
||||
]);
|
||||
|
||||
const BLOCK_TAGS = new Set(["img", "video", "canvas", "ha-camera-stream"]);
|
||||
|
||||
/* A canvas to measure fonts with, made on first use */
|
||||
let measuringContext: CanvasRenderingContext2D | null | undefined;
|
||||
|
||||
const fontContext = (style: CSSStyleDeclaration, size: string) => {
|
||||
measuringContext ??= document.createElement("canvas").getContext("2d");
|
||||
|
||||
if (measuringContext) {
|
||||
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
|
||||
}
|
||||
|
||||
return measuringContext;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a text bar goes on a line of this font: from the top of the
|
||||
* capitals down to the baseline, measured from the font itself.
|
||||
* `size` is the size as drawn, after any SVG scaling.
|
||||
*/
|
||||
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
|
||||
const metrics = fontContext(style, `${size}px`)?.measureText("H");
|
||||
|
||||
// Missing before Chrome 87 and Firefox 116
|
||||
if (!metrics?.fontBoundingBoxAscent || !metrics.actualBoundingBoxAscent) {
|
||||
return { top: size * 0.2, height: size * 0.7 };
|
||||
}
|
||||
|
||||
return {
|
||||
// The line box holds the font's ascent, so the baseline sits that far down
|
||||
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
|
||||
height: metrics.actualBoundingBoxAscent,
|
||||
};
|
||||
};
|
||||
|
||||
/* How wide "…" is in this font, the room cut-off text leaves at its end */
|
||||
const ellipsisWidth = (style: CSSStyleDeclaration) =>
|
||||
fontContext(style, style.fontSize)?.measureText("…").width ??
|
||||
parseFloat(style.fontSize);
|
||||
|
||||
/* The icon as drawn, not its box, which a line of text can crop */
|
||||
const findGlyph = (element: Element, depth = 4): Element | undefined => {
|
||||
if (depth === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const child of [
|
||||
...(element.shadowRoot?.children ?? []),
|
||||
...element.children,
|
||||
]) {
|
||||
if (child instanceof SVGSVGElement) {
|
||||
return child;
|
||||
}
|
||||
|
||||
const found = findGlyph(child, depth - 1);
|
||||
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/* Near-white text or icons, as on a picture card's dark name bar */
|
||||
const isNearWhite = (color: string): boolean => {
|
||||
const channels = color
|
||||
.match(/[\d.]+/g)
|
||||
?.slice(0, 3)
|
||||
.map(Number);
|
||||
|
||||
return channels?.length === 3 && channels.every((channel) => channel >= 200);
|
||||
};
|
||||
|
||||
const isRendered = (style: CSSStyleDeclaration) =>
|
||||
style.display !== "none" && style.visibility !== "hidden";
|
||||
|
||||
const isSeeThrough = (color: string) => {
|
||||
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
|
||||
|
||||
return alpha > 0 && alpha < 1;
|
||||
};
|
||||
|
||||
/* The first element, inside shadow roots too, that rounds its corners */
|
||||
const findRounded = (element: Element, depth = 4): Element | undefined => {
|
||||
if (depth === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const children = [
|
||||
...(element.shadowRoot?.children ?? []),
|
||||
...element.children,
|
||||
];
|
||||
|
||||
for (const child of children) {
|
||||
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
|
||||
return child;
|
||||
}
|
||||
|
||||
const found = findRounded(child, depth - 1);
|
||||
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
|
||||
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
|
||||
const merged: SkeletonPiece[] = [];
|
||||
|
||||
for (const piece of pieces) {
|
||||
const previous = merged[merged.length - 1];
|
||||
|
||||
// Either side, so right-to-left lines join too
|
||||
const gap = previous
|
||||
? Math.max(
|
||||
piece.x - (previous.x + previous.width),
|
||||
previous.x - (piece.x + piece.width)
|
||||
)
|
||||
: Infinity;
|
||||
|
||||
const sameLine =
|
||||
previous?.kind === "text" &&
|
||||
piece.kind === "text" &&
|
||||
Math.abs(previous.y - piece.y) < 2 &&
|
||||
Math.abs(previous.height - piece.height) < 2 &&
|
||||
gap < 12;
|
||||
|
||||
if (sameLine) {
|
||||
const left = Math.min(previous.x, piece.x);
|
||||
|
||||
const right = Math.max(
|
||||
previous.x + previous.width,
|
||||
piece.x + piece.width
|
||||
);
|
||||
|
||||
previous.x = left;
|
||||
previous.width = right - left;
|
||||
continue;
|
||||
}
|
||||
|
||||
merged.push({ ...piece });
|
||||
}
|
||||
|
||||
return merged;
|
||||
};
|
||||
|
||||
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
|
||||
const clone = svg.cloneNode(true);
|
||||
|
||||
if (!(clone instanceof SVGSVGElement)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const originals = [svg, ...svg.querySelectorAll("*")];
|
||||
const copies = [clone, ...clone.querySelectorAll("*")];
|
||||
let drawnPaths = 0;
|
||||
|
||||
originals.forEach((original, index) => {
|
||||
const copy = copies[index];
|
||||
const style = getComputedStyle(original);
|
||||
|
||||
if (original.localName === "text" || !isRendered(style)) {
|
||||
copy.setAttribute("display", "none");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (original !== svg && original.localName !== "g") {
|
||||
drawnPaths++;
|
||||
}
|
||||
|
||||
copy.removeAttribute("class");
|
||||
copy.removeAttribute("style");
|
||||
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
|
||||
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
|
||||
copy.setAttribute("stroke-width", style.strokeWidth);
|
||||
copy.setAttribute("stroke-linecap", style.strokeLinecap);
|
||||
|
||||
// Keep what moves or cuts a shape, such as a gauge's needle and the
|
||||
// dashes that draw its value arc
|
||||
if (style.transform !== "none") {
|
||||
copy.setAttribute(
|
||||
"style",
|
||||
`transform: ${style.transform}; transform-origin: ${style.transformOrigin}; transform-box: ${style.transformBox}`
|
||||
);
|
||||
}
|
||||
|
||||
if (style.strokeDasharray !== "none") {
|
||||
copy.setAttribute("stroke-dasharray", style.strokeDasharray);
|
||||
copy.setAttribute("stroke-dashoffset", style.strokeDashoffset);
|
||||
}
|
||||
});
|
||||
|
||||
if (drawnPaths === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
clone.setAttribute("width", String(width));
|
||||
clone.setAttribute("height", String(height));
|
||||
|
||||
const markup = new XMLSerializer().serializeToString(clone);
|
||||
|
||||
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
|
||||
};
|
||||
|
||||
export const extractSkeleton = (
|
||||
root: Element,
|
||||
origin: DOMRect
|
||||
): ExtractedSkeleton => {
|
||||
const pieces: SkeletonPiece[] = [];
|
||||
const parts = new Set<HTMLElement | SVGElement>();
|
||||
const textParts = new Set<HTMLElement>();
|
||||
|
||||
/* The card's own background, the first solid one found */
|
||||
let surface: string | undefined;
|
||||
|
||||
const box = (rect: DOMRect) => ({
|
||||
x: rect.left - origin.left,
|
||||
y: rect.top - origin.top,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
});
|
||||
|
||||
/* Near-white content on a light card must sit on a dark bar */
|
||||
const onDark = (style: CSSStyleDeclaration) =>
|
||||
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
|
||||
|
||||
/* An element that cuts off its overflow, such as a scrolling list, cuts the
|
||||
pieces read inside it too, as the overlay draws them on a layer of its
|
||||
own where that clip doesn't reach */
|
||||
const clipPieces = (from: number, rect: DOMRect) => {
|
||||
const bounds = box(rect);
|
||||
|
||||
const clipped = pieces.splice(from).flatMap((piece): SkeletonPiece[] => {
|
||||
const x = Math.max(piece.x, bounds.x);
|
||||
const y = Math.max(piece.y, bounds.y);
|
||||
const right = Math.min(piece.x + piece.width, bounds.x + bounds.width);
|
||||
const bottom = Math.min(piece.y + piece.height, bounds.y + bounds.height);
|
||||
|
||||
if (right <= x || bottom <= y) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const cut = { ...piece, x, y, width: right - x, height: bottom - y };
|
||||
|
||||
// A drawing's mask is made for its whole box, so it keeps that box
|
||||
if (piece.kind === "shape") {
|
||||
const mask = piece.maskBox ?? {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: piece.width,
|
||||
height: piece.height,
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
...cut,
|
||||
maskBox: {
|
||||
...mask,
|
||||
x: piece.x + mask.x - x,
|
||||
y: piece.y + mask.y - y,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [cut];
|
||||
});
|
||||
|
||||
pieces.push(...clipped);
|
||||
};
|
||||
|
||||
const addText = (element: Element | ShadowRoot) => {
|
||||
const owner = element instanceof ShadowRoot ? element.host : element;
|
||||
|
||||
// Text cut short with an ellipsis reaches past its box, so clip to it.
|
||||
// An owner with no box of its own, such as one with display: contents,
|
||||
// cuts nothing off.
|
||||
const clip = owner.getBoundingClientRect();
|
||||
const clips = clip.width > 0 || clip.height > 0;
|
||||
|
||||
element.childNodes.forEach((node) => {
|
||||
if (!(node instanceof Text) || !node.textContent?.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Slotted text takes its font and colour from the slot it shows in,
|
||||
// so that's where it's measured and hidden
|
||||
const slot = node.assignedSlot;
|
||||
const hideTarget = slot ?? owner;
|
||||
const style = getComputedStyle(hideTarget);
|
||||
const band = capitalBand(style, parseFloat(style.fontSize));
|
||||
|
||||
if (hideTarget instanceof HTMLElement) {
|
||||
textParts.add(hideTarget);
|
||||
}
|
||||
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
|
||||
for (const rect of range.getClientRects()) {
|
||||
// Cut-off text ends in "…", on the right or, right to left, on the
|
||||
// left, so stop the bar where that starts
|
||||
const left =
|
||||
clips && rect.left < clip.left - 1
|
||||
? clip.left + ellipsisWidth(style)
|
||||
: rect.left;
|
||||
|
||||
const right =
|
||||
clips && rect.right > clip.right + 1
|
||||
? clip.right - ellipsisWidth(style)
|
||||
: rect.right;
|
||||
|
||||
if (right <= left) {
|
||||
continue;
|
||||
}
|
||||
|
||||
pieces.push({
|
||||
kind: "text",
|
||||
x: left - origin.left,
|
||||
width: right - left,
|
||||
y: rect.top - origin.top + band.top,
|
||||
height: band.height,
|
||||
onDark: onDark(style),
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const walk = (node: Element | ShadowRoot) => {
|
||||
// Text straight inside a shadow root, as state-display renders its state
|
||||
if (node instanceof ShadowRoot) {
|
||||
addText(node);
|
||||
}
|
||||
|
||||
for (const child of node.children) {
|
||||
const style = getComputedStyle(child);
|
||||
|
||||
if (!isRendered(style)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rect = child.getBoundingClientRect();
|
||||
const tag = child.localName;
|
||||
// Elements such as slots take no space but their content does
|
||||
const hasSize = rect.width > 0 && rect.height > 0;
|
||||
const override = skeletonOverride(child);
|
||||
|
||||
if (override === "none") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const clipsOverflow =
|
||||
hasSize &&
|
||||
(style.overflowX !== "visible" || style.overflowY !== "visible");
|
||||
|
||||
const from = pieces.length;
|
||||
|
||||
// Read what's inside, cut to the child where it hides its overflow
|
||||
const descend = () => {
|
||||
if (child instanceof HTMLElement) {
|
||||
addText(child);
|
||||
}
|
||||
|
||||
if (child.shadowRoot) {
|
||||
walk(child.shadowRoot);
|
||||
}
|
||||
|
||||
walk(child);
|
||||
|
||||
if (clipsOverflow) {
|
||||
clipPieces(from, rect);
|
||||
}
|
||||
};
|
||||
|
||||
if (override === "keep") {
|
||||
// Its frame stays, but its own text is read like any other
|
||||
descend();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (override !== undefined) {
|
||||
if (
|
||||
hasSize &&
|
||||
(child instanceof HTMLElement || child instanceof SVGElement)
|
||||
) {
|
||||
const size = Math.min(rect.width, rect.height);
|
||||
const piece = box(rect);
|
||||
|
||||
pieces.push(
|
||||
override === "round"
|
||||
? {
|
||||
kind: "round",
|
||||
x: piece.x + (piece.width - size) / 2,
|
||||
y: piece.y + (piece.height - size) / 2,
|
||||
width: size,
|
||||
height: size,
|
||||
}
|
||||
: { kind: override, ...piece, radius: style.borderRadius }
|
||||
);
|
||||
parts.add(child);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
surface === undefined &&
|
||||
hasSize &&
|
||||
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
|
||||
!isSeeThrough(style.backgroundColor)
|
||||
) {
|
||||
surface = style.backgroundColor;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
|
||||
// Use the circle itself, such as the tile icon's 36px background
|
||||
const circle = (
|
||||
findRounded(child) ??
|
||||
findGlyph(child) ??
|
||||
child
|
||||
).getBoundingClientRect();
|
||||
|
||||
const size =
|
||||
Math.min(circle.width, circle.height) ||
|
||||
Math.max(circle.width, circle.height);
|
||||
|
||||
const piece = box(circle);
|
||||
|
||||
if (size > 0) {
|
||||
pieces.push({
|
||||
kind: "round",
|
||||
x: piece.x + (piece.width - size) / 2,
|
||||
y: piece.y + (piece.height - size) / 2,
|
||||
width: size,
|
||||
height: size,
|
||||
onDark: onDark(style),
|
||||
});
|
||||
parts.add(child);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// A see-through bar over a picture stays, so text keeps its contrast
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
style.position === "absolute" &&
|
||||
isSeeThrough(style.backgroundColor)
|
||||
) {
|
||||
pieces.push({
|
||||
kind: "scrim",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
background: style.backgroundColor,
|
||||
});
|
||||
}
|
||||
|
||||
// Pictures drawn as a background, as hui-image does in a fixed ratio
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
style.backgroundImage.startsWith("url(")
|
||||
) {
|
||||
pieces.push({
|
||||
kind: "block",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
});
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
|
||||
pieces.push({
|
||||
kind: "block",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
});
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
tag.endsWith("-card-feature")
|
||||
) {
|
||||
const control = findRounded(child);
|
||||
|
||||
const radius = control
|
||||
? getComputedStyle(control).borderRadius
|
||||
: style.borderRadius;
|
||||
|
||||
pieces.push({ kind: "block", ...box(rect), radius });
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof SVGSVGElement && hasSize) {
|
||||
const piece = box(rect);
|
||||
const mask = svgMask(child, piece.width, piece.height);
|
||||
|
||||
if (mask) {
|
||||
pieces.push({ kind: "shape", ...piece, mask });
|
||||
}
|
||||
|
||||
child.querySelectorAll("text").forEach((text) => {
|
||||
const textRect = text.getBoundingClientRect();
|
||||
|
||||
if (textRect.width === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// SVG text is scaled with its drawing, as the gauge value is
|
||||
const scale = text.getScreenCTM()?.a ?? 1;
|
||||
const textStyle = getComputedStyle(text);
|
||||
|
||||
const band = capitalBand(
|
||||
textStyle,
|
||||
parseFloat(textStyle.fontSize) * scale
|
||||
);
|
||||
|
||||
pieces.push({
|
||||
kind: "text",
|
||||
...box(textRect),
|
||||
y: textRect.top - origin.top + band.top,
|
||||
height: band.height,
|
||||
});
|
||||
});
|
||||
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
descend();
|
||||
}
|
||||
};
|
||||
|
||||
// Text straight inside the root, such as plain text in an overlay
|
||||
addText(root);
|
||||
walk(root);
|
||||
|
||||
return {
|
||||
pieces: mergeLines(pieces),
|
||||
parts: [...parts],
|
||||
textParts: [...textParts],
|
||||
};
|
||||
};
|
||||
@@ -3,23 +3,15 @@ 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
|
||||
"ha-chart-base",
|
||||
"ha-more-info-control-select-container",
|
||||
"ha-filter-chip",
|
||||
// Toasts are inside the sheet while it is open
|
||||
"notification-manager",
|
||||
]);
|
||||
|
||||
const SWIPE_LOCKED_CLASSES = new Set([
|
||||
"volume-slider-container",
|
||||
"forecast",
|
||||
// A zoomed in camera picture pans on touch
|
||||
"camera-player-zoomed",
|
||||
]);
|
||||
const SWIPE_LOCKED_CLASSES = new Set(["volume-slider-container", "forecast"]);
|
||||
|
||||
/**
|
||||
* Whether a touch inside a bottom sheet belongs to its content rather than to
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
/** Loads an image, resolves with undefined when it can't be loaded. */
|
||||
export const loadImage = (url: string): Promise<HTMLImageElement | undefined> =>
|
||||
new Promise((resolve) => {
|
||||
const image = new Image();
|
||||
image.onload = () => resolve(image);
|
||||
image.onerror = () => resolve(undefined);
|
||||
image.src = url;
|
||||
});
|
||||
Loaded 100 of 949 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user