Compare commits

...
Author SHA1 Message Date
WendelinandClaude Opus 5.5 fb7d5eb3af Prepare @home-assistant/components for its first beta release
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 11:27:14 +01:00
WendelinandClaude Opus 5.5 4bc3b0e9b0 Add hac-popover to the component library (#56348)
* Add hac-popover and a shared popup base to the component library

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Let themes set the popover's border, radius and padding

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Use a 1px border on the popover

Browsers round sub-pixel borders up to 1px anyway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Say why the popover closed and type its trigger

The hide events carry detail.reason, so a parent can react differently to
Escape than to a click outside. The trigger takes one word: click, hover
(which still opens on click) or manual.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hand aria-expanded to button components and document popover usage

The popover sets the ariaExpanded property instead of the attribute, so a
button component can pass it on to its inner button. Native buttons still
get the attribute. The JSDoc explains how to use the popover and that it is
not a tooltip. aria-controls and the generated id are gone, as no screen
reader relies on them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Say that the anchor hook does nothing by default

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Make the popup's open and close checks easier to read

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Use only semantic tokens in the popover

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Follow a replaced anchor and keep state when a hide is cancelled

A parent may render a new anchor with the same id; capture listeners on the
root bind it before its own events run. A cancelled hide keeps focus where
it is and keeps the popover pinned. Old browsers without min() keep the
popover within the free space.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Handle trigger changes, programmatic opens and anchor changes while open

Hover timers check the trigger when they fire. An anchor click closes a
popover opened from code. Open popups are tracked on window, so scoped
copies share one Escape order. While open, the popup rebinds to a replaced
anchor or closes when it is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Notice a removed anchor through autoUpdate instead of a MutationObserver

autoUpdate's ResizeObserver already fires when the anchor leaves the DOM,
so the reposition callback checks isConnected and rebinds or closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep the popover working inside a closed shadow root

A press inside a closed shadow root only shows its host to the document,
so the popup decides after its own and the anchor's listeners have seen
the press. Focus inside is looked up from the popup's own root.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep the popover at its anchor and hide it while the anchor is scrolled away

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Drop the undocumented base part of the popover

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 09:48:48 +00:00
afe3e31d9c Don't list disabled entities under the Unavailable status filter (#56438)
Claude-Session: https://claude.ai/code/session_01CDc15sh8fUNmnB9T6EqcML

Co-authored-by: stoppyz0r <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 09:08:45 +00:00
Petar Petrov db89abfc52 Measure initial column count in sections view before first render (#56424)
* Measure initial column count in sections view before first render

* Read column gap from custom property in sections view

* Resolve sections view column gap to pixels
2026-12-04 08:59:16 +00:00
cerealkiller57540andcerealkiller57540 1633f06297 Add a theme variable for the media browser list item background (#56456)
Co-authored-by: cerealkiller57540 <[email protected]>
2026-12-04 08:50:19 +00:00
Paul Bottein 7fec500672 Move gauge card editor translations to the standard structure (#56429) 2026-12-04 08:47:10 +00:00
WendelinandClaude Opus 5.5 237fd4341a Add an empty state to the installed apps page (#56434)
* Add an empty state to the installed apps page

Without installed apps, the page showed a search for 0 apps and a small
link card. It now shows an empty state like the automation, scene and
script pickers, with a centered Install app button and popular apps from
the store fading in one after another around it and drifting slowly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Give each featured app a fixed place and drop the fill-up

Featured apps and their places are one list now. An app missing from
the store leaves its place empty instead of being replaced by another
store app, so the list of hidden apps is no longer needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Move the apps empty state into a lazy-loaded component

The empty state, its store request and the icon reveal now live in
supervisor-apps-empty-state, which the installed apps page only loads
when no app is installed. The component reads contexts instead of hass,
so fetchSupervisorStore takes callWS now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Load the store apps with try/catch

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 08:39:28 +00:00
Paul Bottein 9b5ad7d6bd Move tile card editor translations up to the card level (#56428) 2026-12-04 08:36:35 +00:00
dependabot[bot] b6a6c17053 Bump cross-spawn from 7.0.6 to 7.1.2 (#56457)
Bumps [cross-spawn](https://github.com/moxystudio/node-cross-spawn) from 7.0.6 to 7.1.2.
- [Release notes](https://github.com/moxystudio/node-cross-spawn/releases)
- [Changelog](https://github.com/moxystudio/node-cross-spawn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.6...v7.1.2)

---
updated-dependencies:
- dependency-name: cross-spawn
  dependency-version: 7.1.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-04 08:35:39 +00:00
Petar Petrov 971fe1fec6 Move typed Lovelace editor hosts to contexts (#56408)
* Move typed Lovelace editor hosts to contexts

Entities, glance, distribution, map and stack card editors and the sub-element editor read localize and states from contexts and drop the ha-form hass binding.

* Don't throw in consumeLocalize before the context has a value

ha-form consumes localize since #56402, so the gallery threw before provideHass ran.

* Move the consumeLocalize fix to its own PR

It lands separately in #56418.
2026-12-04 08:33:42 +00:00
Clément NotinandWendelin 60d1400f46 Show keyboard shortcuts for reordering items (#55747)
* Add keyboard shortcut hints for moving editor rows

* Limit move shortcut hints to dashboard condition handles

* Show keyboard reorder hints on drag handles

* Show reorder shortcut hints only when focused

* Fix reorder shortcut hints from review

* Fix reorder shortcut hints and preserve accessible names

* Use upstream tooltip description association

* Clear reorder tooltip association when disabled

* Prepare Web Awesome tooltip dependency update

* Update Web Awesome to 3.15.0-ha.0

* Fix copilot review

---------

Co-authored-by: Wendelin <[email protected]>
2026-12-04 08:33:13 +00:00
Petar Petrov f6cdf9cc5f Stop re-rendering ha-sidebar on unrelated entity state updates (#56419)
* Stop re-rendering ha-sidebar on unrelated entity state updates

* Move count updates out of shouldUpdate and test countInstallableUpdates
2026-12-04 08:29:57 +00:00
renovate[bot] 3273d6804a Update dependency @rspack/core to v2.3.5 (#56455)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-04 09:28:38 +01:00
WendelinandClaude Opus 5.5 dad8eebe51 Upgrade webawesome to 3.15.0-ha.0 (#56440)
* Upgrade webawesome to 3.15.0-ha.0

Use the new button-group and tooltip part names, and describe the editor
mode shortcut tooltips instead of labelling their buttons with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Re-seed bundle budget for Web Awesome 3.15

Web Awesome 3.15 inlines 100 system icons instead of 61 in
library.system.js (+27.6 KiB), which wa-icon imports statically, so
every entrypoint using Web Awesome components grows. New translation
strings add another 3.3 KiB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 09:26:24 +01:00
Nathan Burns 86a05fb48b Add occupancy sensor to the area settings dialog (#56377)
Core stores one motion or occupancy entity per area (home-assistant/core#195471). Add the field to the area registry types and a picker for it next to the temperature and humidity sensors.
2026-12-04 09:21:31 +01:00
Lazizbek Ergashev 493579cee0 Keep pinging the backend after a reconnect (#56452) 2026-12-04 09:11:17 +01:00
Erik Montnemery 1b7932bf91 Clear the name when duplicating a YAML-only script or automation (#56454) 2026-12-04 09:08:27 +01:00
Erik Montnemery aa1d28022b Normalize script config in the YAML editor and for new scripts (#56453)
* Normalize script config in the YAML editor and for new scripts

* Normalize null YAML before accessing the config sequence
2026-12-04 08:37:53 +01:00
Erik Montnemery ed63a7a4bb Fall back to service when describing an action (#56451) 2026-12-04 08:35:12 +01:00
87 changed files with 3615 additions and 771 deletions

No files matched your search

+8 -8
View File
@@ -1,15 +1,15 @@
{
"_comment": "Initial JS budget (raw/uncompressed bytes) for the cold-load critical entrypoints. Enforced by build-scripts/check-bundle-size.cjs in CI. Re-seed after an intentional change with `--update --headroom=<percent>`.",
"frontend-modern": {
"app": 627654,
"core": 57901,
"authorize": 593862,
"onboarding": 709255
"app": 655843,
"core": 58038,
"authorize": 620096,
"onboarding": 753790
},
"frontend-legacy": {
"app": 724225,
"core": 163115,
"authorize": 693913,
"onboarding": 812415
"app": 755140,
"core": 146919,
"authorize": 723005,
"onboarding": 861854
}
}
+2
View File
@@ -10,6 +10,7 @@ export interface DemoArea {
picture?: string;
temperature_entity_id?: string;
humidity_entity_id?: string;
occupancy_entity_id?: string;
}
let areas: AreaRegistryEntry[] = [];
@@ -21,6 +22,7 @@ export const toAreaRegistryEntry = (area: DemoArea): AreaRegistryEntry => ({
icon: area.icon ?? null,
temperature_entity_id: area.temperature_entity_id ?? null,
humidity_entity_id: area.humidity_entity_id ?? null,
occupancy_entity_id: area.occupancy_entity_id ?? null,
aliases: [],
labels: [],
picture: area.picture ?? null,
@@ -122,6 +122,7 @@ const AREAS: AreaRegistryEntry[] = [
labels: [],
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
},
@@ -135,6 +136,7 @@ const AREAS: AreaRegistryEntry[] = [
labels: [],
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
},
@@ -118,6 +118,7 @@ const area = (areaId: string, name: string): AreaRegistryEntry => ({
labels: [],
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
});
+2 -2
View File
@@ -63,7 +63,7 @@
"@formatjs/intl-numberformat": "10.1.2",
"@formatjs/intl-pluralrules": "7.1.2",
"@formatjs/intl-relativetimeformat": "13.0.5",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@home-assistant/webawesome": "3.15.0-ha.0",
"@lezer/common": "1.5.7",
"@lezer/highlight": "1.2.5",
"@lit-labs/motion": "1.1.0",
@@ -156,7 +156,7 @@
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.4",
"@rspack/core": "2.3.5",
"@rspack/dev-server": "2.2.3",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
+17
View File
@@ -0,0 +1,17 @@
# Changelog
## 0.1.0-beta.0
First beta release.
- `hac-card`: card that groups related content, with an optional header and
footer.
- `hac-spinner`: progress indicator for a task of unknown duration, named for
screen readers.
- `hac-popover`: panel opened from a button, for content people read or
interact with, like help text with links.
- Global registration (`@home-assistant/components/<element>`) and scoped
registration for custom cards (`@home-assistant/components/<element>/scoped`
with `ScopedElementsMixin` or `createScopedElementRegistry`).
- A custom elements manifest at
`@home-assistant/components/custom-elements.json`.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+32 -9
View File
@@ -3,7 +3,21 @@
Home Assistant Components (`hac-*`): framework-agnostic web components built
with [Lit](https://lit.dev).
> Work in progress, not published yet.
> [!WARNING]
> **This package is in beta. The API of every component can still change in
> any release, without notice or a major version bump.** This covers
> attributes, properties, events, slots, CSS parts and CSS custom properties.
> Pin an exact version and read the [changelog](CHANGELOG.md) before you
> update.
## Installation
```bash
npm install --save-exact @home-assistant/components@beta
npm install lit
```
`lit` is a peer dependency.
## Registration
@@ -86,8 +100,6 @@ Only elements rendered inside the shadow root use the scoped registry. Light
DOM content, such as slotted elements, uses the registry of the tree it is
written in.
`lit` is a peer dependency.
### TypeScript
Each element's entry points declare its tag in `HTMLElementTagNameMap`, so
@@ -102,6 +114,18 @@ import type { HacCard } from "@home-assistant/components/card/scoped";
The package has no root entry point: each element and the scoped helpers
(`@home-assistant/components/scoped`) have their own.
### Custom elements manifest
`@home-assistant/components/custom-elements.json` describes every element's
attributes, properties, events, slots, parts and CSS custom properties, for
editors and documentation tools.
## Events
Events are named after the element that fires them, like
`hac-popover-show`, and bubble out of shadow roots. A listener further out
can therefore tell a popover closing from a dialog closing around it.
## Theming
Each component exposes its own `--hac-*` custom properties, documented in its
@@ -124,17 +148,16 @@ Each element has its own directory, named like its import path:
```
src/components/card/ <hac-card> -> @home-assistant/components/card
hac-card.ts class, does not register itself
info.ts tag name and version
hac-card.ts class and tag name, does not register itself
global.ts registers globally
scoped.ts element for a scoped registry -> …/card/scoped
```
Shared code lives in `src/utils/`: `registration/` for defining elements
(global and scoped) and `element/` for helpers that components use
themselves, like slot checks.
Every element has its own version in `info.ts`.
(global and scoped), `element/` for helpers that components use
themselves, like slot checks, and `popup/` for the base of floating elements
like `hac-popover`, positioned with
[Floating UI](https://floating-ui.com).
Entry points are mapped with subpath patterns in `package.json`, so a new
element directory needs no `package.json` change. Only `global.ts` files have
@@ -41,10 +41,30 @@ const publicApiOnly = () => ({
declaration.members = declaration.members?.filter(
(member) => !member.privacy || member.privacy === "public"
);
// Events dispatched with a computed name, like the popup base's, have no
// name here; the element documents them with @fires instead
declaration.events = declaration.events?.filter((event) => event.name);
});
},
});
// Only elements and their base classes are documented. Module constants like
// TAG_NAME are internal, as no entry point exports them.
const classesOnly = () => ({
name: "classes-only",
packageLinkPhase({ customElementsManifest }) {
for (const module of customElementsManifest.modules) {
module.declarations = module.declarations?.filter(
(declaration) => declaration.kind === "class"
);
const names = new Set(module.declarations?.map(({ name }) => name));
module.exports = module.exports?.filter((entry) =>
names.has(entry.declaration.name)
);
}
},
});
const distPaths = () => {
const toDist = (value) => value.replace(/^src\/(.+)\.ts$/, "dist/$1.js");
const rewrite = (node) => {
@@ -72,13 +92,15 @@ const distPaths = () => {
};
export default {
globs: ["src/components/**/hac-*.ts"],
// Base classes are analyzed too, so elements list the members they inherit
globs: ["src/components/**/hac-*.ts", "src/utils/popup/*.ts"],
outdir: "dist",
litelement: true,
plugins: [
packageReadme(),
summaryAsDescription(),
publicApiOnly(),
classesOnly(),
distPaths(),
],
};
+15 -7
View File
@@ -1,8 +1,16 @@
{
"name": "@home-assistant/components",
"version": "0.0.0",
"version": "0.1.0-beta.0",
"description": "Home Assistant web components (hac-* elements) built with Lit",
"keywords": [
"home-assistant",
"web-components",
"custom-elements",
"lit"
],
"license": "Apache-2.0",
"homepage": "https://github.com/home-assistant/frontend/tree/dev/packages/components#readme",
"bugs": "https://github.com/home-assistant/frontend/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/home-assistant/frontend.git",
@@ -21,16 +29,12 @@
"import": "./dist/scoped.js"
},
"./package.json": "./package.json",
"./custom-elements.json": "./dist/custom-elements.json",
"./*/scoped": {
"ha-source": "./src/components/*/scoped.ts",
"types": "./dist/components/*/scoped.d.ts",
"import": "./dist/components/*/scoped.js"
},
"./*/info": {
"ha-source": "./src/components/*/info.ts",
"types": "./dist/components/*/info.d.ts",
"import": "./dist/components/*/info.js"
},
"./*": {
"ha-source": "./src/components/*/global.ts",
"types": "./dist/components/*/global.d.ts",
@@ -38,7 +42,8 @@
}
},
"files": [
"dist"
"dist",
"CHANGELOG.md"
],
"publishConfig": {
"access": "public"
@@ -48,6 +53,9 @@
"dev": "rslib build --watch",
"prepublishOnly": "pnpm run build"
},
"dependencies": {
"@floating-ui/dom": "^1.8.0"
},
"peerDependencies": {
"lit": "^3.3.0"
},
@@ -1,6 +1,5 @@
import { define } from "../../utils/registration/define";
import { HacCard } from "./hac-card";
import { TAG_NAME } from "./info";
import { HacCard, TAG_NAME } from "./hac-card";
// Registers <hac-card> in the global registry, as used by Home Assistant
define(TAG_NAME, HacCard);
@@ -5,6 +5,9 @@ import {
hasAssignedElements,
} from "../../utils/element/slot";
/** Tag name of the element. */
export const TAG_NAME = "hac-card";
/**
* @element hac-card
*
@@ -21,13 +24,13 @@ import {
* @csspart footer - Wrapper of the footer slot.
*
* @cssprop --hac-card-background - Background of the card.
* @cssprop --hac-card-color - Text color of the card.
* @cssprop --hac-card-border-color - Border color of the card and the footer divider.
* @cssprop --hac-card-border-width - Border width of the card.
* @cssprop --hac-card-border-radius - Border radius of the card.
* @cssprop {<color>} --hac-card-color - Text color of the card.
* @cssprop {<color>} --hac-card-border-color - Border color of the card and the footer divider.
* @cssprop {<length>} [--hac-card-border-width=1px] - Border width of the card.
* @cssprop {<length>} [--hac-card-border-radius=12px] - Border radius of the card.
* @cssprop --hac-card-box-shadow - Box shadow of the card.
* @cssprop --hac-card-content-padding - Padding of the content.
* @cssprop --hac-card-footer-padding - Padding of the footer.
* @cssprop [--hac-card-content-padding=16px] - Padding of the content.
* @cssprop [--hac-card-footer-padding=8px] - Padding of the footer.
*/
export class HacCard extends LitElement {
/**
@@ -1,5 +0,0 @@
/** Tag name of the element. */
export const TAG_NAME = "hac-card";
/** Version of <hac-card>. */
export const VERSION = "0.1.0";
@@ -1,6 +1,5 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacCard } from "./hac-card";
import { TAG_NAME } from "./info";
import { HacCard, TAG_NAME } from "./hac-card";
export { HacCard };
@@ -0,0 +1,7 @@
import { define } from "../../utils/registration/define";
import { HacPopover, TAG_NAME } from "./hac-popover";
// Registers <hac-popover> in the global registry, as used by Home Assistant
define(TAG_NAME, HacPopover);
export { HacPopover };
@@ -0,0 +1,276 @@
import type { Placement } from "@floating-ui/dom";
import { css, type PropertyValues } from "lit";
import { property } from "lit/decorators.js";
import { containsComposed, deepActiveElement } from "../../utils/element/focus";
import { setAriaExpanded } from "../../utils/element/aria";
import { listen } from "../../utils/element/listen";
import { PopupBase, type PopupHideDetail } from "../../utils/popup/popup-base";
/** Tag name of the element. */
export const TAG_NAME = "hac-popover";
/**
* Works like a disclosure: the anchor gets `aria-expanded`, and focus stays on
* the anchor when the popover opens.
*
* - Set `for` to the id of a `<button>`, or of a button component that
* passes the `ariaExpanded` property on to its inner button.
* - Place the popover right after its anchor, so Tab and screen readers move
* from the anchor into the content.
* - Give an icon-only anchor a name, like `aria-label="About logging in"`.
* - Keep it to a few links or buttons. Tab moves on past the last one and
* closes the popover, so use a dialog for forms and other tasks.
* - Not a tooltip: it doesn't open on focus and isn't announced as a
* description, so don't use it to label an icon.
* - With `trigger="manual"` the parent opens it, like a picker. The parent
* then adds the roles and keys, like `role="combobox"` and arrow keys.
*
* @element hac-popover
*
* @summary
* Panel opened from a button for content people read or interact with, like
* help text with links.
*
* @slot - The popover's content.
*
* @csspart body - The popover's container.
*
* @cssprop {<color>} --hac-popover-background-color - Background of the popover.
* @cssprop {<length>} [--hac-popover-max-width=280px] - Maximum width.
* @cssprop {<length>} [--hac-popover-max-height=360px] - Maximum height.
* @cssprop --hac-popover-box-shadow - Shadow of the popover.
* @cssprop --hac-popover-border - Border shorthand. Set to `none` to remove it.
* @cssprop {<length>} [--hac-popover-border-radius=24px] - Corner radius.
* @cssprop [--hac-popover-padding=16px] - Padding around the content.
*
* @fires hac-popover-show - The popover is about to open. Cancelable.
* @fires hac-popover-after-show - The popover opened.
* @fires hac-popover-hide - The popover is about to close. Cancelable. `detail.reason` says why.
* @fires hac-popover-after-hide - The popover closed. `detail.reason` says why.
*/
export class HacPopover extends PopupBase {
/**
* What opens the popover. `hover` also opens it while a mouse rests on the
* anchor; a click still works, for touch and keyboard. `manual` leaves it to
* `show()`, `hide()` and `open`.
*/
@property() public trigger: "click" | "hover" | "manual" = "click";
/**
* Preferred placement relative to the anchor: `top`, `right`, `bottom` or
* `left`, optionally followed by `-start` or `-end`. Flips to the other
* side when there is no room.
*/
@property({ reflect: true }) public placement: Placement = "bottom-start";
protected readonly eventPrefix = TAG_NAME;
private _pinned = false;
private _timer?: number;
public disconnectedCallback(): void {
super.disconnectedCallback();
clearTimeout(this._timer);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (changedProps.has("open")) {
if (this.anchor) {
setAriaExpanded(this.anchor, this.open);
}
}
}
protected updated(changedProps: PropertyValues<this>): void {
super.updated(changedProps);
// A cancelled hide has set `open` back by now, so it stays pinned
if (changedProps.has("open") && !this.open) {
this._pinned = false;
}
}
protected anchorChanged(
anchor: HTMLElement | null,
oldAnchor: HTMLElement | null
): void {
if (oldAnchor && oldAnchor !== anchor) {
setAriaExpanded(oldAnchor, null);
}
if (anchor) {
setAriaExpanded(anchor, this.open);
}
}
protected attachAnchor(anchor: HTMLElement): (() => void)[] {
return [
listen(anchor, "click", this._handleClick),
listen(anchor, "pointerenter", this._handleEnter),
listen(anchor, "pointerleave", this._handleLeave),
listen(anchor, "focusout", this._handleFocusOut),
listen(this, "pointerenter", this._handleEnter),
listen(this, "pointerleave", this._handleLeave),
listen(this, "focusout", this._handleFocusOut),
];
}
protected async handleEscape(): Promise<void> {
const focusInside = this._focusInside();
this.close("escape-key");
await this.updateComplete;
// A listener may have cancelled the hide
if (focusInside && !this.open) {
this.anchor?.focus();
}
}
private _focusInside(): boolean {
const root = this.getRootNode();
const active = deepActiveElement(
root instanceof ShadowRoot ? root : document
);
return (
containsComposed(this, active) ||
(this.anchor ? containsComposed(this.anchor, active) : false)
);
}
private _opensOnClick(): boolean {
return this.trigger !== "manual";
}
private _handleClick = (): void => {
if (!this._opensOnClick()) {
return;
}
clearTimeout(this._timer);
// Only hover opens it unpinned; a click then pins it instead of closing
if (this.open && (this._pinned || this.trigger !== "hover")) {
this.close("anchor-click");
return;
}
this._pinned = true;
this.open = true;
};
private _handleEnter = (ev: PointerEvent): void => {
if (ev.pointerType !== "mouse" || this.trigger !== "hover") {
return;
}
clearTimeout(this._timer);
if (!this.open) {
this._timer = window.setTimeout(() => {
// The trigger may have changed while waiting
if (this.trigger === "hover") {
this.open = true;
}
}, 150);
}
};
private _handleLeave = (ev: PointerEvent): void => {
if (
ev.pointerType !== "mouse" ||
this.trigger !== "hover" ||
this._pinned
) {
return;
}
clearTimeout(this._timer);
this._timer = window.setTimeout(() => {
// Keyboard users may have moved into the content; focusout closes it
if (this.trigger === "hover" && !this._focusInside()) {
this.close("mouse-leave");
}
}, 150);
};
private _handleFocusOut = (ev: FocusEvent): void => {
const next = ev.relatedTarget as Node | null;
if (!this.open || !next) {
return;
}
const insideAnchor = this.anchor
? containsComposed(this.anchor, next)
: false;
const insidePopover = containsComposed(this, next);
if (!insideAnchor && !insidePopover) {
this.close("focus-out");
}
};
static styles = [
PopupBase.styles,
css`
.body {
max-width: min(
var(--hac-popover-max-width, 280px),
var(--available-width, 100vw)
);
max-height: min(
var(--hac-popover-max-height, 360px),
var(--available-height, 100vh)
);
overflow: auto;
padding: var(--hac-popover-padding, var(--ha-space-4, 16px));
border: var(
--hac-popover-border,
1px solid var(--ha-color-border-neutral-quiet, rgba(0, 0, 0, 0.12))
);
border-radius: var(
--hac-popover-border-radius,
var(--ha-border-radius-3xl, 24px)
);
background-color: var(
--hac-popover-background-color,
var(--ha-color-surface-default, #fff)
);
color: var(--ha-color-text-primary, #141414);
box-shadow: var(
--hac-popover-box-shadow,
0 8px 28px rgba(0, 0, 0, 0.18)
);
font-family: var(--ha-font-family-body, inherit);
font-size: var(--ha-font-size-m, 14px);
line-height: 1.45;
overflow-wrap: anywhere;
animation: hac-popover-in 160ms ease;
}
@keyframes hac-popover-in {
from {
opacity: 0;
transform: translateY(4px);
}
}
/* min() needs Chrome 79; without it the whole max-width is dropped */
@supports not (max-width: min(1px, 2px)) {
.body {
max-width: var(--hac-popover-max-width, 280px);
max-height: var(--available-height, 100vh);
}
}
@media (prefers-reduced-motion: reduce) {
.body {
animation: none;
}
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"hac-popover": HacPopover;
}
interface HTMLElementEventMap {
"hac-popover-show": CustomEvent<null>;
"hac-popover-after-show": CustomEvent<null>;
"hac-popover-hide": CustomEvent<PopupHideDetail>;
"hac-popover-after-hide": CustomEvent<PopupHideDetail>;
}
}
@@ -0,0 +1,14 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacPopover, TAG_NAME } from "./hac-popover";
export { HacPopover };
/**
* The bundled <hac-popover> for a scoped registry:
* `ScopedElementsMixin(LitElement, [hacPopover])` or
* `createScopedElementRegistry([hacPopover])`.
*/
export const hacPopover: ElementDefinition<typeof HacPopover> = {
tagName: TAG_NAME,
element: HacPopover,
};
@@ -1,6 +1,5 @@
import { define } from "../../utils/registration/define";
import { HacSpinner } from "./hac-spinner";
import { TAG_NAME } from "./info";
import { HacSpinner, TAG_NAME } from "./hac-spinner";
// Registers <hac-spinner> in the global registry, as used by Home Assistant
define(TAG_NAME, HacSpinner);
@@ -1,6 +1,9 @@
import { css, html, LitElement, nothing } from "lit";
import { property } from "lit/decorators.js";
/** Tag name of the element. */
export const TAG_NAME = "hac-spinner";
/**
* @element hac-spinner
*
@@ -14,13 +17,11 @@ import { property } from "lit/decorators.js";
* parent's name.
*
* @csspart spinner - The `svg` element.
* @csspart base - Same as `spinner`, kept for styles written for `ha-spinner`.
* Temporary, like the legacy variables.
*
* @cssprop --hac-spinner-size - Diameter of the spinner. Overrides `size`.
* @cssprop --hac-spinner-indicator-color - Color of the moving arc.
* @cssprop --hac-spinner-track-color - Color of the track.
* @cssprop --hac-spinner-track-width - Stroke width of the track and arc.
* @cssprop {<length>} --hac-spinner-size - Diameter of the spinner. Overrides `size`.
* @cssprop {<color>} --hac-spinner-indicator-color - Color of the moving arc.
* @cssprop {<color>} --hac-spinner-track-color - Color of the track.
* @cssprop {<length>} [--hac-spinner-track-width=4px] - Stroke width of the track and arc.
*/
export class HacSpinner extends LitElement {
/** Preset diameter: 16, 28, 48 or 68 pixels. Defaults to 48 pixels. */
@@ -57,7 +58,7 @@ export class HacSpinner extends LitElement {
protected render() {
return html`
<svg
part="spinner base"
part="spinner"
role="progressbar"
aria-label=${this.accessibleLabel || this.defaultLabel()}
aria-hidden=${this.getAttribute("aria-hidden") ?? nothing}
@@ -1,5 +0,0 @@
/** Tag name of the element. */
export const TAG_NAME = "hac-spinner";
/** Version of <hac-spinner>. */
export const VERSION = "0.1.0";
@@ -1,6 +1,5 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacSpinner } from "./hac-spinner";
import { TAG_NAME } from "./info";
import { HacSpinner, TAG_NAME } from "./hac-spinner";
export { HacSpinner };
@@ -0,0 +1,20 @@
/**
* Sets `aria-expanded` through the `ariaExpanded` property, so a button
* component can pass it on to the button inside it instead of getting the
* attribute on its host. Falls back to the attribute where browsers lack ARIA
* reflection, before Chrome 81 and Firefox 119.
*/
export const setAriaExpanded = (
element: HTMLElement,
expanded: boolean | null
): void => {
const value = expanded === null ? null : String(expanded);
const target: object = element;
if ("ariaExpanded" in target) {
element.ariaExpanded = value;
} else if (value === null) {
element.removeAttribute("aria-expanded");
} else {
element.setAttribute("aria-expanded", value);
}
};
@@ -0,0 +1,35 @@
/**
* Like `Node.contains`, but follows slots and shadow hosts, so slotted content
* counts as inside the element it is slotted into.
*/
export const containsComposed = (
container: Node,
node: Node | null
): boolean => {
let current: Node | null = node;
while (current) {
if (current === container) {
return true;
}
current =
(current as Element).assignedSlot ??
current.parentNode ??
(current as ShadowRoot).host ??
null;
}
return false;
};
/**
* The focused element, looking into open shadow roots. Pass the root an
* element lives in to also find focus inside a closed shadow root.
*/
export const deepActiveElement = (
root: Document | ShadowRoot = document
): Element | null => {
let active = root.activeElement;
while (active?.shadowRoot?.activeElement) {
active = active.shadowRoot.activeElement;
}
return active;
};
@@ -0,0 +1,14 @@
/**
* Adds an event listener and returns a function that removes it. Unlike the
* `signal` option, this also works before Chrome 90 and Safari 15.
*/
export const listen = <K extends keyof HTMLElementEventMap>(
target: EventTarget,
type: K,
listener: (ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions
): (() => void) => {
target.addEventListener(type, listener as EventListener, options);
return () =>
target.removeEventListener(type, listener as EventListener, options);
};
@@ -0,0 +1,485 @@
import {
autoUpdate,
computePosition,
flip,
hide,
limitShift,
offset,
type Placement,
shift,
type SideObject,
size,
} from "@floating-ui/dom";
import {
css,
type CSSResultGroup,
html,
LitElement,
nothing,
type PropertyValues,
type TemplateResult,
} from "lit";
import { property, query } from "lit/decorators.js";
import { containsComposed } from "../element/focus";
import { listen } from "../element/listen";
const supportsPopover =
typeof HTMLElement !== "undefined" &&
Object.prototype.hasOwnProperty.call(HTMLElement.prototype, "popover");
// Open popups, newest last, so Escape closes only the topmost one. Kept on
// window, so scoped copies of the library on one page share it.
const popupRegistry = (typeof window === "undefined" ? {} : window) as Record<
symbol,
PopupBase[]
>;
const OPEN_POPUPS = Symbol.for("hac-open-popups");
popupRegistry[OPEN_POPUPS] ??= [];
const openPopups = popupRegistry[OPEN_POPUPS];
const VIEWPORT_PADDING = 8;
/**
* Why a popup closed. `programmatic` covers `hide()`, setting `open`,
* `disabled` and the anchor going away.
*/
export type PopupHideReason =
| "anchor-click"
| "click-outside"
| "escape-key"
| "focus-out"
| "mouse-leave"
| "programmatic";
export interface PopupHideDetail {
reason: PopupHideReason;
}
const SIDES = ["top", "right", "bottom", "left"] as const;
// Distance to keep from each viewport edge: the padding plus the safe area,
// like a notch or the Android navigation bar, which flip, shift and size
// otherwise ignore
const edgePadding = (body: HTMLElement): SideObject => {
const styles = getComputedStyle(body);
const padding = {} as SideObject;
for (const side of SIDES) {
padding[side] =
VIEWPORT_PADDING +
(parseFloat(styles.getPropertyValue(`--_safe-area-${side}`)) || 0);
}
return padding;
};
/**
* Base of floating elements like hac-popover: finds the anchor by id, shows
* the body in the top layer where the Popover API exists (fixed positioning
* otherwise), positions it with floating-ui and closes it with Escape or a
* press outside. Events are named after the element, like
* `hac-popover-show`, so a listener further out can tell them apart from
* those of a dialog or menu around it.
*/
export abstract class PopupBase extends LitElement {
/** The id of the anchor element, in the same root as the popup. */
@property() public for?: string;
/** Whether the popup is shown. */
@property({ type: Boolean, reflect: true }) public open = false;
/**
* Preferred placement relative to the anchor: `top`, `right`, `bottom` or
* `left`, optionally followed by `-start` or `-end`. Flips to the other
* side when there is no room.
*/
@property({ reflect: true }) public placement: Placement = "top";
/** Distance from the anchor in pixels. */
@property({ type: Number }) public distance = 8;
/** Offset along the anchor in pixels. */
@property({ type: Number }) public skidding = 0;
/** Prevents the popup from opening. */
@property({ type: Boolean, reflect: true }) public disabled = false;
@query(".body", true) protected body?: HTMLElement;
protected anchor: HTMLElement | null = null;
/** Prefix of the events, usually the tag name. */
protected abstract readonly eventPrefix: string;
// Whether the body is shown. `open` can briefly differ while a show or hide
// event is being cancelled.
private _shown = false;
private _hideReason?: PopupHideReason;
private _insidePress?: Event;
private _detachAnchor: (() => void)[] = [];
private _detachDocument: (() => void)[] = [];
private _detachRoot: (() => void)[] = [];
private _stopAutoUpdate?: () => void;
public show(): void {
this.open = true;
}
public hide(): void {
this.open = false;
}
public connectedCallback(): void {
super.connectedCallback();
// A parent may render a new anchor with the same id. Capture listeners on
// the root run before the anchor's own, so they can bind the new one in
// time for the event.
const root = this.getRootNode();
this._detachRoot = [
listen(root, "click", this._refreshAnchor, true),
listen(root, "pointerover", this._refreshAnchor, true),
listen(root, "focusin", this._refreshAnchor, true),
listen(this, "pointerdown", this._markInsidePress, true),
];
if (this.hasUpdated) {
this._resolveAnchor();
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
this._detachRoot.forEach((detach) => detach());
this._detachRoot = [];
this._setAnchor(null);
this._teardownOpen();
}
protected updated(changedProps: PropertyValues<this>): void {
super.updated(changedProps);
// Also retry while the anchor is missing, as it may render after the popup
if (changedProps.has("for") || (this.for && !this.anchor?.isConnected)) {
this._resolveAnchor();
}
if (changedProps.has("disabled") && this.disabled && this.open) {
this.open = false;
}
if (changedProps.has("open")) {
this._syncOpen();
}
if (
this._shown &&
(changedProps.has("placement") ||
changedProps.has("distance") ||
changedProps.has("skidding"))
) {
this._reposition();
}
}
/**
* Adds the listeners that open and close the popup to the anchor. Returns
* the functions that remove them again.
*/
protected abstract attachAnchor(anchor: HTMLElement): (() => void)[];
/** Called after the anchor changed, to update its ARIA attributes. */
protected anchorChanged(
_anchor: HTMLElement | null,
_oldAnchor: HTMLElement | null
): void {
// Does nothing by default
}
/** Closes the popup and passes the reason to the hide events. */
protected close(reason: PopupHideReason): void {
if (this.open) {
this._hideReason = reason;
this.open = false;
}
}
/** Closes the popup on Escape. Subclasses may also move focus. */
protected handleEscape(): void {
this.close("escape-key");
}
protected renderBody(): TemplateResult {
return html`<slot></slot>`;
}
protected render(): TemplateResult {
return html`<div
part="body"
class="body"
popover=${supportsPopover ? "manual" : nothing}
?hidden=${!this.open}
>
${this.renderBody()}
</div>`;
}
private _resolveAnchor(): void {
// A popup outside the document has an element as its root, which can't
// look up ids
const root = this.getRootNode();
const anchor =
this.for && (root instanceof Document || root instanceof ShadowRoot)
? root.getElementById(this.for)
: null;
if (anchor !== this.anchor) {
this._setAnchor(anchor);
}
}
private _setAnchor(anchor: HTMLElement | null): void {
const oldAnchor = this.anchor;
this._detachAnchor.forEach((detach) => detach());
this.anchor = anchor;
this._detachAnchor = anchor
? [
...this.attachAnchor(anchor),
listen(anchor, "pointerdown", this._markInsidePress, true),
]
: [];
this.anchorChanged(anchor, oldAnchor);
if (!anchor && this.open) {
this.open = false;
}
if (anchor && this._shown) {
this._startAutoUpdate();
}
}
// Runs a show or hide when `open` and the shown state differ. A cancelled
// event resets `open`, which then matches again and runs nothing.
private _syncOpen(): void {
const reason = this._hideReason ?? "programmatic";
this._hideReason = undefined;
if (this.open === this._shown) {
return;
}
if (this.open) {
if (!this.anchor?.isConnected) {
this._resolveAnchor();
}
if (this.disabled || !this.anchor) {
this.open = false;
return;
}
const canceled = this._fire("show", true);
if (canceled) {
this.open = false;
return;
}
this._showBody();
this._fire("after-show");
return;
}
const detail: PopupHideDetail = { reason };
const canceled = this._fire("hide", true, detail);
if (canceled) {
this.open = true;
return;
}
this._teardownOpen();
this._fire("after-hide", false, detail);
}
private _showBody(): void {
const body = this.body;
if (!body) {
return;
}
this._shown = true;
if (supportsPopover && !body.matches(":popover-open")) {
body.showPopover();
}
openPopups.push(this);
this._detachDocument = [
// Capture phase on window, so Escape closes the popup before a dialog
// around it sees the key
listen(window, "keydown", this._handleKeyDown, true),
listen(document, "pointerdown", this._handlePointerDown, true),
];
this._startAutoUpdate();
}
private _startAutoUpdate(): void {
this._stopAutoUpdate?.();
const body = this.body;
this._stopAutoUpdate =
this.anchor && body
? autoUpdate(this.anchor, body, () => this._reposition())
: undefined;
}
private _teardownOpen(): void {
if (!this._shown) {
return;
}
this._shown = false;
this._detachDocument.forEach((detach) => detach());
this._detachDocument = [];
this._stopAutoUpdate?.();
this._stopAutoUpdate = undefined;
const index = openPopups.indexOf(this);
if (index !== -1) {
openPopups.splice(index, 1);
}
const body = this.body;
if (supportsPopover && body?.matches(":popover-open")) {
body.hidePopover();
}
}
private async _reposition(): Promise<void> {
// autoUpdate's ResizeObserver also fires when the anchor leaves the DOM,
// so rebind to a replacement here, or close when there is none
if (this.anchor && !this.anchor.isConnected) {
this._refreshAnchor();
return;
}
const anchor = this.anchor;
const body = this.body;
if (!anchor || !body || !this._shown) {
return;
}
const padding = edgePadding(body);
const position = await computePosition(anchor, body, {
strategy: "fixed",
placement: this.placement,
middleware: [
offset({ mainAxis: this.distance, crossAxis: this.skidding }),
flip({ padding }),
// Keeps it at the anchor, not at the edge of the screen
shift({ padding, limiter: limitShift() }),
size({
padding,
apply: ({ availableWidth, availableHeight }) => {
body.style.setProperty(
"--available-width",
`${Math.max(0, availableWidth)}px`
);
body.style.setProperty(
"--available-height",
`${Math.max(0, availableHeight)}px`
);
},
}),
// The top layer isn't clipped by scrolling containers, so hide it
// while its anchor is scrolled out of view
hide(),
],
});
const { x, y, placement, middlewareData } = position;
body.style.left = `${x}px`;
body.style.top = `${y}px`;
body.style.visibility = middlewareData.hide?.referenceHidden
? "hidden"
: "";
body.dataset.placement = placement;
}
private _refreshAnchor = (): void => {
if (this.for && !this.anchor?.isConnected) {
this._resolveAnchor();
}
};
private _handleKeyDown = (ev: KeyboardEvent): void => {
if (
ev.key !== "Escape" ||
ev.isComposing ||
openPopups[openPopups.length - 1] !== this
) {
return;
}
ev.preventDefault();
ev.stopPropagation();
this.handleEscape();
};
private _markInsidePress = (ev: PointerEvent): void => {
this._insidePress = ev;
};
private _handlePointerDown = (ev: PointerEvent): void => {
const path = ev.composedPath();
if (path.includes(this) || (this.anchor && path.includes(this.anchor))) {
return;
}
// In a closed shadow root the path stops at its host. The popup's and
// anchor's own listeners see the press later, so decide after them.
const target = ev.target as Node | null;
if (target && containsComposed(target, this)) {
setTimeout(() => {
if (this._insidePress !== ev) {
this.close("click-outside");
}
});
return;
}
this.close("click-outside");
};
// Returns whether a listener canceled the event
private _fire(
type: string,
cancelable = false,
detail: PopupHideDetail | null = null
): boolean {
return !this.dispatchEvent(
new CustomEvent(`${this.eventPrefix}-${type}`, {
bubbles: true,
composed: true,
cancelable,
detail,
})
);
}
static styles: CSSResultGroup = css`
:host {
display: contents;
/* Home Assistant's insets include the companion app's */
--_safe-area-top: var(
--safe-area-inset-top,
env(safe-area-inset-top, 0px)
);
--_safe-area-right: var(
--safe-area-inset-right,
env(safe-area-inset-right, 0px)
);
--_safe-area-bottom: var(
--safe-area-inset-bottom,
env(safe-area-inset-bottom, 0px)
);
--_safe-area-left: var(
--safe-area-inset-left,
env(safe-area-inset-left, 0px)
);
}
.body {
position: fixed;
inset: auto;
left: 0;
top: 0;
z-index: 1000;
box-sizing: border-box;
width: max-content;
max-width: var(--available-width, 100vw);
margin: 0;
border: 0;
overflow: visible;
}
.body[hidden] {
display: none;
}
`;
}
+285
View File
@@ -0,0 +1,285 @@
import { afterEach, describe, expect, it } from "vitest";
import "../src/components/popover/global";
import type { HacPopover } from "../src/components/popover/hac-popover";
const mount = async () => {
document.body.innerHTML = `
<button id="anchor">More info</button>
<hac-popover for="anchor"><a id="link" href="#">Learn more</a></hac-popover>
<button id="outside">Next</button>
`;
const popover = document.querySelector("hac-popover") as HacPopover;
await popover.updateComplete;
const get = (id: string) => document.getElementById(id) as HTMLElement;
return {
popover,
anchor: get("anchor"),
link: get("link"),
outside: get("outside"),
};
};
const pressEscape = () =>
window.dispatchEvent(
new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
);
afterEach(() => {
document.body.innerHTML = "";
});
// Keyboard and screen reader users rely on the anchor's state and on focus
// coming back to the anchor; nothing else shows them the popover closed.
describe("hac-popover", () => {
it("links the anchor and toggles on click", async () => {
const { popover, anchor } = await mount();
expect(anchor.getAttribute("aria-expanded")).toBe("false");
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(anchor.getAttribute("aria-expanded")).toBe("true");
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(false);
expect(anchor.getAttribute("aria-expanded")).toBe("false");
});
it("returns focus to the anchor on Escape from inside", async () => {
const { popover, anchor, link } = await mount();
anchor.click();
await popover.updateComplete;
link.focus();
pressEscape();
await popover.updateComplete;
expect(popover.open).toBe(false);
expect(document.activeElement).toBe(anchor);
});
it("closes when focus leaves the anchor and the content", async () => {
const { popover, anchor, link, outside } = await mount();
anchor.focus();
anchor.click();
await popover.updateComplete;
link.focus();
await popover.updateComplete;
expect(popover.open).toBe(true);
outside.focus();
await popover.updateComplete;
expect(popover.open).toBe(false);
});
it("stays open while focus is inside when the mouse leaves", async () => {
const { popover, anchor, link } = await mount();
popover.trigger = "hover";
const mouse = (type: string) =>
anchor.dispatchEvent(new PointerEvent(type, { pointerType: "mouse" }));
mouse("pointerenter");
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
expect(popover.open).toBe(true);
link.focus();
mouse("pointerleave");
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
expect(popover.open).toBe(true);
});
it("runs each transition once when one is cancelled", async () => {
const { popover, anchor } = await mount();
const fired: string[] = [];
for (const type of ["show", "after-show", "hide", "after-hide"]) {
popover.addEventListener(`hac-popover-${type}`, () => fired.push(type));
}
popover.addEventListener("hac-popover-hide", (ev) => ev.preventDefault(), {
once: true,
});
anchor.click();
await popover.updateComplete;
popover.hide();
await popover.updateComplete;
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(fired).toEqual(["show", "after-show", "hide"]);
});
// A picker cancels some hides; the popover must then behave as if still open
it("keeps focus and pinning when a hide is cancelled", async () => {
const { popover, anchor, link } = await mount();
popover.addEventListener("hac-popover-hide", (ev) => ev.preventDefault(), {
once: true,
});
anchor.click();
await popover.updateComplete;
link.focus();
pressEscape();
await popover.updateComplete;
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(document.activeElement).toBe(link);
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(false);
});
// Lit re-renders can swap the anchor for a new element with the same id
it("follows an anchor that was replaced", async () => {
const { popover, anchor } = await mount();
const replacement = document.createElement("button");
anchor.replaceWith(replacement);
replacement.id = "anchor";
replacement.click();
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(replacement.getAttribute("aria-expanded")).toBe("true");
});
it("closes on an anchor click after opening from code", async () => {
const { popover, anchor } = await mount();
popover.show();
await popover.updateComplete;
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(false);
});
it("rebinds or closes when the anchor changes while open", async () => {
const { popover, anchor } = await mount();
anchor.click();
await popover.updateComplete;
const replacement = document.createElement("button");
replacement.id = "anchor";
anchor.replaceWith(replacement);
// Browsers report the removal through ResizeObserver, which jsdom lacks
window.dispatchEvent(new Event("resize"));
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(replacement.getAttribute("aria-expanded")).toBe("true");
replacement.remove();
window.dispatchEvent(new Event("resize"));
await popover.updateComplete;
await popover.updateComplete;
expect(popover.open).toBe(false);
});
// A custom card may put the popover in a closed shadow root, which hides it
// from the document's view of events and focus
it("works inside a closed shadow root", async () => {
const host = document.createElement("div");
document.body.append(host);
const root = host.attachShadow({ mode: "closed" });
root.innerHTML = `
<button id="anchor">More info</button>
<hac-popover for="anchor"><a id="link" href="#">Learn more</a></hac-popover>
`;
const popover = root.querySelector("hac-popover") as HacPopover;
const anchor = root.getElementById("anchor") as HTMLElement;
const link = root.getElementById("link") as HTMLElement;
const press = (target: Element) =>
target.dispatchEvent(
new PointerEvent("pointerdown", { bubbles: true, composed: true })
);
const settle = () =>
new Promise((resolve) => {
setTimeout(resolve);
});
await popover.updateComplete;
anchor.click();
await popover.updateComplete;
press(link);
await settle();
expect(popover.open).toBe(true);
link.focus();
pressEscape();
await popover.updateComplete;
expect(popover.open).toBe(false);
expect(root.activeElement).toBe(anchor);
anchor.click();
await popover.updateComplete;
press(document.body);
await settle();
expect(popover.open).toBe(false);
});
// Parents like a picker react differently to Escape than to a press outside
it("tells why it closed", async () => {
const { popover, anchor, outside } = await mount();
const reasons: string[] = [];
popover.addEventListener("hac-popover-after-hide", (ev) =>
reasons.push(ev.detail.reason)
);
const closeWith = async (close: () => void) => {
anchor.click();
await popover.updateComplete;
close();
await popover.updateComplete;
};
await closeWith(() => anchor.click());
await closeWith(pressEscape);
await closeWith(() =>
outside.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }))
);
await closeWith(() => popover.hide());
expect(reasons).toEqual([
"anchor-click",
"escape-key",
"click-outside",
"programmatic",
]);
});
it("finds an anchor rendered after the popover", async () => {
document.body.innerHTML = `<hac-popover for="late">Text</hac-popover>`;
const popover = document.querySelector("hac-popover") as HacPopover;
await popover.updateComplete;
const anchor = document.createElement("button");
anchor.id = "late";
popover.before(anchor);
popover.show();
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(anchor.getAttribute("aria-expanded")).toBe("true");
});
// Button components put the state on their inner button; on the host it
// would be announced a second time
it("hands aria-expanded to a button component as a property", async () => {
document.body.innerHTML = `<hac-popover for="anchor">Text</hac-popover>`;
const popover = document.querySelector("hac-popover") as HacPopover;
// Stands in for a component that overrides the ariaExpanded property
const anchor = document.createElement("span");
anchor.id = "anchor";
let expanded: string | null = null;
Object.defineProperty(anchor, "ariaExpanded", {
get: () => expanded,
set: (value: string | null) => {
expanded = value;
},
});
popover.before(anchor);
popover.show();
await popover.updateComplete;
expect(expanded).toBe("true");
expect(anchor.hasAttribute("aria-expanded")).toBe(false);
});
});
+150 -132
View File
@@ -269,8 +269,8 @@ importers:
specifier: 13.0.5
version: 13.0.5
'@home-assistant/webawesome':
specifier: 3.14.0-ha.2
version: 3.14.0-ha.2(@floating-ui/[email protected])(@types/[email protected])
specifier: 3.15.0-ha.0
version: 3.15.0-ha.0(@floating-ui/[email protected])(@types/[email protected])
'@lezer/common':
specifier: 1.5.7
version: 1.5.7
@@ -541,13 +541,13 @@ importers:
version: 1.65.1
'@rsdoctor/rspack-plugin':
specifier: 1.6.5
version: 1.6.5(@emnapi/[email protected].3)(@emnapi/[email protected].3)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].4(@swc/[email protected]))([email protected])
version: 1.6.5(@emnapi/[email protected].2)(@emnapi/[email protected].2)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].5(@swc/[email protected]))([email protected])
'@rspack/core':
specifier: 2.3.4
version: 2.3.4(@swc/[email protected])
specifier: 2.3.5
version: 2.3.5(@swc/[email protected])
'@rspack/dev-server':
specifier: 2.2.3
version: 2.2.3(@rspack/[email protected].4(@swc/[email protected]))
version: 2.2.3(@rspack/[email protected].5(@swc/[email protected]))
'@types/babel__plugin-transform-runtime':
specifier: 7.9.5
version: 7.9.5
@@ -595,7 +595,7 @@ importers:
version: 5.1.2([email protected])
babel-loader:
specifier: 10.1.1
version: 10.1.1(@babel/[email protected])(@rspack/[email protected].4(@swc/[email protected]))
version: 10.1.1(@babel/[email protected])(@rspack/[email protected].5(@swc/[email protected]))
babel-plugin-polyfill-corejs3:
specifier: 1.0.0
version: 1.0.0(@babel/[email protected])
@@ -703,7 +703,7 @@ importers:
version: 3.10.1
rspack-manifest-plugin:
specifier: 5.2.2
version: 5.2.2(@rspack/[email protected].4(@swc/[email protected]))
version: 5.2.2(@rspack/[email protected].5(@swc/[email protected]))
serve:
specifier: 14.2.8
version: 14.2.8([email protected])
@@ -739,12 +739,16 @@ importers:
version: 1.1.3
webpackbar:
specifier: 7.0.0
version: 7.0.0(@rspack/[email protected].4(@swc/[email protected]))
version: 7.0.0(@rspack/[email protected].5(@swc/[email protected]))
workbox-build:
specifier: 7.4.1
version: 7.4.1(patch_hash=75e6346ad8d8af554c167f77ac7d9b9652f010398efdc6b399925a4795133099)([email protected])
packages/components:
dependencies:
'@floating-ui/dom':
specifier: ^1.8.0
version: 1.8.0
devDependencies:
'@custom-elements-manifest/analyzer':
specifier: 0.11.0
@@ -1905,8 +1909,8 @@ packages:
'@emnapi/[email protected]':
resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==}
'@emnapi/[email protected].3':
resolution: {integrity: sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==}
'@emnapi/[email protected].4':
resolution: {integrity: sha512-AhU/vMMXtGgLCrWsL3PjZGSpCWXlGETabnyyB2pBUd6h7AMy2toffJO2T7yXOYXtw8FyD6dYK/5b3u5eRK3yhw==}
'@emnapi/[email protected]':
resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
@@ -1917,8 +1921,8 @@ packages:
'@emnapi/[email protected]':
resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==}
'@emnapi/[email protected].3':
resolution: {integrity: sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==}
'@emnapi/[email protected].4':
resolution: {integrity: sha512-UKxc3beuftD67T1mPCVf0mnwRKOBsq9XrhLCDGGQKsbG9jx6osvGyjIbJm9DsucyUtFSMTV2ZxsjiuTMjEqWkA==}
'@emnapi/[email protected]':
resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
@@ -2092,8 +2096,8 @@ packages:
resolution: {integrity: sha512-kjotm7XJrJ6v+7knhPaRgaT6q8F8K2jiafwYdNHLzmV0uGLuZY43FK6smNSHUPrhq5kX2slCUy+RGG/xGqmIKA==}
engines: {node: '>=10.13.0'}
'@home-assistant/[email protected]4.0-ha.2':
resolution: {integrity: sha512-EX1qiX5h3LAoTjuE3rgfuRlNq3Rds5tGrgDGlHoFbxhXaCSTTtuYU6tdR8vgOXKGUDi5gBDrcoNdLYKFXSrknA==}
'@home-assistant/[email protected]5.0-ha.0':
resolution: {integrity: sha512-s1L2M8oaPNfDXdG2M5afeEpEJOP3s0t2GICl8XYgL6SVLVFDNOwWLG2SysbI/Iw7VhIos/4TIbOKr8IEOdLceQ==}
engines: {node: '>=14.17.0'}
'@html-eslint/[email protected]':
@@ -3049,88 +3053,88 @@ packages:
typescript:
optional: true
'@rspack/[email protected].4':
resolution: {integrity: sha512-eBD71fbmoJKnxcHD03bukbAIOP5r7nD0Ehs+mUrUQlZ6N53EhuJsTeJ1oYdg5L4GoSeQ+KecCqME81Nm0COLrA==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-A5XnBdSoJvcYV4t2Y+XJiCF0UZ42nOKE2D0ZlegfErGhzlQG1t3hDOzskSB2fPD3z+w5QeREoclqQ0zFOZyBpw==}
cpu: [arm64]
os: [darwin]
'@rspack/[email protected].4':
resolution: {integrity: sha512-CqdfzTLPVFQCniOy/GDVWbg+rqg31qfdzbFf8NYCzdDkCQg+p15hU2HsckD/1sLsaNB8Y55EjGz4ZyGDny0cHg==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-iZrweqTIj2cM4f0ADRj6FXn9a0FOpD1Mx/++zrsbrQzmnY0c8wmfpvZ5xA5Zfcq9O6nuUBS6GnhkmoFTgviHwQ==}
cpu: [x64]
os: [darwin]
'@rspack/[email protected].4':
resolution: {integrity: sha512-T/Y1FYiSegcNc+oHuDOLRGIcc+eSdBnfbS70d51EWQj4+0TG/tlfuqFKeAIL3mnKUV5lDLaTz3vsoD0Sws5Fxw==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-aWE9V0ZhmclKsJNuO37cxUMLtXMjhLtFzrWDWC82mksUX6qM2rzOpPuye9i/c9NGqyrIH7EFQre8bskJvNHGuQ==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rspack/[email protected].4':
resolution: {integrity: sha512-WZHCzZ532UfXFXNU8XyM8jb+I6wddegbs/7IXsyw7xiPwwZX1D/M6iKFVpBYdvKcupUM8bS8Uw2REirR/cERVw==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-I8ENTXdv7Th/OHEYhL7uu3B7DA9r1oTWSifkGHJtuT1XJ0KDsxoA6ORpYz1R2qIs87l+8+5QUnRH7iWyZrnroA==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rspack/[email protected].4':
resolution: {integrity: sha512-WeizqeI6HIh7Ax9w2tlmpTtipJWxXcdgt3QqI3N9LOixymlMD5yMBMZNPqwZ6cHXT9gOQ69SvPcVgMwxsdmceQ==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-ps5do0cKf4aTBWd+LHqvwm8Gdn7J/gvzmx9pWJhAIThvzii45wJREFjGOzJNxdQl+pzKq8JFuzbShNskCN9k2w==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rspack/[email protected].4':
resolution: {integrity: sha512-h+001Vbq8LyGwPMNkeRWidPOVKwlAbwNPskY3CjNlSw3euHkVchfhM3uo6+1h0GyTtb3rzsWqsfm1kar7m/tiQ==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-3XXIEMS4SSr1/9wIAGgPT1oj1SzhnlejAG5xeVbGJR5y6iFp/oFKYzUPqyuuzZCkWph2/hJ+Q16sa+BJn1YIkg==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@rspack/[email protected].4':
resolution: {integrity: sha512-S1rlaCnNVG5s4WZ9odLsqN3ySh5TEdNTLXWapEK8x3iQl56aLtdvqXTfbJWHWnYLJuS7M1WqnQGdJNdjy2NDsA==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-z2DbQNcLbUEY9OvUa3gahsHey+dW4acLc9d3QlyJm7TJE//rL9C/XBk4kETvCgtdhqrwBSfWrZfislBPKODjvA==}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@rspack/[email protected].4':
resolution: {integrity: sha512-0SkgGrgulVMam3xel5dMNKQ+U7BEpCczhF1avGT1DzDVIbMfIOsbb32gApQNSz0E7RfAQ/Pa5eWiA9oyRq7ZMQ==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-n2UudDpzt9G2AOmycVS7uWRMcNMd2k4ubU4b4SX3FfU/uT6mfSNzuwhBhCi0RSZQAGBU0ombJ+sqw8vKXjGGbw==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rspack/[email protected].4':
resolution: {integrity: sha512-q7E6x3rJJ/9fJyLuRe5+KyEPi23BF/xkAU4xCM5VwLkTf+rVyOkDZfu0qOkxmILjrxllQPV+b/ojBL/ZaIeQPw==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-1sxASGJXg9luaYsFSmAQxSFbUbnMnPA5Mr94yIlLsq4q94sHUIn5YjG1XGcT+cPhUYF9fHkCsKRmQlzrN9fR8A==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rspack/[email protected].4':
resolution: {integrity: sha512-rey4Tyasui/WeMn6KfhH5xyZGOMt+Ny+GDK7nGh9TSz/cb3/bisxqGzpbu6GJK8leDmTUDD5ZdpODexytA5rzQ==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-/S4pe1wAo8CBTs0X8DNKu1ZOJ2vQcnThLBKS2CxOPiuQXI7UfAsJCEABBoa8yCrZANWh63fJ90UwLb/s245Gsw==}
cpu: [x64]
os: [linux]
libc: [musl]
'@rspack/[email protected].4':
resolution: {integrity: sha512-sDt2MSXZrIaMBa6UaEqmXEqebwpTOPAXLdo9CYJ2Fa9FJWP4TCYbn30mbvV38ZC2n5YX411DRbjck+s97CceIg==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-GQnswrv6AyBdDCcTy8dTVhD0JqnvmgewzPz6qnOYWGKxpCY99Bv6FL4jvxI1yh64Uk3ykEfbwhrPnaA8Px4KJA==}
cpu: [wasm32]
'@rspack/[email protected].4':
resolution: {integrity: sha512-24YC1YSodLAJ8VsMQJmJSHCNvHTqK9JP5hj50T50WE8lCHNsNl/rIYXO9V0VlCYT/HshE6EHHzAeKdahiEOtcw==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-XVKu3Zs5KGr+P5Seh6NtSNU0UQ1GSgSDFANQRZlT1uFZ1NpBCX+9NB8FVZB0hBBoBKI1kU4b0Cr6Df1Xx0K4nQ==}
cpu: [arm64]
os: [win32]
'@rspack/[email protected].4':
resolution: {integrity: sha512-xmUNu6kgV9lLEkRP1Zb+t6i1Z1ZMEWXmLlMalPx8tHqndz2RflNMBBx6kjB2nAPQBIZgWufwm7dVGS0HKomCmw==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-ejCqSuctPcOev2dyi0ayZyfIUY3fJdYHYvrTfSVrrGC19TspuRATXu+RLyu3xvB6TrQF3+JEF4KeG4/ZeWuXOg==}
cpu: [ia32]
os: [win32]
'@rspack/[email protected].4':
resolution: {integrity: sha512-WY+AkJqpbLtLEZiG1fE7CVJZ54y0qHeCiVmLxGBsh4OOGIDCs6v2Ub5COcPrYVzGJFGyeHUS29dV7JAs93qIHw==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-IPvkjM3xAwL1z2N4Jp/GBcZUme703uDy5vrP1IMtXJEl/EOLLfwl7cRb4sSzdeOYGDDHs5dPYDcpgP5eRSRauA==}
cpu: [x64]
os: [win32]
'@rspack/[email protected].4':
resolution: {integrity: sha512-wSOT16LVITL/IKeIiLXgN5Q5jZIDqnQ7Gmk+wzKOSZ6OHYNfEBXAKhSJuYtCBq8ovJuGl8cJjdqatAlHE5XKIA==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-W3x7zw5d/mIH9WhWt4pO9RKYURoqgdUxeLSV5IhDCajnhXdRr7R59u5S2j5ZXzSk3eMGUC0PenfKIIdW7t0ufQ==}
'@rspack/[email protected].4':
resolution: {integrity: sha512-T8HGkIjPVDlGlIN8st/ICe8Gfixq8te75g/8crSdNSf8F+6884sBcKNky0CRdfPxao1C5SXV+Vjv1XJTjyu83w==}
'@rspack/[email protected].5':
resolution: {integrity: sha512-4TG6zGTemEU/FU7bymDgeFOO7CRdd7ucn0CmXo+3cG6EhYmY5+hpAFYBRgxDbDuL4Bwo/s5GsgUvZuI7rLqVbQ==}
engines: {node: ^20.19.0 || >=22.12.0}
peerDependencies:
'@module-federation/runtime-tools': ^0.24.1 || ^2.0.0
@@ -4816,8 +4820,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-bgy+iHRFjsBxBCriXkTuFuHRJGSGZISuqDGhDQG7gLK0F7qOzhH06bdXzGf4b0bZSQ+mApakybiW9xvKnS9dbg==}
cross-spawn@7.0.6:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
cross-spawn@7.1.2:
resolution: {integrity: sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==}
engines: {node: '>= 8'}
[email protected]:
@@ -6607,6 +6611,10 @@ packages:
resolution: {integrity: sha512-j2gvsGUFeS/53WdYLl9H5G2YtMZX9G/PlCvV3E5Pf4j5XSnK19DwazU6wki7OTcKeYKed7+qujRDLhy8NV2zBg==}
engines: {node: '>=22.12.0'}
[email protected]:
resolution: {integrity: sha512-XFUHmKclX4taKWVpYkqJ/GlfUS27FzQTCph1u3v9OwkmQJGXry3Pk1e7SivLz6xGOCxRVyi3DSrztF3e460jrg==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
engines: {node: '>=8.6'}
@@ -10119,7 +10127,7 @@ snapshots:
tslib: 2.9.1
optional: true
'@emnapi/[email protected].3':
'@emnapi/[email protected].4':
dependencies:
'@emnapi/wasi-threads': 2.2.0
tslib: 2.9.1
@@ -10140,7 +10148,7 @@ snapshots:
tslib: 2.9.1
optional: true
'@emnapi/[email protected].3':
'@emnapi/[email protected].4':
dependencies:
tslib: 2.9.1
optional: true
@@ -10331,7 +10339,7 @@ snapshots:
dependencies:
is-negated-glob: 1.0.0
'@home-assistant/[email protected]4.0-ha.2(@floating-ui/[email protected])(@types/[email protected])':
'@home-assistant/[email protected]5.0-ha.0(@floating-ui/[email protected])(@types/[email protected])':
dependencies:
'@ctrl/tinycolor': 4.1.0
'@floating-ui/dom': 1.8.0
@@ -10345,6 +10353,7 @@ snapshots:
composed-offset-position: 0.0.6(@floating-ui/[email protected])
lit: 3.3.3
marked: 11.2.0
microlighter: 2.2.0
nanoid: 5.1.16
transitivePeerDependencies:
- '@floating-ui/utils'
@@ -10701,10 +10710,17 @@ snapshots:
'@tybys/wasm-util': 0.10.3
optional: true
'@napi-rs/[email protected](@emnapi/[email protected].3)(@emnapi/[email protected].3)':
'@napi-rs/[email protected](@emnapi/[email protected].2)(@emnapi/[email protected].2)':
dependencies:
'@emnapi/core': 2.0.0-beta.3
'@emnapi/runtime': 2.0.0-beta.3
'@emnapi/core': 2.0.0-beta.2
'@emnapi/runtime': 2.0.0-beta.2
'@tybys/wasm-util': 0.10.3
optional: true
'@napi-rs/[email protected](@emnapi/[email protected])(@emnapi/[email protected])':
dependencies:
'@emnapi/core': 2.0.0-beta.4
'@emnapi/runtime': 2.0.0-beta.4
'@tybys/wasm-util': 0.10.3
optional: true
@@ -11299,7 +11315,7 @@ snapshots:
'@rsbuild/[email protected]([email protected])':
dependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
'@swc/helpers': 0.5.24
optionalDependencies:
core-js: 3.51.0
@@ -11318,14 +11334,14 @@ snapshots:
'@rsdoctor/[email protected]': {}
'@rsdoctor/[email protected](@emnapi/[email protected].3)(@emnapi/[email protected].3)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].4(@swc/[email protected]))([email protected])':
'@rsdoctor/[email protected](@emnapi/[email protected].2)(@emnapi/[email protected].2)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].5(@swc/[email protected]))([email protected])':
dependencies:
'@rsbuild/plugin-check-syntax': 1.6.1(@rsbuild/[email protected]([email protected]))
'@rsdoctor/graph': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/sdk': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))([email protected])
'@rsdoctor/types': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rspack/resolver': 0.2.8(@emnapi/[email protected].3)(@emnapi/[email protected].3)
'@rsdoctor/graph': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/sdk': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))([email protected])
'@rsdoctor/types': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rspack/resolver': 0.2.8(@emnapi/[email protected].2)(@emnapi/[email protected].2)
browserslist-load-config: 1.0.3
enhanced-resolve: 5.26.0
es-toolkit: 1.50.0
@@ -11343,10 +11359,10 @@ snapshots:
- utf-8-validate
- webpack
'@rsdoctor/[email protected](@rspack/[email protected].4(@swc/[email protected]))':
'@rsdoctor/[email protected](@rspack/[email protected].5(@swc/[email protected]))':
dependencies:
'@rsdoctor/types': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/types': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
es-toolkit: 1.50.0
path-browserify: 1.0.1
source-map: 0.7.6
@@ -11354,15 +11370,15 @@ snapshots:
- '@rspack/core'
- webpack
'@rsdoctor/[email protected](@emnapi/[email protected].3)(@emnapi/[email protected].3)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].4(@swc/[email protected]))([email protected])':
'@rsdoctor/[email protected](@emnapi/[email protected].2)(@emnapi/[email protected].2)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].5(@swc/[email protected]))([email protected])':
dependencies:
'@rsdoctor/core': 1.6.5(@emnapi/[email protected].3)(@emnapi/[email protected].3)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].4(@swc/[email protected]))([email protected])
'@rsdoctor/graph': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/sdk': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))([email protected])
'@rsdoctor/types': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/core': 1.6.5(@emnapi/[email protected].2)(@emnapi/[email protected].2)(@rsbuild/[email protected]([email protected]))(@rspack/[email protected].5(@swc/[email protected]))([email protected])
'@rsdoctor/graph': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/sdk': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))([email protected])
'@rsdoctor/types': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
optionalDependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
@@ -11372,12 +11388,12 @@ snapshots:
- utf-8-validate
- webpack
'@rsdoctor/[email protected](@rspack/[email protected].4(@swc/[email protected]))([email protected])':
'@rsdoctor/[email protected](@rspack/[email protected].5(@swc/[email protected]))([email protected])':
dependencies:
'@rsdoctor/client': 1.6.5
'@rsdoctor/graph': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/types': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/graph': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/types': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@rsdoctor/utils': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
launch-editor: 2.14.2
safer-buffer: 2.1.2
socket.io: 4.8.1([email protected])
@@ -11389,19 +11405,19 @@ snapshots:
- utf-8-validate
- webpack
'@rsdoctor/[email protected](@rspack/[email protected].4(@swc/[email protected]))':
'@rsdoctor/[email protected](@rspack/[email protected].5(@swc/[email protected]))':
dependencies:
'@types/connect': 3.4.38
'@types/estree': 1.0.5
'@types/tapable': 2.3.0
source-map: 0.7.6
optionalDependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
'@rsdoctor/[email protected](@rspack/[email protected].4(@swc/[email protected]))':
'@rsdoctor/[email protected](@rspack/[email protected].5(@swc/[email protected]))':
dependencies:
'@babel/code-frame': 7.26.2
'@rsdoctor/types': 1.6.5(@rspack/[email protected].4(@swc/[email protected]))
'@rsdoctor/types': 1.6.5(@rspack/[email protected].5(@swc/[email protected]))
'@types/estree': 1.0.5
acorn: 8.18.0
acorn-import-attributes: 1.9.5([email protected])
@@ -11430,83 +11446,83 @@ snapshots:
- '@swc-next/parser-binding-wasm'
- core-js
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
dependencies:
'@emnapi/core': 2.0.0-beta.3
'@emnapi/runtime': 2.0.0-beta.3
'@napi-rs/wasm-runtime': 1.2.7(@emnapi/[email protected].3)(@emnapi/[email protected].3)
'@emnapi/core': 2.0.0-beta.4
'@emnapi/runtime': 2.0.0-beta.4
'@napi-rs/wasm-runtime': 1.2.7(@emnapi/[email protected].4)(@emnapi/[email protected].4)
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optional: true
'@rspack/[email protected].4':
'@rspack/[email protected].5':
optionalDependencies:
'@rspack/binding-darwin-arm64': 2.3.4
'@rspack/binding-darwin-x64': 2.3.4
'@rspack/binding-linux-arm64-gnu': 2.3.4
'@rspack/binding-linux-arm64-musl': 2.3.4
'@rspack/binding-linux-ppc64-gnu': 2.3.4
'@rspack/binding-linux-riscv64-gnu': 2.3.4
'@rspack/binding-linux-riscv64-musl': 2.3.4
'@rspack/binding-linux-s390x-gnu': 2.3.4
'@rspack/binding-linux-x64-gnu': 2.3.4
'@rspack/binding-linux-x64-musl': 2.3.4
'@rspack/binding-wasm32-wasi': 2.3.4
'@rspack/binding-win32-arm64-msvc': 2.3.4
'@rspack/binding-win32-ia32-msvc': 2.3.4
'@rspack/binding-win32-x64-msvc': 2.3.4
'@rspack/binding-darwin-arm64': 2.3.5
'@rspack/binding-darwin-x64': 2.3.5
'@rspack/binding-linux-arm64-gnu': 2.3.5
'@rspack/binding-linux-arm64-musl': 2.3.5
'@rspack/binding-linux-ppc64-gnu': 2.3.5
'@rspack/binding-linux-riscv64-gnu': 2.3.5
'@rspack/binding-linux-riscv64-musl': 2.3.5
'@rspack/binding-linux-s390x-gnu': 2.3.5
'@rspack/binding-linux-x64-gnu': 2.3.5
'@rspack/binding-linux-x64-musl': 2.3.5
'@rspack/binding-wasm32-wasi': 2.3.5
'@rspack/binding-win32-arm64-msvc': 2.3.5
'@rspack/binding-win32-ia32-msvc': 2.3.5
'@rspack/binding-win32-x64-msvc': 2.3.5
'@rspack/[email protected].4(@swc/[email protected])':
'@rspack/[email protected].5(@swc/[email protected])':
dependencies:
'@rspack/binding': 2.3.4
'@rspack/binding': 2.3.5
optionalDependencies:
'@swc/helpers': 0.5.24
'@rspack/[email protected](@rspack/[email protected].4(@swc/[email protected]))':
'@rspack/[email protected](@rspack/[email protected].5(@swc/[email protected]))':
optionalDependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
'@rspack/[email protected](@rspack/[email protected].4(@swc/[email protected]))':
'@rspack/[email protected](@rspack/[email protected].5(@swc/[email protected]))':
dependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/dev-middleware': 2.0.6(@rspack/[email protected].4(@swc/[email protected]))
'@rspack/core': 2.3.5(@swc/[email protected])
'@rspack/dev-middleware': 2.0.6(@rspack/[email protected].5(@swc/[email protected]))
'@rspack/[email protected]': {}
@@ -11528,9 +11544,9 @@ snapshots:
'@rspack/[email protected]':
optional: true
'@rspack/[email protected](@emnapi/[email protected].3)(@emnapi/[email protected].3)':
'@rspack/[email protected](@emnapi/[email protected].2)(@emnapi/[email protected].2)':
dependencies:
'@napi-rs/wasm-runtime': 1.2.7(@emnapi/[email protected].3)(@emnapi/[email protected].3)
'@napi-rs/wasm-runtime': 1.2.7(@emnapi/[email protected].2)(@emnapi/[email protected].2)
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
@@ -11545,7 +11561,7 @@ snapshots:
'@rspack/[email protected]':
optional: true
'@rspack/[email protected](@emnapi/[email protected].3)(@emnapi/[email protected].3)':
'@rspack/[email protected](@emnapi/[email protected].2)(@emnapi/[email protected].2)':
optionalDependencies:
'@rspack/resolver-binding-darwin-arm64': 0.2.8
'@rspack/resolver-binding-darwin-x64': 0.2.8
@@ -11553,7 +11569,7 @@ snapshots:
'@rspack/resolver-binding-linux-arm64-musl': 0.2.8
'@rspack/resolver-binding-linux-x64-gnu': 0.2.8
'@rspack/resolver-binding-linux-x64-musl': 0.2.8
'@rspack/resolver-binding-wasm32-wasi': 0.2.8(@emnapi/[email protected].3)(@emnapi/[email protected].3)
'@rspack/resolver-binding-wasm32-wasi': 0.2.8(@emnapi/[email protected].2)(@emnapi/[email protected].2)
'@rspack/resolver-binding-win32-arm64-msvc': 0.2.8
'@rspack/resolver-binding-win32-ia32-msvc': 0.2.8
'@rspack/resolver-binding-win32-x64-msvc': 0.2.8
@@ -12607,12 +12623,12 @@ snapshots:
[email protected]: {}
[email protected](@babel/[email protected])(@rspack/[email protected].4(@swc/[email protected])):
[email protected](@babel/[email protected])(@rspack/[email protected].5(@swc/[email protected])):
dependencies:
'@babel/core': 8.1.4
find-up: 5.0.0
optionalDependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
[email protected](@babel/[email protected]([email protected]))([email protected]):
dependencies:
@@ -13072,7 +13088,7 @@ snapshots:
'@cropper/elements': 2.3.1
'@cropper/utils': 2.3.1
cross-spawn@7.0.6:
cross-spawn@7.1.2:
dependencies:
path-key: 3.1.1
shebang-command: 2.0.0
@@ -13778,7 +13794,7 @@ snapshots:
'@humanwhocodes/retry': 0.4.3
'@types/estree': 1.0.9
ajv: 6.15.0
cross-spawn: 7.0.6
cross-spawn: 7.1.2
debug: 4.4.3([email protected])
escape-string-regexp: 4.0.0
eslint-scope: 9.1.2
@@ -13976,7 +13992,7 @@ snapshots:
[email protected]:
dependencies:
cross-spawn: 7.0.6
cross-spawn: 7.1.2
signal-exit: 4.1.0
[email protected]:
@@ -15073,6 +15089,8 @@ snapshots:
stylis: 4.4.0
ts-dedent: 2.3.0
[email protected]: {}
[email protected]:
dependencies:
braces: 3.0.3
@@ -15978,11 +15996,11 @@ snapshots:
[email protected]: {}
[email protected](@rspack/[email protected].4(@swc/[email protected])):
[email protected](@rspack/[email protected].5(@swc/[email protected])):
dependencies:
'@rspack/lite-tapable': 1.1.5
optionalDependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
[email protected]:
dependencies:
@@ -16975,14 +16993,14 @@ snapshots:
[email protected]: {}
[email protected](@rspack/[email protected].4(@swc/[email protected])):
[email protected](@rspack/[email protected].5(@swc/[email protected])):
dependencies:
ansis: 3.17.0
consola: 3.4.2
pretty-time: 1.1.0
std-env: 3.10.0
optionalDependencies:
'@rspack/core': 2.3.4(@swc/[email protected])
'@rspack/core': 2.3.5(@swc/[email protected])
[email protected]: {}
+6
View File
@@ -103,6 +103,12 @@
"matchDepTypes": ["peerDependencies"],
"rangeStrategy": "widen"
},
{
"description": "Keep semver ranges for dependencies of the published components package, so consumers can share one copy with other libraries",
"matchFileNames": ["packages/components/package.json"],
"matchDepTypes": ["dependencies"],
"rangeStrategy": "bump"
},
{
"description": "Group all Python version updates from home-assistant/core",
"matchDepNames": ["python"],
+7 -1
View File
@@ -1,7 +1,13 @@
/** Loads an image, resolves with undefined when it can't be loaded. */
export const loadImage = (url: string): Promise<HTMLImageElement | undefined> =>
export const loadImage = (
url: string,
crossOrigin?: "anonymous" | "use-credentials"
): Promise<HTMLImageElement | undefined> =>
new Promise((resolve) => {
const image = new Image();
if (crossOrigin) {
image.crossOrigin = crossOrigin;
}
image.onload = () => resolve(image);
image.onerror = () => resolve(undefined);
image.src = url;
@@ -0,0 +1,11 @@
import { html } from "lit";
import { isMac } from "../../util/is_mac";
export const renderMoveShortcutHint = (
moveUpLabel: string,
moveDownLabel: string
) => html`
${moveUpLabel} <span dir="ltr">(${isMac ? "⌥" : "Alt"}+↑)</span>
<br />
${moveDownLabel} <span dir="ltr">(${isMac ? "⌥" : "Alt"}+↓)</span>
`;
+2 -2
View File
@@ -87,7 +87,7 @@ export class HaButtonToggleGroup extends LitElement {
--mdc-icon-size: var(--button-toggle-icon-size, 20px);
}
:host([no-wrap]) wa-button-group::part(base) {
:host([no-wrap]) wa-button-group::part(button-group) {
flex-wrap: nowrap;
}
@@ -96,7 +96,7 @@ export class HaButtonToggleGroup extends LitElement {
}
:host([full-width]) wa-button-group,
:host([full-width]) wa-button-group::part(base) {
:host([full-width]) wa-button-group::part(button-group) {
width: 100%;
}
+27
View File
@@ -11,6 +11,7 @@ import memoizeOne from "memoize-one";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import { stopPropagation } from "../common/dom/stop_propagation";
import { renderMoveShortcutHint } from "../common/keyboard/render-move-shortcut-hint";
import { orderCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { afterNextRender } from "../common/util/render-status";
@@ -19,6 +20,7 @@ import "./ha-icon-button";
import "./ha-icon-next";
import "./ha-sortable";
import "./ha-svg-icon";
import "./ha-tooltip";
import "./item/ha-list-item-button";
import "./list/ha-list-base";
@@ -113,6 +115,7 @@ export class HaItemDisplayEditor extends LitElement {
} = item;
return html`
<ha-list-item-button
id="move-item-row-${idx}"
@click=${
this.showNavigationButton ? this._navigate : undefined
}
@@ -128,6 +131,11 @@ export class HaItemDisplayEditor extends LitElement {
: undefined
}
.idx=${idx}
aria-keyshortcuts=${ifDefined(
isVisible && !disableSorting
? "Alt+ArrowUp Alt+ArrowDown"
: undefined
)}
>
<span slot="headline">${label}</span>
${
@@ -203,10 +211,26 @@ export class HaItemDisplayEditor extends LitElement {
? this._dragHandleKeydown
: undefined
}
id="move-item-${idx}"
class="handle"
.path=${mdiDragHorizontalVariant}
slot="end"
></ha-svg-icon>
<ha-tooltip
slot="end"
trigger="focus"
association="description"
for=${
this.showNavigationButton
? `move-item-${idx}`
: `move-item-row-${idx}`
}
>
${renderMoveShortcutHint(
this._localize("ui.common.move_up"),
this._localize("ui.common.move_down")
)}
</ha-tooltip>
`
: html`<ha-svg-icon slot="end"></ha-svg-icon>`
}
@@ -409,6 +433,9 @@ export class HaItemDisplayEditor extends LitElement {
/* Keep the handle above the row's hit area so dragging can start */
z-index: 1;
}
ha-tooltip {
position: absolute;
}
.separator {
width: 1px;
background-color: var(--divider-color);
@@ -1,7 +1,8 @@
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../common/dom/fire_event";
import type { UiColorSelector } from "../../data/selector";
import type { UiColorExtraOption, UiColorSelector } from "../../data/selector";
import "../ha-color-picker";
@customElement("ha-selector-ui_color")
@@ -16,6 +17,28 @@ export class HaSelectorUiColor extends LitElement {
@property({ type: Boolean }) public disabled = false;
@property({ attribute: false })
public localizeValue?: (key: string) => string;
private _extraOptions = memoizeOne(
(
selector: UiColorSelector,
localizeValue?: (key: string) => string
): UiColorExtraOption[] | undefined => {
const translationKey = selector.ui_color?.translation_key;
return selector.ui_color?.extra_options?.map((option) => {
const localizedLabel =
translationKey && localizeValue
? localizeValue(`${translationKey}.options.${option.value}`)
: undefined;
return {
...option,
label: localizedLabel || option.label || option.value,
};
});
}
);
protected render() {
return html`
<ha-color-picker
@@ -26,7 +49,7 @@ export class HaSelectorUiColor extends LitElement {
.includeNone=${this.selector.ui_color?.include_none}
.includeState=${this.selector.ui_color?.include_state}
.defaultColor=${this.selector.ui_color?.default_color}
.extraOptions=${this.selector.ui_color?.extra_options}
.extraOptions=${this._extraOptions(this.selector, this.localizeValue)}
@value-changed=${this._valueChanged}
></ha-color-picker>
`;
+34 -18
View File
@@ -6,7 +6,7 @@ import {
mdiMenuOpen,
} from "@mdi/js";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import type { PropertyDeclaration, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -28,8 +28,7 @@ import {
import type { PersistentNotification } from "../data/persistent_notification";
import { subscribeNotifications } from "../data/persistent_notification";
import { subscribeRepairsIssueRegistry } from "../data/repairs";
import type { UpdateEntity } from "../data/update";
import { updateCanInstall } from "../data/update";
import { countInstallableUpdates } from "../data/update";
import { showEditSidebarDialog } from "../dialogs/sidebar/show-dialog-edit-sidebar";
import { ScrollableFadeMixin } from "../mixins/scrollable-fade-mixin";
import { SubscribeMixin } from "../mixins/subscribe-mixin";
@@ -223,8 +222,34 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
];
}
public connectedCallback() {
super.connectedCallback();
if (this.hass) {
this._calculateCounts();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
this._calculateCounts.cancel();
}
public override requestUpdate(
name?: PropertyKey,
oldValue?: unknown,
options?: PropertyDeclaration
) {
if (name === "hass" && this.hass && this.isConnected) {
const oldHass = oldValue as HomeAssistant | undefined;
if (
!oldHass ||
this.hass.states !== oldHass.states ||
this.hass.entities !== oldHass.entities
) {
this._calculateCounts();
}
}
super.requestUpdate(name, oldValue, options);
}
protected render() {
@@ -306,7 +331,6 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
hass.user !== oldHass.user ||
hass.localize !== oldHass.localize ||
hass.locale !== oldHass.locale ||
hass.states !== oldHass.states ||
hass.userData !== oldHass.userData ||
hass.systemData !== oldHass.systemData ||
hass.connected !== oldHass.connected
@@ -348,24 +372,16 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
) {
this._subscribePersistentNotifications();
}
this._calculateCounts();
}
private _calculateCounts = throttle(() => {
let updateCount = 0;
for (const entityId of Object.keys(this.hass.states)) {
if (
entityId.startsWith("update.") &&
!this.hass.entities[entityId]?.hidden &&
updateCanInstall(this.hass.states[entityId] as UpdateEntity)
) {
updateCount++;
}
if (!this.hass?.states) {
return;
}
this._updatesCount = updateCount;
this._updatesCount = countInstallableUpdates(
this.hass.states,
this.hass.entities
);
}, 5000);
private _renderHeader() {
@@ -20,6 +20,10 @@ import "./ha-media-browser-thumbnail";
*
* @csspart start - The graphic container.
*
* @cssprop --ha-media-browser-list-item-background - Background of the row.
* Lets a theme keep rows readable over an image panel background, like the
* cards of the grid view. Defaults to `transparent`.
*
* @attr {string} thumbnail - URL of the thumbnail. Shown inside the graphic.
*/
@customElement("ha-media-player-browse-list-item")
@@ -55,6 +59,7 @@ export class HaMediaPlayerBrowseListItem extends HaListItemButton {
css`
:host {
direction: var(--direction);
background: var(--ha-media-browser-list-item-background, transparent);
--ha-row-item-padding-block: 0;
--ha-row-item-min-height: 48px;
}
+2
View File
@@ -16,6 +16,7 @@ export interface AreaRegistryEntry extends RegistryEntry {
icon: string | null;
labels: string[];
name: string;
occupancy_entity_id: string | null;
picture: string | null;
temperature_entity_id: string | null;
}
@@ -34,6 +35,7 @@ export interface AreaRegistryEntryMutableParams {
icon?: string | null;
labels?: string[];
name: string;
occupancy_entity_id?: string | null;
picture?: string | null;
temperature_entity_id?: string | null;
}
+5 -3
View File
@@ -557,10 +557,12 @@ export const migrateAutomationAction = (
return action;
};
export const normalizeScriptConfig = (
config: ScriptConfig,
export const normalizeScriptConfig = <
T extends Partial<ScriptConfig> | ScriptConfig,
>(
config: T,
report?: AutomationMigrationReport
): ScriptConfig => {
): T => {
// Normalize data: ensure sequence is a list
// Happens when people copy paste their scripts into the config
const value = config.sequence;
+7 -7
View File
@@ -89,6 +89,9 @@ const tryDescribeAction = <T extends ActionType>(
if (actionType === "service") {
const config = action as ActionTypes["service"];
// Configs that were not migrated, like the one in a trace, can still use
// the legacy `service` key.
const serviceId = config.action ?? (config as { service?: string }).service;
const targets: string[] = [];
const targetOrData = config.target || config.data;
@@ -101,10 +104,7 @@ const tryDescribeAction = <T extends ActionType>(
);
}
if (
config.service_template ||
(config.action && isTemplate(config.action))
) {
if (config.service_template || (serviceId && isTemplate(serviceId))) {
return hass.localize(
targets.length
? `${actionTranslationBaseKey}.service.description.service_based_on_template`
@@ -115,8 +115,8 @@ const tryDescribeAction = <T extends ActionType>(
);
}
if (config.action) {
const [domain, serviceName] = config.action.split(".", 2);
if (serviceId) {
const [domain, serviceName] = serviceId.split(".", 2);
const descriptionPlaceholders =
hass.services[domain]?.[serviceName]?.description_placeholders;
const service =
@@ -128,7 +128,7 @@ const tryDescribeAction = <T extends ActionType>(
if (service && shouldShowDomainPrefix(domain, manifests)) {
return `${domainToName(hass.localize, domain)}: ${service}`;
}
return service || config.action;
return service || serviceId;
}
return hass.localize(
`${actionTranslationBaseKey}.service.description.service`
+6 -1
View File
@@ -683,12 +683,17 @@ export interface UiColorExtraOption {
display_color?: string;
}
export type UiColorSelectorExtraOption = Omit<UiColorExtraOption, "label"> & {
label?: string;
};
export interface UiColorSelector {
ui_color: {
default_color?: string;
include_none?: boolean;
include_state?: boolean;
extra_options?: UiColorExtraOption[];
extra_options?: readonly UiColorSelectorExtraOption[];
translation_key?: string;
} | null;
}
+9 -3
View File
@@ -1,4 +1,4 @@
import type { HomeAssistant } from "../../types";
import type { CallWS, HomeAssistant } from "../../types";
import type { AddonRole, AddonStage } from "../hassio/addon";
import { supervisorApiCall } from "./common";
import type { SupervisorArch } from "./supervisor";
@@ -56,8 +56,14 @@ export interface SupervisorStore {
}
export const fetchSupervisorStore = async (
hass: HomeAssistant
): Promise<SupervisorStore> => supervisorApiCall(hass, "/store");
callWS: CallWS
): Promise<SupervisorStore> =>
callWS<SupervisorStore>({
type: "supervisor/api",
endpoint: "/store",
method: "get",
timeout: null,
});
export const fetchStoreRepositories = async (
hass: HomeAssistant
+8 -3
View File
@@ -158,9 +158,14 @@ const findUpdateEntityIds = memoizeOne((entityIds: string[]) =>
entityIds.filter((entityId) => computeDomain(entityId) === "update")
);
export const countInstallableUpdates = (states: HassEntityStates): number =>
findUpdateEntityIds(getEntityIds(states)).filter((entityId) =>
updateCanInstall(states[entityId] as UpdateEntity)
export const countInstallableUpdates = (
states: HassEntityStates,
entities?: HomeAssistant["entities"]
): number =>
findUpdateEntityIds(getEntityIds(states)).filter(
(entityId) =>
!entities?.[entityId]?.hidden &&
updateCanInstall(states[entityId] as UpdateEntity)
).length;
export const filterUpdateEntitiesParameterized = (
@@ -0,0 +1,124 @@
export interface FeaturedApp {
slug: string;
// Center in percent of the empty state
x: number;
y: number;
size: number;
tilt: number;
// How far the app drifts around its center, varied so no two move alike
dx: number;
dy: number;
// Beside the text, so only shown on wide screens
side?: boolean;
}
// Popular apps from the repositories the Supervisor adds by default, each
// with its own place around the empty state. Ordered so that apps fading in
// one after another land far apart.
export const FEATURED_APPS: FeaturedApp[] = [
{
slug: "5c53de3b_esphome",
x: 14,
y: 18,
size: 64,
tilt: -6,
dx: 16,
dy: -12,
},
{
slug: "core_mosquitto",
x: 84,
y: 62,
size: 60,
tilt: 5,
dx: -21,
dy: 19,
side: true,
},
{
slug: "core_speech-to-phrase",
x: 46,
y: 10,
size: 48,
tilt: 4,
dx: 18,
dy: 17,
},
{
slug: "d5369777_music_assistant",
x: 20,
y: 80,
size: 56,
tilt: 7,
dx: -20,
dy: -15,
},
{
slug: "core_configurator",
x: 78,
y: 20,
size: 52,
tilt: -4,
dx: 17,
dy: 13,
},
{
slug: "core_matter_server",
x: 8,
y: 50,
size: 48,
tilt: 3,
dx: -22,
dy: 20,
side: true,
},
{
slug: "core_openthread_border_router",
x: 62,
y: 88,
size: 56,
tilt: -5,
dx: 19,
dy: -18,
},
{
slug: "core_samba",
x: 30,
y: 24,
size: 44,
tilt: 6,
dx: -16,
dy: 16,
side: true,
},
{
slug: "a0d7b954_vscode",
x: 92,
y: 36,
size: 44,
tilt: -7,
dx: 22,
dy: 14,
side: true,
},
{
slug: "a0d7b954_adguard",
x: 40,
y: 86,
size: 48,
tilt: -3,
dx: -18,
dy: -12,
},
{ slug: "core_mariadb", x: 66, y: 8, size: 44, tilt: 8, dx: 15, dy: 19 },
{ slug: "core_ssh", x: 86, y: 82, size: 48, tilt: 4, dx: -17, dy: 13 },
];
// Matches the media query in the styles that hides the slots beside the text
export const SCATTER_NARROW_QUERY = "(max-width: 600px)";
// Minimum time between two apps fading in, so cached icons still cascade
export const SCATTER_REVEAL_INTERVAL = 400;
// Apps that load together and show without waiting for each other
export const SCATTER_INSTANT_COUNT = 2;
@@ -0,0 +1,328 @@
import type { ContextType } from "@lit/context";
import { mdiOpenInNew, mdiPuzzle, mdiStorePlus } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../../../common/decorators/consume";
import { loadImage } from "../../../../common/dom/load-image";
import { isExternalHassUrl } from "../../../../common/url/hass-url";
import { waitForMs } from "../../../../common/util/wait";
import "../../../../components/ha-app-icon";
import "../../../../components/ha-button";
import "../../../../components/ha-svg-icon";
import {
apiContext,
configContext,
internationalizationContext,
} from "../../../../data/context";
import { supervisorUrl } from "../../../../data/hassio/common";
import type { StoreAddon } from "../../../../data/supervisor/store";
import { fetchSupervisorStore } from "../../../../data/supervisor/store";
import { documentationUrl } from "../../../../util/documentation-url";
import type { FeaturedApp } from "../common/empty-state";
import {
FEATURED_APPS,
SCATTER_INSTANT_COUNT,
SCATTER_NARROW_QUERY,
SCATTER_REVEAL_INTERVAL,
} from "../common/empty-state";
/**
* @element supervisor-apps-empty-state
*
* @summary Empty state of the installed apps page, with popular apps from the
* store fading in one after another around it.
*/
@customElement("supervisor-apps-empty-state")
export class SupervisorAppsEmptyState extends LitElement {
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
private _config!: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state() private _loadedIcons: ReadonlySet<string> = new Set();
private _storeAppsLoad?: Promise<StoreAddon[]>;
private _revealingIcons = false;
public connectedCallback(): void {
super.connectedCallback();
// Continue with the icons that didn't show before the page was left
if (this.hasUpdated) {
this._loadStoreApps();
}
}
protected firstUpdated(): void {
this._loadStoreApps();
}
protected render() {
return html`
<div class="scatter" aria-hidden="true">
${FEATURED_APPS.map((app, index) => {
if (!this._loadedIcons.has(app.slug)) {
return nothing;
}
return html`
<div
class=${classMap({ bubble: true, side: Boolean(app.side) })}
style=${styleMap({
"--x": `${app.x}%`,
"--y": `${app.y}%`,
"--size": `${app.size}px`,
"--tilt": `${app.tilt}deg`,
"--index": String(index),
"--dx": `${app.dx}px`,
"--dy": `${app.dy}px`,
})}
>
<ha-app-icon .slug=${app.slug} has-icon></ha-app-icon>
</div>
`;
})}
</div>
<div class="content">
<ha-svg-icon class="icon" .path=${mdiPuzzle}></ha-svg-icon>
<h2>
${this._i18n.localize("ui.panel.config.apps.installed.empty_header")}
</h2>
<p>
${this._i18n.localize("ui.panel.config.apps.installed.empty_text")}
</p>
<ha-button size="l" href="/config/apps/available">
<ha-svg-icon slot="start" .path=${mdiStorePlus}></ha-svg-icon>
${this._i18n.localize("ui.panel.config.apps.installed.add_app")}
</ha-button>
<ha-button
class="learn-more"
appearance="plain"
href=${documentationUrl(this._config, "/apps/")}
target="_blank"
rel="noreferrer"
size="s"
>
${this._i18n.localize("ui.panel.config.common.learn_more")}
<ha-svg-icon slot="end" .path=${mdiOpenInNew}></ha-svg-icon>
</ha-button>
</div>
`;
}
private async _loadStoreApps(): Promise<void> {
// Reconnects while the store loads share its request
this._storeAppsLoad ??= this._fetchStoreApps();
this._revealIcons(await this._storeAppsLoad);
}
private async _fetchStoreApps(): Promise<StoreAddon[]> {
try {
return (await fetchSupervisorStore(this._api.callWS)).addons;
} catch (_err: unknown) {
// The apps are decoration only
return [];
}
}
private async _revealIcons(storeApps: StoreAddon[]): Promise<void> {
// The store can answer after the page was left
if (this._revealingIcons || !this.isConnected) {
return;
}
this._revealingIcons = true;
try {
// Same CORS mode as ha-app-icon, so its image comes from the cache
const crossOrigin = isExternalHassUrl() ? undefined : "anonymous";
const load = (app: FeaturedApp) =>
loadImage(supervisorUrl(`addons/${app.slug}/icon`), crossOrigin);
const reveal = (app: FeaturedApp) => {
this._loadedIcons = new Set([...this._loadedIcons, app.slug]);
};
const available = new Set(
storeApps
.filter((app) => app.available && app.icon)
.map((app) => app.slug)
);
const featured = FEATURED_APPS.filter((app) => available.has(app.slug));
const pending = featured.filter(
(app) => !this._loadedIcons.has(app.slug)
);
// The first apps show right away, so the page doesn't look empty
const instant = pending.filter(
(app) => featured.indexOf(app) < SCATTER_INSTANT_COUNT
);
await Promise.all(
instant.map(async (app) => {
if ((await load(app)) && this.isConnected) {
reveal(app);
}
})
);
// The rest one after another, with a pause between two that show
let lastReveal = performance.now();
for (const app of pending) {
if (instant.includes(app)) {
continue;
}
if (!this.isConnected) {
return;
}
// eslint-disable-next-line no-await-in-loop
if (!(await load(app))) {
continue;
}
if (!app.side || !matchMedia(SCATTER_NARROW_QUERY).matches) {
// eslint-disable-next-line no-await-in-loop
await waitForMs(
Math.max(
0,
lastReveal + SCATTER_REVEAL_INTERVAL - performance.now()
)
);
if (!this.isConnected) {
return;
}
lastReveal = performance.now();
}
reveal(app);
}
} finally {
this._revealingIcons = false;
}
}
static styles = css`
:host {
position: relative;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
min-height: 100%;
padding: var(--ha-space-4);
overflow: hidden;
}
.scatter {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
direction: ltr;
pointer-events: none;
}
.bubble {
position: absolute;
left: var(--x);
top: var(--y);
display: flex;
box-sizing: border-box;
width: var(--size);
height: var(--size);
margin: calc(var(--size) / -2);
padding: calc(var(--size) / 6);
border-radius: var(--ha-border-radius-xl);
background-color: var(--card-background-color);
box-shadow: var(--ha-box-shadow-s);
opacity: 0.7;
transform: rotate(var(--tilt));
animation:
appear calc(3 * var(--ha-animation-duration-slow)) ease-out backwards,
drift calc(16s + var(--index) * 0.9s) ease-in-out
calc(var(--index) * -2.3s) infinite;
}
ha-app-icon {
--ha-app-icon-size: 100%;
}
.content {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
max-width: 500px;
text-align: center;
}
.icon {
--mdc-icon-size: 80px;
}
h2 {
margin-block: var(--ha-space-5);
font-family: var(--ha-font-family-heading);
font-size: var(--ha-font-size-3xl);
font-weight: var(--ha-font-weight-normal);
line-height: var(--ha-line-height-condensed);
}
p {
margin: 0 0 var(--ha-space-6);
}
.learn-more {
margin-top: var(--ha-space-3);
}
@keyframes appear {
from {
opacity: 0;
scale: 0.6;
}
}
@keyframes drift {
0%,
100% {
transform: translate(0, 0) rotate(var(--tilt));
}
25% {
transform: translate(var(--dx), calc(-1 * var(--dy)))
rotate(calc(var(--tilt) + 4deg));
}
50% {
transform: translate(calc(-0.4 * var(--dx)), var(--dy))
rotate(calc(var(--tilt) - 3deg));
}
75% {
transform: translate(calc(-1 * var(--dx)), calc(-0.3 * var(--dy)))
rotate(var(--tilt));
}
}
/* Same width as SCATTER_NARROW_QUERY */
@media (max-width: 600px) {
.bubble {
scale: 0.8;
}
.bubble.side {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.bubble {
animation: appear var(--ha-animation-duration-slow) backwards;
}
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"supervisor-apps-empty-state": SupervisorAppsEmptyState;
}
}
@@ -190,7 +190,7 @@ class HaConfigAppDashboard extends LitElement {
slug: string,
repositoryUrl: string
): Promise<void> {
const storeInfo = await fetchSupervisorStore(this.hass);
const storeInfo = await fetchSupervisorStore(this.hass.callWS);
if (storeInfo.repositories.some((repo) => repo.source === repositoryUrl)) {
// Repository is already installed, addon just doesn't exist
return;
@@ -281,7 +281,7 @@ export class HaConfigAppsAvailable extends LitElement {
try {
const [addonInfo, store] = await Promise.all([
addon ?? fetchHassioAddonsInfo(this.hass),
fetchSupervisorStore(this.hass),
fetchSupervisorStore(this.hass.callWS),
]);
this._addon = addonInfo;
@@ -304,7 +304,7 @@ export class HaConfigAppsAvailable extends LitElement {
if (collection === "addon") {
this._addon = await fetchHassioAddonsInfo(this.hass);
} else if (collection === "store") {
this._store = await fetchSupervisorStore(this.hass);
this._store = await fetchSupervisorStore(this.hass.callWS);
}
} catch (_err: any) {
// Silently fail on refresh errors
@@ -7,8 +7,8 @@ import {
mdiRefresh,
mdiStorePlus,
} from "@mdi/js";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { navigate } from "../../../common/navigate";
@@ -84,6 +84,17 @@ export class HaConfigAppsInstalled extends LitElement {
});
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
// Only needed without installed apps, so it isn't part of the page
if (
changedProps.has("_addonInfo") &&
this._addonInfo?.addons.length === 0
) {
import("./components/supervisor-apps-empty-state");
}
}
protected render(): TemplateResult {
if (this._error) {
return html`
@@ -103,6 +114,7 @@ export class HaConfigAppsInstalled extends LitElement {
`;
}
const hasApps = this._addonInfo.addons.length > 0;
const addons = this._getAddons(this._addonInfo.addons, this._filter);
return html`
@@ -122,88 +134,93 @@ export class HaConfigAppsInstalled extends LitElement {
"ui.panel.config.apps.store.check_updates"
)}
></ha-icon-button>
<div class="search">
<ha-input-search
appearance="outlined"
.value=${this._filter}
.placeholder=${this.hass.localize(
"ui.panel.config.apps.installed.search",
{ number: this._addonInfo.addons.length }
)}
@input=${this._handleSearchChange}
>
</ha-input-search>
</div>
<div class="content">
${
addons.length === 0
? html`
<ha-card outlined>
<div class="card-content">
<button class="link" @click=${this._openStore}>
${
hasApps
? html`
<div class="search">
<ha-input-search
appearance="outlined"
.value=${this._filter}
.placeholder=${this.hass.localize(
"ui.panel.config.apps.installed.search",
{ number: this._addonInfo.addons.length }
)}
@input=${this._handleSearchChange}
>
</ha-input-search>
</div>
${
addons.length === 0
? html`<p class="no-results">
${this.hass.localize(
"ui.panel.config.apps.installed.no_apps"
"ui.panel.config.apps.installed.no_results"
)}
</button>
</div>
</ha-card>
`
: addons.map(
(addon) => html`
<ha-card
role="button"
tabindex="0"
outlined
.addon=${addon}
@click=${this._addonTapped}
aria-label=${getAppDisplayName(addon.name, addon.stage)}
>
<div class="card-content">
<supervisor-apps-card-content
.hass=${this.hass}
.title=${addon.name}
.stage=${addon.stage}
.description=${addon.description}
available
.tags=${this._getAppTags(addon)}
.state=${addon.state}
.operation=${this._operations[addon.slug]}
.icon=${
addon.update_available
? mdiArrowUpBoldCircle
: mdiPuzzle
}
.iconTitle=${
addon.state !== "started"
? this.hass.localize(
"ui.panel.config.apps.installed.app_stopped"
)
: addon.update_available
? this.hass.localize(
"ui.panel.config.apps.installed.app_update_available"
)
: this.hass.localize(
"ui.panel.config.apps.installed.app_running"
)
}
.appSlug=${addon.slug}
.hasAppIcon=${addon.icon}
></supervisor-apps-card-content>
</div>
</ha-card>
`
)
}
</div>
<ha-button size="l" href="/config/apps/available">
<ha-svg-icon slot="start" .path=${mdiStorePlus}></ha-svg-icon>
${this.hass.localize("ui.panel.config.apps.installed.add_app")}
</ha-button>
</p>`
: html`<div class="content">
${addons.map((addon) => this._renderApp(addon))}
</div>`
}
`
: html`<supervisor-apps-empty-state></supervisor-apps-empty-state>`
}
${
hasApps
? html`<ha-button
class="fab"
size="l"
href="/config/apps/available"
>
<ha-svg-icon slot="start" .path=${mdiStorePlus}></ha-svg-icon>
${this.hass.localize("ui.panel.config.apps.installed.add_app")}
</ha-button>`
: nothing
}
</hass-subpage>
`;
}
private _renderApp(addon: HassioAddonInfo) {
return html`
<ha-card
role="button"
tabindex="0"
outlined
.addon=${addon}
@click=${this._addonTapped}
aria-label=${getAppDisplayName(addon.name, addon.stage)}
>
<div class="card-content">
<supervisor-apps-card-content
.hass=${this.hass}
.title=${addon.name}
.stage=${addon.stage}
.description=${addon.description}
available
.tags=${this._getAppTags(addon)}
.state=${addon.state}
.operation=${this._operations[addon.slug]}
.icon=${addon.update_available ? mdiArrowUpBoldCircle : mdiPuzzle}
.iconTitle=${
addon.state !== "started"
? this.hass.localize(
"ui.panel.config.apps.installed.app_stopped"
)
: addon.update_available
? this.hass.localize(
"ui.panel.config.apps.installed.app_update_available"
)
: this.hass.localize(
"ui.panel.config.apps.installed.app_running"
)
}
.appSlug=${addon.slug}
.hasAppIcon=${addon.icon}
></supervisor-apps-card-content>
</div>
</ha-card>
`;
}
private _getAddons = memoizeOne(
(addons: HassioAddonInfo[], filter?: string) => {
let filteredAddons = addons;
@@ -345,10 +362,6 @@ export class HaConfigAppsInstalled extends LitElement {
navigate(`/config/app/${addon.slug}/info`);
}
private _openStore(): void {
navigate("/config/apps/available");
}
private _getAppTags(addon: HassioAddonInfo): AppTag[] {
const labels: AppTag[] = [];
@@ -426,18 +439,13 @@ export class HaConfigAppsInstalled extends LitElement {
padding: var(--ha-space-4) var(--ha-space-4) var(--ha-space-2);
}
button.link {
color: var(--primary-color);
background: none;
border: none;
padding: 0;
font: inherit;
text-align: left;
text-decoration: underline;
cursor: pointer;
.no-results {
margin: var(--ha-space-8) var(--ha-space-4);
text-align: center;
color: var(--secondary-text-color);
}
ha-button[size="l"] {
ha-button.fab {
position: fixed;
right: calc(var(--ha-space-4) + var(--safe-area-inset-right));
bottom: calc(var(--ha-space-4) + var(--safe-area-inset-bottom));
@@ -3,6 +3,7 @@ import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event";
import { getEntityAreaId } from "../../../common/entity/context/get_entity_context";
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mixin";
import "../../../components/entity/ha-entity-picker";
@@ -59,6 +60,9 @@ const cropOptions: CropOptions = {
const SENSOR_DOMAINS = ["sensor"];
const TEMPERATURE_DEVICE_CLASSES = [SENSOR_DEVICE_CLASS_TEMPERATURE];
const HUMIDITY_DEVICE_CLASSES = [SENSOR_DEVICE_CLASS_HUMIDITY];
const BINARY_SENSOR_DOMAINS = ["binary_sensor"];
// Core accepts only these device classes for an area's occupancy entity.
const OCCUPANCY_DEVICE_CLASSES = ["motion", "occupancy"];
interface AreaFormState {
name: string;
@@ -69,6 +73,7 @@ interface AreaFormState {
floor: string | null;
temperatureEntity: string | null;
humidityEntity: string | null;
occupancyEntity: string | null;
}
@customElement("dialog-area-registry-detail")
@@ -94,6 +99,8 @@ class DialogAreaDetail
@state() private _humidityEntity!: string | null;
@state() private _occupancyEntity!: string | null;
@state() private _error?: string;
@state() private _params?: AreaRegistryDetailDialogParams;
@@ -126,6 +133,7 @@ class DialogAreaDetail
this._floor = this._params.entry.floor_id;
this._temperatureEntity = this._params.entry.temperature_entity_id;
this._humidityEntity = this._params.entry.humidity_entity_id;
this._occupancyEntity = this._params.entry.occupancy_entity_id;
} else {
this._name = this._params.suggestedName || "";
this._aliases = [];
@@ -135,6 +143,7 @@ class DialogAreaDetail
this._floor = null;
this._temperatureEntity = null;
this._humidityEntity = null;
this._occupancyEntity = null;
}
this._iconFollowsName = !this._params.entry;
this._open = true;
@@ -152,6 +161,7 @@ class DialogAreaDetail
floor: this._floor,
temperatureEntity: this._temperatureEntity,
humidityEntity: this._humidityEntity,
occupancyEntity: this._occupancyEntity,
};
}
@@ -315,6 +325,20 @@ class DialogAreaDetail
.entityFilter=${this._areaEntityFilter}
@value-changed=${this._sensorChanged}
></ha-entity-picker>
<ha-entity-picker
.label=${this.hass.localize(
"ui.panel.config.areas.editor.occupancy_entity"
)}
.helper=${this.hass.localize(
"ui.panel.config.areas.editor.occupancy_entity_description"
)}
.value=${this._occupancyEntity}
.includeDomains=${BINARY_SENSOR_DOMAINS}
.includeDeviceClasses=${OCCUPANCY_DEVICE_CLASSES}
.entityFilter=${this._areaEntityFilter}
@value-changed=${this._occupancyEntityChanged}
></ha-entity-picker>
</div>
</ha-expansion-panel>
`;
@@ -473,21 +497,14 @@ class DialogAreaDetail
return this._name.trim() !== "";
}
private _areaEntityFilter = (stateObj: HassEntityState): boolean => {
const entityReg = this.hass.entities[stateObj.entity_id];
if (!entityReg) {
return false;
}
const areaId = this._params!.entry!.area_id;
if (entityReg.area_id === areaId) {
return true;
}
if (!entityReg.device_id) {
return false;
}
const deviceReg = this.hass.devices[entityReg.device_id];
return deviceReg && deviceReg.area_id === areaId;
};
// The entity's own area takes precedence over its device's area, so a
// sensor assigned to another area isn't offered here.
private _areaEntityFilter = (stateObj: HassEntityState): boolean =>
getEntityAreaId(
stateObj.entity_id,
this.hass.entities,
this.hass.devices
) === this._params!.entry!.area_id;
private _nameChanged(ev: InputEvent & HASSDomTargetEvent<HaInput>) {
this._error = undefined;
@@ -536,6 +553,11 @@ class DialogAreaDetail
this._updateDirtyState(this._currentState());
}
private _occupancyEntityChanged(ev: ValueChangedEvent<string>): void {
this._occupancyEntity = ev.detail.value || null;
this._updateDirtyState(this._currentState());
}
private async _updateEntry() {
const create = !this._params!.entry;
this._submitting = true;
@@ -549,6 +571,7 @@ class DialogAreaDetail
aliases: this._aliases,
temperature_entity_id: this._temperatureEntity,
humidity_entity_id: this._humidityEntity,
occupancy_entity_id: this._occupancyEntity,
};
if (create) {
await this._params!.createEntry!(values);
@@ -5,11 +5,14 @@ import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, queryAll } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import { ifDefined } from "lit/directives/if-defined";
import { renderMoveShortcutHint } from "../../../../common/keyboard/render-move-shortcut-hint";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/ha-button";
import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import {
ACTION_BUILDING_BLOCKS,
getAutomationActionType,
@@ -100,6 +103,8 @@ export default class HaAutomationAction extends AutomationSortableListMixin<Acti
? html`
<div
tabindex="0"
id="move-row-${idx}"
aria-keyshortcuts=${ifDefined(this.optionsInSidebar ? "Alt+ArrowUp Alt+ArrowDown" : undefined)}
class="handle ${
this.rowSortSelected === idx ? "active" : ""
}"
@@ -111,6 +116,20 @@ export default class HaAutomationAction extends AutomationSortableListMixin<Acti
<ha-svg-icon
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
${
this.optionsInSidebar
? html`<ha-tooltip
trigger="focus"
association="description"
for="move-row-${idx}"
>
${renderMoveShortcutHint(
this.hass.localize("ui.common.move_up"),
this.hass.localize("ui.common.move_down")
)}
</ha-tooltip>`
: nothing
}
</div>
`
: nothing
@@ -5,12 +5,15 @@ import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, queryAll, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import { ifDefined } from "lit/directives/if-defined";
import { renderMoveShortcutHint } from "../../../../common/keyboard/render-move-shortcut-hint";
import { consume } from "../../../../common/decorators/consume";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/ha-button";
import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import type { Condition } from "../../../../data/automation";
import type { ConditionDescriptions } from "../../../../data/condition";
import { CONDITION_BUILDING_BLOCKS } from "../../../../data/condition";
@@ -213,6 +216,8 @@ export default class HaAutomationCondition extends AutomationSortableListMixin<C
? html`
<div
tabindex="0"
id="move-row-${idx}"
aria-keyshortcuts=${ifDefined(this.optionsInSidebar ? "Alt+ArrowUp Alt+ArrowDown" : undefined)}
class="handle ${
this.rowSortSelected === idx ? "active" : ""
}"
@@ -224,6 +229,20 @@ export default class HaAutomationCondition extends AutomationSortableListMixin<C
<ha-svg-icon
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
${
this.optionsInSidebar
? html`<ha-tooltip
trigger="focus"
association="description"
for="move-row-${idx}"
>
${renderMoveShortcutHint(
this.hass.localize("ui.common.move_up"),
this.hass.localize("ui.common.move_down")
)}
</ha-tooltip>`
: nothing
}
</div>
`
: nothing
@@ -886,7 +886,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this.yamlErrors = undefined;
this.config = {
id: this.config?.id,
...normalizeAutomationConfig(ev.detail.value),
...normalizeAutomationConfig(ev.detail.value ?? {}),
};
this._updateDirtyState({
config: this.config!,
@@ -80,7 +80,6 @@ import {
duplicateAutomation,
fetchAutomationFileConfig,
getAutomationStateConfig,
showAutomationEditor,
triggerAutomationActions,
} from "../../../data/automation";
import type { CategoryRegistryEntry } from "../../../data/category_registry";
@@ -1234,7 +1233,7 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
this.hass,
automation.entity_id
);
showAutomationEditor({ ...response.config, id: undefined });
duplicateAutomation(response.config);
return;
}
await showAlertDialog(this, {
@@ -3,11 +3,14 @@ import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, queryAll } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import { ifDefined } from "lit/directives/if-defined";
import { renderMoveShortcutHint } from "../../../../common/keyboard/render-move-shortcut-hint";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/ha-button";
import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import type { Option } from "../../../../data/script";
import { AutomationSortableListMixin } from "../ha-automation-sortable-list-mixin";
import { automationRowsStyles } from "../styles";
@@ -74,6 +77,8 @@ export default class HaAutomationOption extends AutomationSortableListMixin<Opti
? html`
<div
tabindex="0"
id="move-row-${idx}"
aria-keyshortcuts=${ifDefined(this.optionsInSidebar ? "Alt+ArrowUp Alt+ArrowDown" : undefined)}
class="handle ${
this.rowSortSelected === idx ? "active" : ""
}"
@@ -85,6 +90,20 @@ export default class HaAutomationOption extends AutomationSortableListMixin<Opti
<ha-svg-icon
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
${
this.optionsInSidebar
? html`<ha-tooltip
trigger="focus"
association="description"
for="move-row-${idx}"
>
${renderMoveShortcutHint(
this.hass.localize("ui.common.move_up"),
this.hass.localize("ui.common.move_down")
)}
</ha-tooltip>`
: nothing
}
</div>
`
: nothing
@@ -5,6 +5,8 @@ import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import { ifDefined } from "lit/directives/if-defined";
import { renderMoveShortcutHint } from "../../../../common/keyboard/render-move-shortcut-hint";
import { consume } from "../../../../common/decorators/consume";
import { ensureArray } from "../../../../common/array/ensure-array";
import { fireEvent } from "../../../../common/dom/fire_event";
@@ -12,6 +14,7 @@ import { stopPropagation } from "../../../../common/dom/stop_propagation";
import "../../../../components/ha-button";
import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import type { Trigger } from "../../../../data/automation";
import { triggerDescriptionsContext } from "../../../../data/context";
import type { TriggerDescriptions } from "../../../../data/trigger";
@@ -108,6 +111,8 @@ export default class HaAutomationTrigger extends AutomationSortableListMixin<Tri
? html`
<div
tabindex="0"
id="move-row-${idx}"
aria-keyshortcuts=${ifDefined(this.optionsInSidebar ? "Alt+ArrowUp Alt+ArrowDown" : undefined)}
class="handle ${
this.rowSortSelected === idx ? "active" : ""
}"
@@ -119,6 +124,20 @@ export default class HaAutomationTrigger extends AutomationSortableListMixin<Tri
<ha-svg-icon
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
${
this.optionsInSidebar
? html`<ha-tooltip
trigger="focus"
association="description"
for="move-row-${idx}"
>
${renderMoveShortcutHint(
this.hass.localize("ui.common.move_up"),
this.hass.localize("ui.common.move_down")
)}
</ha-tooltip>`
: nothing
}
</div>
`
: nothing
@@ -734,14 +734,15 @@ export class HaConfigEntities extends LitElement {
const hidden = !!entry.hidden_by;
const disabled = !!entry.disabled_by;
const readonly = entry.readonly;
// Entities without a state (disabled ones) count as unavailable too,
// so the Available and Unavailable filters are exact opposites. An
// empty state, like that of a cleared text helper, is a valid one.
// An empty state, like that of a cleared text helper, is a valid one.
// Entities without a state (disabled ones) are neither available nor
// unavailable, so the Unavailable filter only lists entities that are
// enabled but not working, matching the Status column.
const available = !!entity && entity.state !== UNAVAILABLE;
if (!(
(showAvailable && available) ||
(showUnavailable && !available) ||
(showUnavailable && unavailable) ||
(showRestored && restored) ||
(showVisible && !hidden) ||
(showHidden && hidden) ||
@@ -3,6 +3,8 @@ import type { CSSResultGroup } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import { ifDefined } from "lit/directives/if-defined";
import { renderMoveShortcutHint } from "../../../../common/keyboard/render-move-shortcut-hint";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../common/translations/localize";
@@ -12,6 +14,7 @@ import "../../../../components/ha-icon-button";
import "../../../../components/ha-icon-picker";
import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import "../../../../components/input/ha-input";
import "../../../../components/item/ha-list-item-base";
import "../../../../components/list/ha-list-base";
@@ -143,17 +146,37 @@ class HaInputSelectForm extends LitElement {
(option) => option,
(option, index) => html`
<ha-list-item-base
id="move-option-${index}"
class="option"
interactive
.headline=${option}
.index=${index}
@keydown=${this._optionKeydown}
aria-keyshortcuts=${ifDefined(
!this.disabled
? "Alt+ArrowUp Alt+ArrowDown"
: undefined
)}
>
<ha-svg-icon
slot="start"
class="handle"
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
<ha-tooltip
trigger="focus"
association="description"
slot="start"
for=${ifDefined(
!this.disabled ? `move-option-${index}` : undefined
)}
.disabled=${this.disabled}
>
${renderMoveShortcutHint(
this._localize("ui.common.move_up"),
this._localize("ui.common.move_down")
)}
</ha-tooltip>
<ha-icon-button
slot="end"
.index=${index}
+5 -2
View File
@@ -587,7 +587,10 @@ export class HaScriptEditor extends SubscribeMixin(
// order. The defaults only fill in what is missing.
const missingDefaults =
initData && "sequence" in initData ? {} : baseConfig;
this.config = { ...initData, ...missingDefaults } as ScriptConfig;
this.config = {
...(initData ? normalizeScriptConfig(initData) : initData),
...missingDefaults,
} as ScriptConfig;
this._initDirtyTracking(
{ type: "deep", compareKeyOrder: true },
{
@@ -738,7 +741,7 @@ export class HaScriptEditor extends SubscribeMixin(
return;
}
this.yamlErrors = undefined;
this.config = ev.detail.value;
this.config = normalizeScriptConfig(ev.detail.value ?? {});
this._updateDirtyState({
config: this.config!,
entityRegistryUpdate: this.entityRegistryUpdate,
+1 -1
View File
@@ -1082,7 +1082,7 @@ ${rejected
this.hass,
script.entity_id
);
showScriptEditor(response.config);
showScriptEditor({ ...response.config, alias: undefined });
return;
}
await showAlertDialog(this, {
@@ -230,7 +230,7 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
color: var(--secondary-text-color);
}
ha-tooltip::part(base__popup) {
ha-tooltip::part(tooltip__popup) {
margin-top: 4px;
}
`;
@@ -195,7 +195,7 @@ class HuiEnergyGridGaugeCard extends LitElement implements LovelaceCard {
color: var(--secondary-text-color);
}
ha-tooltip::part(base__popup) {
ha-tooltip::part(tooltip__popup) {
margin-top: 4px;
}
`;
@@ -194,7 +194,7 @@ class HuiEnergySelfSufficiencyGaugeCard
color: var(--secondary-text-color);
}
ha-tooltip::part(base__popup) {
ha-tooltip::part(tooltip__popup) {
margin-top: 4px;
}
`;
@@ -327,7 +327,11 @@ export class HuiDialogEditBadge
: "ui.panel.lovelace.editor.edit_badge.show_visual_editor"
)}
</ha-button>
<ha-tooltip slot="secondaryAction" for="toggle-editor-mode">
<ha-tooltip
slot="secondaryAction"
for="toggle-editor-mode"
association="description"
>
${ctrlOrCmdLabel(this._i18n.localize)}+Shift+Y
</ha-tooltip>
`
@@ -348,7 +348,11 @@ export class HuiDialogEditCard
: "ui.panel.lovelace.editor.edit_card.show_visual_editor"
)}
</ha-button>
<ha-tooltip slot="secondaryAction" for="toggle-editor-mode">
<ha-tooltip
slot="secondaryAction"
for="toggle-editor-mode"
association="description"
>
${ctrlOrCmdLabel(this._i18n.localize)}+Shift+Y
</ha-tooltip>
`
@@ -11,6 +11,7 @@ import type {
HASSDomTargetEvent,
} from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { renderMoveShortcutHint } from "../../../../common/keyboard/render-move-shortcut-hint";
import { nextRender } from "../../../../common/util/render-status";
import "../../../../components/ha-button";
import "../../../../components/ha-dropdown";
@@ -18,6 +19,7 @@ import type { HaDropdownSelectEvent } from "../../../../components/ha-dropdown";
import "../../../../components/ha-dropdown-item";
import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-tooltip";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import { ICON_CONDITION } from "../../common/icon-condition";
import type {
@@ -236,6 +238,8 @@ export class HaCardConditionsEditor extends LitElement {
return html`
<div
slot="drag-handle"
id="move-condition-${idx}"
aria-keyshortcuts="Alt+ArrowUp Alt+ArrowDown"
class="handle ${this._rowSortSelected === idx ? "active" : ""}"
role="button"
tabindex="0"
@@ -246,6 +250,16 @@ export class HaCardConditionsEditor extends LitElement {
@keydown=${this._handleDragKeydown}
>
<ha-svg-icon .path=${mdiDragHorizontalVariant}></ha-svg-icon>
<ha-tooltip
trigger="focus"
association="description"
for="move-condition-${idx}"
>
${renderMoveShortcutHint(
this.hass.localize("ui.common.move_up"),
this.hass.localize("ui.common.move_down")
)}
</ha-tooltip>
</div>
`;
}
@@ -1,3 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
@@ -11,9 +12,14 @@ import {
string,
union,
} from "superstruct";
import {
consumeEntityState,
consumeLocalize,
} from "../../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { computeDomain } from "../../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-form/ha-form";
import type { SchemaUnion } from "../../../../components/ha-form/types";
import type { HaEntityPickerEntityFilterFunc } from "../../../../data/entity/entity";
@@ -78,6 +84,12 @@ export class HuiDistributionCardEditor
@state() private _configEntities?: EntityConfig[];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consumeEntityState({ entityIdPath: ["_configEntities", "0", "entity"] })
private _firstEntityStateObj?: HassEntityState;
public setConfig(config: DistributionCardConfig): void {
assert(config, cardConfigStruct);
this._config = config;
@@ -89,23 +101,14 @@ export class HuiDistributionCardEditor
private _entityFilter = memoizeOne(
(
entities: EntityConfig[] | undefined,
hass: HomeAssistant
targetDeviceClass: string | undefined
): HaEntityPickerEntityFilterFunc | undefined => {
// No filtering if no entities yet
if (!entities || entities.length === 0) {
return undefined;
}
// Get the domain and device_class of the first entity
const firstEntityState = hass.states[entities[0].entity];
if (!firstEntityState) {
// No filtering if no entities yet, or the first entity has no state
if (!entities || entities.length === 0 || !targetDeviceClass) {
return undefined;
}
const targetDomain = computeDomain(entities[0].entity);
// Default to "none" if no device_class (Home Assistant pattern)
const targetDeviceClass =
firstEntityState.attributes.device_class || "none";
// Create set of already selected entity IDs for fast lookup
const selectedEntityIds = new Set(entities.map((e) => e.entity));
@@ -143,11 +146,16 @@ export class HuiDistributionCardEditor
}
const schema = this._schema();
const entityFilter = this._entityFilter(this._configEntities, this.hass);
// Default to "none" if no device_class (Home Assistant pattern)
const entityFilter = this._entityFilter(
this._configEntities,
this._firstEntityStateObj
? this._firstEntityStateObj.attributes.device_class || "none"
: undefined
);
return html`
<ha-form
.hass=${this.hass}
.data=${this._config}
.schema=${schema}
.computeLabel=${this._computeLabelCallback}
@@ -207,13 +215,13 @@ export class HuiDistributionCardEditor
) => {
switch (schema.name) {
case "title":
return `${this.hass!.localize(
return `${this._localize(
"ui.panel.lovelace.editor.card.generic.title"
)} (${this.hass!.localize(
)} (${this._localize(
"ui.panel.lovelace.editor.card.config.optional"
)})`;
case "expand_legend":
return this.hass!.localize(
return this._localize(
"ui.panel.lovelace.editor.card.generic.expand_legend"
);
default:
@@ -18,9 +18,11 @@ import {
type,
union,
} from "superstruct";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { customType } from "../../../../common/structs/is-custom-type";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-card";
import "../../../../components/ha-form/ha-form";
import type { SchemaUnion } from "../../../../components/ha-form/types";
@@ -224,6 +226,8 @@ export class HuiEntitiesCardEditor
@state() private _subElementEditorConfig?: SubElementEditorConfig;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
public setConfig(config: EntitiesCardConfig): void {
const migratedConfig = migrateEntitiesCardConfig(config);
assert(migratedConfig, cardConfigStruct);
@@ -266,7 +270,6 @@ export class HuiEntitiesCardEditor
return html`
<div class="card-config">
<ha-form
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA}
.computeLabel=${this._computeLabelCallback}
@@ -314,17 +317,17 @@ export class HuiEntitiesCardEditor
switch (schema.name) {
case "title":
case "theme":
return `${this.hass!.localize(
return `${this._localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
)} (${this.hass!.localize(
)} (${this._localize(
"ui.panel.lovelace.editor.card.config.optional"
)})`;
case "show_header_toggle":
return this.hass!.localize(
return this._localize(
"ui.panel.lovelace.editor.card.entities.show_header_toggle"
);
default:
return this.hass!.localize(
return this._localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
);
}
@@ -332,7 +335,7 @@ export class HuiEntitiesCardEditor
private _valueChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (!this._config || !this.hass) {
if (!this._config) {
return;
}
@@ -374,7 +377,7 @@ export class HuiEntitiesCardEditor
private _handleSubElementChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (!this._config || !this.hass) {
if (!this._config) {
return;
}
@@ -14,9 +14,7 @@ import {
} from "superstruct";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-form/ha-form";
import type { SchemaUnion } from "../../../../components/ha-form/types";
import { NON_NUMERIC_ATTRIBUTES } from "../../../../data/entity/entity_attributes";
import type { UiColorExtraOption } from "../../../../data/selector";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type { HomeAssistant } from "../../../../types";
import {
@@ -31,6 +29,7 @@ import {
supportedActions,
} from "../../components/hui-action-editor";
import type { LovelaceCardEditor } from "../../types";
import { editorTranslations } from "../editor-translations";
import { actionConfigStruct } from "../structs/action-struct";
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
import { entityNameStruct } from "../structs/entity-name-struct";
@@ -74,6 +73,160 @@ const cardConfigStruct = assign(
})
);
const SCHEMA = [
{
name: "entity",
selector: {
entity: {
domain: ["counter", "input_number", "number", "sensor"],
},
},
},
{
name: "attribute",
selector: {
attribute: {
hide_attributes: NON_NUMERIC_ATTRIBUTES,
},
},
context: { filter_entity: "entity" },
},
{
name: "name",
selector: {
entity_name: {},
},
context: { entity: "entity" },
},
{ name: "unit", selector: { text: {} } },
{ name: "theme", selector: { theme: {} } },
{
name: "",
type: "grid",
schema: [
{
name: "min",
default: DEFAULT_MIN,
selector: { number: { mode: "box", step: "any" } },
},
{
name: "max",
default: DEFAULT_MAX,
selector: { number: { mode: "box", step: "any" } },
},
],
},
{
name: "",
type: "grid",
schema: [
{ name: "needle", selector: { boolean: {} } },
{
name: "color_mode",
required: true,
selector: {
select: {
mode: "dropdown",
translation_key: "color_mode",
options: ["color", "severity", "segments"],
},
},
},
],
},
{
name: "color",
visible: { field: "color_mode", value: "color" },
selector: {
ui_color: {
default_color: "default",
translation_key: "color",
extra_options: [
{ value: "default", display_color: severityMap.normal },
],
},
},
},
{
name: "segments",
visible: { field: "color_mode", value: "segments" },
selector: {
object: {
multiple: true,
reorder: false,
translation_key: "segments",
fields: {
from: {
required: true,
selector: { number: { mode: "box", step: "any" } },
},
color: {
required: true,
selector: { ui_color: {} },
},
label: {
selector: { text: {} },
},
},
},
},
},
{
name: "severity",
type: "grid",
visible: { field: "color_mode", value: "severity" },
schema: [
{
name: "green",
selector: { number: { mode: "box", step: "any" } },
},
{
name: "yellow",
selector: { number: { mode: "box", step: "any" } },
},
{
name: "red",
selector: { number: { mode: "box", step: "any" } },
},
],
},
{
name: "interactions",
type: "expandable",
flatten: true,
iconPath: mdiGestureTap,
schema: [
{
name: "tap_action",
selector: {
ui_action: {
actions: TAP_ACTIONS,
default_action: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "optional_actions",
flatten: true,
schema: (["hold_action", "double_tap_action"] as const).map(
(action) => ({
name: action,
selector: {
ui_action: {
actions: TAP_ACTIONS,
default_action: "none" as const,
},
},
context: ACTION_RELATED_CONTEXT,
})
),
},
],
},
] as const;
@customElement("hui-gauge-card-editor")
export class HuiGaugeCardEditor
extends LitElement
@@ -88,180 +241,8 @@ export class HuiGaugeCardEditor
this._config = config;
}
private _schema = memoizeOne(
(localize: LocalizeFunc) =>
[
{
name: "entity",
selector: {
entity: {
domain: ["counter", "input_number", "number", "sensor"],
},
},
},
{
name: "attribute",
selector: {
attribute: {
hide_attributes: NON_NUMERIC_ATTRIBUTES,
},
},
context: { filter_entity: "entity" },
},
{
name: "name",
selector: {
entity_name: {},
},
context: { entity: "entity" },
},
{ name: "unit", selector: { text: {} } },
{ name: "theme", selector: { theme: {} } },
{
name: "",
type: "grid",
schema: [
{
name: "min",
default: DEFAULT_MIN,
selector: { number: { mode: "box", step: "any" } },
},
{
name: "max",
default: DEFAULT_MAX,
selector: { number: { mode: "box", step: "any" } },
},
],
},
{
name: "",
type: "grid",
schema: [
{ name: "needle", selector: { boolean: {} } },
{
name: "color_mode",
required: true,
selector: {
select: {
mode: "dropdown",
options: (["color", "severity", "segments"] as const).map(
(mode) => ({
value: mode,
label: localize(
`ui.panel.lovelace.editor.card.gauge.color_mode_options.${mode}`
),
})
),
},
},
},
],
},
{
name: "color",
visible: { field: "color_mode", value: "color" },
selector: {
ui_color: {
default_color: "default",
extra_options: [
{
value: "default",
label: localize(
"ui.panel.lovelace.editor.card.gauge.color_default"
),
display_color: severityMap.normal,
},
] as UiColorExtraOption[],
},
},
},
{
name: "segments",
visible: { field: "color_mode", value: "segments" },
selector: {
object: {
multiple: true,
reorder: false,
fields: {
from: {
label: localize(
"ui.panel.lovelace.editor.card.gauge.segment.from"
),
required: true,
selector: { number: { mode: "box", step: "any" } },
},
color: {
label: localize(
"ui.panel.lovelace.editor.card.generic.color"
),
required: true,
selector: { ui_color: {} },
},
label: {
label: localize(
"ui.panel.lovelace.editor.card.gauge.segment.label"
),
selector: { text: {} },
},
},
},
},
},
{
name: "severity",
type: "grid",
visible: { field: "color_mode", value: "severity" },
schema: [
{
name: "green",
selector: { number: { mode: "box", step: "any" } },
},
{
name: "yellow",
selector: { number: { mode: "box", step: "any" } },
},
{
name: "red",
selector: { number: { mode: "box", step: "any" } },
},
],
},
{
name: "interactions",
type: "expandable",
flatten: true,
iconPath: mdiGestureTap,
schema: [
{
name: "tap_action",
selector: {
ui_action: {
actions: TAP_ACTIONS,
default_action: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "optional_actions",
flatten: true,
schema: (["hold_action", "double_tap_action"] as const).map(
(action) => ({
name: action,
selector: {
ui_action: {
actions: TAP_ACTIONS,
default_action: "none" as const,
},
},
context: ACTION_RELATED_CONTEXT,
})
),
},
],
},
] as const
private _translations = memoizeOne((localize: LocalizeFunc) =>
editorTranslations(localize, "ui.panel.lovelace.editor.card.gauge")
);
protected render() {
@@ -269,7 +250,7 @@ export class HuiGaugeCardEditor
return nothing;
}
const schema = this._schema(this.hass.localize);
const translations = this._translations(this.hass.localize);
const data = {
color_mode: this._colorMode(this._config!),
...this._config,
@@ -280,8 +261,10 @@ export class HuiGaugeCardEditor
<ha-form
.hass=${this.hass}
.data=${data}
.schema=${schema}
.computeLabel=${this._computeLabelCallback}
.schema=${SCHEMA}
.computeLabel=${translations.computeLabel}
.computeHelper=${translations.computeHelper}
.localizeValue=${translations.localizeValue}
@value-changed=${this._valueChanged}
></ha-form>
`;
@@ -336,78 +319,6 @@ export class HuiGaugeCardEditor
fireEvent(this, "config-changed", { config });
}
private _computeLabelCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) => {
switch (schema.name) {
case "name":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.name"
);
case "entity":
return `${this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.entity"
)} (${this.hass!.localize(
"ui.panel.lovelace.editor.card.config.required"
)})`;
case "max":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.maximum"
);
case "min":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.minimum"
);
case "color_mode":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.gauge.color_mode"
);
case "color":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.color"
);
case "segments":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.gauge.segments"
);
case "needle":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.gauge.needle_gauge"
);
case "theme":
return `${this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.theme"
)} (${this.hass!.localize(
"ui.panel.lovelace.editor.card.config.optional"
)})`;
case "unit":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.unit"
);
case "interactions":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.interactions"
);
case "tap_action":
case "hold_action":
case "double_tap_action":
return `${this.hass!.localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
)} (${this.hass!.localize(
"ui.panel.lovelace.editor.card.config.optional"
)})`;
case "attribute":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.generic.attribute"
);
default:
// "green" | "yellow" | "red"
return this.hass!.localize(
`ui.panel.lovelace.editor.card.gauge.severity.${schema.name}`
);
}
};
}
declare global {
@@ -1,3 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import {
@@ -12,7 +13,12 @@ import {
union,
} from "superstruct";
import memoizeOne from "memoize-one";
import {
consumeEntityState,
consumeLocalize,
} from "../../../../common/decorators/consume-context-entry";
import { computeDomain } from "../../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-form/ha-form";
@@ -94,6 +100,14 @@ export class HuiGlanceCardEditor
@state() private _configEntities?: ConfigEntity[];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consumeEntityState({
entityIdPath: ["_subElementEditorConfig", "elementConfig", "entity"],
})
private _subElementStateObj?: HassEntityState;
public setConfig(config: GlanceCardConfig): void {
const migratedConfig = migrateGlanceCardConfig(config);
assert(migratedConfig, cardConfigStruct);
@@ -188,7 +202,7 @@ export class HuiGlanceCardEditor
TIMESTAMP_STATE_DOMAINS.has(domain) ||
(domain === "sensor" &&
SENSOR_TIMESTAMP_DEVICE_CLASSES.includes(
this.hass.states[entity]?.attributes.device_class
this._subElementStateObj?.attributes.device_class
));
return html`
<hui-sub-element-editor
@@ -211,7 +225,6 @@ export class HuiGlanceCardEditor
return html`
<ha-form
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA}
.computeLabel=${this._computeLabelCallback}
@@ -271,17 +284,17 @@ export class HuiGlanceCardEditor
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) => {
switch (schema.name) {
case "theme":
return `${this.hass!.localize(
return `${this._localize(
"ui.panel.lovelace.editor.card.generic.theme"
)} (${this.hass!.localize(
)} (${this._localize(
"ui.panel.lovelace.editor.card.config.optional"
)})`;
case "columns":
return this.hass!.localize(
return this._localize(
`ui.panel.lovelace.editor.card.glance.${schema.name}`
);
default:
return this.hass!.localize(
return this._localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
);
}
@@ -17,7 +17,12 @@ import {
union,
} from "superstruct";
import { ContextProvider } from "@lit/context";
import type { HassEntityState } from "home-assistant-js-websocket";
import type {
HassEntityState,
HassEntityStates,
} from "home-assistant-js-websocket";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { computeDomain } from "../../../../common/entity/compute_domain";
@@ -38,6 +43,7 @@ import {
MAP_STYLES,
} from "../../../../common/map/map-styles";
import { MAP_CARD_MARKER_LABEL_MODES } from "../../../../components/map/ha-map";
import { statesContext } from "../../../../data/context";
import type { SelectSelector } from "../../../../data/selector";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import { THEME_MODES } from "../../../../types";
@@ -126,6 +132,11 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
@state() private _subElementEditorConfig?: SubElementEditorConfig;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@consume({ context: statesContext, subscribe: true })
private _states?: HassEntityStates | null;
private _shouldDisableOptions = (entityId: string) =>
computeDomain(entityId) === "zone";
@@ -327,15 +338,16 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
protected firstUpdated(changedProperties: PropertyValues<this>) {
super.firstUpdated(changedProperties);
this._locationEntities = !this.hass
const states = this._states;
this._locationEntities = !states
? []
: Object.keys(this.hass!.states).filter((entity_id) =>
getEntityLocation(this.hass!.states[entity_id], this.hass!.states)
: Object.keys(states).filter((entity_id) =>
getEntityLocation(states[entity_id], states)
);
}
private _entityHasLocation = (stateObj: HassEntityState) =>
!!getEntityLocation(stateObj, this.hass!.states);
!!getEntityLocation(stateObj, this._states ?? {});
protected render() {
if (!this.hass || !this._config) {
@@ -351,7 +363,7 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
.hass=${this.hass}
.config=${this._subElementEditorConfig}
.form=${this._subForm(
this.hass.localize,
this._localize,
entityId,
this._locationEntities
)}
@@ -367,9 +379,8 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
: [];
return html`
<ha-form
.hass=${this.hass}
.data=${this._formData(this._config)}
.schema=${this._schema(this.hass.localize)}
.schema=${this._schema(this._localize)}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
@value-changed=${this._valueChanged}
@@ -386,19 +397,19 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
></hui-entity-editor>
<h3>
${this.hass.localize(
${this._localize(
"ui.panel.lovelace.editor.card.map.geo_location_sources"
)}
</h3>
<ha-selector-select
.label=${this.hass.localize("ui.panel.lovelace.editor.card.map.source")}
.label=${this._localize("ui.panel.lovelace.editor.card.map.source")}
.required=${false}
.value=${this._geo_location_sources}
@value-changed=${this._geoSourcesChanged}
.selector=${this._selectSchema(
this._possibleGeoSources,
this.hass.localize
this._localize
)}
></ha-selector-select>
${this.renderConditions()}
@@ -408,13 +419,9 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
renderConditions() {
const conditions = this._config?.conditions ?? [];
return html`
<h3>
${this.hass!.localize("ui.panel.lovelace.editor.card.map.conditions")}
</h3>
<h3>${this._localize("ui.panel.lovelace.editor.card.map.conditions")}</h3>
<p class="intro">
${this.hass!.localize(
"ui.panel.lovelace.editor.card.map.conditions_helper"
)}
${this._localize("ui.panel.lovelace.editor.card.map.conditions_helper")}
</p>
<ha-card-conditions-editor
.hass=${this.hass!}
@@ -511,7 +518,7 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
}
private _geoSourcesChanged(ev: ValueChangedEvent<any>): void {
if (!this._config || !this.hass) {
if (!this._config) {
return;
}
@@ -565,9 +572,9 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
);
}
if (this.hass && !this._possibleGeoSources) {
if (this._states && !this._possibleGeoSources) {
const sources: Record<string, string> = {};
Object.entries(this.hass.states).forEach(([entity_id, stateObj]) => {
Object.entries(this._states).forEach(([entity_id, stateObj]) => {
const domain = computeDomain(entity_id);
if (domain === "geo_location" && stateObj.attributes.source) {
sources[stateObj.attributes.source] = stateObj.attributes.attribution;
@@ -596,11 +603,11 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
case "show_zone_radius":
case "cluster":
case "show_all":
return this.hass!.localize(
return this._localize(
`ui.panel.lovelace.editor.card.map.${schema.name}`
);
default:
return this.hass!.localize(
return this._localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
);
}
@@ -617,7 +624,7 @@ export class HuiMapCardEditor extends LitElement implements LovelaceCardEditor {
case "show_zone_radius":
case "cluster":
case "show_all":
return this.hass!.localize(
return this._localize(
`ui.panel.lovelace.editor.card.map.${schema.name}_helper`
);
default:
@@ -20,9 +20,11 @@ import {
optional,
string,
} from "superstruct";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { storage } from "../../../../common/decorators/storage";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type {
HaFormSchema,
SchemaUnion,
@@ -85,6 +87,8 @@ export class HuiStackCardEditor
@state() protected _guiModeAvailable? = true;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
protected _keys = new Map<string, string>();
protected _schema: readonly HaFormSchema[] = SCHEMA;
@@ -116,7 +120,6 @@ export class HuiStackCardEditor
return html`
<ha-form
.hass=${this.hass}
.data=${this.formData()}
.schema=${this._schema}
.computeLabel=${this._computeLabelCallback}
@@ -139,9 +142,7 @@ export class HuiStackCardEditor
<ha-icon-button
@click=${this._handleAddCard}
.path=${mdiPlus}
.label=${this.hass!.localize(
"ui.panel.lovelace.editor.edit_card.add"
)}
.label=${this._localize("ui.panel.lovelace.editor.edit_card.add")}
></ha-icon-button>
</div>
@@ -154,7 +155,7 @@ export class HuiStackCardEditor
class="gui-mode-button"
@click=${this._toggleMode}
.disabled=${!this._guiModeAvailable}
.label=${this.hass!.localize(
.label=${this._localize(
isGuiMode
? "ui.panel.lovelace.editor.edit_card.show_code_editor"
: "ui.panel.lovelace.editor.edit_card.show_visual_editor"
@@ -164,7 +165,7 @@ export class HuiStackCardEditor
<ha-icon-button-arrow-prev
.disabled=${selected === 0}
.label=${this.hass!.localize(
.label=${this._localize(
"ui.panel.lovelace.editor.edit_card.move_before"
)}
@click=${this._handleMove}
@@ -172,7 +173,7 @@ export class HuiStackCardEditor
></ha-icon-button-arrow-prev>
<ha-icon-button-arrow-next
.label=${this.hass!.localize(
.label=${this._localize(
"ui.panel.lovelace.editor.edit_card.move_after"
)}
.disabled=${selected === numcards - 1}
@@ -181,7 +182,7 @@ export class HuiStackCardEditor
></ha-icon-button-arrow-next>
<ha-icon-button
.label=${this.hass!.localize(
.label=${this._localize(
"ui.panel.lovelace.editor.edit_card.copy"
)}
.path=${mdiContentCopy}
@@ -189,7 +190,7 @@ export class HuiStackCardEditor
></ha-icon-button>
<ha-icon-button
.label=${this.hass!.localize(
.label=${this._localize(
"ui.panel.lovelace.editor.edit_card.cut"
)}
.path=${mdiContentCut}
@@ -197,7 +198,7 @@ export class HuiStackCardEditor
></ha-icon-button>
<ha-icon-button
.label=${this.hass!.localize(
.label=${this._localize(
"ui.panel.lovelace.editor.edit_card.delete"
)}
.path=${mdiDelete}
@@ -330,7 +331,7 @@ export class HuiStackCardEditor
}
protected _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) =>
this.hass!.localize(
this._localize(
`ui.panel.lovelace.editor.card.${this._config!.type}.${schema.name}`
);
@@ -125,7 +125,7 @@ export class HuiTileCardEditor
);
private _translations = memoizeOne((localize: LocalizeFunc) =>
editorTranslations(localize, "ui.panel.lovelace.editor.card.tile.editor")
editorTranslations(localize, "ui.panel.lovelace.editor.card.tile")
);
private _hasCompatibleFeatures = memoizeOne(
@@ -2,8 +2,10 @@ import { mdiCodeBraces, mdiListBoxOutline } from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-icon-button";
import "../../../components/ha-icon-button-prev";
import type { HomeAssistant } from "../../../types";
@@ -31,6 +33,8 @@ export class HuiSubElementEditor extends LitElement {
@property({ attribute: false }) public form?: LovelaceConfigForm;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _guiModeAvailable = true;
@state() private _guiMode = true;
@@ -47,22 +51,22 @@ export class HuiSubElementEditor extends LitElement {
<div class="header">
<div class="back-title">
<ha-icon-button-prev
.label=${this.hass!.localize("ui.common.back")}
.label=${this._localize("ui.common.back")}
@click=${this._goBack}
></ha-icon-button-prev>
<span slot="title">
${
this.config?.type === "element"
? this.hass.localize(
? this._localize(
`ui.panel.lovelace.editor.sub-element-editor.types.element_type`,
{
type:
this.hass.localize(
this._localize(
`ui.panel.lovelace.editor.card.picture-elements.element_types.${elementType}`
) || elementType,
}
)
: this.hass.localize(
: this._localize(
`ui.panel.lovelace.editor.sub-element-editor.types.${this.config?.type}`
)
}
@@ -72,7 +76,7 @@ export class HuiSubElementEditor extends LitElement {
class="gui-mode-button"
@click=${this._toggleMode}
.disabled=${!this._guiModeAvailable}
.label=${this.hass!.localize(
.label=${this._localize(
this._guiMode
? "ui.panel.lovelace.editor.edit_card.show_code_editor"
: "ui.panel.lovelace.editor.edit_card.show_visual_editor"
@@ -434,7 +434,11 @@ export class HuiDialogEditSection
: "ui.panel.lovelace.editor.edit_card.show_code_editor"
)}
</ha-button>
<ha-tooltip slot="secondaryAction" for="toggle-editor-mode">
<ha-tooltip
slot="secondaryAction"
for="toggle-editor-mode"
association="description"
>
${ctrlOrCmdLabel(this.hass.localize)}+Shift+Y
</ha-tooltip>
<ha-button
+16
View File
@@ -32,6 +32,7 @@ import { UndoRedoController } from "../../common/controllers/undo-redo-controlle
import { fireEvent } from "../../common/dom/fire_event";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
import { renderMoveShortcutHint } from "../../common/keyboard/render-move-shortcut-hint";
import type { NavigateOptions } from "../../common/navigate";
import { goBack, navigate, replaceCurrentUrl } from "../../common/navigate";
import type { LocalizeKeys } from "../../common/translations/localize";
@@ -528,6 +529,7 @@ class HUIRoot extends KeyboardShortcutMixin(LitElement) {
`;
return html`
<ha-tab-group-tab
id="move-view-${index}"
slot="nav"
panel=${index}
.active=${current}
@@ -552,6 +554,20 @@ class HUIRoot extends KeyboardShortcutMixin(LitElement) {
class="edit-icon view handle"
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
<ha-tooltip
trigger="focus"
association="description"
for="move-view-${index}"
>
${renderMoveShortcutHint(
this.hass.localize(
`ui.panel.lovelace.editor.edit_view.${rtl ? "move_right" : "move_left"}`
),
this.hass.localize(
`ui.panel.lovelace.editor.edit_view.${rtl ? "move_left" : "move_right"}`
)
)}
</ha-tooltip>
<ha-icon-button
.label=${this.hass!.localize(
`ui.panel.lovelace.editor.edit_view.${rtl ? "move_right" : "move_left"}`
+35 -27
View File
@@ -87,32 +87,39 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
private _sidebarScrollTop = 0;
private _columnsController = new ResizeController(this, {
callback: (entries) => {
const totalWidth = entries[0]?.contentRect.width;
private _measuredColumns?: number;
if (!totalWidth) return 1;
constructor() {
super();
new ResizeController(this, {
skipInitial: true,
callback: (entries) => {
const totalWidth = entries[0]?.contentRect.width;
const style = getComputedStyle(this);
const wrapper = this.shadowRoot!.querySelector(".wrapper")!;
const wrapperStyle = getComputedStyle(wrapper);
const container = this.shadowRoot!.querySelector(".container")!;
const containerStyle = getComputedStyle(container);
if (totalWidth) {
this._measuredColumns = this._computeColumnCount(totalWidth);
}
},
});
}
const paddingLeft = parsePx(wrapperStyle.paddingLeft);
const paddingRight = parsePx(wrapperStyle.paddingRight);
const padding = paddingLeft + paddingRight;
const minColumnWidth = parsePx(
style.getPropertyValue("--column-min-width")
);
const columnGap = parsePx(containerStyle.columnGap);
private _computeColumnCount(totalWidth: number): number {
const style = getComputedStyle(this);
const minColumnWidth = parsePx(
style.getPropertyValue("--column-min-width")
);
const columnGap = parsePx(style.columnGap);
const columns = Math.floor(
(totalWidth - padding + columnGap) / (minColumnWidth + columnGap)
);
return Math.max(columns, 1);
},
});
if (!totalWidth || !minColumnWidth || Number.isNaN(columnGap)) {
return 1;
}
// The wrapper's side padding is one column gap on each side
const columns = Math.floor(
(totalWidth - columnGap) / (minColumnWidth + columnGap)
);
return Math.max(columns, 1);
}
public setConfig(config: LovelaceViewConfig): void {
this._config = config;
@@ -152,6 +159,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
disconnectedCallback(): void {
super.disconnectedCallback();
this._measuredColumns = undefined;
this.removeEventListener(
"section-visibility-changed",
this._sectionVisibilityChanged
@@ -175,11 +183,10 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
// The column count is clamped here instead of in the resize callback, so
// that it follows the config of the view the element is currently used for
const maxColumns = this._config?.max_columns ?? DEFAULT_MAX_COLUMNS;
const maxColumnCount = clamp(
this._columnsController.value ?? 1,
1,
maxColumns
);
const availableColumns =
this._measuredColumns ??
(this.isConnected ? this._computeColumnCount(this.clientWidth) : 1);
const maxColumnCount = clamp(availableColumns, 1, maxColumns);
if (maxColumnCount !== this._maxColumns) {
this._maxColumns = maxColumnCount;
@@ -552,6 +559,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
--column-min-width: var(--ha-view-sections-column-min-width, 320px);
--narrow-column-gap: var(--ha-view-sections-narrow-column-gap, 8px);
--top-margin: var(--ha-view-sections-extra-top-margin, 80px);
column-gap: var(--column-gap);
display: block;
flex: 1;
}
+24 -17
View File
@@ -406,26 +406,10 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
);
this._updateHass({ systemData: {} });
});
clearInterval(this.__backendPingInterval);
this._refreshBrandsAccessToken();
this.__backendPingInterval = setInterval(() => {
if (this.hass?.connected) {
// If the backend is busy, or the connection is latent,
// it can take more than 10 seconds for the ping to return.
// We give it a 15 second timeout to be safe.
promiseTimeout(15000, this.hass?.connection.ping()).catch(() => {
if (!this.hass?.connected) {
return;
}
// eslint-disable-next-line no-console
console.log("Websocket died, forcing reconnect...");
this.hass?.connection.reconnect(true);
});
}
}, 30000);
this._startBackendPing();
}
protected hassReconnected() {
@@ -436,6 +420,8 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
this._refreshBrandsAccessToken();
this._startBackendPing();
// on reconnect always fetch config as we might miss an update while we were disconnected
// @ts-ignore
this.hass!.callWS({ type: "get_config" }).then((config: HassConfig) => {
@@ -456,6 +442,27 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
clearBrandsTokenRefresh();
}
private _startBackendPing() {
clearInterval(this.__backendPingInterval);
this.__backendPingInterval = setInterval(() => {
if (this.hass?.connected) {
// If the backend is busy, or the connection is latent,
// it can take more than 10 seconds for the ping to return.
// We give it a 15 second timeout to be safe.
promiseTimeout(15000, this.hass?.connection.ping()).catch(() => {
if (!this.hass?.connected) {
return;
}
// eslint-disable-next-line no-console
console.log("Websocket died, forcing reconnect...");
this.hass?.connection.reconnect(true);
});
}
}, 30000);
}
private async _refreshBrandsAccessToken() {
// The brands WS handler may not be registered yet after a server restart;
// fetchAndScheduleBrandsAccessToken retries internally. If the token
+103 -48
View File
@@ -482,6 +482,8 @@
"and": "and",
"continue": "Continue",
"previous": "Previous",
"move_up": "Move up",
"move_down": "Move down",
"loading": "Loading",
"refresh": "Refresh",
"cancel": "Cancel",
@@ -3463,7 +3465,9 @@
},
"installed": {
"search": "Search {number} {number, plural,\n one {app}\n other {apps}\n}",
"no_apps": "You don't have any apps installed yet. Click here to browse available apps.",
"empty_header": "Install your first app",
"empty_text": "Apps run extra software alongside Home Assistant, like a file editor, an MQTT broker, or a media server. Find the ones that fit your home in the app store.",
"no_results": "No apps match your search",
"add_app": "Install app",
"app_stopped": "App is stopped",
"app_update_available": "Update available",
@@ -3837,6 +3841,8 @@
"temperature_entity_description": "Sensor that represents the area temperature.",
"humidity_entity": "Humidity sensor",
"humidity_entity_description": "Sensor that represents the area humidity.",
"occupancy_entity": "Occupancy sensor",
"occupancy_entity_description": "Motion or occupancy sensor that shows whether the area is in use.",
"related_entities_section": "Related sensors"
},
"delete": {
@@ -6125,8 +6131,8 @@
"alias": "Name",
"automation_alias": "Automation name",
"automation_settings": "Automation settings",
"move_up": "Move up",
"move_down": "Move down",
"move_up": "[%key:ui::common::move_up%]",
"move_down": "[%key:ui::common::move_down%]",
"collapse_all": "Collapse all",
"expand_all": "Expand all",
"description": {
@@ -11642,7 +11648,58 @@
"red": "Red",
"yellow": "Yellow"
},
"description": "This card is a basic card that allows visually seeing sensor data."
"description": "This card is a basic card that allows visually seeing sensor data.",
"sections": {
"interactions": {
"name": "[%key:ui::panel::lovelace::editor::card::generic::interactions%]"
}
},
"data": {
"entity": "[%key:ui::panel::lovelace::editor::card::generic::entity%]",
"attribute": "[%key:ui::panel::lovelace::editor::card::generic::attribute%]",
"name": "[%key:ui::panel::lovelace::editor::card::generic::name%]",
"unit": "[%key:ui::panel::lovelace::editor::card::generic::unit%]",
"theme": "[%key:ui::panel::lovelace::editor::card::generic::theme%]",
"min": "[%key:ui::panel::lovelace::editor::card::generic::minimum%]",
"max": "[%key:ui::panel::lovelace::editor::card::generic::maximum%]",
"needle": "[%key:ui::panel::lovelace::editor::card::gauge::needle_gauge%]",
"color_mode": "[%key:ui::panel::lovelace::editor::card::gauge::color_mode%]",
"color": "[%key:ui::panel::lovelace::editor::card::tile::color%]",
"segments": "[%key:ui::panel::lovelace::editor::card::gauge::segments%]",
"green": "[%key:ui::panel::lovelace::editor::card::gauge::severity::green%]",
"yellow": "[%key:ui::panel::lovelace::editor::card::gauge::severity::yellow%]",
"red": "[%key:ui::panel::lovelace::editor::card::gauge::severity::red%]",
"tap_action": "[%key:ui::panel::lovelace::editor::card::generic::tap_action%]",
"hold_action": "[%key:ui::panel::lovelace::editor::card::generic::hold_action%]",
"double_tap_action": "[%key:ui::panel::lovelace::editor::card::generic::double_tap_action%]"
},
"selector": {
"color_mode": {
"options": {
"color": "[%key:ui::panel::lovelace::editor::card::gauge::color_mode_options::color%]",
"severity": "[%key:ui::panel::lovelace::editor::card::gauge::color_mode_options::severity%]",
"segments": "[%key:ui::panel::lovelace::editor::card::gauge::color_mode_options::segments%]"
}
},
"color": {
"options": {
"default": "[%key:ui::panel::lovelace::editor::card::gauge::color_default%]"
}
},
"segments": {
"fields": {
"from": {
"name": "[%key:ui::panel::lovelace::editor::card::gauge::segment::from%]"
},
"color": {
"name": "[%key:ui::panel::lovelace::editor::card::tile::color%]"
},
"label": {
"name": "[%key:ui::panel::lovelace::editor::card::gauge::segment::label%]"
}
}
}
}
},
"glance": {
"name": "Glance",
@@ -12320,53 +12377,51 @@
"horizontal": "Horizontal",
"vertical": "Vertical"
},
"editor": {
"sections": {
"content": {
"name": "[%key:ui::panel::lovelace::editor::card::generic::content%]"
},
"interactions": {
"name": "[%key:ui::panel::lovelace::editor::card::generic::interactions%]"
"sections": {
"content": {
"name": "[%key:ui::panel::lovelace::editor::card::generic::content%]"
},
"interactions": {
"name": "[%key:ui::panel::lovelace::editor::card::generic::interactions%]"
}
},
"data": {
"entity": "[%key:ui::panel::lovelace::editor::card::generic::entity%]",
"name": "[%key:ui::panel::lovelace::editor::card::generic::name%]",
"icon": "[%key:ui::panel::lovelace::editor::card::generic::icon%]",
"color": "[%key:ui::panel::lovelace::editor::card::tile::color%]",
"show_entity_picture": "[%key:ui::panel::lovelace::editor::card::tile::show_entity_picture%]",
"hide_state": "[%key:ui::panel::lovelace::editor::card::tile::hide_state%]",
"state_content": "[%key:ui::panel::lovelace::editor::card::tile::state_content%]",
"time_format": "[%key:ui::panel::lovelace::editor::card::generic::time_format%]",
"content_layout": "[%key:ui::panel::lovelace::editor::card::tile::content_layout%]",
"tap_action": "[%key:ui::panel::lovelace::editor::card::generic::tap_action%]",
"icon_tap_action": "[%key:ui::panel::lovelace::editor::card::tile::icon_tap_action%]",
"hold_action": "[%key:ui::panel::lovelace::editor::card::generic::hold_action%]",
"icon_hold_action": "[%key:ui::panel::lovelace::editor::card::tile::icon_hold_action%]",
"double_tap_action": "[%key:ui::panel::lovelace::editor::card::generic::double_tap_action%]",
"icon_double_tap_action": "[%key:ui::panel::lovelace::editor::card::tile::icon_double_tap_action%]",
"features_position": "[%key:ui::panel::lovelace::editor::card::tile::features_position%]"
},
"data_description": {
"color": "[%key:ui::panel::lovelace::editor::card::tile::color_helper%]",
"features_position": "[%key:ui::panel::lovelace::editor::card::tile::features_position_helper_vertical%]"
},
"selector": {
"content_layout": {
"options": {
"horizontal": "[%key:ui::panel::lovelace::editor::card::tile::content_layout_options::horizontal%]",
"vertical": "[%key:ui::panel::lovelace::editor::card::tile::content_layout_options::vertical%]"
}
},
"data": {
"entity": "[%key:ui::panel::lovelace::editor::card::generic::entity%]",
"name": "[%key:ui::panel::lovelace::editor::card::generic::name%]",
"icon": "[%key:ui::panel::lovelace::editor::card::generic::icon%]",
"color": "[%key:ui::panel::lovelace::editor::card::tile::color%]",
"show_entity_picture": "[%key:ui::panel::lovelace::editor::card::tile::show_entity_picture%]",
"hide_state": "[%key:ui::panel::lovelace::editor::card::tile::hide_state%]",
"state_content": "[%key:ui::panel::lovelace::editor::card::tile::state_content%]",
"time_format": "[%key:ui::panel::lovelace::editor::card::generic::time_format%]",
"content_layout": "[%key:ui::panel::lovelace::editor::card::tile::content_layout%]",
"tap_action": "[%key:ui::panel::lovelace::editor::card::generic::tap_action%]",
"icon_tap_action": "[%key:ui::panel::lovelace::editor::card::tile::icon_tap_action%]",
"hold_action": "[%key:ui::panel::lovelace::editor::card::generic::hold_action%]",
"icon_hold_action": "[%key:ui::panel::lovelace::editor::card::tile::icon_hold_action%]",
"double_tap_action": "[%key:ui::panel::lovelace::editor::card::generic::double_tap_action%]",
"icon_double_tap_action": "[%key:ui::panel::lovelace::editor::card::tile::icon_double_tap_action%]",
"features_position": "[%key:ui::panel::lovelace::editor::card::tile::features_position%]"
},
"data_description": {
"color": "[%key:ui::panel::lovelace::editor::card::tile::color_helper%]",
"features_position": "[%key:ui::panel::lovelace::editor::card::tile::features_position_helper_vertical%]"
},
"selector": {
"content_layout": {
"options": {
"horizontal": "[%key:ui::panel::lovelace::editor::card::tile::content_layout_options::horizontal%]",
"vertical": "[%key:ui::panel::lovelace::editor::card::tile::content_layout_options::vertical%]"
}
"features_position": {
"options": {
"bottom": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::bottom%]",
"inline": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::inline%]"
},
"features_position": {
"options": {
"bottom": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::bottom%]",
"inline": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::inline%]"
},
"options_description": {
"bottom": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::bottom_description%]",
"inline": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::inline_description%]"
}
"options_description": {
"bottom": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::bottom_description%]",
"inline": "[%key:ui::panel::lovelace::editor::card::tile::features_position_options::inline_description%]"
}
}
}
@@ -95,6 +95,7 @@ export const mockArea = (
created_at: 0,
modified_at: 0,
humidity_entity_id: null,
occupancy_entity_id: null,
temperature_entity_id: null,
icon: null,
labels: [],
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { getEntityContext } from "../../../../src/common/entity/context/get_entity_context";
import {
getEntityAreaId,
getEntityContext,
} from "../../../../src/common/entity/context/get_entity_context";
import type { HomeAssistant } from "../../../../src/types";
import {
mockArea,
@@ -262,3 +265,61 @@ describe("getEntityContext", () => {
});
});
});
describe("getEntityAreaId", () => {
const devices = {
device_1: mockDevice({ id: "device_1", area_id: "living_room" }),
device_2: mockDevice({
id: "device_2",
area_id: null,
parent_device_id: "device_1",
}),
} as unknown as HomeAssistant["devices"];
it("prefers the entity's own area over its device's area", () => {
const entities = {
"binary_sensor.motion": mockEntity({
entity_id: "binary_sensor.motion",
device_id: "device_1",
area_id: "bedroom",
}),
} as unknown as HomeAssistant["entities"];
expect(getEntityAreaId("binary_sensor.motion", entities, devices)).toBe(
"bedroom"
);
});
it("falls back to the device's area, then its parent device's", () => {
const entities = {
"binary_sensor.motion": mockEntity({
entity_id: "binary_sensor.motion",
device_id: "device_1",
}),
"binary_sensor.child": mockEntity({
entity_id: "binary_sensor.child",
device_id: "device_2",
}),
} as unknown as HomeAssistant["entities"];
expect(getEntityAreaId("binary_sensor.motion", entities, devices)).toBe(
"living_room"
);
expect(getEntityAreaId("binary_sensor.child", entities, devices)).toBe(
"living_room"
);
});
it("returns undefined for an unknown entity or one without an area", () => {
const entities = {
"binary_sensor.motion": mockEntity({ entity_id: "binary_sensor.motion" }),
} as unknown as HomeAssistant["entities"];
expect(getEntityAreaId("binary_sensor.missing", entities, devices)).toBe(
undefined
);
expect(getEntityAreaId("binary_sensor.motion", entities, devices)).toBe(
undefined
);
});
});
+82
View File
@@ -0,0 +1,82 @@
import { describe, expect, it } from "vitest";
import type { Action } from "../../src/data/script";
import { describeAction } from "../../src/data/script_i18n";
import type { AutomationTraceExtended } from "../../src/data/trace";
import { buildTraceLabels } from "../../src/data/trace-labels";
import type { HomeAssistant } from "../../src/types";
const DESCRIPTION_KEY =
"ui.panel.config.automation.editor.actions.type.service.description";
const TRANSLATIONS: Record<string, string> = {
"component.light.title": "Light",
"component.light.services.turn_on.name": "Turn on",
};
/** Echoes the key for UI strings, so assertions skip English copy. */
const hass = {
localize: (key: string, params?: Record<string, unknown>) => {
if (key.startsWith("component.")) {
return TRANSLATIONS[key] ?? "";
}
return params ? `${key}(${Object.values(params).join("|")})` : key;
},
locale: { language: "en" },
states: {},
services: { light: { turn_on: {} } },
entities: {},
config: {},
} as unknown as HomeAssistant;
// A trace holds the config as it was written, so a service call can use
// either the `action` key or the legacy `service` key.
describe.each(["action", "service"])(
"describing a service call written with `%s`",
(key) => {
const serviceCall = (service: string) => ({ [key]: service }) as Action;
it("names a known action", () => {
expect(describeAction(hass, [], serviceCall("light.turn_on"))).toBe(
"Light: Turn on"
);
});
it("falls back to the ID of an unknown action", () => {
expect(describeAction(hass, [], serviceCall("light.unknown"))).toBe(
"light.unknown"
);
});
it("says a templated action is templated", () => {
expect(
describeAction(hass, [], serviceCall("light.turn_{{ 'on' }}"))
).toBe(`${DESCRIPTION_KEY}.service_based_on_template_no_targets()`);
});
it("labels the step of a trace", () => {
const timestamp = "2026-09-17T00:00:00Z";
const trace = {
domain: "automation",
item_id: "test",
run_id: "test",
state: "stopped",
script_execution: "finished",
last_step: null,
timestamp: { start: timestamp, finish: timestamp },
context: { id: "test", user_id: null },
trigger: "manual",
config: {
alias: "Test",
triggers: [],
conditions: [],
actions: [serviceCall("light.turn_on")],
},
trace: { "action/0": [{ path: "action/0", timestamp }] },
} as unknown as AutomationTraceExtended;
expect(buildTraceLabels(trace, hass, undefined)["action/0"]).toContain(
"Light: Turn on"
);
});
}
);
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, it } from "vitest";
import type { ScriptConfig } from "../../src/data/script";
import { normalizeScriptConfig } from "../../src/data/script";
describe("normalizeScriptConfig", () => {
it("renames a legacy service key", () => {
const config = normalizeScriptConfig({
alias: "Hall",
sequence: [
{ service: "light.turn_on", target: { entity_id: "light.hall" } },
],
} as any);
expect(config.sequence).toEqual([
{ action: "light.turn_on", target: { entity_id: "light.hall" } },
]);
});
it("wraps a single action in a list", () => {
const config = normalizeScriptConfig({
alias: "Hall",
sequence: { service: "light.turn_on" },
} as any);
expect(config.sequence).toEqual([{ action: "light.turn_on" }]);
});
it("renames legacy service keys in nested actions", () => {
const config = normalizeScriptConfig({
alias: "Hall",
sequence: [
{
if: [{ condition: "state", entity_id: "light.hall", state: "on" }],
then: [{ service: "light.turn_off" }],
else: [{ service: "light.turn_on" }],
},
{
choose: [{ conditions: [], sequence: [{ service: "light.toggle" }] }],
default: [{ service: "scene.turn_on" }],
},
{ repeat: { count: 2, sequence: [{ service: "light.toggle" }] } },
{ parallel: [{ sequence: [{ service: "light.toggle" }] }] },
],
} as any);
expect(config.sequence).toEqual([
{
if: [{ condition: "state", entity_id: "light.hall", state: "on" }],
then: [{ action: "light.turn_off" }],
else: [{ action: "light.turn_on" }],
},
{
choose: [{ conditions: [], sequence: [{ action: "light.toggle" }] }],
default: [{ action: "scene.turn_on" }],
},
{ repeat: { count: 2, sequence: [{ action: "light.toggle" }] } },
{ parallel: [{ sequence: [{ action: "light.toggle" }] }] },
]);
});
it("keeps action when both action and service are set", () => {
const config = normalizeScriptConfig({
alias: "Hall",
sequence: [{ action: "light.turn_on", service: "light.turn_off" }],
} as any);
expect(config.sequence).toEqual([{ action: "light.turn_on" }]);
});
it("leaves an up-to-date config as it is", () => {
const config: ScriptConfig = {
alias: "Hall",
sequence: [
{
action: "light.turn_on",
target: { entity_id: "light.hall" },
data: { brightness: 255 },
},
{ if: [], then: [{ action: "light.turn_off" }] },
],
mode: "single",
};
const expected = structuredClone(config);
const normalized = normalizeScriptConfig(config);
expect(normalized).toEqual(expected);
expect(Object.keys(normalized)).toEqual(Object.keys(expected));
expect(Object.keys(normalized.sequence[0])).toEqual(
Object.keys(expected.sequence[0])
);
});
it("accepts a config without a sequence", () => {
const config = { use_blueprint: { path: "confirmable.yaml" } };
expect(normalizeScriptConfig(config)).toEqual({
use_blueprint: { path: "confirmable.yaml" },
});
});
});
+28 -1
View File
@@ -1,5 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { checkForEntityUpdates } from "../../src/data/update";
import {
checkForEntityUpdates,
countInstallableUpdates,
UpdateEntityFeature,
} from "../../src/data/update";
import { showAlertDialog } from "../../src/dialogs/generic/show-dialog-box";
import type { HomeAssistant } from "../../src/types";
import { createMockEntityState, createMockHass } from "../fixtures/hass";
@@ -52,3 +56,26 @@ describe("checkForEntityUpdates", () => {
}
);
});
describe("countInstallableUpdates", () => {
it("counts installable update entities and skips hidden ones when registry is provided", () => {
const states = {
"update.installable": createMockEntityState("update.installable", "on", {
supported_features: UpdateEntityFeature.INSTALL,
}),
"update.hidden": createMockEntityState("update.hidden", "on", {
supported_features: UpdateEntityFeature.INSTALL,
}),
"update.up_to_date": createMockEntityState("update.up_to_date", "off", {
supported_features: UpdateEntityFeature.INSTALL,
}),
"sensor.other": createMockEntityState("sensor.other", "on"),
};
const entities = {
"update.hidden": { entity_id: "update.hidden", hidden: true, labels: [] },
} as unknown as HomeAssistant["entities"];
expect(countInstallableUpdates(states)).toBe(2);
expect(countInstallableUpdates(states, entities)).toBe(1);
});
});
@@ -0,0 +1,87 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { navigate } from "../../../../src/common/navigate";
import type * as NavigateModule from "../../../../src/common/navigate";
import type { AutomationConfig } from "../../../../src/data/automation";
import { getAutomationEditorInitData } from "../../../../src/data/automation";
import "../../../../src/panels/config/automation/ha-automation-picker";
import { createMockHass } from "../../../fixtures/hass";
vi.mock("../../../../src/common/navigate", async (importOriginal) => {
const actual = await importOriginal<typeof NavigateModule>();
return {
...actual,
navigate: vi.fn(),
};
});
const AUTOMATION_CONFIG: AutomationConfig = {
id: "1700000000000",
alias: "Morning routine",
description: "Starts the day",
mode: "queued",
max: 3,
triggers: [{ trigger: "time", at: "07:00:00" }],
conditions: [],
actions: [{ action: "light.turn_on", target: { entity_id: "light.bed" } }],
};
const duplicate = async (fileConfig: AutomationConfig | undefined) => {
const el = document.createElement("ha-automation-picker") as any;
const hass = createMockHass();
// The REST API only knows the automations in automations.yaml, an
// automation from elsewhere in the YAML configuration gives a 404.
(hass as any).callApi = vi.fn(async () => {
if (!fileConfig) {
throw { status_code: 404 };
}
return fileConfig;
});
(hass as any).callWS = vi.fn(async () => ({ config: AUTOMATION_CONFIG }));
el.hass = hass;
await el._duplicate({
entity_id: "automation.morning_routine",
attributes: { id: "1700000000000" },
});
return hass;
};
describe("automation picker duplicate", () => {
beforeEach(() => {
vi.mocked(navigate).mockClear();
getAutomationEditorInitData();
});
test("clears the id and alias of an automation from automations.yaml", async () => {
const hass = await duplicate(AUTOMATION_CONFIG);
expect(hass.callApi).toHaveBeenCalledWith(
"GET",
"config/automation/config/1700000000000"
);
expect(hass.callWS).not.toHaveBeenCalled();
expect(navigate).toHaveBeenCalledWith("/config/automation/edit/new");
expect(getAutomationEditorInitData()).toEqual({
...AUTOMATION_CONFIG,
id: undefined,
alias: undefined,
});
});
test("clears the id and alias of a YAML-only automation", async () => {
const hass = await duplicate(undefined);
expect(hass.callWS).toHaveBeenCalledWith({
type: "automation/config",
entity_id: "automation.morning_routine",
});
expect(navigate).toHaveBeenCalledWith("/config/automation/edit/new");
expect(getAutomationEditorInitData()).toEqual({
...AUTOMATION_CONFIG,
id: undefined,
alias: undefined,
});
});
});
@@ -105,4 +105,46 @@ describe("YAML editor dirty state", () => {
editYaml(el, { ...yaml, sequence: [reorderAction(yaml.sequence[0])] });
expect(el.isDirtyState).toBe(true);
});
// ha-yaml-editor reports comment-only YAML as undefined and `~` as null
test.each([
{
name: "automation editor, comment-only YAML",
tag: "ha-automation-editor" as const,
config: AUTOMATION,
value: undefined,
expected: { id: "kitchen" },
},
{
name: "automation editor, null YAML",
tag: "ha-automation-editor" as const,
config: AUTOMATION,
value: null,
expected: { id: "kitchen" },
},
{
name: "script editor, comment-only YAML",
tag: "ha-script-editor" as const,
config: SCRIPT,
value: undefined,
expected: {},
},
{
name: "script editor, null YAML",
tag: "ha-script-editor" as const,
config: SCRIPT,
value: null,
expected: {},
},
])(
"$name becomes an empty config",
async ({ tag, config, value, expected }) => {
const el = await loadEditor(tag, config);
expect(() => editYaml(el, value)).not.toThrow();
expect((el as any).config).toEqual(expected);
expect(el.isDirtyState).toBe(true);
}
);
});
@@ -0,0 +1,132 @@
import { describe, expect, test, vi } from "vitest";
import type * as NavigateModule from "../../../../src/common/navigate";
import type { ScriptConfig } from "../../../../src/data/script";
import { showScriptEditor } from "../../../../src/data/script";
import "../../../../src/panels/config/script/ha-script-editor";
import type { HaScriptEditor } from "../../../../src/panels/config/script/ha-script-editor";
import { createMockHass } from "../../../fixtures/hass";
vi.mock("../../../../src/common/navigate", async (importOriginal) => {
const actual = await importOriginal<typeof NavigateModule>();
return {
...actual,
navigate: vi.fn(),
};
});
const LEGACY_SEQUENCE = [
{ service: "light.turn_on", target: { entity_id: "light.hall" } },
{
if: [{ condition: "state", entity_id: "light.hall", state: "on" }],
then: [{ service: "light.turn_off" }],
},
];
const MIGRATED_SEQUENCE = [
{ action: "light.turn_on", target: { entity_id: "light.hall" } },
{
if: [{ condition: "state", entity_id: "light.hall", state: "on" }],
then: [{ action: "light.turn_off" }],
},
];
const createEditor = (): HaScriptEditor => {
const el = document.createElement("ha-script-editor") as HaScriptEditor;
el.hass = createMockHass();
return el;
};
// Opens the editor for a new script, like navigating to /config/script/edit/new
const openNewScript = (initData?: Parameters<typeof showScriptEditor>[0]) => {
const el = createEditor();
showScriptEditor(initData);
(el as any).updated(new Map([["scriptId", "previous"]]));
return el;
};
const editYaml = (el: HaScriptEditor, value: unknown) =>
(el as any)._yamlChanged({
stopPropagation: () => undefined,
detail: { isValid: true, value },
});
const getConfig = (el: HaScriptEditor): ScriptConfig => (el as any).config;
describe("script editor config normalization", () => {
test.each([
{
name: "legacy service keys",
sequence: structuredClone(LEGACY_SEQUENCE),
expected: MIGRATED_SEQUENCE,
},
{
name: "a single action instead of a list",
sequence: { service: "light.turn_on" },
expected: [{ action: "light.turn_on" }],
},
{
name: "an up-to-date config",
sequence: structuredClone(MIGRATED_SEQUENCE),
expected: MIGRATED_SEQUENCE,
},
])("YAML editor normalizes $name", ({ sequence, expected }) => {
const el = openNewScript();
editYaml(el, { alias: "Hall", sequence, mode: "single" });
expect(getConfig(el)).toEqual({
alias: "Hall",
sequence: expected,
mode: "single",
});
expect(Object.keys(getConfig(el))).toEqual(["alias", "sequence", "mode"]);
});
test.each([
{
name: "legacy service keys",
sequence: structuredClone(LEGACY_SEQUENCE),
expected: MIGRATED_SEQUENCE,
},
{
name: "a single action instead of a list",
sequence: { service: "light.turn_on" },
expected: [{ action: "light.turn_on" }],
},
{
name: "an up-to-date config",
sequence: structuredClone(MIGRATED_SEQUENCE),
expected: MIGRATED_SEQUENCE,
},
])("new script init data normalizes $name", ({ sequence, expected }) => {
const el = openNewScript({
alias: "Hall",
sequence,
mode: "single",
} as any);
expect(getConfig(el)).toEqual({
alias: "Hall",
sequence: expected,
mode: "single",
});
expect(Object.keys(getConfig(el))).toEqual(["alias", "sequence", "mode"]);
expect(el.isDirtyState).toBe(true);
});
test("new script without init data starts with an empty sequence", () => {
const el = openNewScript();
expect(getConfig(el)).toEqual({ sequence: [] });
expect(el.isDirtyState).toBe(false);
});
test("new script from a blueprint gets no sequence", () => {
const el = openNewScript({ use_blueprint: { path: "confirmable.yaml" } });
expect(getConfig(el)).toEqual({
use_blueprint: { path: "confirmable.yaml" },
});
});
});
@@ -0,0 +1,83 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { navigate } from "../../../../src/common/navigate";
import type * as NavigateModule from "../../../../src/common/navigate";
import type { ScriptConfig } from "../../../../src/data/script";
import { getScriptEditorInitData } from "../../../../src/data/script";
import "../../../../src/panels/config/script/ha-script-picker";
import { createMockHass } from "../../../fixtures/hass";
vi.mock("../../../../src/common/navigate", async (importOriginal) => {
const actual = await importOriginal<typeof NavigateModule>();
return {
...actual,
navigate: vi.fn(),
};
});
const SCRIPT_CONFIG: ScriptConfig = {
alias: "Morning routine",
description: "Starts the day",
icon: "mdi:weather-sunset-up",
mode: "queued",
max: 3,
sequence: [{ action: "light.turn_on", target: { entity_id: "light.bed" } }],
};
const duplicate = async (fileConfig: ScriptConfig | undefined) => {
const el = document.createElement("ha-script-picker") as any;
const hass = createMockHass();
// The REST API only knows the scripts in scripts.yaml, a script from
// elsewhere in the YAML configuration gives a 404.
(hass as any).callApi = vi.fn(async () => {
if (!fileConfig) {
throw { status_code: 404 };
}
return fileConfig;
});
(hass as any).callWS = vi.fn(async () => ({ config: SCRIPT_CONFIG }));
el.hass = hass;
el._entityReg = [
{ entity_id: "script.morning_routine", unique_id: "morning_routine" },
];
await el._duplicate({ entity_id: "script.morning_routine" });
return hass;
};
describe("script picker duplicate", () => {
beforeEach(() => {
vi.mocked(navigate).mockClear();
getScriptEditorInitData();
});
test("clears the alias of a script from scripts.yaml", async () => {
const hass = await duplicate(SCRIPT_CONFIG);
expect(hass.callApi).toHaveBeenCalledWith(
"GET",
"config/script/config/morning_routine"
);
expect(hass.callWS).not.toHaveBeenCalled();
expect(navigate).toHaveBeenCalledWith("/config/script/edit/new");
expect(getScriptEditorInitData()).toEqual({
...SCRIPT_CONFIG,
alias: undefined,
});
});
test("clears the alias of a YAML-only script", async () => {
const hass = await duplicate(undefined);
expect(hass.callWS).toHaveBeenCalledWith({
type: "script/config",
entity_id: "script.morning_routine",
});
expect(navigate).toHaveBeenCalledWith("/config/script/edit/new");
expect(getScriptEditorInitData()).toEqual({
...SCRIPT_CONFIG,
alias: undefined,
});
});
});
@@ -81,6 +81,7 @@ const area = (id: string, overrides: Record<string, unknown> = {}) =>
picture: null,
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
...overrides,
+49
View File
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { connectionMixin } from "../../src/state/connection-mixin";
import { HassBaseEl } from "../../src/state/hass-base-mixin";
import type { HomeAssistant } from "../../src/types";
vi.mock("../../src/util/brands-url", async (importOriginal) => ({
...(await importOriginal<object>()),
clearBrandsTokenRefresh: vi.fn(),
fetchAndScheduleBrandsAccessToken: vi.fn(() => Promise.resolve(false)),
}));
class ConnectionElement extends connectionMixin(HassBaseEl) {
public reconnect() {
this.hassDisconnected();
this.hassReconnected();
}
}
customElements.define("test-connection-element", ConnectionElement);
declare global {
interface HTMLElementTagNameMap {
"test-connection-element": ConnectionElement;
}
}
describe("connection mixin backend ping", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("pings the backend again after a reconnect", () => {
const ping = vi.fn(() => Promise.resolve());
const element = new ConnectionElement();
element.hass = {
connected: true,
connection: { ping },
callWS: vi.fn(() => Promise.resolve({})),
} as unknown as HomeAssistant;
element.reconnect();
vi.advanceTimersByTime(30000);
expect(ping).toHaveBeenCalledTimes(1);
});
});