Compare commits

..
Author SHA1 Message Date
Maarten Lakerveld 175636d20d Keep dialogs on the remaining default-route redirects
The energy panel, the energy config tabs and the media browser fill in
their default route with a replace, which closed a dialog restored from
the URL and dropped the query the restore needs. They now pass
keepDialogs and keep the query, like the router and dashboard redirects.

The more-info restore runs on every location change, so those redirects
re-showed the dialog that was already open. That hoisted it above any
dialog opened on top of it and reset its view. Skip the restore while
the more-info dialog is open.
2026-11-05 15:33:09 +01:00
TimothyandClaude Opus 5.5 da47ac9c16 Keep navigate async when keeping dialogs
Skipping the await committed the navigation synchronously, so a navigate()
called right after it saw the committed count change and was dropped as
stale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:49:22 +00:00
TimothyandClaude Opus 5.5 3c49abb492 Merge remote-tracking branch 'origin/dev' into fix/dialog_not_open_when_using_navigate
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:49:07 +00:00
Timothy 9494db6462 Apply suggestions 2026-11-05 11:14:43 +01:00
Timothy 06461704ad Keep dialogs while navigating 2026-11-04 12:23:49 +01:00
1548 changed files with 23983 additions and 79418 deletions

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.
+28 -4
View File
@@ -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
@@ -108,5 +134,3 @@ Panels commonly extend `SubscribeMixin(LitElement)` and receive route and narrow
Lovelace cards should implement `LovelaceCard`, validate config in `setConfig()`, handle loading, error, unavailable, and missing-entity states, and add a configuration editor when needed.
Cards are user-story surfaces. Support different households, entity types, responsive layouts, and accessible interaction states.
A new card, badge, or card feature, or a change to their options, needs documentation in other repositories. Follow "Documentation Elsewhere" in `ha-frontend-review`.
+2 -4
View File
@@ -44,8 +44,6 @@ Lazy contexts subscribe on first consumer and tear down after the last consumer:
The single-field contexts such as `localizeContext`, `themesContext`, and `userContext` are deprecated. Use grouped contexts instead.
Custom cards request contexts by key with a `context-request` event, as the custom card documentation on contributors.home-assistant.io describes, so the keys in `src/data/context/index.ts` and their values are a public API. Renaming or removing a key, changing its value, or dropping a deprecated context breaks them. A change to how card, badge, or feature hosts pass data, such as no longer setting `hass` or offering a new context, changes what custom cards should do too. For both, follow "Documentation Elsewhere" in `ha-frontend-review`.
## Consumption Patterns
Import `consume` from `src/common/decorators/consume`, not from `@lit/context`. The `@lit/context` version forces a host update on every context change, so every consumed field rerenders the component, even without `@state()`, and `@transform` cannot skip anything. Our `consume` leaves update scheduling to the field:
@@ -62,7 +60,7 @@ Use entity-scoped helpers when the component watches an entity ID held on the ho
```ts
@state() @consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntityState;
private _stateObj?: HassEntity;
@state() @consumeEntityRegistryEntry({ entityIdPath: ["_config", "entity"] })
private _entity?: EntityRegistryDisplayEntry;
@@ -75,7 +73,7 @@ Use `consumeEntityStates` when the host property contains one or more entity IDs
```ts
@state() @consumeEntityStates({ entityIdPath: ["_config", "entities"] })
private _stateObjs?: Record<string, HassEntityState>;
private _stateObjs?: Record<string, HassEntity>;
```
For a single field from a grouped context, pair `@consume` with `@transform`:
+1 -11
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-demo
description: Home Assistant standalone demo structure, configurations, URL navigation, mocked APIs, shared demo stubs used by gallery, the embed other sites use, and verification. Use when changing files under demo/, including demo/src/embed/, changing gallery consumers of demo/src/stubs/, or running and validating the demo.
description: Home Assistant standalone demo structure, configurations, URL navigation, mocked APIs, shared demo stubs used by gallery, and verification. Use when changing files under demo/, changing gallery consumers of demo/src/stubs/, or running and validating the demo.
---
# HA Frontend Demo
@@ -52,7 +52,6 @@ http://localhost:8090/?demo=<second slug>#/energy/water
- `demo/src/configs/<slug>/`: One directory per demo configuration, containing entities, dashboard, and theme data.
- `demo/src/configs/demo-configs.ts`: Registry of demo configurations and URL slug handling.
- `demo/src/stubs/`: Mocked WebSocket and REST APIs.
- `demo/src/embed/`: The embed, built as `embed.js`. Its `ha-embed-*` elements put cards, sections, views, and dashboards on other sites, against a mocked backend.
- `demo/script/develop_demo`, `demo/script/build_demo`: Development server and static build wrappers.
## Core Data
@@ -65,15 +64,6 @@ The service descriptions in `src/fake_data/demo_services.ts` and the trigger and
The two consumers use a stub differently, so demo behavior does not predict gallery behavior. A gallery page calls stubs against the `hass` from `provideHass`, where `hass.config` is the shared `demoConfig` object. A stub that mutates `hass.config` in place is therefore visible to the page. `demo/src/ha-demo.ts` copies `components` into a new array before the stubs run, so the same mutation never reaches the demo. A change can look correct in the demo while quietly breaking a gallery page.
## Embed
The embed puts parts of the dashboard on any web page, against a mocked backend: a single card with `ha-embed-card`, a section with `ha-embed-section`, a view with `ha-embed-view`, and a whole dashboard with `ha-embed-dashboard`. An `ha-embed-provider` holds the entities and other data they share. The live dashboard demos on home-assistant.io use it, and so can card authors, following the embed's page on contributors.home-assistant.io. Treat the `ha-embed-*` element names, their attributes, and the data the provider takes as a public API.
- `demo/src/html/components.html.template` documents the embed, at `/components.html` of the demo. Update it in the same pull request as an embed change.
- The provider takes most of its mocks from `demo/src/stubs/`, so a stub change reaches the embed as well as the demo and the gallery.
- demo.home-assistant.io deploys from `master`, and the development demo from `dev` (`.github/workflows/demo_deployment.yaml`), so other sites get an embed change only once it is released.
- When the embed's elements or data change, or a change alters what a live demo can show, follow "Documentation Elsewhere" in `ha-frontend-review`.
## Verification
Load `ha-frontend-testing` and use its demo and gallery workflows. Validate both consumers when changing shared stubs. Documentation-only changes do not require code tests unless examples or commands change.
@@ -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}`.
- Content that takes a skeleton's place fades in over `--ha-animation-duration-fast`, which reduced motion makes instant. `ha-skeleton-overlay` does this for you. Elsewhere, use `skeletonOr(loading, skeleton, () => content)` from `src/components/skeleton/skeleton-arrival.ts`: it shows the skeleton while loading and fades the content in once when it replaces it, but not where no skeleton showed, such as table rows made as the table scrolls. Put text in an element of its own inside the content, as only elements fade. For content that fills in where it already is, such as a log, call `fadeInArrival(element)` once when its skeleton goes. Don't add any other fade to loaded content.
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).
+2 -16
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-review
description: Home Assistant frontend PR and review guidance, including implementation quality, existing review feedback, established design patterns, the authority of UI/UX evidence, and documentation needed in other repositories. Use when reviewing frontend changes, preparing a PR, checking recurring review issues, applying the PR template, or working out which docs a change needs.
description: Home Assistant frontend PR and review guidance, including implementation quality, existing review feedback, established design patterns, and the authority of UI/UX evidence. Use when reviewing frontend changes, preparing a PR, checking recurring review issues, or applying the PR template.
---
# HA Frontend Review
@@ -20,23 +20,10 @@ 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.
## Documentation Elsewhere
A frontend change that adds or changes something users see or configure, or an API others build on, needs companion documentation in the user or contributor docs, or the docs miss it. Spot this while making the change, and recommend the documentation changes it needs.
- home-assistant.io documents what users see and configure: a new card, badge, card feature, or heading entity; a new, changed, or removed option or default; a renamed label or menu path; and anything visible that its pages show, in screenshots or in live demos of the demo embed.
- contributors.home-assistant.io documents the design of components and cards in its Design area, and the APIs that custom cards, badges, card features, strategies, and themes use. When a change touches something they could rely on, search its custom UI and Marketplace pages for it. Announce a removal or rename there in a blog post.
To make the change:
- Read the other repository's agent instructions and skills first, and follow them for where and how the change goes.
- Docs follow what people can use. User docs can wait until a feature is usable, such as the last pull request of a stack, and an API still being tried out may stay undocumented, so recommend the docs.
- When a documentation pull request goes with a frontend one, link them to each other, and say in the description when one needs the other merged first.
## Pre-Submission Checklist
- `pnpm lint` passes when practical for the scope.
@@ -47,7 +34,6 @@ To make the change:
- Entity existence is checked before property access.
- Event listeners and subscriptions are cleaned up.
- UI is accessible to screen readers and keyboard users.
- Documentation the change needs in other repositories is linked.
## Recurring Review Issues
@@ -10,14 +10,12 @@ Use this skill when editing CSS, layout, visual hierarchy, theme integration, re
## Theme And Layout Basics
- Use Home Assistant CSS custom properties instead of hardcoded colors.
- CSS in the static HTML templates under `src/html/` must give custom properties a fallback value (for example `var(--ha-space-4, 16px)`), because the global tokens only exist once the JS-appended global stylesheet from `append-ha-style` has loaded.
- Use `--ha-space-*` spacing tokens instead of hardcoded spacing where possible.
- Keep components mobile-first and enhance for desktop.
- Keep layouts RTL-safe. Prefer logical properties when they fit.
- Prefer `ha-*` components and current Web Awesome wrappers.
- Avoid adding new legacy Material Web Components (`mwc-*`).
- Scope styles to the component. Do not rely on global styles for component internals.
- Themes set theme variables and design tokens by name, so renaming or removing one breaks them. The theme variables reference on contributors.home-assistant.io is generated from the frontend, but its theme guides may need a change too: follow "Documentation Elsewhere" in `ha-frontend-review`.
Spacing tokens are defined in `src/resources/theme/core.globals.ts`. The scale runs from `--ha-space-1` at 4px through `--ha-space-20` at 80px in 4px increments. Common values are `--ha-space-2` at 8px, `--ha-space-4` at 16px, and `--ha-space-8` at 32px.
-1
View File
@@ -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
+1 -2
View File
@@ -20,9 +20,8 @@ runs:
steps:
- name: Build ${{ inputs.target }}
shell: bash
run: ./node_modules/.bin/gulp "$TARGET"
run: ./node_modules/.bin/gulp ${{ inputs.target }}
env:
TARGET: ${{ inputs.target }}
GITHUB_TOKEN: ${{ inputs.github-token }}
IS_TEST: ${{ inputs.is-test }}
RSPACK_CACHE: ${{ inputs.rspack-cache }}
+3 -4
View File
@@ -35,12 +35,11 @@ runs:
NETLIFY_AUTH_TOKEN: ${{ inputs.auth-token }}
NETLIFY_SITE_ID: ${{ inputs.site-id }}
run: |
# Execute the deployment (--filter picks the root workspace project,
# --no-build because we deploy an already built directory)
# Execute the deployment
if [ -n "$ALIAS" ]; then
npx -y netlify-cli deploy --filter home-assistant-frontend --no-build --dir="$DIR" --alias "$ALIAS" --json > deploy_output.json
npx -y netlify-cli deploy --dir="$DIR" --alias "$ALIAS" --json > deploy_output.json
else
npx -y netlify-cli deploy --filter home-assistant-frontend --no-build --dir="$DIR" --prod --json > deploy_output.json
npx -y netlify-cli deploy --dir="$DIR" --prod --json > deploy_output.json
fi
# Collect the urls from the deployment output
@@ -16,7 +16,6 @@ runs:
with:
path: |
node_modules
packages/*/node_modules
~/.local/share/pnpm/store
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
@@ -36,7 +35,6 @@ runs:
with:
path: |
node_modules
packages/*/node_modules
~/.local/share/pnpm/store
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
-1
View File
@@ -28,7 +28,6 @@ runs:
with:
path: |
node_modules
packages/*/node_modules
~/.local/share/pnpm/store
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
-19
View File
@@ -40,22 +40,3 @@ jobs:
curl -sSfL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz actionlint
./actionlint -color
zizmor:
name: Check workflow security
runs-on: ubuntu-latest
env:
# renovate: datasource=github-releases depName=zizmorcore/zizmor
ZIZMOR_VERSION: 1.33.1
steps:
- name: Check out files from GitHub
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run zizmor
env:
GH_TOKEN: ${{ github.token }}
run: |
curl -sSfL "https://github.com/zizmorcore/zizmor/releases/download/v${ZIZMOR_VERSION}/zizmor-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz zizmor
./zizmor --format=github .
+1 -1
View File
@@ -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
+21 -21
View File
@@ -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
+2 -2
View File
@@ -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"
+1 -1
View File
@@ -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
+1 -3
View File
@@ -47,6 +47,4 @@ jobs:
site-id: ${{ secrets.NETLIFY_GALLERY_SITE_ID }}
- name: Generate summary
env:
NETLIFY_URL: ${{ steps.deploy.outputs.netlify_url }}
run: echo "$NETLIFY_URL" >> "$GITHUB_STEP_SUMMARY"
run: echo "${{ steps.deploy.outputs.netlify_url }}" >> "$GITHUB_STEP_SUMMARY"
+4 -4
View File
@@ -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.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
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.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
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.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
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.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001 --ipc=host
defaults:
run:
-3
View File
@@ -2,8 +2,6 @@ name: "Pull Request Labeler"
on: pull_request_target # zizmor: ignore[dangerous-triggers] -- safe: checks out base repo scripts only and reads PR files through the API, never PR head code
permissions: {}
# Runs one at a time per pull request, so an older run can't undo a newer one
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
@@ -15,7 +13,6 @@ jobs:
contents: read
pull-requests: write
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Apply labels
id: labeler
@@ -20,7 +20,6 @@ jobs:
check:
name: Check pull request follows contribution standards
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
pull-requests: write # To label and comment on pull requests
steps:
+1 -1
View File
@@ -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 }}
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -1 +1 @@
24.23.0
24.22.2
+4 -8
View File
@@ -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.
@@ -49,17 +48,14 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-testing`: lint, typecheck, Vitest, Playwright e2e dev servers, and benchmarks.
- `ha-frontend-query-params`: typed URL query params, `QueryParamsController`, data table URL sync, in-app links, and My Home Assistant redirect params.
- `ha-frontend-user-facing-text`: localization, terminology, sentence case, and Home Assistant text style.
- `ha-frontend-review`: PR template use, documentation needed in other repositories, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
- `ha-frontend-review`: PR template use, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
- `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, the embed other sites use, 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.
Keep skills current with the code they describe. When a change makes a skill wrong, or adds an area no skill covers yet, update or add the skill in the same pull request, or in one stacked on it. Change skills in a pull request of their own only for a large rework.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
## 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
+42 -107
View File
@@ -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.
+4
View File
@@ -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/")
+7 -1
View File
@@ -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.
+1 -3
View File
@@ -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}`);
}
@@ -1,3 +1,4 @@
/* global module, require */
// rspack/webpack loader that minifies the HTML, SVG, and CSS inside lit
// tagged template literals using `minify-literals` (html-minifier-next +
// lightningcss). Replaces the unmaintained babel-plugin-template-html-minifier.
@@ -35,14 +36,6 @@ const initLoader = (browserslistEnv) => {
return {
minifyHTMLLiterals: minifyModule.minifyHTMLLiterals,
lightningcssTargets,
// With the legacy floor at Chrome 67, lightningcss rewrites rgba()
// to 8-digit hex (#rrggbbaa). Some kiosk webviews served the legacy
// build (e.g. Shelly Wall Display) can't parse that, so any
// var(--divider-color) border falls back to currentColor. Always
// compile hex alpha colors to rgba() in legacy builds.
lightningcssInclude: browserslistEnv.startsWith("legacy")
? lightningcssModule.Features.HexAlphaColors
: 0,
};
})
);
@@ -74,13 +67,12 @@ module.exports = function minifyTemplateLiteralsLoader(source, map, meta) {
const { browserslistEnv } = this.getOptions();
initLoader(browserslistEnv)
.then(({ minifyHTMLLiterals, lightningcssTargets, lightningcssInclude }) =>
.then(({ minifyHTMLLiterals, lightningcssTargets }) =>
minifyHTMLLiterals(source, {
fileName: this.resourcePath,
html: htmlOptions,
css: {
targets: lightningcssTargets,
include: lightningcssInclude,
},
})
)
+4 -41
View File
@@ -68,42 +68,8 @@ const CONFIG_FILES = [
path.join(__dirname, "lit-disable-dev-mode-loader.cjs"),
path.join(__dirname, "babel-plugins", "custom-polyfill-plugin.js"),
path.join(__dirname, "babel-plugins", "inline-constants-plugin.cjs"),
// Its exports define the components source aliases below
path.join(__dirname, "..", "packages", "components", "package.json"),
];
// Resolve @home-assistant/components entry points to their sources, so the package
// needs no build step during development. The entry points are read from the
// "ha-source" export condition of the package; subpath patterns are expanded
// for every element, i.e. every directory with a global.ts, like "card".
const COMPONENTS_PACKAGE_DIR = path.join(
paths.root_dir,
"packages",
"components"
);
const COMPONENTS_SRC_DIR = path.join(
COMPONENTS_PACKAGE_DIR,
"src",
"components"
);
const componentElements = fs
.readdirSync(COMPONENTS_SRC_DIR, { recursive: true })
.filter((file) => path.basename(file) === "global.ts")
.map((file) => path.dirname(file).split(path.sep).join("/"));
const componentsSourceAliases = Object.fromEntries(
Object.entries(require("../packages/components/package.json").exports)
.filter(([, target]) => target["ha-source"])
.flatMap(([subpath, target]) =>
(subpath.includes("*") ? componentElements : [undefined]).map((name) => [
`${path.posix.join("@home-assistant/components", name ? subpath.replaceAll("*", name) : subpath)}$`,
path.join(
COMPONENTS_PACKAGE_DIR,
name ? target["ha-source"].replaceAll("*", name) : target["ha-source"]
),
])
)
);
// Patches change a package's files but not its version, which is all the
// node_modules snapshot checks, so their contents go into the version too.
const PATCHES_DIR = path.join(paths.root_dir, "patches");
@@ -278,9 +244,6 @@ const createRspackConfig = ({
path: paths.root_dir,
env: "legacy",
}),
// Keep rgba() instead of #rrggbbaa, see
// minify-template-literals-loader.cjs
include: { hexAlphaColors: true },
},
},
],
@@ -465,10 +428,6 @@ const createRspackConfig = ({
"src/resources/polyfills/bigdecimal.ts"
),
}),
...componentsSourceAliases,
// elkjs isn't installed (see pnpm-workspace.yaml), so Mermaid's ELK
// layout chunk gets an empty module
"elkjs/lib/elk.bundled.js": false,
"lit/static-html$": "lit/static-html.js",
"lit/decorators$": "lit/decorators.js",
"lit/directive$": "lit/directive.js",
@@ -511,8 +470,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":
+5 -5
View File
@@ -1,5 +1,5 @@
/*
Cache-Control: public, max-age=0, s-maxage=3600, must-revalidate
Cache-Control: public, max-age: 0, s-maxage=3600, must-revalidate
Content-Security-Policy: form-action https:
Feature-Policy: vibrate 'none'; geolocation 'none'; midi 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; vibrate 'none'; payment 'none'
Referrer-Policy: no-referrer-when-downgrade
@@ -8,13 +8,13 @@
X-XSS-Protection: 1; mode=block
/images/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
/manifest.json
Cache-Control: public, max-age=3600, s-maxage=3600
Cache-Control: public, max-age: 3600, s-maxage=3600
/frontend_es5/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
/frontend_latest/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
+1 -1
View File
@@ -1,6 +1,6 @@
{
"background_color": "#FFFFFF",
"description": "Show Home Assistant on your Chromecast or Google Home devices with a screen.",
"description": "Show Home Assistant on your Chromecast or Google Assistant devices with a screen.",
"dir": "ltr",
"display": "standalone",
"icons": [
+2 -2
View File
@@ -5,7 +5,7 @@
<meta property="og:type" content="website" />
<meta
property="og:description"
content="Show Home Assistant on your Chromecast or Google Home devices with a screen."
content="Show Home Assistant on your Chromecast or Google Assistant devices with a screen."
/>
<meta
property="og:image"
@@ -16,7 +16,7 @@
<meta name="twitter:title" content="Home Assistant Cast" />
<meta
name="twitter:description"
content="Show Home Assistant on your Chromecast or Google Home devices with a screen."
content="Show Home Assistant on your Chromecast or Google Assistant devices with a screen."
/>
<meta
name="twitter:image"
+2 -3
View File
@@ -3,7 +3,6 @@
<head>
<title>Home Assistant Cast - FAQ</title>
<link rel="icon" href="/images/ha-cast-icon.png" type="image/png" />
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
body {
@@ -53,7 +52,7 @@
<p>
Home Assistant Cast allows you to show your Home Assistant data on a
Chromecast device and allows you to interact with Home Assistant on
Google Home devices with a screen.
Google Assistant devices with a screen.
</p>
</div>
@@ -100,7 +99,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>
-1
View File
@@ -4,7 +4,6 @@
<title>Home Assistant Cast</title>
<link rel="manifest" href="/manifest.json" />
<link rel="icon" href="/images/ha-cast-icon.png" type="image/png" />
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
body {
-1
View File
@@ -4,7 +4,6 @@
<% for (const entry of latestEntryJS) { %>
<script type="module" src="<%= entry %>"></script>
<% } %>
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
body {
+1 -1
View File
@@ -48,7 +48,7 @@ const translateErr = (err) =>
const INTRO = html`
<p>
Home Assistant Cast allows you to cast your Home Assistant installation to
Chromecast video devices and to Google Home devices with a screen.
Chromecast video devices and to Google Assistant devices with a screen.
</p>
<p>
For more information, see the
+1 -1
View File
@@ -6,7 +6,7 @@ const playerManager = castContext.getPlayerManager();
playerManager.setMessageInterceptor("LOAD", (loadRequestData) => {
const media = loadRequestData.media;
// Special handling if it came from Google Home
// Special handling if it came from Google Assistant
if (media.entity) {
media.contentId = media.entity;
media.streamType = "LIVE";
+1 -1
View File
@@ -13,7 +13,7 @@ export const castDemoLovelace: () => LovelaceConfig = () => {
{
type: "markdown",
title: "Home Assistant Cast",
content: `With Home Assistant you can easily create interfaces (just like this one) which can be shown on Chromecast devices connected to TVs or Google Home devices with a screen.${
content: `With Home Assistant you can easily create interfaces (just like this one) which can be shown on Chromecast devices connected to TVs or Google Assistant devices with a screen.${
touchSupported
? "\n\nYou are able to interact with this demo using the touch screen."
: "\n\nOn a Google Nest Hub you are able to interact with Home Assistant Cast via the touch screen."
+1 -1
View File
@@ -117,7 +117,7 @@ playerManager.setMessageInterceptor("LOAD", (loadRequestData) => {
// We received a play media command, hide Lovelace and show media player
showMediaPlayer();
const media = loadRequestData.media;
// Special handling if it came from Google Home
// Special handling if it came from Google Assistant
if (media.entity) {
media.contentId = media.entity;
media.streamType = "LIVE";
+2 -2
View File
@@ -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;
}
`;
}
+1 -2
View File
@@ -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"
);
+1 -2
View File
@@ -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 || "");
+5 -5
View File
@@ -1,21 +1,21 @@
/*
Cache-Control: public, max-age=0, s-maxage=3600, must-revalidate
Cache-Control: public, max-age: 0, s-maxage=3600, must-revalidate
Content-Security-Policy: form-action https:
Referrer-Policy: no-referrer-when-downgrade
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
/api/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
/assets/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
/frontend_es5/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
/frontend_latest/*
Cache-Control: public, max-age=604800, s-maxage=604800
Cache-Control: public, max-age: 604800, s-maxage=604800
Access-Control-Allow-Origin: *
/embed.js
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

+2 -1
View File
@@ -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,
};
+1
View File
@@ -0,0 +1 @@
export const demoThemeArsaboo = () => ({});
+2 -7
View File
@@ -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));
-2
View File
@@ -48,8 +48,6 @@ class DemoHomeDashboardStrategy extends ReactiveElement {
),
};
}
static getConfigElement = HomeDashboardStrategy.getConfigElement;
}
class DemoHomeOverviewViewStrategy extends ReactiveElement {
File diff suppressed because it is too large. Load diff
+28 -33
View File
@@ -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",
});
+28 -30
View File
@@ -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",
});
+18 -23
View File
@@ -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)",
});
+1 -7
View File
@@ -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 };
+88
View File
@@ -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);
+198
View File
@@ -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");
}
+3 -8
View File
@@ -1,5 +1,5 @@
import { ContextProvider, provide } from "@lit/context";
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
@@ -168,8 +168,7 @@ export class HaEmbedProvider extends LitElement {
hass.mockWS("config/device_registry/list", (_msg, currentHass) =>
Object.values(currentHass.devices)
);
// The registry of the entities, with the options each entity sets, such
// as timer presets. Other settings, such as calendar colors, are not set.
// The registry of the entities, without settings such as calendar colors
const registryEntries = (currentHass: MockHomeAssistant) =>
Object.values(currentHass.entities).map(
(entity): EntityRegistryEntry => ({
@@ -180,9 +179,6 @@ export class HaEmbedProvider extends LitElement {
}),
area_id: entity.area_id ?? null,
device_id: entity.device_id ?? null,
options:
this.entities.find((item) => item.entity_id === entity.entity_id)
?.options ?? null,
})
);
hass.mockWS("config/entity_registry/list", (_msg, currentHass) =>
@@ -207,7 +203,6 @@ export class HaEmbedProvider extends LitElement {
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
this._applyColorScheme();
@@ -317,6 +312,6 @@ declare global {
"ha-embed-provider": HaEmbedProvider;
}
interface HASSDomEvents {
"states-changed": { states: HassEntityStates };
"states-changed": { states: HassEntities };
}
}
+2 -4
View File
@@ -580,10 +580,8 @@ provider.entities = Object.values(provider.hass.states).map((entity) =&gt;
<ul>
<li>
<code>areas</code>: a list of areas, each with an
<code>area_id</code> and a <code>name</code>, and optionally an
<code>icon</code> and a <code>picture</code>, the URL of an image.
Without it, each <code>area_id</code> of the entities and devices
becomes an area.
<code>area_id</code> and a <code>name</code>. Without it, each
<code>area_id</code> of the entities and devices becomes an area.
</li>
<li>
<code>devices</code>: a list of devices, each with an
+90 -3
View File
@@ -35,12 +35,13 @@
/>
<meta name="theme-color" content="#03a9f4" />
<%= renderTemplate("_social_meta.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
html {
background-color: var(--primary-background-color, #fafafa);
color: var(--primary-text-color, #212121);
height: 100vh;
/* Prevent iOS Safari from inflating text when rotating to landscape */
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
@media (prefers-color-scheme: dark) {
html {
@@ -48,8 +49,94 @@
color: var(--primary-text-color, #e1e1e1);
}
}
body {
font-family: Roboto, Noto, sans-serif;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-weight: 400;
height: 100vh;
margin: 0;
padding: 0;
}
#ha-launch-screen {
font-family: ui-sans-serif, system-ui, sans-serif;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
user-select: none;
-webkit-user-select: none;
transition: opacity var(--ha-animation-duration-normal, 250ms) ease-out;
}
#ha-launch-screen.removing {
opacity: 0;
}
@keyframes launch-lockup-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#ha-launch-screen .ha-lockup {
display: flex;
align-items: center;
flex-shrink: 0;
animation: launch-lockup-in var(--ha-animation-duration-normal, 250ms) ease-out both;
}
#ha-launch-screen-info-box > *,
#ha-launch-screen .ohf-logo {
animation: launch-lockup-in var(--ha-animation-duration-normal, 250ms) ease-out both;
}
#ha-launch-screen .ha-logo {
width: 96px;
height: 96px;
}
#ha-launch-screen .ha-launch-screen-spacer-top {
flex: 1;
margin-top: calc( 2 * max(var(--safe-area-inset-top, 0px), 48px) + 46px );
padding-top: 48px;
}
#ha-launch-screen .ha-launch-screen-spacer-bottom {
flex: 1;
padding-top: 16px;
}
.ohf-logo {
margin: max(var(--safe-area-inset-bottom, 0px), 48px) 0;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
opacity: .66;
}
.ohf-logo span {
font-size: 12px;
line-height: 12px;
text-transform: uppercase;
}
.ohf-logo picture {
display: flex;
}
.ohf-logo img {
width: 237px;
aspect-ratio: 237 / 24;
height: auto;
}
@media (max-height: 560px) {
#ha-launch-screen .ha-launch-screen-spacer-top {
margin-top: 24px;
padding-top: 24px;
}
#ha-launch-screen .ha-launch-screen-spacer-bottom {
padding-top: 16px;
}
.ohf-logo {
margin-block: 24px;
}
}
</style>
<%= renderTemplate("../../../src/html/_style_launch_screen.html.template") %>
</head>
<body>
<div id="ha-launch-screen">
+1 -3
View File
@@ -6,8 +6,6 @@ export interface DemoArea {
name: string;
floor_id?: string;
icon?: string;
// An image URL, such as for an area card with `display_type: picture`
picture?: string;
temperature_entity_id?: string;
humidity_entity_id?: string;
}
@@ -23,7 +21,7 @@ export const toAreaRegistryEntry = (area: DemoArea): AreaRegistryEntry => ({
humidity_entity_id: area.humidity_entity_id ?? null,
aliases: [],
labels: [],
picture: area.picture ?? null,
picture: null,
created_at: 0,
modified_at: 0,
});
+1 -1
View File
@@ -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",
+1 -1
View File
@@ -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 -3
View File
@@ -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 },
}));
};
@@ -44,21 +44,14 @@ export const lorawanFixtures: ConnectivityFixtures = {
],
commands: ["lorawan/"],
manifests: [
manifest("lorawan", "LoRaWAN", {
config_flow: false,
integration_type: "service",
}),
manifest("lorawan", "LoRaWAN", { integration_type: "helper" }),
manifest("sensecap_lorawan", "SenseCAP", {
integration_type: "device",
dependencies: ["lorawan"],
}),
manifest("chirpstack", "ChirpStack", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
manifest("chirpstack", "ChirpStack", { integration_type: "hub" }),
manifest("thethingsnetwork_lorawan", "The Things Network", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
],
configEntries: [
@@ -10,26 +10,19 @@ export const FRONIUS_ENTRY_ID = "mock-fronius";
export const RS485_PORT = "/dev/ttyUSB1";
export const modbusFixtures: ConnectivityFixtures = {
components: ["modbus", "flexit", "solaredge_modbus", "fronius"],
components: ["modbus"],
commands: ["modbus/"],
manifests: [
manifest("modbus", "Modbus", {
config_flow: false,
iot_class: "local_polling",
}),
manifest("flexit", "Flexit", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("solaredge_modbus", "SolarEdge Modbus", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("fronius", "Fronius", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
],
-67
View File
@@ -1,67 +0,0 @@
// Made-up values for the mock history and statistics that look like a real
// home and are the same on every load, so a chart doesn't change each time
// the page opens.
const HOUR = 60 * 60 * 1000;
/** A number from 0 up to 1 for each key, the same every time. */
export const hashFraction = (key: string): number => {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash * 31 + key.charCodeAt(i)) % 2147483647;
}
return hash / 2147483647;
};
/**
* How far a value drifts from its state: 10% of it, or 5% above 80, as for a
* temperature or a power reading. A state of 0 drifts by up to 1.
*/
export const driftScale = (value: number): number =>
value === 0 ? 1 : Math.abs(value) * (Math.abs(value) > 80 ? 0.05 : 0.1);
/**
* A drifted reading kept on the same side of 0 as the state, as a reading such
* as a power or a speed doesn't cross 0. A state of 0 stays at 0 or above.
*/
export const sameSideOfZero = (value: number, drifted: number): number =>
value < 0 ? Math.min(drifted, 0) : Math.max(drifted, 0);
// The point each wave starts at, kept once picked from its key, as a long
// period asks for the drift of hundreds of thousands of hours
const phases = new Map<string, number>();
const phase = (key: string): number => {
let value = phases.get(key);
if (value === undefined) {
value = 2 * Math.PI * hashFraction(key);
phases.set(key, value);
}
return value;
};
const wave = (key: string, time: number, period: number): number =>
Math.sin((2 * Math.PI * time) / period + phase(key));
/**
* The value of an entity at a time, drifting slowly around its state: a swing
* over the day and two faster, smaller ones, each starting at a point picked
* from the entity ID.
*/
export const driftedValue = (
key: string,
time: number,
value: number
): number =>
sameSideOfZero(
value,
value +
driftScale(value) *
(0.6 * wave(`${key}:day`, time, 24 * HOUR) +
0.3 * wave(`${key}:hours`, time, 5 * HOUR) +
0.1 * wave(`${key}:hour`, time, 1.3 * HOUR))
);
+7 -35
View File
@@ -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",
@@ -112,28 +97,15 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.water_garden",
},
],
device_consumption_gas: [
{
stat_consumption: "sensor.gas_kitchen",
},
{
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 }, () => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
-95
View File
@@ -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",
@@ -235,26 +160,6 @@ export const energyEntities = () =>
unit_of_measurement: "L",
},
},
"sensor.gas_kitchen": {
entity_id: "sensor.gas_kitchen",
state: "100",
attributes: {
friendly_name: "Gas kitchen",
unit_of_measurement: "m³",
device_class: "gas",
state_class: "total_increasing",
},
},
"sensor.gas_heat_pump": {
entity_id: "sensor.gas_heat_pump",
state: "500",
attributes: {
friendly_name: "Gas heat pump",
unit_of_measurement: "m³",
device_class: "gas",
state_class: "total_increasing",
},
},
"sensor.energy_car": {
entity_id: "sensor.energy_car",
state: "4",
+7 -33
View File
@@ -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);
};
+23 -102
View File
@@ -1,10 +1,9 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HistoryStates } from "../../../src/data/history";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import { driftedValue, hashFraction } from "./drift";
const generateStateHistory = (
state: HassEntityState,
state: HassEntity,
deltas,
start_date: Date,
end_date: Date
@@ -41,76 +40,6 @@ const generateStateHistory = (
const incrementalUnits = ["clients", "queries", "ads"];
// Changes over the range of an on/off entity, ending in its state
const ON_OFF_CHANGES = 6;
// The most points of a number over the range
const NUMBER_POINTS = 96;
// An on/off entity, such as a light, switches a few times over the range, at
// times picked from its entity ID, and ends in its state
const generateOnOffHistory = (
state: HassEntityState,
start: Date,
end: Date
): HistoryStates[string] => {
const span = end.getTime() - start.getTime();
const opposite = state.state === "on" ? "off" : "on";
return Array.from({ length: ON_OFF_CHANGES }, (_, index) => {
const time =
index === 0
? start.getTime()
: start.getTime() +
(span *
(index - 0.3 + 0.6 * hashFraction(`${state.entity_id}:${index}`))) /
ON_OFF_CHANGES;
return {
a: state.attributes,
s: (ON_OFF_CHANGES - 1 - index) % 2 === 0 ? state.state : opposite,
lc: time / 1000,
lu: time / 1000,
};
});
};
// A number drifts around its state over the range, the same on every load,
// with as many decimals as its state, and ends in its state
const generateNumberHistory = (
state: HassEntityState,
value: number,
start: Date,
end: Date
): HistoryStates[string] => {
const decimals = Math.max(state.state.split(".")[1]?.length ?? 0, 1);
const step = Math.max(
(end.getTime() - start.getTime()) / NUMBER_POINTS,
5 * 60 * 1000
);
const history: HistoryStates[string] = [];
for (let time = start.getTime(); time < end.getTime(); time += step) {
history.push({
a: state.attributes,
s: driftedValue(state.entity_id, time, value).toFixed(decimals),
lc: time / 1000,
lu: time / 1000,
});
}
history.push({
a: state.attributes,
s: state.state,
lc: end.getTime() / 1000,
lu: end.getTime() / 1000,
});
return history;
};
export const mockHistory = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"history/stream",
@@ -141,11 +70,6 @@ export const mockHistory = (mockHass: MockHomeAssistant) => {
continue;
}
if (state.state === "on" || state.state === "off") {
states[entityId] = generateOnOffHistory(state, start, end);
continue;
}
if (!state.attributes.unit_of_measurement) {
states[entityId] = generateStateHistory(
state,
@@ -168,35 +92,32 @@ export const mockHistory = (mockHass: MockHomeAssistant) => {
continue;
}
if (!incrementalUnits.includes(state.attributes.unit_of_measurement)) {
states[entityId] = generateNumberHistory(
state,
numberState,
start,
end
);
continue;
}
// A counter climbs to its state
const statesToGenerate = 15;
let genFunc;
let initial = Math.floor(
numberState * 0.4 + numberState * Math.random() * 0.2
);
const diff = Math.max(
1,
Math.floor((numberState - initial) / statesToGenerate)
);
if (incrementalUnits.includes(state.attributes.unit_of_measurement)) {
let initial = Math.floor(
numberState * 0.4 + numberState * Math.random() * 0.2
);
const diff = Math.max(
1,
Math.floor((numberState - initial) / statesToGenerate)
);
genFunc = () => {
initial += diff;
return Math.min(numberState, initial);
};
} else {
const diff = Math.floor(
numberState * (numberState > 80 ? 0.05 : 0.5)
);
genFunc = () =>
numberState - diff + Math.floor(Math.random() * 2 * diff);
}
states[entityId] = generateStateHistory(
state,
Array.from({ length: statesToGenerate }, () => {
initial += diff;
return Math.min(numberState, initial);
}),
Array.from({ length: statesToGenerate }, genFunc),
start,
end
);
-10
View File
@@ -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,
+59 -424
View File
@@ -1,37 +1,19 @@
import { TZDate } from "@date-fns/tz";
import type { Day } from "date-fns";
import {
addDays,
addHours,
addMinutes,
addMonths,
addWeeks,
addYears,
constructFrom,
differenceInHours,
endOfDay,
startOfDay,
startOfHour,
startOfMonth,
startOfWeek,
startOfYear,
} from "date-fns";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HaDurationData } from "../../../src/components/ha-duration-input";
import type {
Statistic,
Statistics,
StatisticsMetaData,
StatisticsUnitConfiguration,
StatisticValue,
} from "../../../src/data/recorder";
import { StatisticMeanType } from "../../../src/data/recorder";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import {
driftedValue,
driftScale,
hashFraction,
sameSideOfZero,
} from "./drift";
const getFirstDate = (
start: Date,
@@ -49,57 +31,34 @@ const getNextDate = (
currentDate: Date,
period: "5minute" | "hour" | "day" | "month"
): Date => {
if (period === "day") {
return addDays(currentDate, 1);
}
if (period === "month") {
return addMonths(currentDate, 1);
}
// An hour or 5 minutes is the same length in any timezone, so a plain Date
// will do. Making a timezone date for each one is slow over a long period,
// which has hundreds of thousands of hours.
return new Date(
currentDate.getTime() + (period === "hour" ? 60 : 5) * 60 * 1000
);
return period === "day"
? addDays(currentDate, 1)
: period === "month"
? addMonths(currentDate, 1)
: period === "hour"
? addHours(currentDate, 1)
: addMinutes(currentDate, 5);
};
// The mean of each period drifts around the entity's state, as its history
// does, and the same on every load. Longer periods span more of the drift.
// The values drift in the entity's unit, then are multiplied by factor to give
// them in the unit asked for.
const generateMeanStatistics = (
id: string,
start: Date,
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
value: number,
factor = 1
maxDiff: number
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
const spread =
driftScale(value) *
(period === "5minute" || period === "hour" ? 0.2 : 0.8) *
factor;
let currentDate = getFirstDate(start, period);
const now = new Date();
while (end > currentDate && currentDate < now) {
const delta = Math.random() * maxDiff;
const mean = delta;
const nextDate = getNextDate(currentDate, period);
const mean =
driftedValue(
id,
(currentDate.getTime() + nextDate.getTime()) / 2,
value
) * factor;
statistics.push({
start: currentDate.getTime(),
end: nextDate.getTime(),
mean,
min: sameSideOfZero(value, mean - spread),
max: sameSideOfZero(value, mean + spread),
min: mean - Math.random() * maxDiff,
max: mean + Math.random() * maxDiff,
last_reset: 0,
state: mean,
sum: null,
@@ -114,9 +73,7 @@ const generateSumStatistics = (
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
initValue: number,
maxDiff: number | ((start: Date, end: Date) => number),
// A number from 0 up to 1 for each period's share of maxDiff
random: (periodStart: Date) => number = () => Math.random()
maxDiff: number | ((start: Date, end: Date) => number)
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
let currentDate = getFirstDate(start, period);
@@ -126,8 +83,7 @@ const generateSumStatistics = (
const nextDate = getNextDate(currentDate, period);
const bound =
typeof maxDiff === "function" ? maxDiff(currentDate, nextDate) : maxDiff;
const add = random(currentDate) * bound;
const add = Math.random() * bound;
sum += add;
statistics.push({
start: currentDate.getTime(),
@@ -202,24 +158,6 @@ const statisticsFunctions: Record<
(bucketStart, bucketEnd) =>
(20 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
),
"sensor.gas_kitchen": (_id, start, end, period = "hour") =>
generateSumStatistics(
start,
end,
period,
100,
(bucketStart, bucketEnd) =>
(0.1 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
),
"sensor.gas_heat_pump": (_id, start, end, period = "hour") =>
generateSumStatistics(
start,
end,
period,
500,
(bucketStart, bucketEnd) =>
(0.6 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
),
"sensor.energy_consumption_tarif_1": (
_id: string,
start: Date,
@@ -395,367 +333,64 @@ 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,
},
};
const hasSum = (stateObj: HassEntityState | undefined): boolean =>
stateObj?.attributes.state_class === "total" ||
stateObj?.attributes.state_class === "total_increasing";
// Like Core, statistics are given in the unit asked for, such as power in kW
// for the energy dashboard while the demo's power sensors are in W
const unitFactor = (
stateObj: HassEntityState | undefined,
units?: StatisticsUnitConfiguration
): number => {
const unit = stateObj?.attributes.unit_of_measurement;
if (unit === "W" && units?.power === "kW") {
return 1 / 1000;
}
if (unit === "kW" && units?.power === "W") {
return 1000;
}
return 1;
};
const getStatistics = (
hass: MockHomeAssistant,
statisticIds: string[],
start: Date,
end: Date,
period: "5minute" | "hour" | "day" | "month",
units?: StatisticsUnitConfiguration
): Statistics => {
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
return cache[id];
};
const scaleStats = (source: string, factor: number) => {
let sum = 0;
return getStats(source).map((statistic) => {
const change = (statistic.change ?? 0) * factor;
sum += change;
return { ...statistic, change, state: sum, sum };
});
};
statisticIds.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);
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
// Like Core, only an entity with a state class has statistics, so the
// history of a light has no empty chart of them
if (entityState && !entityState.attributes.state_class) {
return;
}
const state = entityState ? Number(entityState.state) : 1;
// Each period's share is picked from the entity ID, so a meter's bars
// are the same on every load. The cap grows with the period's length,
// so a day's bar adds up to about 24 hours' worth.
statistics[id] = hasSum(entityState)
? generateSumStatistics(
start,
end,
period,
state,
(periodStart, periodEnd) =>
state *
(state > 80 ? 0.01 : 0.05) *
((periodEnd.getTime() - periodStart.getTime()) / 3600000),
(periodStart) => hashFraction(`${id}:${periodStart.getTime()}`)
)
: generateMeanStatistics(
id,
start,
end,
period,
state,
unitFactor(entityState, units)
);
}
});
return statistics;
};
const durationMs = (duration?: HaDurationData): number =>
duration
? ((duration.days ?? 0) * 24 + (duration.hours ?? 0)) * 3600000 +
(duration.minutes ?? 0) * 60000 +
(duration.seconds ?? 0) * 1000 +
(duration.milliseconds ?? 0)
: 0;
const WEEK_STARTS = {
sun: 0,
mon: 1,
tue: 2,
wed: 3,
thu: 4,
fri: 5,
sat: 6,
} satisfies Record<string, Day>;
interface StatisticDuringPeriodMessage {
statistic_id: string;
types?: string[];
fixed_period?: { start_time?: string; end_time?: string };
calendar?: {
period: "hour" | "day" | "week" | "month" | "year";
offset?: number;
first_weekday?: keyof typeof WEEK_STARTS;
};
rolling_window?: { duration: HaDurationData; offset?: HaDurationData };
units?: StatisticsUnitConfiguration;
}
// The start and end of the period of recorder/statistic_during_period, as
// Core reads it, in the server timezone
const statisticPeriodBounds = (
message: StatisticDuringPeriodMessage,
timeZone: string
): [Date, Date] => {
const now = new TZDate(Date.now(), timeZone);
if (message.fixed_period) {
const { start_time, end_time } = message.fixed_period;
return [
new TZDate(start_time ? Date.parse(start_time) : 0, timeZone),
new TZDate(end_time ? Date.parse(end_time) : Date.now(), timeZone),
];
}
if (message.rolling_window) {
const end = new TZDate(
now.getTime() + durationMs(message.rolling_window.offset),
timeZone
);
return [
new TZDate(
end.getTime() - durationMs(message.rolling_window.duration),
timeZone
),
end,
];
}
if (message.calendar) {
const offset = message.calendar.offset ?? 0;
switch (message.calendar.period) {
case "hour": {
const start = addHours(startOfHour(now), offset);
return [start, addHours(start, 1)];
}
case "week": {
const weekStartsOn =
WEEK_STARTS[message.calendar.first_weekday ?? "mon"];
const start = addWeeks(startOfWeek(now, { weekStartsOn }), offset);
return [start, addWeeks(start, 1)];
}
case "month": {
const start = addMonths(startOfMonth(now), offset);
return [start, addMonths(start, 1)];
}
case "year": {
const start = addYears(startOfYear(now), offset);
return [start, addYears(start, 1)];
}
default: {
const start = addDays(startOfDay(now), offset);
return [start, addDays(start, 1)];
}
}
}
// All the history, which the mock makes up for the last day
return [addDays(now, -1), now];
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"recorder/get_statistics_metadata",
(
{ statistic_ids }: { statistic_ids?: string[] },
hass
): StatisticsMetaData[] =>
(statistic_ids ?? []).flatMap((id) => {
const stateObj = hass.states[id];
if (!stateObj?.attributes.state_class) {
return [];
}
const sum = hasSum(stateObj);
return [
{
statistic_id: id,
source: "recorder",
name: stateObj.attributes.friendly_name ?? null,
statistics_unit_of_measurement:
stateObj.attributes.unit_of_measurement ?? null,
has_sum: sum,
mean_type: sum
? StatisticMeanType.NONE
: StatisticMeanType.ARITHMETIC,
unit_class: null,
},
];
})
(): StatisticsMetaData[] => []
);
mockHass.mockWS(
"recorder/list_statistic_ids",
(): StatisticsMetaData[] => []
);
mockHass.mockWS(
"recorder/statistics_during_period",
(
{ statistic_ids, start_time, end_time, period, units },
hass
): Statistics =>
({ statistic_ids, start_time, end_time, period }, hass): Statistics => {
// Calendar buckets follow the server timezone, independent of the browser.
getStatistics(
hass,
statistic_ids,
new TZDate(start_time, hass.config.time_zone),
new TZDate(end_time ?? Date.now(), hass.config.time_zone),
period,
units
)
);
const start = new TZDate(start_time, hass.config.time_zone);
const end = new TZDate(end_time ?? Date.now(), hass.config.time_zone);
// The statistic card asks for one number over a period: the mean, lowest,
// highest or change of the hourly statistics in it
mockHass.mockWS(
"recorder/statistic_during_period",
(message: StatisticDuringPeriodMessage, hass): Statistic => {
const [start, end] = statisticPeriodBounds(
message,
hass.config.time_zone
);
const id = message.statistic_id;
// Like Core, an ID without statistics, such as a misspelled one, gets
// none, rather than values made up for it
const hasStatistics =
id in hass.states ||
id in statisticsFunctions ||
id in derivedCosts ||
id in derivedBatteryFlows;
// The energy demo's tariffs place their phases from the start they're
// asked for, as the energy dashboard asks from midnight. So the hours
// are made up one day at a time from each midnight, then only those
// inside the period count. Like Core, an hour that runs past the end
// isn't counted, so a day ending at 23:59:59.999 leaves out the hour
// from 23:00.
const days: Date[] = [];
for (
let day = startOfDay(start);
hasStatistics && day < end;
day = addDays(day, 1)
) {
days.push(day);
}
const values = days
.flatMap(
(day) =>
getStatistics(
hass,
[id],
day,
addDays(day, 1),
"hour",
message.units
)[id] ?? []
)
.filter(
(value) =>
value.start >= start.getTime() && value.end <= end.getTime()
);
const numbers = (key: "mean" | "min" | "max" | "change") =>
values.flatMap((value) => (value[key] == null ? [] : [value[key]]));
const means = numbers("mean");
const mins = numbers("min");
const maxes = numbers("max");
const changes = numbers("change");
return {
mean: means.length
? means.reduce((total, mean) => total + mean, 0) / means.length
: null,
// Reduced rather than spread, as a long period has more hours than a
// call can take as arguments
min: mins.length
? mins.reduce((lowest, min) => Math.min(lowest, min))
: null,
max: maxes.length
? maxes.reduce((highest, max) => Math.max(highest, max))
: null,
change: changes.length
? changes.reduce((total, change) => total + change, 0)
: null,
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
return cache[id];
};
statistic_ids.forEach((id: string) => {
if (id in derivedCosts) {
const { source, price } = derivedCosts[id];
let cost = 0;
statistics[id] = getStats(source).map((statistic) => {
const change = statistic.change! * price;
cost += change;
return { ...statistic, change, state: cost, sum: cost };
});
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
const state = entityState ? Number(entityState.state) : 1;
statistics[id] =
entityState &&
(entityState.attributes.state_class === "total" ||
entityState.attributes.state_class === "total_increasing")
? generateSumStatistics(
start,
end,
period,
state,
state * (state > 80 ? 0.01 : 0.05)
)
: generateMeanStatistics(
start,
end,
period,
state * (state > 80 ? 0.05 : 0.1)
);
}
});
return statistics;
}
);
};
-217
View File
@@ -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 -6
View File
@@ -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))
)
);
};
-8
View File
@@ -301,14 +301,6 @@ export default tseslint.config(
globals: globals.node,
},
},
{
// Published as native ESM, where package subpath imports such as
// "lit/decorators.js" need their extension.
files: ["packages/*/src/**/*.ts"],
rules: {
"import-x/extensions": ["error", "ignorePackages", { ts: "never" }],
},
},
{
plugins: {
html,
+1 -2
View File
@@ -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",
-12
View File
@@ -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
View File
@@ -25,6 +25,7 @@ class DemoMoreInfo extends LitElement {
!computeShowNewMoreInfo(state)
? html`<state-card-content
.stateObj=${state}
.hass=${this.hass}
in-dialog
></state-card-content>`
: nothing
-19
View File
@@ -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,
});
}
});
-48
View File
@@ -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 },
],
};
-1
View File
@@ -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",
+2 -2
View File
@@ -4,7 +4,7 @@ title: "Our story"
## Open source home automation that puts local control and privacy first
Home Assistant is a free and open-source software for home automation that is designed to be the central control system for smart home devices with a focus on local control and privacy. It can be accessed via a web-based user interface, via apps for Android and iOS, or using voice commands via a supported virtual assistant like Google Home and Amazon Alexa.
Home Assistant is a free and open-source software for home automation that is designed to be the central control system for smart home devices with a focus on local control and privacy. It can be accessed via a web-based user interface, via apps for Android and iOS, or using voice commands via a supported virtual assistant like Google Assistant and Amazon Alexa.
IoT devices and services are supported by modular support for controlling proprietary ecosystems if they provide public access via an Open API for third-party integrations and protocols like Bluetooth, MQTT, Zigbee, and Z-Wave, After the Home Assistant software application is installed as a computer appliance it will act as a central control system for home automation. Information from all entities it sees can be used and controlled from within scripts trigger automations using scheduling and "blueprint" subroutines, e.g. for controlling lighting, climate, entertainment systems, and appliances.
@@ -36,6 +36,6 @@ Durability for the Open Home means that devices are designed and built to keep w
The project was started as a Python application by Paulus Schoutsen in September 2013 and first published publicly on GitHub in November 2013. In July 2017, a managed operating system called Hass.io was initially introduced to make it easier use to use Home Assistant on single-board computers like the Raspberry Pi series. Its bundled "supervisor" management system allowed users to manage, backup, and update the local installation and introduced the option to extend the functionality of the software with add-ons.
An optional subscription service was introduced in December 2017 for $5/month to solve the complexities associated with secured remote access, as well as linking to Amazon Alexa and Google Home. Nabu Casa, Inc. was formed in September 2018 to take over the subscription service. The company's funding is based solely on revenue from the subscription service. It is used to finance the project's infrastructure and to pay for full-time employees contributing to the project.
An optional subscription service was introduced in December 2017 for $5/month to solve the complexities associated with secured remote access, as well as linking to Amazon Alexa and Google Assistant. Nabu Casa, Inc. was formed in September 2018 to take over the subscription service. The company's funding is based solely on revenue from the subscription service. It is used to finance the project's infrastructure and to pay for full-time employees contributing to the project.
In January 2020, branding was adjusted to make it easier to refer to different parts of the project. The main piece of software was renamed to Home Assistant Core, while the full suite of software with the embedded operating system and bundled "supervisor" management system was renamed to Home Assistant.
@@ -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. |
+7 -7
View File
@@ -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}
+5 -72
View File
@@ -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**
@@ -171,18 +165,6 @@ Interactive row. Renders an inner `<a>` when `href` is set, otherwise a
roving tabindex, the host is the tab stop and the inner element carries
`tabindex="-1"`.
Only the headline and supporting text are inside the `<a>` or `<button>`; its
hit area is stretched over the whole row. The `start` and `end` slots sit next
to it, so controls placed there, like an `ha-icon-button` or `ha-dropdown`,
stay separate controls for screen readers. Slotted elements are raised above
the hit area so they can be clicked, except icons, badges, `span`s and empty
`div`s (dividers), which let clicks and hover through to the row. A focusable
element (with `tabindex`) is always raised. To keep another element clickable
on its own, like a drag handle, give it `z-index: 1` in the consumer's styles.
Subclasses customize the row by overriding `_renderStart()`,
`_renderContent()` and `_renderEnd()`. `_renderInner()` is not used.
**Attributes**
- `href` (String) — when set, renders an `<a>` instead of a `<button>`.
@@ -192,54 +174,8 @@ Subclasses customize the row by overriding `_renderStart()`,
**CSS parts**
- `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 +186,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>`.
-146
View File
@@ -2,28 +2,21 @@ import {
mdiAccount,
mdiChevronRight,
mdiCog,
mdiDelete,
mdiHome,
mdiInformationOutline,
mdiMapMarker,
mdiOpenInNew,
mdiPencil,
mdiViewDashboard,
mdiWifi,
} from "@mdi/js";
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";
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";
@@ -84,8 +77,6 @@ const treeKey = (group: TreeGroup, child: TreeChild) =>
export class DemoHaList extends LitElement {
@state() private _buttonClicks = 0;
@state() private _lastAction = "none";
@state() private _single: number | Set<number> = -1;
@state() private _multiLine: number | Set<number> = new Set();
@@ -96,12 +87,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 +185,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>
@@ -249,101 +220,6 @@ export class DemoHaList extends LitElement {
</ha-list-base>
</ha-card>
<ha-card header="Row with actions in the end slot">
<p class="card-text">
Last action: <code>${this._lastAction}</code>. The action buttons are
separate controls; icons and the divider activate the row.
</p>
<ha-list-base aria-label="Rows with actions">
<ha-list-item-button data-action="row" @click=${this._onActionClick}>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
<span slot="headline">Button row</span>
<span slot="supporting-text">Click the row or an action</span>
<ha-icon-next slot="end"></ha-icon-next>
<div slot="end" class="vertical-divider"></div>
<ha-icon-button
slot="end"
data-action="edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-button
slot="end"
data-action="delete"
.path=${mdiDelete}
label="Delete"
@click=${this._onActionClick}
></ha-icon-button>
</ha-list-item-button>
<ha-list-item-button href="#components/ha-list">
<ha-svg-icon slot="start" .path=${mdiMapMarker}></ha-svg-icon>
<span slot="headline">Link row</span>
<span slot="supporting-text"
>Cmd/Ctrl-click on the icon or chevron opens a new tab</span
>
<ha-icon-button
slot="end"
data-action="link-edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
</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
@@ -552,23 +428,10 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
return value instanceof Set ? [...value] : value;
}
private _onActionClick = (ev: MouseEvent) => {
ev.stopPropagation();
this._lastAction =
(ev.currentTarget as HTMLElement).dataset.action ?? "none";
};
private _onButtonClick = () => {
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,
@@ -679,15 +542,6 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
ha-card {
max-width: 560px;
}
.card-text {
margin: 0;
padding: 0 var(--ha-space-4) var(--ha-space-2);
}
.vertical-divider {
align-self: stretch;
width: 1px;
background: var(--divider-color);
}
pre {
padding: var(--ha-space-4);
background: var(--secondary-background-color);
+2 -14
View File
@@ -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.
+2 -4
View File
@@ -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: {
Loaded 100 of 1548 files, more files were not shown because too many files have changed in this diff. Show more