Compare commits

..

44 Commits

Author SHA1 Message Date
Joakim Plate 34dba7ea5a Normalize number entity row input (#53284)
hui-number-entity-row.ts bound the raw stateObj.state string to the
non-slider ha-input, so a state like "50.0" showed decimals on the
device page. state-card-number.ts (used by the more-info dialog)
already normalizes via Number(state).toString(); apply the same here
so both views render consistently.
2026-07-24 18:25:56 +02:00
renovate[bot] e76e7d1064 Unpin dependency glob resolution (#53282)
* Pin dependency glob to 10.5.0

* Apply suggestions from code review

Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com>

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com>
2026-07-24 15:39:16 +00:00
Paulus Schoutsen b6675159ae Mock the usage prediction command in the demo (#53279)
Mock usage_prediction/common_control and load the usage_prediction
component so common-controls sections in strategy dashboards render
suggested entities in the demo. Entities that don't exist in the
currently loaded demo config are filtered out by the section strategy.


Claude-Session: https://claude.ai/code/session_01KZ6ydA22VeQndgynH4SxCV

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-24 17:20:29 +02:00
renovate[bot] 9d96d0b4aa Update dependency @rspack/core to v2.1.5 (#53276)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-24 13:07:05 +00:00
Paulus Schoutsen d900cc70c5 Fix unhandled error when the Cast SDK fails to load (#53271)
* Fix unhandled error when the Cast SDK fails to load

Resolve the Cast API as unavailable when the cast_sender.js script
fails to load (offline, blocked by an ad-blocker or firewall), instead
of leaking an unhandled promise rejection. Handle the resulting
getCastManager rejection in the demo cast row, matching hui-cast-row,
so the row hides itself.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3oj5uaCRRaoXRd5iEffhi

* Drop redundant comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3oj5uaCRRaoXRd5iEffhi

* Simplify promise memoization with ??=

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3oj5uaCRRaoXRd5iEffhi

* Revert "Simplify promise memoization with ??="

This reverts commit 5527741b6a.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-24 13:01:46 +00:00
pcan08 837baff26c Fix My Backups navigation (#53259) 2026-07-24 14:57:41 +02:00
Petar Petrov 43b4e247af Fix tile trend-graph feature not extending unchanging values to now (#53265)
Extend tile trend-graph feature to current time for unchanged sensors
2026-07-24 12:52:06 +02:00
renovate[bot] 17def3c5ee Update dependency prettier to v3.9.6 (#53267)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-24 12:46:59 +02:00
renovate[bot] ba15879662 Update dependency @rsdoctor/rspack-plugin to v1.6.1 (#53266)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-24 12:46:53 +02:00
renovate[bot] 0046f72641 Update dependency marked to v18.0.7 (#53263)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-24 05:41:12 +00:00
renovate[bot] f66ba11705 Update dependency typescript-eslint to v8.65.0 (#53262)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-24 08:30:42 +03:00
renovate[bot] bded4341df Update dependency sinon to v22.1.0 (#53261)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-24 08:30:21 +03:00
Bram Kragten 7a6091b5e2 Surface active HTTP config slot and reverted pending state (#53166) 2026-07-23 17:59:51 +02:00
Aidan Timson 6d12672c3e Update skill guidance, move gallery to skill (#53249)
* Correct frontend component and context guidance

* Clarify frontend benchmark requirements

* Move gallery guidance into a skill

* Clarify gallery guidance ownership

* Correct context API ownership
2026-07-23 17:47:02 +03:00
Aidan Timson 495562d748 Prepare copilot environment (#53241)
* Prepare Copilot build and test environment

* Cache Playwright browsers for Copilot

* Cache deps

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Remove indefinite playwright installs

* Spacing

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-23 17:03:18 +03:00
Paul Bottein 5cf7fb3a3d Fix inverted and missing feature checks in lock and lawn mower (#53222) 2026-07-23 15:58:55 +03:00
dependabot[bot] b6813ce060 Bump fast-uri from 3.1.3 to 3.1.4 (#53248)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-23 10:30:41 +01:00
Paul Bottein 3a060feb82 Unify number slider threshold across rows and state cards (#53224)
* Unify number slider threshold across rows and state cards

* Add showNumberSlider test
2026-07-23 09:37:12 +02:00
Petar Petrov ab39c4dd4a Group small device flows into "Other" in sankey cards and share logic (#53235)
The water and energy sankey cards skipped device flows below a hardcoded
0.01 while still counting them in the home total, so small-but-real
devices (e.g. 0.004 m³) were misattributed to "Untracked consumption".
Adopt the power/water-flow relative-threshold + "Other"-grouping strategy
and extract the logic shared by all four cards into energy/common/sankey.
2026-07-23 08:52:54 +02:00
Petar Petrov 82167a81f7 Keep ha-qr-code legible when theme colors collide (#53246)
Ensure ha-qr-code stays legible when theme colors collide
2026-07-23 09:43:31 +03:00
karwosts 1f14f8689c Cleanup some toggle behavior (#53242)
* Cleanup some toggle behavior

* fix tests

* prior behavior did not consider off

* Revert "prior behavior did not consider off"

This reverts commit 59cc93d308.

* Attempt rearranging features to address bundle growth failure

* Revert a no-longer-needed change to setup.ts

* Add test

* test

* Apply suggestion from @MindFreeze

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2026-07-23 06:09:03 +00:00
karwosts 56966ee04b Add uom to selector-selector number (#53245) 2026-07-23 08:45:44 +03:00
Aidan Timson 598a987ba5 Share dependencies across E2E jobs (#53114)
* Share dependencies across E2E jobs

* Add container-compatible dependency cache

* Use one dependency cache key

* Centralise dependency cache preparation

* Separate Playwright dependency cache
2026-07-23 08:19:23 +03:00
Paul Bottein 8775d3f4c5 Use ha-form conditional field visibility in dashboard editors (#53239)
* Use ha-form conditional field visibility in dashboard editors

* Keep view and section editors on localize context
2026-07-22 16:09:17 +01:00
Paul Bottein 2771a565b9 Rename ha-form conditional field to visible and skip it in config flow submission (#53168)
* Skip hidden fields in config flow submission

* Resolve hidden fields until stable so they hold no value

* Rename ha-form conditional field from `hidden` to `visible`
2026-07-22 16:06:03 +02:00
Petar Petrov d3505cece0 Fix missing app update button on app info page (#53238)
Fix missing app update button by resolving update entity reactively
2026-07-22 15:17:34 +02:00
Aidan Timson 8579f77c12 Add demo theme persistence tests (#53237)
* Add demo theme persistence tests

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Use shared demo theme storage key in e2e tests

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-22 15:50:08 +03:00
Aidan Timson 6249e037ed Add ask assist command action to quick search (#53234)
* Add ask assist action to quick search and support params in dialog

* Support native android

* Group Ask Assist with quick search commands

* Hide Ask Assist when native Assist is active

* Test Ask Assist from quick search

* Fix

* Use new test structure
2026-07-22 15:18:04 +03:00
Paul Bottein 8beb4ee36e Migrate entities and glance card state_color to color (#53151)
* Migrate entities and glance card state_color to color

* Improve tests
2026-07-22 15:08:10 +03:00
Maarten Lakerveld 58ded99773 Onboarding survey (#53236)
Use new OHF shortlink service
2026-07-22 12:26:54 +02:00
Timothy 0d2b99b3a5 Disable LaunchScreen for mobile (#53171)
* Disable LaunchScreen for mobile

* Apply suggestions
2026-07-22 12:36:41 +03:00
WazoAkaRapace 4be7a32148 Fix energy graph off-by-one colors with export-only grid source (#53145)
Fix energy usage graph off-by-one colors with export-only grid source

When a grid source configured without an import sensor (export-only) was
listed before other grid sources, the energy usage graph card assigned
color indices based on the filtered `statIds.from_grid` array — skipping
that source — instead of the positional index in the user's energy
sources config. This shifted every subsequent grid source's color by one
relative to the energy sources table card, which uses positional indices.

Populate `colorIndices.from_grid` and `colorIndices.to_grid` during the
source loop using a positional `gridIdx` counter, so import-only and
export-only grid sources no longer shift the colors of sources that
follow them.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-22 11:43:04 +03:00
Aidan Timson e47cebcf6e Workflows shared node modules cache (#53113)
* Benchmark shared dependency cache

* Avoid restoring warm producer cache

* Benchmark build with shared dependencies

* Use shared dependencies in CI

* Use one dependency cache key

* Allow manual CI runs

* Fall back when dependency cache is unavailable

* Keep dependency cache fallbacks fast
2026-07-22 10:16:08 +03:00
Petar Petrov e8bb029d7e Fix excessive y-axis decimals on near-flat energy charts (#53229) 2026-07-22 09:07:24 +02:00
Petar Petrov 4373f016c9 Fix energy usage graph stacking order for grid + solar without battery (#53230)
* Fix energy usage graph stacking so grid consumption stays above solar

* remove useless comment
2026-07-22 09:06:31 +02:00
renovate[bot] 9820428cd3 Update dependency @material/web to v2.5.0 (#53175)
* Update dependency @material/web to v2.5.0

* Update internal style imports for @material/web 2.5.0

2.5.0 renamed the generated internal `*-styles.js` modules to
`*-styles.cssresult.js` (they still export the named `styles`
CSSResult). Point our deep imports at the new paths.

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2026-07-22 07:02:17 +00:00
karwosts 4fa09b0085 Don't present toggle as a ui_action option for untoggleable entities (#53210)
* Don't present toggle as a ui_action option for untoggleable entities

* Fix climate enums

* unmemoize

* fix test

* Add button/valve to canToggleDomain
2026-07-22 08:13:39 +03:00
Aidan Timson 5d63fad772 Migrate section and view editors to conditional visibility (#53217) 2026-07-22 08:11:08 +03:00
Aidan Timson 7f27c9a948 E2E performance improvements and consolidation (#53057)
* Run e2e suites in parallel

* Make suites run as parallel jobs in CI. Merge reports after

* Consolidate app route e2e helpers

* Move app e2e smoke data out of spec

* Tighten app e2e smoke timeouts

* Split e2e helpers by suite

* Consolidate app e2e smoke data

* Move app e2e helpers into src

* Enable workers and full paralelism to tests. Use 60% for local (4 in my case) and 1 for CI

* Shard e2e tests

* Fold e2e-local into report job

* Fix name

* Format

* Double sharding count

* Shard demo (2) and gallery (3)

* rm

* 6,4,6

* Add local sharded e2e runner

* Queue e2e benchmark runs

* Use test mode for e2e builds

* Fix e2e benchmark concurrency

* Build e2e app artifact modern only

* Build demo e2e artifact modern only

* 4/4/2 sharding

* Remove local sharded e2e runner

* Use Playwright image for e2e tests

* Remove redundant e2e test cases

* Run e2e sidebar checks concurrently

* Consolidate config link e2e checks

* Avoid duplicate gallery page waits

* Avoid slow gallery alert count wait

* Run app e2e readiness waits concurrently

* Avoid duplicate gallery readiness wait

* Restore concurrency

* Restore concurrency

* Share parallel e2e smoke registration

* Restore demo page error tracking

* Remove ineffective gallery test mode

* Remove unused route project filtering

* Remove duplicate smoke test parallel mode

* Keep page error filtering internal

* Require helper reuse in test changes

* Clarify local E2E server workflow

* Stabilize demo sidebar navigation test

* Avoid concurrent cold E2E builds

* Validate E2E worker overrides

* Restore real demo sidebar clicks

* Keep app shell error checks strict

* Limit gallery shell error filtering

* Address E2E review findings
2026-07-21 22:27:37 +02:00
Maarten Lakerveld c07264fc27 Add onboarding survey toast (#53221)
Conditions/triggers/actions use the same logic for the automations picker sorting
2026-07-21 21:54:39 +02:00
renovate[bot] 978ad69c1b Update dependency lint-staged to v17.1.0 (#53227)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-21 21:45:41 +02:00
Paul Bottein 047ebd4524 Sync entity constants with core (#53223)
* Sync entity constants with core

* Suggest mean statistics graphs for measurement_angle sensors
2026-07-21 21:45:12 +02:00
karwosts a25aa656a3 Replace feature magic numbers in media-player-model (#53214) 2026-07-21 10:04:39 +02:00
Simon Lamon 88f244b9df Replace the memoize call to fullcalendar (#53215)
Replace the memoize one
2026-07-21 10:04:13 +02:00
170 changed files with 5302 additions and 3468 deletions
+14 -9
View File
@@ -23,11 +23,10 @@ Dialog implementation requirements:
- Use `ha-dialog`.
- Use `DialogMixin`, which implements `HassDialogNext<T>`, for new dialogs. See `src/dialogs/dialog-mixin.ts`.
- Read dialog parameters from the mixin's `params` property and render the dialog open. Return `nothing` while required parameters are absent.
- Call the mixin's `closeDialog()` to close a new dialog. The mixin handles the `closed` event, fires `dialog-closed`, and removes the host element.
- Existing dialogs may implement the legacy `HassDialog<T>` interface from `src/dialogs/make-dialog-manager.ts`.
- Use `@state() private _open = false` to control visibility.
- Set `_open = true` in `showDialog()` and `_open = false` in `closeDialog()`.
- Return `nothing` while required params are absent.
- Fire `dialog-closed` in the close handler.
- Preserve the existing `showDialog()`, open-state, and close-event lifecycle when maintaining a legacy dialog; do not copy that lifecycle into a `DialogMixin` dialog.
- Use `header-title` and `header-subtitle` for simple header text.
- Use slots when standard header attributes are not enough.
- Use `ha-dialog-footer` with `primaryAction` and `secondaryAction` slots.
@@ -64,7 +63,7 @@ Use `computeLabel`, `computeError`, and `computeHelper` for translated labels, v
.data=${this._data}
.schema=${this._schema}
.error=${this._errors}
.computeLabel=${(schema) => this.hass.localize(`ui.panel.${schema.name}`)}
.computeLabel=${(schema) => this._localize(`ui.panel.${schema.name}`)}
@value-changed=${this._valueChanged}
></ha-form>
```
@@ -78,10 +77,16 @@ Use `ha-alert` for user-visible status messaging.
- Slots: `icon` for custom leading icon, `action` for custom action content.
- Content is announced by screen readers when dynamically displayed.
```html
<ha-alert alert-type="error">Error message</ha-alert>
<ha-alert alert-type="warning" title="Warning">Description</ha-alert>
<ha-alert alert-type="success" dismissable>Success message</ha-alert>
```ts
html`
<ha-alert alert-type="error">${this._localize("ui.example.error")}</ha-alert>
<ha-alert alert-type="warning" .title=${this._localize("ui.example.warning")}>
${this._localize("ui.example.description")}
</ha-alert>
<ha-alert alert-type="success" dismissable>
${this._localize("ui.example.success")}
</ha-alert>
`;
```
## Shortcuts And Tooltips
+23 -16
View File
@@ -23,27 +23,27 @@ Container components may keep `hass` when they own it and feed providers. Leaf c
## Context Selection
| Context | Replaces |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `statesContext` | `hass.states` |
| `entitiesContext`, `devicesContext`, `areasContext`, `floorsContext` | `hass.entities`, `hass.devices`, `hass.areas`, `hass.floors` |
| `registriesContext` | all four registries together |
| `servicesContext` | `hass.services` |
| `internationalizationContext` | `hass.localize`, `hass.locale`, `hass.language` |
| `formattersContext` | entity and attribute formatters |
| `configContext` | `hass.config`, `hass.user`, `hass.auth`, `hass.userData` |
| `connectionContext` | `hass.connection`, `hass.connected`, `hass.hassUrl` |
| `apiContext` | `hass.callService`, `hass.callApi`, `hass.callWS`, `hass.sendWS`, `hass.fetchWithAuth` |
| `uiContext` | themes, selected theme, panels, sidebar, and UI state |
| `narrowViewportContext` | narrow-layout boolean |
| Context | Replaces |
| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `statesContext` | `hass.states` |
| `entitiesContext`, `devicesContext`, `areasContext`, `floorsContext` | `hass.entities`, `hass.devices`, `hass.areas`, `hass.floors` |
| `registriesContext` | all four registries together |
| `servicesContext` | `hass.services` |
| `internationalizationContext` | `hass.localize`, `hass.locale`, `hass.language` |
| `formattersContext` | entity and attribute formatters |
| `configContext` | `hass.config`, `hass.user`, `hass.auth`, `hass.userData` |
| `connectionContext` | `hass.connection`, `hass.connected`, `hass.debugConnection`, `hass.hassUrl` |
| `apiContext` | `hass.callService`, `hass.callApi`, `hass.callApiRaw`, `hass.callWS`, `hass.sendWS`, `hass.fetchWithAuth` |
| `uiContext` | themes, selected theme, panels, sidebar, and UI state |
| `narrowViewportContext` | narrow-layout boolean |
Lazy contexts subscribe on first consumer and tear down after the last consumer: `labelsContext`, `fullEntitiesContext`, `configEntriesContext`, and `manifestsContext`.
Lazy contexts subscribe on first consumer and tear down after the last consumer: `labelsContext`, `fullEntitiesContext`, `configEntriesContext`, `manifestsContext`, `triggerDescriptionsContext`, and `conditionDescriptionsContext`.
The single-field contexts such as `localizeContext`, `themesContext`, and `userContext` are deprecated. Use grouped contexts instead.
## Consumption Patterns
Use entity-scoped helpers when the component watches an entity id held on the host:
Use entity-scoped helpers when the component watches an entity ID held on the host:
```ts
@state() @consumeEntityState({ entityIdPath: ["_config", "entity"] })
@@ -56,6 +56,13 @@ private _entity?: EntityRegistryDisplayEntry;
private _localize!: LocalizeFunc;
```
Use `consumeEntityStates` when the host property contains one or more entity IDs. It filters missing entities and preserves the previous record when none of the selected entities changed.
```ts
@state() @consumeEntityStates({ entityIdPath: ["_config", "entities"] })
private _stateObjs?: Record<string, HassEntity>;
```
For a single field from a grouped context, pair `@consume` with `@transform`:
```ts
@@ -65,7 +72,7 @@ For a single field from a grouped context, pair `@consume` with `@transform`:
private _themes!: Themes;
```
Use `@transform` with `watch` when the transformer depends on a host property, such as a computed entity id. `consumeEntityState` only watches the first path segment.
Use `@transform` with `watch` when the transformer depends on a host property, such as a computed entity ID. `consumeEntityState` and `consumeEntityStates` only watch the first path segment.
To consume a whole group untransformed, omit `@transform` and type the field as `ContextType<typeof statesContext>` or the matching context type.
@@ -1,6 +1,11 @@
# Gallery Agent Instructions
---
name: ha-frontend-gallery
description: Home Assistant frontend gallery structure, pages, demos, content, and verification. Use when changing files under gallery/, including gallery markdown, TypeScript demos, sidebar entries, mock data, page generation, or gallery builds.
---
This file applies to all files under `gallery/`. Follow the root `AGENTS.md` for repository-wide Home Assistant frontend, TypeScript, Lit, accessibility, and copy standards. This file adds gallery-specific structure, page, demo, and verification guidance.
# HA Frontend Gallery
Use this skill for all work under `gallery/`. Follow the persistent repository guidance in `AGENTS.md` and load the matching specialist skills alongside this gallery-specific guidance.
## Quick Reference
@@ -13,7 +18,7 @@ yarn lint # ESLint, Prettier, TypeScript, and Lit checks
yarn lint:types # TypeScript compiler, without file arguments
```
Never run `yarn lint:types` or `tsc` with file arguments. See the root `AGENTS.md` for the generated `.js` file risk.
Never run `yarn lint:types` or `tsc` with file arguments. File arguments make `tsc` ignore `tsconfig.json` and can emit `.js` files into `src/`.
## Purpose
@@ -26,36 +31,36 @@ The gallery is a developer and designer reference for Home Assistant frontend UI
## Structure
- `sidebar.js`: Defines gallery sections, headers, and explicit page ordering.
- `script/develop_gallery`: Wrapper for the `develop-gallery` gulp task.
- `script/build_gallery`: Wrapper for the `build-gallery` gulp task.
- `src/entrypoint.js`: Creates the `<ha-gallery>` shell.
- `src/ha-gallery.ts`: Renders the drawer, page routing, markdown descriptions, demos, edit links, and RTL toggle.
- `src/html/index.html.template`: HTML template used by the gallery build.
- `src/pages/<category>/<page>.markdown`: Optional page description and frontmatter.
- `src/pages/<category>/<page>.ts`: Optional live demo module for the same page id.
- `src/components/`: Gallery-only demo wrappers like `demo-card`, `demo-cards`, `demo-more-info`, and `page-description`.
- `src/data/`: Fake `hass`, demo states, mock traces, and reusable sample data.
- `public/`: Static assets copied into the gallery output.
- `gallery/sidebar.js`: Defines gallery sections, headers, and explicit page ordering.
- `gallery/script/develop_gallery`: Wrapper for the `develop-gallery` gulp task.
- `gallery/script/build_gallery`: Wrapper for the `build-gallery` gulp task.
- `gallery/src/entrypoint.js`: Creates the `<ha-gallery>` shell.
- `gallery/src/ha-gallery.ts`: Renders the drawer, page routing, markdown descriptions, demos, edit links, and RTL toggle.
- `gallery/src/html/index.html.template`: HTML template used by the gallery build.
- `gallery/src/pages/<category>/<page>.markdown`: Optional page description and frontmatter.
- `gallery/src/pages/<category>/<page>.ts`: Optional live demo module for the same page ID.
- `gallery/src/components/`: Gallery-only demo wrappers like `demo-card`, `demo-cards`, `demo-more-info`, and `page-description`.
- `gallery/src/data/`: Fake `hass`, demo states, mock traces, and reusable sample data.
- `gallery/public/`: Static assets copied into the gallery output.
## Page Model
Gallery pages are generated by `gather-gallery-pages` in `build-scripts/gulp/gallery.js`.
- A page id is the path under `src/pages/` without the extension, like `components/ha-button`.
- A `.markdown` file and a `.ts` file with the same page id become one gallery page.
- A page ID is the path under `gallery/src/pages/` without the extension, like `components/ha-button`.
- A `.markdown` file and a `.ts` file with the same page ID become one gallery page.
- A page may have only markdown, only a TypeScript demo, or both.
- Markdown can contain YAML frontmatter with `title` and optional `subtitle`.
- Markdown that contains only frontmatter contributes metadata without rendering a description block.
- TypeScript demo modules are dynamically imported for side effects when the page is opened.
- A demo module must define a custom element named `demo-${category}-${page}` with slashes replaced by hyphens, like `demo-components-ha-button` for `components/ha-button`.
- `ha-gallery.ts` renders that element with `dynamicElement()` based on the current page id.
- `gallery/src/ha-gallery.ts` renders that element with `dynamicElement()` based on the current page ID.
## Sidebar
Use `sidebar.js` when a page needs a visible section, section header, or deterministic ordering.
Use `gallery/sidebar.js` when a page needs a visible section, section header, or deterministic ordering.
- `category` must match the first directory name under `src/pages/`.
- `category` must match the first directory name under `gallery/src/pages/`.
- `header` is the section label shown in the drawer.
- `pages` is optional. When present, listed pages keep that exact order.
- Pages in a category that are not listed are appended alphabetically after the listed pages.
@@ -83,20 +88,20 @@ Use markdown pages for explanations, design guidance, API notes, and copy standa
- Use fenced code blocks with a language tag for copyable examples.
- Keep examples short and focused on the behavior being documented.
- Prefer real component names and attributes over prose-only descriptions.
- Use Home Assistant terminology from the root `AGENTS.md`.
- For remove/delete and add/create wording, follow `src/pages/misc/remove-delete-add-create.markdown`.
- Use Home Assistant terminology from `ha-frontend-user-facing-text`.
- For remove/delete and add/create wording, follow `gallery/src/pages/misc/remove-delete-add-create.markdown`.
Gallery markdown is documentation content and is not localized with `localize`. If demo code creates production UI strings, keep those strings aligned with the root localization and copy guidance.
Gallery markdown is documentation content and is not localized with `localize`. If demo code creates production UI strings, follow the localization and copy guidance in `ha-frontend-user-facing-text`.
## Demo Components
Use TypeScript demo pages for interactive or stateful examples.
- Import production components from `../../../src/...` or the correct relative path from the demo file.
- Import production components from `src/` using the correct relative path from the demo file.
- Import reusable gallery helpers from `gallery/src/components/` when they already model the pattern.
- Use `demo-card` and `demo-cards` for Lovelace card examples that render YAML card configs.
- Use `demo-more-info` and `demo-more-infos` for more-info dialog examples.
- Use shared mock data from `src/data/` instead of repeating large fake state objects inline.
- Use shared mock data from `gallery/src/data/` instead of repeating large fake state objects inline.
- Show meaningful states, such as loading, unavailable, empty, error, active, inactive, and disabled when relevant.
- Check responsive behavior and the gallery RTL toggle when layout or direction-sensitive UI changes.
- Keep unavoidable casts or loose demo parsing local to the demo helper or demo page.
@@ -105,7 +110,7 @@ The gallery ESLint config allows `console` for gallery diagnostics. Do not copy
## Content Standards
The root copy standards still apply: use American English, sentence case, active voice, inclusive language, direct user-focused wording, and consistent Home Assistant terminology.
Follow the detailed copy standards in `ha-frontend-user-facing-text`: use American English, sentence case, active voice, inclusive language, direct user-focused wording, and consistent Home Assistant terminology.
- Use `Home Assistant` in full, not `HA` or `HASS`.
- Use `integration` instead of `component` for product concepts.
+18 -10
View File
@@ -1,12 +1,18 @@
---
name: ha-frontend-testing
description: Home Assistant frontend validation workflow. Use when running lint, TypeScript checks, Vitest, Playwright e2e suites, dev servers, or chart-data benchmarks.
description: Home Assistant frontend testing and validation workflow. Use when adding or updating tests, running lint, TypeScript checks, Vitest, Playwright e2e suites, dev servers, or chart-data benchmarks.
---
# HA Frontend Testing
Use this skill when choosing or running validation for frontend changes.
## Test Helpers
- Before adding or changing tests, inspect the relevant suite's existing helpers and fixtures. Reuse them instead of duplicating setup, test data, navigation, interactions, waits, or assertions.
- When the same test flow appears more than once, move it into the closest suite-local helper with a focused interface.
- Keep one-off test behaviour in the test unless a helper makes the intent materially clearer. Do not hide the behaviour under test behind broad, configurable abstractions.
## Core Commands
```bash
@@ -35,7 +41,7 @@ For focused type feedback on one file, use editor diagnostics instead of a file-
`yarn dev:serve` also serves locally and supports `-c` for the core URL and `-p` for the port. The default is 8124, or 8123 in a devcontainer.
Dev server commands support `--background`, `--status`, `--stop`, and `--logs [--follow]`.
Dev server commands support `--background`, `--status`, `--stop`, and `--logs [--follow]`. Prefer managed background mode while iterating so the watcher stays available across test runs without occupying the terminal.
## Playwright E2E
@@ -43,23 +49,25 @@ Each suite has its own dev server port. Playwright reuses an existing server loc
Start the relevant suite server, then run that suite:
| Suite | Server | Test command |
| ------- | ------------------------------- | ----------------------- |
| App | `yarn test:e2e:app:dev` on 8095 | `yarn test:e2e:app` |
| Demo | `yarn dev:demo` on 8090 | `yarn test:e2e:demo` |
| Gallery | `yarn dev:gallery` on 8100 | `yarn test:e2e:gallery` |
| Suite | Background server | Test command |
| ------- | -------------------------------------------- | ----------------------- |
| App | `yarn test:e2e:app:dev --background` on 8095 | `yarn test:e2e:app` |
| Demo | `yarn dev:demo --background` on 8090 | `yarn test:e2e:demo` |
| Gallery | `yarn dev:gallery --background` on 8100 | `yarn test:e2e:gallery` |
The custom development wrappers use `/__ha_dev_status` to identify and manage their own suites. Playwright server reuse checks the configured URL instead. Wrapper start and stop operations are idempotent for a matching suite and reject an unrelated process occupying the port.
Use `-g "<title>" --project=chromium` to narrow a run. `yarn test:e2e` runs all three suites. Run suites directly; piping through output truncation hides progress and failures.
Local runs against a watched development server do not always match CI's clean build artifacts, environment, sharding, or worker configuration. Use background servers for the fast iteration loop, but confirm the relevant CI jobs complete successfully before considering E2E changes verified.
Use `-g "<title>" --project=chromium` to narrow a run. `yarn test:e2e` runs all three suites in parallel when every managed server is available, otherwise it runs them sequentially to prevent cold builds racing over shared generated assets. Run suites directly; piping through output truncation hides progress and failures.
The app suite uses a stripped-down harness for e2e. Demo and gallery use their normal dev servers.
## Benchmarks
For chart data transforms such as history, statistics, energy, and downsampling, follow `test/benchmarks/README.md`.
For chart data transforms such as history, statistics, energy, and downsampling, read and follow the complete workflow in `test/benchmarks/README.md` before making benchmark or optimization changes.
Use seeded fixtures, characterization snapshot tests, and `yarn test:bench` before and after optimization. Optimizations must keep output bit-identical.
That workflow owns the baseline, noise analysis, guardrails, acceptance thresholds, and reporting requirements. In particular, optimizations must keep output bit-identical; never update snapshots or modify fixtures to make an optimization pass.
## Verification Selection
@@ -16,7 +16,7 @@ Use this skill for all user-facing text, translations, labels, buttons, dialog c
- Give translators enough context through key naming and placeholders.
```ts
this.hass.localize("ui.panel.config.updates.updates_refreshed", {
this._localize("ui.panel.config.updates.updates_refreshed", {
count: 5,
});
```
@@ -0,0 +1,41 @@
name: Prepare dependencies
description: Install and cache the complete dependency tree
inputs:
node-modules-cache-key:
description: Prefix for the shared node_modules cache key
default: node-modules-v1
runs:
using: composite
steps:
- name: Check for complete dependency tree
id: dependencies
continue-on-error: true
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
node_modules
.yarn/install-state.gz
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
hashFiles('.nvmrc', 'package.json', 'yarn.lock', '.yarnrc.yml', '.yarn/releases/**', '.yarn/patches/**') }}
lookup-only: true
- name: Setup Node and install
if: steps.dependencies.outputs.cache-hit != 'true'
uses: ./.github/actions/setup
with:
cache: false
- name: Save complete dependency tree
if: steps.dependencies.outputs.cache-hit != 'true'
continue-on-error: true
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
node_modules
.yarn/install-state.gz
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
hashFiles('.nvmrc', 'package.json', 'yarn.lock', '.yarnrc.yml', '.yarn/releases/**', '.yarn/patches/**') }}
+25 -1
View File
@@ -8,16 +8,40 @@ inputs:
cache:
description: Enable the yarn cache in setup-node
default: "true"
node-modules-cache:
description: Restore the exact shared node_modules cache before installing
default: "false"
node-modules-cache-key:
description: Prefix for the shared node_modules cache key
default: node-modules-v1
runs:
using: composite
steps:
- name: Restore complete dependency tree
id: dependency-cache
if: inputs.node-modules-cache == 'true'
continue-on-error: true
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
node_modules
.yarn/install-state.gz
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
hashFiles('.nvmrc', 'package.json', 'yarn.lock', '.yarnrc.yml', '.yarn/releases/**', '.yarn/patches/**') }}
- name: Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version-file: ".nvmrc"
cache: ${{ inputs.cache == 'true' && 'yarn' || '' }}
cache: ${{ inputs.cache == 'true' && (inputs.node-modules-cache != 'true' || steps.dependency-cache.outputs.cache-hit != 'true') && 'yarn' || '' }}
- name: Enable Corepack
shell: bash
run: corepack enable
- name: Install dependencies
if: inputs.node-modules-cache != 'true' || steps.dependency-cache.outputs.cache-hit != 'true'
shell: bash
run: yarn install ${{ inputs.immutable == 'true' && '--immutable' || '' }}
+26 -5
View File
@@ -1,6 +1,7 @@
name: CI
on:
workflow_dispatch:
push:
branches:
- dev
@@ -21,16 +22,30 @@ permissions:
contents: read
jobs:
lint:
name: Lint and check format
prepare-dependencies:
name: Prepare dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node and install
- name: Prepare dependencies
uses: ./.github/actions/prepare-dependencies
lint:
name: Lint and check format
needs: prepare-dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Check for duplicate dependencies
run: yarn dedupe --check
- name: Build resources
@@ -63,14 +78,17 @@ jobs:
run: yarn run lint:licenses
test:
name: Run tests
needs: prepare-dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node and install
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Build resources
run: ./node_modules/.bin/gulp gen-icons-json build-translations build-locale-data
env:
@@ -80,6 +98,7 @@ jobs:
build:
name: Build frontend
needs:
- prepare-dependencies
- lint
- test
runs-on: ubuntu-latest
@@ -88,8 +107,10 @@ jobs:
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node and install
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Build Application
uses: ./.github/actions/build
with:
+34
View File
@@ -0,0 +1,34 @@
name: Copilot Setup Steps
on:
workflow_dispatch:
push:
paths:
- .github/workflows/copilot-setup-steps.yml
pull_request:
paths:
- .github/workflows/copilot-setup-steps.yml
env:
NODE_OPTIONS: --max_old_space_size=6144
jobs:
copilot-setup-steps:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node and install
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Skip fetching nightly translations
run: echo "SKIP_FETCH_NIGHTLY_TRANSLATIONS=1" >> "$GITHUB_ENV"
- name: Build resources
run: ./node_modules/.bin/gulp gen-icons-json build-translations build-locale-data gather-gallery-pages
+223 -47
View File
@@ -22,9 +22,8 @@ permissions:
contents: read
jobs:
# ── Build the demo once and share it across test jobs via artifact ──────────
build-demo:
name: Build demo
prepare-dependencies:
name: Prepare dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
@@ -32,14 +31,51 @@ jobs:
with:
persist-credentials: false
- name: Setup Node and install
- name: Prepare dependencies
uses: ./.github/actions/prepare-dependencies
prepare-container-dependencies:
name: Prepare container dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.61.1-noble
options: --user 1001
defaults:
run:
shell: bash
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Prepare dependencies
uses: ./.github/actions/prepare-dependencies
with:
node-modules-cache-key: node-modules-container-v1
# ── Build the demo once and share it across test jobs via artifact ──────────
build-demo:
name: Build demo
needs: prepare-dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Build demo
uses: ./.github/actions/build
with:
target: build-demo
target: build-demo-e2e
github-token: ${{ secrets.GITHUB_TOKEN }}
is-test: true
- name: Upload demo build
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
@@ -52,6 +88,7 @@ jobs:
# ── Build the e2e test app and share it via artifact ────────────────────────
build-e2e-test-app:
name: Build e2e test app
needs: prepare-dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
@@ -59,14 +96,17 @@ jobs:
with:
persist-credentials: false
- name: Setup Node and install
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Build e2e test app
uses: ./.github/actions/build
with:
target: build-e2e-test-app
target: build-e2e-test-app-e2e
github-token: ${{ secrets.GITHUB_TOKEN }}
is-test: true
- name: Upload e2e test app build
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
@@ -79,6 +119,7 @@ jobs:
# ── Build the gallery and share it via artifact ─────────────────────────────
build-gallery:
name: Build gallery
needs: prepare-dependencies
runs-on: ubuntu-latest
steps:
- name: Check out files from GitHub
@@ -86,8 +127,10 @@ jobs:
with:
persist-credentials: false
- name: Setup Node and install
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Build gallery
uses: ./.github/actions/build
@@ -103,41 +146,39 @@ jobs:
if-no-files-found: error
retention-days: 3
# ── Run Playwright tests locally against Chromium ──────────────────────────
e2e-local:
name: E2E (local Chromium)
needs: [build-demo, build-e2e-test-app, build-gallery]
# ── Run Playwright tests against Chromium ──────────────────────────────────
e2e-demo:
name: E2E demo (${{ matrix.shardIndex }}/${{ matrix.shardTotal }})
needs:
- build-demo
- prepare-container-dependencies
runs-on: ubuntu-latest
# Fail fast if anything hangs. The whole suite should take < 15 minutes on
# Chromium; anything longer is almost certainly an install or webServer
# hang.
timeout-minutes: 30
container:
image: mcr.microsoft.com/playwright:v1.61.1-noble
options: --user 1001 --ipc=host
defaults:
run:
shell: bash
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
shardIndex:
- 1
- 2
shardTotal:
- 2
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node and install
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
# Resolve the installed Playwright version so the browser cache tracks
# Playwright itself, not every unrelated dependency bump.
- name: Resolve Playwright version
id: playwright-version
run: echo "version=$(node -p 'require("@playwright/test/package.json").version')" >> "$GITHUB_OUTPUT"
# Cache the downloaded browser build keyed on the installed Playwright
# version, so re-runs skip the ~170 MB download unless Playwright changes.
- name: Cache Playwright browsers
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ steps.playwright-version.outputs.version }}
- name: Install Playwright browsers
run: yarn playwright install --with-deps chromium
timeout-minutes: 10
node-modules-cache: true
node-modules-cache-key: node-modules-container-v1
- name: Download demo build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
@@ -145,36 +186,135 @@ jobs:
name: demo-dist
path: demo/dist/
- name: Run Playwright demo tests
run: yarn test:e2e:demo --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
timeout-minutes: 15
- name: Upload demo blob report
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: blob-report-demo-${{ matrix.shardIndex }}
path: test/e2e/reports/demo/
if-no-files-found: warn
retention-days: 3
e2e-app:
name: E2E app (${{ matrix.shardIndex }}/${{ matrix.shardTotal }})
needs:
- build-e2e-test-app
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.61.1-noble
options: --user 1001 --ipc=host
defaults:
run:
shell: bash
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
shardIndex:
- 1
- 2
- 3
- 4
shardTotal:
- 4
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
node-modules-cache-key: node-modules-container-v1
- name: Download e2e test app build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: e2e-test-app-dist
path: test/e2e/app/dist/
- name: Run Playwright app tests
run: yarn test:e2e:app --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
timeout-minutes: 15
- name: Upload app blob report
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: blob-report-app-${{ matrix.shardIndex }}
path: test/e2e/reports/app/
if-no-files-found: warn
retention-days: 3
e2e-gallery:
name: E2E gallery (${{ matrix.shardIndex }}/${{ matrix.shardTotal }})
needs:
- build-gallery
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.61.1-noble
options: --user 1001 --ipc=host
defaults:
run:
shell: bash
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
shardIndex:
- 1
- 2
- 3
- 4
shardTotal:
- 4
steps:
- name: Check out files from GitHub
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
node-modules-cache-key: node-modules-container-v1
- name: Download gallery build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: gallery-dist
path: gallery/dist/
- name: Run Playwright tests (local)
run: yarn test:e2e
- name: Run Playwright gallery tests
run: yarn test:e2e:gallery --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
timeout-minutes: 15
- name: Upload blob report
- name: Upload gallery blob report
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: blob-report-local
path: test/e2e/reports/
name: blob-report-gallery-${{ matrix.shardIndex }}
path: test/e2e/reports/gallery/
if-no-files-found: warn
retention-days: 3
# ── Merge local blob reports and post PR comment ───────────────────────────
report:
name: Report
needs: [e2e-local]
needs:
- e2e-demo
- e2e-app
- e2e-gallery
runs-on: ubuntu-latest
if: ${{ !cancelled() }}
if: ${{ always() }}
permissions:
contents: read
pull-requests: write
@@ -184,15 +324,31 @@ jobs:
with:
persist-credentials: false
- name: Setup Node and install
- name: Setup Node with shared dependencies
uses: ./.github/actions/setup
with:
node-modules-cache: true
- name: Download blob report (local)
- name: Download demo blob reports
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
continue-on-error: true
with:
name: blob-report-local
path: test/e2e/reports/
pattern: blob-report-demo-*
path: test/e2e/reports/demo/
- name: Download app blob reports
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
continue-on-error: true
with:
pattern: blob-report-app-*
path: test/e2e/reports/app/
- name: Download gallery blob reports
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
continue-on-error: true
with:
pattern: blob-report-gallery-*
path: test/e2e/reports/gallery/
- name: Stage blobs for merge
run: node test/e2e/collect-blob-reports.mjs
@@ -209,7 +365,11 @@ jobs:
retention-days: 14
- name: Post report to PR
if: github.event_name == 'pull_request' && needs.e2e-local.result == 'failure'
if: >-
github.event_name == 'pull_request' &&
(needs.e2e-demo.result == 'failure' ||
needs.e2e-app.result == 'failure' ||
needs.e2e-gallery.result == 'failure')
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
@@ -217,3 +377,19 @@ jobs:
`${process.env.GITHUB_WORKSPACE}/test/e2e/post-report-comment.mjs`
);
await postReportComment({ github, context, core });
- name: Check suite results
run: |
failed=0
for suite in \
"demo:${{ needs.e2e-demo.result }}" \
"app:${{ needs.e2e-app.result }}" \
"gallery:${{ needs.e2e-gallery.result }}"; do
name="${suite%%:*}"
result="${suite#*:}"
echo "E2E ${name}: ${result}"
if [ "$result" != "success" ]; then
failed=1
fi
done
exit "$failed"
+1 -2
View File
@@ -2,8 +2,6 @@
You are helping develop the Home Assistant frontend. This repository is a TypeScript application built from Lit-based Web Components for the Home Assistant web UI.
For gallery-specific documentation, demos, page structure, and examples, read `gallery/AGENTS.md` when working under `gallery/`.
## Essential Commands
```bash
@@ -46,6 +44,7 @@ Detailed guidance lives in project skills under `.agents/skills/`. Load the matc
- `ha-frontend-testing`: lint, typecheck, Vitest, Playwright e2e dev servers, and benchmarks.
- `ha-frontend-user-facing-text`: localization, terminology, sentence case, and Home Assistant text style.
- `ha-frontend-review`: PR template use, review checklist, and recurring review issues.
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
## Pull Requests
+4 -2
View File
@@ -232,7 +232,7 @@ module.exports.config = {
};
},
demo({ isProdBuild, latestBuild, isStatsBuild }) {
demo({ isProdBuild, latestBuild, isStatsBuild, isTestBuild }) {
return {
name: "demo" + nameSuffix(latestBuild),
entry: {
@@ -247,6 +247,7 @@ module.exports.config = {
isProdBuild,
latestBuild,
isStatsBuild,
isTestBuild,
};
},
@@ -306,7 +307,7 @@ module.exports.config = {
};
},
e2eTestApp({ isProdBuild, latestBuild, isStatsBuild }) {
e2eTestApp({ isProdBuild, latestBuild, isStatsBuild, isTestBuild }) {
return {
name: "e2e-test-app" + nameSuffix(latestBuild),
entry: {
@@ -321,6 +322,7 @@ module.exports.config = {
isProdBuild,
latestBuild,
isStatsBuild,
isTestBuild,
};
},
};
+16
View File
@@ -42,6 +42,22 @@ gulp.task(
)
);
gulp.task(
"build-demo-e2e",
gulp.series(
async function setEnv() {
process.env.NODE_ENV = "production";
},
"clean-demo",
// Cast needs to be backwards compatible and older HA has no translations
"translations-enable-merge-backend",
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
"copy-static-demo",
"rspack-prod-demo-e2e",
"gen-pages-demo-prod-e2e"
)
);
gulp.task(
"analyze-demo",
gulp.series(
+15
View File
@@ -39,3 +39,18 @@ gulp.task(
"gen-pages-e2e-test-app-prod"
)
);
gulp.task(
"build-e2e-test-app-e2e",
gulp.series(
async function setEnv() {
process.env.NODE_ENV = "production";
},
"clean-e2e-test-app",
"translations-enable-merge-backend",
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
"copy-static-e2e-test-app",
"rspack-prod-e2e-test-app-e2e",
"gen-pages-e2e-test-app-prod"
)
);
+10
View File
@@ -225,6 +225,16 @@ gulp.task(
)
);
gulp.task(
"gen-pages-demo-prod-e2e",
genPagesProdTask(
DEMO_PAGE_ENTRIES,
paths.demo_dir,
paths.demo_output_root,
paths.demo_output_latest
)
);
const GALLERY_PAGE_ENTRIES = { "index.html": ["entrypoint"] };
gulp.task(
+24
View File
@@ -177,6 +177,18 @@ gulp.task("rspack-prod-demo", () =>
bothBuilds(createDemoConfig, {
isProdBuild: true,
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
})
)
);
gulp.task("rspack-prod-demo-e2e", () =>
prodBuild(
createDemoConfig({
isProdBuild: true,
latestBuild: true,
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
})
)
);
@@ -269,6 +281,18 @@ gulp.task("rspack-prod-e2e-test-app", () =>
bothBuilds(createE2eTestAppConfig, {
isProdBuild: true,
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
})
)
);
gulp.task("rspack-prod-e2e-test-app-e2e", () =>
prodBuild(
createE2eTestAppConfig({
isProdBuild: true,
latestBuild: true,
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
})
)
);
+19 -4
View File
@@ -387,9 +387,14 @@ const createAppConfig = ({
bundle.config.app({ isProdBuild, latestBuild, isStatsBuild, isTestBuild })
);
const createDemoConfig = ({ isProdBuild, latestBuild, isStatsBuild }) =>
const createDemoConfig = ({
isProdBuild,
latestBuild,
isStatsBuild,
isTestBuild,
}) =>
createRspackConfig(
bundle.config.demo({ isProdBuild, latestBuild, isStatsBuild })
bundle.config.demo({ isProdBuild, latestBuild, isStatsBuild, isTestBuild })
);
const createCastConfig = ({ isProdBuild, latestBuild }) =>
@@ -401,9 +406,19 @@ const createGalleryConfig = ({ isProdBuild, latestBuild }) =>
const createLandingPageConfig = ({ isProdBuild, latestBuild }) =>
createRspackConfig(bundle.config.landingPage({ isProdBuild, latestBuild }));
const createE2eTestAppConfig = ({ isProdBuild, latestBuild, isStatsBuild }) =>
const createE2eTestAppConfig = ({
isProdBuild,
latestBuild,
isStatsBuild,
isTestBuild,
}) =>
createRspackConfig(
bundle.config.e2eTestApp({ isProdBuild, latestBuild, isStatsBuild })
bundle.config.e2eTestApp({
isProdBuild,
latestBuild,
isStatsBuild,
isTestBuild,
})
);
module.exports = {
+23 -18
View File
@@ -41,25 +41,30 @@ class CastDemoRow extends LitElement implements LovelaceRow {
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
import("../../../src/cast/cast_manager").then(({ getCastManager }) =>
getCastManager().then((mgr) => {
this._castManager = mgr;
mgr.addEventListener("state-changed", () => {
this.requestUpdate();
});
mgr.castContext.addEventListener(
cast.framework.CastContextEventType.SESSION_STATE_CHANGED,
(ev) => {
// On Android, opening a new session always results in SESSION_RESUMED.
// So treat both as the same.
if (
ev.sessionState === "SESSION_STARTED" ||
ev.sessionState === "SESSION_RESUMED"
) {
castSendShowDemo(mgr);
getCastManager().then(
(mgr) => {
this._castManager = mgr;
mgr.addEventListener("state-changed", () => {
this.requestUpdate();
});
mgr.castContext.addEventListener(
cast.framework.CastContextEventType.SESSION_STATE_CHANGED,
(ev) => {
// On Android, opening a new session always results in SESSION_RESUMED.
// So treat both as the same.
if (
ev.sessionState === "SESSION_STARTED" ||
ev.sessionState === "SESSION_RESUMED"
) {
castSendShowDemo(mgr);
}
}
}
);
})
);
},
() => {
this._castManager = null;
}
)
);
}
+10 -2
View File
@@ -29,6 +29,7 @@ import { mockSystemLog } from "./stubs/system_log";
import { mockTemplate } from "./stubs/template";
import { mockTodo } from "./stubs/todo";
import { mockTranslations } from "./stubs/translations";
import { mockUsagePrediction } from "./stubs/usage_prediction";
import "./cloud/cloud-demo-controls";
// WS command / REST path prefixes whose mocks live in the lazily imported
@@ -74,11 +75,17 @@ export class HaDemo extends HomeAssistantAppEl {
// The cloud account page only fetches backup config and the webhook count
// when those integrations are loaded. Enable them here (demo only) so the
// mocked backup/config/info and webhook/list are queried.
// mocked backup/config/info and webhook/list are queried. usage_prediction
// is needed for common-controls sections in strategy dashboards.
hass.updateHass({
config: {
...hass.config,
components: [...(hass.config?.components ?? []), "backup", "webhook"],
components: [
...(hass.config?.components ?? []),
"backup",
"webhook",
"usage_prediction",
],
},
});
@@ -122,6 +129,7 @@ export class HaDemo extends HomeAssistantAppEl {
mockDeviceRegistry(hass, demoDevices);
mockFloorRegistry(hass);
mockLabelRegistry(hass);
mockUsagePrediction(hass);
mockEntityRegistry(hass, [
{
config_entry_id: "co2signal",
+19
View File
@@ -0,0 +1,19 @@
import type { CommonControlsResult } from "../../../src/data/usage_prediction";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockUsagePrediction = (hass: MockHomeAssistant) => {
// Entities that don't exist in the currently loaded demo config are
// filtered out by the common-controls section strategy.
hass.mockWS("usage_prediction/common_control", (): CommonControlsResult => ({
entities: [
"light.living_room_floor_lamp",
"climate.living_room",
"cover.living_room_blinds",
"media_player.living_room_speaker",
"light.kitchen_spotlights",
"switch.coffee_machine",
"light.bedside_lamp",
"alarm_control_panel.home_alarm",
],
}));
};
+9 -10
View File
@@ -77,7 +77,7 @@
"@lit/task": "1.0.3",
"@material/mwc-formfield": "patch:@material/mwc-formfield@npm%3A0.27.0#~/.yarn/patches/@material-mwc-formfield-npm-0.27.0-9528cb60f6.patch",
"@material/mwc-list": "patch:@material/mwc-list@npm%3A0.27.0#~/.yarn/patches/@material-mwc-list-npm-0.27.0-5344fc9de4.patch",
"@material/web": "2.4.1",
"@material/web": "2.5.0",
"@mdi/js": "7.4.47",
"@mdi/svg": "7.4.47",
"@replit/codemirror-indentation-markers": "6.5.3",
@@ -115,7 +115,7 @@
"lit": "3.3.3",
"lit-html": "3.3.3",
"luxon": "3.7.2",
"marked": "18.0.6",
"marked": "18.0.7",
"memoize-one": "6.0.0",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -151,8 +151,8 @@
"@octokit/plugin-retry": "8.1.0",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.61.1",
"@rsdoctor/rspack-plugin": "1.6.0",
"@rspack/core": "2.1.4",
"@rsdoctor/rspack-plugin": "1.6.1",
"@rspack/core": "2.1.5",
"@rspack/dev-server": "2.1.0",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "6.0.26",
@@ -196,22 +196,22 @@
"jsdom": "29.1.1",
"jszip": "3.10.1",
"license-checker-rseidelsohn": "5.0.1",
"lint-staged": "17.0.8",
"lint-staged": "17.1.0",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.18.1",
"map-stream": "0.0.7",
"minify-literals": "2.1.0",
"pinst": "3.0.0",
"prettier": "3.9.5",
"prettier": "3.9.6",
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.6",
"sinon": "22.0.0",
"sinon": "22.1.0",
"tar": "7.5.20",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.64.0",
"typescript-eslint": "8.65.0",
"vite-tsconfig-paths": "6.1.1",
"vitest": "4.1.10",
"webpack-stats-plugin": "1.1.3",
@@ -226,8 +226,7 @@
"@fullcalendar/daygrid": "6.1.21",
"globals": "17.7.0",
"tslib": "2.8.1",
"@material/mwc-list@^0.27.0": "patch:@material/mwc-list@npm%3A0.27.0#~/.yarn/patches/@material-mwc-list-npm-0.27.0-5344fc9de4.patch",
"glob@^10.2.2": "^10.5.0"
"@material/mwc-list@^0.27.0": "patch:@material/mwc-list@npm%3A0.27.0#~/.yarn/patches/@material-mwc-list-npm-0.27.0-5344fc9de4.patch"
},
"packageManager": "yarn@4.17.1",
"volta": {
+16
View File
@@ -58,6 +58,17 @@
"depNameTemplate": "rhysd/actionlint",
"datasourceTemplate": "github-releases",
"extractVersionTemplate": "^v(?<version>.+)$"
},
{
"description": "Keep Playwright CI container image up to date",
"customType": "regex",
"managerFilePatterns": ["/^\\.github/workflows/e2e\\.yaml$/"],
"matchStrings": [
"mcr\\.microsoft\\.com/playwright:(?<currentValue>v\\d+\\.\\d+\\.\\d+-noble)"
],
"depNameTemplate": "mcr.microsoft.com/playwright",
"datasourceTemplate": "docker",
"versioningTemplate": "regex:^v(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)-(?<compatibility>noble)$"
}
],
"packageRules": [
@@ -91,6 +102,11 @@
"description": "Group formatjs monorepo package",
"groupName": "formatjs",
"matchPackageNames": ["@formatjs/**"]
},
{
"description": "Group Playwright package and CI container updates",
"groupName": "Playwright",
"matchPackageNames": ["@playwright/test", "mcr.microsoft.com/playwright"]
}
]
}
+11 -10
View File
@@ -9,16 +9,17 @@ export const castApiAvailable = () => {
loadedPromise = new Promise((resolve) => {
(window as any).__onGCastApiAvailable = resolve;
});
// Any element with a specific ID will get set as a JS variable on window
// This will override the cast SDK if the iconset is loaded afterwards.
// Conflicting IDs will no longer mess with window, so we'll just append one.
const el = document.createElement("div");
el.id = "cast";
document.body.append(el);
loadJS(
"https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"
);
// Any element with a specific ID will get set as a JS variable on window
// This will override the cast SDK if the iconset is loaded afterwards.
// Conflicting IDs will no longer mess with window, so we'll just append one.
const el = document.createElement("div");
el.id = "cast";
document.body.append(el);
loadJS(
"https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"
).catch(() => resolve(false));
});
return loadedPromise;
};
+8 -1
View File
@@ -91,7 +91,14 @@ export const STATES_OFF = ["closed", "locked", "off"];
export const BINARY_STATE_ON = "on";
export const BINARY_STATE_OFF = "off";
/** Domains where we allow toggle in Lovelace. */
/** Domains where we allow toggle in Lovelace.
* This is not strictly a list of what is possible to toggle, but the list of
* domains where toggle is considered the primary default behavior.
* Entities card uses this to determine which entities are controlled by the
* header toggle.
* Some cards use this to decide the default tap action.
* Use canToggleDomain/canToggleState for determining if toggling is possible.
*/
export const DOMAINS_TOGGLE = new Set([
"fan",
"input_boolean",
+4 -8
View File
@@ -1,16 +1,12 @@
import type { HomeAssistant } from "../../types";
import { getToggleAction } from "./get_toggle_action";
export const canToggleDomain = (hass: HomeAssistant, domain: string) => {
const services = hass.services[domain];
if (!services) {
return false;
}
if (domain === "lock") {
return "lock" in services;
}
if (domain === "cover") {
return "open_cover" in services;
}
return "turn_on" in services;
const actionOn = getToggleAction(domain, true);
const actionOff = getToggleAction(domain, false);
return actionOn in services && actionOff in services;
};
+8 -2
View File
@@ -3,6 +3,7 @@ import type { HomeAssistant } from "../../types";
import { canToggleDomain } from "./can_toggle_domain";
import { computeStateDomain } from "./compute_state_domain";
import { supportsFeature } from "./supports-feature";
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
const domain = computeStateDomain(stateObj);
@@ -25,8 +26,13 @@ export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
return false;
}
if (domain === "climate") {
return supportsFeature(stateObj, 4096);
if (
domain in SPECIAL_TOGGLE_ACTIONS &&
SPECIAL_TOGGLE_ACTIONS[domain].feature
) {
return SPECIAL_TOGGLE_ACTIONS[domain].feature.every((f) =>
supportsFeature(stateObj, f)
);
}
return canToggleDomain(hass, domain);
+5 -5
View File
@@ -2,19 +2,19 @@ import { AITaskEntityFeature } from "../../data/ai_task";
import { AlarmControlPanelEntityFeature } from "../../data/alarm_control_panel";
import { AssistSatelliteEntityFeature } from "../../data/assist_satellite";
import { CalendarEntityFeature } from "../../data/calendar";
import { CameraEntityFeature } from "../../data/camera";
import { ClimateEntityFeature } from "../../data/climate";
import { CameraEntityFeature } from "../../data/feature/camera_entity_feature";
import { ClimateEntityFeature } from "../../data/feature/climate_entity_feature";
import { ConversationEntityFeature } from "../../data/conversation";
import { CoverEntityFeature } from "../../data/cover";
import { CoverEntityFeature } from "../../data/feature/cover_entity_feature";
import { FanEntityFeature } from "../../data/fan";
import { HumidifierEntityFeature } from "../../data/humidifier";
import { LawnMowerEntityFeature } from "../../data/lawn_mower";
import { LightEntityFeature } from "../../data/light";
import { LockEntityFeature } from "../../data/lock";
import { MediaPlayerEntityFeature } from "../../data/media-player";
import { MediaPlayerEntityFeature } from "../../data/feature/media-player_entity_feature";
import { NotifyEntityFeature } from "../../data/notify";
import { RemoteEntityFeature } from "../../data/remote";
import { SirenEntityFeature } from "../../data/siren";
import { SirenEntityFeature } from "../../data/feature/siren_entity_feature";
import { TodoListEntityFeature } from "../../data/todo";
import { UpdateEntityFeature } from "../../data/update";
import { VacuumEntityFeature } from "../../data/vacuum";
+7 -2
View File
@@ -89,7 +89,7 @@ const FIXED_DOMAIN_ATTRIBUTE_STATES = {
device_class: [
"battery",
"battery_charging",
"co",
"carbon_monoxide",
"cold",
"connectivity",
"door",
@@ -227,7 +227,12 @@ const FIXED_DOMAIN_ATTRIBUTE_STATES = {
"voltage",
"volume_flow_rate",
],
state_class: ["measurement", "total", "total_increasing"],
state_class: [
"measurement",
"measurement_angle",
"total",
"total_increasing",
],
},
switch: {
device_class: ["outlet", "switch"],
+72
View File
@@ -0,0 +1,72 @@
import { CameraEntityFeature } from "../../data/feature/camera_entity_feature";
import { ClimateEntityFeature } from "../../data/feature/climate_entity_feature";
import { CoverEntityFeature } from "../../data/feature/cover_entity_feature";
import { MediaPlayerEntityFeature } from "../../data/feature/media-player_entity_feature";
import { SirenEntityFeature } from "../../data/feature/siren_entity_feature";
// These are domains which have nonstandard 'toggle' behavior.
// Otherwise, any domain with a turn_on and turn_off service may be toggled.
// If features are provided, all features must be supported.
interface SpecialToggleAction {
on: string;
off?: string;
feature?: number[];
}
export const SPECIAL_TOGGLE_ACTIONS: Record<string, SpecialToggleAction> = {
button: {
on: "press",
},
camera: {
on: "turn_on",
off: "turn_off",
feature: [CameraEntityFeature.ON_OFF],
},
climate: {
on: "turn_on",
off: "turn_off",
feature: [ClimateEntityFeature.TURN_ON, ClimateEntityFeature.TURN_OFF],
},
cover: {
on: "open_cover",
off: "close_cover",
feature: [CoverEntityFeature.OPEN, CoverEntityFeature.CLOSE],
},
input_button: {
on: "press",
},
lock: {
on: "unlock",
off: "lock",
},
media_player: {
on: "turn_on",
off: "turn_off",
feature: [
MediaPlayerEntityFeature.TURN_ON,
MediaPlayerEntityFeature.TURN_OFF,
],
},
scene: {
on: "turn_on",
},
siren: {
on: "turn_on",
off: "turn_off",
feature: [SirenEntityFeature.TURN_ON, SirenEntityFeature.TURN_OFF],
},
valve: {
on: "open_valve",
off: "close_valve",
},
};
// This function assumes that the passed domain can toggle, it may otherwise
// return a service that does not exist.
export const getToggleAction = (domain: string, onOff: boolean): string => {
return (
SPECIAL_TOGGLE_ACTIONS[domain]?.[onOff ? "on" : "off"] ||
SPECIAL_TOGGLE_ACTIONS[domain]?.["on"] ||
(onOff ? "turn_on" : "turn_off")
);
};
+2 -4
View File
@@ -2,6 +2,7 @@ import type { HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { HomeAssistant } from "../../types";
import { computeStateDomain } from "./compute_state_domain";
import { getToggleAction } from "./get_toggle_action";
export const computeGroupEntitiesState = (states: HassEntity[]): string => {
if (!states.length) {
@@ -57,14 +58,11 @@ export const toggleGroupEntities = (
const isOn = state === "on" || state === "open";
let service = isOn ? "turn_off" : "turn_on";
let service = getToggleAction(domain, !isOn);
if (domain === "cover") {
if (state === "opening" || state === "closing") {
// If the cover is opening or closing, we toggle it to stop it
service = "stop_cover";
} else {
// For covers, we use the open/close service
service = isOn ? "close_cover" : "open_cover";
}
}
+23 -12
View File
@@ -1,12 +1,27 @@
// A range smaller than this fraction of the axis magnitude is floating-point
// noise (e.g. from summed statistics), not real precision.
const NEGLIGIBLE_RANGE_RATIO = 1e-10;
// Derive the number of decimal digits to use for Y-axis labels from the
// observed data range. We mirror how ECharts sizes its ticks: it splits the
// range into ~5 intervals (its default `splitNumber`) and rounds that raw
// interval to a "nice" 1/2/3/5×10ⁿ value, then reports the decimals that nice
// interval needs. This matches the precision ECharts actually renders, so
// labels are neither truncated to identical values nor padded with extra zeros.
export function computeYAxisFractionDigits(min: number, max: number): number {
const range = max - min;
export function computeYAxisFractionDigits(
min: number,
max: number,
// Bar axes render from 0, so union the extent with 0 to match.
includeZero = false
): number {
const lo = includeZero ? Math.min(min, 0) : min;
const hi = includeZero ? Math.max(max, 0) : max;
const range = hi - lo;
if (!Number.isFinite(range) || range <= 0) return 1;
// A near-zero range is fp noise; deriving digits from it would pad the labels
// with a tail of zeros (e.g. "0.20000000000000"), so treat it as flat.
const magnitude = Math.max(Math.abs(lo), Math.abs(hi));
if (range <= magnitude * NEGLIGIBLE_RANGE_RATIO) return 1;
const rawInterval = range / 5;
const exponent = Math.floor(Math.log10(rawInterval));
const mantissa = rawInterval / 10 ** exponent; // in [1, 10)
@@ -38,9 +53,7 @@ const resolveYAxisBound = (
export function createYAxisPrecisionBounds(options: {
min?: YAxisBound;
max?: YAxisBound;
// Axes without `scale: true` (e.g. bar charts) stay anchored at 0, so the
// rendered ticks span from 0 even when the data does not. Union the extent
// with 0 to match the labels ECharts actually draws.
// Set for bar axes anchored at 0, so precision reflects the 0-based range.
includeZero?: boolean;
onFractionDigits: (digits: number) => void;
}): {
@@ -52,13 +65,11 @@ export function createYAxisPrecisionBounds(options: {
min: (values) => {
const resolvedMin = resolveYAxisBound(min, values);
const resolvedMax = resolveYAxisBound(max, values);
let extentMin = resolvedMin ?? values.min;
let extentMax = resolvedMax ?? values.max;
if (includeZero) {
extentMin = Math.min(extentMin, 0);
extentMax = Math.max(extentMax, 0);
}
onFractionDigits(computeYAxisFractionDigits(extentMin, extentMax));
const extentMin = resolvedMin ?? values.min;
const extentMax = resolvedMax ?? values.max;
onFractionDigits(
computeYAxisFractionDigits(extentMin, extentMax, includeZero)
);
return resolvedMin;
},
max: (values) => resolveYAxisBound(max, values),
+3 -3
View File
@@ -1,8 +1,8 @@
import { AssistChip } from "@material/web/chips/internal/assist-chip";
import { styles } from "@material/web/chips/internal/assist-styles";
import { styles } from "@material/web/chips/internal/assist-styles.cssresult.js";
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles";
import { styles as elevatedStyles } from "@material/web/chips/internal/elevated-styles";
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles.cssresult.js";
import { styles as elevatedStyles } from "@material/web/chips/internal/elevated-styles.cssresult.js";
import { css, html } from "lit";
import { customElement, property } from "lit/decorators";
+5 -5
View File
@@ -1,9 +1,9 @@
import { styles as elevatedStyles } from "@material/web/chips/internal/elevated-styles";
import { styles as elevatedStyles } from "@material/web/chips/internal/elevated-styles.cssresult.js";
import { FilterChip } from "@material/web/chips/internal/filter-chip";
import { styles } from "@material/web/chips/internal/filter-styles";
import { styles as selectableStyles } from "@material/web/chips/internal/selectable-styles";
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles";
import { styles as trailingIconStyles } from "@material/web/chips/internal/trailing-icon-styles";
import { styles } from "@material/web/chips/internal/filter-styles.cssresult.js";
import { styles as selectableStyles } from "@material/web/chips/internal/selectable-styles.cssresult.js";
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles.cssresult.js";
import { styles as trailingIconStyles } from "@material/web/chips/internal/trailing-icon-styles.cssresult.js";
import { css, html } from "lit";
import { customElement, property } from "lit/decorators";
+4 -4
View File
@@ -1,8 +1,8 @@
import { InputChip } from "@material/web/chips/internal/input-chip";
import { styles } from "@material/web/chips/internal/input-styles";
import { styles as selectableStyles } from "@material/web/chips/internal/selectable-styles";
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles";
import { styles as trailingIconStyles } from "@material/web/chips/internal/trailing-icon-styles";
import { styles } from "@material/web/chips/internal/input-styles.cssresult.js";
import { styles as selectableStyles } from "@material/web/chips/internal/selectable-styles.cssresult.js";
import { styles as sharedStyles } from "@material/web/chips/internal/shared-styles.cssresult.js";
import { styles as trailingIconStyles } from "@material/web/chips/internal/trailing-icon-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
@@ -33,7 +33,6 @@ const HIDDEN_ATTRIBUTES = [
"battery_level",
"code_arm_required",
"code_format",
"color_modes",
"device_class",
"editable",
"effect_list",
+4 -18
View File
@@ -13,6 +13,7 @@ import { forwardHaptic } from "../../data/haptics";
import "../ha-formfield";
import "../ha-icon-button";
import "../ha-switch";
import { getToggleAction } from "../../common/entity/get_toggle_action";
const isOn = (stateObj?: HassEntity) =>
stateObj !== undefined &&
@@ -124,25 +125,10 @@ export class HaEntityToggle extends LitElement {
}
forwardHaptic(this, "light");
const stateDomain = computeStateDomain(this.stateObj);
let serviceDomain;
let service;
if (stateDomain === "lock") {
serviceDomain = "lock";
service = turnOn ? "unlock" : "lock";
} else if (stateDomain === "cover") {
serviceDomain = "cover";
service = turnOn ? "open_cover" : "close_cover";
} else if (stateDomain === "valve") {
serviceDomain = "valve";
service = turnOn ? "open_valve" : "close_valve";
} else if (stateDomain === "group") {
serviceDomain = "homeassistant";
service = turnOn ? "turn_on" : "turn_off";
} else {
serviceDomain = stateDomain;
service = turnOn ? "turn_on" : "turn_off";
}
const serviceDomain =
stateDomain === "group" ? "homeassistant" : stateDomain;
const service = getToggleAction(stateDomain, turnOn);
const currentState = this.stateObj;
+24 -11
View File
@@ -6,8 +6,10 @@ import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { styleMap } from "lit/directives/style-map";
import { computeCssColor } from "../../common/color/compute-color";
import { computeDomain } from "../../common/entity/compute_domain";
import { computeStateDomain } from "../../common/entity/compute_state_domain";
import { stateActive } from "../../common/entity/state_active";
import {
stateColorBrightness,
stateColorCss,
@@ -27,10 +29,15 @@ export class StateBadge extends LitElement {
@property({ attribute: false }) public overrideImage?: string;
// Cannot be a boolean attribute because undefined is treated different than
// false. When it is undefined, state is still colored for light entities.
/**
* Cannot be a boolean attribute because undefined is treated different than
* false. When it is undefined, state is still colored for light entities.
* @deprecated use `color` instead
*/
@property({ attribute: false }) public stateColor?: boolean;
// "state", "none" or a color (theme color name or CSS color). Custom colors
// apply when the entity is active. Takes precedence over stateColor.
@property() public color?: string;
// @todo Consider reworking to eliminate need for attribute since it is manipulated internally
@@ -67,11 +74,17 @@ export class StateBadge extends LitElement {
}
}
private get _stateColor() {
private get _color(): string | undefined {
if (this.color) {
return this.color;
}
if (this.stateColor !== undefined) {
return this.stateColor ? "state" : "none";
}
const domain = this.stateObj
? computeStateDomain(this.stateObj)
: undefined;
return this.stateColor ?? domain === "light";
return domain === "light" ? "state" : undefined;
}
protected render() {
@@ -131,6 +144,7 @@ export class StateBadge extends LitElement {
if (stateObj) {
const domain = computeDomain(stateObj.entity_id);
const color = this._color;
if (this.overrideImage === undefined) {
// hide icon if we have entity picture
if (
@@ -147,13 +161,10 @@ export class StateBadge extends LitElement {
}
backgroundImage = `url(${imageUrl})`;
this.icon = false;
} else if (this.color) {
// Externally provided overriding color wins over state color
iconStyle.color = this.color;
} else if (this._stateColor) {
const color = stateColorCss(stateObj);
if (color) {
iconStyle.color = color;
} else if (color === "state") {
const stateColor = stateColorCss(stateObj);
if (stateColor) {
iconStyle.color = stateColor;
}
if (stateObj.attributes.rgb_color) {
iconStyle.color = `rgb(${stateObj.attributes.rgb_color.join(",")})`;
@@ -180,6 +191,8 @@ export class StateBadge extends LitElement {
delete iconStyle.color;
}
}
} else if (color && color !== "none" && stateActive(stateObj)) {
iconStyle.color = computeCssColor(color);
}
} else if (this.overrideImage) {
backgroundImage = `url(${this._resolveImageUrl(this.overrideImage)})`;
+4 -2
View File
@@ -1,6 +1,7 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import type { HomeAssistant } from "../../types";
import "../ha-relative-time";
import "../ha-tooltip";
@@ -23,10 +24,11 @@ class StateInfo extends LitElement {
const name = this.hass.formatEntityName(this.stateObj, { type: "entity" });
// Inline style because the state-badge color API only colors active entities
return html`<state-badge
.stateObj=${this.stateObj}
.stateColor=${true}
.color=${this.color}
.stateColor=${!this.color}
style=${styleMap({ color: this.color })}
></state-badge>
<div class="info">
<div class="name ${this.inDialog ? "in-dialog" : ""}" .title=${name}>
+37 -1
View File
@@ -57,6 +57,16 @@ interface AssistMessage {
error?: boolean;
}
export const initialPromptToSubmit = (
prompt: string | undefined,
submit: boolean
): string | undefined => (submit ? prompt?.trim() || undefined : undefined);
export const assistPipelineChanged = (
previous: AssistPipeline | undefined,
current: AssistPipeline | undefined
): boolean => previous?.id !== current?.id;
@customElement("ha-assist-chat")
export class HaAssistChat extends LitElement {
@property({ attribute: false }) public pipeline?: AssistPipeline;
@@ -67,6 +77,12 @@ export class HaAssistChat extends LitElement {
@property({ attribute: false })
public startListening?: boolean;
@property({ attribute: false })
public initialPrompt?: string;
@property({ attribute: false })
public submitInitialPrompt = false;
@query("#message-input") private _messageInput!: HaInput;
@query(".message:last-child")
@@ -99,6 +115,8 @@ export class HaAssistChat extends LitElement {
private _conversationId: string | null = null;
private _initialPromptSubmitted = false;
private _audioRecorder?: AudioRecorder;
private _audioBuffer?: Int16Array[];
@@ -108,7 +126,11 @@ export class HaAssistChat extends LitElement {
private _stt_binary_handler_id?: number | null;
protected willUpdate(changedProperties: PropertyValues<this>): void {
if (!this.hasUpdated || changedProperties.has("pipeline")) {
if (
!this.hasUpdated ||
(changedProperties.has("pipeline") &&
assistPipelineChanged(changedProperties.get("pipeline"), this.pipeline))
) {
this._conversation = [
{
who: "hass",
@@ -138,6 +160,20 @@ export class HaAssistChat extends LitElement {
if (changedProps.has("_conversation")) {
this._scrollMessagesBottom();
}
if (
!this._initialPromptSubmitted &&
(changedProps.has("initialPrompt") ||
changedProps.has("submitInitialPrompt"))
) {
const prompt = initialPromptToSubmit(
this.initialPrompt,
this.submitInitialPrompt
);
if (prompt) {
this._initialPromptSubmitted = true;
this._processText(prompt);
}
}
}
public disconnectedCallback() {
+30 -7
View File
@@ -57,17 +57,40 @@ export const evaluateCondition = (
return matchFieldCondition(condition, data);
};
export const isFieldHidden = (
export const isFieldVisible = (
schema: HaFormSchema,
data: HaFormDataContainer | undefined
): boolean => {
const { hidden } = schema as HaFormBaseSchema;
if (!hidden) {
return false;
}
if (hidden === true) {
const { visible } = schema as HaFormBaseSchema;
if (visible === undefined || visible === true) {
return true;
}
const conditions = Array.isArray(hidden) ? hidden : [hidden];
if (visible === false) {
return false;
}
const conditions = Array.isArray(visible) ? visible : [visible];
return conditions.every((condition) => evaluateCondition(condition, data));
};
// Hiding a field drops its value, which can flip another field's condition, so
// resolve the set to a fixpoint.
export const getHiddenFields = (
schema: readonly HaFormSchema[],
data: HaFormDataContainer | undefined
): Set<string> => {
const hidden = new Set<string>();
const evalData: HaFormDataContainer = { ...(data ?? {}) };
let changed = true;
while (changed) {
changed = false;
for (const field of schema) {
if (hidden.has(field.name) || isFieldVisible(field, evalData)) {
continue;
}
hidden.add(field.name);
delete evalData[field.name];
changed = true;
}
}
return hidden;
};
+4 -2
View File
@@ -2,7 +2,7 @@ import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, queryAll } from "lit/decorators";
import type { HomeAssistant } from "../../types";
import { isFieldHidden } from "./conditions";
import { getHiddenFields } from "./conditions";
import "./ha-form";
import type { HaForm } from "./ha-form";
import type {
@@ -68,9 +68,11 @@ export class HaFormGrid extends LitElement implements HaFormElement {
}
protected render(): TemplateResult {
const hiddenFields = getHiddenFields(this.schema.schema, this.data);
return html`
${this.schema.schema
.filter((item) => !isFieldHidden(item, this.data))
.filter((item) => !hiddenFields.has(item.name))
.map(
(item) => html`
<ha-form
+6 -3
View File
@@ -6,7 +6,7 @@ import { fireEvent } from "../../common/dom/fire_event";
import type { HomeAssistant } from "../../types";
import "../ha-alert";
import "../ha-selector/ha-selector";
import { isFieldHidden } from "./conditions";
import { getHiddenFields } from "./conditions";
import type { HaFormDataContainer, HaFormElement, HaFormSchema } from "./types";
const LOAD_ELEMENTS = {
@@ -99,8 +99,9 @@ export class HaForm extends LitElement implements HaFormElement {
let isValid = true;
let firstInvalidElement: HTMLElement | undefined;
const hiddenFields = getHiddenFields(this.schema, this.data);
const visibleSchema = this.schema.filter(
(item) => !isFieldHidden(item, this.data)
(item) => !hiddenFields.has(item.name)
);
visibleSchema.forEach((item, index) => {
@@ -157,6 +158,8 @@ export class HaForm extends LitElement implements HaFormElement {
}
protected render(): TemplateResult {
const renderHiddenFields = getHiddenFields(this.schema, this.data);
return html`
<div class="root" part="root">
${
@@ -169,7 +172,7 @@ export class HaForm extends LitElement implements HaFormElement {
: ""
}
${this.schema.map((item) => {
if (isFieldHidden(item, this.data)) {
if (renderHiddenFields.has(item.name)) {
return nothing;
}
+3 -3
View File
@@ -22,9 +22,9 @@ export interface HaFormBaseSchema {
default?: HaFormData;
required?: boolean;
disabled?: boolean;
// Field is hidden while the condition holds. Serializable so it can be
// shared with the backend and other renderers.
hidden?: boolean | HaFormCondition | HaFormCondition[];
// Field is visible while the condition holds (visible by default).
// Serializable so it can be shared with the backend and other renderers.
visible?: boolean | HaFormCondition | HaFormCondition[];
description?: {
suffix?: string;
// This value will be set initially when form is loaded
+1 -1
View File
@@ -1,5 +1,5 @@
import { ListItemEl } from "@material/web/list/internal/listitem/list-item";
import { styles } from "@material/web/list/internal/listitem/list-item-styles";
import { styles } from "@material/web/list/internal/listitem/list-item-styles.cssresult.js";
import { css, html, nothing, type TemplateResult } from "lit";
import { customElement } from "lit/decorators";
import "./ha-ripple";
+1 -1
View File
@@ -1,5 +1,5 @@
import { List } from "@material/web/list/internal/list";
import { styles } from "@material/web/list/internal/list-styles";
import { styles } from "@material/web/list/internal/list-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
+2 -2
View File
@@ -1,6 +1,6 @@
import { OutlinedButton } from "@material/web/button/internal/outlined-button";
import { styles as sharedStyles } from "@material/web/button/internal/shared-styles";
import { styles } from "@material/web/button/internal/outlined-styles";
import { styles as sharedStyles } from "@material/web/button/internal/shared-styles.cssresult.js";
import { styles } from "@material/web/button/internal/outlined-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
+2 -2
View File
@@ -1,6 +1,6 @@
import { OutlinedField } from "@material/web/field/internal/outlined-field";
import { styles } from "@material/web/field/internal/outlined-styles";
import { styles as sharedStyles } from "@material/web/field/internal/shared-styles";
import { styles } from "@material/web/field/internal/outlined-styles.cssresult.js";
import { styles as sharedStyles } from "@material/web/field/internal/shared-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
import { literal } from "lit/static-html";
+2 -2
View File
@@ -1,6 +1,6 @@
import { IconButton } from "@material/web/iconbutton/internal/icon-button";
import { styles } from "@material/web/iconbutton/internal/outlined-styles";
import { styles as sharedStyles } from "@material/web/iconbutton/internal/shared-styles";
import { styles } from "@material/web/iconbutton/internal/outlined-styles.cssresult.js";
import { styles as sharedStyles } from "@material/web/iconbutton/internal/shared-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
+35 -18
View File
@@ -4,6 +4,23 @@ import { customElement, property, query, state } from "lit/decorators";
import QRCode from "qrcode";
import "./ha-alert";
import { rgb2hex } from "../common/color/convert-color";
import {
getContrastedColorHex,
getRGBContrastRatio,
} from "../common/color/rgb";
// Minimum contrast ratio (WCAG non-text minimum) below which we substitute a
// legible foreground so the QR code never renders unscannable.
const MIN_CONTRAST_RATIO = 3;
const parseRgbVariable = (
value: string
): [number, number, number] | undefined => {
const parts = value.split(",").map((part) => parseInt(part, 10));
return parts.length === 3 && parts.every((part) => !Number.isNaN(part))
? (parts as [number, number, number])
: undefined;
};
@customElement("ha-qr-code")
export class HaQrCode extends LitElement {
@@ -60,27 +77,27 @@ export class HaQrCode extends LitElement {
changedProperties.has("centerImage"))
) {
const computedStyles = getComputedStyle(this);
const textRgb = computedStyles.getPropertyValue(
"--rgb-primary-text-color"
const textRgb = parseRgbVariable(
computedStyles.getPropertyValue("--rgb-primary-text-color")
);
const backgroundRgb = computedStyles.getPropertyValue(
"--rgb-card-background-color"
);
const textHex = rgb2hex(
textRgb.split(",").map((a) => parseInt(a, 10)) as [
number,
number,
number,
]
);
const backgroundHex = rgb2hex(
backgroundRgb.split(",").map((a) => parseInt(a, 10)) as [
number,
number,
number,
]
const backgroundRgb = parseRgbVariable(
computedStyles.getPropertyValue("--rgb-card-background-color")
);
const backgroundHex = backgroundRgb ? rgb2hex(backgroundRgb) : "#ffffff";
let textHex = textRgb ? rgb2hex(textRgb) : "#000000";
// If the theme colors are missing/invalid or don't contrast enough, the
// QR code would be unscannable (e.g. white-on-white). Fall back to a
// foreground guaranteed to contrast the resolved background.
if (
!textRgb ||
!backgroundRgb ||
getRGBContrastRatio(textRgb, backgroundRgb) < MIN_CONTRAST_RATIO
) {
textHex = getContrastedColorHex(backgroundHex);
}
QRCode.toCanvas(canvas, this.data, {
errorCorrectionLevel:
this.errorCorrectionLevel || (this.centerImage ? "Q" : "M"),
+1 -1
View File
@@ -1,6 +1,6 @@
import { AttachableController } from "@material/web/internal/controller/attachable-controller";
import { Ripple } from "@material/web/ripple/internal/ripple";
import { styles } from "@material/web/ripple/internal/ripple-styles";
import { styles } from "@material/web/ripple/internal/ripple-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
+40 -14
View File
@@ -1,19 +1,23 @@
import { consume, type ContextType } from "@lit/context";
import { initialState } from "@lit/task";
import { html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import type { HassEntity } from "home-assistant-js-websocket";
import { AsyncValueTask } from "../../common/controllers/async-value-task";
import { consumeEntityState } from "../../common/decorators/consume-context-entry";
import { fireEvent } from "../../common/dom/fire_event";
import {
configContext,
connectionContext,
entitiesContext,
} from "../../data/context";
import { entityIcon } from "../../data/icons";
import type { IconSelector } from "../../data/selector";
import type { HomeAssistant } from "../../types";
import "../ha-icon-picker";
import "../ha-state-icon";
@customElement("ha-selector-icon")
export class HaIconSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: IconSelector;
@property() public value?: string;
@@ -30,10 +34,21 @@ export class HaIconSelector extends LitElement {
icon_entity?: string;
};
private get _stateObj(): HassEntity | undefined {
const iconEntity = this.context?.icon_entity;
return iconEntity ? this.hass.states[iconEntity] : undefined;
}
@state()
@consumeEntityState({ entityIdPath: ["context", "icon_entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: entitiesContext, subscribe: true })
private _entities?: ContextType<typeof entitiesContext>;
@state()
@consume({ context: configContext, subscribe: true })
private _config?: ContextType<typeof configContext>;
@state()
@consume({ context: connectionContext, subscribe: true })
private _connection?: ContextType<typeof connectionContext>;
private _placeholderTask = new AsyncValueTask(this, {
task: ([
@@ -44,19 +59,31 @@ export class HaIconSelector extends LitElement {
connection,
stateObj,
]) => {
if (placeholder || attributeIcon || !stateObj) {
if (
placeholder ||
attributeIcon ||
!entities ||
!config ||
!connection ||
!stateObj
) {
return initialState;
}
return entityIcon(entities, config, connection, stateObj);
return entityIcon(
entities,
config.config,
connection.connection,
stateObj
);
},
args: () => {
const stateObj = this._stateObj;
return [
this.selector.icon?.placeholder,
stateObj?.attributes.icon,
this.hass.entities,
this.hass.config,
this.hass.connection,
this._entities,
this._config,
this._connection,
stateObj,
] as const;
},
@@ -72,7 +99,6 @@ export class HaIconSelector extends LitElement {
return html`
<ha-icon-picker
.hass=${this.hass}
.label=${this.label}
.value=${this.value}
.required=${this.required}
@@ -10,6 +10,7 @@ import type {
} from "../../common/translations/localize";
import type { HomeAssistant } from "../../types";
import "../ha-form/ha-form";
import { unitOfMeasurementOptions } from "../../data/number";
const SELECTOR_DEFAULTS = {
number: {
@@ -112,6 +113,16 @@ const SELECTOR_SCHEMAS = {
name: "step",
selector: { number: { mode: "box", step: "any" } },
},
{
name: "unit_of_measurement",
selector: {
select: {
custom_value: true,
sort: true,
options: unitOfMeasurementOptions,
},
},
},
] as const,
object: [] as const,
color_rgb: [] as const,
+1 -1
View File
@@ -1,5 +1,5 @@
import { SubMenu } from "@material/web/menu/internal/submenu/sub-menu";
import { styles } from "@material/web/menu/internal/submenu/sub-menu-styles";
import { styles } from "@material/web/menu/internal/submenu/sub-menu-styles.cssresult.js";
import { css } from "lit";
import { customElement } from "lit/decorators";
+1 -2
View File
@@ -1,4 +1,3 @@
import { memoize } from "@fullcalendar/core/internal";
import { setHours, setMinutes } from "date-fns";
import type { HassConfig } from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
@@ -411,7 +410,7 @@ export type BackupType = "automatic" | "manual" | "app_update";
const BACKUP_TYPE_ORDER: BackupType[] = ["automatic", "app_update", "manual"];
export const getBackupTypes = memoize((isHassio: boolean) =>
export const getBackupTypes = memoizeOne((isHassio: boolean) =>
isHassio
? BACKUP_TYPE_ORDER
: BACKUP_TYPE_ORDER.filter((type) => type !== "app_update")
+1 -4
View File
@@ -13,10 +13,7 @@ export const STREAM_TYPE_WEB_RTC = "web_rtc";
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
export enum CameraEntityFeature {
ON_OFF = 1,
STREAM = 2,
}
export { CameraEntityFeature } from "./feature/camera_entity_feature";
interface CameraEntityAttributes extends HassEntityAttributeBase {
model_name: string;
+1 -12
View File
@@ -68,18 +68,7 @@ export type ClimateEntity = HassEntityBase & {
};
};
export enum ClimateEntityFeature {
TARGET_TEMPERATURE = 1,
TARGET_TEMPERATURE_RANGE = 2,
TARGET_HUMIDITY = 4,
FAN_MODE = 8,
PRESET_MODE = 16,
SWING_MODE = 32,
AUX_HEAT = 64,
TURN_OFF = 128,
TURN_ON = 256,
SWING_HORIZONTAL_MODE = 512,
}
export { ClimateEntityFeature } from "./feature/climate_entity_feature";
const hvacModeOrdering = HVAC_MODES.reduce(
(order, mode, index) => {
+2 -10
View File
@@ -6,17 +6,9 @@ import { stateActive } from "../common/entity/state_active";
import { supportsFeature } from "../common/entity/supports-feature";
import type { HomeAssistantFormatters } from "../types";
import { UNAVAILABLE } from "./entity/entity";
import { CoverEntityFeature } from "./feature/cover_entity_feature";
export enum CoverEntityFeature {
OPEN = 1,
CLOSE = 2,
SET_POSITION = 4,
STOP = 8,
OPEN_TILT = 16,
CLOSE_TILT = 32,
STOP_TILT = 64,
SET_TILT_POSITION = 128,
}
export { CoverEntityFeature };
export const DEFAULT_COVER_FAVORITE_POSITIONS = [0, 25, 75, 100];
+2 -2
View File
@@ -127,7 +127,6 @@ export const NON_NUMERIC_ATTRIBUTES = [
"away_mode",
"changed_by",
"code_format",
"color_modes",
"current_activity",
"device_class",
"editable",
@@ -177,6 +176,7 @@ export const NON_NUMERIC_ATTRIBUTES = [
"source_type",
"source",
"state_class",
"supported_color_modes",
"supported_features",
"swing_mode",
"swing_mode",
@@ -190,7 +190,6 @@ export const NON_NUMERIC_ATTRIBUTES = [
export const STATE_CONDITION_HIDDEN_ATTRIBUTES = [
"access_token",
"available_modes",
"color_modes",
"editable",
"effect_list",
"entity_picture",
@@ -207,6 +206,7 @@ export const STATE_CONDITION_HIDDEN_ATTRIBUTES = [
"sound_mode_list",
"source_list",
"state_class",
"supported_color_modes",
"swing_modes",
"token",
];
@@ -0,0 +1,4 @@
export enum CameraEntityFeature {
ON_OFF = 1,
STREAM = 2,
}
@@ -0,0 +1,12 @@
export enum ClimateEntityFeature {
TARGET_TEMPERATURE = 1,
TARGET_TEMPERATURE_RANGE = 2,
TARGET_HUMIDITY = 4,
FAN_MODE = 8,
PRESET_MODE = 16,
SWING_MODE = 32,
AUX_HEAT = 64,
TURN_OFF = 128,
TURN_ON = 256,
SWING_HORIZONTAL_MODE = 512,
}
+10
View File
@@ -0,0 +1,10 @@
export enum CoverEntityFeature {
OPEN = 1,
CLOSE = 2,
SET_POSITION = 4,
STOP = 8,
OPEN_TILT = 16,
CLOSE_TILT = 32,
STOP_TILT = 64,
SET_TILT_POSITION = 128,
}
@@ -0,0 +1,22 @@
export enum MediaPlayerEntityFeature {
PAUSE = 1,
SEEK = 2,
VOLUME_SET = 4,
VOLUME_MUTE = 8,
PREVIOUS_TRACK = 16,
NEXT_TRACK = 32,
TURN_ON = 128,
TURN_OFF = 256,
PLAY_MEDIA = 512,
VOLUME_STEP = 1024,
SELECT_SOURCE = 2048,
STOP = 4096,
CLEAR_PLAYLIST = 8192,
PLAY = 16384,
SHUFFLE_SET = 32768,
SELECT_SOUND_MODE = 65536,
BROWSE_MEDIA = 131072,
REPEAT_SET = 262144,
GROUPING = 524288,
}
+7
View File
@@ -0,0 +1,7 @@
export enum SirenEntityFeature {
TURN_ON = 1,
TURN_OFF = 2,
TONES = 4,
VOLUME_SET = 8,
DURATION = 16,
}
+8
View File
@@ -1,6 +1,11 @@
import type { Connection } from "home-assistant-js-websocket";
import type { ShortcutItem } from "./home_shortcuts";
export interface SurveyInteraction {
date: string;
action: "opened" | "dismissed";
}
export interface CoreFrontendUserData {
showEntityIdPicker?: boolean;
default_panel?: string;
@@ -16,6 +21,9 @@ export interface CoreFrontendSystemData {
default_panel?: string;
onboarded_version?: string;
onboarded_date?: string;
surveys?: {
onboarding?: SurveyInteraction;
};
}
export interface HomeFrontendSystemData {
+32 -3
View File
@@ -15,10 +15,26 @@ export interface HttpConfig {
ssl_profile?: "modern" | "intermediate";
}
// The slot the running HTTP server was actually started with.
export type ActiveConfigType = "stable" | "pending" | "default";
// A stored config slot carries metadata alongside the editable fields:
// - created_at: when the slot was staged
// - error: null while healthy; set once a slot could not be applied or a
// pending trial was not confirmed (then it is kept for display, not retried)
export interface HttpConfigWithMeta extends HttpConfig {
created_at?: string;
error?: string | null;
}
export interface HttpConfigState {
stable: HttpConfig;
pending: HttpConfig | null;
stable: HttpConfigWithMeta;
pending: HttpConfigWithMeta | null;
revert_at: string | null;
// Added in the "active HTTP config slot" backend change; optional so the
// frontend keeps working against cores without it.
active_config_type?: ActiveConfigType;
default?: HttpConfigWithMeta;
}
export const HTTP_CONFIG_FIELDS: (keyof HttpConfig)[] = [
@@ -40,6 +56,19 @@ export interface SaveHttpConfigResult {
restart: boolean;
}
// Keep only the editable fields; the backend storage schema rejects unknown
// keys, so the created_at/error metadata that rides along on a fetched slot
// must be dropped before configuring.
export const stripHttpConfigMeta = (config: HttpConfig): HttpConfig => {
const stripped: Partial<Record<keyof HttpConfig, unknown>> = {};
for (const key of HTTP_CONFIG_FIELDS) {
if (config[key] !== undefined) {
stripped[key] = config[key];
}
}
return stripped as HttpConfig;
};
export const fetchHttpConfig = (hass: HomeAssistant) =>
hass.callWS<HttpConfigState>({ type: "http/config" });
@@ -49,7 +78,7 @@ export const saveHttpConfig = (
) =>
hass.callWS<SaveHttpConfigResult>({
type: "http/config/configure",
config,
config: config ? stripHttpConfigMeta(config) : null,
});
export const promoteHttpConfig = (hass: HomeAssistant) =>
+3 -23
View File
@@ -40,6 +40,9 @@ import type { MediaPlayerItemId } from "../components/media-player/ha-media-play
import type { HomeAssistant, TranslationDict } from "../types";
import { UNAVAILABLE } from "./entity/entity";
import { isTTSMediaSource } from "./tts";
import { MediaPlayerEntityFeature } from "./feature/media-player_entity_feature";
export { MediaPlayerEntityFeature };
interface MediaPlayerEntityAttributes extends HassEntityAttributeBase {
media_content_id?: string;
@@ -82,29 +85,6 @@ export interface MediaPlayerEntity extends HassEntityBase {
| "buffering";
}
export enum MediaPlayerEntityFeature {
PAUSE = 1,
SEEK = 2,
VOLUME_SET = 4,
VOLUME_MUTE = 8,
PREVIOUS_TRACK = 16,
NEXT_TRACK = 32,
TURN_ON = 128,
TURN_OFF = 256,
PLAY_MEDIA = 512,
VOLUME_STEP = 1024,
SELECT_SOURCE = 2048,
STOP = 4096,
CLEAR_PLAYLIST = 8192,
PLAY = 16384,
SHUFFLE_SET = 32768,
SELECT_SOUND_MODE = 65536,
BROWSE_MEDIA = 131072,
REPEAT_SET = 262144,
GROUPING = 524288,
}
export type MediaPlayerBrowseAction = "pick" | "play";
export const BROWSER_PLAYER = "browser";
+14
View File
@@ -1,9 +1,23 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HomeAssistant } from "../types";
export interface NumberDeviceClassUnits {
units: string[];
}
const AUTO_MODE_MAX_STEPS = 256;
export const showNumberSlider = (stateObj: HassEntity): boolean => {
const { mode, min, max, step } = stateObj.attributes;
if (mode === "slider") {
return true;
}
return (
mode === "auto" &&
(Number(max) - Number(min)) / Number(step) <= AUTO_MODE_MAX_STEPS
);
};
export const getNumberDeviceClassConvertibleUnits = (
hass: HomeAssistant,
deviceClass: string
+1 -7
View File
@@ -1,7 +1 @@
export enum SirenEntityFeature {
TURN_ON = 1,
TURN_OFF = 2,
TONES = 4,
VOLUME_SET = 8,
DURATION = 16,
}
export { SirenEntityFeature } from "./feature/siren_entity_feature";
+2
View File
@@ -149,6 +149,7 @@ export const weatherAttrIcons = {
humidity: mdiWaterPercent,
wind_bearing: mdiWeatherWindy,
wind_speed: mdiWeatherWindy,
wind_gust_speed: mdiWeatherWindy,
pressure: mdiGauge,
temperature: mdiThermometer,
uv_index: mdiSunWireless,
@@ -268,6 +269,7 @@ export const getWeatherUnit = (
return (
stateObj.attributes.temperature_unit || config.unit_system.temperature
);
case "wind_gust_speed":
case "wind_speed":
return stateObj.attributes.wind_speed_unit || `${lengthUnit}/h`;
case "cloud_coverage":
@@ -21,6 +21,7 @@ import { isTiltOnly } from "../../../data/cover";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { ImageEntity } from "../../../data/image";
import { computeImageUrl } from "../../../data/image";
import { showNumberSlider } from "../../../data/number";
import "../../../panels/lovelace/components/hui-timestamp-display";
import type { HomeAssistant } from "../../../types";
import {
@@ -249,15 +250,9 @@ class EntityPreviewRow extends LitElement {
}
if (domain === "number") {
const showNumberSlider =
stateObj.attributes.mode === "slider" ||
(stateObj.attributes.mode === "auto" &&
(Number(stateObj.attributes.max) - Number(stateObj.attributes.min)) /
Number(stateObj.attributes.step) <=
256);
return html`
${
showNumberSlider
showNumberSlider(stateObj)
? html`
<div class="numberflex">
<ha-slider
+16 -6
View File
@@ -9,6 +9,7 @@ import { fireEvent } from "../../common/dom/fire_event";
import { isNavigationClick } from "../../common/dom/is-navigation-click";
import "../../components/ha-alert";
import { computeInitialHaFormData } from "../../components/ha-form/compute-initial-ha-form-data";
import { getHiddenFields } from "../../components/ha-form/conditions";
import "../../components/ha-form/ha-form";
import type {
HaFormSchema,
@@ -226,14 +227,17 @@ class StepFlowForm extends LitElement {
const checkAllRequiredFields = (
schema: readonly HaFormSchema[],
data: Record<string, any>
) =>
schema.every(
) => {
const hidden = getHiddenFields(schema, data);
return schema.every(
(field) =>
(!field.required || !["", undefined].includes(data[field.name])) &&
(field.type !== "expandable" ||
(!field.required && data[field.name] === undefined) ||
checkAllRequiredFields(field.schema, data[field.name]))
hidden.has(field.name) ||
((!field.required || !["", undefined].includes(data[field.name])) &&
(field.type !== "expandable" ||
(!field.required && data[field.name] === undefined) ||
checkAllRequiredFields(field.schema, data[field.name])))
);
};
const allRequiredInfoFilledIn =
stepData === undefined
@@ -255,8 +259,14 @@ class StepFlowForm extends LitElement {
const flowId = this.step.flow_id;
const hiddenFields = getHiddenFields(this.step.data_schema, stepData);
const toSendData: Record<string, unknown> = {};
Object.keys(stepData).forEach((key) => {
if (hiddenFields.has(key)) {
// Hidden fields are not part of the submitted config
return;
}
const value = stepData[key];
const isEmpty = [undefined, ""].includes(value);
const field = this.step.data_schema?.find((f) => f.name === key);
@@ -78,18 +78,21 @@ class MoreInfoLawnMower extends LitElement {
);
}
private get _startPauseIcon(): string {
if (!this.stateObj) return mdiPlay;
return isMowing(this.stateObj) &&
private get _showPause(): boolean {
if (!this.stateObj) return false;
return (
isMowing(this.stateObj) &&
supportsFeature(this.stateObj, LawnMowerEntityFeature.PAUSE)
? mdiPause
: mdiPlay;
);
}
private get _startPauseIcon(): string {
return this._showPause ? mdiPause : mdiPlay;
}
private get _startPauseLabel(): string {
if (!this.stateObj) return "";
return isMowing(this.stateObj) &&
supportsFeature(this.stateObj, LawnMowerEntityFeature.PAUSE)
return this._showPause
? this._i18n.localize("ui.dialogs.more_info_control.lawn_mower.pause")
: this._i18n.localize(
"ui.dialogs.more_info_control.lawn_mower.start_mowing"
@@ -99,8 +102,11 @@ class MoreInfoLawnMower extends LitElement {
private get _startPauseDisabled(): boolean {
if (!this.stateObj) return true;
if (this.stateObj.state === UNAVAILABLE) return true;
if (isMowing(this.stateObj)) return false;
return !canStartMowing(this.stateObj);
if (this._showPause) return false;
return (
!supportsFeature(this.stateObj, LawnMowerEntityFeature.START_MOWING) ||
!canStartMowing(this.stateObj)
);
}
private _renderBattery() {
@@ -156,7 +162,7 @@ class MoreInfoLawnMower extends LitElement {
private _handleStartPause() {
if (!this.stateObj) return;
forwardHaptic(this, "light");
if (isMowing(this.stateObj)) {
if (this._showPause) {
this._api.callService("lawn_mower", "pause", {
entity_id: this.stateObj.entity_id,
});
+56 -17
View File
@@ -1,4 +1,4 @@
import { mdiDevices } from "@mdi/js";
import { mdiCommentProcessingOutline, mdiDevices } from "@mdi/js";
import { consume } from "@lit/context";
import Fuse from "fuse.js";
import type { CSSResultGroup, PropertyValues } from "lit";
@@ -61,6 +61,7 @@ import { isIosApp } from "../../util/is_ios";
import { isMac } from "../../util/is_mac";
import { showConfirmationDialog } from "../generic/show-dialog-box";
import { showShortcutsDialog } from "../shortcuts/show-shortcuts-dialog";
import { showVoiceCommandDialog } from "../voice-command-dialog/show-ha-voice-command-dialog";
import {
effectiveQuickBarMode,
type QuickBarParams,
@@ -69,6 +70,18 @@ import {
const SEPARATOR = "________";
interface AssistComboBoxItem extends PickerComboBoxItem {
action: "assist";
assistPrompt: string;
}
type QuickBarComboBoxItem =
| NavigationComboBoxItem
| ActionCommandComboBoxItem
| EntityComboBoxItem
| DevicePickerItem
| AssistComboBoxItem;
@customElement("ha-quick-bar")
export class QuickBar extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -290,13 +303,7 @@ export class QuickBar extends LitElement {
`;
}
private _renderRow = (
item:
| NavigationComboBoxItem
| ActionCommandComboBoxItem
| EntityComboBoxItem
| DevicePickerItem
) => {
private _renderRow = (item: QuickBarComboBoxItem) => {
if (!item) {
return nothing;
}
@@ -412,8 +419,8 @@ export class QuickBar extends LitElement {
}: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
firstItem: QuickBarComboBoxItem | string;
secondItem: QuickBarComboBoxItem | string;
itemsCount: number;
}) => {
if (
@@ -461,7 +468,23 @@ export class QuickBar extends LitElement {
filter?: string,
section?: QuickBarSection
) => {
const items: (string | PickerComboBoxItem)[] = [];
const items: (string | QuickBarComboBoxItem)[] = [];
const prompt = filter?.trim();
const assistItem =
prompt &&
(!section || section === "command") &&
isComponentLoaded(this.hass.config, "conversation") &&
!this.hass.auth.external?.config.hasAssist
? ({
id: "ask-assist",
action: "assist",
primary: this.hass.localize("ui.dialogs.quick-bar.ask_assist", {
query: prompt,
}),
icon_path: mdiCommentProcessingOutline,
assistPrompt: prompt,
} satisfies AssistComboBoxItem)
: undefined;
if (!section || section === "navigate") {
let navigateItems = this._generateNavigationCommandsMemoized(
@@ -486,10 +509,12 @@ export class QuickBar extends LitElement {
items.push(...navigateItems);
}
if (this.hass.user?.is_admin && (!section || section === "command")) {
let commandItems = this._generateActionCommandsMemoized(this.hass).sort(
this._sortBySortingLabel
);
if (!section || section === "command") {
let commandItems = this.hass.user?.is_admin
? this._generateActionCommandsMemoized(this.hass).sort(
this._sortBySortingLabel
)
: [];
if (filter) {
commandItems = this._filterGroup(
@@ -499,12 +524,15 @@ export class QuickBar extends LitElement {
) as ActionCommandComboBoxItem[];
}
if (!section && commandItems.length) {
if (!section && (commandItems.length || assistItem)) {
// show group title
items.push(this.hass.localize("ui.dialogs.quick-bar.commands_title"));
}
items.push(...commandItems);
if (assistItem) {
items.push(assistItem);
}
}
if (!section || section === "entity") {
@@ -723,10 +751,21 @@ export class QuickBar extends LitElement {
const { index, newTab } = ev.detail;
const item = this._comboBox.virtualizerElement.items[
index
] as PickerComboBoxItem;
] as QuickBarComboBoxItem;
this._itemSelected = true;
if (item && "assistPrompt" in item) {
this.closeDialog();
showVoiceCommandDialog(this, this.hass, {
pipeline_id: "last_used",
start_listening: false,
prompt: item.assistPrompt,
submit: true,
});
return;
}
// entity selected
if (item && "stateObj" in item) {
this.closeDialog();
@@ -58,9 +58,11 @@ export class HaVoiceCommandDialog extends LitElement {
private _startListening = false;
public async showDialog(
params: Required<VoiceCommandDialogParams>
): Promise<void> {
private _prompt?: string;
private _submitPrompt = false;
public async showDialog(params: VoiceCommandDialogParams): Promise<void> {
await this._loadPipelines();
const pipelinesIds = this._pipelines?.map((pipeline) => pipeline.id) || [];
if (
@@ -77,7 +79,9 @@ export class HaVoiceCommandDialog extends LitElement {
this._pipelineId = this._preferredPipeline;
}
this._startListening = params.start_listening;
this._startListening = params.start_listening ?? false;
this._prompt = params.prompt;
this._submitPrompt = params.submit ?? false;
this._dialogOpen = true;
this._open = true;
}
@@ -189,6 +193,8 @@ export class HaVoiceCommandDialog extends LitElement {
.hass=${this.hass}
.pipeline=${this._pipeline}
.startListening=${this._startListening}
.initialPrompt=${this._prompt}
.submitInitialPrompt=${this._submitPrompt}
>
</ha-assist-chat>
`
@@ -6,6 +6,8 @@ const loadVoiceCommandDialog = () => import("./ha-voice-command-dialog");
export interface VoiceCommandDialogParams {
pipeline_id: "last_used" | "preferred" | string;
start_listening?: boolean;
prompt?: string;
submit?: boolean;
}
export const showVoiceCommandDialog = (
@@ -31,6 +33,8 @@ export const showVoiceCommandDialog = (
pipeline_id: dialogParams.pipeline_id,
// Don't start listening by default for web
start_listening: dialogParams.start_listening ?? false,
prompt: dialogParams.prompt,
submit: dialogParams.submit ?? false,
},
});
};
+2 -1
View File
@@ -124,7 +124,7 @@ interface EMOutgoingMessageConnectionStatus extends EMMessage {
}
interface EMOutgoingMessageFrontendLoaded extends EMMessage {
type: "frontend/loaded"; // Fired once the launch screen is removed (connected and essential data loaded)
type: "frontend/loaded"; // Fired once the launch screen is removed; with hasSplashscreen this is after the first panel has rendered
}
interface EMOutgoingMessageAppConfiguration extends EMMessage {
@@ -371,6 +371,7 @@ export interface ExternalConfig {
appVersion?: string;
hasEntityAddTo?: boolean; // Supports "Add to" from more-info dialog, with action coming from external app
hasAssistSettings?: boolean; // Shows the "This device" section in voice assistant settings
hasSplashscreen?: boolean; // App covers the frontend with its own loading screen until frontend/loaded, so the launch screen is removed without animation
}
export interface ExternalEntityAddToAction {
+28 -2
View File
@@ -20,6 +20,7 @@ import {
removeLaunchScreen,
renderLaunchScreenInfoBox,
} from "../util/launch-screen";
import { checkOnboardingSurveyToast } from "../util/onboarding-survey";
import {
registerServiceWorker,
supportsServiceWorker,
@@ -59,6 +60,8 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
private _httpPendingDialogOpen = false;
private _onboardingSurveyChecked = false;
private _panelUrl: string;
@storage({ key: "ha-version", state: false, subscribe: false })
@@ -108,6 +111,17 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
) {
this.checkHttpPendingConfig();
}
if (
changedProps.has("hass") &&
!this._onboardingSurveyChecked &&
this.hass?.user &&
this.hass.systemData
) {
this._onboardingSurveyChecked = true;
if (!__DEMO__) {
checkOnboardingSurveyToast(this, this.hass);
}
}
}
protected update(changedProps: PropertyValues<this>) {
@@ -119,7 +133,12 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
) {
this.render = this.renderHass;
this.update = super.update;
removeLaunchScreen();
// Apps with a native splash screen keep covering the frontend until
// frontend/loaded, so the launch screen stays up (invisibly) until the
// first panel has rendered and partial-panel-resolver removes it.
if (!this.hass.auth.external?.config.hasSplashscreen) {
removeLaunchScreen();
}
this.hass.auth.external?.fireMessage({ type: "frontend/loaded" });
}
super.update(changedProps);
@@ -250,7 +269,14 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
// The check re-runs on the next reconnect; ignore transient failures.
return;
}
if (!httpConfig.pending || this._httpPendingDialogOpen) {
// Only prompt for an active trial. A pending config with an error was
// already reverted/failed and is kept only for display in the config form,
// so it must not pop the confirm/revert dialog.
if (
!httpConfig.pending ||
httpConfig.pending.error ||
this._httpPendingDialogOpen
) {
return;
}
this._httpPendingDialogOpen = true;
+2 -1
View File
@@ -220,7 +220,8 @@ class PartialPanelResolver extends HassRouterPage {
) {
await this.rebuild();
await this.pageRendered;
removeLaunchScreen();
removeLaunchScreen(!!this.hass.auth.external?.config.hasSplashscreen);
this.hass.auth.external?.fireMessage({ type: "frontend/loaded" });
}
}
}
+5 -1
View File
@@ -15,6 +15,7 @@ export interface ShowToastParams {
message:
string | { translationKey: LocalizeKeys; args?: Record<string, string> };
action?: ToastActionParams;
dismiss?: () => void;
duration?: number;
dismissable?: boolean;
bottomOffset?: number;
@@ -71,7 +72,10 @@ class NotificationManager extends LitElement {
this._toast?.show();
}
private _toastClosed(_ev: HASSDomEvent<ToastClosedEventDetail>) {
private _toastClosed(ev: HASSDomEvent<ToastClosedEventDetail>) {
if (ev.detail.reason === "dismiss") {
this._parameters?.dismiss?.();
}
this._parameters = undefined;
}
@@ -95,7 +95,7 @@ import { showMoreInfoDialog } from "../../../../../dialogs/more-info/show-ha-mor
import { MobileAwareMixin } from "../../../../../mixins/mobile-aware-mixin";
import { mdiHomeAssistant } from "../../../../../resources/home-assistant-logo-svg";
import { haStyle } from "../../../../../resources/styles";
import type { Route } from "../../../../../types";
import type { HomeAssistantRegistries, Route } from "../../../../../types";
import { bytesToString } from "../../../../../util/bytes-to-string";
import { getAppDisplayName } from "../../common/app";
import "../../components/supervisor-apps-state";
@@ -172,10 +172,20 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
public connectedCallback() {
super.connectedCallback();
this._computeUpdateEntityId();
this._startPolling();
}
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Registries load asynchronously and change over time; resolve the update
// entity reactively instead of only once on connect.
this._updateEntityId = this._findUpdateEntityId(
this.registries.devices,
this.registries.entities,
(this._currentAddon as HassioAddonDetails).slug
);
}
public disconnectedCallback() {
super.disconnectedCallback();
this._stopPolling();
@@ -1500,26 +1510,24 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
"system_managed" in addon && addon.system_managed
);
private _computeUpdateEntityId() {
const addon = this._currentAddon as HassioAddonDetails;
const device = Object.values(this.registries.devices).find((d) =>
d.identifiers.some(
([domain, id]) => domain === "hassio" && id === addon.slug
)
);
if (!device) {
return;
private _findUpdateEntityId = memoizeOne(
(
devices: HomeAssistantRegistries["devices"],
entities: HomeAssistantRegistries["entities"],
slug: string
): string | undefined => {
const device = Object.values(devices).find((d) =>
d.identifiers.some(([domain, id]) => domain === "hassio" && id === slug)
);
if (!device) {
return undefined;
}
return Object.values(entities).find(
(e) =>
e.device_id === device.id && computeDomain(e.entity_id) === "update"
)?.entity_id;
}
const updateEntity = Object.values(this.registries.entities).find(
(e) =>
e.device_id === device.id && computeDomain(e.entity_id) === "update"
);
if (!updateEntity) {
return;
}
this._updateEntityId = updateEntity.entity_id;
}
);
private _openUpdate() {
showMoreInfoDialog(this, { entityId: this._updateEntityId! });
@@ -30,7 +30,6 @@ const SCHEMA = [
"code_arm_required",
"code_format",
"color_mode",
"color_modes",
"current_activity",
"device_class",
"editable",
@@ -80,7 +80,6 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
"available_modes",
"code_arm_required",
"code_format",
"color_modes",
"device_class",
"editable",
"effect_list",
@@ -145,6 +145,10 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
public connectedCallback() {
super.connectedCallback();
// Re-apply the type filter from the URL when the page is (re)displayed,
// e.g. when navigating back to a cached instance of this page with a
// different `type` query param.
this._setFiltersFromUrl();
window.addEventListener("location-changed", this._locationChanged);
window.addEventListener("popstate", this._popState);
}
@@ -19,7 +19,11 @@ import {
HTTP_CONFIG_FIELDS,
saveHttpConfig,
} from "../../../data/http";
import type { HttpConfig } from "../../../data/http";
import type {
ActiveConfigType,
HttpConfig,
HttpConfigWithMeta,
} from "../../../data/http";
import { showConfirmationDialog } from "../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../resources/styles";
import type { HomeAssistant } from "../../../types";
@@ -161,6 +165,11 @@ class HaConfigHttpForm extends LitElement {
@state() private _showNoChanges = false;
@state() private _activeConfigType?: ActiveConfigType;
// A pending config that was reverted/failed and kept only for display.
@state() private _revertedPending?: HttpConfigWithMeta;
@query("ha-form") private _form?: HaForm;
@query("ha-alert") private _firstAlert?: HTMLElement;
@@ -201,6 +210,40 @@ class HaConfigHttpForm extends LitElement {
<p class="description">
${this.hass.localize("ui.panel.config.network.http.description")}
</p>
${
this._activeConfigType === "default"
? html`
<ha-alert alert-type="warning">
${this.hass.localize(
"ui.panel.config.network.http.running_default"
)}
</ha-alert>
`
: nothing
}
${
this._revertedPending
? html`
<ha-alert alert-type="warning">
${
this._revertedPending.error === "not_promoted"
? this.hass.localize(
"ui.panel.config.network.http.reverted_not_confirmed"
)
: this.hass.localize(
"ui.panel.config.network.http.reverted_failed",
{ error: this._revertedPending.error ?? "" }
)
}
<ha-button slot="action" @click=${this._reviewReverted}>
${this.hass.localize(
"ui.panel.config.network.http.reverted_action"
)}
</ha-button>
</ha-alert>
`
: nothing
}
${
portChanged
? html`
@@ -266,16 +309,30 @@ class HaConfigHttpForm extends LitElement {
private async _fetchConfig(): Promise<void> {
try {
// Pending is exclusively handled by the global confirm/revert dialog, so
// the form only ever displays stable.
const { stable } = await fetchHttpConfig(this.hass);
const { stable, pending, active_config_type } = await fetchHttpConfig(
this.hass
);
this._stable = stable;
this._config = { ...stable };
this._activeConfigType = active_config_type;
// An active trial pending (no error) is handled by the global
// confirm/revert dialog. A pending carrying an error was reverted or
// failed to apply and is kept only so we can surface it here.
this._revertedPending = pending?.error ? pending : undefined;
} catch (err: any) {
this._error = err.message;
}
}
private _reviewReverted(): void {
if (!this._revertedPending) {
return;
}
// Load the reverted values into the form so the user can fix and re-save.
this._config = { ...this._revertedPending };
this._revertedPending = undefined;
}
private _computeLabel = (
schema: SchemaUnion<ReturnType<typeof SCHEMA>>
): string => {
@@ -16,7 +16,11 @@ import "../../../components/ha-svg-icon";
import { apiContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { LawnMowerEntity } from "../../../data/lawn_mower";
import { LawnMowerEntityFeature, canDock } from "../../../data/lawn_mower";
import {
LawnMowerEntityFeature,
canDock,
canStartMowing,
} from "../../../data/lawn_mower";
import type { HomeAssistant, HomeAssistantApi } from "../../../types";
import type { LovelaceCardFeature, LovelaceCardFeatureEditor } from "../types";
import { cardFeatureStyles } from "./common/card-feature-styles";
@@ -72,6 +76,9 @@ export const LAWN_MOWER_COMMANDS_BUTTONS: Record<
translationKey: "start",
icon: mdiPlay,
serviceName: "start_mowing",
disabled:
!supportsFeature(stateObj, LawnMowerEntityFeature.START_MOWING) ||
!canStartMowing(stateObj),
};
},
dock: (stateObj) => ({
@@ -34,6 +34,8 @@ export const supportsTrendGraphCardFeature = (
export const DEFAULT_HOURS_TO_SHOW = 24;
const HOUR = 60 * 60 * 1000;
@customElement("hui-trend-graph-card-feature")
class HuiHistoryChartCardFeature
extends LitElement
@@ -93,9 +95,13 @@ class HuiHistoryChartCardFeature
public connectedCallback() {
super.connectedCallback();
// redraw the graph every minute to update the time axis
// recompute the graph every minute so the x-axis (and the horizontal fill
// to now) keeps advancing even while the sensor value stays constant
clearInterval(this._interval);
this._interval = window.setInterval(() => this.requestUpdate(), 1000 * 60);
this._interval = window.setInterval(
() => this._calculateCoordinates(),
1000 * 60
);
if (this.hasUpdated) {
this._subscribeHistory();
}
@@ -146,12 +152,18 @@ class HuiHistoryChartCardFeature
? Math.max(10, width / 5, hourToShow)
: Math.max(10, hourToShow);
const useMean = !detail;
// Anchor the x-axis to the full time window so a constant value is drawn as
// a horizontal line up to now, instead of ending at the last state change.
const now = Date.now();
const { points, yAxisOrigin } = coordinatesMinimalResponseCompressedState(
this._stateHistory,
width,
height,
maxDetails,
undefined,
{
minX: now - hourToShow * HOUR,
maxX: now,
},
useMean
);
this._coordinates = points;
@@ -36,6 +36,30 @@ const MEASUREMENT_VARIANTS: Variant[] = [
},
];
const MEASUREMENT_ANGLE_VARIANTS: Variant[] = [
{
labelKey: "last_24h",
days_to_show: 1,
period: "hour",
chart_type: "line",
stat_types: ["mean"],
},
{
labelKey: "last_7d",
days_to_show: 7,
period: "day",
chart_type: "line",
stat_types: ["mean"],
},
{
labelKey: "last_30d",
days_to_show: 30,
period: "day",
chart_type: "line",
stat_types: ["mean"],
},
];
const TOTAL_VARIANTS: Variant[] = [
{
labelKey: "last_7d",
@@ -60,6 +84,13 @@ const TOTAL_VARIANTS: Variant[] = [
},
];
const VARIANTS_BY_STATE_CLASS: Record<string, Variant[]> = {
measurement: MEASUREMENT_VARIANTS,
measurement_angle: MEASUREMENT_ANGLE_VARIANTS,
total: TOTAL_VARIANTS,
total_increasing: TOTAL_VARIANTS,
};
export const statisticsGraphCardSuggestions: CardSuggestionProvider<StatisticsGraphCardConfig> =
{
getEntitySuggestion(hass, entityId) {
@@ -67,8 +98,8 @@ export const statisticsGraphCardSuggestions: CardSuggestionProvider<StatisticsGr
const stateObj = hass.states[entityId];
const stateClass = stateObj?.attributes.state_class;
if (!stateClass) return null;
const variants =
stateClass === "measurement" ? MEASUREMENT_VARIANTS : TOTAL_VARIANTS;
const variants = VARIANTS_BY_STATE_CLASS[stateClass];
if (!variants) return null;
const suggestions: CardSuggestion<StatisticsGraphCardConfig>[] =
variants.map((v) => ({
label: hass.localize(`${LABEL_PREFIX}${v.labelKey}` as any),
@@ -0,0 +1,473 @@
import { fireEvent } from "../../../../../common/dom/fire_event";
import { getGraphColorByIndex } from "../../../../../common/color/colors";
import { getEntityContext } from "../../../../../common/entity/context/get_entity_context";
import type {
Link,
Node,
} from "../../../../../components/chart/ha-sankey-chart";
import type { DeviceConsumptionEnergyPreference } from "../../../../../data/energy";
import type { HomeAssistant } from "../../../../../types";
// Devices below this fraction of the home total are grouped into an "Other" node
export const MIN_SANKEY_THRESHOLD_FACTOR = 0.001; // 0.1% of home total
// While the graph is assembled, device nodes carry an ad-hoc `parent` field
// that is not part of the chart's Node interface. The chart ignores it.
export type SankeyDeviceNode = Node & { parent?: string };
interface SmallConsumer {
id: string;
name: string | undefined;
value: number;
effectiveParent: string | undefined;
idx: number;
}
const OTHER_LABEL_KEY =
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.other";
const UNTRACKED_LABEL_KEY =
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.untracked_consumption";
/** Open more-info for a clicked sankey node that maps to an entity. */
export const fireSankeyNodeMoreInfo = (el: HTMLElement, node: Node): void => {
if (node.entityId) {
fireEvent(el, "hass-more-info", { entityId: node.entityId });
}
};
export interface BuildSankeyDeviceNodesOptions {
devices: DeviceConsumptionEnergyPreference[];
computedStyle: CSSStyleDeclaration;
localize: HomeAssistant["localize"];
/** Node small consumers and untracked flow attach to (usually "home"). */
rootNodeId: string;
/** Flows below this value are grouped into an "Other" node. */
minThreshold: number;
/** Per-parent untracked residual only shown when above this value. */
untrackedFloor: number;
/** Round the "Other" node value up (instantaneous cards only). */
ceilOtherValue: boolean;
/** Starting untracked total (the home/root value). */
initialUntracked: number;
getId: (device: DeviceConsumptionEnergyPreference) => string | undefined;
getValue: (id: string) => number;
getLabel: (id: string, name: string | undefined) => string;
getEntityId: (id: string) => string | undefined;
findEffectiveParent: (
includedInStat: string | undefined
) => string | undefined;
}
/**
* Build the device layer of a sankey card: one node per device, small devices
* folded into per-parent "Other" nodes, and per-parent untracked residuals.
* Value/label/id/entityId are supplied via callbacks so both cumulative
* (statistic growth) and instantaneous (live power/flow) cards can share it.
*/
export const buildSankeyDeviceNodes = (
options: BuildSankeyDeviceNodesOptions
): {
deviceNodes: SankeyDeviceNode[];
parentLinks: Record<string, string>;
links: Link[];
untrackedConsumption: number;
} => {
const {
devices,
computedStyle,
localize,
rootNodeId,
minThreshold,
untrackedFloor,
ceilOtherValue,
initialUntracked,
getId,
getValue,
getLabel,
getEntityId,
findEffectiveParent,
} = options;
const unavailableColor = computedStyle
.getPropertyValue("--state-unavailable-color")
.trim();
const links: Link[] = [];
const deviceNodes: SankeyDeviceNode[] = [];
const parentLinks: Record<string, string> = {};
const smallConsumersByParent = new Map<string, SmallConsumer[]>();
let untrackedConsumption = initialUntracked;
devices.forEach((device, idx) => {
const id = getId(device);
// Falsy check (not `=== undefined`) mirrors the cards' original `!stat_rate` guard.
if (!id) {
return;
}
const value = getValue(id);
const effectiveParent = findEffectiveParent(device.included_in_stat);
if (value < minThreshold) {
// Collect small consumers instead of folding them into untracked
const parentKey = effectiveParent ?? rootNodeId;
if (!smallConsumersByParent.has(parentKey)) {
smallConsumersByParent.set(parentKey, []);
}
smallConsumersByParent.get(parentKey)!.push({
id,
name: device.name,
value,
effectiveParent,
idx,
});
return;
}
const node: SankeyDeviceNode = {
id,
label: getLabel(id, device.name),
value,
color: getGraphColorByIndex(idx, computedStyle),
index: 4,
parent: effectiveParent,
entityId: getEntityId(id),
};
if (node.parent) {
parentLinks[node.id] = node.parent;
links.push({ source: node.parent, target: node.id });
} else {
untrackedConsumption -= value;
}
deviceNodes.push(node);
});
// Process small consumers - show a lone one directly, group clusters as "Other"
smallConsumersByParent.forEach((consumers, parentKey) => {
const totalValue = consumers.reduce((sum, c) => sum + c.value, 0);
if (totalValue <= 0) {
return;
}
if (consumers.length === 1) {
const consumer = consumers[0];
const node: SankeyDeviceNode = {
id: consumer.id,
label: getLabel(consumer.id, consumer.name),
value: consumer.value,
color: getGraphColorByIndex(consumer.idx, computedStyle),
index: 4,
parent: consumer.effectiveParent,
entityId: getEntityId(consumer.id),
};
if (node.parent) {
parentLinks[node.id] = node.parent;
links.push({ source: node.parent, target: node.id });
} else {
untrackedConsumption -= consumer.value;
}
deviceNodes.push(node);
} else {
const otherNodeId = `other_${parentKey}`;
const otherNode: SankeyDeviceNode = {
id: otherNodeId,
label: localize(OTHER_LABEL_KEY),
value: ceilOtherValue ? Math.ceil(totalValue) : totalValue,
color: unavailableColor,
index: 4,
};
if (parentKey !== rootNodeId) {
parentLinks[otherNodeId] = parentKey;
links.push({ source: parentKey, target: otherNodeId });
} else {
untrackedConsumption -= totalValue;
}
deviceNodes.push(otherNode);
}
});
// Add untracked consumption nodes for parent devices whose sub-devices
// don't account for the parent's full consumption
const parentDeviceIds = new Set(Object.values(parentLinks));
parentDeviceIds.forEach((parentId) => {
const parentNode = deviceNodes.find((node) => node.id === parentId);
if (!parentNode) {
return;
}
const childrenSum = deviceNodes.reduce(
(sum, node) =>
parentLinks[node.id] === parentId ? sum + node.value : sum,
0
);
const untracked = parentNode.value - childrenSum;
if (untracked > untrackedFloor) {
const untrackedNodeId = `untracked_${parentId}`;
deviceNodes.push({
id: untrackedNodeId,
label: localize(UNTRACKED_LABEL_KEY),
value: untracked,
color: unavailableColor,
index: 4,
});
parentLinks[untrackedNodeId] = parentId;
links.push({
source: parentId,
target: untrackedNodeId,
value: untracked,
});
}
});
return { deviceNodes, parentLinks, links, untrackedConsumption };
};
/** Bucket device nodes by their entity's area and floor. */
export const groupSankeyDevicesByFloorAndArea = (
hass: HomeAssistant,
deviceNodes: Node[]
): {
areas: Record<string, { value: number; devices: Node[] }>;
floors: Record<string, { value: number; areas: string[] }>;
} => {
const areas: Record<string, { value: number; devices: Node[] }> = {
no_area: {
value: 0,
devices: [],
},
};
const floors: Record<string, { value: number; areas: string[] }> = {
no_floor: {
value: 0,
areas: ["no_area"],
},
};
deviceNodes.forEach((deviceNode) => {
const entity = hass.states[deviceNode.id];
const { area, floor } = entity
? getEntityContext(
entity,
hass.entities,
hass.devices,
hass.areas,
hass.floors
)
: { area: null, floor: null };
if (area) {
if (area.area_id in areas) {
areas[area.area_id].value += deviceNode.value;
areas[area.area_id].devices.push(deviceNode);
} else {
areas[area.area_id] = {
value: deviceNode.value,
devices: [deviceNode],
};
}
// see if the area has a floor
if (floor) {
if (floor.floor_id in floors) {
floors[floor.floor_id].value += deviceNode.value;
if (!floors[floor.floor_id].areas.includes(area.area_id)) {
floors[floor.floor_id].areas.push(area.area_id);
}
} else {
floors[floor.floor_id] = {
value: deviceNode.value,
areas: [area.area_id],
};
}
} else {
floors.no_floor.value += deviceNode.value;
if (!floors.no_floor.areas.includes(area.area_id)) {
floors.no_floor.areas.unshift(area.area_id);
}
}
} else {
areas.no_area.value += deviceNode.value;
areas.no_area.devices.push(deviceNode);
}
});
return { areas, floors };
};
/**
* Organize device nodes into hierarchical sections based on parent-child
* relationships (top-level parents first, then their children, recursively).
*/
export const getSankeyDeviceSections = (
parentLinks: Record<string, string>,
deviceNodes: Node[]
): Node[][] => {
const parentSection: Node[] = [];
const childSection: Node[] = [];
const parentIds = Object.values(parentLinks);
const remainingLinks: Record<string, string> = {};
deviceNodes.forEach((deviceNode) => {
const isChild = deviceNode.id in parentLinks;
const isParent = parentIds.includes(deviceNode.id);
if (isParent && !isChild) {
// Top-level parents (have children but no parents themselves)
parentSection.push(deviceNode);
} else {
childSection.push(deviceNode);
}
});
// Filter out links where parent is already in current parent section
Object.entries(parentLinks).forEach(([child, parent]) => {
if (!parentSection.some((node) => node.id === parent)) {
remainingLinks[child] = parent;
}
});
if (parentSection.length > 0) {
// Recursively process child section with remaining links
return [
parentSection,
...getSankeyDeviceSections(remainingLinks, childSection),
];
}
// Base case: no more parent-child relationships to process
return [deviceNodes];
};
export interface BuildSankeyLayoutOptions {
hass: HomeAssistant;
computedStyle: CSSStyleDeclaration;
localize: HomeAssistant["localize"];
deviceNodes: SankeyDeviceNode[];
parentLinks: Record<string, string>;
rootNodeId: string;
groupByFloor: boolean;
groupByArea: boolean;
untrackedConsumption: number;
untrackedFloor: number;
}
/**
* Build the floor/area grouping layer, emit the device section nodes with
* their final section indices, and add the top-level untracked node.
*/
export const buildSankeyLayout = (
options: BuildSankeyLayoutOptions
): { nodes: Node[]; links: Link[] } => {
const {
hass,
computedStyle,
localize,
deviceNodes,
parentLinks,
rootNodeId,
groupByFloor,
groupByArea,
untrackedConsumption,
untrackedFloor,
} = options;
const nodes: Node[] = [];
const links: Link[] = [];
const primaryColor = computedStyle.getPropertyValue("--primary-color").trim();
const devicesWithoutParent = deviceNodes.filter(
(node) => !parentLinks[node.id]
);
if (groupByArea || groupByFloor) {
const { areas, floors } = groupSankeyDevicesByFloorAndArea(
hass,
devicesWithoutParent
);
Object.keys(floors)
.sort(
(a, b) =>
(hass.floors[b]?.level ?? -Infinity) -
(hass.floors[a]?.level ?? -Infinity)
)
.forEach((floorId) => {
let floorNodeId = `floor_${floorId}`;
if (floorId === "no_floor" || !groupByFloor) {
// link "no_floor" areas to the root
floorNodeId = rootNodeId;
} else {
nodes.push({
id: floorNodeId,
label: hass.floors[floorId].name,
value: floors[floorId].value,
index: 2,
color: primaryColor,
});
links.push({
source: rootNodeId,
target: floorNodeId,
});
}
floors[floorId].areas.forEach((areaId) => {
let targetNodeId: string;
if (areaId === "no_area" || !groupByArea) {
// If group_by_area is false, link devices to floor or root
targetNodeId = floorNodeId;
} else {
// Create area node and link it to floor
const areaNodeId = `area_${areaId}`;
nodes.push({
id: areaNodeId,
label: hass.areas[areaId]?.name || areaId,
value: areas[areaId].value,
index: 3,
color: primaryColor,
});
links.push({
source: floorNodeId,
target: areaNodeId,
value: areas[areaId].value,
});
targetNodeId = areaNodeId;
}
// Link devices to the appropriate target (area, floor, or root)
areas[areaId].devices.forEach((device) => {
links.push({
source: targetNodeId,
target: device.id,
value: device.value,
});
});
});
});
} else {
devicesWithoutParent.forEach((deviceNode) => {
links.push({
source: rootNodeId,
target: deviceNode.id,
value: deviceNode.value,
});
});
}
const deviceSections = getSankeyDeviceSections(parentLinks, deviceNodes);
deviceSections.forEach((section, index) => {
section.forEach((node: Node) => {
nodes.push({ ...node, index: 4 + index });
});
});
// untracked consumption
if (untrackedConsumption > untrackedFloor) {
nodes.push({
id: "untracked",
label: localize(UNTRACKED_LABEL_KEY),
value: untrackedConsumption,
color: computedStyle.getPropertyValue("--state-unavailable-color").trim(),
index: 3 + deviceSections.length,
});
links.push({
source: rootNodeId,
target: "untracked",
value: untrackedConsumption,
});
}
return { nodes, links };
};
@@ -521,7 +521,7 @@ export function generateEnergyDevicesDetailGraphData(
true,
generateFillBuckets(datasets, start, end, getSuggestedPeriod(start, end))
);
const yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax);
const yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax, true);
return {
chartData: datasets,
@@ -119,7 +119,7 @@ export function generateEnergyGasGraphData(
true,
generateFillBuckets(datasets, start, end, period)
);
const yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax);
const yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax, true);
const chartData = datasets;
const total = processTotal(energyData.stats, gasSources);
@@ -146,7 +146,7 @@ export function generateEnergySolarGraphData(
end,
compareStart,
compareEnd,
yAxisFractionDigits: computeYAxisFractionDigits(yMin, yMax),
yAxisFractionDigits: computeYAxisFractionDigits(yMin, yMax, true),
};
}
@@ -5,7 +5,6 @@ import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import "../../../../components/ha-card";
import "../../../../components/ha-svg-icon";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { EnergyData } from "../../../../data/energy";
import {
computeConsumptionData,
@@ -25,10 +24,14 @@ import type { LovelaceCard, LovelaceGridOptions } from "../../types";
import type { EnergySankeyCardConfig } from "../types";
import "../../../../components/chart/ha-sankey-chart";
import type { Link, Node } from "../../../../components/chart/ha-sankey-chart";
import { getGraphColorByIndex } from "../../../../common/color/colors";
import { formatNumber } from "../../../../common/number/format_number";
import { getEntityContext } from "../../../../common/entity/context/get_entity_context";
import { MobileAwareMixin } from "../../../../mixins/mobile-aware-mixin";
import {
buildSankeyDeviceNodes,
buildSankeyLayout,
fireSankeyNodeMoreInfo,
MIN_SANKEY_THRESHOLD_FACTOR,
} from "./common/sankey";
const DEFAULT_CONFIG: Partial<EnergySankeyCardConfig> = {
group_by_floor: true,
@@ -138,6 +141,8 @@ class HuiEnergySankeyCard
};
nodes.push(homeNode);
const minEnergyThreshold = homeNode.value * MIN_SANKEY_THRESHOLD_FACTOR;
if (types.battery) {
const totalBatteryOut = summedData.total.from_battery ?? 0;
const totalBatteryIn = summedData.total.to_battery ?? 0;
@@ -262,185 +267,85 @@ class HuiEnergySankeyCard
}
}
let untrackedConsumption = homeNode.value;
const deviceNodes: Node[] = [];
const parentLinks: Record<string, string> = {};
prefs.device_consumption.forEach((device, idx) => {
const value =
device.stat_consumption in this._data!.stats
? calculateStatisticSumGrowth(
this._data!.stats[device.stat_consumption]
) || 0
: 0;
if (value < 0.01) {
return;
const deviceValue = (statConsumption: string) =>
statConsumption in this._data!.stats
? calculateStatisticSumGrowth(this._data!.stats[statConsumption]) || 0
: 0;
// Set of device stats that will be rendered as their own node
const renderedStats = new Set<string>();
prefs.device_consumption.forEach((device) => {
if (deviceValue(device.stat_consumption) >= minEnergyThreshold) {
renderedStats.add(device.stat_consumption);
}
const node = {
id: device.stat_consumption,
label:
device.name ||
getStatisticLabel(
this.hass,
device.stat_consumption,
this._data!.statsMetadata[device.stat_consumption]
),
value,
color: getGraphColorByIndex(idx, computedStyle),
index: 4,
parent: device.included_in_stat,
entityId: isExternalStatistic(device.stat_consumption)
? undefined
: device.stat_consumption,
};
if (node.parent) {
parentLinks[node.id] = node.parent;
links.push({
source: node.parent,
target: node.id,
});
} else {
untrackedConsumption -= value;
}
deviceNodes.push(node);
});
// Add untracked consumption nodes for parent devices whose sub-devices
// don't account for the parent's full consumption
const parentDeviceIds = new Set(Object.values(parentLinks));
parentDeviceIds.forEach((parentId) => {
const parentNode = deviceNodes.find((node) => node.id === parentId);
if (!parentNode) {
return;
// Walk up the included_in_stat chain to the first ancestor that is rendered
const deviceMap = new Map<string, string | undefined>();
prefs.device_consumption.forEach((device) => {
deviceMap.set(device.stat_consumption, device.included_in_stat);
});
const findEffectiveParent = (
includedInStat: string | undefined
): string | undefined => {
let currentParent = includedInStat;
while (currentParent) {
if (renderedStats.has(currentParent)) {
return currentParent;
}
if (!deviceMap.has(currentParent)) {
return undefined;
}
currentParent = deviceMap.get(currentParent);
}
const childrenSum = deviceNodes.reduce(
(sum, node) =>
parentLinks[node.id] === parentId ? sum + node.value : sum,
0
return undefined;
};
const deviceLabel = (statConsumption: string, name?: string) =>
name ||
getStatisticLabel(
this.hass,
statConsumption,
this._data!.statsMetadata[statConsumption]
);
const untracked = parentNode.value - childrenSum;
if (untracked > 0) {
const untrackedNodeId = `untracked_${parentId}`;
deviceNodes.push({
id: untrackedNodeId,
label: this.hass.localize(
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.untracked_consumption"
),
value: untracked,
color: computedStyle
.getPropertyValue("--state-unavailable-color")
.trim(),
index: 4,
});
parentLinks[untrackedNodeId] = parentId;
links.push({
source: parentId,
target: untrackedNodeId,
value: untracked,
});
}
});
const devicesWithoutParent = deviceNodes.filter(
(node) => !parentLinks[node.id]
);
const {
deviceNodes,
parentLinks,
links: deviceLinks,
untrackedConsumption,
} = buildSankeyDeviceNodes({
devices: prefs.device_consumption,
computedStyle,
localize: this.hass.localize,
rootNodeId: "home",
minThreshold: minEnergyThreshold,
untrackedFloor: 0,
ceilOtherValue: false,
initialUntracked: homeNode.value,
getId: (device) => device.stat_consumption,
getValue: deviceValue,
getLabel: deviceLabel,
getEntityId: (id) => (isExternalStatistic(id) ? undefined : id),
findEffectiveParent,
});
links.push(...deviceLinks);
const { group_by_area, group_by_floor } = this._config;
if (group_by_area || group_by_floor) {
const { areas, floors } = this._groupByFloorAndArea(devicesWithoutParent);
Object.keys(floors)
.sort(
(a, b) =>
(this.hass.floors[b]?.level ?? -Infinity) -
(this.hass.floors[a]?.level ?? -Infinity)
)
.forEach((floorId) => {
let floorNodeId = `floor_${floorId}`;
if (floorId === "no_floor" || !group_by_floor) {
// link "no_floor" areas to home
floorNodeId = "home";
} else {
nodes.push({
id: floorNodeId,
label: this.hass.floors[floorId].name,
value: floors[floorId].value,
index: 2,
color: computedStyle.getPropertyValue("--primary-color").trim(),
});
links.push({
source: "home",
target: floorNodeId,
});
}
floors[floorId].areas.forEach((areaId) => {
let targetNodeId: string;
if (areaId === "no_area" || !group_by_area) {
// If group_by_area is false, link devices to floor or home
targetNodeId = floorNodeId;
} else {
// Create area node and link it to floor
const areaNodeId = `area_${areaId}`;
nodes.push({
id: areaNodeId,
label: this.hass.areas[areaId]!.name,
value: areas[areaId].value,
index: 3,
color: computedStyle.getPropertyValue("--primary-color").trim(),
});
links.push({
source: floorNodeId,
target: areaNodeId,
value: areas[areaId].value,
});
targetNodeId = areaNodeId;
}
// Link devices to the appropriate target (area, floor, or home)
areas[areaId].devices.forEach((device) => {
links.push({
source: targetNodeId,
target: device.id,
value: device.value,
});
});
});
});
} else {
devicesWithoutParent.forEach((deviceNode) => {
links.push({
source: "home",
target: deviceNode.id,
value: deviceNode.value,
});
});
}
const deviceSections = this._getDeviceSections(parentLinks, deviceNodes);
deviceSections.forEach((section, index) => {
section.forEach((node: Node) => {
nodes.push({ ...node, index: 4 + index });
});
const layout = buildSankeyLayout({
hass: this.hass,
computedStyle,
localize: this.hass.localize,
deviceNodes,
parentLinks,
rootNodeId: "home",
groupByFloor: !!group_by_floor,
groupByArea: !!group_by_area,
untrackedConsumption,
untrackedFloor: 0,
});
// untracked consumption
if (untrackedConsumption > 0) {
nodes.push({
id: "untracked",
label: this.hass.localize(
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.untracked_consumption"
),
value: untrackedConsumption,
color: computedStyle
.getPropertyValue("--state-unavailable-color")
.trim(),
index: 3 + deviceSections.length,
});
links.push({
source: "home",
target: "untracked",
value: untrackedConsumption,
});
}
nodes.push(...layout.nodes);
links.push(...layout.links);
const hasData = nodes.some((node) => node.value > 0);
@@ -480,113 +385,7 @@ class HuiEnergySankeyCard
`${formatNumber(value, this.hass.locale, value < 0.1 ? { maximumFractionDigits: 3 } : undefined)} kWh`;
private _handleNodeClick(ev: CustomEvent<{ node: Node }>) {
const { node } = ev.detail;
if (node.entityId) {
fireEvent(this, "hass-more-info", { entityId: node.entityId });
}
}
protected _groupByFloorAndArea(deviceNodes: Node[]) {
const areas: Record<string, { value: number; devices: Node[] }> = {
no_area: {
value: 0,
devices: [],
},
};
const floors: Record<string, { value: number; areas: string[] }> = {
no_floor: {
value: 0,
areas: ["no_area"],
},
};
deviceNodes.forEach((deviceNode) => {
const entity = this.hass.states[deviceNode.id];
const { area, floor } = entity
? getEntityContext(
entity,
this.hass.entities,
this.hass.devices,
this.hass.areas,
this.hass.floors
)
: { area: null, floor: null };
if (area) {
if (area.area_id in areas) {
areas[area.area_id].value += deviceNode.value;
areas[area.area_id].devices.push(deviceNode);
} else {
areas[area.area_id] = {
value: deviceNode.value,
devices: [deviceNode],
};
}
// see if the area has a floor
if (floor) {
if (floor.floor_id in floors) {
floors[floor.floor_id].value += deviceNode.value;
if (!floors[floor.floor_id].areas.includes(area.area_id)) {
floors[floor.floor_id].areas.push(area.area_id);
}
} else {
floors[floor.floor_id] = {
value: deviceNode.value,
areas: [area.area_id],
};
}
} else {
floors.no_floor.value += deviceNode.value;
if (!floors.no_floor.areas.includes(area.area_id)) {
floors.no_floor.areas.unshift(area.area_id);
}
}
} else {
areas.no_area.value += deviceNode.value;
areas.no_area.devices.push(deviceNode);
}
});
return { areas, floors };
}
/**
* Organizes device nodes into hierarchical sections based on parent-child relationships.
*/
protected _getDeviceSections(
parentLinks: Record<string, string>,
deviceNodes: Node[]
): Node[][] {
const parentSection: Node[] = [];
const childSection: Node[] = [];
const parentIds = Object.values(parentLinks);
const remainingLinks: typeof parentLinks = {};
deviceNodes.forEach((deviceNode) => {
const isChild = deviceNode.id in parentLinks;
const isParent = parentIds.includes(deviceNode.id);
if (isParent && !isChild) {
// Top-level parents (have children but no parents themselves)
parentSection.push(deviceNode);
} else {
childSection.push(deviceNode);
}
});
// Filter out links where parent is already in current parent section
Object.entries(parentLinks).forEach(([child, parent]) => {
if (!parentSection.some((node) => node.id === parent)) {
remainingLinks[child] = parent;
}
});
if (parentSection.length > 0) {
// Recursively process child section with remaining links
return [
parentSection,
...this._getDeviceSections(remainingLinks, childSection),
];
}
// Base case: no more parent-child relationships to process
return [deviceNodes];
fireSankeyNodeMoreInfo(this, ev.detail.node);
}
static styles = css`
@@ -59,6 +59,8 @@ const stackOrder = {
to_grid: 2,
used_solar: 3,
used_battery: 4,
from_grid: 5,
used_grid: 5,
};
@customElement("hui-energy-usage-graph-card")
@@ -295,6 +297,15 @@ export class HuiEnergyUsageGraphCard
to_battery: {},
};
// Grid sources can be import-only or export-only; assign color indices by
// position in the user's grid sources config so this card matches the
// energy sources table, which uses positional indices.
const colorIndices: Record<string, Record<string, number>> = {};
Object.keys(colorPropertyMap).forEach((key) => {
colorIndices[key] = {};
});
let gridIdx = 0;
for (const source of energyData.prefs.energy_sources) {
if (source.type === "solar") {
if (statIds.solar) {
@@ -333,6 +344,7 @@ export class HuiEnergyUsageGraphCard
} else {
statIds.from_grid = [gridSource.stat_energy_from];
}
colorIndices.from_grid[gridSource.stat_energy_from] = gridIdx;
if (gridSource.name) {
statLabels.from_grid[gridSource.stat_energy_from] =
gridSource.stat_energy_to
@@ -349,6 +361,7 @@ export class HuiEnergyUsageGraphCard
} else {
statIds.to_grid = [gridSource.stat_energy_to];
}
colorIndices.to_grid[gridSource.stat_energy_to] = gridIdx;
if (gridSource.name) {
statLabels.to_grid[gridSource.stat_energy_to] =
gridSource.stat_energy_from
@@ -359,17 +372,18 @@ export class HuiEnergyUsageGraphCard
: gridSource.name;
}
}
gridIdx++;
}
const computedStyles = getComputedStyle(this);
const colorIndices: Record<string, Record<string, number>> = {};
Object.keys(colorPropertyMap).forEach((key) => {
colorIndices[key] = {};
if (
key === "used_grid" ||
key === "used_solar" ||
key === "used_battery"
key === "used_battery" ||
key === "from_grid" ||
key === "to_grid"
) {
return;
}
@@ -461,7 +475,7 @@ export class HuiEnergyUsageGraphCard
getSuggestedPeriod(this._start, this._end)
)
);
this._yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax);
this._yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax, true);
this._chartData = datasets;
this._legendData = this._getLegendData(datasets);
this._total = this._processTotal(consumption);
@@ -274,7 +274,7 @@ export class HuiEnergyWaterGraphCard
getSuggestedPeriod(this._start, this._end)
)
);
this._yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax);
this._yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax, true);
this._chartData = datasets;
this._total = this._processTotal(energyData.stats, waterSources);
}
@@ -5,7 +5,6 @@ import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import "../../../../components/ha-card";
import "../../../../components/ha-svg-icon";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { EnergyData, EnergyPreferences } from "../../../../data/energy";
import {
formatPowerShort,
@@ -19,19 +18,19 @@ import type { LovelaceCard, LovelaceGridOptions } from "../../types";
import type { PowerSankeyCardConfig } from "../types";
import "../../../../components/chart/ha-sankey-chart";
import type { Link, Node } from "../../../../components/chart/ha-sankey-chart";
import { getGraphColorByIndex } from "../../../../common/color/colors";
import { getEntityContext } from "../../../../common/entity/context/get_entity_context";
import { MobileAwareMixin } from "../../../../mixins/mobile-aware-mixin";
import {
buildSankeyDeviceNodes,
buildSankeyLayout,
fireSankeyNodeMoreInfo,
MIN_SANKEY_THRESHOLD_FACTOR,
} from "./common/sankey";
const DEFAULT_CONFIG: Partial<PowerSankeyCardConfig> = {
group_by_floor: true,
group_by_area: true,
};
// Minimum power threshold as a fraction of total consumption to display a device node
// Devices below this threshold will be grouped into an "Other" node
const MIN_POWER_THRESHOLD_FACTOR = 0.001; // 0.1% of used_total
interface PowerData {
solar: number;
from_grid: number;
@@ -48,14 +47,6 @@ interface PowerData {
used_total: number;
}
interface SmallConsumer {
statRate: string;
name: string | undefined;
value: number;
effectiveParent: string | undefined;
idx: number;
}
@customElement("hui-power-sankey-card")
class HuiPowerSankeyCard
extends SubscribeMixin(MobileAwareMixin(LitElement))
@@ -163,7 +154,8 @@ class HuiPowerSankeyCard
const computedStyle = getComputedStyle(this);
// Calculate dynamic threshold based on total consumption
const minPowerThreshold = powerData.used_total * MIN_POWER_THRESHOLD_FACTOR;
const minPowerThreshold =
powerData.used_total * MIN_SANKEY_THRESHOLD_FACTOR;
const nodes: Node[] = [];
const links: Link[] = [];
@@ -286,10 +278,6 @@ class HuiPowerSankeyCard
}
}
let untrackedConsumption = homeNode.value;
const deviceNodes: Node[] = [];
const parentLinks: Record<string, string> = {};
// Build a map of device relationships for hierarchy resolution
// Key: stat_consumption (energy), Value: { stat_rate, included_in_stat }
const deviceMap = new Map<
@@ -338,252 +326,43 @@ class HuiPowerSankeyCard
return undefined;
};
// Collect small consumers by their effective parent
const smallConsumersByParent = new Map<string, SmallConsumer[]>();
prefs.device_consumption.forEach((device, idx) => {
if (!device.stat_rate) {
return;
}
const value = this._getCurrentPower(device.stat_rate);
// Find the effective parent (may be different from direct parent if parent has no stat_rate)
const effectiveParent = findEffectiveParent(device.included_in_stat);
if (value < minPowerThreshold) {
// Collect small consumers instead of skipping them
const parentKey = effectiveParent ?? "home";
if (!smallConsumersByParent.has(parentKey)) {
smallConsumersByParent.set(parentKey, []);
}
smallConsumersByParent.get(parentKey)!.push({
statRate: device.stat_rate,
name: device.name,
value,
effectiveParent,
idx,
});
return;
}
const node = {
id: device.stat_rate,
label: device.name || this._getEntityLabel(device.stat_rate),
value,
color: getGraphColorByIndex(idx, computedStyle),
index: 4,
parent: effectiveParent,
entityId: device.stat_rate,
};
if (node.parent) {
parentLinks[node.id] = node.parent;
links.push({
source: node.parent,
target: node.id,
});
} else {
untrackedConsumption -= value;
}
deviceNodes.push(node);
const {
deviceNodes,
parentLinks,
links: deviceLinks,
untrackedConsumption,
} = buildSankeyDeviceNodes({
devices: prefs.device_consumption,
computedStyle,
localize: this.hass.localize,
rootNodeId: "home",
minThreshold: minPowerThreshold,
untrackedFloor: 1,
ceilOtherValue: true,
initialUntracked: homeNode.value,
getId: (device) => device.stat_rate,
getValue: (id) => this._getCurrentPower(id),
getLabel: (id, name) => name || this._getEntityLabel(id),
getEntityId: (id) => id,
findEffectiveParent,
});
// Process small consumers - create "Other" nodes or show single entities
smallConsumersByParent.forEach((consumers, parentKey) => {
const totalValue = consumers.reduce((sum, c) => sum + c.value, 0);
if (totalValue <= 0) {
return;
}
if (consumers.length === 1) {
// Single entity - show it directly instead of grouping
const consumer = consumers[0];
const node = {
id: consumer.statRate,
label: consumer.name || this._getEntityLabel(consumer.statRate),
value: consumer.value,
color: getGraphColorByIndex(consumer.idx, computedStyle),
index: 4,
parent: consumer.effectiveParent,
entityId: consumer.statRate,
};
if (node.parent) {
parentLinks[node.id] = node.parent;
links.push({
source: node.parent,
target: node.id,
});
} else {
untrackedConsumption -= consumer.value;
}
deviceNodes.push(node);
} else {
// Multiple entities - create "Other" group
const otherNodeId = `other_${parentKey}`;
const otherNode: Node = {
id: otherNodeId,
label: this.hass.localize(
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.other"
),
value: Math.ceil(totalValue),
color: computedStyle
.getPropertyValue("--state-unavailable-color")
.trim(),
index: 4,
};
if (parentKey !== "home") {
// Has a parent device
parentLinks[otherNodeId] = parentKey;
links.push({
source: parentKey,
target: otherNodeId,
});
} else {
// Top-level "Other" - will be linked to home/floor/area later
untrackedConsumption -= totalValue;
}
deviceNodes.push(otherNode);
}
});
// Add untracked consumption nodes for parent devices whose sub-devices
// don't account for the parent's full power
const parentDeviceIds = new Set(Object.values(parentLinks));
parentDeviceIds.forEach((parentId) => {
const parentNode = deviceNodes.find((node) => node.id === parentId);
if (!parentNode) {
return;
}
const childrenSum = deviceNodes.reduce(
(sum, node) =>
parentLinks[node.id] === parentId ? sum + node.value : sum,
0
);
const untracked = parentNode.value - childrenSum;
// only show if larger than 1W
if (untracked > 1) {
const untrackedNodeId = `untracked_${parentId}`;
deviceNodes.push({
id: untrackedNodeId,
label: this.hass.localize(
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.untracked_consumption"
),
value: untracked,
color: computedStyle
.getPropertyValue("--state-unavailable-color")
.trim(),
index: 4,
});
parentLinks[untrackedNodeId] = parentId;
links.push({
source: parentId,
target: untrackedNodeId,
value: untracked,
});
}
});
const devicesWithoutParent = deviceNodes.filter(
(node) => !parentLinks[node.id]
);
links.push(...deviceLinks);
const { group_by_area, group_by_floor } = this._config;
if (group_by_area || group_by_floor) {
const { areas, floors } = this._groupByFloorAndArea(devicesWithoutParent);
Object.keys(floors)
.sort(
(a, b) =>
(this.hass.floors[b]?.level ?? -Infinity) -
(this.hass.floors[a]?.level ?? -Infinity)
)
.forEach((floorId) => {
let floorNodeId = `floor_${floorId}`;
if (floorId === "no_floor" || !group_by_floor) {
// link "no_floor" areas to home
floorNodeId = "home";
} else {
nodes.push({
id: floorNodeId,
label: this.hass.floors[floorId].name,
value: floors[floorId].value,
index: 2,
color: computedStyle.getPropertyValue("--primary-color").trim(),
});
links.push({
source: "home",
target: floorNodeId,
});
}
floors[floorId].areas.forEach((areaId) => {
let targetNodeId: string;
if (areaId === "no_area" || !group_by_area) {
// If group_by_area is false, link devices to floor or home
targetNodeId = floorNodeId;
} else {
// Create area node and link it to floor
const areaNodeId = `area_${areaId}`;
nodes.push({
id: areaNodeId,
label: this.hass.areas[areaId]?.name || areaId,
value: areas[areaId].value,
index: 3,
color: computedStyle.getPropertyValue("--primary-color").trim(),
});
links.push({
source: floorNodeId,
target: areaNodeId,
value: areas[areaId].value,
});
targetNodeId = areaNodeId;
}
// Link devices to the appropriate target (area, floor, or home)
areas[areaId].devices.forEach((device) => {
links.push({
source: targetNodeId,
target: device.id,
value: device.value,
});
});
});
});
} else {
devicesWithoutParent.forEach((deviceNode) => {
links.push({
source: "home",
target: deviceNode.id,
value: deviceNode.value,
});
});
}
const deviceSections = this._getDeviceSections(parentLinks, deviceNodes);
deviceSections.forEach((section, index) => {
section.forEach((node: Node) => {
nodes.push({ ...node, index: 4 + index });
});
const layout = buildSankeyLayout({
hass: this.hass,
computedStyle,
localize: this.hass.localize,
deviceNodes,
parentLinks,
rootNodeId: "home",
groupByFloor: !!group_by_floor,
groupByArea: !!group_by_area,
untrackedConsumption,
untrackedFloor: 1,
});
// untracked consumption (only show if larger than 1W)
if (untrackedConsumption > 1) {
nodes.push({
id: "untracked",
label: this.hass.localize(
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.untracked_consumption"
),
value: untrackedConsumption,
color: computedStyle
.getPropertyValue("--state-unavailable-color")
.trim(),
index: 3 + deviceSections.length,
});
links.push({
source: "home",
target: "untracked",
value: untrackedConsumption,
});
}
nodes.push(...layout.nodes);
links.push(...layout.links);
const hasData = nodes.some((node) => node.value > 0);
@@ -623,10 +402,7 @@ class HuiPowerSankeyCard
formatPowerShort(this.hass, value);
private _handleNodeClick(ev: CustomEvent<{ node: Node }>) {
const { node } = ev.detail;
if (node.entityId) {
fireEvent(this, "hass-more-info", { entityId: node.entityId });
}
fireSankeyNodeMoreInfo(this, ev.detail.node);
}
/**
@@ -758,109 +534,6 @@ class HuiPowerSankeyCard
};
}
protected _groupByFloorAndArea(deviceNodes: Node[]) {
const areas: Record<string, { value: number; devices: Node[] }> = {
no_area: {
value: 0,
devices: [],
},
};
const floors: Record<string, { value: number; areas: string[] }> = {
no_floor: {
value: 0,
areas: ["no_area"],
},
};
deviceNodes.forEach((deviceNode) => {
const entity = this.hass.states[deviceNode.id];
const { area, floor } = entity
? getEntityContext(
entity,
this.hass.entities,
this.hass.devices,
this.hass.areas,
this.hass.floors
)
: { area: null, floor: null };
if (area) {
if (area.area_id in areas) {
areas[area.area_id].value += deviceNode.value;
areas[area.area_id].devices.push(deviceNode);
} else {
areas[area.area_id] = {
value: deviceNode.value,
devices: [deviceNode],
};
}
// see if the area has a floor
if (floor) {
if (floor.floor_id in floors) {
floors[floor.floor_id].value += deviceNode.value;
if (!floors[floor.floor_id].areas.includes(area.area_id)) {
floors[floor.floor_id].areas.push(area.area_id);
}
} else {
floors[floor.floor_id] = {
value: deviceNode.value,
areas: [area.area_id],
};
}
} else {
floors.no_floor.value += deviceNode.value;
if (!floors.no_floor.areas.includes(area.area_id)) {
floors.no_floor.areas.unshift(area.area_id);
}
}
} else {
areas.no_area.value += deviceNode.value;
areas.no_area.devices.push(deviceNode);
}
});
return { areas, floors };
}
/**
* Organizes device nodes into hierarchical sections based on parent-child relationships.
*/
protected _getDeviceSections(
parentLinks: Record<string, string>,
deviceNodes: Node[]
): Node[][] {
const parentSection: Node[] = [];
const childSection: Node[] = [];
const parentIds = Object.values(parentLinks);
const remainingLinks: typeof parentLinks = {};
deviceNodes.forEach((deviceNode) => {
const isChild = deviceNode.id in parentLinks;
const isParent = parentIds.includes(deviceNode.id);
if (isParent && !isChild) {
// Top-level parents (have children but no parents themselves)
parentSection.push(deviceNode);
} else {
childSection.push(deviceNode);
}
});
// Filter out links where parent is already in current parent section
Object.entries(parentLinks).forEach(([child, parent]) => {
if (!parentSection.some((node) => node.id === parent)) {
remainingLinks[child] = parent;
}
});
if (parentSection.length > 0) {
// Recursively process child section with remaining links
return [
parentSection,
...this._getDeviceSections(remainingLinks, childSection),
];
}
// Base case: no more parent-child relationships to process
return [deviceNodes];
}
/**
* Get current power value from entity state, normalized to watts (W)
* @param entityId - The entity ID to get power value from
@@ -261,7 +261,7 @@ export function generatePowerSourcesGraphData(
const end = energyData.end || endOfToday();
const chartData = fillLineGaps(datasets);
const yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax);
const yAxisFractionDigits = computeYAxisFractionDigits(yMin, yMax, true);
const usageData: NonNullable<LineSeriesOption["data"]> = [];
// fillLineGaps ensures all datasets share the same x values, so iterate the
+14 -13
View File
@@ -8,6 +8,7 @@ import "../../../components/ha-card";
import type { HomeAssistant } from "../../../types";
import { computeCardSize } from "../common/compute-card-size";
import { findEntities } from "../common/find-entities";
import { applyDefaultColor } from "../common/entity-color-config";
import { processConfigEntities } from "../common/process-config-entities";
import "../components/hui-entities-toggle";
import { createHeaderFooterElement } from "../create-element/create-header-footer-element";
@@ -24,7 +25,7 @@ import type {
LovelaceHeaderFooter,
} from "../types";
import { migrateEntitiesCardConfig } from "./migrate-card-config";
import type { EntitiesCardConfig } from "./types";
import type { EntitiesCardConfig, EntitiesCardEntityConfig } from "./types";
import { haStyleScrollbar } from "../../../resources/styles";
export const computeShowHeaderToggle = <
@@ -159,7 +160,7 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
const migratedConfig = migrateEntitiesCardConfig(config);
const entities = processConfigEntities(migratedConfig.entities);
this._config = migratedConfig;
this._config = { color: "state", ...migratedConfig };
this._configEntities = entities;
this._showHeaderToggle = computeShowHeaderToggle(migratedConfig, entities);
if (this._config.header) {
@@ -343,18 +344,18 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
`,
];
private _renderEntity(entityConf: LovelaceRowConfig): TemplateResult {
const element = createRowElement(
(!("type" in entityConf) || entityConf.type === "conditional") &&
"state_color" in this._config!
? ({
state_color: this._config.state_color,
...(entityConf as EntityConfig),
} as EntityConfig)
: entityConf.type === "perform-action"
? { ...entityConf, type: "call-service" }
: entityConf
private _rowConfig(entityConf: LovelaceRowConfig): LovelaceRowConfig {
if (entityConf.type === "perform-action") {
return { ...entityConf, type: "call-service" };
}
return applyDefaultColor(
entityConf as EntitiesCardEntityConfig,
this._config!.color
);
}
private _renderEntity(entityConf: LovelaceRowConfig): TemplateResult {
const element = createRowElement(this._rowConfig(entityConf));
if (this._hass) {
element.hass = this._hass;
}
+12 -8
View File
@@ -26,6 +26,7 @@ import { findEntities } from "../common/find-entities";
import { handleAction } from "../common/handle-action";
import { hasAction, hasAnyAction } from "../common/has-action";
import { hasConfigOrEntitiesChanged } from "../common/has-changed";
import { applyDefaultColor } from "../common/entity-color-config";
import { processConfigEntities } from "../common/process-config-entities";
import "../components/hui-timestamp-display";
import { createEntityNotFoundWarning } from "../components/hui-warning";
@@ -87,14 +88,19 @@ export class HuiGlanceCard extends LitElement implements LovelaceCard {
show_name: true,
show_state: true,
show_icon: true,
state_color: true,
color: "state",
...migratedConfig,
};
const cardColor = this._config.color;
const entities = processConfigEntities(migratedConfig.entities).map(
(entityConf) => ({
hold_action: { action: "more-info" } as MoreInfoActionConfig,
...entityConf,
})
(entityConf) =>
applyDefaultColor(
{
hold_action: { action: "more-info" } as MoreInfoActionConfig,
...entityConf,
},
cardColor
)
);
for (const entity of entities) {
@@ -294,9 +300,7 @@ export class HuiGlanceCard extends LitElement implements LovelaceCard {
.stateObj=${stateObj}
.overrideIcon=${entityConf.icon}
.overrideImage=${entityConf.image}
.stateColor=${
entityConf.state_color ?? this._config!.state_color
}
.color=${entityConf.color}
></state-badge>
`
: ""
@@ -14,6 +14,7 @@ import { forwardHaptic } from "../../../data/haptics";
import type { HomeAssistant } from "../../../types";
import type { LovelaceCard, LovelaceGridOptions } from "../types";
import type { ToggleGroupCardConfig } from "./types";
import { getToggleAction } from "../../../common/entity/get_toggle_action";
@customElement("hui-toggle-group-card")
export class HuiToggleGroupCard extends LitElement implements LovelaceCard {
@@ -95,12 +96,7 @@ export class HuiToggleGroupCard extends LitElement implements LovelaceCard {
const onEntities = this._getOnEntities();
const domain = computeDomain(this._config.entities[0]);
let service: string;
if (domain === "cover") {
service = onEntities.length > 0 ? "close_cover" : "open_cover";
} else {
service = onEntities.length > 0 ? "turn_off" : "turn_on";
}
const service = getToggleAction(domain, onEntities.length === 0);
this.hass.callService(domain, service, {
entity_id: this._config.entities,
@@ -1,40 +1,56 @@
import type { EntityConfig, LovelaceRowConfig } from "../entity-rows/types";
import { migrateStateColorConfig } from "../common/entity-color-config";
import { migrateTimeFormatConfig } from "../common/entity-time-format-config";
import type {
ConditionalRowConfig,
LovelaceRowConfig,
} from "../entity-rows/types";
import type {
EntitiesCardConfig,
EntitiesCardEntityConfig,
GlanceCardConfig,
GlanceConfigEntity,
} from "./types";
const migrateEntitiesRowConfig = (
rowConf: LovelaceRowConfig | string
): LovelaceRowConfig | string => {
if (typeof rowConf !== "object") {
return rowConf;
}
let newConf: LovelaceRowConfig = rowConf;
newConf = migrateTimeFormatConfig(newConf as EntitiesCardEntityConfig);
newConf = migrateStateColorConfig(newConf as EntitiesCardEntityConfig);
if (newConf.type === "conditional") {
const row = (newConf as ConditionalRowConfig).row;
if (row && typeof row === "object") {
let newRow = migrateTimeFormatConfig(row as EntitiesCardEntityConfig);
newRow = migrateStateColorConfig(newRow);
if (newRow !== row) {
newConf = { ...newConf, row: newRow } as ConditionalRowConfig;
}
}
}
return newConf;
};
export const migrateEntitiesCardConfig = (
config: EntitiesCardConfig
): EntitiesCardConfig => {
let changed = false;
const newEntities = config.entities?.map((e) => {
if (typeof e !== "object") {
return e;
const newConf = migrateEntitiesRowConfig(e);
if (newConf !== e) {
changed = true;
}
// Custom rows own their config schema and may use `format` with a
// different meaning (e.g. custom:multiple-entity-row), so leave it
// untouched.
if (e.type?.startsWith("custom:")) {
return e;
}
if (!("format" in e)) {
return e;
}
changed = true;
const { format, ...rest } = e;
return {
...rest,
time_format: (rest as EntityConfig).time_format ?? format,
};
return newConf;
});
const newConfig = migrateStateColorConfig(config);
if (!changed) {
return config;
return newConfig;
}
return {
...config,
entities: newEntities as (LovelaceRowConfig | string)[],
...newConfig,
entities: newEntities,
};
};
@@ -46,21 +62,20 @@ export const migrateGlanceCardConfig = (
if (typeof e !== "object") {
return e;
}
if (!("format" in e)) {
return e;
let newConf = e;
newConf = migrateTimeFormatConfig(newConf);
newConf = migrateStateColorConfig(newConf);
if (newConf !== e) {
changed = true;
}
changed = true;
const { format, ...rest } = e;
return {
...rest,
time_format: rest.time_format ?? format,
};
return newConf;
});
const newConfig = migrateStateColorConfig(config);
if (!changed) {
return config;
return newConfig;
}
return {
...config,
...newConfig,
entities: newEntities as (GlanceConfigEntity | string)[],
};
};

Some files were not shown because too many files have changed in this diff Show More