Compare commits

..

51 Commits

Author SHA1 Message Date
Simon Lamon
8535ee0694 Merge branch 'dev' into sec_pypi_publishing 2025-11-13 06:58:30 +01:00
Paulus Schoutsen
a6ee670682 Fix bad minification (#27926) 2025-11-12 23:29:58 -05:00
Wendelin
c457f92826 Upgrade WA to 3.0.0 (#27919) 2025-11-12 17:39:56 +01:00
karwosts
c73bd96a1f Fix fields without selectors (#27917) 2025-11-12 17:26:48 +02:00
Wendelin
711f8e2fc3 Fix ha-dropdown and add shadow tokens (#27916)
* Fix dropdown select handle in refresh tokens

* Use semantic shadows for dropdown

* Fix token names
2025-11-12 16:52:05 +02:00
Aidan Timson
91a0066544 Add dashboard time visibility condition (#27790)
* Add time-based conditional visibility for cards

* Move clearTimeout outside of scheduleUpdate

* Add time string validation

* Add time string validation

* Remove runtime validation as config shouldnt allow bad values

* Fix for midnight crossing

* Cap timeout to 32-bit signed integer

* Add listener tests

* Additional tests

* Format
2025-11-12 15:55:59 +02:00
Aidan Timson
aee7b8b8d4 Setup base animation styles, add fade out to launch screen (#27829)
* Setup base animation styles

* Add fade out to launch screen

* Cleanup

* Set opacity before removing element

* Remove

* Final

* Use computed duration for timeout

* Add skip animation prop

* Swap

* Use common function and fix issue
2025-11-12 11:54:53 +02:00
Aidan Timson
d38d770e1a Refactor ConditionalListenerMixin and extract shared utilities (#27858)
* Refactor ConditionalListenerMixin and extract shared utilities

* Remove

* Use proper type

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>

* Import

* Fix typing

* Docstrings

* Use generic types and refactor visibility handling

* Fix function signature and handle other keys separately

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2025-11-12 09:50:38 +00:00
Petar Petrov
0036679553 Fix target picker displaying blank (#27910) 2025-11-12 09:49:37 +01:00
Simon Lamon
2b85108242 Introduce ha-dropdown (#27417)
Co-authored-by: Wendelin <12148533+wendevlin@users.noreply.github.com>
Co-authored-by: Wendelin <w@pe8.at>
2025-11-12 09:23:31 +01:00
Petar Petrov
c74320cb82 Add power configuration to Energy dashboard (#27373)
Co-authored-by: Norbert Rittel <norbert@rittel.de>
Co-authored-by: Aidan Timson <aidan@timmo.dev>
2025-11-12 09:21:52 +01:00
renovate[bot]
8ebe6e24d2 Update dependency marked to v17 (#27885)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-12 09:24:17 +02:00
Paul Bottein
d3182da587 Create dedicated panel for home dashboard (#27861)
* Create dedicated panel for home dashboard

* Don't use state if only one view

* Prettier

* Use hui-root

* Add alert for edit mode

* Remove no edit

* Add home panel to dashboard list
2025-11-12 09:09:46 +02:00
Petar Petrov
41fbc5e44b Increase ZHA reconfiguration dialog width for details view (#27909) 2025-11-11 20:07:10 +01:00
Tobias Bieniek
3fea41eb0e Add scenes category to home dashboard area views (#27712)
This is similar to the "Automations" category that was added in 52eb3d8, but for "Scenes" this time. It is positioned after the other summary sections.
2025-11-11 11:19:02 +02:00
ildar170975
9a627bdea7 Data tables: remove unneeded "direction: asc" lines (#27903)
* remove unneeded "direction: asc"

* remove unneeded "direction: asc"

* remove unneeded "direction: asc"
2025-11-11 08:14:03 +02:00
Norbert Rittel
d9a67f603d Fix grammar in new_automation_setup_failed_text (#27898)
* Fix grammar in `new_automation_setup_failed_text`

* Remove excessive comma
2025-11-10 18:48:26 +01:00
Wendelin
5f37f8c0ab Use generic picker for target-picker (#27850)
Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2025-11-10 17:15:16 +01:00
Petar Petrov
f222702abf Fix entity name in statistics chart (#27896) 2025-11-10 15:08:33 +01:00
Copilot
2107b7c267 Fix doubled tooltips on timeline charts for mobile devices (#27888)
* Initial plan

* Fix doubled date popups in timeline charts on mobile

Co-authored-by: MindFreeze <5219205+MindFreeze@users.noreply.github.com>

* Add comment explaining triggerTooltip fix

* Actual fix

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: MindFreeze <5219205+MindFreeze@users.noreply.github.com>
Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2025-11-10 14:31:30 +01:00
Petar Petrov
1c05afebd7 Smooth sensor card more when "Show more detail" is disabled (#27891)
* Smooth sensor card more when "Show more detail" is disabled

* Set minimum sample points to 10
2025-11-10 14:23:26 +01:00
Paul Bottein
7179bb2d26 Assume default visible true for panels (#27894) 2025-11-10 15:04:14 +02:00
Wendelin
95cf1fdcf7 Fix target picker for entity_id: none (#27893)
Fix notFound condition to exclude 'none' in ha-target-picker-item-row
2025-11-10 12:23:16 +00:00
renovate[bot]
9617956cc6 Update vitest monorepo to v4.0.8 (#27892)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-10 14:15:36 +02:00
karwosts
65df464731 Fix entity editor with non-existant entity (#27875) 2025-11-10 14:09:44 +02:00
Wendelin
bd4e9a3d05 Use ha-ripple in ha-md-list-item (#27889) 2025-11-10 14:04:30 +02:00
ildar170975
963fc13a99 relative_time: increase thresholds (#27870)
* increase thresholds

* restored for days & hours
2025-11-10 12:58:13 +02:00
renovate[bot]
ff614918d4 Update vaadinWebComponents monorepo to v24.9.5 (#27884)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-10 12:55:03 +02:00
ildar170975
48aa5fb970 hui-generic-entity-row: add tooltips for relative-time (#27871)
* add tooltips for relative-rime

* lint

* fix import

* prettier

* move a call of uid() to a private property

* some test change
2025-11-10 12:54:26 +02:00
ildar170975
190af65756 Display tooltips for labels (#27613)
* add a description fo ha-label

* add a description fo ha-label

* add a description fo ha-label

* add a description fo ha-label

* add a description fo ha-label

* add a description fo ha-label

* add a description fo ha-label

* add a description for ha-label

* add ha-tooltip for ha-input-chip

* add ha-tooltip

* replace() -> replaceAll()

* replace() -> replaceAll()

* prettier

* fix styles to enlarge an "active tooltip area"

* additional check for null for "description"

* simplify a check for description

* simplify a check for description

* simplify a check for description

* simplify a check for description

* simplify a check for description

* simplify a check for description

* simplify a check for description

* simplify a check for description

* simplify a check for description

* call uid() in constructor

* fix a check for null

* attempting to bypass insecure randomness

* move a call of uid() into constructor

* uid generation tweak

* Apply suggestions from code review

* prettier

* simplify

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2025-11-10 10:04:31 +00:00
Petar Petrov
76911e0e0d Dynamic total energy for pie chart (#27883) 2025-11-10 10:20:26 +01:00
Petar Petrov
b8ec7c2e72 Fix chart label outline color (#27882) 2025-11-10 08:53:18 +01:00
dependabot[bot]
10e20c2272 Bump softprops/action-gh-release from 2.4.1 to 2.4.2 (#27879) 2025-11-09 22:14:19 -08:00
dependabot[bot]
2ec05aac2f Bump relative-ci/agent-action from 3.1.0 to 3.2.0 (#27880) 2025-11-09 22:12:30 -08:00
renovate[bot]
61fbe5b53c Update dependency marked to v16.4.2 (#27877)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-10 06:57:39 +01:00
Yuksel Beyti
5f3f1c7139 Fix malformed HTML tags in backup backups component (#27872) 2025-11-09 13:56:43 +02:00
ildar170975
48f37b1b1e "Expand" tooltips: remove a trailing dot (#27869)
remove trailing dot
2025-11-09 09:00:28 +01:00
karwosts
9091df9db5 Fix sequence action copy-paste (#27652) 2025-11-08 15:50:38 +01:00
renovate[bot]
1cd7a1cd78 Update dependency @rsdoctor/rspack-plugin to v1.3.8 (#27867)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-08 13:48:08 +01:00
renovate[bot]
ae5c7026b9 Update dependency @rspack/core to v1.6.1 (#27864)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-08 13:16:38 +01:00
renovate[bot]
3900f3995a Update vitest monorepo to v4.0.7 (#27862)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-11-08 13:16:16 +01:00
Paul Bottein
237f974ee8 Only show panel with default visible flag in sidebar (#27838) 2025-11-08 13:15:43 +01:00
Paul Bottein
b2ec4b7d2c Fix backup download and delete actions (#27851) 2025-11-07 13:43:00 +02:00
Aidan Timson
b4c83d7877 Migrate dialog-repairs-issue to ha-wa-dialog (#27667)
* Migrate dialog-repairs-issue to ha-wa-dialog

* Allow for custom slots for header title and subtitle, using boolean to enable

* Fix typing

* Cleanup

* Refactor header slot logic

* [workaround] pass aria attributes to dialog

* Update src/components/ha-wa-dialog.ts

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>

* Remove unused (by wa) aira attrs

* Fix imports

* Revert "Remove unused (by wa) aira attrs"

This reverts commit ce97bebce4.

* Remove workaround

* Remove

* Format

* Fix subtitle margin

* Use spacing token

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2025-11-07 13:42:07 +02:00
Paul Bottein
22c53b6859 Add area context in zha, zwave and bluetooth graph (#27849)
* Add area context in zha, zwave and bluetooth graph

* Fix undefined device

* Fix typing

* Add context to find area
2025-11-07 13:34:44 +02:00
Simon Lamon
b8110d1a45 Merge branch 'dev' into sec_pypi_publishing 2025-10-27 06:41:51 +01:00
Simon Lamon
19e9de39c5 Merge branch 'dev' into sec_pypi_publishing 2025-10-19 10:56:12 +02:00
Simon Lamon
f22f01e513 Merge branch 'dev' into sec_pypi_publishing 2025-10-06 20:28:38 +02:00
Simon Lamon
3f86f144b5 Merge branch 'dev' into sec_pypi_publishing 2025-10-04 17:25:20 +02:00
Simon Lamon
4efef5ed16 Update release.yaml 2025-09-24 07:04:06 +02:00
Simon Lamon
cac7ae2a40 Remove twine and introduce trusted publishing 2025-09-20 21:23:04 +02:00
115 changed files with 5693 additions and 2481 deletions

View File

@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Send bundle stats and build information to RelativeCI - name: Send bundle stats and build information to RelativeCI
uses: relative-ci/agent-action@8504826a02078b05756e4c07e380023cc2c4274a # v3.1.0 uses: relative-ci/agent-action@feb19ddc698445db27401f1490f6ac182da0816f # v3.2.0
with: with:
key: ${{ secrets[format('RELATIVE_CI_KEY_{0}_{1}', matrix.bundle, matrix.build)] }} key: ${{ secrets[format('RELATIVE_CI_KEY_{0}_{1}', matrix.bundle, matrix.build)] }}
token: ${{ github.token }} token: ${{ github.token }}

View File

@@ -19,8 +19,11 @@ jobs:
release: release:
name: Release name: Release
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment: pypi
permissions: permissions:
contents: write # Required to upload release assets contents: write # Required to upload release assets
id-token: write # For "Trusted Publisher" to PyPi
if: github.repository_owner == 'home-assistant'
steps: steps:
- name: Checkout the repository - name: Checkout the repository
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
@@ -46,16 +49,20 @@ jobs:
run: ./script/translations_download run: ./script/translations_download
env: env:
LOKALISE_TOKEN: ${{ secrets.LOKALISE_TOKEN }} LOKALISE_TOKEN: ${{ secrets.LOKALISE_TOKEN }}
- name: Build and release package - name: Build and release package
run: | run: |
python3 -m pip install twine build python3 -m pip install build
export TWINE_USERNAME="__token__"
export TWINE_PASSWORD="${{ secrets.TWINE_TOKEN }}"
export SKIP_FETCH_NIGHTLY_TRANSLATIONS=1 export SKIP_FETCH_NIGHTLY_TRANSLATIONS=1
script/release script/release
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0
with:
skip-existing: true
- name: Upload release assets - name: Upload release assets
uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1 uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
with: with:
files: | files: |
dist/*.whl dist/*.whl
@@ -108,7 +115,7 @@ jobs:
- name: Tar folder - name: Tar folder
run: tar -czf landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz -C landing-page/dist . run: tar -czf landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz -C landing-page/dist .
- name: Upload release asset - name: Upload release asset
uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1 uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
with: with:
files: landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz files: landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz
@@ -137,6 +144,6 @@ jobs:
- name: Tar folder - name: Tar folder
run: tar -czf hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz -C hassio/build . run: tar -czf hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz -C hassio/build .
- name: Upload release asset - name: Upload release asset
uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1 uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
with: with:
files: hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz files: hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz

View File

@@ -0,0 +1,55 @@
---
title: Dropdown
---
# Dropdown `<ha-dropdown>`
## Implementation
A compact, accessible dropdown menu for choosing actions or settings. `ha-dropdown` supports composed menu items (`<ha-dropdown-item>`) for icons, submenus, checkboxes, disabled entries, and destructive variants. Use composition with `slot="trigger"` to control the trigger button and use `<ha-dropdown-item>` for rich item content.
### Example usage (composition)
```html
<ha-dropdown open>
<ha-button slot="trigger" with-caret>Dropdown</ha-button>
<ha-dropdown-item>
<ha-svg-icon .path="mdiContentCut" slot="icon"></ha-svg-icon>
Cut
</ha-dropdown-item>
<ha-dropdown-item>
<ha-svg-icon .path="mdiContentCopy" slot="icon"></ha-svg-icon>
Copy
</ha-dropdown-item>
<ha-dropdown-item disabled>
<ha-svg-icon .path="mdiContentPaste" slot="icon"></ha-svg-icon>
Paste
</ha-dropdown-item>
<ha-dropdown-item>
Show images
<ha-dropdown-item slot="submenu" value="show-all-images"
>Show all images</ha-dropdown-item
>
<ha-dropdown-item slot="submenu" value="show-thumbnails"
>Show thumbnails</ha-dropdown-item
>
</ha-dropdown-item>
<ha-dropdown-item type="checkbox" checked>Emoji shortcuts</ha-dropdown-item>
<ha-dropdown-item type="checkbox" checked>Word wrap</ha-dropdown-item>
<ha-dropdown-item variant="danger">
<ha-svg-icon .path="mdiDelete" slot="icon"></ha-svg-icon>
Delete
</ha-dropdown-item>
</ha-dropdown>
```
### API
This component is based on the webawesome dropdown component.
Check the [webawesome documentation](https://webawesome.com/docs/components/dropdown/) for more details.

View File

@@ -0,0 +1,133 @@
import "@home-assistant/webawesome/dist/components/button/button";
import "@home-assistant/webawesome/dist/components/dropdown/dropdown";
import "@home-assistant/webawesome/dist/components/icon/icon";
import "@home-assistant/webawesome/dist/components/popup/popup";
import {
mdiContentCopy,
mdiContentCut,
mdiContentPaste,
mdiDelete,
} from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators";
import { applyThemesOnElement } from "../../../../src/common/dom/apply_themes_on_element";
import "../../../../src/components/ha-button";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-dropdown";
import "../../../../src/components/ha-dropdown-item";
import "../../../../src/components/ha-icon-button";
import "../../../../src/components/ha-svg-icon";
@customElement("demo-components-ha-dropdown")
export class DemoHaDropdown extends LitElement {
protected render(): TemplateResult {
return html`
${["light", "dark"].map(
(mode) => html`
<div class=${mode}>
<ha-card header="ha-button in ${mode}">
<div class="card-content">
<ha-dropdown open>
<ha-button slot="trigger" with-caret>Dropdown</ha-button>
<ha-dropdown-item>
<ha-svg-icon
.path=${mdiContentCut}
slot="icon"
></ha-svg-icon>
Cut
</ha-dropdown-item>
<ha-dropdown-item>
<ha-svg-icon
.path=${mdiContentCopy}
slot="icon"
></ha-svg-icon>
Copy
</ha-dropdown-item>
<ha-dropdown-item disabled>
<ha-svg-icon
.path=${mdiContentPaste}
slot="icon"
></ha-svg-icon>
Paste
</ha-dropdown-item>
<ha-dropdown-item>
Show images
<ha-dropdown-item slot="submenu" value="show-all-images"
>Show All Images</ha-dropdown-item
>
<ha-dropdown-item slot="submenu" value="show-thumbnails"
>Show Thumbnails</ha-dropdown-item
>
</ha-dropdown-item>
<ha-dropdown-item type="checkbox" checked
>Emoji Shortcuts</ha-dropdown-item
>
<ha-dropdown-item type="checkbox" checked
>Word Wrap</ha-dropdown-item
>
<ha-dropdown-item variant="danger">
<ha-svg-icon .path=${mdiDelete} slot="icon"></ha-svg-icon>
Delete
</ha-dropdown-item>
</ha-dropdown>
</div>
</ha-card>
</div>
`
)}
`;
}
firstUpdated(changedProps) {
super.firstUpdated(changedProps);
applyThemesOnElement(
this.shadowRoot!.querySelector(".dark"),
{
default_theme: "default",
default_dark_theme: "default",
themes: {},
darkMode: true,
theme: "default",
},
undefined,
undefined,
true
);
}
static styles = css`
:host {
display: flex;
justify-content: center;
}
.dark,
.light {
display: block;
background-color: var(--primary-background-color);
padding: 0 50px;
}
.button {
padding: unset;
}
ha-card {
margin: 24px auto;
}
.card-content {
display: flex;
flex-direction: column;
gap: 24px;
}
.card-content div {
display: flex;
gap: 8px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"demo-components-ha-dropdown": DemoHaDropdown;
}
}

View File

@@ -52,7 +52,7 @@
"@fullcalendar/list": "6.1.19", "@fullcalendar/list": "6.1.19",
"@fullcalendar/luxon3": "6.1.19", "@fullcalendar/luxon3": "6.1.19",
"@fullcalendar/timegrid": "6.1.19", "@fullcalendar/timegrid": "6.1.19",
"@home-assistant/webawesome": "3.0.0-beta.6.ha.7", "@home-assistant/webawesome": "3.0.0",
"@lezer/highlight": "1.2.3", "@lezer/highlight": "1.2.3",
"@lit-labs/motion": "1.0.9", "@lit-labs/motion": "1.0.9",
"@lit-labs/observers": "2.0.6", "@lit-labs/observers": "2.0.6",
@@ -89,8 +89,8 @@
"@thomasloven/round-slider": "0.6.0", "@thomasloven/round-slider": "0.6.0",
"@tsparticles/engine": "3.9.1", "@tsparticles/engine": "3.9.1",
"@tsparticles/preset-links": "3.2.0", "@tsparticles/preset-links": "3.2.0",
"@vaadin/combo-box": "24.9.4", "@vaadin/combo-box": "24.9.5",
"@vaadin/vaadin-themable-mixin": "24.9.4", "@vaadin/vaadin-themable-mixin": "24.9.5",
"@vibrant/color": "4.0.0", "@vibrant/color": "4.0.0",
"@vue/web-component-wrapper": "1.3.0", "@vue/web-component-wrapper": "1.3.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10", "@webcomponents/scoped-custom-element-registry": "0.0.10",
@@ -122,7 +122,7 @@
"lit": "3.3.1", "lit": "3.3.1",
"lit-html": "3.3.1", "lit-html": "3.3.1",
"luxon": "3.7.2", "luxon": "3.7.2",
"marked": "16.4.1", "marked": "17.0.0",
"memoize-one": "6.0.0", "memoize-one": "6.0.0",
"node-vibrant": "4.0.3", "node-vibrant": "4.0.3",
"object-hash": "3.0.0", "object-hash": "3.0.0",
@@ -157,8 +157,8 @@
"@octokit/auth-oauth-device": "8.0.3", "@octokit/auth-oauth-device": "8.0.3",
"@octokit/plugin-retry": "8.0.3", "@octokit/plugin-retry": "8.0.3",
"@octokit/rest": "22.0.1", "@octokit/rest": "22.0.1",
"@rsdoctor/rspack-plugin": "1.3.7", "@rsdoctor/rspack-plugin": "1.3.8",
"@rspack/core": "1.6.0", "@rspack/core": "1.6.1",
"@rspack/dev-server": "1.1.4", "@rspack/dev-server": "1.1.4",
"@types/babel__plugin-transform-runtime": "7.9.5", "@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "6.0.22", "@types/chromecast-caf-receiver": "6.0.22",
@@ -178,7 +178,7 @@
"@types/tar": "6.1.13", "@types/tar": "6.1.13",
"@types/ua-parser-js": "0.7.39", "@types/ua-parser-js": "0.7.39",
"@types/webspeechapi": "0.0.29", "@types/webspeechapi": "0.0.29",
"@vitest/coverage-v8": "4.0.6", "@vitest/coverage-v8": "4.0.8",
"babel-loader": "10.0.0", "babel-loader": "10.0.0",
"babel-plugin-template-html-minifier": "4.1.0", "babel-plugin-template-html-minifier": "4.1.0",
"browserslist-useragent-regexp": "4.1.3", "browserslist-useragent-regexp": "4.1.3",
@@ -219,7 +219,7 @@
"typescript": "5.9.3", "typescript": "5.9.3",
"typescript-eslint": "8.46.3", "typescript-eslint": "8.46.3",
"vite-tsconfig-paths": "5.1.4", "vite-tsconfig-paths": "5.1.4",
"vitest": "4.0.6", "vitest": "4.0.8",
"webpack-stats-plugin": "1.1.3", "webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0", "webpackbar": "7.0.0",
"workbox-build": "patch:workbox-build@npm%3A7.1.1#~/.yarn/patches/workbox-build-npm-7.1.1-a854f3faae.patch" "workbox-build": "patch:workbox-build@npm%3A7.1.1#~/.yarn/patches/workbox-build-npm-7.1.1-a854f3faae.patch"

View File

@@ -1,5 +1,4 @@
#!/bin/sh #!/bin/sh
# Pushes a new version to PyPi.
# Stop on errors # Stop on errors
set -e set -e
@@ -12,5 +11,4 @@ yarn install
script/build_frontend script/build_frontend
rm -rf dist home_assistant_frontend.egg-info rm -rf dist home_assistant_frontend.egg-info
python3 -m build python3 -m build -q
python3 -m twine upload dist/*.whl --skip-existing

View File

@@ -0,0 +1,36 @@
import type {
Condition,
TimeCondition,
} from "../../panels/lovelace/common/validate-condition";
/**
* Extract media queries from conditions recursively
*/
export function extractMediaQueries(conditions: Condition[]): string[] {
return conditions.reduce<string[]>((array, c) => {
if ("conditions" in c && c.conditions) {
array.push(...extractMediaQueries(c.conditions));
}
if (c.condition === "screen" && c.media_query) {
array.push(c.media_query);
}
return array;
}, []);
}
/**
* Extract time conditions from conditions recursively
*/
export function extractTimeConditions(
conditions: Condition[]
): TimeCondition[] {
return conditions.reduce<TimeCondition[]>((array, c) => {
if ("conditions" in c && c.conditions) {
array.push(...extractTimeConditions(c.conditions));
}
if (c.condition === "time") {
array.push(c);
}
return array;
}, []);
}

View File

@@ -0,0 +1,89 @@
import { listenMediaQuery } from "../dom/media_query";
import type { HomeAssistant } from "../../types";
import type { Condition } from "../../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../../panels/lovelace/common/validate-condition";
import { extractMediaQueries, extractTimeConditions } from "./extract";
import { calculateNextTimeUpdate } from "./time-calculator";
/** Maximum delay for setTimeout (2^31 - 1 milliseconds, ~24.8 days)
* Values exceeding this will overflow and execute immediately
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value
*/
const MAX_TIMEOUT_DELAY = 2147483647;
/**
* Helper to setup media query listeners for conditional visibility
*/
export function setupMediaQueryListeners(
conditions: Condition[],
hass: HomeAssistant,
addListener: (unsub: () => void) => void,
onUpdate: (conditionsMet: boolean) => void
): void {
const mediaQueries = extractMediaQueries(conditions);
if (mediaQueries.length === 0) return;
// Optimization for single media query
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;
mediaQueries.forEach((mediaQuery) => {
const unsub = listenMediaQuery(mediaQuery, (matches) => {
if (hasOnlyMediaQuery) {
onUpdate(matches);
} else {
const conditionsMet = checkConditionsMet(conditions, hass);
onUpdate(conditionsMet);
}
});
addListener(unsub);
});
}
/**
* Helper to setup time-based listeners for conditional visibility
*/
export function setupTimeListeners(
conditions: Condition[],
hass: HomeAssistant,
addListener: (unsub: () => void) => void,
onUpdate: (conditionsMet: boolean) => void
): void {
const timeConditions = extractTimeConditions(conditions);
if (timeConditions.length === 0) return;
timeConditions.forEach((timeCondition) => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const scheduleUpdate = () => {
const delay = calculateNextTimeUpdate(hass, timeCondition);
if (delay === undefined) return;
// Cap delay to prevent setTimeout overflow
const cappedDelay = Math.min(delay, MAX_TIMEOUT_DELAY);
timeoutId = setTimeout(() => {
if (delay <= MAX_TIMEOUT_DELAY) {
const conditionsMet = checkConditionsMet(conditions, hass);
onUpdate(conditionsMet);
}
scheduleUpdate();
}, cappedDelay);
};
// Register cleanup function once, outside of scheduleUpdate
addListener(() => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
});
scheduleUpdate();
});
}

View File

@@ -0,0 +1,73 @@
import { TZDate } from "@date-fns/tz";
import {
startOfDay,
addDays,
addMinutes,
differenceInMilliseconds,
} from "date-fns";
import type { HomeAssistant } from "../../types";
import { TimeZone } from "../../data/translation";
import { parseTimeString } from "../datetime/check_time";
import type { TimeCondition } from "../../panels/lovelace/common/validate-condition";
/**
* Calculate milliseconds until next time boundary for a time condition
* @param hass Home Assistant object
* @param timeCondition Time condition to calculate next update for
* @returns Milliseconds until next boundary, or undefined if no boundaries
*/
export function calculateNextTimeUpdate(
hass: HomeAssistant,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): number | undefined {
const timezone =
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
const updates: Date[] = [];
// Calculate next occurrence of after time
if (after) {
let afterDate = parseTimeString(after, timezone);
if (afterDate <= now) {
// If time has passed today, schedule for tomorrow
afterDate = addDays(afterDate, 1);
}
updates.push(afterDate);
}
// Calculate next occurrence of before time
if (before) {
let beforeDate = parseTimeString(before, timezone);
if (beforeDate <= now) {
// If time has passed today, schedule for tomorrow
beforeDate = addDays(beforeDate, 1);
}
updates.push(beforeDate);
}
// If weekdays are specified, check for midnight (weekday transition)
if (weekdays && weekdays.length > 0 && weekdays.length < 7) {
// Calculate next midnight using startOfDay + addDays
const tomorrow = addDays(now, 1);
const midnight = startOfDay(tomorrow);
updates.push(midnight);
}
if (updates.length === 0) {
return undefined;
}
// Find the soonest update time
const nextUpdate = updates.reduce((soonest, current) =>
current < soonest ? current : soonest
);
// Add 1 minute buffer to ensure we're past the boundary
const updateWithBuffer = addMinutes(nextUpdate, 1);
// Calculate difference in milliseconds
return differenceInMilliseconds(updateWithBuffer, now);
}

View File

@@ -0,0 +1,131 @@
import { TZDate } from "@date-fns/tz";
import { isBefore, isAfter, isWithinInterval } from "date-fns";
import type { HomeAssistant } from "../../types";
import { TimeZone } from "../../data/translation";
import { WEEKDAY_MAP } from "./weekday";
import type { TimeCondition } from "../../panels/lovelace/common/validate-condition";
/**
* Validate a time string format and value ranges without creating Date objects
* @param timeString Time string to validate (HH:MM or HH:MM:SS)
* @returns true if valid, false otherwise
*/
export function isValidTimeString(timeString: string): boolean {
// Reject empty strings
if (!timeString || timeString.trim() === "") {
return false;
}
const parts = timeString.split(":");
if (parts.length < 2 || parts.length > 3) {
return false;
}
// Ensure each part contains only digits (and optional leading zeros)
// This prevents "8:00 AM" from passing validation
if (!parts.every((part) => /^\d+$/.test(part))) {
return false;
}
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
const seconds = parts.length === 3 ? parseInt(parts[2], 10) : 0;
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
return false;
}
return (
hours >= 0 &&
hours <= 23 &&
minutes >= 0 &&
minutes <= 59 &&
seconds >= 0 &&
seconds <= 59
);
}
/**
* Parse a time string (HH:MM or HH:MM:SS) and set it on today's date in the given timezone
*
* Note: This function assumes the time string has already been validated by
* isValidTimeString() at configuration time. It does not re-validate at runtime
* for consistency with other condition types (screen, user, location, etc.)
*
* @param timeString The time string to parse (must be pre-validated)
* @param timezone The timezone to use
* @returns The Date object
*/
export const parseTimeString = (timeString: string, timezone: string): Date => {
const parts = timeString.split(":");
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
const seconds = parts.length === 3 ? parseInt(parts[2], 10) : 0;
const now = new TZDate(new Date(), timezone);
const dateWithTime = new TZDate(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes,
seconds,
0,
timezone
);
return new Date(dateWithTime.getTime());
};
/**
* Check if the current time matches the time condition (after/before/weekday)
* @param hass Home Assistant object
* @param timeCondition Time condition to check
* @returns true if current time matches the condition
*/
export const checkTimeInRange = (
hass: HomeAssistant,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): boolean => {
const timezone =
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
// Check weekday condition
if (weekdays && weekdays.length > 0) {
const currentWeekday = WEEKDAY_MAP[now.getDay()];
if (!weekdays.includes(currentWeekday)) {
return false;
}
}
// Check time conditions
if (!after && !before) {
return true;
}
const afterDate = after ? parseTimeString(after, timezone) : undefined;
const beforeDate = before ? parseTimeString(before, timezone) : undefined;
if (afterDate && beforeDate) {
if (isBefore(beforeDate, afterDate)) {
// Crosses midnight (e.g., 22:00 to 06:00)
return !isBefore(now, afterDate) || !isAfter(now, beforeDate);
}
return isWithinInterval(now, { start: afterDate, end: beforeDate });
}
if (afterDate) {
return !isBefore(now, afterDate);
}
if (beforeDate) {
return !isAfter(now, beforeDate);
}
return true;
};

View File

@@ -1,18 +1,7 @@
import { getWeekStartByLocale } from "weekstart"; import { getWeekStartByLocale } from "weekstart";
import type { FrontendLocaleData } from "../../data/translation"; import type { FrontendLocaleData } from "../../data/translation";
import { FirstWeekday } from "../../data/translation"; import { FirstWeekday } from "../../data/translation";
import { WEEKDAYS_LONG, type WeekdayIndex } from "./weekday";
export const weekdays = [
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
] as const;
type WeekdayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export const firstWeekdayIndex = (locale: FrontendLocaleData): WeekdayIndex => { export const firstWeekdayIndex = (locale: FrontendLocaleData): WeekdayIndex => {
if (locale.first_weekday === FirstWeekday.language) { if (locale.first_weekday === FirstWeekday.language) {
@@ -23,12 +12,12 @@ export const firstWeekdayIndex = (locale: FrontendLocaleData): WeekdayIndex => {
} }
return (getWeekStartByLocale(locale.language) % 7) as WeekdayIndex; return (getWeekStartByLocale(locale.language) % 7) as WeekdayIndex;
} }
return weekdays.includes(locale.first_weekday) return WEEKDAYS_LONG.includes(locale.first_weekday)
? (weekdays.indexOf(locale.first_weekday) as WeekdayIndex) ? (WEEKDAYS_LONG.indexOf(locale.first_weekday) as WeekdayIndex)
: 1; : 1;
}; };
export const firstWeekday = (locale: FrontendLocaleData) => { export const firstWeekday = (locale: FrontendLocaleData) => {
const index = firstWeekdayIndex(locale); const index = firstWeekdayIndex(locale);
return weekdays[index]; return WEEKDAYS_LONG[index];
}; };

View File

@@ -0,0 +1,59 @@
export type WeekdayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export type WeekdayShort =
| "sun"
| "mon"
| "tue"
| "wed"
| "thu"
| "fri"
| "sat";
export type WeekdayLong =
| "sunday"
| "monday"
| "tuesday"
| "wednesday"
| "thursday"
| "friday"
| "saturday";
export const WEEKDAYS_SHORT = [
"sun",
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
] as const satisfies readonly WeekdayShort[];
export const WEEKDAYS_LONG = [
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
] as const satisfies readonly WeekdayLong[];
export const WEEKDAY_MAP = {
0: "sun",
1: "mon",
2: "tue",
3: "wed",
4: "thu",
5: "fri",
6: "sat",
} as const satisfies Record<WeekdayIndex, WeekdayShort>;
export const WEEKDAY_SHORT_TO_LONG = {
sun: "sunday",
mon: "monday",
tue: "tuesday",
wed: "wednesday",
thu: "thursday",
fri: "friday",
sat: "saturday",
} as const satisfies Record<WeekdayShort, WeekdayLong>;

View File

@@ -1,5 +1,6 @@
import type { ThemeVars } from "../../data/ws-themes"; import type { ThemeVars } from "../../data/ws-themes";
import { darkColorVariables } from "../../resources/theme/color"; import { darkColorVariables } from "../../resources/theme/color";
import { darkSemanticVariables } from "../../resources/theme/semantic.globals";
import { derivedStyles } from "../../resources/theme/theme"; import { derivedStyles } from "../../resources/theme/theme";
import type { HomeAssistant } from "../../types"; import type { HomeAssistant } from "../../types";
import { import {
@@ -52,7 +53,7 @@ export const applyThemesOnElement = (
if (themeToApply && darkMode) { if (themeToApply && darkMode) {
cacheKey = `${cacheKey}__dark`; cacheKey = `${cacheKey}__dark`;
themeRules = { ...darkColorVariables }; themeRules = { ...darkSemanticVariables, ...darkColorVariables };
} }
if (themeToApply === "default") { if (themeToApply === "default") {

View File

@@ -0,0 +1,36 @@
/**
* Parses a CSS duration string (e.g., "300ms", "3s") and returns the duration in milliseconds.
*
* @param duration - A CSS duration string (e.g., "300ms", "3s", "0.5s")
* @returns The duration in milliseconds, or 0 if the input is invalid
*
* @example
* parseAnimationDuration("300ms") // Returns 300
* parseAnimationDuration("3s") // Returns 3000
* parseAnimationDuration("0.5s") // Returns 500
* parseAnimationDuration("invalid") // Returns 0
*/
export const parseAnimationDuration = (duration: string): number => {
const trimmed = duration.trim();
let value: number;
let multiplier: number;
if (trimmed.endsWith("ms")) {
value = parseFloat(trimmed.slice(0, -2));
multiplier = 1;
} else if (trimmed.endsWith("s")) {
value = parseFloat(trimmed.slice(0, -1));
multiplier = 1000;
} else {
// No recognized unit, try parsing as number (assume ms)
value = parseFloat(trimmed);
multiplier = 1;
}
if (!isFinite(value) || value < 0) {
return 0;
}
return value * multiplier;
};

View File

@@ -119,8 +119,8 @@ type Thresholds = Record<
>; >;
export const DEFAULT_THRESHOLDS: Thresholds = { export const DEFAULT_THRESHOLDS: Thresholds = {
second: 45, // seconds to minute second: 59, // seconds to minute
minute: 45, // minutes to hour minute: 59, // minutes to hour
hour: 22, // hour to day hour: 22, // hour to day
day: 5, // day to week day: 5, // day to week
week: 4, // week to months week: 4, // week to months

View File

@@ -6,7 +6,8 @@ export function downSampleLineData<
data: T[] | undefined, data: T[] | undefined,
maxDetails: number, maxDetails: number,
minX?: number, minX?: number,
maxX?: number maxX?: number,
useMean = false
): T[] { ): T[] {
if (!data) { if (!data) {
return []; return [];
@@ -17,15 +18,13 @@ export function downSampleLineData<
const min = minX ?? getPointData(data[0]!)[0]; const min = minX ?? getPointData(data[0]!)[0];
const max = maxX ?? getPointData(data[data.length - 1]!)[0]; const max = maxX ?? getPointData(data[data.length - 1]!)[0];
const step = Math.ceil((max - min) / Math.floor(maxDetails)); const step = Math.ceil((max - min) / Math.floor(maxDetails));
const frames = new Map<
number,
{
min: { point: (typeof data)[number]; x: number; y: number };
max: { point: (typeof data)[number]; x: number; y: number };
}
>();
// Group points into frames // Group points into frames
const frames = new Map<
number,
{ point: (typeof data)[number]; x: number; y: number }[]
>();
for (const point of data) { for (const point of data) {
const pointData = getPointData(point); const pointData = getPointData(point);
if (!Array.isArray(pointData)) continue; if (!Array.isArray(pointData)) continue;
@@ -36,28 +35,53 @@ export function downSampleLineData<
const frameIndex = Math.floor((x - min) / step); const frameIndex = Math.floor((x - min) / step);
const frame = frames.get(frameIndex); const frame = frames.get(frameIndex);
if (!frame) { if (!frame) {
frames.set(frameIndex, { min: { point, x, y }, max: { point, x, y } }); frames.set(frameIndex, [{ point, x, y }]);
} else { } else {
if (frame.min.y > y) { frame.push({ point, x, y });
frame.min = { point, x, y };
}
if (frame.max.y < y) {
frame.max = { point, x, y };
}
} }
} }
// Convert frames back to points // Convert frames back to points
const result: T[] = []; const result: T[] = [];
for (const [_i, frame] of frames) {
// Use min/max points to preserve visual accuracy if (useMean) {
// The order of the data must be preserved so max may be before min // Use mean values for each frame
if (frame.min.x > frame.max.x) { for (const [_i, framePoints] of frames) {
result.push(frame.max.point); const sumY = framePoints.reduce((acc, p) => acc + p.y, 0);
const meanY = sumY / framePoints.length;
const sumX = framePoints.reduce((acc, p) => acc + p.x, 0);
const meanX = sumX / framePoints.length;
const firstPoint = framePoints[0].point;
const pointData = getPointData(firstPoint);
const meanPoint = (
Array.isArray(pointData) ? [meanX, meanY] : { value: [meanX, meanY] }
) as T;
result.push(meanPoint);
}
} else {
// Use min/max values for each frame
for (const [_i, framePoints] of frames) {
let minPoint = framePoints[0];
let maxPoint = framePoints[0];
for (const p of framePoints) {
if (p.y < minPoint.y) {
minPoint = p;
}
if (p.y > maxPoint.y) {
maxPoint = p;
}
}
// The order of the data must be preserved so max may be before min
if (minPoint.x > maxPoint.x) {
result.push(maxPoint.point);
}
result.push(minPoint.point);
if (minPoint.x < maxPoint.x) {
result.push(maxPoint.point);
} }
result.push(frame.min.point);
if (frame.min.x < frame.max.x) {
result.push(frame.max.point);
} }
} }

View File

@@ -427,6 +427,7 @@ export class HaChartBase extends LitElement {
...axis.axisPointer?.handle, ...axis.axisPointer?.handle,
show: true, show: true,
}, },
label: { show: false },
}, },
} }
: axis : axis
@@ -627,6 +628,10 @@ export class HaChartBase extends LitElement {
} }
private _createTheme(style: CSSStyleDeclaration) { private _createTheme(style: CSSStyleDeclaration) {
const textBorderColor =
style.getPropertyValue("--ha-card-background") ||
style.getPropertyValue("--card-background-color");
const textBorderWidth = 2;
return { return {
color: getAllGraphColors(style), color: getAllGraphColors(style),
backgroundColor: "transparent", backgroundColor: "transparent",
@@ -650,22 +655,22 @@ export class HaChartBase extends LitElement {
graph: { graph: {
label: { label: {
color: style.getPropertyValue("--primary-text-color"), color: style.getPropertyValue("--primary-text-color"),
textBorderColor: style.getPropertyValue("--primary-background-color"), textBorderColor,
textBorderWidth: 2, textBorderWidth,
}, },
}, },
pie: { pie: {
label: { label: {
color: style.getPropertyValue("--primary-text-color"), color: style.getPropertyValue("--primary-text-color"),
textBorderColor: style.getPropertyValue("--primary-background-color"), textBorderColor,
textBorderWidth: 2, textBorderWidth,
}, },
}, },
sankey: { sankey: {
label: { label: {
color: style.getPropertyValue("--primary-text-color"), color: style.getPropertyValue("--primary-text-color"),
textBorderColor: style.getPropertyValue("--primary-background-color"), textBorderColor,
textBorderWidth: 2, textBorderWidth,
}, },
}, },
categoryAxis: { categoryAxis: {

View File

@@ -2,7 +2,10 @@ import type { EChartsType } from "echarts/core";
import type { GraphSeriesOption } from "echarts/charts"; import type { GraphSeriesOption } from "echarts/charts";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state, query } from "lit/decorators"; import { customElement, property, state, query } from "lit/decorators";
import type { TopLevelFormatterParams } from "echarts/types/dist/shared"; import type {
CallbackDataParams,
TopLevelFormatterParams,
} from "echarts/types/dist/shared";
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js"; import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { listenMediaQuery } from "../../common/dom/media_query"; import { listenMediaQuery } from "../../common/dom/media_query";
@@ -16,6 +19,7 @@ import { deepEqual } from "../../common/util/deep-equal";
export interface NetworkNode { export interface NetworkNode {
id: string; id: string;
name?: string; name?: string;
context?: string;
category?: number; category?: number;
value?: number; value?: number;
symbolSize?: number; symbolSize?: number;
@@ -188,6 +192,25 @@ export class HaNetworkGraph extends SubscribeMixin(LitElement) {
label: { label: {
show: showLabels, show: showLabels,
position: "right", position: "right",
formatter: (params: CallbackDataParams) => {
const node = params.data as NetworkNode;
if (node.context) {
return `{primary|${node.name ?? ""}}\n{secondary|${node.context}}`;
}
return node.name ?? "";
},
rich: {
primary: {
fontSize: 12,
},
secondary: {
fontSize: 12,
color: getComputedStyle(document.body).getPropertyValue(
"--secondary-text-color"
),
lineHeight: 16,
},
},
}, },
emphasis: { emphasis: {
focus: isMobile ? "none" : "adjacency", focus: isMobile ? "none" : "adjacency",
@@ -225,6 +248,7 @@ export class HaNetworkGraph extends SubscribeMixin(LitElement) {
({ ({
id: node.id, id: node.id,
name: node.name, name: node.name,
context: node.context,
category: node.category, category: node.category,
value: node.value, value: node.value,
symbolSize: node.symbolSize || 30, symbolSize: node.symbolSize || 30,

View File

@@ -62,6 +62,7 @@ class HaDataTableLabels extends LitElement {
@click=${clickAction ? this._labelClicked : undefined} @click=${clickAction ? this._labelClicked : undefined}
@keydown=${clickAction ? this._labelClicked : undefined} @keydown=${clickAction ? this._labelClicked : undefined}
style=${color ? `--color: ${color}` : ""} style=${color ? `--color: ${color}` : ""}
.description=${label.description}
> >
${label?.icon ${label?.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`

View File

@@ -197,9 +197,6 @@ export class HaDevicePicker extends LitElement {
const placeholder = const placeholder =
this.placeholder ?? this.placeholder ??
this.hass.localize("ui.components.device-picker.placeholder"); this.hass.localize("ui.components.device-picker.placeholder");
const notFoundLabel = this.hass.localize(
"ui.components.device-picker.no_match"
);
const valueRenderer = this._valueRenderer(this._configEntryLookup); const valueRenderer = this._valueRenderer(this._configEntryLookup);
@@ -209,7 +206,10 @@ export class HaDevicePicker extends LitElement {
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.searchLabel=${this.searchLabel} .searchLabel=${this.searchLabel}
.notFoundLabel=${notFoundLabel} .notFoundLabel=${this._notFoundLabel}
.emptyLabel=${this.hass.localize(
"ui.components.device-picker.no_devices"
)}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.rowRenderer=${this._rowRenderer} .rowRenderer=${this._rowRenderer}
@@ -233,6 +233,11 @@ export class HaDevicePicker extends LitElement {
this.value = value; this.value = value;
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.device-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -269,9 +269,6 @@ export class HaEntityPicker extends LitElement {
const placeholder = const placeholder =
this.placeholder ?? this.placeholder ??
this.hass.localize("ui.components.entity.entity-picker.placeholder"); this.hass.localize("ui.components.entity.entity-picker.placeholder");
const notFoundLabel = this.hass.localize(
"ui.components.entity.entity-picker.no_match"
);
return html` return html`
<ha-generic-picker <ha-generic-picker
@@ -282,7 +279,7 @@ export class HaEntityPicker extends LitElement {
.label=${this.label} .label=${this.label}
.helper=${this.helper} .helper=${this.helper}
.searchLabel=${this.searchLabel} .searchLabel=${this.searchLabel}
.notFoundLabel=${notFoundLabel} .notFoundLabel=${this._notFoundLabel}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.addButton ? undefined : this.value} .value=${this.addButton ? undefined : this.value}
.rowRenderer=${this._rowRenderer} .rowRenderer=${this._rowRenderer}
@@ -356,6 +353,11 @@ export class HaEntityPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.entity.entity-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -21,7 +21,6 @@ import "../ha-combo-box-item";
import "../ha-generic-picker"; import "../ha-generic-picker";
import type { HaGenericPicker } from "../ha-generic-picker"; import type { HaGenericPicker } from "../ha-generic-picker";
import "../ha-icon-button"; import "../ha-icon-button";
import "../ha-input-helper-text";
import type { import type {
PickerComboBoxItem, PickerComboBoxItem,
PickerComboBoxSearchFn, PickerComboBoxSearchFn,
@@ -271,7 +270,6 @@ export class HaStatisticPicker extends LitElement {
const secondary = [areaName, entityName ? deviceName : undefined] const secondary = [areaName, entityName ? deviceName : undefined]
.filter(Boolean) .filter(Boolean)
.join(isRTL ? " ◂ " : " ▸ "); .join(isRTL ? " ◂ " : " ▸ ");
const a11yLabel = [deviceName, entityName].filter(Boolean).join(" - ");
const sortingPrefix = `${TYPE_ORDER.indexOf("entity")}`; const sortingPrefix = `${TYPE_ORDER.indexOf("entity")}`;
output.push({ output.push({
@@ -279,7 +277,6 @@ export class HaStatisticPicker extends LitElement {
statistic_id: id, statistic_id: id,
primary, primary,
secondary, secondary,
a11y_label: a11yLabel,
stateObj: stateObj, stateObj: stateObj,
type: "entity", type: "entity",
sorting_label: [sortingPrefix, deviceName, entityName].join("_"), sorting_label: [sortingPrefix, deviceName, entityName].join("_"),
@@ -458,9 +455,6 @@ export class HaStatisticPicker extends LitElement {
const placeholder = const placeholder =
this.placeholder ?? this.placeholder ??
this.hass.localize("ui.components.statistic-picker.placeholder"); this.hass.localize("ui.components.statistic-picker.placeholder");
const notFoundLabel = this.hass.localize(
"ui.components.statistic-picker.no_match"
);
return html` return html`
<ha-generic-picker <ha-generic-picker
@@ -468,7 +462,10 @@ export class HaStatisticPicker extends LitElement {
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.allowCustomValue=${this.allowCustomEntity} .allowCustomValue=${this.allowCustomEntity}
.label=${this.label} .label=${this.label}
.notFoundLabel=${notFoundLabel} .notFoundLabel=${this._notFoundLabel}
.emptyLabel=${this.hass.localize(
"ui.components.statistic-picker.no_statistics"
)}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.rowRenderer=${this._rowRenderer} .rowRenderer=${this._rowRenderer}
@@ -477,6 +474,7 @@ export class HaStatisticPicker extends LitElement {
.hideClearIcon=${this.hideClearIcon} .hideClearIcon=${this.hideClearIcon}
.searchFn=${this._searchFn} .searchFn=${this._searchFn}
.valueRenderer=${this._valueRenderer} .valueRenderer=${this._valueRenderer}
.helper=${this.helper}
@value-changed=${this._valueChanged} @value-changed=${this._valueChanged}
> >
</ha-generic-picker> </ha-generic-picker>
@@ -521,6 +519,11 @@ export class HaStatisticPicker extends LitElement {
await this.updateComplete; await this.updateComplete;
await this._picker?.open(); await this._picker?.open();
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.statistic-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -369,9 +369,10 @@ export class HaAreaPicker extends LitElement {
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.helper=${this.helper} .helper=${this.helper}
.notFoundLabel=${this.hass.localize( .notFoundLabel=${this._notFoundLabel}
"ui.components.area-picker.no_match" .emptyLabel=${this.hass.localize("ui.components.area-picker.no_areas")}
)} .disabled=${this.disabled}
.required=${this.required}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.getItems=${this._getItems} .getItems=${this._getItems}
@@ -425,6 +426,11 @@ export class HaAreaPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.area-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -0,0 +1,41 @@
import DropdownItem from "@home-assistant/webawesome/dist/components/dropdown-item/dropdown-item";
import { css, type CSSResultGroup } from "lit";
import { customElement } from "lit/decorators";
/**
* Home Assistant dropdown item component
*
* @element ha-dropdown-item
* @extends {DropdownItem}
*
* @summary
* A stylable dropdown item component supporting Home Assistant theming, variants, and appearances based on webawesome dropdown item.
*
*/
@customElement("ha-dropdown-item")
export class HaDropdownItem extends DropdownItem {
static get styles(): CSSResultGroup {
return [
DropdownItem.styles,
css`
:host {
min-height: var(--ha-space-10);
}
#icon ::slotted(*) {
color: var(--ha-color-on-neutral-normal);
}
:host([variant="danger"]) #icon ::slotted(*) {
color: var(--ha-color-on-danger-quiet);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-dropdown-item": HaDropdownItem;
}
}

View File

@@ -0,0 +1,45 @@
import Dropdown from "@home-assistant/webawesome/dist/components/dropdown/dropdown";
import { css, type CSSResultGroup } from "lit";
import { customElement, property } from "lit/decorators";
/**
* Home Assistant dropdown component
*
* @element ha-dropdown
* @extends {Dropdown}
*
* @summary
* A stylable dropdown component supporting Home Assistant theming, variants, and appearances based on webawesome dropdown.
*
*/
@customElement("ha-dropdown")
export class HaDropdown extends Dropdown {
@property({ attribute: false }) dropdownTag = "ha-dropdown";
@property({ attribute: false }) dropdownItemTag = "ha-dropdown-item";
static get styles(): CSSResultGroup {
return [
Dropdown.styles,
css`
:host {
font-size: var(--ha-dropdown-font-size, var(--ha-font-size-m));
--wa-color-surface-raised: var(
--card-background-color,
var(--ha-dialog-surface-background, var(--mdc-theme-surface, #fff)),
);
}
#menu {
padding: var(--ha-space-1);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-dropdown": HaDropdown;
}
}

View File

@@ -109,7 +109,10 @@ export class HaFilterLabels extends SubscribeMixin(LitElement) {
.selected=${(this.value || []).includes(label.label_id)} .selected=${(this.value || []).includes(label.label_id)}
hasMeta hasMeta
> >
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon ? html`<ha-icon
slot="icon" slot="icon"

View File

@@ -383,8 +383,9 @@ export class HaFloorPicker extends LitElement {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this.hass.localize( .notFoundLabel=${this._notFoundLabel}
"ui.components.floor-picker.no_match" .emptyLabel=${this.hass.localize(
"ui.components.floor-picker.no_floors"
)} )}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
@@ -444,6 +445,11 @@ export class HaFloorPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.floor-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -25,9 +25,6 @@ import "./ha-svg-icon";
export class HaGenericPicker extends LitElement { export class HaGenericPicker extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant; @property({ attribute: false }) public hass?: HomeAssistant;
// eslint-disable-next-line lit/no-native-attributes
@property({ type: Boolean }) public autofocus = false;
@property({ type: Boolean }) public disabled = false; @property({ type: Boolean }) public disabled = false;
@property({ type: Boolean }) public required = false; @property({ type: Boolean }) public required = false;
@@ -49,8 +46,11 @@ export class HaGenericPicker extends LitElement {
@property({ attribute: "hide-clear-icon", type: Boolean }) @property({ attribute: "hide-clear-icon", type: Boolean })
public hideClearIcon = false; public hideClearIcon = false;
@property({ attribute: false, type: Array }) @property({ attribute: false })
public getItems?: () => PickerComboBoxItem[]; public getItems?: (
searchString?: string,
section?: string
) => (PickerComboBoxItem | string)[];
@property({ attribute: false, type: Array }) @property({ attribute: false, type: Array })
public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[]; public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[];
@@ -64,8 +64,11 @@ export class HaGenericPicker extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>; public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>;
@property({ attribute: "not-found-label", type: String }) @property({ attribute: false })
public notFoundLabel?: string; public notFoundLabel?: string | ((search: string) => string);
@property({ attribute: "empty-label" })
public emptyLabel?: string;
@property({ attribute: "popover-placement" }) @property({ attribute: "popover-placement" })
public popoverPlacement: public popoverPlacement:
@@ -85,6 +88,25 @@ export class HaGenericPicker extends LitElement {
/** If set picker shows an add button instead of textbox when value isn't set */ /** If set picker shows an add button instead of textbox when value isn't set */
@property({ attribute: "add-button-label" }) public addButtonLabel?: string; @property({ attribute: "add-button-label" }) public addButtonLabel?: string;
/** Section filter buttons for the list, section headers needs to be defined in getItems as strings */
@property({ attribute: false }) public sections?: (
| {
id: string;
label: string;
}
| "separator"
)[];
@property({ attribute: false }) public sectionTitleFunction?: (listInfo: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
itemsCount: number;
}) => string | undefined;
@property({ attribute: "selected-section" }) public selectedSection?: string;
@query(".container") private _containerElement?: HTMLDivElement; @query(".container") private _containerElement?: HTMLDivElement;
@query("ha-picker-combo-box") private _comboBox?: HaPickerComboBox; @query("ha-picker-combo-box") private _comboBox?: HaPickerComboBox;
@@ -97,6 +119,11 @@ export class HaGenericPicker extends LitElement {
@state() private _openedNarrow = false; @state() private _openedNarrow = false;
static shadowRootOptions = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
private _narrow = false; private _narrow = false;
// helper to set new value after closing picker, to avoid flicker // helper to set new value after closing picker, to avoid flicker
@@ -189,16 +216,19 @@ export class HaGenericPicker extends LitElement {
<ha-picker-combo-box <ha-picker-combo-box
.hass=${this.hass} .hass=${this.hass}
.allowCustomValue=${this.allowCustomValue} .allowCustomValue=${this.allowCustomValue}
.label=${this.searchLabel ?? .label=${this.searchLabel}
(this.hass?.localize("ui.common.search") || "Search")}
.value=${this.value} .value=${this.value}
@value-changed=${this._valueChanged} @value-changed=${this._valueChanged}
.rowRenderer=${this.rowRenderer} .rowRenderer=${this.rowRenderer}
.notFoundLabel=${this.notFoundLabel} .notFoundLabel=${this.notFoundLabel}
.emptyLabel=${this.emptyLabel}
.getItems=${this.getItems} .getItems=${this.getItems}
.getAdditionalItems=${this.getAdditionalItems} .getAdditionalItems=${this.getAdditionalItems}
.searchFn=${this.searchFn} .searchFn=${this.searchFn}
.mode=${dialogMode ? "dialog" : "popover"} .mode=${dialogMode ? "dialog" : "popover"}
.sections=${this.sections}
.sectionTitleFunction=${this.sectionTitleFunction}
.selectedSection=${this.selectedSection}
></ha-picker-combo-box> ></ha-picker-combo-box>
`; `;
} }

View File

@@ -224,8 +224,9 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this.hass.localize( .notFoundLabel=${this._notFoundLabel}
"ui.components.label-picker.no_match" .emptyLabel=${this.hass.localize(
"ui.components.label-picker.no_labels"
)} )}
.addButtonLabel=${this.hass.localize("ui.components.label-picker.add")} .addButtonLabel=${this.hass.localize("ui.components.label-picker.add")}
.placeholder=${placeholder} .placeholder=${placeholder}
@@ -288,6 +289,11 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
fireEvent(this, "change"); fireEvent(this, "change");
}, 0); }, 0);
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.label-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -1,17 +1,32 @@
import type { CSSResultGroup, TemplateResult } from "lit"; import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit"; import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators"; import { customElement, property } from "lit/decorators";
import { uid } from "../common/util/uid";
import "./ha-tooltip";
@customElement("ha-label") @customElement("ha-label")
class HaLabel extends LitElement { class HaLabel extends LitElement {
@property({ type: Boolean, reflect: true }) dense = false; @property({ type: Boolean, reflect: true }) dense = false;
@property({ attribute: "description" })
public description?: string;
private _elementId = "label-" + uid();
protected render(): TemplateResult { protected render(): TemplateResult {
return html` return html`
<ha-tooltip
.for=${this._elementId}
.disabled=${!this.description?.trim()}
>
${this.description}
</ha-tooltip>
<div class="container" .id=${this._elementId}>
<span class="content"> <span class="content">
<slot name="icon"></slot> <slot name="icon"></slot>
<slot></slot> <slot></slot>
</span> </span>
</div>
`; `;
} }
@@ -36,9 +51,7 @@ class HaLabel extends LitElement {
font-weight: var(--ha-font-weight-medium); font-weight: var(--ha-font-weight-medium);
line-height: var(--ha-line-height-condensed); line-height: var(--ha-line-height-condensed);
letter-spacing: 0.1px; letter-spacing: 0.1px;
vertical-align: middle;
height: 32px; height: 32px;
padding: 0 16px;
border-radius: var(--ha-border-radius-xl); border-radius: var(--ha-border-radius-xl);
color: var(--ha-label-text-color); color: var(--ha-label-text-color);
--mdc-icon-size: 12px; --mdc-icon-size: 12px;
@@ -66,15 +79,24 @@ class HaLabel extends LitElement {
display: flex; display: flex;
} }
.container {
display: flex;
position: relative;
height: 100%;
padding: 0 16px;
}
span { span {
display: inline-flex; display: inline-flex;
} }
:host([dense]) { :host([dense]) {
height: 20px; height: 20px;
padding: 0 12px;
border-radius: var(--ha-border-radius-md); border-radius: var(--ha-border-radius-md);
} }
:host([dense]) .container {
padding: 0 12px;
}
:host([dense]) ::slotted([slot="icon"]) { :host([dense]) ::slotted([slot="icon"]) {
margin-right: 4px; margin-right: 4px;
margin-left: -4px; margin-left: -4px;

View File

@@ -21,6 +21,7 @@ import "./chips/ha-input-chip";
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker"; import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
import "./ha-label-picker"; import "./ha-label-picker";
import type { HaLabelPicker } from "./ha-label-picker"; import type { HaLabelPicker } from "./ha-label-picker";
import "./ha-tooltip";
@customElement("ha-labels-picker") @customElement("ha-labels-picker")
export class HaLabelsPicker extends SubscribeMixin(LitElement) { export class HaLabelsPicker extends SubscribeMixin(LitElement) {
@@ -142,9 +143,17 @@ export class HaLabelsPicker extends SubscribeMixin(LitElement) {
const color = label?.color const color = label?.color
? computeCssColor(label.color) ? computeCssColor(label.color)
: undefined; : undefined;
const elementId = "label-" + label.label_id;
return html` return html`
<ha-tooltip
.for=${elementId}
.disabled=${!label?.description?.trim()}
>
${label?.description}
</ha-tooltip>
<ha-input-chip <ha-input-chip
.item=${label} .item=${label}
.id=${elementId}
@remove=${this._removeItem} @remove=${this._removeItem}
@click=${this._openDetail} @click=${this._openDetail}
.disabled=${this.disabled} .disabled=${this.disabled}

View File

@@ -125,9 +125,10 @@ export class HaLanguagePicker extends LitElement {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
popover-placement="bottom-end" popover-placement="bottom-end"
.notFoundLabel=${this.hass?.localize( .notFoundLabel=${this._notFoundLabel}
"ui.components.language-picker.no_match" .emptyLabel=${this.hass?.localize(
)} "ui.components.language-picker.no_languages"
) || "No languages available"}
.placeholder=${this.label ?? .placeholder=${this.label ??
(this.hass?.localize("ui.components.language-picker.language") || (this.hass?.localize("ui.components.language-picker.language") ||
"Language")} "Language")}
@@ -172,6 +173,15 @@ export class HaLanguagePicker extends LitElement {
this.value = ev.detail.value; this.value = ev.detail.value;
fireEvent(this, "value-changed", { value: this.value }); fireEvent(this, "value-changed", { value: this.value });
} }
private _notFoundLabel = (search: string) => {
const term = html`<b>${search}</b>`;
return this.hass
? this.hass.localize("ui.components.language-picker.no_match", {
term,
})
: html`No languages found for ${term}`;
};
} }
declare global { declare global {

View File

@@ -1,7 +1,8 @@
import { ListItemEl } from "@material/web/list/internal/listitem/list-item"; 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";
import { css } from "lit"; import { css, html, nothing, type TemplateResult } from "lit";
import { customElement } from "lit/decorators"; import { customElement } from "lit/decorators";
import "./ha-ripple";
export const haMdListStyles = [ export const haMdListStyles = [
styles, styles,
@@ -25,6 +26,18 @@ export const haMdListStyles = [
@customElement("ha-md-list-item") @customElement("ha-md-list-item")
export class HaMdListItem extends ListItemEl { export class HaMdListItem extends ListItemEl {
static override styles = haMdListStyles; static override styles = haMdListStyles;
protected renderRipple(): TemplateResult | typeof nothing {
if (this.type === "text") {
return nothing;
}
return html`<ha-ripple
part="ripple"
for="item"
?disabled=${this.disabled && this.type !== "link"}
></ha-ripple>`;
}
} }
declare global { declare global {

View File

@@ -1,6 +1,6 @@
import type { LitVirtualizer } from "@lit-labs/virtualizer"; import type { LitVirtualizer } from "@lit-labs/virtualizer";
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize"; import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import { mdiMagnify } from "@mdi/js"; import { mdiMagnify, mdiMinusBoxOutline } from "@mdi/js";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { import {
@@ -14,11 +14,12 @@ import memoizeOne from "memoize-one";
import { tinykeys } from "tinykeys"; import { tinykeys } from "tinykeys";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { caseInsensitiveStringCompare } from "../common/string/compare"; import { caseInsensitiveStringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { HaFuse } from "../resources/fuse"; import { HaFuse } from "../resources/fuse";
import { haStyleScrollbar } from "../resources/styles"; import { haStyleScrollbar } from "../resources/styles";
import { loadVirtualizer } from "../resources/virtualizer"; import { loadVirtualizer } from "../resources/virtualizer";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import "./chips/ha-chip-set";
import "./chips/ha-filter-chip";
import "./ha-combo-box-item"; import "./ha-combo-box-item";
import "./ha-icon"; import "./ha-icon";
import "./ha-textfield"; import "./ha-textfield";
@@ -27,28 +28,18 @@ import type { HaTextField } from "./ha-textfield";
export interface PickerComboBoxItem { export interface PickerComboBoxItem {
id: string; id: string;
primary: string; primary: string;
a11y_label?: string;
secondary?: string; secondary?: string;
search_labels?: string[]; search_labels?: string[];
sorting_label?: string; sorting_label?: string;
icon_path?: string; icon_path?: string;
icon?: string; icon?: string;
} }
const NO_ITEMS_AVAILABLE_ID = "___no_items_available___";
// Hack to force empty label to always display empty value by default in the search field
export interface PickerComboBoxItemWithLabel extends PickerComboBoxItem {
a11y_label: string;
}
const NO_MATCHING_ITEMS_FOUND_ID = "___no_matching_items_found___";
const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = ( const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = (
item item
) => html` ) => html`
<ha-combo-box-item <ha-combo-box-item type="button" compact>
.type=${item.id === NO_MATCHING_ITEMS_FOUND_ID ? "text" : "button"}
compact
>
${item.icon ${item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>` ? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: item.icon_path : item.icon_path
@@ -87,8 +78,11 @@ export class HaPickerComboBox extends LitElement {
@state() private _listScrolled = false; @state() private _listScrolled = false;
@property({ attribute: false, type: Array }) @property({ attribute: false })
public getItems?: () => PickerComboBoxItem[]; public getItems?: (
searchString?: string,
section?: string
) => (PickerComboBoxItem | string)[];
@property({ attribute: false, type: Array }) @property({ attribute: false, type: Array })
public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[]; public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[];
@@ -96,21 +90,45 @@ export class HaPickerComboBox extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public rowRenderer?: RenderItemFunction<PickerComboBoxItem>; public rowRenderer?: RenderItemFunction<PickerComboBoxItem>;
@property({ attribute: "not-found-label", type: String }) @property({ attribute: false })
public notFoundLabel?: string; public notFoundLabel?: string | ((search: string) => string);
@property({ attribute: "empty-label" })
public emptyLabel?: string;
@property({ attribute: false }) @property({ attribute: false })
public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>; public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>;
@property({ reflect: true }) public mode: "popover" | "dialog" = "popover"; @property({ reflect: true }) public mode: "popover" | "dialog" = "popover";
/** Section filter buttons for the list, section headers needs to be defined in getItems as strings */
@property({ attribute: false }) public sections?: (
| {
id: string;
label: string;
}
| "separator"
)[];
@property({ attribute: false }) public sectionTitleFunction?: (listInfo: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
itemsCount: number;
}) => string | undefined;
@property({ attribute: "selected-section" }) public selectedSection?: string;
@query("lit-virtualizer") private _virtualizerElement?: LitVirtualizer; @query("lit-virtualizer") private _virtualizerElement?: LitVirtualizer;
@query("ha-textfield") private _searchFieldElement?: HaTextField; @query("ha-textfield") private _searchFieldElement?: HaTextField;
@state() private _items: PickerComboBoxItemWithLabel[] = []; @state() private _items: (PickerComboBoxItem | string)[] = [];
private _allItems: PickerComboBoxItemWithLabel[] = []; @state() private _sectionTitle?: string;
private _allItems: (PickerComboBoxItem | string)[] = [];
private _selectedItemIndex = -1; private _selectedItemIndex = -1;
@@ -121,6 +139,8 @@ export class HaPickerComboBox extends LitElement {
private _removeKeyboardShortcuts?: () => void; private _removeKeyboardShortcuts?: () => void;
private _search = "";
protected firstUpdated() { protected firstUpdated() {
this._registerKeyboardShortcuts(); this._registerKeyboardShortcuts();
} }
@@ -145,74 +165,142 @@ export class HaPickerComboBox extends LitElement {
"Search"} "Search"}
@input=${this._filterChanged} @input=${this._filterChanged}
></ha-textfield> ></ha-textfield>
${this._renderSectionButtons()}
${this.sections?.length
? html`
<div class="section-title-wrapper">
<div
class="section-title ${!this.selectedSection &&
this._sectionTitle
? "show"
: ""}"
>
${this._sectionTitle}
</div>
</div>
`
: nothing}
<lit-virtualizer <lit-virtualizer
@scroll=${this._onScrollList} .keyFunction=${this._keyFunction}
tabindex="0" tabindex="0"
scroller scroller
.items=${this._items} .items=${this._items}
.renderItem=${this._renderItem} .renderItem=${this._renderItem}
style="min-height: 36px;" style="min-height: 36px;"
class=${this._listScrolled ? "scrolled" : ""} class=${this._listScrolled ? "scrolled" : ""}
@scroll=${this._onScrollList}
@focus=${this._focusList} @focus=${this._focusList}
@visibilityChanged=${this._visibilityChanged}
> >
</lit-virtualizer> `; </lit-virtualizer> `;
} }
private _defaultNotFoundItem = memoizeOne( private _renderSectionButtons() {
( if (!this.sections || this.sections.length === 0) {
label: this["notFoundLabel"], return nothing;
localize?: LocalizeFunc }
): PickerComboBoxItemWithLabel => ({
id: NO_MATCHING_ITEMS_FOUND_ID,
primary:
label ||
(localize && localize("ui.components.combo-box.no_match")) ||
"No matching items found",
icon_path: mdiMagnify,
a11y_label:
label ||
(localize && localize("ui.components.combo-box.no_match")) ||
"No matching items found",
})
);
private _getAdditionalItems = (searchString?: string) => { return html`
const items = this.getAdditionalItems?.(searchString) || []; <ha-chip-set class="sections">
${this.sections.map((section) =>
section === "separator"
? html`<div class="separator"></div>`
: html`<ha-filter-chip
@click=${this._toggleSection}
.section-id=${section.id}
.selected=${this.selectedSection === section.id}
.label=${section.label}
>
</ha-filter-chip>`
)}
</ha-chip-set>
`;
}
return items.map<PickerComboBoxItemWithLabel>((item) => ({ @eventOptions({ passive: true })
...item, private _visibilityChanged(ev) {
a11y_label: item.a11y_label || item.primary, if (
})); this._virtualizerElement &&
}; this.sectionTitleFunction &&
this.sections?.length
) {
const firstItem = this._virtualizerElement.items[ev.first];
const secondItem = this._virtualizerElement.items[ev.first + 1];
this._sectionTitle = this.sectionTitleFunction({
firstIndex: ev.first,
lastIndex: ev.last,
firstItem: firstItem as PickerComboBoxItem | string,
secondItem: secondItem as PickerComboBoxItem | string,
itemsCount: this._virtualizerElement.items.length,
});
}
}
private _getItems = (): PickerComboBoxItemWithLabel[] => { private _getAdditionalItems = (searchString?: string) =>
const items = this.getItems ? this.getItems() : []; this.getAdditionalItems?.(searchString) || [];
const sortedItems = items private _getItems = () => {
.map<PickerComboBoxItemWithLabel>((item) => ({ let items = [
...item, ...(this.getItems
a11y_label: item.a11y_label || item.primary, ? this.getItems(this._search, this.selectedSection)
})) : []),
.sort((entityA, entityB) => ];
if (!this.sections?.length) {
items = items.sort((entityA, entityB) =>
caseInsensitiveStringCompare( caseInsensitiveStringCompare(
entityA.sorting_label!, (entityA as PickerComboBoxItem).sorting_label!,
entityB.sorting_label!, (entityB as PickerComboBoxItem).sorting_label!,
this.hass?.locale.language ?? navigator.language this.hass?.locale.language ?? navigator.language
) )
); );
}
if (!sortedItems.length) { if (!items.length) {
sortedItems.push( items.push(NO_ITEMS_AVAILABLE_ID);
this._defaultNotFoundItem(this.notFoundLabel, this.hass?.localize)
);
} }
const additionalItems = this._getAdditionalItems(); const additionalItems = this._getAdditionalItems();
sortedItems.push(...additionalItems); items.push(...additionalItems);
return sortedItems;
if (this.mode === "dialog") {
items.push("padding"); // padding for safe area inset
}
return items;
}; };
private _renderItem = (item: PickerComboBoxItem, index: number) => { private _renderItem = (item: PickerComboBoxItem | string, index: number) => {
if (item === "padding") {
return html`<div class="bottom-padding"></div>`;
}
if (item === NO_ITEMS_AVAILABLE_ID) {
return html`
<div class="combo-box-row">
<ha-combo-box-item type="text" compact>
<ha-svg-icon
slot="start"
.path=${this._search ? mdiMagnify : mdiMinusBoxOutline}
></ha-svg-icon>
<span slot="headline"
>${this._search
? typeof this.notFoundLabel === "function"
? this.notFoundLabel(this._search)
: this.notFoundLabel ||
this.hass?.localize("ui.components.combo-box.no_match") ||
"No matching items found"
: this.emptyLabel ||
this.hass?.localize("ui.components.combo-box.no_items") ||
"No items available"}</span
>
</ha-combo-box-item>
</div>
`;
}
if (typeof item === "string") {
return html`<div class="title">${item}</div>`;
}
const renderer = this.rowRenderer || DEFAULT_ROW_RENDERER; const renderer = this.rowRenderer || DEFAULT_ROW_RENDERER;
return html`<div return html`<div
id=${`list-item-${index}`} id=${`list-item-${index}`}
@@ -221,9 +309,7 @@ export class HaPickerComboBox extends LitElement {
.index=${index} .index=${index}
@click=${this._valueSelected} @click=${this._valueSelected}
> >
${item.id === NO_MATCHING_ITEMS_FOUND_ID ${renderer(item, index)}
? DEFAULT_ROW_RENDERER(item, index)
: renderer(item, index)}
</div>`; </div>`;
}; };
@@ -242,10 +328,6 @@ export class HaPickerComboBox extends LitElement {
const value = (ev.currentTarget as any).value as string; const value = (ev.currentTarget as any).value as string;
const newValue = value?.trim(); const newValue = value?.trim();
if (newValue === NO_MATCHING_ITEMS_FOUND_ID) {
return;
}
fireEvent(this, "value-changed", { value: newValue }); fireEvent(this, "value-changed", { value: newValue });
}; };
@@ -256,15 +338,19 @@ export class HaPickerComboBox extends LitElement {
private _filterChanged = (ev: Event) => { private _filterChanged = (ev: Event) => {
const textfield = ev.target as HaTextField; const textfield = ev.target as HaTextField;
const searchString = textfield.value.trim(); const searchString = textfield.value.trim();
this._search = searchString;
if (this.sections?.length) {
this._items = this._getItems();
} else {
if (!searchString) { if (!searchString) {
this._items = this._allItems; this._items = this._allItems;
return; return;
} }
const index = this._fuseIndex(this._allItems); const index = this._fuseIndex(this._allItems as PickerComboBoxItem[]);
const fuse = new HaFuse( const fuse = new HaFuse(
this._allItems, this._allItems as PickerComboBoxItem[],
{ {
shouldSort: false, shouldSort: false,
minMatchCharLength: Math.min(searchString.length, 2), minMatchCharLength: Math.min(searchString.length, 2),
@@ -273,34 +359,62 @@ export class HaPickerComboBox extends LitElement {
); );
const results = fuse.multiTermsSearch(searchString); const results = fuse.multiTermsSearch(searchString);
let filteredItems = this._allItems as PickerComboBoxItem[]; let filteredItems = [...this._allItems];
if (results) { if (results) {
const items = results.map((result) => result.item); const items: (PickerComboBoxItem | string)[] = results.map(
if (items.length === 0) { (result) => result.item
items.push(
this._defaultNotFoundItem(this.notFoundLabel, this.hass?.localize)
); );
if (!items.length) {
filteredItems.push(NO_ITEMS_AVAILABLE_ID);
} }
const additionalItems = this._getAdditionalItems(searchString);
const additionalItems = this._getAdditionalItems();
items.push(...additionalItems); items.push(...additionalItems);
filteredItems = items; filteredItems = items;
} }
if (this.searchFn) { if (this.searchFn) {
filteredItems = this.searchFn( filteredItems = this.searchFn(
searchString, searchString,
filteredItems, filteredItems as PickerComboBoxItem[],
this._allItems this._allItems as PickerComboBoxItem[]
); );
} }
this._items = filteredItems as PickerComboBoxItemWithLabel[]; this._items = filteredItems as PickerComboBoxItem[];
}
this._selectedItemIndex = -1; this._selectedItemIndex = -1;
if (this._virtualizerElement) { if (this._virtualizerElement) {
this._virtualizerElement.scrollTo(0, 0); this._virtualizerElement.scrollTo(0, 0);
} }
}; };
private _toggleSection(ev: Event) {
ev.stopPropagation();
this._resetSelectedItem();
this._sectionTitle = undefined;
const section = (ev.target as HTMLElement)["section-id"] as string;
if (!section) {
return;
}
if (this.selectedSection === section) {
this.selectedSection = undefined;
} else {
this.selectedSection = section;
}
this._items = this._getItems();
// Reset scroll position when filter changes
if (this._virtualizerElement) {
this._virtualizerElement.scrollToIndex(0);
}
}
private _registerKeyboardShortcuts() { private _registerKeyboardShortcuts() {
this._removeKeyboardShortcuts = tinykeys(this, { this._removeKeyboardShortcuts = tinykeys(this, {
ArrowUp: this._selectPreviousItem, ArrowUp: this._selectPreviousItem,
@@ -344,7 +458,7 @@ export class HaPickerComboBox extends LitElement {
return; return;
} }
if (items[nextIndex].id === NO_MATCHING_ITEMS_FOUND_ID) { if (typeof items[nextIndex] === "string") {
// Skip titles, padding and empty search // Skip titles, padding and empty search
if (nextIndex === maxItems) { if (nextIndex === maxItems) {
return; return;
@@ -373,7 +487,7 @@ export class HaPickerComboBox extends LitElement {
return; return;
} }
if (items[nextIndex]?.id === NO_MATCHING_ITEMS_FOUND_ID) { if (typeof items[nextIndex] === "string") {
// Skip titles, padding and empty search // Skip titles, padding and empty search
if (nextIndex === 0) { if (nextIndex === 0) {
return; return;
@@ -395,13 +509,6 @@ export class HaPickerComboBox extends LitElement {
const nextIndex = 0; const nextIndex = 0;
if (
(this._virtualizerElement.items[nextIndex] as PickerComboBoxItem)?.id ===
NO_MATCHING_ITEMS_FOUND_ID
) {
return;
}
if (typeof this._virtualizerElement.items[nextIndex] === "string") { if (typeof this._virtualizerElement.items[nextIndex] === "string") {
this._selectedItemIndex = nextIndex + 1; this._selectedItemIndex = nextIndex + 1;
} else { } else {
@@ -419,13 +526,6 @@ export class HaPickerComboBox extends LitElement {
const nextIndex = this._virtualizerElement.items.length - 1; const nextIndex = this._virtualizerElement.items.length - 1;
if (
(this._virtualizerElement.items[nextIndex] as PickerComboBoxItem)?.id ===
NO_MATCHING_ITEMS_FOUND_ID
) {
return;
}
if (typeof this._virtualizerElement.items[nextIndex] === "string") { if (typeof this._virtualizerElement.items[nextIndex] === "string") {
this._selectedItemIndex = nextIndex - 1; this._selectedItemIndex = nextIndex - 1;
} else { } else {
@@ -453,10 +553,7 @@ export class HaPickerComboBox extends LitElement {
ev.stopPropagation(); ev.stopPropagation();
const firstItem = this._virtualizerElement?.items[0] as PickerComboBoxItem; const firstItem = this._virtualizerElement?.items[0] as PickerComboBoxItem;
if ( if (this._virtualizerElement?.items.length === 1) {
this._virtualizerElement?.items.length === 1 &&
firstItem.id !== NO_MATCHING_ITEMS_FOUND_ID
) {
fireEvent(this, "value-changed", { fireEvent(this, "value-changed", {
value: firstItem.id, value: firstItem.id,
}); });
@@ -472,7 +569,7 @@ export class HaPickerComboBox extends LitElement {
const item = this._virtualizerElement?.items[ const item = this._virtualizerElement?.items[
this._selectedItemIndex this._selectedItemIndex
] as PickerComboBoxItem; ] as PickerComboBoxItem;
if (item && item.id !== NO_MATCHING_ITEMS_FOUND_ID) { if (item) {
fireEvent(this, "value-changed", { value: item.id }); fireEvent(this, "value-changed", { value: item.id });
} }
}; };
@@ -484,6 +581,9 @@ export class HaPickerComboBox extends LitElement {
this._selectedItemIndex = -1; this._selectedItemIndex = -1;
} }
private _keyFunction = (item: PickerComboBoxItem | string) =>
typeof item === "string" ? item : item.id;
static styles = [ static styles = [
haStyleScrollbar, haStyleScrollbar,
css` css`
@@ -558,6 +658,80 @@ export class HaPickerComboBox extends LitElement {
background-color: var(--ha-color-fill-neutral-normal-hover); background-color: var(--ha-color-fill-neutral-normal-hover);
} }
} }
.sections {
display: flex;
flex-wrap: nowrap;
gap: var(--ha-space-2);
padding: var(--ha-space-3) var(--ha-space-3);
overflow: auto;
}
:host([mode="dialog"]) .sections {
padding: var(--ha-space-3) var(--ha-space-4);
}
.sections ha-filter-chip {
flex-shrink: 0;
--md-filter-chip-selected-container-color: var(
--ha-color-fill-primary-normal-hover
);
color: var(--primary-color);
}
.sections .separator {
height: var(--ha-space-8);
width: 0;
border: 1px solid var(--ha-color-border-neutral-quiet);
}
.section-title,
.title {
background-color: var(--ha-color-fill-neutral-quiet-resting);
padding: var(--ha-space-1) var(--ha-space-2);
font-weight: var(--ha-font-weight-bold);
color: var(--secondary-text-color);
min-height: var(--ha-space-6);
display: flex;
align-items: center;
}
.title {
width: 100%;
}
:host([mode="dialog"]) .title {
padding: var(--ha-space-1) var(--ha-space-4);
}
:host([mode="dialog"]) ha-textfield {
padding: 0 var(--ha-space-4);
}
.section-title-wrapper {
height: 0;
position: relative;
}
.section-title {
opacity: 0;
position: absolute;
top: 1px;
width: calc(100% - var(--ha-space-8));
}
.section-title.show {
opacity: 1;
z-index: 1;
}
.empty-search {
display: flex;
width: 100%;
flex-direction: column;
align-items: center;
padding: var(--ha-space-3);
}
`, `,
]; ];
} }

View File

@@ -157,7 +157,9 @@ export const computePanels = memoizeOne(
Object.values(panels).forEach((panel) => { Object.values(panels).forEach((panel) => {
if ( if (
hiddenPanels.includes(panel.url_path) || hiddenPanels.includes(panel.url_path) ||
(!panel.title && panel.url_path !== defaultPanel) (!panel.title && panel.url_path !== defaultPanel) ||
(panel.default_visible === false &&
!panelsOrder.includes(panel.url_path))
) { ) {
return; return;
} }

View File

@@ -1,15 +1,31 @@
import "@home-assistant/webawesome/dist/components/popover/popover"; import "@home-assistant/webawesome/dist/components/popover/popover";
import { consume } from "@lit/context";
// @ts-ignore // @ts-ignore
import chipStyles from "@material/chips/dist/mdc.chips.min.css"; import chipStyles from "@material/chips/dist/mdc.chips.min.css";
import { mdiPlaylistPlus } from "@mdi/js"; import { mdiPlus, mdiTextureBox } from "@mdi/js";
import Fuse from "fuse.js";
import type { HassServiceTarget } from "home-assistant-js-websocket"; import type { HassServiceTarget } from "home-assistant-js-websocket";
import type { CSSResultGroup } from "lit"; import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing, unsafeCSS } from "lit"; import { LitElement, css, html, nothing, unsafeCSS } from "lit";
import { customElement, property, query, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { ensureArray } from "../common/array/ensure-array"; import { ensureArray } from "../common/array/ensure-array";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { isValidEntityId } from "../common/entity/valid_entity_id"; import { isValidEntityId } from "../common/entity/valid_entity_id";
import { computeRTL } from "../common/util/compute_rtl";
import {
getAreasAndFloors,
type AreaFloorValue,
type FloorComboBoxItem,
} from "../data/area_floor";
import { getConfigEntries, type ConfigEntry } from "../data/config_entries";
import { labelsContext } from "../data/context";
import { getDevices, type DevicePickerItem } from "../data/device_registry";
import type { HaEntityPickerEntityFilterFunc } from "../data/entity"; import type { HaEntityPickerEntityFilterFunc } from "../data/entity";
import { getEntities, type EntityComboBoxItem } from "../data/entity_registry";
import { domainToName } from "../data/integration";
import { getLabels, type LabelRegistryEntry } from "../data/label_registry";
import { import {
areaMeetsFilter, areaMeetsFilter,
deviceMeetsFilter, deviceMeetsFilter,
@@ -18,18 +34,23 @@ import {
type TargetTypeFloorless, type TargetTypeFloorless,
} from "../data/target"; } from "../data/target";
import { SubscribeMixin } from "../mixins/subscribe-mixin"; import { SubscribeMixin } from "../mixins/subscribe-mixin";
import { isHelperDomain } from "../panels/config/helpers/const";
import { showHelperDetailDialog } from "../panels/config/helpers/show-dialog-helper-detail"; import { showHelperDetailDialog } from "../panels/config/helpers/show-dialog-helper-detail";
import { HaFuse } from "../resources/fuse";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import { brandsUrl } from "../util/brands-url";
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker"; import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
import "./ha-bottom-sheet"; import "./ha-generic-picker";
import "./ha-button"; import type { PickerComboBoxItem } from "./ha-picker-combo-box";
import "./ha-input-helper-text";
import "./ha-svg-icon"; import "./ha-svg-icon";
import "./ha-tree-indicator";
import "./target-picker/ha-target-picker-item-group"; import "./target-picker/ha-target-picker-item-group";
import "./target-picker/ha-target-picker-selector";
import type { HaTargetPickerSelector } from "./target-picker/ha-target-picker-selector";
import "./target-picker/ha-target-picker-value-chip"; import "./target-picker/ha-target-picker-value-chip";
const EMPTY_SEARCH = "___EMPTY_SEARCH___";
const SEPARATOR = "________";
const CREATE_ID = "___create-new-entity___";
@customElement("ha-target-picker") @customElement("ha-target-picker")
export class HaTargetPicker extends SubscribeMixin(LitElement) { export class HaTargetPicker extends SubscribeMixin(LitElement) {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@@ -68,23 +89,54 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
@property({ attribute: "add-on-top", type: Boolean }) public addOnTop = false; @property({ attribute: "add-on-top", type: Boolean }) public addOnTop = false;
@state() private _open = false; @state() private _selectedSection?: TargetTypeFloorless;
@state() private _addTargetWidth = 0; @state() private _configEntryLookup: Record<string, ConfigEntry> = {};
@state() private _narrow = false; @state()
@consume({ context: labelsContext, subscribe: true })
@state() private _pickerFilter?: TargetTypeFloorless; private _labelRegistry!: LabelRegistryEntry[];
@state() private _pickerWrapperOpen = false;
@query(".add-target-wrapper") private _addTargetWrapper?: HTMLDivElement;
@query("ha-target-picker-selector")
private _targetPickerSelectorElement?: HaTargetPickerSelector;
private _newTarget?: { type: TargetType; id: string }; private _newTarget?: { type: TargetType; id: string };
private _getDevicesMemoized = memoizeOne(getDevices);
private _getLabelsMemoized = memoizeOne(getLabels);
private _getEntitiesMemoized = memoizeOne(getEntities);
private _getAreasAndFloorsMemoized = memoizeOne(getAreasAndFloors);
private get _showEntityId() {
return this.hass.userData?.showEntityIdPicker;
}
private _fuseIndexes = {
area: memoizeOne((states: FloorComboBoxItem[]) =>
this._createFuseIndex(states)
),
entity: memoizeOne((states: EntityComboBoxItem[]) =>
this._createFuseIndex(states)
),
device: memoizeOne((states: DevicePickerItem[]) =>
this._createFuseIndex(states)
),
label: memoizeOne((states: PickerComboBoxItem[]) =>
this._createFuseIndex(states)
),
};
public willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this._loadConfigEntries();
}
}
private _createFuseIndex = (states) =>
Fuse.createIndex(["search_labels"], states);
protected render() { protected render() {
if (this.addOnTop) { if (this.addOnTop) {
return html` ${this._renderPicker()} ${this._renderItems()} `; return html` ${this._renderPicker()} ${this._renderItems()} `;
@@ -289,139 +341,65 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
} }
private _renderPicker() { private _renderPicker() {
const sections = [
{
id: "entity",
label: this.hass.localize("ui.components.target-picker.type.entities"),
},
{
id: "device",
label: this.hass.localize("ui.components.target-picker.type.devices"),
},
{
id: "area",
label: this.hass.localize("ui.components.target-picker.type.areas"),
},
"separator" as const,
{
id: "label",
label: this.hass.localize("ui.components.target-picker.type.labels"),
},
];
return html` return html`
<div class="add-target-wrapper"> <div class="add-target-wrapper">
<ha-button <ha-generic-picker
id="add-target-button"
size="small"
appearance="filled"
@click=${this._showPicker}
>
<ha-svg-icon .path=${mdiPlaylistPlus} slot="start"></ha-svg-icon>
${this.hass.localize("ui.components.target-picker.add_target")}
</ha-button>
${!this._narrow && (this._pickerWrapperOpen || this._open)
? html`
<wa-popover
.open=${this._pickerWrapperOpen}
style="--body-width: ${this._addTargetWidth}px;"
without-arrow
distance="-4"
placement="bottom-start"
for="add-target-button"
auto-size="vertical"
auto-size-padding="16"
@wa-after-show=${this._showSelector}
@wa-after-hide=${this._hidePicker}
trap-focus
role="dialog"
aria-modal="true"
aria-label=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
>
${this._renderTargetSelector()}
</wa-popover>
`
: this._pickerWrapperOpen || this._open
? html`<ha-bottom-sheet
flexcontent
.open=${this._pickerWrapperOpen}
@wa-after-show=${this._showSelector}
@closed=${this._hidePicker}
role="dialog"
aria-modal="true"
aria-label=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
>
${this._renderTargetSelector(true)}
</ha-bottom-sheet>`
: nothing}
</div>
${this.helper
? html`<ha-input-helper-text .disabled=${this.disabled}
>${this.helper}</ha-input-helper-text
>`
: nothing}
`;
}
connectedCallback() {
super.connectedCallback();
this._handleResize();
window.addEventListener("resize", this._handleResize);
}
public disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener("resize", this._handleResize);
}
private _handleResize = () => {
this._narrow =
window.matchMedia("(max-width: 870px)").matches ||
window.matchMedia("(max-height: 500px)").matches;
};
private _showPicker() {
this._addTargetWidth = this._addTargetWrapper?.offsetWidth || 0;
this._pickerWrapperOpen = true;
}
// wait for drawer animation to finish
private _showSelector = () => {
this._open = true;
requestAnimationFrame(() => {
this._targetPickerSelectorElement?.focus();
});
};
private _handleUpdatePickerFilter(
ev: CustomEvent<TargetTypeFloorless | undefined>
) {
this._updatePickerFilter(
typeof ev.detail === "string" ? ev.detail : undefined
);
}
private _updatePickerFilter = (filter?: TargetTypeFloorless) => {
this._pickerFilter = filter;
};
private _hidePicker(ev) {
ev.stopPropagation();
this._open = false;
this._pickerWrapperOpen = false;
if (this._newTarget) {
this._addTarget(this._newTarget.id, this._newTarget.type);
this._newTarget = undefined;
}
}
private _renderTargetSelector(dialogMode = false) {
if (!this._open) {
return nothing;
}
return html`
<ha-target-picker-selector
.hass=${this.hass} .hass=${this.hass}
@filter-type-changed=${this._handleUpdatePickerFilter} .disabled=${this.disabled}
.filterType=${this._pickerFilter} .autofocus=${this.autofocus}
@target-picked=${this._handleTargetPicked} .helper=${this.helper}
@create-domain-picked=${this._handleCreateDomain} .sections=${sections}
.targetValue=${this.value} .notFoundLabel=${this._noTargetFoundLabel}
.deviceFilter=${this.deviceFilter} .emptyLabel=${this.hass.localize(
.entityFilter=${this.entityFilter} "ui.components.target-picker.no_targets"
.includeDomains=${this.includeDomains} )}
.includeDeviceClasses=${this.includeDeviceClasses} .sectionTitleFunction=${this._sectionTitleFunction}
.createDomains=${this.createDomains} .selectedSection=${this._selectedSection}
.mode=${dialogMode ? "dialog" : "popover"} .rowRenderer=${this._renderRow}
></ha-target-picker-selector> .getItems=${this._getItems}
@value-changed=${this._targetPicked}
.addButtonLabel=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
.getAdditionalItems=${this._getAdditionalItems}
>
</ha-generic-picker>
</div>
`; `;
} }
private _targetPicked(ev: CustomEvent<{ value: string }>) {
ev.stopPropagation();
const value = ev.detail.value;
if (value.startsWith(CREATE_ID)) {
this._createNewDomainElement(value.substring(CREATE_ID.length));
return;
}
const [type, id] = ev.detail.value.split(SEPARATOR);
this._addTarget(id, type as TargetType);
}
private _addTarget(id: string, type: TargetType) { private _addTarget(id: string, type: TargetType) {
const typeId = `${type}_id`; const typeId = `${type}_id`;
@@ -454,26 +432,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
?.removeAttribute("collapsed"); ?.removeAttribute("collapsed");
} }
private _handleTargetPicked = async ( private _createNewDomainElement = (domain: string) => {
ev: CustomEvent<{ type: TargetType; id: string }>
) => {
ev.stopPropagation();
this._pickerWrapperOpen = false;
if (!ev.detail.type || !ev.detail.id) {
return;
}
// save new target temporarily to add it after dialog closes
this._newTarget = ev.detail;
};
private _handleCreateDomain = (ev: CustomEvent<string>) => {
this._pickerWrapperOpen = false;
const domain = ev.detail;
showHelperDetailDialog(this, { showHelperDetailDialog(this, {
domain, domain,
dialogClosedCallback: (item) => { dialogClosedCallback: (item) => {
@@ -675,6 +634,459 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
return undefined; return undefined;
} }
private _getRowType = (
item:
| PickerComboBoxItem
| (FloorComboBoxItem & { last?: boolean | undefined })
| EntityComboBoxItem
| DevicePickerItem
) => {
if (
(item as FloorComboBoxItem).type === "area" ||
(item as FloorComboBoxItem).type === "floor"
) {
return (item as FloorComboBoxItem).type;
}
if ("domain" in item) {
return "device";
}
if ("stateObj" in item) {
return "entity";
}
if (item.id === EMPTY_SEARCH) {
return "empty";
}
return "label";
};
private _sectionTitleFunction = ({
firstIndex,
lastIndex,
firstItem,
secondItem,
itemsCount,
}: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
itemsCount: number;
}) => {
if (
firstItem === undefined ||
secondItem === undefined ||
typeof firstItem === "string" ||
(typeof secondItem === "string" && secondItem !== "padding") ||
(firstIndex === 0 && lastIndex === itemsCount - 1)
) {
return undefined;
}
const type = this._getRowType(firstItem as PickerComboBoxItem);
const translationType:
| "areas"
| "entities"
| "devices"
| "labels"
| undefined =
type === "area" || type === "floor"
? "areas"
: type === "entity"
? "entities"
: type && type !== "empty"
? `${type}s`
: undefined;
return translationType
? this.hass.localize(
`ui.components.target-picker.type.${translationType}`
)
: undefined;
};
private _getItems = (searchString: string, section: string) => {
this._selectedSection = section as TargetTypeFloorless | undefined;
return this._getItemsMemoized(
this.hass.localize,
this.entityFilter,
this.deviceFilter,
this.includeDomains,
this.includeDeviceClasses,
this.value,
searchString,
this._configEntryLookup,
this._selectedSection
);
};
private _getItemsMemoized = memoizeOne(
(
localize: HomeAssistant["localize"],
entityFilter: this["entityFilter"],
deviceFilter: this["deviceFilter"],
includeDomains: this["includeDomains"],
includeDeviceClasses: this["includeDeviceClasses"],
targetValue: this["value"],
searchTerm: string,
configEntryLookup: Record<string, ConfigEntry>,
filterType?: TargetTypeFloorless
) => {
const items: (
| string
| FloorComboBoxItem
| EntityComboBoxItem
| PickerComboBoxItem
)[] = [];
if (!filterType || filterType === "entity") {
let entityItems = this._getEntitiesMemoized(
this.hass,
includeDomains,
undefined,
entityFilter,
includeDeviceClasses,
undefined,
undefined,
targetValue?.entity_id
? ensureArray(targetValue.entity_id)
: undefined,
undefined,
`entity${SEPARATOR}`
);
if (searchTerm) {
entityItems = this._filterGroup(
"entity",
entityItems,
searchTerm,
(item: EntityComboBoxItem) =>
item.stateObj?.entity_id === searchTerm
) as EntityComboBoxItem[];
}
if (!filterType && entityItems.length) {
// show group title
items.push(localize("ui.components.target-picker.type.entities"));
}
items.push(...entityItems);
}
if (!filterType || filterType === "device") {
let deviceItems = this._getDevicesMemoized(
this.hass,
configEntryLookup,
includeDomains,
undefined,
includeDeviceClasses,
deviceFilter,
entityFilter,
targetValue?.device_id
? ensureArray(targetValue.device_id)
: undefined,
undefined,
`device${SEPARATOR}`
);
if (searchTerm) {
deviceItems = this._filterGroup("device", deviceItems, searchTerm);
}
if (!filterType && deviceItems.length) {
// show group title
items.push(localize("ui.components.target-picker.type.devices"));
}
items.push(...deviceItems);
}
if (!filterType || filterType === "area") {
let areasAndFloors = this._getAreasAndFloorsMemoized(
this.hass.states,
this.hass.floors,
this.hass.areas,
this.hass.devices,
this.hass.entities,
memoizeOne((value: AreaFloorValue): string =>
[value.type, value.id].join(SEPARATOR)
),
includeDomains,
undefined,
includeDeviceClasses,
deviceFilter,
entityFilter,
targetValue?.area_id ? ensureArray(targetValue.area_id) : undefined,
targetValue?.floor_id ? ensureArray(targetValue.floor_id) : undefined
);
if (searchTerm) {
areasAndFloors = this._filterGroup(
"area",
areasAndFloors,
searchTerm
) as FloorComboBoxItem[];
}
if (!filterType && areasAndFloors.length) {
// show group title
items.push(localize("ui.components.target-picker.type.areas"));
}
items.push(
...areasAndFloors.map((item, index) => {
const nextItem = areasAndFloors[index + 1];
if (
!nextItem ||
(item.type === "area" && nextItem.type === "floor")
) {
return {
...item,
last: true,
};
}
return item;
})
);
}
if (!filterType || filterType === "label") {
let labels = this._getLabelsMemoized(
this.hass,
this._labelRegistry,
includeDomains,
undefined,
includeDeviceClasses,
deviceFilter,
entityFilter,
targetValue?.label_id ? ensureArray(targetValue.label_id) : undefined,
`label${SEPARATOR}`
);
if (searchTerm) {
labels = this._filterGroup("label", labels, searchTerm);
}
if (!filterType && labels.length) {
// show group title
items.push(localize("ui.components.target-picker.type.labels"));
}
items.push(...labels);
}
return items;
}
);
private _filterGroup(
type: TargetType,
items: (FloorComboBoxItem | PickerComboBoxItem | EntityComboBoxItem)[],
searchTerm: string,
checkExact?: (
item: FloorComboBoxItem | PickerComboBoxItem | EntityComboBoxItem
) => boolean
) {
const fuseIndex = this._fuseIndexes[type](items);
const fuse = new HaFuse(
items,
{
shouldSort: false,
minMatchCharLength: Math.min(searchTerm.length, 2),
},
fuseIndex
);
const results = fuse.multiTermsSearch(searchTerm);
let filteredItems = items;
if (results) {
filteredItems = results.map((result) => result.item);
}
if (!checkExact) {
return filteredItems;
}
// If there is exact match for entity id, put it first
const index = filteredItems.findIndex((item) => checkExact(item));
if (index === -1) {
return filteredItems;
}
const [exactMatch] = filteredItems.splice(index, 1);
filteredItems.unshift(exactMatch);
return filteredItems;
}
private _getAdditionalItems = () => this._getCreateItems(this.createDomains);
private _getCreateItems = memoizeOne(
(createDomains: this["createDomains"]) => {
if (!createDomains?.length) {
return [];
}
return createDomains.map((domain) => {
const primary = this.hass.localize(
"ui.components.entity.entity-picker.create_helper",
{
domain: isHelperDomain(domain)
? this.hass.localize(`ui.panel.config.helpers.types.${domain}`)
: domainToName(this.hass.localize, domain),
}
);
return {
id: CREATE_ID + domain,
primary: primary,
secondary: this.hass.localize(
"ui.components.entity.entity-picker.new_entity"
),
icon_path: mdiPlus,
} satisfies EntityComboBoxItem;
});
}
);
private async _loadConfigEntries() {
const configEntries = await getConfigEntries(this.hass);
this._configEntryLookup = Object.fromEntries(
configEntries.map((entry) => [entry.entry_id, entry])
);
}
private _renderRow = (
item:
| PickerComboBoxItem
| (FloorComboBoxItem & { last?: boolean | undefined })
| EntityComboBoxItem
| DevicePickerItem,
index: number
) => {
if (!item) {
return nothing;
}
const type = this._getRowType(item);
let hasFloor = false;
let rtl = false;
let showEntityId = false;
if (type === "area" || type === "floor") {
item.id = item[type]?.[`${type}_id`];
rtl = computeRTL(this.hass);
hasFloor =
type === "area" && !!(item as FloorComboBoxItem).area?.floor_id;
}
if (type === "entity") {
showEntityId = !!this._showEntityId;
}
return html`
<ha-combo-box-item
id=${`list-item-${index}`}
tabindex="-1"
.type=${type === "empty" ? "text" : "button"}
class=${type === "empty" ? "empty" : ""}
style=${(item as FloorComboBoxItem).type === "area" && hasFloor
? "--md-list-item-leading-space: var(--ha-space-12);"
: ""}
>
${(item as FloorComboBoxItem).type === "area" && hasFloor
? html`
<ha-tree-indicator
style=${styleMap({
width: "var(--ha-space-12)",
position: "absolute",
top: "var(--ha-space-0)",
left: rtl ? undefined : "var(--ha-space-1)",
right: rtl ? "var(--ha-space-1)" : undefined,
transform: rtl ? "scaleX(-1)" : "",
})}
.end=${(
item as FloorComboBoxItem & { last?: boolean | undefined }
).last}
slot="start"
></ha-tree-indicator>
`
: nothing}
${item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: item.icon_path
? html`<ha-svg-icon
slot="start"
.path=${item.icon_path}
></ha-svg-icon>`
: type === "entity" && (item as EntityComboBoxItem).stateObj
? html`
<state-badge
slot="start"
.stateObj=${(item as EntityComboBoxItem).stateObj}
.hass=${this.hass}
></state-badge>
`
: type === "device" && (item as DevicePickerItem).domain
? html`
<img
slot="start"
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl({
domain: (item as DevicePickerItem).domain!,
type: "icon",
darkOptimized: this.hass.themes.darkMode,
})}
/>
`
: type === "floor"
? html`<ha-floor-icon
slot="start"
.floor=${(item as FloorComboBoxItem).floor!}
></ha-floor-icon>`
: type === "area"
? html`<ha-svg-icon
slot="start"
.path=${item.icon_path || mdiTextureBox}
></ha-svg-icon>`
: nothing}
<span slot="headline">${item.primary}</span>
${item.secondary
? html`<span slot="supporting-text">${item.secondary}</span>`
: nothing}
${(item as EntityComboBoxItem).stateObj && showEntityId
? html`
<span slot="supporting-text" class="code">
${(item as EntityComboBoxItem).stateObj?.entity_id}
</span>
`
: nothing}
${(item as EntityComboBoxItem).domain_name &&
(type !== "entity" || !showEntityId)
? html`
<div slot="trailing-supporting-text" class="domain">
${(item as EntityComboBoxItem).domain_name}
</div>
`
: nothing}
</ha-combo-box-item>
`;
};
private _noTargetFoundLabel = (search: string) =>
this.hass.localize("ui.components.target-picker.no_target_found", {
term: html`<b>${search}</b>`,
});
static get styles(): CSSResultGroup { static get styles(): CSSResultGroup {
return css` return css`
.add-target-wrapper { .add-target-wrapper {
@@ -683,31 +1095,8 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
margin-top: var(--ha-space-3); margin-top: var(--ha-space-3);
} }
wa-popover { ha-generic-picker {
--wa-space-l: var(--ha-space-0); width: 100%;
}
wa-popover::part(body) {
width: min(max(var(--body-width), 336px), 600px);
max-width: min(max(var(--body-width), 336px), 600px);
max-height: 500px;
height: 70vh;
overflow: hidden;
}
@media (max-height: 1000px) {
wa-popover::part(body) {
max-height: 400px;
}
}
ha-bottom-sheet {
--ha-bottom-sheet-height: 90vh;
--ha-bottom-sheet-height: calc(100dvh - var(--ha-space-12));
--ha-bottom-sheet-max-height: var(--ha-bottom-sheet-height);
--ha-bottom-sheet-max-width: 600px;
--ha-bottom-sheet-padding: var(--ha-space-0);
--ha-bottom-sheet-surface-background: var(--card-background-color);
} }
${unsafeCSS(chipStyles)} ${unsafeCSS(chipStyles)}

View File

@@ -1,6 +1,4 @@
import "@home-assistant/webawesome/dist/components/dialog/dialog"; import { css, html, LitElement } from "lit";
import { mdiClose } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { import {
customElement, customElement,
eventOptions, eventOptions,
@@ -8,6 +6,9 @@ import {
query, query,
state, state,
} from "lit/decorators"; } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { mdiClose } from "@mdi/js";
import "@home-assistant/webawesome/dist/components/dialog/dialog";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { haStyleScrollbar } from "../resources/styles"; import { haStyleScrollbar } from "../resources/styles";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
@@ -31,6 +32,8 @@ export type DialogWidth = "small" | "medium" | "large" | "full";
* *
* @slot header - Replace the entire header area. * @slot header - Replace the entire header area.
* @slot headerNavigationIcon - Leading header action (e.g. close/back button). * @slot headerNavigationIcon - Leading header action (e.g. close/back button).
* @slot headerTitle - Custom title content (used when header-title is not set).
* @slot headerSubtitle - Custom subtitle content (used when header-subtitle is not set).
* @slot headerActionItems - Trailing header actions (e.g. buttons, menus). * @slot headerActionItems - Trailing header actions (e.g. buttons, menus).
* @slot - Dialog content body. * @slot - Dialog content body.
* @slot footer - Dialog footer content. * @slot footer - Dialog footer content.
@@ -52,8 +55,8 @@ export type DialogWidth = "small" | "medium" | "large" | "full";
* @attr {boolean} open - Controls the dialog open state. * @attr {boolean} open - Controls the dialog open state.
* @attr {("small"|"medium"|"large"|"full")} width - Preferred dialog width preset. Defaults to "medium". * @attr {("small"|"medium"|"large"|"full")} width - Preferred dialog width preset. Defaults to "medium".
* @attr {boolean} prevent-scrim-close - Prevents closing the dialog by clicking the scrim/overlay. Defaults to false. * @attr {boolean} prevent-scrim-close - Prevents closing the dialog by clicking the scrim/overlay. Defaults to false.
* @attr {string} header-title - Header title text when no custom title slot is provided. * @attr {string} header-title - Header title text. If not set, the headerTitle slot is used.
* @attr {string} header-subtitle - Header subtitle text when no custom subtitle slot is provided. * @attr {string} header-subtitle - Header subtitle text. If not set, the headerSubtitle slot is used.
* @attr {("above"|"below")} header-subtitle-position - Position of the subtitle relative to the title. Defaults to "below". * @attr {("above"|"below")} header-subtitle-position - Position of the subtitle relative to the title. Defaults to "below".
* @attr {boolean} flexcontent - Makes the dialog body a flex container for flexible layouts. * @attr {boolean} flexcontent - Makes the dialog body a flex container for flexible layouts.
* *
@@ -72,6 +75,12 @@ export type DialogWidth = "small" | "medium" | "large" | "full";
export class HaWaDialog extends LitElement { export class HaWaDialog extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: "aria-labelledby" })
public ariaLabelledBy?: string;
@property({ attribute: "aria-describedby" })
public ariaDescribedBy?: string;
@property({ type: Boolean, reflect: true }) @property({ type: Boolean, reflect: true })
public open = false; public open = false;
@@ -81,11 +90,11 @@ export class HaWaDialog extends LitElement {
@property({ type: Boolean, reflect: true, attribute: "prevent-scrim-close" }) @property({ type: Boolean, reflect: true, attribute: "prevent-scrim-close" })
public preventScrimClose = false; public preventScrimClose = false;
@property({ type: String, attribute: "header-title" }) @property({ attribute: "header-title" })
public headerTitle = ""; public headerTitle?: string;
@property({ type: String, attribute: "header-subtitle" }) @property({ attribute: "header-subtitle" })
public headerSubtitle = ""; public headerSubtitle?: string;
@property({ type: String, attribute: "header-subtitle-position" }) @property({ type: String, attribute: "header-subtitle-position" })
public headerSubtitlePosition: "above" | "below" = "below"; public headerSubtitlePosition: "above" | "below" = "below";
@@ -117,6 +126,11 @@ export class HaWaDialog extends LitElement {
.open=${this._open} .open=${this._open}
.lightDismiss=${!this.preventScrimClose} .lightDismiss=${!this.preventScrimClose}
without-header without-header
aria-labelledby=${ifDefined(
this.ariaLabelledBy ||
(this.headerTitle !== undefined ? "ha-wa-dialog-title" : undefined)
)}
aria-describedby=${ifDefined(this.ariaDescribedBy)}
@wa-show=${this._handleShow} @wa-show=${this._handleShow}
@wa-after-show=${this._handleAfterShow} @wa-after-show=${this._handleAfterShow}
@wa-after-hide=${this._handleAfterHide} @wa-after-hide=${this._handleAfterHide}
@@ -133,14 +147,14 @@ export class HaWaDialog extends LitElement {
.path=${mdiClose} .path=${mdiClose}
></ha-icon-button> ></ha-icon-button>
</slot> </slot>
${this.headerTitle ${this.headerTitle !== undefined
? html`<span slot="title" class="title"> ? html`<span slot="title" class="title" id="ha-wa-dialog-title">
${this.headerTitle} ${this.headerTitle}
</span>` </span>`
: nothing} : html`<slot name="headerTitle" slot="title"></slot>`}
${this.headerSubtitle ${this.headerSubtitle !== undefined
? html`<span slot="subtitle">${this.headerSubtitle}</span>` ? html`<span slot="subtitle">${this.headerSubtitle}</span>`
: nothing} : html`<slot name="headerSubtitle" slot="subtitle"></slot>`}
<slot name="headerActionItems" slot="actionItems"></slot> <slot name="headerActionItems" slot="actionItems"></slot>
</ha-dialog-header> </ha-dialog-header>
</slot> </slot>

View File

@@ -545,7 +545,7 @@ export class HaTargetPickerItemRow extends LitElement {
name: entityName || deviceName || item, name: entityName || deviceName || item,
context, context,
stateObject, stateObject,
notFound: !stateObject && item !== "all", notFound: !stateObject && item !== "all" && item !== "none",
}; };
} }

File diff suppressed because it is too large Load Diff

View File

@@ -128,9 +128,7 @@ class HaUserPicker extends LitElement {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this.hass.localize( .notFoundLabel=${this._notFoundLabel}
"ui.components.user-picker.no_match"
)}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.getItems=${this._getItems} .getItems=${this._getItems}
@@ -149,6 +147,11 @@ class HaUserPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.user-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -12,6 +12,7 @@ import { CONDITION_BUILDING_BLOCKS } from "./condition";
import type { DeviceCondition, DeviceTrigger } from "./device_automation"; import type { DeviceCondition, DeviceTrigger } from "./device_automation";
import type { Action, Field, MODES } from "./script"; import type { Action, Field, MODES } from "./script";
import { migrateAutomationAction } from "./script"; import { migrateAutomationAction } from "./script";
import type { WeekdayShort } from "../common/datetime/weekday";
export const AUTOMATION_DEFAULT_MODE: (typeof MODES)[number] = "single"; export const AUTOMATION_DEFAULT_MODE: (typeof MODES)[number] = "single";
export const AUTOMATION_DEFAULT_MAX = 10; export const AUTOMATION_DEFAULT_MAX = 10;
@@ -257,13 +258,11 @@ export interface ZoneCondition extends BaseCondition {
zone: string; zone: string;
} }
type Weekday = "sun" | "mon" | "tue" | "wed" | "thu" | "fri" | "sat";
export interface TimeCondition extends BaseCondition { export interface TimeCondition extends BaseCondition {
condition: "time"; condition: "time";
after?: string; after?: string;
before?: string; before?: string;
weekday?: Weekday | Weekday[]; weekday?: WeekdayShort | WeekdayShort[];
} }
export interface TemplateCondition extends BaseCondition { export interface TemplateCondition extends BaseCondition {

View File

@@ -186,7 +186,8 @@ export const getDevices = (
deviceFilter?: HaDevicePickerDeviceFilterFunc, deviceFilter?: HaDevicePickerDeviceFilterFunc,
entityFilter?: HaEntityPickerEntityFilterFunc, entityFilter?: HaEntityPickerEntityFilterFunc,
excludeDevices?: string[], excludeDevices?: string[],
value?: string value?: string,
idPrefix = ""
): DevicePickerItem[] => { ): DevicePickerItem[] => {
const devices = Object.values(hass.devices); const devices = Object.values(hass.devices);
const entities = Object.values(hass.entities); const entities = Object.values(hass.entities);
@@ -298,7 +299,7 @@ export const getDevices = (
const domainName = domain ? domainToName(hass.localize, domain) : undefined; const domainName = domain ? domainToName(hass.localize, domain) : undefined;
return { return {
id: device.id, id: `${idPrefix}${device.id}`,
label: "", label: "",
primary: primary:
deviceName || deviceName ||

View File

@@ -102,6 +102,7 @@ export type EnergySolarForecasts = Record<string, EnergySolarForecast>;
export interface DeviceConsumptionEnergyPreference { export interface DeviceConsumptionEnergyPreference {
// This is an ever increasing value // This is an ever increasing value
stat_consumption: string; stat_consumption: string;
stat_rate?: string;
name?: string; name?: string;
included_in_stat?: string; included_in_stat?: string;
} }
@@ -130,11 +131,17 @@ export interface FlowToGridSourceEnergyPreference {
number_energy_price: number | null; number_energy_price: number | null;
} }
export interface GridPowerSourceEnergyPreference {
// W meter
stat_rate: string;
}
export interface GridSourceTypeEnergyPreference { export interface GridSourceTypeEnergyPreference {
type: "grid"; type: "grid";
flow_from: FlowFromGridSourceEnergyPreference[]; flow_from: FlowFromGridSourceEnergyPreference[];
flow_to: FlowToGridSourceEnergyPreference[]; flow_to: FlowToGridSourceEnergyPreference[];
power?: GridPowerSourceEnergyPreference[];
cost_adjustment_day: number; cost_adjustment_day: number;
} }
@@ -143,6 +150,7 @@ export interface SolarSourceTypeEnergyPreference {
type: "solar"; type: "solar";
stat_energy_from: string; stat_energy_from: string;
stat_rate?: string;
config_entry_solar_forecast: string[] | null; config_entry_solar_forecast: string[] | null;
} }
@@ -150,6 +158,7 @@ export interface BatterySourceTypeEnergyPreference {
type: "battery"; type: "battery";
stat_energy_from: string; stat_energy_from: string;
stat_energy_to: string; stat_energy_to: string;
stat_rate?: string;
} }
export interface GasSourceTypeEnergyPreference { export interface GasSourceTypeEnergyPreference {
type: "gas"; type: "gas";

View File

@@ -344,7 +344,8 @@ export const getEntities = (
includeUnitOfMeasurement?: string[], includeUnitOfMeasurement?: string[],
includeEntities?: string[], includeEntities?: string[],
excludeEntities?: string[], excludeEntities?: string[],
value?: string value?: string,
idPrefix = ""
): EntityComboBoxItem[] => { ): EntityComboBoxItem[] => {
let items: EntityComboBoxItem[] = []; let items: EntityComboBoxItem[] = [];
@@ -395,10 +396,9 @@ export const getEntities = (
const secondary = [areaName, entityName ? deviceName : undefined] const secondary = [areaName, entityName ? deviceName : undefined]
.filter(Boolean) .filter(Boolean)
.join(isRTL ? " ◂ " : " ▸ "); .join(isRTL ? " ◂ " : " ▸ ");
const a11yLabel = [deviceName, entityName].filter(Boolean).join(" - ");
return { return {
id: entityId, id: `${idPrefix}${entityId}`,
primary: primary, primary: primary,
secondary: secondary, secondary: secondary,
domain_name: domainName, domain_name: domainName,
@@ -411,7 +411,6 @@ export const getEntities = (
friendlyName, friendlyName,
entityId, entityId,
].filter(Boolean) as string[], ].filter(Boolean) as string[],
a11y_label: a11yLabel,
stateObj: stateObj, stateObj: stateObj,
}; };
}); });

View File

@@ -108,7 +108,8 @@ export const getLabels = (
includeDeviceClasses?: string[], includeDeviceClasses?: string[],
deviceFilter?: HaDevicePickerDeviceFilterFunc, deviceFilter?: HaDevicePickerDeviceFilterFunc,
entityFilter?: HaEntityPickerEntityFilterFunc, entityFilter?: HaEntityPickerEntityFilterFunc,
excludeLabels?: string[] excludeLabels?: string[],
idPrefix = ""
): PickerComboBoxItem[] => { ): PickerComboBoxItem[] => {
if (!labels || labels.length === 0) { if (!labels || labels.length === 0) {
return []; return [];
@@ -262,7 +263,7 @@ export const getLabels = (
} }
const items = outputLabels.map<PickerComboBoxItem>((label) => ({ const items = outputLabels.map<PickerComboBoxItem>((label) => ({
id: label.label_id, id: `${idPrefix}${label.label_id}`,
primary: label.name, primary: label.name,
secondary: label.description ?? "", secondary: label.description ?? "",
icon: label.icon || undefined, icon: label.icon || undefined,

View File

@@ -222,6 +222,7 @@ export interface StopAction extends BaseAction {
export interface SequenceAction extends BaseAction { export interface SequenceAction extends BaseAction {
sequence: (ManualScriptConfig | Action)[]; sequence: (ManualScriptConfig | Action)[];
metadata?: {};
} }
export interface ParallelAction extends BaseAction { export interface ParallelAction extends BaseAction {
@@ -479,6 +480,7 @@ export const migrateAutomationAction = (
} }
if (typeof action === "object" && action !== null && "sequence" in action) { if (typeof action === "object" && action !== null && "sequence" in action) {
delete (action as SequenceAction).metadata;
for (const sequenceAction of (action as SequenceAction).sequence) { for (const sequenceAction of (action as SequenceAction).sequence) {
migrateAutomationAction(sequenceAction); migrateAutomationAction(sequenceAction);
} }

View File

@@ -102,6 +102,17 @@ class DialogEditSidebar extends LitElement {
this.hass.locale this.hass.locale
); );
// Add default hidden panels that are missing in hidden
for (const panel of panels) {
if (
panel.default_visible === false &&
!this._order.includes(panel.url_path) &&
!this._hidden.includes(panel.url_path)
) {
this._hidden.push(panel.url_path);
}
}
const items = [ const items = [
...beforeSpacer, ...beforeSpacer,
...panels.filter((panel) => this._hidden!.includes(panel.url_path)), ...panels.filter((panel) => this._hidden!.includes(panel.url_path)),

View File

@@ -20,6 +20,21 @@
<meta name="color-scheme" content="dark light" /> <meta name="color-scheme" content="dark light" />
<%= renderTemplate("_style_base.html.template") %> <%= renderTemplate("_style_base.html.template") %>
<style> <style>
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
::view-transition-group(launch-screen) {
animation-duration: var(--ha-animation-base-duration, 350ms);
animation-timing-function: ease-out;
}
::view-transition-old(launch-screen) {
animation: fade-out var(--ha-animation-base-duration, 350ms) ease-out;
}
html { html {
background-color: var(--primary-background-color, #fafafa); background-color: var(--primary-background-color, #fafafa);
color: var(--primary-text-color, #212121); color: var(--primary-text-color, #212121);
@@ -32,11 +47,29 @@
} }
} }
#ha-launch-screen { #ha-launch-screen {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
view-transition-name: launch-screen;
background-color: var(--primary-background-color, #fafafa);
z-index: 100;
}
@media (prefers-color-scheme: dark) {
/* body selector to avoid minification causing bad jinja2 */
body #ha-launch-screen {
background-color: var(--primary-background-color, #111111);
}
}
#ha-launch-screen.removing {
opacity: 0;
} }
#ha-launch-screen svg { #ha-launch-screen svg {
width: 112px; width: 112px;

View File

@@ -11,14 +11,10 @@ class HaInitPage extends LitElement {
@state() private _retryInSeconds = 60; @state() private _retryInSeconds = 60;
@state() private _loadingTimeout = false;
private _showProgressIndicatorTimeout?: number; private _showProgressIndicatorTimeout?: number;
private _retryInterval?: number; private _retryInterval?: number;
private _loadingTimeoutHandle?: number;
protected render() { protected render() {
return this.error return this.error
? html` ? html`
@@ -55,35 +51,8 @@ class HaInitPage extends LitElement {
The upgrade may need a long time to complete, please be The upgrade may need a long time to complete, please be
patient. patient.
` `
: this._loadingTimeout
? html`
<p>Loading is taking longer than expected.</p>
<p class="hint">
This could be caused by a slow connection or cached data.
</p>
`
: "Loading data"} : "Loading data"}
</div> </div>
${this._loadingTimeout && !this.migration
? html`
<div class="button-row">
<ha-button
size="small"
appearance="plain"
@click=${this._retry}
>
Retry now
</ha-button>
<ha-button
size="small"
appearance="plain"
@click=${this._clearCacheAndRetry}
>
Clear cache and retry
</ha-button>
</div>
`
: ""}
`; `;
} }
@@ -95,16 +64,10 @@ class HaInitPage extends LitElement {
if (this._retryInterval) { if (this._retryInterval) {
clearInterval(this._retryInterval); clearInterval(this._retryInterval);
} }
if (this._loadingTimeoutHandle) {
clearTimeout(this._loadingTimeoutHandle);
}
} }
protected willUpdate(changedProperties: PropertyValues<this>) { protected willUpdate(changedProperties: PropertyValues<this>) {
if ( if (changedProperties.has("error") && this.error) {
(changedProperties.has("error") && this.error) ||
(changedProperties.has("_loadingTimeout") && this._loadingTimeout)
) {
import("../components/ha-button"); import("../components/ha-button");
} }
} }
@@ -114,8 +77,6 @@ class HaInitPage extends LitElement {
import("../components/ha-spinner"); import("../components/ha-spinner");
}, 5000); }, 5000);
// Only start retry interval for error state
if (this.error) {
this._retryInterval = window.setInterval(() => { this._retryInterval = window.setInterval(() => {
const remainingSeconds = this._retryInSeconds--; const remainingSeconds = this._retryInSeconds--;
if (remainingSeconds <= 0) { if (remainingSeconds <= 0) {
@@ -124,14 +85,6 @@ class HaInitPage extends LitElement {
}, 1000); }, 1000);
} }
// Start loading timeout for normal loading (not error, not migration)
if (!this.error && !this.migration) {
this._loadingTimeoutHandle = window.setTimeout(() => {
this._loadingTimeout = true;
}, 30000); // 30 seconds
}
}
private _retry() { private _retry() {
if (this._retryInterval) { if (this._retryInterval) {
clearInterval(this._retryInterval); clearInterval(this._retryInterval);
@@ -139,25 +92,6 @@ class HaInitPage extends LitElement {
location.reload(); location.reload();
} }
private async _clearCacheAndRetry() {
// Deregister service worker and clear caches
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
await registration.unregister();
}
if ("caches" in window) {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map((name) => caches.delete(name)));
}
} catch (err: any) {
// Ignore errors, we'll reload anyway
}
}
location.reload();
}
static styles = css` static styles = css`
:host { :host {
flex: 0; flex: 0;
@@ -177,23 +111,12 @@ class HaInitPage extends LitElement {
.retry-text { .retry-text {
margin-top: 0; margin-top: 0;
} }
.hint {
margin-top: 8px;
font-size: 0.9em;
opacity: 0.7;
}
p, p,
#loading-text { #loading-text {
max-width: 350px; max-width: 350px;
color: var(--primary-text-color); color: var(--primary-text-color);
text-align: center; text-align: center;
} }
.button-row {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 16px;
}
`; `;
} }

View File

@@ -35,6 +35,7 @@ const COMPONENTS = {
light: () => import("../panels/light/ha-panel-light"), light: () => import("../panels/light/ha-panel-light"),
security: () => import("../panels/security/ha-panel-security"), security: () => import("../panels/security/ha-panel-security"),
climate: () => import("../panels/climate/ha-panel-climate"), climate: () => import("../panels/climate/ha-panel-climate"),
home: () => import("../panels/home/ha-panel-home"),
}; };
@customElement("partial-panel-resolver") @customElement("partial-panel-resolver")

View File

@@ -1,82 +1,56 @@
import type { ReactiveElement } from "lit"; import type { ReactiveElement } from "lit";
import { listenMediaQuery } from "../common/dom/media_query";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import {
setupMediaQueryListeners,
setupTimeListeners,
} from "../common/condition/listeners";
import type { Condition } from "../panels/lovelace/common/validate-condition"; import type { Condition } from "../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../panels/lovelace/common/validate-condition";
type Constructor<T> = abstract new (...args: any[]) => T; type Constructor<T> = abstract new (...args: any[]) => T;
/** /**
* Extract media queries from conditions recursively * Base config type that can be used with conditional listeners
*/ */
export function extractMediaQueries(conditions: Condition[]): string[] { export interface ConditionalConfig {
return conditions.reduce<string[]>((array, c) => { visibility?: Condition[];
if ("conditions" in c && c.conditions) { [key: string]: any;
array.push(...extractMediaQueries(c.conditions));
}
if (c.condition === "screen" && c.media_query) {
array.push(c.media_query);
}
return array;
}, []);
}
/**
* Helper to setup media query listeners for conditional visibility
*/
export function setupMediaQueryListeners(
conditions: Condition[],
hass: HomeAssistant,
addListener: (unsub: () => void) => void,
onUpdate: (conditionsMet: boolean) => void
): void {
const mediaQueries = extractMediaQueries(conditions);
if (mediaQueries.length === 0) return;
// Optimization for single media query
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;
mediaQueries.forEach((mediaQuery) => {
const unsub = listenMediaQuery(mediaQuery, (matches) => {
if (hasOnlyMediaQuery) {
onUpdate(matches);
} else {
const conditionsMet = checkConditionsMet(conditions, hass);
onUpdate(conditionsMet);
}
});
addListener(unsub);
});
} }
/** /**
* Mixin to handle conditional listeners for visibility control * Mixin to handle conditional listeners for visibility control
* *
* Provides lifecycle management for listeners (media queries, time-based, state changes, etc.) * Provides lifecycle management for listeners that control conditional
* that control conditional visibility of components. * visibility of components.
* *
* Usage: * Usage:
* 1. Extend your component with ConditionalListenerMixin(ReactiveElement) * 1. Extend your component with ConditionalListenerMixin<YourConfigType>(ReactiveElement)
* 2. Override setupConditionalListeners() to setup your listeners * 2. Ensure component has config.visibility or _config.visibility property with conditions
* 3. Use addConditionalListener() to register unsubscribe functions * 3. Ensure component has _updateVisibility() or _updateElement() method
* 4. Call clearConditionalListeners() and setupConditionalListeners() when config changes * 4. Override setupConditionalListeners() if custom behavior needed (e.g., filter conditions)
* *
* The mixin automatically: * The mixin automatically:
* - Sets up listeners when component connects to DOM * - Sets up listeners when component connects to DOM
* - Cleans up listeners when component disconnects from DOM * - Cleans up listeners when component disconnects from DOM
* - Handles conditional visibility based on defined conditions
*/ */
export const ConditionalListenerMixin = < export const ConditionalListenerMixin = <
T extends Constructor<ReactiveElement>, TConfig extends ConditionalConfig = ConditionalConfig,
>( >(
superClass: T superClass: Constructor<ReactiveElement>
) => { ) => {
abstract class ConditionalListenerClass extends superClass { abstract class ConditionalListenerClass extends superClass {
private __listeners: (() => void)[] = []; private __listeners: (() => void)[] = [];
protected _config?: TConfig;
public config?: TConfig;
public hass?: HomeAssistant;
protected _updateElement?(config: TConfig): void;
protected _updateVisibility?(conditionsMet?: boolean): void;
public connectedCallback() { public connectedCallback() {
super.connectedCallback(); super.connectedCallback();
this.setupConditionalListeners(); this.setupConditionalListeners();
@@ -87,17 +61,72 @@ export const ConditionalListenerMixin = <
this.clearConditionalListeners(); this.clearConditionalListeners();
} }
/**
* Clear conditional listeners
*
* This method is called when the component is disconnected from the DOM.
* It clears all the listeners that were set up by the setupConditionalListeners() method.
*/
protected clearConditionalListeners(): void { protected clearConditionalListeners(): void {
this.__listeners.forEach((unsub) => unsub()); this.__listeners.forEach((unsub) => unsub());
this.__listeners = []; this.__listeners = [];
} }
/**
* Add a conditional listener to the list of listeners
*
* This method is called when a new listener is added.
* It adds the listener to the list of listeners.
*
* @param unsubscribe - The unsubscribe function to call when the listener is no longer needed
* @returns void
*/
protected addConditionalListener(unsubscribe: () => void): void { protected addConditionalListener(unsubscribe: () => void): void {
this.__listeners.push(unsubscribe); this.__listeners.push(unsubscribe);
} }
protected setupConditionalListeners(): void { /**
// Override in subclass * Setup conditional listeners for visibility control
*
* Default implementation:
* - Checks config.visibility or _config.visibility for conditions (if not provided)
* - Sets up appropriate listeners based on condition types
* - Calls _updateVisibility() or _updateElement() when conditions change
*
* Override this method to customize behavior (e.g., filter conditions first)
* and call super.setupConditionalListeners(customConditions) to reuse the base implementation
*
* @param conditions - Optional conditions array. If not provided, will check config.visibility or _config.visibility
*/
protected setupConditionalListeners(conditions?: Condition[]): void {
const config = this.config || this._config;
const finalConditions = conditions || config?.visibility;
if (!finalConditions || !this.hass) {
return;
}
const onUpdate = (conditionsMet: boolean) => {
if (this._updateVisibility) {
this._updateVisibility(conditionsMet);
} else if (this._updateElement && config) {
this._updateElement(config);
}
};
setupMediaQueryListeners(
finalConditions,
this.hass,
(unsub) => this.addConditionalListener(unsub),
onUpdate
);
setupTimeListeners(
finalConditions,
this.hass,
(unsub) => this.addConditionalListener(unsub),
onUpdate
);
} }
} }
return ConditionalListenerClass; return ConditionalListenerClass;

View File

@@ -104,7 +104,6 @@ export class HaConfigApplicationCredentials extends LitElement {
), ),
sortable: true, sortable: true,
filterable: true, filterable: true,
direction: "asc",
}, },
actions: { actions: {
title: "", title: "",

View File

@@ -588,7 +588,11 @@ export default class HaAutomationActionRow extends LitElement {
...this._clipboard, ...this._clipboard,
action: deepClone(this.action), action: deepClone(this.action),
}; };
copyToClipboard(dump(this.action)); let action = this.action;
if ("sequence" in action) {
action = { ...this.action, metadata: {} };
}
copyToClipboard(dump(action));
} }
private _onDisable = () => { private _onDisable = () => {

View File

@@ -452,7 +452,10 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -372,16 +372,14 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
clickable clickable
id="backup_id" id="backup_id"
has-filters has-filters
.filters=${ .filters=${Object.values(this._filters).filter((filter) =>
Object.values(this._filters).filter((filter) =>
Array.isArray(filter) Array.isArray(filter)
? filter.length ? filter.length
: filter && : filter &&
Object.values(filter).some((val) => Object.values(filter).some((val) =>
Array.isArray(val) ? val.length : val Array.isArray(val) ? val.length : val
) )
).length ).length}
}
selectable selectable
.selected=${this._selected.length} .selected=${this._selected.length}
.initialGroupColumn=${this._activeGrouping} .initialGroupColumn=${this._activeGrouping}
@@ -423,8 +421,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
</div> </div>
<div slot="selection-bar"> <div slot="selection-bar">
${ ${!this.narrow
!this.narrow
? html` ? html`
<ha-button <ha-button
appearance="plain" appearance="plain"
@@ -445,8 +442,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
class="warning" class="warning"
@click=${this._deleteSelected} @click=${this._deleteSelected}
></ha-icon-button> ></ha-icon-button>
` `}
}
</div> </div>
<ha-filter-states <ha-filter-states
@@ -459,8 +455,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
expanded expanded
.narrow=${this.narrow} .narrow=${this.narrow}
></ha-filter-states> ></ha-filter-states>
${ ${!this._needsOnboarding
!this._needsOnboarding
? html` ? html`
<ha-fab <ha-fab
slot="fab" slot="fab"
@@ -481,8 +476,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
></ha-svg-icon>`} ></ha-svg-icon>`}
</ha-fab> </ha-fab>
` `
: nothing : nothing}
}
</hass-tabs-subpage-data-table> </hass-tabs-subpage-data-table>
<ha-md-menu id="overflow-menu" positioning="fixed"> <ha-md-menu id="overflow-menu" positioning="fixed">
<ha-md-menu-item .clickAction=${this._downloadBackup}> <ha-md-menu-item .clickAction=${this._downloadBackup}>
@@ -494,8 +488,6 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
${this.hass.localize("ui.common.delete")} ${this.hass.localize("ui.common.delete")}
</ha-md-menu-item> </ha-md-menu-item>
</ha-md-menu> </ha-md-menu>
>
</ha-icon-overflow-menu>
`; `;
} }
@@ -569,15 +561,15 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
navigate(`/config/backup/details/${id}`); navigate(`/config/backup/details/${id}`);
} }
private async _downloadBackup(ev): Promise<void> { private _downloadBackup = async (ev): Promise<void> => {
const backup = ev.parentElement.anchorElement.backup; const backup = ev.parentElement.anchorElement.backup;
if (!backup) { if (!backup) {
return; return;
} }
downloadBackup(this.hass, this, backup, this.config); downloadBackup(this.hass, this, backup, this.config);
} };
private async _deleteBackup(ev): Promise<void> { private _deleteBackup = async (ev): Promise<void> => {
const backup = ev.parentElement.anchorElement.backup; const backup = ev.parentElement.anchorElement.backup;
if (!backup) { if (!backup) {
return; return;
@@ -609,7 +601,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
return; return;
} }
fireEvent(this, "ha-refresh-backup-info"); fireEvent(this, "ha-refresh-backup-info");
} };
private async _deleteSelected() { private async _deleteSelected() {
const confirm = await showConfirmationDialog(this, { const confirm = await showConfirmationDialog(this, {

View File

@@ -182,13 +182,11 @@ class HaBlueprintOverview extends LitElement {
sortable: true, sortable: true,
filterable: true, filterable: true,
groupable: true, groupable: true,
direction: "asc",
}, },
path: { path: {
title: localize("ui.panel.config.blueprint.overview.headers.file_name"), title: localize("ui.panel.config.blueprint.overview.headers.file_name"),
sortable: true, sortable: true,
filterable: true, filterable: true,
direction: "asc",
flex: 2, flex: 2,
}, },
fullpath: { fullpath: {

View File

@@ -1,4 +1,4 @@
import { mdiTag, mdiPlus } from "@mdi/js"; import { mdiPlus, mdiTag } from "@mdi/js";
import type { UnsubscribeFunc } from "home-assistant-js-websocket"; import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { TemplateResult } from "lit"; import type { TemplateResult } from "lit";
import { html, LitElement } from "lit"; import { html, LitElement } from "lit";
@@ -194,8 +194,9 @@ export class HaCategoryPicker extends SubscribeMixin(LitElement) {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this.hass.localize( .notFoundLabel=${this._notFoundLabel}
"ui.components.category-picker.no_match" .emptyLabel=${this.hass.localize(
"ui.components.category-picker.no_categories"
)} )}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
@@ -254,6 +255,11 @@ export class HaCategoryPicker extends SubscribeMixin(LitElement) {
fireEvent(this, "change"); fireEvent(this, "change");
}, 0); }, 0);
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.category-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -771,7 +771,10 @@ export class HaConfigDeviceDashboard extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -26,6 +26,7 @@ import type {
EnergySource, EnergySource,
FlowFromGridSourceEnergyPreference, FlowFromGridSourceEnergyPreference,
FlowToGridSourceEnergyPreference, FlowToGridSourceEnergyPreference,
GridPowerSourceEnergyPreference,
GridSourceTypeEnergyPreference, GridSourceTypeEnergyPreference,
} from "../../../../data/energy"; } from "../../../../data/energy";
import { import {
@@ -47,6 +48,7 @@ import { documentationUrl } from "../../../../util/documentation-url";
import { import {
showEnergySettingsGridFlowFromDialog, showEnergySettingsGridFlowFromDialog,
showEnergySettingsGridFlowToDialog, showEnergySettingsGridFlowToDialog,
showEnergySettingsGridPowerDialog,
} from "../dialogs/show-dialogs-energy"; } from "../dialogs/show-dialogs-energy";
import "./ha-energy-validation-result"; import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles"; import { energyCardStyles } from "./styles";
@@ -226,6 +228,58 @@ export class EnergyGridSettings extends LitElement {
> >
</div> </div>
<h3>
${this.hass.localize("ui.panel.config.energy.grid.grid_power")}
</h3>
${gridSource.power?.map((power) => {
const entityState = this.hass.states[power.stat_rate];
return html`
<div class="row" .source=${power}>
${entityState?.attributes.icon
? html`<ha-icon
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiTransmissionTower}
></ha-svg-icon>`}
<span class="content"
>${getStatisticLabel(
this.hass,
power.stat_rate,
this.statsMetadata?.[power.stat_rate]
)}</span
>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.edit_power"
)}
@click=${this._editPowerSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.delete_power"
)}
@click=${this._deletePowerSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
`;
})}
<div class="row border-bottom">
<ha-svg-icon .path=${mdiTransmissionTower}></ha-svg-icon>
<ha-button
@click=${this._addPowerSource}
appearance="filled"
size="small"
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.grid.add_power"
)}</ha-button
>
</div>
<h3> <h3>
${this.hass.localize( ${this.hass.localize(
"ui.panel.config.energy.grid.grid_carbon_footprint" "ui.panel.config.energy.grid.grid_carbon_footprint"
@@ -499,6 +553,97 @@ export class EnergyGridSettings extends LitElement {
await this._savePreferences(cleanedPreferences); await this._savePreferences(cleanedPreferences);
} }
private _addPowerSource() {
const gridSource = this.preferences.energy_sources.find(
(src) => src.type === "grid"
) as GridSourceTypeEnergyPreference | undefined;
showEnergySettingsGridPowerDialog(this, {
grid_source: gridSource,
saveCallback: async (power) => {
let preferences: EnergyPreferences;
if (!gridSource) {
preferences = {
...this.preferences,
energy_sources: [
...this.preferences.energy_sources,
{
...emptyGridSourceEnergyPreference(),
power: [power],
},
],
};
} else {
preferences = {
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src.type === "grid"
? { ...src, power: [...(gridSource.power || []), power] }
: src
),
};
}
await this._savePreferences(preferences);
},
});
}
private _editPowerSource(ev) {
const origSource: GridPowerSourceEnergyPreference =
ev.currentTarget.closest(".row").source;
const gridSource = this.preferences.energy_sources.find(
(src) => src.type === "grid"
) as GridSourceTypeEnergyPreference | undefined;
showEnergySettingsGridPowerDialog(this, {
source: { ...origSource },
grid_source: gridSource,
saveCallback: async (source) => {
const power =
energySourcesByType(this.preferences).grid![0].power || [];
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src.type === "grid"
? {
...src,
power: power.map((p) => (p === origSource ? source : p)),
}
: src
),
};
await this._savePreferences(preferences);
},
});
}
private async _deletePowerSource(ev) {
const sourceToDelete: GridPowerSourceEnergyPreference =
ev.currentTarget.closest(".row").source;
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
}
const power =
energySourcesByType(this.preferences).grid![0].power?.filter(
(p) => p !== sourceToDelete
) || [];
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: this.preferences.energy_sources.map((source) =>
source.type === "grid" ? { ...source, power } : source
),
};
const cleanedPreferences = this._removeEmptySources(preferences);
await this._savePreferences(cleanedPreferences);
}
private _removeEmptySources(preferences: EnergyPreferences) { private _removeEmptySources(preferences: EnergyPreferences) {
// Check if grid sources became an empty type and remove if so // Check if grid sources became an empty type and remove if so
preferences.energy_sources = preferences.energy_sources.reduce< preferences.energy_sources = preferences.energy_sources.reduce<
@@ -507,7 +652,8 @@ export class EnergyGridSettings extends LitElement {
if ( if (
source.type !== "grid" || source.type !== "grid" ||
source.flow_from.length > 0 || source.flow_from.length > 0 ||
source.flow_to.length > 0 source.flow_to.length > 0 ||
(source.power && source.power.length > 0)
) { ) {
acc.push(source); acc.push(source);
} }

View File

@@ -18,6 +18,7 @@ import type { HomeAssistant } from "../../../../types";
import type { EnergySettingsBatteryDialogParams } from "./show-dialogs-energy"; import type { EnergySettingsBatteryDialogParams } from "./show-dialogs-energy";
const energyUnitClasses = ["energy"]; const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-battery-settings") @customElement("dialog-energy-battery-settings")
export class DialogEnergyBatterySettings export class DialogEnergyBatterySettings
@@ -32,10 +33,14 @@ export class DialogEnergyBatterySettings
@state() private _energy_units?: string[]; @state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string; @state() private _error?: string;
private _excludeList?: string[]; private _excludeList?: string[];
private _excludeListPower?: string[];
public async showDialog( public async showDialog(
params: EnergySettingsBatteryDialogParams params: EnergySettingsBatteryDialogParams
): Promise<void> { ): Promise<void> {
@@ -46,6 +51,9 @@ export class DialogEnergyBatterySettings
this._energy_units = ( this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy") await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units; ).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
const allSources: string[] = []; const allSources: string[] = [];
this._params.battery_sources.forEach((entry) => { this._params.battery_sources.forEach((entry) => {
allSources.push(entry.stat_energy_from); allSources.push(entry.stat_energy_from);
@@ -56,6 +64,9 @@ export class DialogEnergyBatterySettings
id !== this._source?.stat_energy_from && id !== this._source?.stat_energy_from &&
id !== this._source?.stat_energy_to id !== this._source?.stat_energy_to
); );
this._excludeListPower = this._params.battery_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
} }
public closeDialog() { public closeDialog() {
@@ -72,8 +83,6 @@ export class DialogEnergyBatterySettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
return html` return html`
<ha-dialog <ha-dialog
open open
@@ -85,12 +94,6 @@ export class DialogEnergyBatterySettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
${this.hass.localize(
"ui.panel.config.energy.battery.dialog.entity_para",
{ unit: pickableUnit }
)}
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -105,6 +108,10 @@ export class DialogEnergyBatterySettings
this._source.stat_energy_from, this._source.stat_energy_from,
]} ]}
@value-changed=${this._statisticToChanged} @value-changed=${this._statisticToChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.energy_helper_into",
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
@@ -121,6 +128,25 @@ export class DialogEnergyBatterySettings
this._source.stat_energy_to, this._source.stat_energy_to,
]} ]}
@value-changed=${this._statisticFromChanged} @value-changed=${this._statisticFromChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.energy_helper_out",
{ unit: this._energy_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-statistic-picker
.hass=${this.hass}
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.power_helper",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker> ></ha-statistic-picker>
<ha-button <ha-button
@@ -150,6 +176,10 @@ export class DialogEnergyBatterySettings
this._source = { ...this._source!, stat_energy_from: ev.detail.value }; this._source = { ...this._source!, stat_energy_from: ev.detail.value };
} }
private _powerChanged(ev: CustomEvent<{ value: string }>) {
this._source = { ...this._source!, stat_rate: ev.detail.value };
}
private async _save() { private async _save() {
try { try {
await this._params!.saveCallback(this._source!); await this._params!.saveCallback(this._source!);
@@ -168,7 +198,11 @@ export class DialogEnergyBatterySettings
--mdc-dialog-max-width: 430px; --mdc-dialog-max-width: 430px;
} }
ha-statistic-picker { ha-statistic-picker {
width: 100%; display: block;
margin-bottom: var(--ha-space-4);
}
ha-statistic-picker:last-of-type {
margin-bottom: 0;
} }
`, `,
]; ];

View File

@@ -21,6 +21,7 @@ import type { HomeAssistant } from "../../../../types";
import type { EnergySettingsDeviceDialogParams } from "./show-dialogs-energy"; import type { EnergySettingsDeviceDialogParams } from "./show-dialogs-energy";
const energyUnitClasses = ["energy"]; const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-device-settings") @customElement("dialog-energy-device-settings")
export class DialogEnergyDeviceSettings export class DialogEnergyDeviceSettings
@@ -35,10 +36,14 @@ export class DialogEnergyDeviceSettings
@state() private _energy_units?: string[]; @state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string; @state() private _error?: string;
private _excludeList?: string[]; private _excludeList?: string[];
private _excludeListPower?: string[];
private _possibleParents: DeviceConsumptionEnergyPreference[] = []; private _possibleParents: DeviceConsumptionEnergyPreference[] = [];
public async showDialog( public async showDialog(
@@ -50,9 +55,15 @@ export class DialogEnergyDeviceSettings
this._energy_units = ( this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy") await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units; ).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeList = this._params.device_consumptions this._excludeList = this._params.device_consumptions
.map((entry) => entry.stat_consumption) .map((entry) => entry.stat_consumption)
.filter((id) => id !== this._device?.stat_consumption); .filter((id) => id !== this._device?.stat_consumption);
this._excludeListPower = this._params.device_consumptions
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._device?.stat_rate) as string[];
} }
private _computePossibleParents() { private _computePossibleParents() {
@@ -93,8 +104,6 @@ export class DialogEnergyDeviceSettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
return html` return html`
<ha-dialog <ha-dialog
open open
@@ -108,12 +117,6 @@ export class DialogEnergyDeviceSettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: pickableUnit }
)}
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -125,9 +128,28 @@ export class DialogEnergyDeviceSettings
)} )}
.excludeStatistics=${this._excludeList} .excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
<ha-statistic-picker
.hass=${this.hass}
.includeUnitClass=${powerUnitClasses}
.value=${this._device?.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.device_consumption_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-textfield <ha-textfield
.label=${this.hass.localize( .label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.display_name" "ui.panel.config.energy.device_consumption.dialog.display_name"
@@ -210,6 +232,20 @@ export class DialogEnergyDeviceSettings
this._computePossibleParents(); this._computePossibleParents();
} }
private _powerStatisticChanged(ev: CustomEvent<{ value: string }>) {
if (!this._device) {
return;
}
const newDevice = {
...this._device,
stat_rate: ev.detail.value,
} as DeviceConsumptionEnergyPreference;
if (!newDevice.stat_rate) {
delete newDevice.stat_rate;
}
this._device = newDevice;
}
private _nameChanged(ev) { private _nameChanged(ev) {
const newDevice = { const newDevice = {
...this._device!, ...this._device!,
@@ -245,15 +281,19 @@ export class DialogEnergyDeviceSettings
return [ return [
haStyleDialog, haStyleDialog,
css` css`
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-2);
}
ha-statistic-picker { ha-statistic-picker {
width: 100%; width: 100%;
} }
ha-select { ha-select {
margin-top: 16px; margin-top: var(--ha-space-4);
width: 100%; width: 100%;
} }
ha-textfield { ha-textfield {
margin-top: 16px; margin-top: var(--ha-space-4);
width: 100%; width: 100%;
} }
`, `,

View File

@@ -104,8 +104,6 @@ export class DialogEnergyGridFlowSettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
const unitPriceFixed = `${this.hass.config.currency}/kWh`; const unitPriceFixed = `${this.hass.config.currency}/kWh`;
const externalSource = const externalSource =
@@ -135,19 +133,11 @@ export class DialogEnergyGridFlowSettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
<p> <p>
${this.hass.localize( ${this.hass.localize(
`ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.paragraph` `ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.paragraph`
)} )}
</p> </p>
<p>
${this.hass.localize(
`ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.entity_para`,
{ unit: pickableUnit }
)}
</p>
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -163,6 +153,10 @@ export class DialogEnergyGridFlowSettings
)} )}
.excludeStatistics=${this._excludeList} .excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
.helper=${this.hass.localize(
`ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.entity_para`,
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
@@ -361,6 +355,10 @@ export class DialogEnergyGridFlowSettings
ha-dialog { ha-dialog {
--mdc-dialog-max-width: 430px; --mdc-dialog-max-width: 430px;
} }
ha-statistic-picker {
display: block;
margin: var(--ha-space-4) 0;
}
ha-formfield { ha-formfield {
display: block; display: block;
} }

View File

@@ -0,0 +1,153 @@
import { mdiTransmissionTower } from "@mdi/js";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-dialog";
import "../../../../components/ha-button";
import type { GridPowerSourceEnergyPreference } from "../../../../data/energy";
import { energyStatisticHelpUrl } from "../../../../data/energy";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import type { EnergySettingsGridPowerDialogParams } from "./show-dialogs-energy";
const powerUnitClasses = ["power"];
@customElement("dialog-energy-grid-power-settings")
export class DialogEnergyGridPowerSettings
extends LitElement
implements HassDialog<EnergySettingsGridPowerDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: EnergySettingsGridPowerDialogParams;
@state() private _source?: GridPowerSourceEnergyPreference;
@state() private _power_units?: string[];
@state() private _error?: string;
private _excludeListPower?: string[];
public async showDialog(
params: EnergySettingsGridPowerDialogParams
): Promise<void> {
this._params = params;
this._source = params.source ? { ...params.source } : { stat_rate: "" };
const initialSourceIdPower = this._source.stat_rate;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeListPower = [
...(this._params.grid_source?.power?.map((entry) => entry.stat_rate) ||
[]),
].filter((id) => id && id !== initialSourceIdPower) as string[];
}
public closeDialog() {
this._params = undefined;
this._source = undefined;
this._error = undefined;
this._excludeListPower = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
return true;
}
protected render() {
if (!this._params || !this._source) {
return nothing;
}
return html`
<ha-dialog
open
.heading=${html`<ha-svg-icon
.path=${mdiTransmissionTower}
style="--mdc-icon-size: 32px;"
></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.grid.power_dialog.header"
)}`}
@closed=${this.closeDialog}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
<ha-statistic-picker
.hass=${this.hass}
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.grid.power_dialog.power_stat"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.grid.power_dialog.power_helper",
{ unit: this._power_units?.join(", ") || "" }
)}
dialogInitialFocus
></ha-statistic-picker>
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="primaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${!this._source.stat_rate}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog>
`;
}
private _powerStatisticChanged(ev: CustomEvent<{ value: string }>) {
this._source = {
...this._source!,
stat_rate: ev.detail.value,
};
}
private async _save() {
try {
await this._params!.saveCallback(this._source!);
this.closeDialog();
} catch (err: any) {
this._error = err.message;
}
}
static get styles(): CSSResultGroup {
return [
haStyleDialog,
css`
ha-dialog {
--mdc-dialog-max-width: 430px;
}
ha-statistic-picker {
display: block;
margin: var(--ha-space-4) 0;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-grid-power-settings": DialogEnergyGridPowerSettings;
}
}

View File

@@ -28,6 +28,7 @@ import { brandsUrl } from "../../../../util/brands-url";
import type { EnergySettingsSolarDialogParams } from "./show-dialogs-energy"; import type { EnergySettingsSolarDialogParams } from "./show-dialogs-energy";
const energyUnitClasses = ["energy"]; const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-solar-settings") @customElement("dialog-energy-solar-settings")
export class DialogEnergySolarSettings export class DialogEnergySolarSettings
@@ -46,10 +47,14 @@ export class DialogEnergySolarSettings
@state() private _energy_units?: string[]; @state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string; @state() private _error?: string;
private _excludeList?: string[]; private _excludeList?: string[];
private _excludeListPower?: string[];
public async showDialog( public async showDialog(
params: EnergySettingsSolarDialogParams params: EnergySettingsSolarDialogParams
): Promise<void> { ): Promise<void> {
@@ -62,9 +67,15 @@ export class DialogEnergySolarSettings
this._energy_units = ( this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy") await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units; ).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeList = this._params.solar_sources this._excludeList = this._params.solar_sources
.map((entry) => entry.stat_energy_from) .map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from); .filter((id) => id !== this._source?.stat_energy_from);
this._excludeListPower = this._params.solar_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
} }
public closeDialog() { public closeDialog() {
@@ -81,8 +92,6 @@ export class DialogEnergySolarSettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
return html` return html`
<ha-dialog <ha-dialog
open open
@@ -94,12 +103,6 @@ export class DialogEnergySolarSettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: pickableUnit }
)}
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -111,9 +114,28 @@ export class DialogEnergySolarSettings
)} )}
.excludeStatistics=${this._excludeList} .excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
<ha-statistic-picker
.hass=${this.hass}
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<h3> <h3>
${this.hass.localize( ${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_forecast" "ui.panel.config.energy.solar.dialog.solar_production_forecast"
@@ -267,6 +289,10 @@ export class DialogEnergySolarSettings
this._source = { ...this._source!, stat_energy_from: ev.detail.value }; this._source = { ...this._source!, stat_energy_from: ev.detail.value };
} }
private _powerStatisticChanged(ev: CustomEvent<{ value: string }>) {
this._source = { ...this._source!, stat_rate: ev.detail.value };
}
private async _save() { private async _save() {
try { try {
if (!this._forecast) { if (!this._forecast) {
@@ -287,6 +313,10 @@ export class DialogEnergySolarSettings
ha-dialog { ha-dialog {
--mdc-dialog-max-width: 430px; --mdc-dialog-max-width: 430px;
} }
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
img { img {
height: 24px; height: 24px;
margin-right: 16px; margin-right: 16px;

View File

@@ -7,6 +7,7 @@ import type {
FlowFromGridSourceEnergyPreference, FlowFromGridSourceEnergyPreference,
FlowToGridSourceEnergyPreference, FlowToGridSourceEnergyPreference,
GasSourceTypeEnergyPreference, GasSourceTypeEnergyPreference,
GridPowerSourceEnergyPreference,
GridSourceTypeEnergyPreference, GridSourceTypeEnergyPreference,
SolarSourceTypeEnergyPreference, SolarSourceTypeEnergyPreference,
WaterSourceTypeEnergyPreference, WaterSourceTypeEnergyPreference,
@@ -41,6 +42,12 @@ export interface EnergySettingsGridFlowToDialogParams {
saveCallback: (source: FlowToGridSourceEnergyPreference) => Promise<void>; saveCallback: (source: FlowToGridSourceEnergyPreference) => Promise<void>;
} }
export interface EnergySettingsGridPowerDialogParams {
source?: GridPowerSourceEnergyPreference;
grid_source?: GridSourceTypeEnergyPreference;
saveCallback: (source: GridPowerSourceEnergyPreference) => Promise<void>;
}
export interface EnergySettingsSolarDialogParams { export interface EnergySettingsSolarDialogParams {
info: EnergyInfo; info: EnergyInfo;
source?: SolarSourceTypeEnergyPreference; source?: SolarSourceTypeEnergyPreference;
@@ -152,3 +159,14 @@ export const showEnergySettingsGridFlowToDialog = (
dialogParams: { ...dialogParams, direction: "to" }, dialogParams: { ...dialogParams, direction: "to" },
}); });
}; };
export const showEnergySettingsGridPowerDialog = (
element: HTMLElement,
dialogParams: EnergySettingsGridPowerDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-grid-power-settings",
dialogImport: () => import("./dialog-energy-grid-power-settings"),
dialogParams: dialogParams,
});
};

View File

@@ -792,7 +792,10 @@ export class HaConfigEntities extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -634,7 +634,10 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -8,6 +8,7 @@ import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { relativeTime } from "../../../../../common/datetime/relative_time"; import { relativeTime } from "../../../../../common/datetime/relative_time";
import { getDeviceContext } from "../../../../../common/entity/context/get_device_context";
import { navigate } from "../../../../../common/navigate"; import { navigate } from "../../../../../common/navigate";
import { throttle } from "../../../../../common/util/throttle"; import { throttle } from "../../../../../common/util/throttle";
import "../../../../../components/chart/ha-network-graph"; import "../../../../../components/chart/ha-network-graph";
@@ -194,11 +195,17 @@ export class BluetoothNetworkVisualization extends LitElement {
]; ];
const links: NetworkLink[] = []; const links: NetworkLink[] = [];
Object.values(scanners).forEach((scanner) => { Object.values(scanners).forEach((scanner) => {
const scannerDevice = this._sourceDevices[scanner.source]; const scannerDevice = this._sourceDevices[scanner.source] as
| DeviceRegistryEntry
| undefined;
const area = scannerDevice
? getDeviceContext(scannerDevice, this.hass).area
: undefined;
nodes.push({ nodes.push({
id: scanner.source, id: scanner.source,
name: name:
scannerDevice?.name_by_user || scannerDevice?.name || scanner.name, scannerDevice?.name_by_user || scannerDevice?.name || scanner.name,
context: area?.name,
category: 1, category: 1,
value: 5, value: 5,
symbol: "circle", symbol: "circle",
@@ -231,10 +238,16 @@ export class BluetoothNetworkVisualization extends LitElement {
}); });
return; return;
} }
const device = this._sourceDevices[node.address]; const device = this._sourceDevices[node.address] as
| DeviceRegistryEntry
| undefined;
const area = device
? getDeviceContext(device, this.hass).area
: undefined;
nodes.push({ nodes.push({
id: node.address, id: node.address,
name: this._getBluetoothDeviceName(node.address), name: this._getBluetoothDeviceName(node.address),
context: area?.name,
value: device ? 1 : 0, value: device ? 1 : 0,
category: device ? 2 : 3, category: device ? 2 : 3,
symbolSize: 20, symbolSize: 20,
@@ -294,19 +307,24 @@ export class BluetoothNetworkVisualization extends LitElement {
const btDevice = this._data.find((d) => d.address === address); const btDevice = this._data.find((d) => d.address === address);
if (btDevice) { if (btDevice) {
tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}<br><b>${this.hass.localize("ui.panel.config.bluetooth.rssi")}:</b> ${btDevice.rssi}<br><b>${this.hass.localize("ui.panel.config.bluetooth.source")}:</b> ${btDevice.source}<br><b>${this.hass.localize("ui.panel.config.bluetooth.updated")}:</b> ${relativeTime(new Date(btDevice.time * 1000), this.hass.locale)}`; tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}<br><b>${this.hass.localize("ui.panel.config.bluetooth.rssi")}:</b> ${btDevice.rssi}<br><b>${this.hass.localize("ui.panel.config.bluetooth.source")}:</b> ${btDevice.source}<br><b>${this.hass.localize("ui.panel.config.bluetooth.updated")}:</b> ${relativeTime(new Date(btDevice.time * 1000), this.hass.locale)}`;
const device = this._sourceDevices[address];
if (device) {
const area = getDeviceContext(device, this.hass).area;
if (area) {
tooltipText += `<br><b>${this.hass.localize("ui.panel.config.bluetooth.area")}: </b>${area.name}`;
}
}
} else { } else {
const device = this._sourceDevices[address]; const device = this._sourceDevices[address];
if (device) { if (device) {
tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}`; tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}`;
if (device.area_id) { const area = getDeviceContext(device, this.hass).area;
const area = this.hass.areas[device.area_id];
if (area) { if (area) {
tooltipText += `<br><b>${this.hass.localize("ui.panel.config.bluetooth.area")}: </b>${area.name}`; tooltipText += `<br><b>${this.hass.localize("ui.panel.config.bluetooth.area")}: </b>${area.name}`;
} }
} }
} }
} }
}
return tooltipText; return tooltipText;
}; };

View File

@@ -426,6 +426,10 @@ class DialogZHAReconfigureDevice extends LitElement {
return [ return [
haStyleDialog, haStyleDialog,
css` css`
ha-dialog {
--mdc-dialog-max-width: 800px;
}
.wrapper { .wrapper {
display: grid; display: grid;
grid-template-columns: 3fr 1fr 2fr; grid-template-columns: 3fr 1fr 2fr;

View File

@@ -19,6 +19,8 @@ import "../../../../../layouts/hass-tabs-subpage";
import type { HomeAssistant, Route } from "../../../../../types"; import type { HomeAssistant, Route } from "../../../../../types";
import { formatAsPaddedHex } from "./functions"; import { formatAsPaddedHex } from "./functions";
import { zhaTabs } from "./zha-config-dashboard"; import { zhaTabs } from "./zha-config-dashboard";
import type { DeviceRegistryEntry } from "../../../../../data/device_registry";
import { getDeviceContext } from "../../../../../common/entity/context/get_device_context";
@customElement("zha-network-visualization-page") @customElement("zha-network-visualization-page")
export class ZHANetworkVisualizationPage extends LitElement { export class ZHANetworkVisualizationPage extends LitElement {
@@ -117,8 +119,11 @@ export class ZHANetworkVisualizationPage extends LitElement {
} else { } else {
label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.device_not_in_db")}</b>`; label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.device_not_in_db")}</b>`;
} }
if (device.area_id) { const haDevice = this.hass.devices[device.device_reg_id] as
const area = this.hass.areas[device.area_id]; | DeviceRegistryEntry
| undefined;
if (haDevice) {
const area = getDeviceContext(haDevice, this.hass).area;
if (area) { if (area) {
label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.area")}: </b>${area.name}`; label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.area")}: </b>${area.name}`;
} }
@@ -204,10 +209,17 @@ export class ZHANetworkVisualizationPage extends LitElement {
category = 2; // End Device category = 2; // End Device
} }
const haDevice = this.hass.devices[device.device_reg_id] as
| DeviceRegistryEntry
| undefined;
const area = haDevice
? getDeviceContext(haDevice, this.hass).area
: undefined;
// Create node // Create node
nodes.push({ nodes.push({
id: device.ieee, id: device.ieee,
name: device.user_given_name || device.name || device.ieee, name: device.user_given_name || device.name || device.ieee,
context: area?.name,
category, category,
value: isCoordinator ? 3 : device.device_type === "Router" ? 2 : 1, value: isCoordinator ? 3 : device.device_type === "Router" ? 2 : 1,
symbolSize: isCoordinator symbolSize: isCoordinator

View File

@@ -5,6 +5,7 @@ import type {
import { css, html, LitElement } from "lit"; import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { getDeviceContext } from "../../../../../common/entity/context/get_device_context";
import { navigate } from "../../../../../common/navigate"; import { navigate } from "../../../../../common/navigate";
import { debounce } from "../../../../../common/util/debounce"; import { debounce } from "../../../../../common/util/debounce";
import "../../../../../components/chart/ha-network-graph"; import "../../../../../components/chart/ha-network-graph";
@@ -124,7 +125,7 @@ export class ZWaveJSNetworkVisualization extends SubscribeMixin(LitElement) {
return tip; return tip;
} }
const { id, name } = data as any; const { id, name } = data as any;
const device = this._devices[id]; const device = this._devices[id] as DeviceRegistryEntry | undefined;
const nodeStatus = this._nodeStatuses[id]; const nodeStatus = this._nodeStatuses[id];
let tip = `${(params as any).marker} ${name}`; let tip = `${(params as any).marker} ${name}`;
tip += `<br><b>${this.hass.localize("ui.panel.config.zwave_js.visualization.node_id")}:</b> ${id}`; tip += `<br><b>${this.hass.localize("ui.panel.config.zwave_js.visualization.node_id")}:</b> ${id}`;
@@ -138,6 +139,12 @@ export class ZWaveJSNetworkVisualization extends SubscribeMixin(LitElement) {
tip += `<br><b>Z-Wave Plus:</b> ${this.hass.localize("ui.panel.config.zwave_js.visualization.version")} ${nodeStatus.zwave_plus_version}`; tip += `<br><b>Z-Wave Plus:</b> ${this.hass.localize("ui.panel.config.zwave_js.visualization.version")} ${nodeStatus.zwave_plus_version}`;
} }
} }
if (device) {
const area = getDeviceContext(device, this.hass).area;
if (area) {
tip += `<br><b>${this.hass.localize("ui.panel.config.zwave_js.visualization.area")}:</b> ${area.name}`;
}
}
return tip; return tip;
}; };
@@ -197,10 +204,16 @@ export class ZWaveJSNetworkVisualization extends SubscribeMixin(LitElement) {
if (node.is_controller_node) { if (node.is_controller_node) {
controllerNode = node.node_id; controllerNode = node.node_id;
} }
const device = this._devices[node.node_id]; const device = this._devices[node.node_id] as
| DeviceRegistryEntry
| undefined;
const area = device
? getDeviceContext(device, this.hass).area
: undefined;
nodes.push({ nodes.push({
id: String(node.node_id), id: String(node.node_id),
name: device?.name_by_user ?? device?.name ?? String(node.node_id), name: device?.name_by_user ?? device?.name ?? String(node.node_id),
context: area?.name,
value: node.is_controller_node ? 3 : node.is_routing ? 2 : 1, value: node.is_controller_node ? 3 : node.is_routing ? 2 : 1,
category: category:
node.status === NodeStatus.Dead node.status === NodeStatus.Dead

View File

@@ -320,9 +320,9 @@ export class HaConfigLovelaceDashboards extends LitElement {
if (this.hass.panels.light) { if (this.hass.panels.light) {
result.push({ result.push({
icon: "mdi:lamps", icon: this.hass.panels.light.icon || "mdi:lamps",
title: this.hass.localize("panel.light"), title: this.hass.localize("panel.light"),
show_in_sidebar: false, show_in_sidebar: true,
mode: "storage", mode: "storage",
url_path: "light", url_path: "light",
filename: "", filename: "",
@@ -334,9 +334,9 @@ export class HaConfigLovelaceDashboards extends LitElement {
if (this.hass.panels.security) { if (this.hass.panels.security) {
result.push({ result.push({
icon: "mdi:security", icon: this.hass.panels.security.icon || "mdi:security",
title: this.hass.localize("panel.security"), title: this.hass.localize("panel.security"),
show_in_sidebar: false, show_in_sidebar: true,
mode: "storage", mode: "storage",
url_path: "security", url_path: "security",
filename: "", filename: "",
@@ -348,9 +348,9 @@ export class HaConfigLovelaceDashboards extends LitElement {
if (this.hass.panels.climate) { if (this.hass.panels.climate) {
result.push({ result.push({
icon: "mdi:home-thermometer", icon: this.hass.panels.climate.icon || "mdi:home-thermometer",
title: this.hass.localize("panel.climate"), title: this.hass.localize("panel.climate"),
show_in_sidebar: false, show_in_sidebar: true,
mode: "storage", mode: "storage",
url_path: "climate", url_path: "climate",
filename: "", filename: "",
@@ -360,6 +360,20 @@ export class HaConfigLovelaceDashboards extends LitElement {
}); });
} }
if (this.hass.panels.home) {
result.push({
icon: this.hass.panels.home.icon || "mdi:home",
title: this.hass.localize("panel.home"),
show_in_sidebar: true,
mode: "storage",
url_path: "home",
filename: "",
default: false,
require_admin: false,
type: this._localizeType("built_in"),
});
}
result.push( result.push(
...dashboards ...dashboards
.sort((a, b) => .sort((a, b) =>
@@ -470,13 +484,18 @@ export class HaConfigLovelaceDashboards extends LitElement {
} }
private _canDelete(urlPath: string) { private _canDelete(urlPath: string) {
return !["lovelace", "energy", "light", "security", "climate"].includes( return ![
urlPath "lovelace",
); "energy",
"light",
"security",
"climate",
"home",
].includes(urlPath);
} }
private _canEdit(urlPath: string) { private _canEdit(urlPath: string) {
return !["light", "security", "climate"].includes(urlPath); return !["light", "security", "climate", "home"].includes(urlPath);
} }
private _handleDelete = async (item: DataTableItem) => { private _handleDelete = async (item: DataTableItem) => {

View File

@@ -41,7 +41,6 @@ class DialogRepairsIssueSubtitle extends LitElement {
:host { :host {
display: block; display: block;
font-size: var(--ha-font-size-m); font-size: var(--ha-font-size-m);
margin-bottom: 8px;
color: var(--secondary-text-color); color: var(--secondary-text-color);
text-overflow: ellipsis; text-overflow: ellipsis;
overflow: hidden; overflow: hidden;

View File

@@ -1,15 +1,14 @@
import { mdiClose, mdiOpenInNew } from "@mdi/js"; import { mdiOpenInNew } from "@mdi/js";
import type { CSSResultGroup } from "lit"; import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state, query } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event"; import { fireEvent } from "../../../common/dom/fire_event";
import { isNavigationClick } from "../../../common/dom/is-navigation-click"; import { isNavigationClick } from "../../../common/dom/is-navigation-click";
import "../../../components/ha-alert"; import "../../../components/ha-alert";
import "../../../components/ha-md-dialog"; import "../../../components/ha-wa-dialog";
import type { HaMdDialog } from "../../../components/ha-md-dialog";
import "../../../components/ha-button"; import "../../../components/ha-button";
import "../../../components/ha-svg-icon"; import "../../../components/ha-svg-icon";
import "../../../components/ha-dialog-header"; import "../../../components/ha-dialog-footer";
import "./dialog-repairs-issue-subtitle"; import "./dialog-repairs-issue-subtitle";
import "../../../components/ha-markdown"; import "../../../components/ha-markdown";
import type { RepairsIssue } from "../../../data/repairs"; import type { RepairsIssue } from "../../../data/repairs";
@@ -26,11 +25,12 @@ class DialogRepairsIssue extends LitElement {
@state() private _params?: RepairsIssueDialogParams; @state() private _params?: RepairsIssueDialogParams;
@query("ha-md-dialog") private _dialog?: HaMdDialog; @state() private _open = false;
public showDialog(params: RepairsIssueDialogParams): void { public showDialog(params: RepairsIssueDialogParams): void {
this._params = params; this._params = params;
this._issue = this._params.issue; this._issue = this._params.issue;
this._open = true;
} }
private _dialogClosed() { private _dialogClosed() {
@@ -44,7 +44,7 @@ class DialogRepairsIssue extends LitElement {
} }
public closeDialog() { public closeDialog() {
this._dialog?.close(); this._open = false;
} }
protected render() { protected render() {
@@ -62,32 +62,19 @@ class DialogRepairsIssue extends LitElement {
) || this.hass!.localize("ui.panel.config.repairs.dialog.title"); ) || this.hass!.localize("ui.panel.config.repairs.dialog.title");
return html` return html`
<ha-md-dialog <ha-wa-dialog
open .hass=${this.hass}
@closed=${this._dialogClosed} .open=${this._open}
aria-labelledby="dialog-repairs-issue-title" header-title=${dialogTitle}
aria-describedby="dialog-repairs-issue-description" aria-describedby="dialog-repairs-issue-description"
> @closed=${this._dialogClosed}
<ha-dialog-header slot="headline">
<ha-icon-button
slot="navigationIcon"
.label=${this.hass.localize("ui.common.close") ?? "Close"}
.path=${mdiClose}
@click=${this.closeDialog}
></ha-icon-button>
<span
slot="title"
id="dialog-repairs-issue-title"
.title=${dialogTitle}
>${dialogTitle}</span
> >
<dialog-repairs-issue-subtitle <dialog-repairs-issue-subtitle
slot="subtitle" slot="headerSubtitle"
.hass=${this.hass} .hass=${this.hass}
.issue=${this._issue} .issue=${this._issue}
></dialog-repairs-issue-subtitle> ></dialog-repairs-issue-subtitle>
</ha-dialog-header> <div class="dialog-content">
<div slot="content" class="dialog-content">
${this._issue.breaks_in_ha_version ${this._issue.breaks_in_ha_version
? html` ? html`
<ha-alert alert-type="warning"> <ha-alert alert-type="warning">
@@ -122,8 +109,12 @@ class DialogRepairsIssue extends LitElement {
` `
: ""} : ""}
</div> </div>
<div slot="actions"> <ha-dialog-footer slot="footer">
<ha-button appearance="plain" @click=${this._ignoreIssue}> <ha-button
slot="secondaryAction"
appearance="plain"
@click=${this._ignoreIssue}
>
${this._issue!.ignored ${this._issue!.ignored
? this.hass!.localize("ui.panel.config.repairs.dialog.unignore") ? this.hass!.localize("ui.panel.config.repairs.dialog.unignore")
: this.hass!.localize("ui.panel.config.repairs.dialog.ignore")} : this.hass!.localize("ui.panel.config.repairs.dialog.ignore")}
@@ -131,6 +122,7 @@ class DialogRepairsIssue extends LitElement {
${this._issue.learn_more_url ${this._issue.learn_more_url
? html` ? html`
<ha-button <ha-button
slot="primaryAction"
appearance="filled" appearance="filled"
rel="noopener noreferrer" rel="noopener noreferrer"
href=${learnMoreUrlIsHomeAssistant href=${learnMoreUrlIsHomeAssistant
@@ -149,8 +141,8 @@ class DialogRepairsIssue extends LitElement {
</ha-button> </ha-button>
` `
: ""} : ""}
</div> </ha-dialog-footer>
</ha-md-dialog> </ha-wa-dialog>
`; `;
} }
@@ -172,7 +164,7 @@ class DialogRepairsIssue extends LitElement {
padding-top: 0; padding-top: 0;
} }
ha-alert { ha-alert {
margin-bottom: 16px; margin-bottom: var(--ha-space-4);
display: block; display: block;
} }
.dismissed { .dismissed {

View File

@@ -473,7 +473,10 @@ class HaSceneDashboard extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -65,13 +65,15 @@ export default class HaScriptFieldRow extends LitElement {
private _selectorRowElement?: HaAutomationRow; private _selectorRowElement?: HaAutomationRow;
protected render() { protected render() {
const hasSelector =
this.field.selector && typeof this.field.selector === "object";
return html` return html`
<ha-card outlined> <ha-card outlined>
<ha-automation-row <ha-automation-row
.disabled=${this.disabled} .disabled=${this.disabled}
@click=${this._toggleSidebar} @click=${this._toggleSidebar}
.selected=${this._selected} .selected=${this._selected}
left-chevron .leftChevron=${hasSelector}
@toggle-collapsed=${this._toggleCollapse} @toggle-collapsed=${this._toggleCollapse}
.collapsed=${this._collapsed} .collapsed=${this._collapsed}
.highlight=${this.highlight} .highlight=${this.highlight}
@@ -140,6 +142,8 @@ export default class HaScriptFieldRow extends LitElement {
<slot name="icons" slot="icons"></slot> <slot name="icons" slot="icons"></slot>
</ha-automation-row> </ha-automation-row>
</ha-card> </ha-card>
${hasSelector
? html`
<div <div
class=${classMap({ class=${classMap({
"selector-row": true, "selector-row": true,
@@ -203,7 +207,10 @@ export default class HaScriptFieldRow extends LitElement {
.disabled=${this.disabled} .disabled=${this.disabled}
class="warning" class="warning"
> >
<ha-svg-icon slot="start" .path=${mdiDelete}></ha-svg-icon> <ha-svg-icon
slot="start"
.path=${mdiDelete}
></ha-svg-icon>
<div class="overflow-label"> <div class="overflow-label">
${this.hass.localize( ${this.hass.localize(
"ui.panel.config.automation.editor.actions.delete" "ui.panel.config.automation.editor.actions.delete"
@@ -251,6 +258,8 @@ export default class HaScriptFieldRow extends LitElement {
` `
: nothing} : nothing}
</div> </div>
`
: nothing}
`; `;
} }

View File

@@ -458,7 +458,10 @@ class HaScriptPicker extends SubscribeMixin(LitElement) {
.checked=${selected} .checked=${selected}
.indeterminate=${partial} .indeterminate=${partial}
></ha-checkbox> ></ha-checkbox>
<ha-label style=${color ? `--color: ${color}` : ""}> <ha-label
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -371,7 +371,11 @@ export class HaManualScriptEditor extends LitElement {
} }
} }
if (!["sequence", "unknown"].includes(getActionType(config))) { const actionType = getActionType(config);
if (
!["sequence", "unknown"].includes(actionType) ||
(actionType === "sequence" && "metadata" in config)
) {
config = { sequence: [config] }; config = { sequence: [config] };
} }

View File

@@ -90,7 +90,6 @@ export class HaConfigUsers extends LitElement {
title: localize("ui.panel.config.users.picker.headers.username"), title: localize("ui.panel.config.users.picker.headers.username"),
sortable: true, sortable: true,
filterable: true, filterable: true,
direction: "asc",
template: (user) => html`${user.username || "—"}`, template: (user) => html`${user.username || "—"}`,
}, },
group: { group: {
@@ -98,7 +97,6 @@ export class HaConfigUsers extends LitElement {
sortable: true, sortable: true,
filterable: true, filterable: true,
groupable: true, groupable: true,
direction: "asc",
}, },
is_active: { is_active: {
title: this.hass.localize( title: this.hass.localize(

View File

@@ -0,0 +1,144 @@
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import type { LovelaceDashboardStrategyConfig } from "../../data/lovelace/config/types";
import type { HomeAssistant, PanelInfo, Route } from "../../types";
import "../lovelace/hui-root";
import { generateLovelaceDashboardStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import { showAlertDialog } from "../lovelace/custom-card-helpers";
const HOME_LOVELACE_CONFIG: LovelaceDashboardStrategyConfig = {
strategy: {
type: "home",
},
};
@customElement("ha-panel-home")
class PanelHome extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@property({ attribute: false }) public route?: Route;
@property({ attribute: false }) public panel?: PanelInfo;
@state() private _lovelace?: Lovelace;
public willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
// Initial setup
if (!this.hasUpdated) {
this.hass.loadFragmentTranslation("lovelace");
this._setLovelace();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// If the entity registry changed, ask the user if they want to refresh the config
if (
oldHass.entities !== this.hass.entities ||
oldHass.devices !== this.hass.devices ||
oldHass.areas !== this.hass.areas ||
oldHass.floors !== this.hass.floors
) {
if (this.hass.config.state === "RUNNING") {
this._debounceRegistriesChanged();
return;
}
}
// If ha started, refresh the config
if (
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setLovelace();
}
}
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
);
private _registriesChanged = async () => {
this._setLovelace();
};
protected render() {
if (!this._lovelace) {
return nothing;
}
return html`
<hui-root
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.route=${this.route}
.panel=${this.panel}
></hui-root>
`;
}
private async _setLovelace() {
const config = await generateLovelaceDashboardStrategy(
HOME_LOVELACE_CONFIG,
this.hass
);
if (deepEqual(config, this._lovelace?.config)) {
return;
}
this._lovelace = {
config: config,
rawConfig: config,
editMode: false,
urlPath: "home",
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: this._setEditMode,
showToast: () => undefined,
};
}
private _setEditMode = () => {
// For now, we just show an alert that edit mode is not supported.
// This will be expanded in the future.
showAlertDialog(this, {
title: "Edit mode not available",
text: "The Home panel does not support edit mode.",
confirmText: this.hass.localize("ui.common.ok"),
});
};
static readonly styles: CSSResultGroup = css`
:host {
display: block;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-panel-home": PanelHome;
}
}

View File

@@ -5,10 +5,7 @@ import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon"; import "../../../components/ha-svg-icon";
import type { LovelaceBadgeConfig } from "../../../data/lovelace/config/badge"; import type { LovelaceBadgeConfig } from "../../../data/lovelace/config/badge";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import { import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
ConditionalListenerMixin,
setupMediaQueryListeners,
} from "../../../mixins/conditional-listener-mixin";
import { checkConditionsMet } from "../common/validate-condition"; import { checkConditionsMet } from "../common/validate-condition";
import { createBadgeElement } from "../create-element/create-badge-element"; import { createBadgeElement } from "../create-element/create-badge-element";
import { createErrorBadgeConfig } from "../create-element/create-element-base"; import { createErrorBadgeConfig } from "../create-element/create-element-base";
@@ -22,7 +19,9 @@ declare global {
} }
@customElement("hui-badge") @customElement("hui-badge")
export class HuiBadge extends ConditionalListenerMixin(ReactiveElement) { export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
ReactiveElement
) {
@property({ type: Boolean }) public preview = false; @property({ type: Boolean }) public preview = false;
@property({ attribute: false }) public config?: LovelaceBadgeConfig; @property({ attribute: false }) public config?: LovelaceBadgeConfig;
@@ -53,7 +52,7 @@ export class HuiBadge extends ConditionalListenerMixin(ReactiveElement) {
this._updateVisibility(); this._updateVisibility();
} }
private _updateElement(config: LovelaceBadgeConfig) { protected _updateElement(config: LovelaceBadgeConfig) {
if (!this._element) { if (!this._element) {
return; return;
} }
@@ -133,22 +132,7 @@ export class HuiBadge extends ConditionalListenerMixin(ReactiveElement) {
} }
} }
protected setupConditionalListeners() { protected _updateVisibility(conditionsMet?: boolean) {
if (!this.config?.visibility || !this.hass) {
return;
}
setupMediaQueryListeners(
this.config.visibility,
this.hass,
(unsub) => this.addConditionalListener(unsub),
(conditionsMet) => {
this._updateVisibility(conditionsMet);
}
);
}
private _updateVisibility(ignoreConditions?: boolean) {
if (!this._element || !this.hass) { if (!this._element || !this.hass) {
return; return;
} }
@@ -169,9 +153,9 @@ export class HuiBadge extends ConditionalListenerMixin(ReactiveElement) {
} }
const visible = const visible =
ignoreConditions || conditionsMet ??
!this.config?.visibility || (!this.config?.visibility ||
checkConditionsMet(this.config.visibility, this.hass); checkConditionsMet(this.config.visibility, this.hass));
this._setElementVisibility(visible); this._setElementVisibility(visible);
} }

View File

@@ -8,6 +8,7 @@ import memoizeOne from "memoize-one";
import type { BarSeriesOption, PieSeriesOption } from "echarts/charts"; import type { BarSeriesOption, PieSeriesOption } from "echarts/charts";
import { PieChart } from "echarts/charts"; import { PieChart } from "echarts/charts";
import type { ECElementEvent } from "echarts/types/dist/shared"; import type { ECElementEvent } from "echarts/types/dist/shared";
import type { PieDataItemOption } from "echarts/types/src/chart/pie/PieSeries";
import { filterXSS } from "../../../../common/util/xss"; import { filterXSS } from "../../../../common/util/xss";
import { getGraphColorByIndex } from "../../../../common/color/colors"; import { getGraphColorByIndex } from "../../../../common/color/colors";
import { formatNumber } from "../../../../common/number/format_number"; import { formatNumber } from "../../../../common/number/format_number";
@@ -387,6 +388,7 @@ export class HuiEnergyDevicesGraphCard
}); });
if (this._chartType === "pie") { if (this._chartType === "pie") {
const pieChartData = chartData as NonNullable<PieSeriesOption["data"]>;
const { summedData, compareSummedData } = getSummedData(energyData); const { summedData, compareSummedData } = getSummedData(energyData);
const { consumption, compareConsumption } = computeConsumptionData( const { consumption, compareConsumption } = computeConsumptionData(
summedData, summedData,
@@ -399,7 +401,10 @@ export class HuiEnergyDevicesGraphCard
"from_battery" in summedData; "from_battery" in summedData;
const untracked = showUntracked const untracked = showUntracked
? totalUsed - ? totalUsed -
chartData.reduce((acc: number, d: any) => acc + d.value[0], 0) pieChartData.reduce(
(acc: number, d) => acc + (d as PieDataItemOption).value![0],
0
)
: 0; : 0;
if (untracked > 0) { if (untracked > 0) {
const color = getEnergyColor( const color = getEnergyColor(
@@ -409,7 +414,7 @@ export class HuiEnergyDevicesGraphCard
false, false,
"--history-unknown-color" "--history-unknown-color"
); );
chartData.push({ pieChartData.push({
id: "untracked", id: "untracked",
value: [untracked, "untracked"] as any, value: [untracked, "untracked"] as any,
name: this.hass.localize( name: this.hass.localize(
@@ -442,13 +447,20 @@ export class HuiEnergyDevicesGraphCard
} }
} }
} }
const totalChart = pieChartData.reduce(
(acc: number, d) =>
this._hiddenStats.includes((d as PieDataItemOption).id as string)
? acc
: acc + (d as PieDataItemOption).value![0],
0
);
datasets.push({ datasets.push({
type: "pie", type: "pie",
radius: ["0%", compareData ? "30%" : "40%"], radius: ["0%", compareData ? "30%" : "40%"],
name: this.hass.localize( name: this.hass.localize(
"ui.panel.lovelace.cards.energy.energy_devices_graph.total_energy_usage" "ui.panel.lovelace.cards.energy.energy_devices_graph.total_energy_usage"
), ),
data: [totalUsed], data: [totalChart],
label: { label: {
show: true, show: true,
position: "center", position: "center",
@@ -456,7 +468,7 @@ export class HuiEnergyDevicesGraphCard
fontSize: computedStyle.getPropertyValue("--ha-font-size-l"), fontSize: computedStyle.getPropertyValue("--ha-font-size-l"),
lineHeight: 24, lineHeight: 24,
fontWeight: "bold", fontWeight: "bold",
formatter: `{a}\n${formatNumber(totalUsed, this.hass.locale)} kWh`, formatter: `{a}\n${formatNumber(totalChart, this.hass.locale)} kWh`,
}, },
cursor: "default", cursor: "default",
itemStyle: { itemStyle: {

View File

@@ -5,10 +5,7 @@ import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon"; import "../../../components/ha-svg-icon";
import type { LovelaceCardConfig } from "../../../data/lovelace/config/card"; import type { LovelaceCardConfig } from "../../../data/lovelace/config/card";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import { import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
ConditionalListenerMixin,
setupMediaQueryListeners,
} from "../../../mixins/conditional-listener-mixin";
import { migrateLayoutToGridOptions } from "../common/compute-card-grid-size"; import { migrateLayoutToGridOptions } from "../common/compute-card-grid-size";
import { computeCardSize } from "../common/compute-card-size"; import { computeCardSize } from "../common/compute-card-size";
import { checkConditionsMet } from "../common/validate-condition"; import { checkConditionsMet } from "../common/validate-condition";
@@ -24,7 +21,9 @@ declare global {
} }
@customElement("hui-card") @customElement("hui-card")
export class HuiCard extends ConditionalListenerMixin(ReactiveElement) { export class HuiCard extends ConditionalListenerMixin<LovelaceCardConfig>(
ReactiveElement
) {
@property({ type: Boolean }) public preview = false; @property({ type: Boolean }) public preview = false;
@property({ attribute: false }) public config?: LovelaceCardConfig; @property({ attribute: false }) public config?: LovelaceCardConfig;
@@ -121,7 +120,7 @@ export class HuiCard extends ConditionalListenerMixin(ReactiveElement) {
return {}; return {};
} }
private _updateElement(config: LovelaceCardConfig) { protected _updateElement(config: LovelaceCardConfig) {
if (!this._element) { if (!this._element) {
return; return;
} }
@@ -247,22 +246,7 @@ export class HuiCard extends ConditionalListenerMixin(ReactiveElement) {
} }
} }
protected setupConditionalListeners() { protected _updateVisibility(conditionsMet?: boolean) {
if (!this.config?.visibility || !this.hass) {
return;
}
setupMediaQueryListeners(
this.config.visibility,
this.hass,
(unsub) => this.addConditionalListener(unsub),
(conditionsMet) => {
this._updateVisibility(conditionsMet);
}
);
}
private _updateVisibility(ignoreConditions?: boolean) {
if (!this._element || !this.hass) { if (!this._element || !this.hass) {
return; return;
} }
@@ -283,9 +267,9 @@ export class HuiCard extends ConditionalListenerMixin(ReactiveElement) {
} }
const visible = const visible =
ignoreConditions || conditionsMet ??
!this.config?.visibility || (!this.config?.visibility ||
checkConditionsMet(this.config.visibility, this.hass); checkConditionsMet(this.config.visibility, this.hass));
this._setElementVisibility(visible); this._setElementVisibility(visible);
} }

View File

@@ -175,9 +175,9 @@ export class HuiStatisticsGraphCard extends LitElement implements LovelaceCard {
this._names = {}; this._names = {};
this._entities.forEach((config) => { this._entities.forEach((config) => {
const stateObj = this.hass!.states[config.entity]; const stateObj = this.hass!.states[config.entity];
this._names[config.entity] = stateObj this._names[config.entity] =
? computeLovelaceEntityName(this.hass!, stateObj, config.name) computeLovelaceEntityName(this.hass!, stateObj, config.name) ||
: config.entity; config.entity;
}); });
} }

View File

@@ -50,7 +50,8 @@ export const coordinates = (
width: number, width: number,
height: number, height: number,
maxDetails: number, maxDetails: number,
limits?: { minX?: number; maxX?: number; minY?: number; maxY?: number } limits?: { minX?: number; maxX?: number; minY?: number; maxY?: number },
useMean = false
) => { ) => {
history = history.filter((item) => !Number.isNaN(item[1])); history = history.filter((item) => !Number.isNaN(item[1]));
@@ -58,7 +59,8 @@ export const coordinates = (
history, history,
maxDetails, maxDetails,
limits?.minX, limits?.minX,
limits?.maxX limits?.maxX,
useMean
); );
return calcPoints(sampledData, width, height, limits); return calcPoints(sampledData, width, height, limits);
}; };
@@ -68,7 +70,8 @@ export const coordinatesMinimalResponseCompressedState = (
width: number, width: number,
height: number, height: number,
maxDetails: number, maxDetails: number,
limits?: { minX?: number; maxX?: number; minY?: number; maxY?: number } limits?: { minX?: number; maxX?: number; minY?: number; maxY?: number },
useMean = false
) => { ) => {
if (!history?.length) { if (!history?.length) {
return { points: [], yAxisOrigin: 0 }; return { points: [], yAxisOrigin: 0 };
@@ -80,5 +83,5 @@ export const coordinatesMinimalResponseCompressedState = (
item.lu * 1000, item.lu * 1000,
Number(item.s), Number(item.s),
]); ]);
return coordinates(mappedHistory, width, height, maxDetails, limits); return coordinates(mappedHistory, width, height, maxDetails, limits, useMean);
}; };

View File

@@ -1,6 +1,7 @@
import { import {
mdiAccount, mdiAccount,
mdiAmpersand, mdiAmpersand,
mdiCalendarClock,
mdiGateOr, mdiGateOr,
mdiMapMarker, mdiMapMarker,
mdiNotEqualVariant, mdiNotEqualVariant,
@@ -15,6 +16,7 @@ export const ICON_CONDITION: Record<Condition["condition"], string> = {
numeric_state: mdiNumeric, numeric_state: mdiNumeric,
state: mdiStateMachine, state: mdiStateMachine,
screen: mdiResponsive, screen: mdiResponsive,
time: mdiCalendarClock,
user: mdiAccount, user: mdiAccount,
and: mdiAmpersand, and: mdiAmpersand,
not: mdiNotEqualVariant, not: mdiNotEqualVariant,

View File

@@ -1,15 +1,23 @@
import { ensureArray } from "../../../common/array/ensure-array"; import type { HomeAssistant } from "../../../types";
import { isValidEntityId } from "../../../common/entity/valid_entity_id";
import { UNKNOWN } from "../../../data/entity"; import { UNKNOWN } from "../../../data/entity";
import { getUserPerson } from "../../../data/person"; import { getUserPerson } from "../../../data/person";
import type { HomeAssistant } from "../../../types"; import { ensureArray } from "../../../common/array/ensure-array";
import {
checkTimeInRange,
isValidTimeString,
} from "../../../common/datetime/check_time";
import {
WEEKDAYS_SHORT,
type WeekdayShort,
} from "../../../common/datetime/weekday";
import { isValidEntityId } from "../../../common/entity/valid_entity_id";
export type Condition = export type Condition =
| LocationCondition | LocationCondition
| NumericStateCondition | NumericStateCondition
| StateCondition | StateCondition
| ScreenCondition | ScreenCondition
| TimeCondition
| UserCondition | UserCondition
| OrCondition | OrCondition
| AndCondition | AndCondition
@@ -50,6 +58,13 @@ export interface ScreenCondition extends BaseCondition {
media_query?: string; media_query?: string;
} }
export interface TimeCondition extends BaseCondition {
condition: "time";
after?: string;
before?: string;
weekdays?: WeekdayShort[];
}
export interface UserCondition extends BaseCondition { export interface UserCondition extends BaseCondition {
condition: "user"; condition: "user";
users?: string[]; users?: string[];
@@ -150,6 +165,13 @@ function checkScreenCondition(condition: ScreenCondition, _: HomeAssistant) {
: false; : false;
} }
function checkTimeCondition(
condition: Omit<TimeCondition, "condition">,
hass: HomeAssistant
) {
return checkTimeInRange(hass, condition);
}
function checkLocationCondition( function checkLocationCondition(
condition: LocationCondition, condition: LocationCondition,
hass: HomeAssistant hass: HomeAssistant
@@ -195,6 +217,8 @@ export function checkConditionsMet(
return conditions.every((c) => { return conditions.every((c) => {
if ("condition" in c) { if ("condition" in c) {
switch (c.condition) { switch (c.condition) {
case "time":
return checkTimeCondition(c, hass);
case "screen": case "screen":
return checkScreenCondition(c, hass); return checkScreenCondition(c, hass);
case "user": case "user":
@@ -271,6 +295,35 @@ function validateScreenCondition(condition: ScreenCondition) {
return condition.media_query != null; return condition.media_query != null;
} }
function validateTimeCondition(condition: TimeCondition) {
// Check if time strings are present and non-empty
const hasAfter = condition.after != null && condition.after !== "";
const hasBefore = condition.before != null && condition.before !== "";
const hasTime = hasAfter || hasBefore;
const hasWeekdays =
condition.weekdays != null && condition.weekdays.length > 0;
const weekdaysValid =
!hasWeekdays ||
condition.weekdays!.every((w: WeekdayShort) => WEEKDAYS_SHORT.includes(w));
// Validate time string formats if present
const timeStringsValid =
(!hasAfter || isValidTimeString(condition.after!)) &&
(!hasBefore || isValidTimeString(condition.before!));
// Prevent after and before being identical (creates zero-length interval)
const timeRangeValid =
!hasAfter || !hasBefore || condition.after !== condition.before;
return (
(hasTime || hasWeekdays) &&
weekdaysValid &&
timeStringsValid &&
timeRangeValid
);
}
function validateUserCondition(condition: UserCondition) { function validateUserCondition(condition: UserCondition) {
return condition.users != null; return condition.users != null;
} }
@@ -310,6 +363,8 @@ export function validateConditionalConfig(
switch (c.condition) { switch (c.condition) {
case "screen": case "screen":
return validateScreenCondition(c); return validateScreenCondition(c);
case "time":
return validateTimeCondition(c);
case "user": case "user":
return validateUserCondition(c); return validateUserCondition(c);
case "location": case "location":

View File

@@ -2,10 +2,7 @@ import type { PropertyValues } from "lit";
import { ReactiveElement } from "lit"; import { ReactiveElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import { import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
ConditionalListenerMixin,
setupMediaQueryListeners,
} from "../../../mixins/conditional-listener-mixin";
import type { HuiCard } from "../cards/hui-card"; import type { HuiCard } from "../cards/hui-card";
import type { ConditionalCardConfig } from "../cards/types"; import type { ConditionalCardConfig } from "../cards/types";
import type { Condition } from "../common/validate-condition"; import type { Condition } from "../common/validate-condition";
@@ -22,9 +19,9 @@ declare global {
} }
@customElement("hui-conditional-base") @customElement("hui-conditional-base")
export class HuiConditionalBase extends ConditionalListenerMixin( export class HuiConditionalBase extends ConditionalListenerMixin<
ReactiveElement ConditionalCardConfig | ConditionalRowConfig
) { >(ReactiveElement) {
@property({ attribute: false }) public hass?: HomeAssistant; @property({ attribute: false }) public hass?: HomeAssistant;
@property({ type: Boolean }) public preview = false; @property({ type: Boolean }) public preview = false;
@@ -73,18 +70,13 @@ export class HuiConditionalBase extends ConditionalListenerMixin(
return; return;
} }
// Filter to supported conditions (those with 'condition' property)
const supportedConditions = this._config.conditions.filter( const supportedConditions = this._config.conditions.filter(
(c) => "condition" in c (c) => "condition" in c
) as Condition[]; ) as Condition[];
setupMediaQueryListeners( // Pass filtered conditions to parent implementation
supportedConditions, super.setupConditionalListeners(supportedConditions);
this.hass,
(unsub) => this.addConditionalListener(unsub),
(conditionsMet) => {
this.setVisibility(conditionsMet);
}
);
} }
protected update(changed: PropertyValues): void { protected update(changed: PropertyValues): void {
@@ -102,17 +94,15 @@ export class HuiConditionalBase extends ConditionalListenerMixin(
} }
} }
private _updateVisibility() { protected _updateVisibility(conditionsMet?: boolean) {
if (!this._element || !this.hass || !this._config) { if (!this._element || !this.hass || !this._config) {
return; return;
} }
this._element.preview = this.preview; this._element.preview = this.preview;
const conditionMet = checkConditionsMet( const conditionMet =
this._config!.conditions, conditionsMet ?? checkConditionsMet(this._config.conditions, this.hass);
this.hass!
);
this.setVisibility(conditionMet); this.setVisibility(conditionMet);
} }

View File

@@ -39,21 +39,23 @@ export class HuiEntityEditor extends LitElement {
private _renderItem(item: EntityConfig, index: number) { private _renderItem(item: EntityConfig, index: number) {
const stateObj = this.hass.states[item.entity]; const stateObj = this.hass.states[item.entity];
const useDeviceName = entityUseDeviceName( const useDeviceName =
stateObj, stateObj &&
this.hass.entities, entityUseDeviceName(stateObj, this.hass.entities, this.hass.devices);
this.hass.devices
);
const isRTL = computeRTL(this.hass); const isRTL = computeRTL(this.hass);
const primary = const primary =
(stateObj &&
this.hass.formatEntityName( this.hass.formatEntityName(
stateObj, stateObj,
useDeviceName ? { type: "device" } : { type: "entity" } useDeviceName ? { type: "device" } : { type: "entity" }
) || item.entity; )) ||
item.entity;
const secondary = this.hass.formatEntityName( const secondary =
stateObj &&
this.hass.formatEntityName(
stateObj, stateObj,
useDeviceName useDeviceName
? [{ type: "area" }] ? [{ type: "area" }]

View File

@@ -4,11 +4,14 @@ import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map"; import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined"; import { ifDefined } from "lit/directives/if-defined";
import { DOMAINS_INPUT_ROW } from "../../../common/const"; import { DOMAINS_INPUT_ROW } from "../../../common/const";
import { uid } from "../../../common/util/uid";
import { stopPropagation } from "../../../common/dom/stop_propagation"; import { stopPropagation } from "../../../common/dom/stop_propagation";
import { toggleAttribute } from "../../../common/dom/toggle_attribute"; import { toggleAttribute } from "../../../common/dom/toggle_attribute";
import { computeDomain } from "../../../common/entity/compute_domain"; import { computeDomain } from "../../../common/entity/compute_domain";
import { formatDateTimeWithSeconds } from "../../../common/datetime/format_date_time";
import "../../../components/entity/state-badge"; import "../../../components/entity/state-badge";
import "../../../components/ha-relative-time"; import "../../../components/ha-relative-time";
import "../../../components/ha-tooltip";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler"; import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types"; import type { EntitiesCardEntityConfig } from "../cards/types";
@@ -36,6 +39,8 @@ export class HuiGenericEntityRow extends LitElement {
@property({ attribute: "catch-interaction", type: Boolean }) @property({ attribute: "catch-interaction", type: Boolean })
public catchInteraction?; public catchInteraction?;
private _secondaryInfoElementId = "-" + uid();
protected render() { protected render() {
if (!this.hass || !this.config) { if (!this.hass || !this.config) {
return nothing; return nothing;
@@ -100,7 +105,19 @@ export class HuiGenericEntityRow extends LitElement {
? stateObj.entity_id ? stateObj.entity_id
: this.config.secondary_info === "last-changed" : this.config.secondary_info === "last-changed"
? html` ? html`
<ha-tooltip
for="last-changed${this
._secondaryInfoElementId}"
placement="right"
>
${formatDateTimeWithSeconds(
new Date(stateObj.last_changed),
this.hass.locale,
this.hass.config
)}
</ha-tooltip>
<ha-relative-time <ha-relative-time
id="last-changed${this._secondaryInfoElementId}"
.hass=${this.hass} .hass=${this.hass}
.datetime=${stateObj.last_changed} .datetime=${stateObj.last_changed}
capitalize capitalize
@@ -108,7 +125,20 @@ export class HuiGenericEntityRow extends LitElement {
` `
: this.config.secondary_info === "last-updated" : this.config.secondary_info === "last-updated"
? html` ? html`
<ha-tooltip
for="last-updated${this
._secondaryInfoElementId}"
placement="right"
>
${formatDateTimeWithSeconds(
new Date(stateObj.last_updated),
this.hass.locale,
this.hass.config
)}
</ha-tooltip>
<ha-relative-time <ha-relative-time
id="last-updated${this
._secondaryInfoElementId}"
.hass=${this.hass} .hass=${this.hass}
.datetime=${stateObj.last_updated} .datetime=${stateObj.last_updated}
capitalize capitalize
@@ -117,7 +147,22 @@ export class HuiGenericEntityRow extends LitElement {
: this.config.secondary_info === "last-triggered" : this.config.secondary_info === "last-triggered"
? stateObj.attributes.last_triggered ? stateObj.attributes.last_triggered
? html` ? html`
<ha-tooltip
for="last-triggered${this
._secondaryInfoElementId}"
placement="right"
>
${formatDateTimeWithSeconds(
new Date(
stateObj.attributes.last_triggered
),
this.hass.locale,
this.hass.config
)}
</ha-tooltip>
<ha-relative-time <ha-relative-time
id="last-triggered${this
._secondaryInfoElementId}"
.hass=${this.hass} .hass=${this.hass}
.datetime=${stateObj.attributes .datetime=${stateObj.attributes
.last_triggered} .last_triggered}

View File

@@ -25,6 +25,7 @@ import "./types/ha-card-condition-numeric_state";
import "./types/ha-card-condition-or"; import "./types/ha-card-condition-or";
import "./types/ha-card-condition-screen"; import "./types/ha-card-condition-screen";
import "./types/ha-card-condition-state"; import "./types/ha-card-condition-state";
import "./types/ha-card-condition-time";
import "./types/ha-card-condition-user"; import "./types/ha-card-condition-user";
import { storage } from "../../../../common/decorators/storage"; import { storage } from "../../../../common/decorators/storage";
@@ -33,6 +34,7 @@ const UI_CONDITION = [
"numeric_state", "numeric_state",
"state", "state",
"screen", "screen",
"time",
"user", "user",
"and", "and",
"not", "not",

View File

@@ -0,0 +1,102 @@
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import {
literal,
array,
object,
optional,
string,
assert,
enums,
} from "superstruct";
import memoizeOne from "memoize-one";
import type { HomeAssistant } from "../../../../../types";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import {
WEEKDAY_SHORT_TO_LONG,
WEEKDAYS_SHORT,
} from "../../../../../common/datetime/weekday";
import type { TimeCondition } from "../../../common/validate-condition";
import { fireEvent } from "../../../../../common/dom/fire_event";
import type {
HaFormSchema,
SchemaUnion,
} from "../../../../../components/ha-form/types";
import "../../../../../components/ha-form/ha-form";
const timeConditionStruct = object({
condition: literal("time"),
after: optional(string()),
before: optional(string()),
weekdays: optional(array(enums(WEEKDAYS_SHORT))),
});
@customElement("ha-card-condition-time")
export class HaCardConditionTime extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: TimeCondition;
@property({ type: Boolean }) public disabled = false;
public static get defaultConfig(): TimeCondition {
return { condition: "time", after: "08:00", before: "17:00" };
}
protected static validateUIConfig(condition: TimeCondition) {
return assert(condition, timeConditionStruct);
}
private _schema = memoizeOne(
(localize: LocalizeFunc) =>
[
{ name: "after", selector: { time: { no_second: true } } },
{ name: "before", selector: { time: { no_second: true } } },
{
name: "weekdays",
selector: {
select: {
mode: "list",
multiple: true,
options: WEEKDAYS_SHORT.map((day) => ({
value: day,
label: localize(`ui.weekdays.${WEEKDAY_SHORT_TO_LONG[day]}`),
})),
},
},
},
] as const satisfies HaFormSchema[]
);
protected render() {
return html`
<ha-form
.hass=${this.hass}
.data=${this.condition}
.computeLabel=${this._computeLabelCallback}
.schema=${this._schema(this.hass.localize)}
.disabled=${this.disabled}
@value-changed=${this._valueChanged}
></ha-form>
`;
}
private _valueChanged(ev: CustomEvent) {
ev.stopPropagation();
const data = ev.detail.value as TimeCondition;
fireEvent(this, "value-changed", { value: data });
}
private _computeLabelCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
): string =>
this.hass.localize(
`ui.panel.lovelace.editor.condition-editor.condition.time.${schema.name}`
);
}
declare global {
interface HTMLElementTagNameMap {
"ha-card-condition-time": HaCardConditionTime;
}
}

View File

@@ -155,16 +155,20 @@ export class HuiGraphHeaderFooter
} }
const width = this.clientWidth || this.offsetWidth; const width = this.clientWidth || this.offsetWidth;
// sample to 1 point per hour or 1 point per 5 pixels // sample to 1 point per hour or 1 point per 5 pixels
const maxDetails = const maxDetails = Math.max(
10,
this._config.detail! > 1 this._config.detail! > 1
? Math.max(width / 5, this._config.hours_to_show!) ? Math.max(width / 5, this._config.hours_to_show!)
: this._config.hours_to_show!; : this._config.hours_to_show!
);
const useMean = this._config.detail !== 2;
const { points } = coordinatesMinimalResponseCompressedState( const { points } = coordinatesMinimalResponseCompressedState(
combinedHistory[this._config.entity], combinedHistory[this._config.entity],
width, width,
width / 5, width / 5,
maxDetails, maxDetails,
{ minY: this._config.limits?.min, maxY: this._config.limits?.max } { minY: this._config.limits?.min, maxY: this._config.limits?.max },
useMean
); );
this._coordinates = points; this._coordinates = points;
}, },

View File

@@ -4,10 +4,7 @@ import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event"; import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon"; import "../../../components/ha-svg-icon";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import { import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
ConditionalListenerMixin,
setupMediaQueryListeners,
} from "../../../mixins/conditional-listener-mixin";
import { checkConditionsMet } from "../common/validate-condition"; import { checkConditionsMet } from "../common/validate-condition";
import { createHeadingBadgeElement } from "../create-element/create-heading-badge-element"; import { createHeadingBadgeElement } from "../create-element/create-heading-badge-element";
import type { LovelaceHeadingBadge } from "../types"; import type { LovelaceHeadingBadge } from "../types";
@@ -21,7 +18,9 @@ declare global {
} }
@customElement("hui-heading-badge") @customElement("hui-heading-badge")
export class HuiHeadingBadge extends ConditionalListenerMixin(ReactiveElement) { export class HuiHeadingBadge extends ConditionalListenerMixin<LovelaceHeadingBadgeConfig>(
ReactiveElement
) {
@property({ type: Boolean }) public preview = false; @property({ type: Boolean }) public preview = false;
@property({ attribute: false }) public config?: LovelaceHeadingBadgeConfig; @property({ attribute: false }) public config?: LovelaceHeadingBadgeConfig;
@@ -52,7 +51,7 @@ export class HuiHeadingBadge extends ConditionalListenerMixin(ReactiveElement) {
this._updateVisibility(); this._updateVisibility();
} }
private _updateElement(config: LovelaceHeadingBadgeConfig) { protected _updateElement(config: LovelaceHeadingBadgeConfig) {
if (!this._element) { if (!this._element) {
return; return;
} }
@@ -133,22 +132,7 @@ export class HuiHeadingBadge extends ConditionalListenerMixin(ReactiveElement) {
} }
} }
protected setupConditionalListeners() { protected _updateVisibility(conditionsMet?: boolean) {
if (!this.config?.visibility || !this.hass) {
return;
}
setupMediaQueryListeners(
this.config.visibility,
this.hass,
(unsub) => this.addConditionalListener(unsub),
(conditionsMet) => {
this._updateVisibility(conditionsMet);
}
);
}
private _updateVisibility(forceVisible?: boolean) {
if (!this._element || !this.hass) { if (!this._element || !this.hass) {
return; return;
} }
@@ -158,11 +142,20 @@ export class HuiHeadingBadge extends ConditionalListenerMixin(ReactiveElement) {
return; return;
} }
if (this.preview) {
this._setElementVisibility(true);
return;
}
if (this.config?.disabled) {
this._setElementVisibility(false);
return;
}
const visible = const visible =
forceVisible || conditionsMet ??
this.preview || (!this.config?.visibility ||
!this.config?.visibility || checkConditionsMet(this.config.visibility, this.hass));
checkConditionsMet(this.config.visibility, this.hass);
this._setElementVisibility(visible); this._setElementVisibility(visible);
} }

View File

@@ -13,10 +13,7 @@ import type {
} from "../../../data/lovelace/config/section"; } from "../../../data/lovelace/config/section";
import { isStrategySection } from "../../../data/lovelace/config/section"; import { isStrategySection } from "../../../data/lovelace/config/section";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import { import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
ConditionalListenerMixin,
setupMediaQueryListeners,
} from "../../../mixins/conditional-listener-mixin";
import "../cards/hui-card"; import "../cards/hui-card";
import type { HuiCard } from "../cards/hui-card"; import type { HuiCard } from "../cards/hui-card";
import { checkConditionsMet } from "../common/validate-condition"; import { checkConditionsMet } from "../common/validate-condition";
@@ -37,7 +34,9 @@ declare global {
} }
@customElement("hui-section") @customElement("hui-section")
export class HuiSection extends ConditionalListenerMixin(ReactiveElement) { export class HuiSection extends ConditionalListenerMixin<LovelaceSectionConfig>(
ReactiveElement
) {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public config!: LovelaceSectionRawConfig; @property({ attribute: false }) public config!: LovelaceSectionRawConfig;
@@ -59,8 +58,6 @@ export class HuiSection extends ConditionalListenerMixin(ReactiveElement) {
private _layoutElement?: LovelaceSectionElement; private _layoutElement?: LovelaceSectionElement;
private _config: LovelaceSectionConfig | undefined;
@storage({ @storage({
key: "dashboardCardClipboard", key: "dashboardCardClipboard",
state: false, state: false,
@@ -116,7 +113,7 @@ export class HuiSection extends ConditionalListenerMixin(ReactiveElement) {
public connectedCallback() { public connectedCallback() {
super.connectedCallback(); super.connectedCallback();
this._updateElement(); this._updateVisibility();
} }
protected update(changedProperties) { protected update(changedProperties) {
@@ -147,26 +144,11 @@ export class HuiSection extends ConditionalListenerMixin(ReactiveElement) {
this._layoutElement.cards = this._cards; this._layoutElement.cards = this._cards;
} }
if (changedProperties.has("hass") || changedProperties.has("preview")) { if (changedProperties.has("hass") || changedProperties.has("preview")) {
this._updateElement(); this._updateVisibility();
} }
} }
} }
protected setupConditionalListeners() {
if (!this._config?.visibility || !this.hass) {
return;
}
setupMediaQueryListeners(
this._config.visibility,
this.hass,
(unsub) => this.addConditionalListener(unsub),
(conditionsMet) => {
this._updateElement(conditionsMet);
}
);
}
private async _initializeConfig() { private async _initializeConfig() {
let sectionConfig = { ...this.config }; let sectionConfig = { ...this.config };
let isStrategy = false; let isStrategy = false;
@@ -208,11 +190,11 @@ export class HuiSection extends ConditionalListenerMixin(ReactiveElement) {
while (this.lastChild) { while (this.lastChild) {
this.removeChild(this.lastChild); this.removeChild(this.lastChild);
} }
this._updateElement(); this._updateVisibility();
} }
} }
private _updateElement(ignoreConditions?: boolean) { protected _updateVisibility(conditionsMet?: boolean) {
if (!this._layoutElement || !this._config) { if (!this._layoutElement || !this._config) {
return; return;
} }
@@ -228,9 +210,9 @@ export class HuiSection extends ConditionalListenerMixin(ReactiveElement) {
} }
const visible = const visible =
ignoreConditions || conditionsMet ??
!this._config.visibility || (!this._config.visibility ||
checkConditionsMet(this._config.visibility, this.hass); checkConditionsMet(this._config.visibility, this.hass));
this._setElementVisibility(visible); this._setElementVisibility(visible);
} }

View File

@@ -168,6 +168,27 @@ export class HomeAreaViewStrategy extends ReactiveElement {
const summaryEntities = Object.values(entitiesBySummary).flat(); const summaryEntities = Object.values(entitiesBySummary).flat();
// Scenes section
const sceneFilter = generateEntityFilter(hass, {
domain: "scene",
entity_category: "none",
});
const scenes = areaEntities.filter(sceneFilter);
if (scenes.length > 0) {
sections.push({
type: "grid",
cards: [
computeHeadingCard(
hass.localize("ui.panel.lovelace.strategy.home.scenes"),
"mdi:palette",
"/config/scene/dashboard"
),
...scenes.map(computeTileCard),
],
});
}
// Automations section // Automations section
const automationFilter = generateEntityFilter(hass, { const automationFilter = generateEntityFilter(hass, {
domain: "automation", domain: "automation",
@@ -178,7 +199,9 @@ export class HomeAreaViewStrategy extends ReactiveElement {
// Rest of entities grouped by device // Rest of entities grouped by device
const otherEntities = areaEntities.filter( const otherEntities = areaEntities.filter(
(entityId) => (entityId) =>
!summaryEntities.includes(entityId) && !automations.includes(entityId) !summaryEntities.includes(entityId) &&
!scenes.includes(entityId) &&
!automations.includes(entityId)
); );
const entitiesByDevice: Record<string, string[]> = {}; const entitiesByDevice: Record<string, string[]> = {};

View File

@@ -14,12 +14,14 @@ import memoizeOne from "memoize-one";
import { relativeTime } from "../../common/datetime/relative_time"; import { relativeTime } from "../../common/datetime/relative_time";
import { fireEvent } from "../../common/dom/fire_event"; import { fireEvent } from "../../common/dom/fire_event";
import "../../components/ha-button"; import "../../components/ha-button";
import "../../components/ha-md-button-menu";
import "../../components/ha-md-menu-item";
import "../../components/ha-card"; import "../../components/ha-card";
import "../../components/ha-dropdown";
import "../../components/ha-dropdown-item";
import "../../components/ha-icon-button"; import "../../components/ha-icon-button";
import "../../components/ha-label"; import "../../components/ha-label";
import "../../components/ha-list-item"; import "../../components/ha-list-item";
import "../../components/ha-md-button-menu";
import "../../components/ha-md-menu-item";
import "../../components/ha-settings-row"; import "../../components/ha-settings-row";
import { deleteAllRefreshTokens } from "../../data/auth"; import { deleteAllRefreshTokens } from "../../data/auth";
import type { RefreshToken } from "../../data/refresh_token"; import type { RefreshToken } from "../../data/refresh_token";
@@ -146,19 +148,18 @@ class HaRefreshTokens extends LitElement {
)} )}
</div> </div>
<div> <div>
<ha-md-button-menu positioning="popover"> <ha-dropdown @wa-select=${this._handleDropdownSelect}>
<ha-icon-button <ha-icon-button
slot="trigger" slot="trigger"
.label=${this.hass.localize("ui.common.menu")} .label=${this.hass.localize("ui.common.menu")}
.path=${mdiDotsVertical} .path=${mdiDotsVertical}
></ha-icon-button> ></ha-icon-button>
<ha-md-menu-item <ha-dropdown-item
graphic="icon"
@click=${this._toggleTokenExpiration}
.token=${token} .token=${token}
.action=${"toggle_expiration"}
> >
<ha-svg-icon <ha-svg-icon
slot="start" slot="icon"
.path=${token.expire_at .path=${token.expire_at
? mdiClockRemoveOutline ? mdiClockRemoveOutline
: mdiClockCheckOutline} : mdiClockCheckOutline}
@@ -170,24 +171,20 @@ class HaRefreshTokens extends LitElement {
: this.hass.localize( : this.hass.localize(
"ui.panel.profile.refresh_tokens.enable_token_expiration" "ui.panel.profile.refresh_tokens.enable_token_expiration"
)} )}
</ha-md-menu-item> </ha-dropdown-item>
<ha-md-menu-item <ha-dropdown-item
graphic="icon"
class="warning"
.disabled=${token.is_current}
@click=${this._deleteToken}
.token=${token} .token=${token}
.action=${"delete_token"}
variant="danger"
.disabled=${token.is_current}
> >
<ha-svg-icon <ha-svg-icon
class="warning" slot="icon"
slot="start"
.path=${mdiDelete} .path=${mdiDelete}
></ha-svg-icon> ></ha-svg-icon>
<div slot="headline">
${this.hass.localize("ui.common.delete")} ${this.hass.localize("ui.common.delete")}
</div> </ha-dropdown-item>
</ha-md-menu-item> </ha-dropdown>
</ha-md-button-menu>
</div> </div>
</ha-settings-row> </ha-settings-row>
` `
@@ -210,8 +207,17 @@ class HaRefreshTokens extends LitElement {
`; `;
} }
private async _toggleTokenExpiration(ev): Promise<void> { private _handleDropdownSelect(
const token = (ev.currentTarget as any).token as RefreshToken; ev: CustomEvent<{ item: { action: string; token: RefreshToken } }>
) {
if (ev.detail.item.action === "toggle_expiration") {
this._toggleTokenExpiration(ev.detail.item.token);
} else if (ev.detail.item.action === "delete_token") {
this._deleteToken(ev.detail.item.token);
}
}
private async _toggleTokenExpiration(token: RefreshToken): Promise<void> {
const enable = !token.expire_at; const enable = !token.expire_at;
if (!enable) { if (!enable) {
if ( if (
@@ -252,8 +258,7 @@ class HaRefreshTokens extends LitElement {
} }
} }
private async _deleteToken(ev): Promise<void> { private async _deleteToken(token: RefreshToken): Promise<void> {
const token = (ev.currentTarget as any).token as RefreshToken;
if ( if (
!(await showConfirmationDialog(this, { !(await showConfirmationDialog(this, {
title: this.hass.localize( title: this.hass.localize(

View File

@@ -199,3 +199,23 @@ export const baseEntrypointStyles = css`
width: 100vw; width: 100vw;
} }
`; `;
export const baseAnimationStyles = css`
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
`;

View File

@@ -74,6 +74,10 @@ export const coreColorStyles = css`
--ha-color-green-80: #93da98; --ha-color-green-80: #93da98;
--ha-color-green-90: #c2f2c1; --ha-color-green-90: #c2f2c1;
--ha-color-green-95: #e3f9e3; --ha-color-green-95: #e3f9e3;
/* shadow */
--ha-color-shadow-light: #00000014;
--ha-color-shadow-dark: #00000046;
} }
`; `;

View File

@@ -155,6 +155,7 @@ export const semanticColorStyles = css`
/* Surfaces */ /* Surfaces */
--ha-color-surface-default: var(--ha-color-neutral-95); --ha-color-surface-default: var(--ha-color-neutral-95);
--ha-color-on-surface-default: var(--ha-color-neutral-05);
} }
`; `;
@@ -286,5 +287,6 @@ export const darkSemanticColorStyles = css`
/* Surfaces */ /* Surfaces */
--ha-color-surface-default: var(--ha-color-neutral-10); --ha-color-surface-default: var(--ha-color-neutral-10);
--ha-color-on-surface-default: var(--ha-color-neutral-95);
} }
`; `;

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