Compare commits

..
Author SHA1 Message Date
Wendelin 98e3bd5f80 Merge branch 'dev' of github.com:home-assistant/frontend into automation-editor-path-undo
# Conflicts:
#	src/panels/config/automation/trigger/ha-automation-trigger-row.ts
2026-11-06 11:23:28 +01:00
Wendelin 9bcdaecb77 feat: enhance automation editor with path management and undo/redo support
- Introduced AutomationPathController to manage paths in automation configurations.
- Updated ha-automation-sortable-list-mixin to include pathKey property for better path handling.
- Enhanced ManualEditorMixin to track sidebar row changes and manage undo/redo operations.
- Integrated pathKey attributes in automation trigger, condition, and action components for improved path tracking.
- Implemented ConfigChangeUndoRedoController to manage undo/redo functionality for script and automation configurations.
- Added tests for config change utilities and automation path management to ensure reliability and correctness.
2026-10-29 14:21:30 +01:00
353 changed files with 9597 additions and 16298 deletions

No files matched your search

+3 -4
View File
@@ -35,12 +35,11 @@ runs:
NETLIFY_AUTH_TOKEN: ${{ inputs.auth-token }}
NETLIFY_SITE_ID: ${{ inputs.site-id }}
run: |
# Execute the deployment (--filter picks the root workspace project,
# --no-build because we deploy an already built directory)
# Execute the deployment
if [ -n "$ALIAS" ]; then
npx -y netlify-cli deploy --filter home-assistant-frontend --no-build --dir="$DIR" --alias "$ALIAS" --json > deploy_output.json
npx -y netlify-cli deploy --dir="$DIR" --alias "$ALIAS" --json > deploy_output.json
else
npx -y netlify-cli deploy --filter home-assistant-frontend --no-build --dir="$DIR" --prod --json > deploy_output.json
npx -y netlify-cli deploy --dir="$DIR" --prod --json > deploy_output.json
fi
# Collect the urls from the deployment output
@@ -16,7 +16,6 @@ runs:
with:
path: |
node_modules
packages/*/node_modules
~/.local/share/pnpm/store
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
@@ -36,7 +35,6 @@ runs:
with:
path: |
node_modules
packages/*/node_modules
~/.local/share/pnpm/store
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
-1
View File
@@ -28,7 +28,6 @@ runs:
with:
path: |
node_modules
packages/*/node_modules
~/.local/share/pnpm/store
key: >-
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
+4 -4
View File
@@ -38,7 +38,7 @@ jobs:
name: Prepare container dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
defaults:
run:
@@ -155,7 +155,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001 --ipc=host
defaults:
run:
@@ -207,7 +207,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001 --ipc=host
defaults:
run:
@@ -261,7 +261,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001 --ipc=host
defaults:
run:
-8
View File
@@ -28,18 +28,10 @@ AI can be a helpful tool for writing code and documentation. However, due to the
All contributions must be reviewed and understood by the contributor before submission. You should be able to explain every change in a pull request you submit. Pull requests that appear to be unreviewed AI output will be closed without review.
## Design contributions
AI can be a helpful tool to explore ideas and build mockups and prototypes. But AI tends to give the most common answer, not the one that fits Home Assistant and its users. So we require a human who brings the point of view and owns the design decisions.
You should be able to explain the problem your design solves and why you made your choices. If a mockup or prototype was mostly generated with AI, say so when you share it. Check your work against the [design guidelines](https://contributors.home-assistant.io/design/), as AI tools often make up components, colors, or spacing that don't exist in Home Assistant. Design proposals that look like unreviewed AI output may be closed or hidden.
## Our use of AI
Some of our projects use AI tools to assist with code reviews, issue triaging, reporting, and other project management tasks. These tools may leave comments on pull requests or issues. As with any automated tooling, these comments are not always correct.
We also use AI to help keep the design system, the Figma kit, and the code in sync. The design decisions behind them are made by people.
If an AI tool leaves a comment on your contribution, treat it as you would any other review comment. If you believe it is incorrect, say so; a brief explanation is sufficient. Maintainers always have the final say. If in doubt, ask a maintainer.
## Enforcement
@@ -1,3 +1,4 @@
/* global module, require */
// rspack/webpack loader that minifies the HTML, SVG, and CSS inside lit
// tagged template literals using `minify-literals` (html-minifier-next +
// lightningcss). Replaces the unmaintained babel-plugin-template-html-minifier.
@@ -35,14 +36,6 @@ const initLoader = (browserslistEnv) => {
return {
minifyHTMLLiterals: minifyModule.minifyHTMLLiterals,
lightningcssTargets,
// With the legacy floor at Chrome 67, lightningcss rewrites rgba()
// to 8-digit hex (#rrggbbaa). Some kiosk webviews served the legacy
// build (e.g. Shelly Wall Display) can't parse that, so any
// var(--divider-color) border falls back to currentColor. Always
// compile hex alpha colors to rgba() in legacy builds.
lightningcssInclude: browserslistEnv.startsWith("legacy")
? lightningcssModule.Features.HexAlphaColors
: 0,
};
})
);
@@ -74,13 +67,12 @@ module.exports = function minifyTemplateLiteralsLoader(source, map, meta) {
const { browserslistEnv } = this.getOptions();
initLoader(browserslistEnv)
.then(({ minifyHTMLLiterals, lightningcssTargets, lightningcssInclude }) =>
.then(({ minifyHTMLLiterals, lightningcssTargets }) =>
minifyHTMLLiterals(source, {
fileName: this.resourcePath,
html: htmlOptions,
css: {
targets: lightningcssTargets,
include: lightningcssInclude,
},
})
)
-38
View File
@@ -68,42 +68,8 @@ const CONFIG_FILES = [
path.join(__dirname, "lit-disable-dev-mode-loader.cjs"),
path.join(__dirname, "babel-plugins", "custom-polyfill-plugin.js"),
path.join(__dirname, "babel-plugins", "inline-constants-plugin.cjs"),
// Its exports define the components source aliases below
path.join(__dirname, "..", "packages", "components", "package.json"),
];
// Resolve @home-assistant/components entry points to their sources, so the package
// needs no build step during development. The entry points are read from the
// "ha-source" export condition of the package; subpath patterns are expanded
// for every element, i.e. every directory with a global.ts, like "card".
const COMPONENTS_PACKAGE_DIR = path.join(
paths.root_dir,
"packages",
"components"
);
const COMPONENTS_SRC_DIR = path.join(
COMPONENTS_PACKAGE_DIR,
"src",
"components"
);
const componentElements = fs
.readdirSync(COMPONENTS_SRC_DIR, { recursive: true })
.filter((file) => path.basename(file) === "global.ts")
.map((file) => path.dirname(file).split(path.sep).join("/"));
const componentsSourceAliases = Object.fromEntries(
Object.entries(require("../packages/components/package.json").exports)
.filter(([, target]) => target["ha-source"])
.flatMap(([subpath, target]) =>
(subpath.includes("*") ? componentElements : [undefined]).map((name) => [
`${path.posix.join("@home-assistant/components", name ? subpath.replaceAll("*", name) : subpath)}$`,
path.join(
COMPONENTS_PACKAGE_DIR,
name ? target["ha-source"].replaceAll("*", name) : target["ha-source"]
),
])
)
);
// Patches change a package's files but not its version, which is all the
// node_modules snapshot checks, so their contents go into the version too.
const PATCHES_DIR = path.join(paths.root_dir, "patches");
@@ -278,9 +244,6 @@ const createRspackConfig = ({
path: paths.root_dir,
env: "legacy",
}),
// Keep rgba() instead of #rrggbbaa, see
// minify-template-literals-loader.cjs
include: { hexAlphaColors: true },
},
},
],
@@ -465,7 +428,6 @@ const createRspackConfig = ({
"src/resources/polyfills/bigdecimal.ts"
),
}),
...componentsSourceAliases,
"lit/static-html$": "lit/static-html.js",
"lit/decorators$": "lit/decorators.js",
"lit/directive$": "lit/directive.js",
-1
View File
@@ -3,7 +3,6 @@
<head>
<title>Home Assistant Cast - FAQ</title>
<link rel="icon" href="/images/ha-cast-icon.png" type="image/png" />
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
body {
-1
View File
@@ -4,7 +4,6 @@
<title>Home Assistant Cast</title>
<link rel="manifest" href="/manifest.json" />
<link rel="icon" href="/images/ha-cast-icon.png" type="image/png" />
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
body {
-1
View File
@@ -4,7 +4,6 @@
<% for (const entry of latestEntryJS) { %>
<script type="module" src="<%= entry %>"></script>
<% } %>
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
body {
+90 -3
View File
@@ -35,12 +35,13 @@
/>
<meta name="theme-color" content="#03a9f4" />
<%= renderTemplate("_social_meta.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
html {
background-color: var(--primary-background-color, #fafafa);
color: var(--primary-text-color, #212121);
height: 100vh;
/* Prevent iOS Safari from inflating text when rotating to landscape */
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
@media (prefers-color-scheme: dark) {
html {
@@ -48,8 +49,94 @@
color: var(--primary-text-color, #e1e1e1);
}
}
body {
font-family: Roboto, Noto, sans-serif;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-weight: 400;
height: 100vh;
margin: 0;
padding: 0;
}
#ha-launch-screen {
font-family: ui-sans-serif, system-ui, sans-serif;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
user-select: none;
-webkit-user-select: none;
transition: opacity var(--ha-animation-duration-normal, 250ms) ease-out;
}
#ha-launch-screen.removing {
opacity: 0;
}
@keyframes launch-lockup-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#ha-launch-screen .ha-lockup {
display: flex;
align-items: center;
flex-shrink: 0;
animation: launch-lockup-in var(--ha-animation-duration-normal, 250ms) ease-out both;
}
#ha-launch-screen-info-box > *,
#ha-launch-screen .ohf-logo {
animation: launch-lockup-in var(--ha-animation-duration-normal, 250ms) ease-out both;
}
#ha-launch-screen .ha-logo {
width: 96px;
height: 96px;
}
#ha-launch-screen .ha-launch-screen-spacer-top {
flex: 1;
margin-top: calc( 2 * max(var(--safe-area-inset-top, 0px), 48px) + 46px );
padding-top: 48px;
}
#ha-launch-screen .ha-launch-screen-spacer-bottom {
flex: 1;
padding-top: 16px;
}
.ohf-logo {
margin: max(var(--safe-area-inset-bottom, 0px), 48px) 0;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
opacity: .66;
}
.ohf-logo span {
font-size: 12px;
line-height: 12px;
text-transform: uppercase;
}
.ohf-logo picture {
display: flex;
}
.ohf-logo img {
width: 237px;
aspect-ratio: 237 / 24;
height: auto;
}
@media (max-height: 560px) {
#ha-launch-screen .ha-launch-screen-spacer-top {
margin-top: 24px;
padding-top: 24px;
}
#ha-launch-screen .ha-launch-screen-spacer-bottom {
padding-top: 16px;
}
.ohf-logo {
margin-block: 24px;
}
}
</style>
<%= renderTemplate("../../../src/html/_style_launch_screen.html.template") %>
</head>
<body>
<div id="ha-launch-screen">
@@ -44,21 +44,14 @@ export const lorawanFixtures: ConnectivityFixtures = {
],
commands: ["lorawan/"],
manifests: [
manifest("lorawan", "LoRaWAN", {
config_flow: false,
integration_type: "service",
}),
manifest("lorawan", "LoRaWAN", { integration_type: "helper" }),
manifest("sensecap_lorawan", "SenseCAP", {
integration_type: "device",
dependencies: ["lorawan"],
}),
manifest("chirpstack", "ChirpStack", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
manifest("chirpstack", "ChirpStack", { integration_type: "hub" }),
manifest("thethingsnetwork_lorawan", "The Things Network", {
integration_type: "hub",
dependencies: ["lorawan"],
}),
],
configEntries: [
@@ -10,26 +10,19 @@ export const FRONIUS_ENTRY_ID = "mock-fronius";
export const RS485_PORT = "/dev/ttyUSB1";
export const modbusFixtures: ConnectivityFixtures = {
components: ["modbus", "flexit", "solaredge_modbus", "fronius"],
components: ["modbus"],
commands: ["modbus/"],
manifests: [
manifest("modbus", "Modbus", {
config_flow: false,
iot_class: "local_polling",
}),
manifest("flexit", "Flexit", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("solaredge_modbus", "SolarEdge Modbus", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
manifest("fronius", "Fronius", {
integration_type: "device",
dependencies: ["modbus"],
iot_class: "local_polling",
}),
],
-8
View File
@@ -301,14 +301,6 @@ export default tseslint.config(
globals: globals.node,
},
},
{
// Published as native ESM, where package subpath imports such as
// "lit/decorators.js" need their extension.
files: ["packages/*/src/**/*.ts"],
rules: {
"import-x/extensions": ["error", "ignorePackages", { ts: "never" }],
},
},
{
plugins: {
html,
+1
View File
@@ -25,6 +25,7 @@ class DemoMoreInfo extends LitElement {
!computeShowNewMoreInfo(state)
? html`<state-card-content
.stateObj=${state}
.hass=${this.hass}
in-dialog
></state-card-content>`
: nothing
@@ -165,18 +165,6 @@ Interactive row. Renders an inner `<a>` when `href` is set, otherwise a
roving tabindex, the host is the tab stop and the inner element carries
`tabindex="-1"`.
Only the headline and supporting text are inside the `<a>` or `<button>`; its
hit area is stretched over the whole row. The `start` and `end` slots sit next
to it, so controls placed there, like an `ha-icon-button` or `ha-dropdown`,
stay separate controls for screen readers. Slotted elements are raised above
the hit area so they can be clicked, except icons, badges, `span`s and empty
`div`s (dividers), which let clicks and hover through to the row. A focusable
element (with `tabindex`) is always raised. To keep another element clickable
on its own, like a drag handle, give it `z-index: 1` in the consumer's styles.
Subclasses customize the row by overriding `_renderStart()`,
`_renderContent()` and `_renderEnd()`. `_renderInner()` is not used.
**Attributes**
- `href` (String) — when set, renders an `<a>` instead of a `<button>`.
@@ -186,7 +174,6 @@ Subclasses customize the row by overriding `_renderStart()`,
**CSS parts**
- `control` — the inner `<a>` or `<button>`.
- `ripple` — the ripple effect element.
### `<ha-list-item-option>`
-66
View File
@@ -2,12 +2,10 @@ import {
mdiAccount,
mdiChevronRight,
mdiCog,
mdiDelete,
mdiHome,
mdiInformationOutline,
mdiMapMarker,
mdiOpenInNew,
mdiPencil,
mdiViewDashboard,
mdiWifi,
} from "@mdi/js";
@@ -15,8 +13,6 @@ import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, state } from "lit/decorators";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-icon-button";
import "../../../../src/components/ha-icon-next";
import "../../../../src/components/ha-svg-icon";
import "../../../../src/components/item/ha-list-item-base";
import "../../../../src/components/item/ha-list-item-button";
@@ -81,8 +77,6 @@ const treeKey = (group: TreeGroup, child: TreeChild) =>
export class DemoHaList extends LitElement {
@state() private _buttonClicks = 0;
@state() private _lastAction = "none";
@state() private _single: number | Set<number> = -1;
@state() private _multiLine: number | Set<number> = new Set();
@@ -226,51 +220,6 @@ export class DemoHaList extends LitElement {
</ha-list-base>
</ha-card>
<ha-card header="Row with actions in the end slot">
<p class="card-text">
Last action: <code>${this._lastAction}</code>. The action buttons are
separate controls; icons and the divider activate the row.
</p>
<ha-list-base aria-label="Rows with actions">
<ha-list-item-button data-action="row" @click=${this._onActionClick}>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
<span slot="headline">Button row</span>
<span slot="supporting-text">Click the row or an action</span>
<ha-icon-next slot="end"></ha-icon-next>
<div slot="end" class="vertical-divider"></div>
<ha-icon-button
slot="end"
data-action="edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-button
slot="end"
data-action="delete"
.path=${mdiDelete}
label="Delete"
@click=${this._onActionClick}
></ha-icon-button>
</ha-list-item-button>
<ha-list-item-button href="#components/ha-list">
<ha-svg-icon slot="start" .path=${mdiMapMarker}></ha-svg-icon>
<span slot="headline">Link row</span>
<span slot="supporting-text"
>Cmd/Ctrl-click on the icon or chevron opens a new tab</span
>
<ha-icon-button
slot="end"
data-action="link-edit"
.path=${mdiPencil}
label="Edit"
@click=${this._onActionClick}
></ha-icon-button>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
</ha-list-base>
</ha-card>
<h2>ha-list-selectable + ha-list-item-option</h2>
<p>
Selectable list (<code>role="listbox"</code>). Items must be
@@ -479,12 +428,6 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
return value instanceof Set ? [...value] : value;
}
private _onActionClick = (ev: MouseEvent) => {
ev.stopPropagation();
this._lastAction =
(ev.currentTarget as HTMLElement).dataset.action ?? "none";
};
private _onButtonClick = () => {
this._buttonClicks++;
};
@@ -599,15 +542,6 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
ha-card {
max-width: 560px;
}
.card-text {
margin: 0;
padding: 0 var(--ha-space-4) var(--ha-space-2);
}
.vertical-divider {
align-self: stretch;
width: 1px;
background: var(--divider-color);
}
pre {
padding: var(--ha-space-4);
background: var(--secondary-background-color);
@@ -3,7 +3,6 @@
<head>
<title>Home Assistant</title>
<%= renderTemplate("../../../src/html/_header.html.template") %>
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
html {
+19 -19
View File
@@ -13,7 +13,7 @@
"lint:prettier": "prettier . --cache --check",
"format:prettier": "prettier . --cache --write",
"lint:types": "node ./node_modules/@typescript/native/bin/tsc && node ./node_modules/@typescript/native/bin/tsc -p .github/scripts",
"lint:lit": "lit-analyzer \"{.,*,packages/*}/src/**/*.ts\"",
"lint:lit": "lit-analyzer \"{.,*}/src/**/*.ts\"",
"lint:element-imports": "eslint \"**/src/**/*.{js,ts,html}\" --ignore-pattern=.gitignore --rule '{\"ha/no-unused-element-import\": \"warn\"}'",
"lint:licenses": "node --no-deprecation script/check-licenses",
"lint": "pnpm run lint:eslint && pnpm run lint:prettier && pnpm run lint:types && pnpm run lint:lit",
@@ -73,22 +73,23 @@
"@lit/reactive-element": "2.1.2",
"@lit/task": "1.0.3",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@material/mwc-list": "0.27.0",
"@mdi/js": "7.4.47",
"@mdi/svg": "7.4.47",
"@replit/codemirror-indentation-markers": "6.5.3",
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.3",
"@tsparticles/preset-links": "4.5.3",
"@versatiles/style": "9.0.0",
"@swc/helpers": "0.5.23",
"@tsparticles/engine": "4.5.1",
"@tsparticles/preset-links": "4.5.1",
"@versatiles/style": "8.0.0",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.204.0",
"@vvo/tzdb": "6.202.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10",
"barcode-detector": "3.2.3",
"cally": "0.9.2",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
"cropperjs": "2.3.1",
"cropperjs": "1.7.0",
"culori": "4.0.2",
"date-fns": "4.4.0",
"decimal.js": "10.6.0",
@@ -97,7 +98,7 @@
"echarts": "6.1.0",
"echarts-extension-chart2music": "0.1.1",
"element-internals-polyfill": "3.0.2",
"fullcalendar": "7.1.4",
"fullcalendar": "7.1.3",
"fuse.js": "7.5.0",
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.8.1",
@@ -108,7 +109,7 @@
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.17.0",
"maplibre-gl": "6.16.0",
"marked": "18.1.3",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
@@ -122,7 +123,7 @@
"sortablejs": "1.15.7",
"stacktrace-js": "2.0.2",
"superstruct": "2.0.2",
"temporal-polyfill": "1.0.8",
"temporal-polyfill": "1.0.6",
"tinykeys": "4.0.1",
"weekstart": "2.0.0",
"workbox-cacheable-response": "7.4.1",
@@ -146,12 +147,11 @@
"@bundle-stats/plugin-webpack-filter": "4.23.1",
"@eslint/js": "10.0.1",
"@gfx/zopfli": "1.0.15",
"@home-assistant/components": "workspace:*",
"@html-eslint/eslint-plugin": "0.68.0",
"@html-eslint/eslint-plugin": "0.67.0",
"@lokalise/node-api": "17.0.1",
"@octokit/auth-oauth-device": "8.0.5",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.0",
"@playwright/test": "1.64.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.1",
"@rspack/dev-server": "2.2.2",
@@ -180,7 +180,7 @@
"eslint": "10.14.0",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.0",
"eslint-plugin-import-x": "4.17.1",
"eslint-plugin-lit": "2.3.1",
"eslint-plugin-lit-a11y": "5.1.3",
"eslint-plugin-unused-imports": "4.4.1",
@@ -188,14 +188,14 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "14.0.4",
"glob": "14.0.3",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
"gulp-rename": "2.1.0",
"html-minifier-terser": "7.2.0",
"husky": "9.1.7",
"jsdom": "31.0.0",
"jsdom": "30.1.3",
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
@@ -208,21 +208,21 @@
"pinst": "3.0.0",
"prettier": "3.9.10",
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.7",
"serve": "14.2.6",
"sinon": "22.1.0",
"tar": "7.5.22",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.72.1",
"vite": "8.3.6",
"vite": "8.3.5",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.0",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]8.0",
"packageManager": "[email protected]7.0",
"volta": {
"node": "24.22.2"
}
-156
View File
@@ -1,156 +0,0 @@
# @home-assistant/components
Home Assistant Components (`hac-*`): framework-agnostic web components built
with [Lit](https://lit.dev).
> Work in progress, not published yet.
## Registration
Every element is imported on its own, in one of two ways:
| Import | Registers in | For |
| --------------------------------------------- | -------------------- | ----------------------------------------------------------- |
| `@home-assistant/components/<element>` | Global registry | Home Assistant itself |
| `@home-assistant/components/<element>/scoped` | Your scoped registry | Custom cards and other code that runs inside Home Assistant |
`<element>` is the tag name without the `hac-` prefix, like `card` for
`hac-card`.
Both use the copy bundled with your code. A scoped copy is isolated from the
one Home Assistant registers globally, so a custom card keeps the version it
was built with.
Global registration skips tag names that are already registered, so the first
registration wins and nothing throws.
### Global
```ts
import "@home-assistant/components/card";
```
### Scoped
Pass the component's elements to `ScopedElementsMixin` for Lit, or to
`createScopedElementRegistry` for plain custom elements. Forgetting the
elements is a TypeScript error, and a runtime error in plain JavaScript.
Lit:
```ts
import { LitElement, html } from "lit";
import { ScopedElementsMixin } from "@home-assistant/components/scoped";
import { hacCard } from "@home-assistant/components/card/scoped";
class MyCard extends ScopedElementsMixin(LitElement, [hacCard]) {
render() {
return html`<hac-card>…</hac-card>`;
}
}
```
Plain custom elements:
```js
import {
attachScopedShadow,
createScopedElement,
createScopedElementRegistry,
} from "@home-assistant/components/scoped";
import { hacCard } from "@home-assistant/components/card/scoped";
// Create the registry once, outside the class: all instances of the card share it
const registry = createScopedElementRegistry([hacCard]);
class MyCard extends HTMLElement {
constructor() {
super();
const root = attachScopedShadow(this, { mode: "open" }, registry);
root.innerHTML = "<hac-card>…</hac-card>";
// or: root.append(createScopedElement(root, "hac-card"));
}
}
```
`innerHTML`, `insertAdjacentHTML` and `createScopedElement` use the scoped
registry. `document.createElement` uses the global one, so avoid it for
scoped elements.
Scoped registries need native support (Chrome 146+, Safari 26) or
`@webcomponents/scoped-custom-element-registry`, which Home Assistant loads.
Without either, elements are registered globally instead, and an already
registered tag name keeps its existing class.
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
`document.querySelector("hac-card")` and templates are typed once the element
is imported. For the class itself, import its type from the `scoped` entry
point; `import type` loads nothing at runtime:
```ts
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.
## Theming
Each component exposes its own `--hac-*` custom properties, documented in its
source, which take precedence. Next come the theme variables of the existing
Home Assistant element it replaces, so current themes keep working: `hac-card`
reads the variables of `ha-card` (`--ha-card-background`,
`--card-background-color`, `--ha-card-border-radius`, …). Last come the
semantic color tokens (`--ha-color-*`, like `--ha-color-surface-default`) and
their light values, so the components also render outside Home Assistant.
The legacy theme variables are a temporary bridge for this experiment, not the
target design. Home Assistant always defines some of them, like
`--card-background-color`, so inside Home Assistant they currently win over
the semantic tokens. Once themes move to the semantic tokens, the legacy
variables will be removed from the fallbacks.
## Structure
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
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`.
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
side effects, which `sideEffects` relies on for tree shaking.
## Development
```bash
pnpm --filter @home-assistant/components build # ESM, type declarations and custom-elements.json to dist/
pnpm --filter @home-assistant/components dev # rebuild on change
```
Inside this repository the app uses the sources directly through
the `ha-source` export condition, so no build is needed during development.
The package is built with [Rslib](https://rslib.rs) in bundleless mode: every
source file becomes its own ES module. The build then generates a
[custom elements manifest](https://custom-elements-manifest.open-wc.org) from
the JSDoc of each element, so document new slots, parts, CSS properties and
events there.
@@ -1,84 +0,0 @@
// Generates dist/custom-elements.json from the JSDoc of the hac elements, for
// editors and documentation tools. Only hac-*.ts files declare elements; the
// entry points just re-export them.
const forEachDeclaration = (customElementsManifest, callback) => {
for (const module of customElementsManifest.modules) {
for (const declaration of module.declarations ?? []) {
callback(declaration);
}
}
};
// The analyzer leaves the readme empty. Paths in the manifest are relative to
// the package root, like the module paths.
const packageReadme = () => ({
name: "package-readme",
packageLinkPhase({ customElementsManifest }) {
customElementsManifest.readme = "README.md";
},
});
// Elements are documented with @summary, which the analyzer only puts into
// `summary`. Most tools show `description`, so fall back to the summary.
const summaryAsDescription = () => ({
name: "summary-as-description",
packageLinkPhase({ customElementsManifest }) {
forEachDeclaration(customElementsManifest, (declaration) => {
if (!declaration.description && declaration.summary) {
declaration.description = declaration.summary;
}
});
},
});
// Private and protected members are internal, so keep them out of the
// documented API.
const publicApiOnly = () => ({
name: "public-api-only",
packageLinkPhase({ customElementsManifest }) {
forEachDeclaration(customElementsManifest, (declaration) => {
declaration.members = declaration.members?.filter(
(member) => !member.privacy || member.privacy === "public"
);
});
},
});
const distPaths = () => {
const toDist = (value) => value.replace(/^src\/(.+)\.ts$/, "dist/$1.js");
const rewrite = (node) => {
if (Array.isArray(node)) {
node.forEach(rewrite);
return;
}
if (!node || typeof node !== "object") {
return;
}
for (const [key, value] of Object.entries(node)) {
if ((key === "path" || key === "module") && typeof value === "string") {
node[key] = toDist(value);
} else {
rewrite(value);
}
}
};
return {
name: "dist-paths",
packageLinkPhase({ customElementsManifest }) {
rewrite(customElementsManifest.modules);
},
};
};
export default {
globs: ["src/components/**/hac-*.ts"],
outdir: "dist",
litelement: true,
plugins: [
packageReadme(),
summaryAsDescription(),
publicApiOnly(),
distPaths(),
],
};
-60
View File
@@ -1,60 +0,0 @@
{
"name": "@home-assistant/components",
"version": "0.0.0",
"description": "Home Assistant web components (hac-* elements) built with Lit",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/home-assistant/frontend.git",
"directory": "packages/components"
},
"type": "module",
"sideEffects": [
"./dist/components/**/global.js",
"./src/components/**/global.ts"
],
"customElements": "dist/custom-elements.json",
"exports": {
"./scoped": {
"ha-source": "./src/scoped.ts",
"types": "./dist/scoped.d.ts",
"import": "./dist/scoped.js"
},
"./package.json": "./package.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",
"import": "./dist/components/*/global.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rslib build && cem analyze",
"dev": "rslib build --watch",
"prepublishOnly": "pnpm run build"
},
"peerDependencies": {
"lit": "^3.3.0"
},
"devDependencies": {
"@custom-elements-manifest/analyzer": "0.11.0",
"@rslib/core": "1.0.6",
"lit": "3.3.3",
"typescript": "6.0.3"
}
}
-24
View File
@@ -1,24 +0,0 @@
import { defineConfig } from "@rslib/core";
// Bundleless build: every source file becomes its own ESM file, so consumers'
// bundlers only include the entry points they import. Only global.ts files
// register elements; everything else is free of side effects.
export default defineConfig({
source: {
entry: { index: ["./src/**/*.ts"] },
decorators: { version: "legacy" },
tsconfigPath: "./tsconfig.json",
},
tools: {
swc: { jsc: { transform: { decoratorMetadata: false } } },
},
lib: [
{
format: "esm",
bundle: false,
syntax: "es2021",
dts: true,
output: { target: "web", distPath: { root: "./dist" } },
},
],
});
@@ -1,8 +0,0 @@
import { define } from "../../utils/registration/define";
import { HacCard } from "./hac-card";
import { TAG_NAME } from "./info";
// Registers <hac-card> in the global registry, as used by Home Assistant
define(TAG_NAME, HacCard);
export { HacCard };
@@ -1,165 +0,0 @@
import { css, html, LitElement } from "lit";
import { property, state } from "lit/decorators.js";
import {
hasAssignedContent,
hasAssignedElements,
} from "../../utils/element/slot";
/**
* @element hac-card
*
* @summary
* Card that groups related content, with an optional header and footer.
*
* @slot header - Header of the card. Its spacing replaces the top padding of
* the content.
* @slot - Content of the card. Its padding is omitted when empty.
* @slot footer - Footer of the card. Hidden when empty.
*
* @csspart header - Wrapper of the header slot.
* @csspart content - Wrapper of the default slot.
* @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 --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.
*/
export class HacCard extends LitElement {
/**
* Visual style of the card. `outlined` draws a border without a shadow.
* `raised` hides the border and lifts the card with a shadow instead.
*/
@property({ reflect: true }) public appearance: "outlined" | "raised" =
"outlined";
@state() private _hasHeader = false;
@state() private _hasFooter = false;
@state() private _hasContent = false;
protected render() {
return html`
<div class="header" part="header" ?hidden=${!this._hasHeader}>
<slot name="header" @slotchange=${this._headerChanged}></slot>
</div>
<div
class="content ${this._hasHeader ? "below-header" : ""}"
part="content"
?hidden=${!this._hasContent}
>
<slot @slotchange=${this._contentChanged}></slot>
</div>
<div class="footer" part="footer" ?hidden=${!this._hasFooter}>
<slot name="footer" @slotchange=${this._footerChanged}></slot>
</div>
`;
}
private _headerChanged(ev: Event) {
this._hasHeader = hasAssignedElements(ev);
}
private _contentChanged(ev: Event) {
this._hasContent = hasAssignedContent(ev);
}
private _footerChanged(ev: Event) {
this._hasFooter = hasAssignedElements(ev);
}
/*
* Fallback order: --hac-card-*, then the theme variables of ha-card
* (--ha-card-*, --card-background-color, --divider-color,
* --primary-text-color) so existing themes keep working, then the semantic
* tokens and their light values for use outside Home Assistant.
* The ha-card variables are temporary, see "Theming" in the README.
*/
static styles = css`
:host {
display: block;
position: relative;
box-sizing: border-box;
background: var(
--hac-card-background,
var(
--ha-card-background,
var(--card-background-color, var(--ha-color-surface-default, #fff))
)
);
backdrop-filter: var(--ha-card-backdrop-filter, none);
color: var(
--hac-card-color,
var(--primary-text-color, var(--ha-color-on-surface-default, #141414))
);
border: var(--hac-card-border-width, var(--ha-card-border-width, 1px))
solid
var(
--hac-card-border-color,
var(
--ha-card-border-color,
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
)
);
border-radius: var(
--hac-card-border-radius,
var(--ha-card-border-radius, var(--ha-border-radius-lg, 12px))
);
box-shadow: var(--hac-card-box-shadow, var(--ha-card-box-shadow, none));
}
:host([appearance="raised"]) {
border-color: transparent;
box-shadow: var(
--hac-card-box-shadow,
var(
--ha-card-box-shadow,
var(
--ha-box-shadow-s,
0 1px 2px 0 rgba(0, 0, 0, 0.08),
0 1px 3px 0 rgba(0, 0, 0, 0.12)
)
)
);
}
.content {
padding: var(--hac-card-content-padding, var(--ha-space-4, 16px));
}
/* The header already provides the spacing above the content */
.content.below-header {
padding-block-start: 0;
}
.footer {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--ha-space-2, 8px);
padding: var(--hac-card-footer-padding, var(--ha-space-2, 8px));
border-block-start: 1px solid
var(
--hac-card-border-color,
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
);
}
.header[hidden],
.content[hidden],
.footer[hidden] {
display: none;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hac-card": HacCard;
}
}
@@ -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,15 +0,0 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacCard } from "./hac-card";
import { TAG_NAME } from "./info";
export { HacCard };
/**
* The bundled <hac-card> for a scoped registry:
* `ScopedElementsMixin(LitElement, [hacCard])` or
* `createScopedElementRegistry([hacCard])`.
*/
export const hacCard: ElementDefinition<typeof HacCard> = {
tagName: TAG_NAME,
element: HacCard,
};
-132
View File
@@ -1,132 +0,0 @@
import type { LitElement } from "lit";
import { define } from "./utils/registration/define";
import type { ElementDefinition } from "./utils/registration/definition";
import {
createScopedRegistry,
scopedCreationScope,
scopedRegistrySupport,
scopedShadowRootInit,
} from "./utils/registration/scoped-registry";
export type { ElementDefinition } from "./utils/registration/definition";
/**
* Creates a registry with the given elements, for `attachScopedShadow`:
* definitions from `scoped` entry points, e.g. `[hacCard]`.
* Create it once, outside the class, so all instances of a card share it.
*
* Without scoped registry support (native or polyfill), the elements are
* registered in the global registry instead, unless their tag name is already
* taken there, and the global registry is returned.
*/
export const createScopedElementRegistry = (
elements: readonly ElementDefinition[]
): CustomElementRegistry => {
// Checked as unknown: Array.isArray would narrow the list to any[]
if (!Array.isArray(elements as unknown)) {
throw new TypeError(
"@home-assistant/components: pass the elements to register, e.g. [hacCard]"
);
}
const registry = createScopedRegistry() ?? customElements;
for (const { tagName, element } of elements) {
define(tagName, element, registry);
}
return registry;
};
const shadowRootInit = (
init: ShadowRootInit,
registry: CustomElementRegistry
): ShadowRootInit =>
registry === customElements ? init : scopedShadowRootInit(init, registry);
const registries = new WeakMap<ShadowRoot, CustomElementRegistry>();
/**
* Attaches a shadow root that uses `registry` for custom elements in it.
*
* Content added with `innerHTML` or `insertAdjacentHTML` uses the registry.
* Create single elements with `createScopedElement`; `document.createElement`
* would use the global registry.
*
* Light DOM content, like slotted elements, keeps using the registry of the
* tree it is written in.
*/
export const attachScopedShadow = (
host: HTMLElement,
init: ShadowRootInit,
registry: CustomElementRegistry
): ShadowRoot => {
const root = host.attachShadow(shadowRootInit(init, registry));
registries.set(root, registry);
return root;
};
/** Creates an element from the registry of a shadow root. */
export const createScopedElement = <K extends keyof HTMLElementTagNameMap>(
root: ShadowRoot,
tagName: K
): HTMLElementTagNameMap[K] => {
const registry = registries.get(root);
if (!registry || registry === customElements) {
return document.createElement(tagName);
}
if (scopedRegistrySupport() === "polyfill") {
// The polyfill adds createElement to shadow roots
return (
root as unknown as {
createElement(tagName: K): HTMLElementTagNameMap[K];
}
).createElement(tagName);
}
return (
document.createElement as (
tagName: K,
options: { customElementRegistry: CustomElementRegistry }
) => HTMLElementTagNameMap[K]
)(tagName, { customElementRegistry: registry });
};
type LitElementConstructor = abstract new (...args: any[]) => LitElement;
/**
* Renders a Lit element into a shadow root with its own custom element
* registry, containing `elements`:
*
* ```ts
* class MyCard extends ScopedElementsMixin(LitElement, [hacCard]) {}
* ```
*
* See `createScopedElementRegistry` and `attachScopedShadow` for the details.
*/
export const ScopedElementsMixin = <T extends LitElementConstructor>(
superClass: T,
elements: readonly ElementDefinition[]
) => {
// Created on first use, so defining the class has no side effects
let registry: CustomElementRegistry | undefined;
const getRegistry = () => {
registry ??= createScopedElementRegistry(elements);
return registry;
};
abstract class ScopedElementsHost extends superClass {
public attachShadow(init: ShadowRootInit): ShadowRoot {
const root = super.attachShadow(shadowRootInit(init, getRegistry()));
registries.set(root, getRegistry());
return root;
}
protected createRenderRoot() {
const root = super.createRenderRoot();
const scoped = getRegistry();
if (scoped !== customElements && root instanceof ShadowRoot) {
this.renderOptions.creationScope = scopedCreationScope(root, scoped);
}
return root;
}
}
// Typed as the base class: the overrides add no public API
return ScopedElementsHost as unknown as T;
};
@@ -1,15 +0,0 @@
/** Whether the slot of a `slotchange` event has elements assigned. */
export const hasAssignedElements = (ev: Event): boolean =>
(ev.target as HTMLSlotElement).assignedElements().length > 0;
/**
* Whether the slot of a `slotchange` event has content assigned: elements or
* text. Whitespace between tags is not content.
*/
export const hasAssignedContent = (ev: Event): boolean =>
(ev.target as HTMLSlotElement)
.assignedNodes()
.some(
(node) =>
node.nodeType === Node.ELEMENT_NODE || Boolean(node.textContent?.trim())
);
@@ -1,17 +0,0 @@
/**
* Registers a custom element unless the tag name is already taken in the
* registry.
*
* Home Assistant and custom cards can each ship a copy of this library, so
* registering the same tag name twice must not throw. The first registration
* wins.
*/
export const define = (
tagName: string,
elementClass: CustomElementConstructor,
registry: CustomElementRegistry = customElements
): void => {
if (!registry.get(tagName)) {
registry.define(tagName, elementClass);
}
};
@@ -1,10 +0,0 @@
/**
* An element to register: its tag name and its class. The `scoped` entry
* point of an element exports one, e.g. `hacCard`.
*/
export interface ElementDefinition<
E extends CustomElementConstructor = CustomElementConstructor,
> {
readonly tagName: string;
readonly element: E;
}
@@ -1,67 +0,0 @@
/**
* Scoped custom element registries come in two flavors: the standard API
* (Chrome 146+, Safari 26) and the older API of
* `@webcomponents/scoped-custom-element-registry`, which Home Assistant loads
* and which replaces the native implementation when present.
*/
export type ScopedRegistrySupport = "polyfill" | "native" | "none";
let support: ScopedRegistrySupport | undefined;
export const scopedRegistrySupport = (): ScopedRegistrySupport => {
if (support) {
return support;
}
if ("CustomElementRegistryPolyfill" in globalThis) {
support = "polyfill";
} else {
try {
new CustomElementRegistry();
support = "native";
} catch (_err) {
support = "none";
}
}
return support;
};
/** A new scoped registry, or `undefined` if the browser has no support. */
export const createScopedRegistry = (): CustomElementRegistry | undefined =>
scopedRegistrySupport() === "none" ? undefined : new CustomElementRegistry();
/** Shadow root options that make the shadow root use `registry`. */
export const scopedShadowRootInit = (
init: ShadowRootInit,
registry: CustomElementRegistry
): ShadowRootInit =>
scopedRegistrySupport() === "polyfill"
? ({ ...init, registry } as ShadowRootInit)
: ({ ...init, customElementRegistry: registry } as ShadowRootInit);
interface CreationScope {
importNode(node: Node, deep?: boolean): Node;
}
/**
* The object Lit should create template content with, so custom elements in
* it are created from the scoped registry (Lit's `creationScope`).
*/
export const scopedCreationScope = (
root: ShadowRoot,
registry: CustomElementRegistry
): CreationScope => {
if (scopedRegistrySupport() === "polyfill") {
// The polyfill adds importNode to shadow roots
return root as unknown as CreationScope;
}
// Standard API: the registry is passed to importNode
return {
importNode: (node, deep) =>
(
document.importNode as (
node: Node,
options: { selfOnly: boolean; customElementRegistry: unknown }
) => Node
)(node, { selfOnly: !deep, customElementRegistry: registry }),
};
};
-20
View File
@@ -1,20 +0,0 @@
import { describe, expect, it } from "vitest";
import { define } from "../src/utils/registration/define";
// Home Assistant and custom cards can each ship a copy of the library, so a
// second registration of the same tag must be ignored instead of throwing.
describe("define", () => {
it("registers an element that is not registered yet", () => {
class First extends HTMLElement {}
define("hac-test-first", First);
expect(customElements.get("hac-test-first")).toBe(First);
});
it("keeps the first registration of a tag name", () => {
class Original extends HTMLElement {}
class Duplicate extends HTMLElement {}
define("hac-test-duplicate", Original);
expect(() => define("hac-test-duplicate", Duplicate)).not.toThrow();
expect(customElements.get("hac-test-duplicate")).toBe(Original);
});
});
-40
View File
@@ -1,40 +0,0 @@
import { describe, expect, it } from "vitest";
import {
hasAssignedContent,
hasAssignedElements,
} from "../src/utils/element/slot";
// Components hide wrappers of empty slots, e.g. the padding of an empty card.
// Whitespace between tags must not count as content.
const slotEvent = (light: string, name?: string) => {
const host = document.createElement("div");
host.innerHTML = light;
const slot = document.createElement("slot");
if (name) {
slot.name = name;
}
host.attachShadow({ mode: "open" }).append(slot);
return { target: slot } as unknown as Event;
};
describe("hasAssignedContent", () => {
it("ignores whitespace", () => {
expect(hasAssignedContent(slotEvent("\n \n"))).toBe(false);
});
it("counts text", () => {
expect(hasAssignedContent(slotEvent(" Hello "))).toBe(true);
});
it("counts elements", () => {
expect(hasAssignedContent(slotEvent("\n <p></p>\n"))).toBe(true);
});
});
describe("hasAssignedElements", () => {
it("only counts elements assigned to the slot", () => {
const light = '<span slot="icon"></span> text';
expect(hasAssignedElements(slotEvent(light, "icon"))).toBe(true);
expect(hasAssignedElements(slotEvent(light, "actions"))).toBe(false);
});
});
-20
View File
@@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "ES2021",
"lib": ["ES2021", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"isolatedModules": true,
"skipLibCheck": true,
"declaration": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}
+26
View File
@@ -0,0 +1,26 @@
diff --git a/mwc-list-base.js b/mwc-list-base.js
index 1ba95b6a01dcecea4d85b5cbbbcc3dfb04c40d5f..dced13fdb7929c490d6661b1bbe7e9f96dcd2285 100644
--- a/mwc-list-base.js
+++ b/mwc-list-base.js
@@ -11,7 +11,7 @@ import { BaseElement } from '@material/mwc-base/base-element.js';
import { observer } from '@material/mwc-base/observer.js';
import { deepActiveElementPath, doesElementContainFocus, isNodeElement } from '@material/mwc-base/utils.js';
import { html } from 'lit';
-import { property, query, queryAssignedNodes } from 'lit/decorators.js';
+import { property, query, queryAssignedElements } from 'lit/decorators.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import MDCListFoundation, { isIndexSet } from './mwc-list-foundation.js';
export { createSetFromIndex, isEventMulti, isIndexSet } from './mwc-list-foundation.js';
@@ -425,10 +425,10 @@ __decorate([
query('.mdc-deprecated-list')
], ListBase.prototype, "mdcRoot", void 0);
__decorate([
- queryAssignedNodes('', true, '*')
+ queryAssignedElements({ flatten: true, selector: "*" })
], ListBase.prototype, "assignedElements", void 0);
__decorate([
- queryAssignedNodes('', true, '[tabindex="0"]')
+ queryAssignedElements({ flatten: true, selector: '[tabindex="0"]' })
], ListBase.prototype, "tabbableElements", void 0);
__decorate([
property({ type: Boolean }),
+822 -1278
View File
File diff suppressed because it is too large. Load diff
+1 -5
View File
@@ -1,7 +1,3 @@
packages:
- "."
- "packages/*"
savePrefix: ""
autoInstallPeers: false
@@ -23,7 +19,6 @@ trustPolicyExclude:
allowBuilds:
"@tsparticles/engine": false
core-js: false
rs-module-lexer: false
unrs-resolver: false
overrides:
@@ -34,6 +29,7 @@ overrides:
tslib: 2.9.1
patchedDependencies:
"@material/[email protected]": patches/@[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
-5
View File
@@ -89,11 +89,6 @@
}
],
"packageRules": [
{
"description": "Keep semver ranges for peer dependencies of published packages, pinning them would force consumers onto one exact version",
"matchDepTypes": ["peerDependencies"],
"rangeStrategy": "widen"
},
{
"description": "Group all Python version updates from home-assistant/core",
"matchDepNames": ["python"],
@@ -0,0 +1,312 @@
import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import {
applyConfigChanges,
diffConfigs,
invertConfigChanges,
type ConfigChange,
} from "../util/config-change";
import { pathStartsWith, type ConfigPath } from "../util/config-path";
import { afterNextRender } from "../util/render-status";
const UNDO_REDO_STACK_LIMIT = 75;
/**
* One undo step. `meta` is what the commit described the changes with, and
* is missing for changes made without a commit.
*/
export interface ConfigChangeStep<Meta = unknown> {
changes: ConfigChange[];
meta?: Meta;
}
const changedPaths = (changes: ConfigChange[]): ConfigPath[] =>
changes.flatMap((change) =>
change.op === "move" ? [change.from, change.path] : [change.path]
);
// Whether `changes` only touch values at, in or around the paths of `of`
const onlyTouches = (changes: ConfigChange[], of: ConfigChange[]) => {
const paths = changedPaths(of);
return changedPaths(changes).every((changed) =>
paths.some(
(path) => pathStartsWith(changed, path) || pathStartsWith(path, changed)
)
);
};
export interface ConfigChangeUndoRedoControllerConfig<ConfigType, Meta> {
stackLimit?: number;
currentConfig: () => ConfigType | undefined;
/**
* Applies the config after undo or redo, with the changes that led to it.
* On undo these are the inverted changes of the step, in reverse order.
*/
apply: (
config: ConfigType,
step: ConfigChangeStep<Meta>,
undo: boolean
) => void;
/** Called for every container copied while applying a change. */
onCopy?: (original: object, copy: object) => void;
}
/**
* Undo and redo for immutably updated configs. Instead of whole snapshots, each
* step stores the changes that were made, with their paths, so the host can
* point the user at what undo or redo touched.
*
* @template ConfigType The type of configuration to manage.
* @template Meta Extra state stored with each step, e.g. UI state to restore.
*/
export class ConfigChangeUndoRedoController<
ConfigType,
Meta = undefined,
> implements ReactiveController {
private _host: ReactiveControllerHost;
private _undoStack: ConfigChangeStep<Meta>[] = [];
private _redoStack: ConfigChangeStep<Meta>[] = [];
private readonly _stackLimit: number = UNDO_REDO_STACK_LIMIT;
private readonly _options: ConfigChangeUndoRedoControllerConfig<
ConfigType,
Meta
>;
// The config after the last commit, undo or redo
private _lastConfig?: ConfigType;
private _grouping = false;
// The step commits add to until endGroup()
private _groupStep?: ConfigChangeStep<Meta>;
// Whether the last undo may still be answered by an editor putting back
// what it removed
private _undoPending = false;
private _undoWithPreviousScheduled = false;
constructor(
host: ReactiveControllerHost,
options: ConfigChangeUndoRedoControllerConfig<ConfigType, Meta>
) {
if (options.stackLimit !== undefined) {
this._stackLimit = options.stackLimit;
}
this._options = options;
this._host = host;
host.addController(this);
}
hostConnected() {
window.addEventListener("undo-change", this._onUndoChange);
}
hostDisconnected() {
window.removeEventListener("undo-change", this._onUndoChange);
this._forgetUndo();
}
private _onUndoChange = (ev: Event) => {
ev.stopPropagation();
this.undo();
};
public get canUndo(): boolean {
return this._undoStack.length > 0;
}
public get canRedo(): boolean {
return this._redoStack.length > 0;
}
/**
* Records the difference between two configs and clears the redo stack.
* Configs without a difference are not recorded. `describe` is called with
* all changes of the step, to store state about them with it.
*/
public commit(
before: ConfigType,
after: ConfigType,
describe?: (changes: ConfigChange[]) => Meta
) {
// An editor put back what the last undo removed, e.g. defaults it fills
// in, maybe in several commits. That step can't be undone on its own, so
// it is undone together with the one before it.
const undone = this._redoStack[this._redoStack.length - 1];
if (
this._undoPending &&
undone &&
before === this._lastConfig &&
onlyTouches(diffConfigs(before, after), undone.changes)
) {
this._lastConfig = after;
this._scheduleUndoWithPrevious(undone);
return;
}
this._forgetUndo();
this._syncExternalChanges(before);
this._lastConfig = after;
this._record(before, after, describe);
}
public undo() {
const current = this._options.currentConfig();
this._syncExternalChanges(current);
const step = this._undoStack.pop();
if (!step || current === undefined) {
return;
}
this._redoStack.push(step);
this._rememberUndo();
this._applyStep(
current,
{ changes: invertConfigChanges(step.changes), meta: step.meta },
true
);
}
public redo() {
this._forgetUndo();
const current = this._options.currentConfig();
this._syncExternalChanges(current);
const step = this._redoStack.pop();
if (!step || current === undefined) {
return;
}
this._undoStack.push(step);
this._applyStep(current, step, false);
}
/**
* Records the commits until `endGroup()` as one step, e.g. for a drag
* between two lists, which report their changes one after the other.
*/
public startGroup() {
this._grouping = true;
this._groupStep = undefined;
}
public endGroup() {
this._grouping = false;
this._groupStep = undefined;
}
public reset() {
this._undoStack = [];
this._redoStack = [];
this._host.requestUpdate();
}
/**
* Records a change made without a commit, e.g. in the YAML editor or a
* dialog, as its own step. Without it, later undo steps would replay on a
* config they weren't recorded on and could hit another row.
*/
private _syncExternalChanges(config: ConfigType | undefined) {
const last = this._lastConfig;
this._lastConfig = config;
if (config === last || config === undefined || last === undefined) {
return;
}
this._record(last, config);
}
private _record(
before: ConfigType,
after: ConfigType,
describe?: (changes: ConfigChange[]) => Meta
) {
const changes = diffConfigs(before, after);
if (!changes.length) {
return;
}
const group = this._groupStep;
if (group && group === this._undoStack[this._undoStack.length - 1]) {
group.changes = [...group.changes, ...changes];
if (describe) {
group.meta = describe(group.changes);
}
} else {
if (this._undoStack.length >= this._stackLimit) {
this._undoStack.shift();
}
const step = { changes, meta: describe?.(changes) };
this._undoStack.push(step);
if (this._grouping) {
this._groupStep = step;
}
}
this._redoStack = [];
this._host.requestUpdate();
}
// Editors put defaults back on their own. Anything after the user's next
// input is a change of their own, even if it puts the same value back.
private _rememberUndo() {
this._forgetUndo();
this._undoPending = true;
window.addEventListener("pointerdown", this._forgetUndo, true);
window.addEventListener("keydown", this._forgetUndo, true);
}
private _forgetUndo = () => {
this._undoPending = false;
window.removeEventListener("pointerdown", this._forgetUndo, true);
window.removeEventListener("keydown", this._forgetUndo, true);
};
// Waits until the editors rendered the undo. One still updating could
// otherwise write an old value back while the next undo runs.
private _scheduleUndoWithPrevious(step: ConfigChangeStep<Meta>) {
if (this._undoWithPreviousScheduled) {
return;
}
this._undoWithPreviousScheduled = true;
afterNextRender(() => {
this._undoWithPreviousScheduled = false;
// Another undo or redo came first
if (this._redoStack[this._redoStack.length - 1] !== step) {
return;
}
this._redoStack.pop();
const previous = this._undoStack.pop();
if (!previous) {
this._host.requestUpdate();
return;
}
this._undoStack.push({
changes: [...previous.changes, ...step.changes],
meta: previous.meta,
});
this.undo();
});
}
private _applyStep(
current: ConfigType,
step: ConfigChangeStep<Meta>,
undo: boolean
) {
const config = applyConfigChanges(
current,
step.changes,
this._options.onCopy
);
this._lastConfig = config;
this._options.apply(config, step, undo);
this._host.requestUpdate();
}
}
declare global {
interface HASSDomEvents {
"undo-change": undefined;
}
}
-29
View File
@@ -1,29 +0,0 @@
const INTERACTIVE_SELECTOR = [
"a[href]",
"button",
"input",
"select",
"textarea",
"summary",
"label",
"[contenteditable]:not([contenteditable='false'])",
"[tabindex]:not([tabindex='-1'])",
"[role='button']",
"[role='link']",
"[role='checkbox']",
"[role='radio']",
"[role='switch']",
"[role='slider']",
"[role='tab']",
"[role='menuitem']",
"[role='option']",
"[role='combobox']",
"[role='textbox']",
].join(",");
/**
* Whether `node` is an element that handles clicks or keyboard input on its
* own, such as a button, link, form control or a focusable widget.
*/
export const isInteractiveElement = (node: EventTarget): boolean =>
node instanceof Element && node.matches(INTERACTIVE_SELECTOR);
+5 -5
View File
@@ -1,12 +1,12 @@
import type { HassServices } from "home-assistant-js-websocket";
import type { HomeAssistant } from "../../types";
import { getToggleAction } from "./get_toggle_action";
export const canToggleDomain = (services: HassServices, domain: string) => {
const domainServices = services[domain];
if (!domainServices) {
export const canToggleDomain = (hass: HomeAssistant, domain: string) => {
const services = hass.services[domain];
if (!services) {
return false;
}
const actionOn = getToggleAction(domain, true);
const actionOff = getToggleAction(domain, false);
return actionOn in domainServices && actionOff in domainServices;
return actionOn in services && actionOff in services;
};
+6 -13
View File
@@ -1,30 +1,23 @@
import type {
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HomeAssistant } from "../../types";
import { canToggleDomain } from "./can_toggle_domain";
import { computeStateDomain } from "./compute_state_domain";
import { supportsFeature } from "./supports-feature";
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
export const canToggleState = (
states: HassEntities,
services: HassServices,
stateObj: HassEntity
) => {
export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
const domain = computeStateDomain(stateObj);
if (domain === "group") {
if (
stateObj.attributes?.entity_id?.some((entity) => {
const entityStateObj = states[entity];
const entityStateObj = hass.states[entity];
if (!entityStateObj) {
return false;
}
const entityDomain = computeStateDomain(entityStateObj);
return canToggleDomain(services, entityDomain);
return canToggleDomain(hass, entityDomain);
})
) {
return stateObj.state === "on" || stateObj.state === "off";
@@ -42,5 +35,5 @@ export const canToggleState = (
);
}
return canToggleDomain(services, domain);
return canToggleDomain(hass, domain);
};
+2 -17
View File
@@ -163,21 +163,9 @@ export const findEntities = (
return results;
};
export const excludeEntities = (
entityIds: string[],
excludedEntityIds?: string[]
): string[] => {
if (!excludedEntityIds?.length) {
return entityIds;
}
const excluded = new Set(excludedEntityIds);
return entityIds.filter((entityId) => !excluded.has(entityId));
};
export const findFilteredEntities = (
sources: EntityFilterSources,
filters: EntityFilter[],
excludedEntityIds?: string[]
filters: EntityFilter[]
): string[] => {
const filterFuncs = filters.map((filter) =>
generateEntityFilter(
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
filter
)
);
return excludeEntities(
findEntities(Object.keys(sources.states), filterFuncs),
excludedEntityIds
);
return findEntities(Object.keys(sources.states), filterFuncs);
};
+4 -11
View File
@@ -1,18 +1,11 @@
import type {
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE } from "../../data/entity/entity";
import type { HomeAssistant } from "../../types";
import { DOMAINS_WITH_CARD } from "../const";
import { canToggleState } from "./can_toggle_state";
import { computeStateDomain } from "./compute_state_domain";
export const stateCardType = (
states: HassEntities,
services: HassServices,
stateObj: HassEntity
) => {
export const stateCardType = (hass: HomeAssistant, stateObj: HassEntity) => {
if (stateObj.state === UNAVAILABLE) {
return "display";
}
@@ -23,7 +16,7 @@ export const stateCardType = (
return domain;
}
if (
canToggleState(states, services, stateObj) &&
canToggleState(hass, stateObj) &&
stateObj.attributes.control !== "hidden"
) {
return "toggle";
@@ -1,33 +0,0 @@
import type { LocalizeFunc } from "./localize";
const YAML_ERROR_REASON_KEYS = new Map(
Object.entries({
"duplicated mapping key": "duplicated_mapping_key",
"bad indentation of a mapping entry": "bad_mapping_indentation",
"bad indentation of a sequence entry": "bad_sequence_indentation",
"deficient indentation": "deficient_indentation",
"tab characters must not be used in indentation": "tab_indentation",
"can not read a block mapping entry; a multiline key may not be an implicit key":
"multiline_implicit_key",
"a whitespace character is expected after the key-value separator within a block mapping":
"missing_key_value_space",
"expected ':' after a mapping key": "missing_colon",
"missed comma between flow collection entries": "missing_comma",
"unexpected end of the stream within a flow collection":
"unterminated_flow_collection",
"unexpected end of the stream within a single quoted scalar":
"unterminated_single_quote",
"unexpected end of the stream within a double quoted scalar":
"unterminated_double_quote",
"end of the stream or a document separator is expected":
"unexpected_content",
} as const)
);
export const localizeYamlErrorReason = (
localize: LocalizeFunc,
reason: string | undefined
): string | undefined => {
const key = reason ? YAML_ERROR_REASON_KEYS.get(reason) : undefined;
return key ? localize(`ui.components.yaml-editor.reasons.${key}`) : reason;
};
+5 -11
View File
@@ -1,7 +1,6 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
@@ -26,7 +25,6 @@ export const automationsFilterQueryParamConfig = {
"assistants",
"blueprint",
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type AutomationsFilterQueryParams = QueryParamValues<
@@ -38,7 +36,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
): Record<string, string[]> | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const automationsFilterQueryParams = (
@@ -46,7 +44,6 @@ export const automationsFilterQueryParams = (
): AutomationsFilterQueryParams => ({
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
device: list(filters["ha-filter-devices"]),
entity: list(filters["ha-filter-entities"]),
label: list(filters["ha-filter-labels"]),
@@ -62,7 +59,7 @@ export const automationsFilterQueryString = (
filters: DataTableFilters
): string => {
const params = automationsFilterQueryParams(filters);
const sorted: AutomationsFilterQueryParams = { ...params };
const sorted: AutomationsFilterQueryParams = {};
for (const key of automationsFilterQueryParamConfig.list) {
sorted[key] = params[key] && [...params[key]].sort();
@@ -97,9 +94,8 @@ export const automationsLinkFromUrl = (
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
const values = (
key: (typeof automationsFilterQueryParamConfig.list)[number]
): string[] => params[key]?.filter(Boolean) ?? [];
const values = (key: keyof AutomationsFilterQueryParams): string[] =>
params[key]?.filter(Boolean) ?? [];
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
value,
@@ -113,9 +109,7 @@ export const automationsLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas": filter(
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
floors.length || areas.length ? { floors, areas } : undefined
),
"ha-filter-devices": filter(values("device")),
"ha-filter-entities": filter(values("entity")),
+5 -11
View File
@@ -1,7 +1,6 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
@@ -25,7 +24,6 @@ export const devicesFilterQueryParamConfig = {
"config_entry",
"sub_entry",
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type DevicesFilterQueryParams = QueryParamValues<
@@ -37,7 +35,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
): Record<string, string[]> | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const devicesFilterQueryParams = (
@@ -46,7 +44,6 @@ export const devicesFilterQueryParams = (
status: list(filters["ha-filter-states"]),
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
domain: list(filters["ha-filter-integrations"]),
label: list(filters["ha-filter-labels"]),
config_entry: list(filters.config_entry),
@@ -58,7 +55,7 @@ export const devicesFilterQueryParams = (
// filter list sends back what it was given in its own order.
export const devicesFilterQueryString = (filters: DataTableFilters): string => {
const params = devicesFilterQueryParams(filters);
const sorted: DevicesFilterQueryParams = { ...params };
const sorted: DevicesFilterQueryParams = {};
for (const key of devicesFilterQueryParamConfig.list) {
sorted[key] = params[key] && [...params[key]].sort();
@@ -90,9 +87,8 @@ export const devicesLinkFromUrl = (
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
const values = (
key: (typeof devicesFilterQueryParamConfig.list)[number]
): string[] => params[key]?.filter(Boolean) ?? [];
const values = (key: keyof DevicesFilterQueryParams): string[] =>
params[key]?.filter(Boolean) ?? [];
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
value,
@@ -107,9 +103,7 @@ export const devicesLinkFromUrl = (
filters: {
"ha-filter-states": filter(values("status")),
"ha-filter-floor-areas": filter(
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
floors.length || areas.length ? { floors, areas } : undefined
),
"ha-filter-integrations": filter(values("domain")),
"ha-filter-labels": filter(values("label")),
+5 -11
View File
@@ -1,7 +1,6 @@
import type {
DataTableFiltersValue,
DataTableFiltersValues,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
@@ -31,7 +30,6 @@ export const entitiesFilterQueryParamConfig = {
// Read until 2027.5, replaced with `assistants` on the next write
"voice_assistant",
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type EntitiesFilterQueryParams = QueryParamValues<
@@ -43,7 +41,7 @@ const list = (value: DataTableFiltersValue): string[] | undefined =>
const floorAreas = (
value: DataTableFiltersValue
): FloorAreasFilterValue | undefined =>
): Record<string, string[]> | undefined =>
value && !Array.isArray(value) ? value : undefined;
export const entitiesFilterQueryParams = (
@@ -52,7 +50,6 @@ export const entitiesFilterQueryParams = (
status: list(filters["ha-filter-states"]),
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
device: list(filters["ha-filter-devices"]),
device_class: list(filters["ha-filter-device-classes"]),
domain: list(filters["ha-filter-integrations"]),
@@ -70,7 +67,7 @@ export const entitiesFilterQueryString = (
filters: DataTableFiltersValues
): string => {
const params = entitiesFilterQueryParams(filters);
const sorted: EntitiesFilterQueryParams = { ...params };
const sorted: EntitiesFilterQueryParams = {};
for (const key of entitiesFilterQueryParamConfig.list) {
sorted[key] = params[key] && [...params[key]].sort();
@@ -105,9 +102,8 @@ export const entitiesLinkFromUrl = (
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
const values = (
key: (typeof entitiesFilterQueryParamConfig.list)[number]
): string[] => params[key]?.filter(Boolean) ?? [];
const values = (key: keyof EntitiesFilterQueryParams): string[] =>
params[key]?.filter(Boolean) ?? [];
const floors = values("floor");
const areas = values("area");
@@ -118,9 +114,7 @@ export const entitiesLinkFromUrl = (
filters: {
"ha-filter-states": values("status"),
"ha-filter-floor-areas":
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined,
floors.length || areas.length ? { floors, areas } : undefined,
"ha-filter-devices": values("device"),
"ha-filter-device-classes": values("device_class"),
"ha-filter-integrations": values("domain"),
+5 -11
View File
@@ -1,7 +1,6 @@
import type {
DataTableFiltersValue,
DataTableFiltersValues,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
@@ -26,7 +25,6 @@ export const helpersFilterQueryParamConfig = {
// Read until 2027.5, replaced with `assistants` on the next write
"voice_assistant",
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type HelpersFilterQueryParams = QueryParamValues<
@@ -38,7 +36,7 @@ const list = (value: DataTableFiltersValue): string[] | undefined =>
const floorAreas = (
value: DataTableFiltersValue
): FloorAreasFilterValue | undefined =>
): Record<string, string[]> | undefined =>
value && !Array.isArray(value) ? value : undefined;
export const helpersFilterQueryParams = (
@@ -46,7 +44,6 @@ export const helpersFilterQueryParams = (
): HelpersFilterQueryParams => ({
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
device: list(filters["ha-filter-devices"]),
label: list(filters["ha-filter-labels"]),
category: list(filters["ha-filter-categories"]),
@@ -60,7 +57,7 @@ export const helpersFilterQueryString = (
filters: DataTableFiltersValues
): string => {
const params = helpersFilterQueryParams(filters);
const sorted: HelpersFilterQueryParams = { ...params };
const sorted: HelpersFilterQueryParams = {};
for (const key of helpersFilterQueryParamConfig.list) {
sorted[key] = params[key] && [...params[key]].sort();
@@ -92,9 +89,8 @@ export const helpersLinkFromUrl = (
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
const values = (
key: (typeof helpersFilterQueryParamConfig.list)[number]
): string[] => params[key]?.filter(Boolean) ?? [];
const values = (key: keyof HelpersFilterQueryParams): string[] =>
params[key]?.filter(Boolean) ?? [];
const floors = values("floor");
const areas = values("area");
@@ -104,9 +100,7 @@ export const helpersLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas":
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined,
floors.length || areas.length ? { floors, areas } : undefined,
"ha-filter-devices": values("device"),
"ha-filter-labels": values("label"),
"ha-filter-categories": values("category"),
+5 -11
View File
@@ -1,7 +1,6 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
@@ -25,7 +24,6 @@ export const scenesFilterQueryParamConfig = {
"category",
"assistants",
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type ScenesFilterQueryParams = QueryParamValues<
@@ -37,7 +35,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
): Record<string, string[]> | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const scenesFilterQueryParams = (
@@ -45,7 +43,6 @@ export const scenesFilterQueryParams = (
): ScenesFilterQueryParams => ({
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
device: list(filters["ha-filter-devices"]),
entity: list(filters["ha-filter-entities"]),
label: list(filters["ha-filter-labels"]),
@@ -58,7 +55,7 @@ export const scenesFilterQueryParams = (
// filter list sends back what it was given in its own order.
export const scenesFilterQueryString = (filters: DataTableFilters): string => {
const params = scenesFilterQueryParams(filters);
const sorted: ScenesFilterQueryParams = { ...params };
const sorted: ScenesFilterQueryParams = {};
for (const key of scenesFilterQueryParamConfig.list) {
sorted[key] = params[key] && [...params[key]].sort();
@@ -90,9 +87,8 @@ export const scenesLinkFromUrl = (
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
const values = (
key: (typeof scenesFilterQueryParamConfig.list)[number]
): string[] => params[key]?.filter(Boolean) ?? [];
const values = (key: keyof ScenesFilterQueryParams): string[] =>
params[key]?.filter(Boolean) ?? [];
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
value,
@@ -106,9 +102,7 @@ export const scenesLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas": filter(
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
floors.length || areas.length ? { floors, areas } : undefined
),
"ha-filter-devices": filter(values("device")),
"ha-filter-entities": filter(values("entity")),
+5 -11
View File
@@ -1,7 +1,6 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
@@ -26,7 +25,6 @@ export const scriptsFilterQueryParamConfig = {
"assistants",
"blueprint",
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type ScriptsFilterQueryParams = QueryParamValues<
@@ -38,7 +36,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
): Record<string, string[]> | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const scriptsFilterQueryParams = (
@@ -46,7 +44,6 @@ export const scriptsFilterQueryParams = (
): ScriptsFilterQueryParams => ({
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
device: list(filters["ha-filter-devices"]),
entity: list(filters["ha-filter-entities"]),
label: list(filters["ha-filter-labels"]),
@@ -60,7 +57,7 @@ export const scriptsFilterQueryParams = (
// filter list sends back what it was given in its own order.
export const scriptsFilterQueryString = (filters: DataTableFilters): string => {
const params = scriptsFilterQueryParams(filters);
const sorted: ScriptsFilterQueryParams = { ...params };
const sorted: ScriptsFilterQueryParams = {};
for (const key of scriptsFilterQueryParamConfig.list) {
sorted[key] = params[key] && [...params[key]].sort();
@@ -92,9 +89,8 @@ export const scriptsLinkFromUrl = (
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
const values = (
key: (typeof scriptsFilterQueryParamConfig.list)[number]
): string[] => params[key]?.filter(Boolean) ?? [];
const values = (key: keyof ScriptsFilterQueryParams): string[] =>
params[key]?.filter(Boolean) ?? [];
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
value,
@@ -108,9 +104,7 @@ export const scriptsLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas": filter(
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
floors.length || areas.length ? { floors, areas } : undefined
),
"ha-filter-devices": filter(values("device")),
"ha-filter-entities": filter(values("entity")),
+408
View File
@@ -0,0 +1,408 @@
import { deepEqual } from "./deep-equal";
import {
getAtPath,
pathStartsWith,
setAtPath,
type ConfigPath,
} from "./config-path";
/**
* One edit of a config as plain JSON, so it can be stored for undo, shown as
* a diff or proposed by someone else and applied later.
*
* Like JSON Patch, `add` and `remove` work on object keys and list items: in a
* list, `add` inserts at the index that ends `path` and later items shift.
* `remove` and `replace` keep the old value, so they can be inverted and
* checked against the config they are applied to. `move` removes the item at
* `from`, then adds it at `path`.
*
* Changes apply in order, each to the config the previous ones left.
*/
export type ConfigChange =
| { op: "add"; path: ConfigPath; value: unknown }
| { op: "remove"; path: ConfigPath; value: unknown }
| { op: "replace"; path: ConfigPath; before: unknown; after: unknown }
| { op: "move"; from: ConfigPath; path: ConfigPath };
// Key order counts, as the editors compare configs with it
const equal = (a: unknown, b: unknown) =>
deepEqual(a, b, { compareKeyOrder: true });
const isContainer = (value: unknown): value is object =>
typeof value === "object" && value !== null;
/** Whether removing and appending keys turns `from` into `to`. */
const keepsKeyOrder = (from: string[], to: string[]) => {
const kept = from.filter((key) => to.includes(key));
return [...kept, ...to.filter((key) => !from.includes(key))].every(
(key, index) => key === to[index]
);
};
const itemsEqual = (
a: unknown[],
aStart: number,
b: unknown[],
bStart: number,
count: number
) => {
for (let i = 0; i < count; i++) {
if (!equal(a[aStart + i], b[bStart + i])) {
return false;
}
}
return true;
};
const diffLists = (
before: unknown[],
after: unknown[],
path: ConfigPath,
changes: ConfigChange[]
) => {
const length = Math.min(before.length, after.length);
let first = 0;
while (first < length && equal(before[first], after[first])) {
first++;
}
if (first === length && before.length === after.length) {
return;
}
if (
after.length === before.length + 1 &&
itemsEqual(before, first, after, first + 1, before.length - first)
) {
changes.push({ op: "add", path: [...path, first], value: after[first] });
return;
}
if (
before.length === after.length + 1 &&
itemsEqual(before, first + 1, after, first, after.length - first)
) {
changes.push({
op: "remove",
path: [...path, first],
value: before[first],
});
return;
}
if (Math.abs(before.length - after.length) === 1) {
diffListsWithOneMore(before, after, path, changes);
return;
}
if (before.length !== after.length) {
changes.push({ op: "replace", path, before, after });
return;
}
let last = before.length - 1;
while (equal(before[last], after[last])) {
last--;
}
const count = last - first;
// A move shifts the items between its old and new index by one
if (
count > 0 &&
equal(after[last], before[first]) &&
itemsEqual(before, first + 1, after, first, count)
) {
changes.push({ op: "move", from: [...path, first], path: [...path, last] });
return;
}
if (
count > 0 &&
equal(after[first], before[last]) &&
itemsEqual(before, first, after, first + 1, count)
) {
changes.push({ op: "move", from: [...path, last], path: [...path, first] });
return;
}
for (let index = first; index <= last; index++) {
diffValues(before[index], after[index], [...path, index], changes);
}
};
const sameKind = (a: unknown, b: unknown) =>
isContainer(a) &&
isContainer(b) &&
Object.keys(a).sort().join() === Object.keys(b).sort().join();
/**
* One item was added or removed and others changed, as when a row is dragged
* into a block in the same list. The added or removed item is the one that
* leaves the fewest other items changed, and of those the fewest changed
* into another kind of item.
*/
const diffListsWithOneMore = (
before: unknown[],
after: unknown[],
path: ConfigPath,
changes: ConfigChange[]
) => {
const added = after.length > before.length;
const longer = added ? after : before;
const shorter = added ? before : after;
let index = 0;
let fewest = Infinity;
for (let candidate = 0; candidate < longer.length; candidate++) {
let score = 0;
shorter.forEach((item, i) => {
const counterpart = longer[i < candidate ? i : i + 1];
if (!equal(counterpart, item)) {
score += sameKind(counterpart, item) ? 2 : 3;
}
});
if (score < fewest) {
index = candidate;
fewest = score;
}
}
changes.push(
added
? { op: "add", path: [...path, index], value: after[index] }
: { op: "remove", path: [...path, index], value: before[index] }
);
// Compared at the indices of `after`, where they are after the first change
after.forEach((item, i) => {
if (added && i === index) {
return;
}
const counterpart = added
? before[i < index ? i : i - 1]
: before[i < index ? i : i + 1];
diffValues(counterpart, item, [...path, i], changes);
});
};
const diffValues = (
before: unknown,
after: unknown,
path: ConfigPath,
changes: ConfigChange[]
) => {
if (before === after) {
return;
}
if (Array.isArray(before) && Array.isArray(after)) {
diffLists(before, after, path, changes);
return;
}
if (
isContainer(before) &&
isContainer(after) &&
!Array.isArray(before) &&
!Array.isArray(after)
) {
const beforeKeys = Object.keys(before);
const afterKeys = Object.keys(after);
// Applying a change adds a key at the end, and undo adds removed keys
// back in reverse order. Where that would change the key order, the whole
// object is replaced instead.
const keysChanged =
afterKeys.filter((key) => !beforeKeys.includes(key)).length +
beforeKeys.filter((key) => !afterKeys.includes(key)).length;
// A key holding undefined is no change as a value, but the dirty check
// compares keys
const undefinedKeyChanged = [...beforeKeys, ...afterKeys].some(
(key) =>
key in before !== key in after &&
(before as Record<string, unknown>)[key] === undefined &&
(after as Record<string, unknown>)[key] === undefined
);
if (
keysChanged > 1 ||
undefinedKeyChanged ||
!keepsKeyOrder(beforeKeys, afterKeys) ||
!keepsKeyOrder(afterKeys, beforeKeys)
) {
changes.push({ op: "replace", path, before, after });
return;
}
for (const key of new Set([...beforeKeys, ...afterKeys])) {
diffValues(
(before as Record<string, unknown>)[key],
(after as Record<string, unknown>)[key],
[...path, key],
changes
);
}
return;
}
if (before === undefined) {
changes.push({ op: "add", path, value: after });
} else if (after === undefined) {
changes.push({ op: "remove", path, value: before });
} else if (!equal(before, after)) {
changes.push({ op: "replace", path, before, after });
}
};
/**
* The changes that turn `before` into `after`, each as small as possible.
* An insertion, removal or move of a single list item is found as such; other
* list changes are compared item by item, or replace the list.
*/
export const diffConfigs = (
before: unknown,
after: unknown
): ConfigChange[] => {
const changes: ConfigChange[] = [];
diffValues(before, after, [], changes);
return changes;
};
const isListItem = (root: unknown, path: ConfigPath) =>
Array.isArray(getAtPath(root, path.slice(0, -1)));
const updateList = <T>(
root: T,
path: ConfigPath,
update: (list: unknown[], index: number) => unknown[],
onCopy?: (original: object, copy: object) => void
): T => {
const listPath = path.slice(0, -1);
const list = getAtPath(root, listPath) as unknown[];
const updated = update(list, path[path.length - 1] as number);
onCopy?.(list, updated);
return setAtPath(root, listPath, updated, onCopy);
};
const add = <T>(
root: T,
path: ConfigPath,
value: unknown,
onCopy?: (original: object, copy: object) => void
) =>
isListItem(root, path)
? updateList(
root,
path,
(list, index) => [...list.slice(0, index), value, ...list.slice(index)],
onCopy
)
: setAtPath(root, path, value, onCopy);
const remove = <T>(
root: T,
path: ConfigPath,
onCopy?: (original: object, copy: object) => void
) =>
isListItem(root, path)
? updateList(
root,
path,
(list, index) => list.filter((_item, i) => i !== index),
onCopy
)
: setAtPath(root, path, undefined, onCopy);
/**
* Applies changes immutably. `onCopy` sees every copied container next to its
* original.
*/
export const applyConfigChanges = <T>(
root: T,
changes: ConfigChange[],
onCopy?: (original: object, copy: object) => void
): T =>
changes.reduce((config, change) => {
switch (change.op) {
case "add":
return add(config, change.path, change.value, onCopy);
case "remove":
return remove(config, change.path, onCopy);
case "replace":
return setAtPath(config, change.path, change.after, onCopy);
case "move":
return add(
remove(config, change.from, onCopy),
change.path,
getAtPath(config, change.from),
onCopy
);
}
return config;
}, root);
/** The changes that undo `changes`. */
export const invertConfigChanges = (changes: ConfigChange[]): ConfigChange[] =>
changes
.map((change): ConfigChange => {
switch (change.op) {
case "add":
return { op: "remove", path: change.path, value: change.value };
case "remove":
return { op: "add", path: change.path, value: change.value };
case "replace":
return {
op: "replace",
path: change.path,
before: change.after,
after: change.before,
};
case "move":
return { op: "move", from: change.path, path: change.from };
}
return change;
})
.reverse();
// Moves `path` along when an item is added to or removed from a list above it
const shift = (
path: ConfigPath,
itemPath: ConfigPath,
by: 1 | -1
): ConfigPath => {
const listPath = itemPath.slice(0, -1);
const index = itemPath[itemPath.length - 1];
const segment = path[listPath.length];
if (
typeof index !== "number" ||
typeof segment !== "number" ||
path.length <= listPath.length ||
!pathStartsWith(path, listPath) ||
(by === 1 ? segment < index : segment <= index)
) {
return path;
}
return [...listPath, segment + by, ...path.slice(listPath.length + 1)];
};
/**
* Where the value at `path` is after `changes`, or `undefined` when it was
* removed or is part of a replaced value.
*/
export const mapConfigPath = (
path: ConfigPath,
changes: ConfigChange[]
): ConfigPath | undefined => {
let mapped: ConfigPath | undefined = path;
for (const change of changes) {
if (!mapped) {
return undefined;
}
switch (change.op) {
case "add":
mapped = shift(mapped, change.path, 1);
break;
case "remove":
mapped = pathStartsWith(mapped, change.path)
? undefined
: shift(mapped, change.path, -1);
break;
case "replace":
if (
pathStartsWith(mapped, change.path) &&
mapped.length > change.path.length
) {
mapped = undefined;
}
break;
case "move":
mapped = pathStartsWith(mapped, change.from)
? [...change.path, ...mapped.slice(change.from.length)]
: shift(shift(mapped, change.from, -1), change.path, 1);
break;
}
}
return mapped;
};
+51 -2
View File
@@ -1,7 +1,56 @@
/** Where a value is in a config, e.g. `["actions", 0, "then", 1]`. */
export type ConfigPath = (string | number)[];
export const stringifyPath = (path: ConfigPath): string => path.join("/");
const isContainer = (value: unknown): value is object =>
typeof value === "object" && value !== null;
export const pathEquals = (a: ConfigPath, b: ConfigPath): boolean =>
a.length === b.length && a.every((segment, index) => segment === b[index]);
export const pathStartsWith = (path: ConfigPath, prefix: ConfigPath) =>
prefix.length <= path.length &&
prefix.every((segment, index) => path[index] === segment);
export const getAtPath = (root: unknown, path: ConfigPath): unknown =>
path.reduce<unknown>(
(node, segment) =>
isContainer(node)
? (node as Record<string, unknown>)[segment]
: undefined,
root
);
/**
* Immutably replaces the value at `path`, copying only the containers along it.
* An `undefined` value removes an object key instead of storing `undefined`.
* `onCopy` sees every copied container next to its original.
*/
export const setAtPath = <T>(
root: T,
path: ConfigPath,
value: unknown,
onCopy?: (original: object, copy: object) => void
): T => {
if (path.length === 0) {
return value as T;
}
const [segment, ...rest] = path;
const node: unknown = root;
const copy = (
Array.isArray(node) ? node.slice() : { ...(isContainer(node) ? node : {}) }
) as Record<string | number, unknown>;
const child = setAtPath(
isContainer(node) ? (node as Record<string, unknown>)[segment] : undefined,
rest,
value,
onCopy
);
if (child === undefined && !Array.isArray(node)) {
delete copy[segment];
} else {
copy[segment] = child;
}
if (isContainer(node)) {
onCopy?.(node, copy);
}
return copy as T;
};
+12 -56
View File
@@ -30,40 +30,10 @@ export class HaAutomationRow extends LitElement {
@property({ type: Boolean, reflect: true })
public dim = false;
/** Makes the row a link, with the icons slot outside of it */
@property() public href?: string;
@query(".row")
private _rowElement?: HTMLDivElement;
@query(".link")
private _linkElement?: HTMLAnchorElement;
protected render(): TemplateResult {
const content = html`
<div class="leading-icon-wrapper">
<slot name="leading-icon"></slot>
</div>
<div class="header">
<slot name="header"></slot>
<slot name="event"></slot>
</div>
`;
const icons = html`
<div class="icons">
<slot name="icons"></slot>
</div>
`;
if (this.href) {
return html`
<div class="row has-link">
<a class="link" href=${this.href}>${content}</a>
${icons}
</div>
`;
}
return html`
<div
class="row"
@@ -83,7 +53,17 @@ export class HaAutomationRow extends LitElement {
`
: nothing
}
${content} ${icons}
<div class="leading-icon-wrapper">
<slot name="leading-icon"></slot>
</div>
<div class="header">
<slot name="header"></slot>
<slot name="event"></slot>
</div>
<div class="icons">
<slot name="icons"></slot>
</div>
</div>
`;
}
@@ -139,7 +119,7 @@ export class HaAutomationRow extends LitElement {
public focus() {
requestAnimationFrame(() => {
(this._linkElement ?? this._rowElement)?.focus();
this._rowElement?.focus();
});
}
@@ -164,30 +144,6 @@ export class HaAutomationRow extends LitElement {
outline: var(--wa-focus-ring);
outline-offset: -2px;
}
.row.has-link {
padding-left: 0;
padding-inline-start: 0;
cursor: default;
}
.link {
display: flex;
align-items: flex-start;
align-self: stretch;
flex: 1;
min-width: 0;
padding-left: var(--ha-space-3);
padding-inline-start: var(--ha-space-3);
padding-inline-end: initial;
color: inherit;
text-decoration: none;
cursor: pointer;
outline: none;
border-radius: inherit;
}
.link:focus-visible {
outline: var(--wa-focus-ring);
outline-offset: -2px;
}
.expand-button {
transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
color: var(--ha-color-on-neutral-quiet);
+24 -46
View File
@@ -17,7 +17,6 @@ import {
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { join } from "lit/directives/join";
import { keyed } from "lit/directives/keyed";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
@@ -125,16 +124,16 @@ export interface DataTableRowData {
export type SortableColumnContainer = Record<string, ClonedDataTableColumnData>;
// Renders the actions at the end of a group's header, they don't toggle the
// group. Return `ha-icon-button`s with a label. They get the rows' icon
// Slot for the actions at the end of a group's header, they don't toggle the
// group. Put `ha-icon-button`s with a label in it. They get the rows' icon
// colour and size by default, which `--data-table-group-actions-color`,
// `--data-table-group-actions-button-size` and
// `--data-table-group-actions-icon-size` change for all of them; style a
// button itself for its own colour or size. Not a slot per group, as WebKit
// is slow to add and remove slots while the rows scroll.
export type DataTableGroupActions = (
group: string
) => TemplateResult | typeof nothing;
// button itself for its own colour or size.
export const GROUP_ACTIONS_SLOT_PREFIX = "group-actions-";
export const groupActionsSlot = (group: string) =>
`${GROUP_ACTIONS_SLOT_PREFIX}${group}`;
const UNDEFINED_GROUP_KEY = "zzzzz_undefined";
@@ -198,9 +197,6 @@ export class HaDataTable extends LitElement {
@property({ attribute: false }) public groupOrder?: string[];
@property({ attribute: false })
public renderGroupActions?: DataTableGroupActions;
@property({ attribute: false }) public sortColumn?: string;
@property({ attribute: false }) public sortDirection: SortingDirection = null;
@@ -401,13 +397,9 @@ export class HaDataTable extends LitElement {
}
if (properties.has("data")) {
// Clean up checked rows that no longer exist or can no longer be selected
// Clean up checked rows that no longer exist in the data
if (this._checkedRows.length) {
const validIds = new Set(
this.data
.filter((row) => row.selectable !== false)
.map((row) => String(row[this.id]))
);
const validIds = new Set(this.data.map((row) => String(row[this.id])));
const validCheckedRows = this._checkedRows.filter((id) =>
validIds.has(id)
);
@@ -514,8 +506,7 @@ export class HaDataTable extends LitElement {
this.groupOrder,
this._collapsedGroups,
this.sortColumn,
this.sortDirection,
this.renderGroupActions
this.sortDirection
)
: [];
@@ -768,6 +759,8 @@ export class HaDataTable extends LitElement {
`
: html`
${
// Rendered before the rows, so the group's actions slot
// shows here and not in its scrolled out header row
this.groupColumn &&
!this.autoHeight &&
this._stickyGroup !== undefined
@@ -782,15 +775,11 @@ export class HaDataTable extends LitElement {
.group=${this._stickyGroup}
@click=${this._collapseStickyGroup}
>
${keyed(
${this._renderGroupHeader(
this._stickyGroup,
this._renderGroupHeader(
this._stickyGroup,
this._collapsedGroups.includes(this._stickyGroup),
this._i18n?.localize,
this.renderGroupActions,
true
)
this._collapsedGroups.includes(this._stickyGroup),
this._i18n?.localize,
true
)}
</div>`
: nothing
@@ -814,14 +803,7 @@ export class HaDataTable extends LitElement {
`;
}
// Group headers are keyed by their group, so they keep their actions' state
// when the data changes. The prefixes keep them apart from row ids.
private _keyFunction = (row: DataTableRowData) =>
row?.[this.id]
? `row-${row[this.id]}`
: row?.groupHeader !== undefined
? `group-${row.groupHeader}`
: row;
private _keyFunction = (row: DataTableRowData) => row?.[this.id] || row;
private _renderMainValue(value: unknown) {
return this.clickable
@@ -1081,8 +1063,7 @@ export class HaDataTable extends LitElement {
groupOrder: string[] | undefined,
collapsedGroups: string[],
sortColumn: string | undefined,
sortDirection: SortingDirection,
renderGroupActions: DataTableGroupActions | undefined
sortDirection: SortingDirection
) => {
if (appendRow || groupColumn) {
let items = [...data];
@@ -1141,8 +1122,7 @@ export class HaDataTable extends LitElement {
content: this._renderGroupHeader(
groupName,
collapsedGroups.includes(groupName),
localize,
renderGroupActions
localize
),
});
if (!collapsedGroups.includes(groupName)) {
@@ -1168,7 +1148,6 @@ export class HaDataTable extends LitElement {
groupName: string,
collapsed: boolean,
localize: LocalizeFunc | undefined,
renderGroupActions: DataTableGroupActions | undefined,
sticky = false
) {
// The sticky copy's button and name are hidden from assistive technology,
@@ -1204,7 +1183,7 @@ export class HaDataTable extends LitElement {
}
</span>
<div class="group-actions" @click=${this._stopGroupToggle}>
${renderGroupActions?.(groupName)}
<slot name=${groupActionsSlot(groupName)}></slot>
</div>
</div>`;
}
@@ -1285,8 +1264,7 @@ export class HaDataTable extends LitElement {
this.groupOrder,
this._collapsedGroups,
this.sortColumn,
this.sortDirection,
this.renderGroupActions
this.sortDirection
);
if (
@@ -1983,7 +1961,7 @@ export class HaDataTable extends LitElement {
align-self: stretch;
margin-top: -12px;
margin-inline-start: auto;
/* The rows' icon button size, inherited by the actions */
/* The rows' icon button size, inherited by the slotted ones */
--_button-size: var(--data-table-group-actions-button-size, 48px);
--ha-icon-button-size: var(--_button-size);
--mdc-icon-size: var(--data-table-group-actions-icon-size, 24px);
@@ -1996,9 +1974,9 @@ export class HaDataTable extends LitElement {
position: sticky;
inset-inline-end: 0;
cursor: default;
/* Don't pass the group name's weight on to the actions */
/* Don't pass the group name's weight on to slotted menus */
font-weight: var(--ha-font-weight-normal);
/* Inherited by the actions, like the rows' icon cells */
/* Inherited by the slotted icon buttons, like the rows' icon cells */
color: var(
--data-table-group-actions-color,
var(--secondary-text-color)
@@ -97,8 +97,6 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
@state() private _dateValue?: string;
@state() private _rangeIncomplete = false;
@state() private _timeValue = {
from: { hours: 0, minutes: 0 },
to: { hours: 23, minutes: 59 },
@@ -197,7 +195,6 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
.locale=${this._i18n.locale.language}
.focusedDate=${this._focusDate}
@focusday=${this._focusChanged}
@rangestart=${this._handleRangeStart}
@change=${this._handleChange}
show-outside-days
.firstDayOfWeek=${firstWeekdayIndex(this._i18n.locale)}
@@ -256,9 +253,7 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
<ha-button appearance="plain" @click=${this._cancel}
>${this._i18n.localize("ui.common.cancel")}</ha-button
>
<ha-button
.disabled=${!this._dateValue || this._rangeIncomplete}
@click=${this._save}
<ha-button .disabled=${!this._dateValue} @click=${this._save}
>${this._i18n.localize(
"ui.components.date-range-picker.select"
)}</ha-button
@@ -285,7 +280,7 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
}
private _save() {
if (!this._dateValue || this._rangeIncomplete) {
if (!this._dateValue) {
return;
}
@@ -336,21 +331,9 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
this._focusDate = ev.target.focusedDate;
}
private _handleRangeStart(
ev: HASSDomTargetEvent<HTMLElementTagNameMap["calendar-range"]>
) {
this._rangeIncomplete = matchMedia("(hover: hover)").matches;
if (this._rangeIncomplete) {
return;
}
const day = ev.target.tentative;
this._dateValue = `${day}/${day}`;
}
private _handleChange(
ev: HASSDomTargetEvent<HTMLElementTagNameMap["calendar-range"]>
) {
this._rangeIncomplete = false;
const dateElement = ev.target as HTMLElementTagNameMap["calendar-range"];
this._dateValue = dateElement.value;
this._focusDate = dateElement.focusedDate;
+19 -18
View File
@@ -371,24 +371,25 @@ export class HaEntityPicker extends LitElement {
excludeEntities?: string[],
value?: string
) =>
getEntities({
states,
entities: registries.entities,
devices: registries.devices,
areas: registries.areas,
floors: registries.floors,
localize: i18n.localize,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
includeDomains,
excludeDomains,
entityFilter,
includeDeviceClasses,
includeUnitOfMeasurement,
includeEntities,
excludeEntities,
value,
})
getEntities(
{
states,
...registries,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
localize: i18n.localize,
},
{
includeDomains,
excludeDomains,
entityFilter,
includeDeviceClasses,
includeUnitOfMeasurement,
includeEntities,
excludeEntities,
value,
}
)
);
private _sortByRelatedContext = memoizeOne(
+11 -7
View File
@@ -2,7 +2,6 @@ import type { ContextType } from "@lit/context";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../common/decorators/consume";
import { configContext } from "../data/context";
import "./ha-icon-next";
@@ -35,14 +34,17 @@ class HaConfigNavigationList extends LitElement {
.href=${externalApp ? undefined : page.path}
@click=${externalApp ? this._handleExternalApp : undefined}
>
<ha-svg-icon
<div
slot="start"
class=${page.iconColor ? "icon-background" : ""}
style=${styleMap({ backgroundColor: page.iconColor })}
.path=${page.iconPath}
.secondaryPath=${page.iconSecondaryPath}
.viewBox=${page.iconViewBox}
></ha-svg-icon>
.style="background-color: ${page.iconColor || "undefined"}"
>
<ha-svg-icon
.path=${page.iconPath}
.secondaryPath=${page.iconSecondaryPath}
.viewBox=${page.iconViewBox}
></ha-svg-icon>
</div>
<span slot="headline">${page.name}</span>
${
this.hasSecondary
@@ -80,6 +82,8 @@ class HaConfigNavigationList extends LitElement {
}
.icon-background {
border-radius: var(--ha-border-radius-circle);
}
.icon-background ha-svg-icon {
color: #fff;
}
`;
-1
View File
@@ -219,7 +219,6 @@ export class HaControlSlider extends LitElement {
this.pressed = false;
this._hideTooltip();
this.value = savedValue;
fireEvent(this, "slider-moved", { value: undefined });
});
this._mc.on("panmove", (e) => {
if (this.disabled) return;
+23 -136
View File
@@ -8,8 +8,6 @@ import { createRef, ref } from "lit/directives/ref";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { getDeviceAreaId } from "../common/entity/context/get_device_context";
import {
FilterPanelController,
filterPanelStyles,
@@ -19,16 +17,11 @@ import { fireEvent } from "../common/dom/fire_event";
import { computeRTL } from "../common/util/compute_rtl";
import { deepEqual } from "../common/util/deep-equal";
import type { LocalizeFunc } from "../common/translations/localize";
import type { AreaRegistryEntry } from "../data/area/area_registry";
import type { FloorAreasFilterValue } from "../data/data_table_filters";
import {
apiContext,
areasContext,
devicesContext,
floorsContext,
fullEntitiesContext,
internationalizationContext,
statesContext,
} from "../data/context";
import { getFloorAreaLookup } from "../data/floor_registry";
import type { RelatedResult } from "../data/search";
@@ -40,7 +33,6 @@ import "./ha-icon";
import "./ha-icon-button";
import "./ha-svg-icon";
import "./ha-tree-indicator";
import "./item/ha-list-item-base";
import "./item/ha-list-item-option";
import type { HaListItemOption } from "./item/ha-list-item-option";
import "./list/ha-list-selectable";
@@ -67,27 +59,10 @@ export class HaFilterFloorAreas extends LitElement {
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@consume({ context: devicesContext, subscribe: true })
@state()
private _devices!: ContextType<typeof devicesContext>;
@consume({ context: fullEntitiesContext, subscribe: true })
@state()
private _entities?: ContextType<typeof fullEntitiesContext>;
// Only a state being added or removed can change the state-only entities,
// so plain state updates keep the previous set and don't rerender
@state()
@consume({ context: statesContext, subscribe: true })
@transform<ContextType<typeof statesContext>, Set<string>>({
transformer: function (this: HaFilterFloorAreas, states) {
const ids = new Set(Object.keys(states));
return deepEqual(ids, this._stateIds) ? this._stateIds : ids;
},
})
private _stateIds?: Set<string>;
@property({ attribute: false }) public value?: FloorAreasFilterValue;
@property({ attribute: false }) public value?: {
floors?: string[];
areas?: string[];
};
@property() public type?: keyof RelatedResult;
@@ -106,17 +81,12 @@ export class HaFilterFloorAreas extends LitElement {
private _relatedRequestId = 0;
public willUpdate(properties: PropertyValues) {
public willUpdate(properties: PropertyValues<this>) {
super.willUpdate(properties);
if (
(properties.has("value") &&
!deepEqual(this.value, properties.get("value"))) ||
// Items without an area are worked out from the registries
(this.value?.no_area &&
(properties.has("_devices") ||
properties.has("_entities") ||
(this.type !== "device" && properties.has("_stateIds"))))
properties.has("value") &&
!deepEqual(this.value, properties.get("value"))
) {
this._findRelated();
}
@@ -124,12 +94,6 @@ export class HaFilterFloorAreas extends LitElement {
protected render() {
const areas = this._areas(this._areasReg, this._floorsReg);
const groupOtherAreas =
!!areas.floors.length && !!areas.unassisgnedAreas.length;
const count =
(this.value?.areas?.length || 0) +
(this.value?.floors?.length || 0) +
(this.value?.no_area ? 1 : 0);
return html`
<ha-expansion-panel
@@ -140,8 +104,13 @@ export class HaFilterFloorAreas extends LitElement {
<div slot="header" class="header">
${this._localize("ui.panel.config.areas.caption")}
${
count
? html`<div class="badge">${count}</div>
this.value?.areas?.length || this.value?.floors?.length
? html`<div class="badge">
${
(this.value?.areas?.length || 0) +
(this.value?.floors?.length || 0)
}
</div>
<ha-icon-button
.path=${mdiFilterVariantRemove}
@click=${this._clearFilter}
@@ -162,17 +131,6 @@ export class HaFilterFloorAreas extends LitElement {
@ha-list-item-deselected=${this._handleRemoved}
aria-label=${this._localize("ui.panel.config.areas.caption")}
>
<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${"no_area"}
.type=${"no_area"}
.selected=${this.value?.no_area || false}
>
<span slot="headline">
${this._localize("ui.components.area-picker.no_area")}
</span>
</ha-list-item-option>
${repeat(
areas?.floors || [],
(floor) => floor.floor_id,
@@ -204,31 +162,10 @@ export class HaFilterFloorAreas extends LitElement {
)}
`
)}
${
groupOtherAreas
? html`<ha-list-item-base role="presentation">
<ha-svg-icon
slot="start"
.path=${mdiTextureBox}
></ha-svg-icon>
<span slot="headline">
${this._localize(
"ui.panel.config.areas.picker.other_areas"
)}
</span>
</ha-list-item-base>`
: nothing
}
${repeat(
areas.unassisgnedAreas,
(area, index) =>
`${area.area_id}${index === areas.unassisgnedAreas.length - 1 ? "___last" : ""}`,
(area, index) =>
this._renderArea(
area,
index === areas.unassisgnedAreas.length - 1,
groupOtherAreas
)
areas?.unassisgnedAreas,
(area) => area.area_id,
(area) => this._renderArea(area)
)}
</ha-list-selectable>
</div>
@@ -238,11 +175,9 @@ export class HaFilterFloorAreas extends LitElement {
`;
}
private _renderArea(
area: AreaRegistryEntry,
last = false,
nested = !!area.floor_id
) {
private _renderArea(area, last = false) {
const hasFloor = !!area.floor_id;
return html`
<ha-list-item-option
appearance="checkbox"
@@ -255,11 +190,11 @@ export class HaFilterFloorAreas extends LitElement {
this._i18n.language,
this._i18n.translationMetadata.translations
),
floor: nested,
floor: hasFloor,
})}
>
${
nested
hasFloor
? html`<ha-tree-indicator
slot="start"
.end=${last}
@@ -292,11 +227,6 @@ export class HaFilterFloorAreas extends LitElement {
return;
}
if (addedItem.type === "no_area") {
this.value = { ...this.value, no_area: true };
return;
}
this.value = {
...this.value,
[addedItem.type]: [
@@ -319,11 +249,6 @@ export class HaFilterFloorAreas extends LitElement {
return;
}
if (removedItem.type === "no_area") {
this.value = { ...this.value, no_area: false };
return;
}
this.value = {
...this.value,
[removedItem.type]: this.value![removedItem.type].filter(
@@ -364,9 +289,7 @@ export class HaFilterFloorAreas extends LitElement {
if (
!this.value ||
(!this.value.areas?.length &&
!this.value.floors?.length &&
!this.value.no_area)
(!this.value.areas?.length && !this.value.floors?.length)
) {
this.value = {};
fireEvent(this, "data-table-filter-changed", {
@@ -409,9 +332,6 @@ export class HaFilterFloorAreas extends LitElement {
}
const items = new Set<string>();
if (this.value.no_area) {
this._itemsWithoutArea().forEach((item) => items.add(item));
}
for (const result of results) {
if (result[this.type!]) {
result[this.type!]!.forEach((item) => items.add(item));
@@ -424,39 +344,6 @@ export class HaFilterFloorAreas extends LitElement {
});
}
private _itemsWithoutArea(): string[] {
if (this.type === "device") {
return Object.values(this._devices)
.filter((device) => !getDeviceAreaId(device, this._devices))
.map((device) => device.id);
}
// Matches the area column of each table: the entities and helpers tables
// give an entity without its own area the area of its device, the
// automations, scripts and scenes tables only show the entity's own area
const useDeviceArea = this.type === "entity";
const entities = this._entities || [];
const items = entities
.filter(
(entity) =>
(this.includeDisabledEntities || !entity.disabled_by) &&
!entity.area_id &&
!(
useDeviceArea &&
entity.device_id &&
this._devices[entity.device_id]?.area_id
)
)
.map((entity) => entity.entity_id);
// Entities without a registry entry can't have an area
const registered = new Set(entities.map((entity) => entity.entity_id));
for (const entityId of this._stateIds || []) {
if (!registered.has(entityId)) {
items.push(entityId);
}
}
return items;
}
private _handleClearFilterKeydown(ev: KeyboardEvent) {
if (ev.key === "Enter" || ev.key === " ") {
ev.stopPropagation();
+19 -25
View File
@@ -16,30 +16,6 @@ import type {
HaFormIntegerSchema,
} from "./types";
/**
* The value the slider shows: the data, or for a required field without data
* its suggested value, default or minimum.
*/
export const computeIntegerSliderValue = (
schema: HaFormIntegerSchema,
data?: HaFormIntegerData
): number => {
if (data !== undefined) {
return data;
}
if (!schema.required) {
return schema.valueMin || 0;
}
return (
(schema.description?.suggested_value as HaFormIntegerData | undefined) ??
schema.default ??
schema.valueMin ??
0
);
};
@customElement("ha-form-integer")
export class HaFormInteger extends LitElement implements HaFormElement {
@property({ attribute: false }) public localize?: LocalizeFunc;
@@ -103,7 +79,7 @@ export class HaFormInteger extends LitElement implements HaFormElement {
}
<ha-slider
labeled
.value=${computeIntegerSliderValue(this.schema, this.data)}
.value=${this._value}
.min=${this.schema.valueMin}
.max=${this.schema.valueMax}
.disabled=${
@@ -160,6 +136,24 @@ export class HaFormInteger extends LitElement implements HaFormElement {
}
}
private get _value() {
if (this.data !== undefined) {
return this.data;
}
if (!this.schema.required) {
return this.schema.valueMin || 0;
}
return (
(this.schema.description?.suggested_value !== undefined &&
this.schema.description?.suggested_value !== null) ||
this.schema.default ||
this.schema.valueMin ||
0
);
}
private _handleCheckboxChange(ev: HASSDomTargetEvent<HaCheckbox>) {
const checked = (ev.target as HaCheckbox).checked;
let value: HaFormIntegerData | undefined;
+6 -11
View File
@@ -214,19 +214,15 @@ class HaHsColorPicker extends LitElement {
this._mc.add(new Tap({ event: "singletap" }));
let savedPosition;
let savedValue: [number, number] | undefined;
this._mc.on("panstart", (e) => {
if (this.disabled) return;
this._pressed = e.pointerType;
savedPosition = this._cursorPosition;
savedValue = this._localValue;
});
this._mc.on("pancancel", () => {
if (this.disabled) return;
this._pressed = undefined;
this._cursorPosition = savedPosition;
this._localValue = savedValue;
fireEvent(this, "cursor-moved", { value: undefined });
});
this._mc.on("panmove", (e) => {
if (this.disabled) return;
@@ -287,14 +283,13 @@ class HaHsColorPicker extends LitElement {
const x = e.center.x;
const y = e.center.y;
const boundingRect = e.target.getBoundingClientRect();
// The wheel is drawn as a centered square (object-fit: contain), but the
// canvas box itself is not always square (e.g. wider in Safari).
const size = Math.min(boundingRect.width, boundingRect.height);
const centerX = boundingRect.left + boundingRect.width / 2;
const centerY = boundingRect.top + boundingRect.height / 2;
const offsetX = boundingRect.left;
const offsetY = boundingRect.top;
const maxX = e.target.clientWidth;
const maxY = e.target.clientHeight;
const _x = (2 * (x - centerX)) / size;
const _y = (2 * (y - centerY)) / size;
const _x = (2 * (x - offsetX)) / maxX - 1;
const _y = (2 * (y - offsetY)) / maxY - 1;
const [r, phi] = xy2polar(_x, _y);
const [xx, yy] = polar2xy(Math.min(1, r), phi);
@@ -406,8 +406,6 @@ export class HaItemDisplayEditor extends LitElement {
cursor: move;
padding: 8px;
margin: -8px;
/* Keep the handle above the row's hit area so dragging can start */
z-index: 1;
}
.separator {
width: 1px;
+116
View File
@@ -0,0 +1,116 @@
import { ListItemBase } from "@material/mwc-list/mwc-list-item-base";
import { styles } from "@material/mwc-list/mwc-list-item.css";
import type { CSSResultGroup } from "lit";
import { css } from "lit";
import { customElement } from "lit/decorators";
@customElement("ha-list-item")
export class HaListItem extends ListItemBase {
protected renderRipple() {
if (this.noninteractive) {
return "";
}
return super.renderRipple();
}
static get styles(): CSSResultGroup {
return [
styles,
css`
:host {
padding-left: var(
--mdc-list-side-padding-left,
var(--mdc-list-side-padding, 20px)
);
padding-inline-start: var(
--mdc-list-side-padding-left,
var(--mdc-list-side-padding, 20px)
);
padding-right: var(
--mdc-list-side-padding-right,
var(--mdc-list-side-padding, 20px)
);
padding-inline-end: var(
--mdc-list-side-padding-right,
var(--mdc-list-side-padding, 20px)
);
}
:host([graphic="avatar"]:not([twoLine])),
:host([graphic="icon"]:not([twoLine])) {
height: 48px;
}
span.material-icons:first-of-type {
margin-inline-start: 0px !important;
margin-inline-end: var(
--mdc-list-item-graphic-margin,
16px
) !important;
direction: var(--direction) !important;
}
span.material-icons:last-of-type {
margin-inline-start: auto !important;
margin-inline-end: 0px !important;
direction: var(--direction) !important;
}
.mdc-deprecated-list-item__meta {
display: var(--mdc-list-item-meta-display);
align-items: center;
flex-shrink: 0;
}
:host([graphic="icon"]:not([twoline]))
.mdc-deprecated-list-item__graphic {
margin-inline-end: var(
--mdc-list-item-graphic-margin,
20px
) !important;
}
:host([multiline-secondary]) {
height: auto;
}
:host([multiline-secondary]) .mdc-deprecated-list-item__text {
padding: 8px 0;
}
:host([multiline-secondary]) .mdc-deprecated-list-item__secondary-text {
text-overflow: initial;
white-space: normal;
overflow: auto;
display: inline-block;
margin-top: 10px;
}
:host([multiline-secondary]) .mdc-deprecated-list-item__primary-text {
margin-top: 10px;
}
:host([multiline-secondary])
.mdc-deprecated-list-item__secondary-text::before {
display: none;
}
:host([multiline-secondary])
.mdc-deprecated-list-item__primary-text::before {
display: none;
}
:host([disabled]) {
color: var(--disabled-text-color);
}
:host([noninteractive]) {
pointer-events: unset;
}
`,
// safari workaround - must be explicit
document.dir === "rtl"
? css`
span.material-icons:first-of-type,
span.material-icons:last-of-type {
direction: rtl !important;
--direction: rtl;
}
`
: css``,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-list-item": HaListItem;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { ListBase } from "@material/mwc-list/mwc-list-base";
import { styles } from "@material/mwc-list/mwc-list.css";
import { customElement } from "lit/decorators";
@customElement("ha-list")
export class HaList extends ListBase {
static styles = styles;
}
declare global {
interface HTMLElementTagNameMap {
"ha-list": HaList;
}
}
+2 -7
View File
@@ -219,7 +219,6 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
if (this._searchFieldElement) {
this._searchFieldElement.value = value;
}
this._applySearch(value);
}
protected get scrollableElement(): HTMLElement | null {
@@ -692,11 +691,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
private _filterChanged = (ev: InputEvent) => {
const textfield = ev.target as HaInputSearch;
this._applySearch(textfield.value ?? "");
};
private _applySearch(value: string) {
const searchString = value.trim();
const searchString = (textfield.value ?? "").trim();
this._search = searchString;
if (this.sections?.length) {
@@ -741,7 +736,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
this._resetSelectedItem();
this._resetListScroll();
}
};
// Keep focus in the search field, so a focus change doesn't scroll the
// list to the active row and make the click miss.
+2 -3
View File
@@ -50,7 +50,6 @@ const wait = (ms: number) =>
* @cssprop --ha-ripple-hover-color - Hover color.
* @cssprop --ha-ripple-pressed-color - Pressed color.
* @cssprop --ha-ripple-hover-opacity - Hover opacity. Defaults to 0.08.
* @cssprop --ha-ripple-hover-duration - Fade duration of the hover color. Defaults to 15ms.
* @cssprop --ha-ripple-pressed-opacity - Pressed opacity. Defaults to 0.12.
*/
@customElement("ha-ripple")
@@ -397,8 +396,8 @@ export class HaRipple extends LitElement {
var(--ha-ripple-color, var(--secondary-text-color))
);
transition:
opacity var(--ha-ripple-hover-duration, 15ms) linear,
background-color var(--ha-ripple-hover-duration, 15ms) linear;
opacity 15ms linear,
background-color 15ms linear;
}
.hovered .hover {
opacity: var(--ha-ripple-hover-opacity, 0.08);
@@ -11,22 +11,6 @@ import type { LocalizeFunc } from "../../common/translations/localize";
import "../ha-button-toggle-group";
import "./ha-selector";
/**
* A copy of the value with each choice's value under its key. A plain value,
* like a duration without active_choice, belongs to the active choice.
*/
export const computeChooseValues = (
value: any,
activeChoice: string
): Record<string, any> => {
if (value === null || value === undefined) {
return {};
}
return typeof value === "object" && "active_choice" in value
? { ...value }
: { [activeChoice]: value };
};
@customElement("ha-selector-choose")
export class HaChooseSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -125,7 +109,12 @@ export class HaChooseSelector extends LitElement {
private _choiceChanged(ev) {
ev.stopPropagation();
const value = computeChooseValues(this.value, this._activeChoice!);
const value =
typeof this.value === "object"
? this.value
: {
[this._activeChoice!]: this.value,
};
const choice = ev.detail?.value || ev.target.value;
this._activeChoice = choice;
if (choice && "constant" in this.selector.choose.choices[choice].selector) {
@@ -142,7 +131,7 @@ export class HaChooseSelector extends LitElement {
private _handleValueChanged(ev: CustomEvent) {
ev.stopPropagation();
const value = computeChooseValues(this.value, this._activeChoice!);
const value = typeof this.value === "object" ? this.value : {};
fireEvent(this, "value-changed", {
value: {
...value,
@@ -278,13 +278,6 @@ export class HaNumericThresholdSelector extends LitElement {
`;
}
private _getActiveChoice(entry: ThresholdValueEntry | undefined) {
return (
entry?.active_choice ??
(entry?.entity !== undefined ? "entity" : "number")
);
}
private _renderValueRow(
rowLabel: string,
entry: ThresholdValueEntry | undefined,
@@ -294,7 +287,7 @@ export class HaNumericThresholdSelector extends LitElement {
unitOptions: readonly string[] | undefined,
choiceToggleButtons: { label: string; value: string }[]
) {
const activeChoice = this._getActiveChoice(entry);
const activeChoice = entry?.active_choice ?? "number";
const isEntity = activeChoice === "entity";
const showUnit = !isEntity && !!unitOptions && unitOptions.length > 1;
const innerValue = isEntity ? entry?.entity : entry?.number;
@@ -416,7 +409,7 @@ export class HaNumericThresholdSelector extends LitElement {
ev: CustomEvent
) {
ev.stopPropagation();
const activeChoice = this._getActiveChoice(this.value?.[field]);
const activeChoice = this.value?.[field]?.active_choice ?? "number";
const defaultUnit = this._getUnitOptions()?.[0];
const entry: ThresholdValueEntry = {
...this.value?.[field],
@@ -457,7 +450,7 @@ export class HaNumericThresholdSelector extends LitElement {
) {
const unit = ev.detail?.value;
if (unit === this.value?.[field]?.unit_of_measurement) return;
const activeChoice = this._getActiveChoice(this.value?.[field]);
const activeChoice = this.value?.[field]?.active_choice ?? "number";
const defaultType = field === "value" ? "above" : "between";
fireEvent(this, "value-changed", {
value: {
@@ -1,18 +1,9 @@
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { ensureArray } from "../../common/array/ensure-array";
import { consume } from "../../common/decorators/consume";
import {
apiContext,
connectionContext,
devicesContext,
entitiesContext,
statesContext,
} from "../../data/context";
import type { DeviceRegistryEntry } from "../../data/device/device_registry";
import { getDeviceIntegrationLookup } from "../../data/device/device_registry";
import type { EntitySources } from "../../data/entity/entity_sources";
@@ -24,7 +15,7 @@ import {
filterSelectorEntities,
} from "../../data/selector";
import type { HassServiceTargetWithExclude } from "../../data/target";
import type { HomeAssistant, HomeAssistantConnection } from "../../types";
import type { HomeAssistant } from "../../types";
import "../ha-target-picker";
type TargetSelectorFilters = NonNullable<TargetSelector["target"]>;
@@ -37,6 +28,8 @@ const ALL_DEVICES = () => true;
@customElement("ha-selector-target")
export class HaTargetSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: TargetSelector;
@property({ type: Object }) public value?: HassServiceTargetWithExclude;
@@ -51,27 +44,9 @@ export class HaTargetSelector extends LitElement {
@state() private _createDomains: string[] | undefined;
@consume({ context: apiContext, subscribe: true })
private _api?: ContextType<typeof apiContext>;
@state()
@consume({ context: connectionContext, subscribe: true })
private _connection?: ContextType<typeof connectionContext>;
@consume({ context: statesContext, subscribe: true })
private _states?: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities?: ContextType<typeof entitiesContext>;
@consume({ context: devicesContext, subscribe: true })
private _devices?: ContextType<typeof devicesContext>;
private _fetchedEntitySources = false;
private _deviceIntegrationLookup = memoizeOne(
(entities: HomeAssistant["entities"] | undefined) =>
getDeviceIntegrationLookup(Object.values(entities ?? {}))
(entities: HomeAssistant["entities"]) =>
getDeviceIntegrationLookup(Object.values(entities))
);
private _hasIntegration(selector: TargetSelector) {
@@ -87,31 +62,18 @@ export class HaTargetSelector extends LitElement {
);
}
protected updated(changedProperties: PropertyValues): void {
protected updated(changedProperties: PropertyValues<this>): void {
super.updated(changedProperties);
const oldConnection = changedProperties.get("_connection") as
HomeAssistantConnection | undefined;
if (
oldConnection &&
this._connection &&
(oldConnection.connection !== this._connection.connection ||
(!oldConnection.connected && this._connection.connected))
changedProperties.has("selector") &&
this._hasIntegration(this.selector) &&
!this._entitySources
) {
this._fetchedEntitySources = false;
}
if (
this._api &&
!this._fetchedEntitySources &&
this._hasIntegration(this.selector)
) {
this._fetchedEntitySources = true;
fetchEntitySourcesWithCache(this._api.callWS, this._states ?? {})
.then((sources) => {
fetchEntitySourcesWithCache(this.hass.callWS, this.hass.states).then(
(sources) => {
this._entitySources = sources;
})
.catch(() => {
this._entitySources ??= {};
});
}
);
}
if (changedProperties.has("selector")) {
this._createDomains = computeCreateDomains(this.selector);
@@ -125,6 +87,7 @@ export class HaTargetSelector extends LitElement {
return html` ${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-target-picker
.hass=${this.hass}
.value=${this.value}
.helper=${this.helper}
.deviceFilter=${this._deviceFilter(this.selector.target?.device)}
@@ -155,8 +118,8 @@ export class HaTargetSelector extends LitElement {
filter,
entity,
entitySources,
this._entities,
this._devices
this.hass.entities,
this.hass.devices
)
);
}
@@ -169,7 +132,7 @@ export class HaTargetSelector extends LitElement {
}
return (device: DeviceRegistryEntry): boolean => {
const deviceIntegrations = this._hasIntegration(this.selector)
? this._deviceIntegrationLookup(this._entities)
? this._deviceIntegrationLookup(this.hass.entities)
: undefined;
return ensureArray(filters).some((filter) =>
filterSelectorDevices(filter, device, deviceIntegrations)
+6 -14
View File
@@ -1,13 +1,10 @@
import type { ContextType } from "@lit/context";
import type { HassServiceTarget } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { ensureArray } from "../common/array/ensure-array";
import { consume } from "../common/decorators/consume";
import { fireEvent } from "../common/dom/fire_event";
import { entitiesContext, statesContext } from "../data/context";
import type { DataTableFiltersValue } from "../data/data_table_filters";
import type { HaEntityPickerEntityFilterFunc } from "../data/entity/entity";
import { entityTypeFilterFunc } from "../data/entity/entity_type";
@@ -111,6 +108,8 @@ export const applySourceFilters = (
*/
@customElement("ha-sources-picker")
export class HaSourcesPicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public value: HassServiceTarget = {};
/** The filters the page applies, so the picker counts what they keep. */
@@ -126,14 +125,6 @@ export class HaSourcesPicker extends LitElement {
@property({ type: Boolean }) public disabled = false;
@state()
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@state()
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
protected render() {
const noTargets = countTargets(this.value) === 0;
@@ -145,12 +136,13 @@ export class HaSourcesPicker extends LitElement {
}
<ha-target-picker
class=${classMap({ "no-padding-top": noTargets })}
.hass=${this.hass}
.value=${this.value}
.entityFilter=${this.entityFilter}
.activeFilter=${this._activeFilter(
this.filters,
this._states,
this._entities,
this.hass.states,
this.hass.entities,
this.entitySources
)}
.primaryEntitiesOnly=${false}
+84 -165
View File
@@ -1,4 +1,3 @@
import type { ContextType } from "@lit/context";
import "@home-assistant/webawesome/dist/components/popover/popover";
import { mdiPlaylistMinus, mdiPlus, mdiTextureBox } from "@mdi/js";
import Fuse from "fuse.js";
@@ -9,7 +8,6 @@ import { customElement, property, query, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { ensureArray } from "../common/array/ensure-array";
import type { HASSDomEvent } from "../common/dom/fire_event";
import { fireEvent } from "../common/dom/fire_event";
@@ -23,17 +21,7 @@ import {
type FloorComboBoxItem,
} from "../data/area_floor_picker";
import { getConfigEntries, type ConfigEntry } from "../data/config_entries";
import {
apiContext,
brandsAccessTokenContext,
configContext,
connectionContext,
internationalizationContext,
labelsContext,
registriesContext,
statesContext,
uiContext,
} from "../data/context";
import { labelsContext } from "../data/context";
import {
deviceComboBoxKeys,
getDevices,
@@ -59,6 +47,7 @@ import {
type TargetType,
type TargetTypeFloorless,
} from "../data/target";
import { SubscribeMixin } from "../mixins/subscribe-mixin";
import { isHelperDomain } from "../panels/config/helpers/const";
import { showHelperDetailDialog } from "../panels/config/helpers/show-dialog-helper-detail";
import {
@@ -66,11 +55,7 @@ import {
multiTermSortedSearch,
type FuseWeightedKey,
} from "../resources/fuseMultiTerm";
import type {
HomeAssistant,
HomeAssistantUI,
ValueChangedEvent,
} from "../types";
import type { HomeAssistant, ValueChangedEvent } from "../types";
import { brandsUrl } from "../util/brands-url";
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
import "./ha-button";
@@ -104,7 +89,9 @@ const isTargetType = (value: string): value is TargetType =>
value === "floor";
@customElement("ha-target-picker")
export class HaTargetPicker extends LitElement {
export class HaTargetPicker extends SubscribeMixin(LitElement) {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public value?: HassServiceTargetWithExclude;
@property() public helper?: string;
@@ -170,47 +157,6 @@ export class HaTargetPicker extends LitElement {
@consume({ context: labelsContext, subscribe: true })
private _labelRegistry!: LabelRegistryEntry[];
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HomeAssistant["states"], boolean>({
transformer: function (this: HaTargetPicker, states) {
return !!this._pendingEntityId && !!states?.[this._pendingEntityId];
},
watch: ["_pendingEntityId"],
})
private _pendingEntityLoaded = false;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, boolean | undefined>({
transformer: (ui) => ui?.themes?.darkMode,
})
private _darkMode?: boolean;
@consume({ context: configContext, subscribe: true })
private _config?: ContextType<typeof configContext>;
@consume({ context: apiContext, subscribe: true })
private _api?: ContextType<typeof apiContext>;
@consume({ context: connectionContext, subscribe: true })
private _connection?: ContextType<typeof connectionContext>;
@state()
@consume({ context: brandsAccessTokenContext, subscribe: true })
private _brandsAccessToken?: string;
@query("ha-generic-picker") private _picker?: HaGenericPicker;
@query("ha-generic-picker.exclude") private _excludePicker?: HaGenericPicker;
@@ -221,9 +167,7 @@ export class HaTargetPicker extends LitElement {
private _getDevicesMemoized = memoizeOne(
(
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>,
hass: HomeAssistant,
configEntryLookup: Record<string, ConfigEntry>,
includeDomains?: string[],
includeDeviceClasses?: string[],
@@ -234,13 +178,13 @@ export class HaTargetPicker extends LitElement {
idPrefix?: string
) =>
getDevices({
states,
areas: registries.areas,
devices: registries.devices,
entities: registries.entities,
localize: i18n.localize,
language: i18n.locale.language,
translationMetadata: i18n.translationMetadata,
states: hass.states,
areas: hass.areas,
devices: hass.devices,
entities: hass.entities,
localize: hass.localize,
language: hass.locale.language,
translationMetadata: hass.translationMetadata,
configEntryLookup,
includeDomains,
includeDeviceClasses,
@@ -257,9 +201,7 @@ export class HaTargetPicker extends LitElement {
private _getEntitiesMemoized = memoizeOne(
(
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
i18n: ContextType<typeof internationalizationContext>,
hass: HomeAssistant,
includeDomains?: string[],
excludeDomains?: string[],
entityFilter?: HaEntityPickerEntityFilterFunc,
@@ -270,15 +212,7 @@ export class HaTargetPicker extends LitElement {
value?: string,
idPrefix?: string
) =>
getEntities({
states,
entities: registries.entities,
devices: registries.devices,
areas: registries.areas,
floors: registries.floors,
localize: i18n.localize,
language: i18n.language,
translationMetadata: i18n.translationMetadata,
getEntities(hass, {
includeDomains,
excludeDomains,
entityFilter,
@@ -294,7 +228,7 @@ export class HaTargetPicker extends LitElement {
private _getAreasAndFloorsMemoized = memoizeOne(getAreasAndFloors);
private get _showEntityId() {
return this._config?.userData?.showEntityIdPicker;
return this.hass.userData?.showEntityIdPicker;
}
private _fuseIndexes = {
@@ -314,34 +248,36 @@ export class HaTargetPicker extends LitElement {
@state() private _pendingEntityId?: string;
public willUpdate(changedProps: PropertyValues) {
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this._loadConfigEntries();
}
const devices = this._registries?.devices;
const devicesChanged =
changedProps.has("_registries") &&
devices !==
(
changedProps.get("_registries") as
ContextType<typeof registriesContext> | undefined
)?.devices;
changedProps.has("hass") &&
this.hass.devices !== changedProps.get("hass")?.devices;
if (
(changedProps.has("value") || devicesChanged) &&
devices &&
this.hass &&
this._compositeSplits === undefined &&
!this._loadingCompositeSplits &&
this.value?.device_id &&
ensureArray(this.value.device_id).some((deviceId) => !devices[deviceId])
ensureArray(this.value.device_id).some(
(deviceId) => !this.hass.devices[deviceId]
)
) {
// A referenced device is missing from the registry; it might be a legacy
// composite device that was split. Fetch the split map to offer a fix.
this._loadCompositeSplits();
}
const registriesChanged =
changedProps.has("hass") &&
(devicesChanged ||
this.hass.entities !== changedProps.get("hass")?.entities ||
this.hass.areas !== changedProps.get("hass")?.areas);
if (
changedProps.has("value") ||
changedProps.has("allowExclude") ||
@@ -349,12 +285,18 @@ export class HaTargetPicker extends LitElement {
changedProps.has("deviceFilter") ||
changedProps.has("includeDomains") ||
changedProps.has("includeDeviceClasses") ||
changedProps.has("entityFilter")
changedProps.has("entityFilter") ||
registriesChanged
) {
this._exclusions.resolve();
}
if (this._pendingEntityId && this._pendingEntityLoaded) {
if (
this._pendingEntityId &&
changedProps.has("hass") &&
this.hass.states !== changedProps.get("hass")?.states &&
this.hass.states[this._pendingEntityId]
) {
this._addTarget(this._pendingEntityId, "entity");
this._pendingEntityId = undefined;
}
@@ -511,7 +453,7 @@ export class HaTargetPicker extends LitElement {
return nothing;
}
return html`
<div class="exclusion-list-label">${this._i18n.localize(label)}</div>
<div class="exclusion-list-label">${this.hass.localize(label)}</div>
<ha-list-base>
${items.map(
(item) =>
@@ -544,16 +486,16 @@ export class HaTargetPicker extends LitElement {
.helper=${this.helper}
.sections=${sections}
.notFoundLabel=${this._noTargetFoundLabel}
.emptyLabel=${this._i18n.localize(
.emptyLabel=${this.hass.localize(
"ui.components.target-picker.no_targets"
)}
.selectedSection=${this._selectedSection}
.popoverAnchor=${this._replaceTargetAnchor}
.rowRenderer=${this._rowRenderer(this._brandsAccessToken)}
.rowRenderer=${this._renderRow}
.getItems=${this._getItems}
@value-changed=${this._targetPicked}
@picker-closed=${this._handlePickerClosed}
.addButtonLabel=${this._i18n.localize(
.addButtonLabel=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
.getAdditionalItems=${this._getAdditionalItems}
@@ -568,11 +510,11 @@ export class HaTargetPicker extends LitElement {
.disabled=${this.disabled}
.sections=${sections}
.notFoundLabel=${this._noTargetFoundLabel}
.emptyLabel=${this._i18n.localize(
.emptyLabel=${this.hass.localize(
"ui.components.target-picker.no_targets"
)}
.selectedSection=${this._excludeSection}
.rowRenderer=${this._rowRenderer(this._brandsAccessToken)}
.rowRenderer=${this._renderRow}
.getItems=${this._getExcludeItems}
@value-changed=${this._excludePicked}
>
@@ -587,7 +529,7 @@ export class HaTargetPicker extends LitElement {
.path=${mdiPlaylistMinus}
slot="start"
></ha-svg-icon>
${this._i18n.localize(
${this.hass.localize(
"ui.components.target-picker.exclude_target"
)}
</ha-button>
@@ -603,20 +545,20 @@ export class HaTargetPicker extends LitElement {
return [
{
id: "entity",
label: this._i18n.localize("ui.components.target-picker.type.entities"),
label: this.hass.localize("ui.components.target-picker.type.entities"),
},
{
id: "device",
label: this._i18n.localize("ui.components.target-picker.type.devices"),
label: this.hass.localize("ui.components.target-picker.type.devices"),
},
{
id: "area",
label: this._i18n.localize("ui.components.target-picker.type.areas"),
label: this.hass.localize("ui.components.target-picker.type.areas"),
},
"separator" as const,
{
id: "label",
label: this._i18n.localize("ui.components.target-picker.type.labels"),
label: this.hass.localize("ui.components.target-picker.type.labels"),
},
];
}
@@ -745,7 +687,7 @@ export class HaTargetPicker extends LitElement {
this._excludeSection = section as TargetTypeFloorless | undefined;
return this._getItemsMemoized(
this._i18n,
this.hass.localize,
this._excludeEntityFilter(
this.entityFilter,
this._exclusions.includedEntities
@@ -757,8 +699,7 @@ export class HaTargetPicker extends LitElement {
undefined,
searchString,
this._configEntryLookup,
this._states,
this._registries,
this.hass.entities,
this._excludeSection,
this._excludePickerIncludedDevices(this.value)
);
@@ -875,7 +816,7 @@ export class HaTargetPicker extends LitElement {
domain,
dialogClosedCallback: (item) => {
if (item.entityId) {
if (this._states?.[item.entityId]) {
if (this.hass.states[item.entityId]) {
this._addTarget(item.entityId, "entity");
} else {
this._pendingEntityId = item.entityId;
@@ -962,7 +903,7 @@ export class HaTargetPicker extends LitElement {
this._selectedSection = section as TargetTypeFloorless | undefined;
return this._getItemsMemoized(
this._i18n,
this.hass.localize,
this.entityFilter,
this.deviceFilter,
this.includeDomains,
@@ -971,15 +912,14 @@ export class HaTargetPicker extends LitElement {
this._replaceTarget,
searchString,
this._configEntryLookup,
this._states,
this._registries,
this.hass.entities,
this._selectedSection
);
};
private _getItemsMemoized = memoizeOne(
(
i18n: ContextType<typeof internationalizationContext>,
localize: HomeAssistant["localize"],
entityFilter: this["entityFilter"],
deviceFilter: this["deviceFilter"],
includeDomains: this["includeDomains"],
@@ -988,13 +928,11 @@ export class HaTargetPicker extends LitElement {
replaceTarget: TargetItem | undefined,
searchTerm: string,
configEntryLookup: Record<string, ConfigEntry>,
states: HomeAssistant["states"],
registries: ContextType<typeof registriesContext>,
_entities: HomeAssistant["entities"],
filterType?: TargetTypeFloorless,
// Hidden without hiding their child devices.
hiddenDeviceIds?: string[]
) => {
const localize = i18n.localize;
const replacingEntityId =
replaceTarget?.type === "entity" ? replaceTarget.id : undefined;
const replacingDeviceId =
@@ -1012,9 +950,7 @@ export class HaTargetPicker extends LitElement {
if (!filterType || filterType === "entity") {
let entityItems = this._getEntitiesMemoized(
states,
registries,
i18n,
this.hass,
includeDomains,
undefined,
entityFilter,
@@ -1068,7 +1004,7 @@ export class HaTargetPicker extends LitElement {
...(hiddenDeviceIds ?? []),
...(selectedDeviceIds ?? []),
...(selectedDeviceIds
? Object.values(registries.devices)
? Object.values(this.hass.devices)
.filter(
(device) =>
device.parent_device_id !== null &&
@@ -1079,9 +1015,7 @@ export class HaTargetPicker extends LitElement {
]
: undefined;
let deviceItems = this._getDevicesMemoized(
states,
registries,
i18n,
this.hass,
configEntryLookup,
includeDomains,
includeDeviceClasses,
@@ -1132,11 +1066,11 @@ export class HaTargetPicker extends LitElement {
if (!filterType || filterType === "area") {
let areasAndFloors = this._getAreasAndFloorsMemoized(
states,
registries.floors,
registries.areas,
registries.devices,
registries.entities,
this.hass.states,
this.hass.floors,
this.hass.areas,
this.hass.devices,
this.hass.entities,
memoizeOne((value: AreaFloorValue): string =>
[value.type, value.id].join(SEPARATOR)
),
@@ -1197,10 +1131,10 @@ export class HaTargetPicker extends LitElement {
if (!filterType || filterType === "label") {
let labels = this._getLabelsMemoized(
states,
registries.areas,
registries.devices,
registries.entities,
this.hass.states,
this.hass.areas,
this.hass.devices,
this.hass.entities,
this._labelRegistry,
includeDomains,
undefined,
@@ -1261,32 +1195,30 @@ export class HaTargetPicker extends LitElement {
});
}
private _getAdditionalItems = () =>
this._getCreateItems(this.createDomains, this._i18n.localize);
private _getAdditionalItems = () => this._getCreateItems(this.createDomains);
private _getCreateItems = memoizeOne(
(
createDomains: this["createDomains"],
localize: ContextType<typeof internationalizationContext>["localize"]
) => {
(createDomains: this["createDomains"]) => {
if (!createDomains?.length) {
return [];
}
return createDomains.map((domain) => {
const primary = localize(
const primary = this.hass.localize(
"ui.components.entity.entity-picker.create_helper",
{
domain: isHelperDomain(domain)
? localize(`ui.panel.config.helpers.types.${domain}`)
: domainToName(localize, domain),
? this.hass.localize(`ui.panel.config.helpers.types.${domain}`)
: domainToName(this.hass.localize, domain),
}
);
return {
id: CREATE_ID + domain,
primary: primary,
secondary: localize("ui.components.entity.entity-picker.new_entity"),
secondary: this.hass.localize(
"ui.components.entity.entity-picker.new_entity"
),
icon_path: mdiPlus,
} satisfies EntityComboBoxItem;
});
@@ -1294,24 +1226,18 @@ export class HaTargetPicker extends LitElement {
);
private async _loadConfigEntries() {
if (!this._api) {
return;
}
const configEntries = await getConfigEntries(this._api);
const configEntries = await getConfigEntries(this.hass);
this._configEntryLookup = Object.fromEntries(
configEntries.map((entry) => [entry.entry_id, entry])
);
}
private async _loadCompositeSplits() {
if (!this._api || !this._connection) {
return;
}
this._loadingCompositeSplits = true;
try {
this._compositeSplits = await fetchDeviceCompositeSplits(
this._connection.connection,
this._api.callWS
this.hass.connection,
this.hass.callWS
);
} catch (_err) {
this._compositeSplits = {};
@@ -1336,13 +1262,6 @@ export class HaTargetPicker extends LitElement {
});
}
// A new renderer when the brands token arrives, so open lists redraw icons.
private _rowRenderer = memoizeOne(
(_brandsAccessToken: string | undefined) =>
(item: Parameters<HaTargetPicker["_renderRow"]>[0]) =>
this._renderRow(item)
);
private _renderRow = (
item:
| PickerComboBoxItem
@@ -1362,8 +1281,8 @@ export class HaTargetPicker extends LitElement {
type === "device" && !!(item as DevicePickerItem).is_child;
if (type === "area" || type === "floor" || isChildDeviceRow) {
rtl = computeRTL(
this._i18n.language,
this._i18n.translationMetadata.translations
this.hass.language,
this.hass.translationMetadata.translations
);
hasFloor =
type === "area" && !!(item as FloorComboBoxItem).area?.floor_id;
@@ -1429,9 +1348,9 @@ export class HaTargetPicker extends LitElement {
{
domain: (item as DevicePickerItem).domain!,
type: "icon",
darkOptimized: this._darkMode,
darkOptimized: this.hass.themes.darkMode,
},
this._config?.auth?.data.hassUrl
this.hass.auth.data.hassUrl
)}
/>
`
@@ -1477,7 +1396,7 @@ export class HaTargetPicker extends LitElement {
};
private _noTargetFoundLabel = (search: string) =>
this._i18n.localize("ui.components.target-picker.no_target_found", {
this.hass.localize("ui.components.target-picker.no_target_found", {
term: html`<b>‘${search}’</b>`,
});
@@ -1485,7 +1404,7 @@ export class HaTargetPicker extends LitElement {
caseInsensitiveStringCompare(
(entityA as PickerComboBoxItem).sorting_label!,
(entityB as PickerComboBoxItem).sorting_label!,
this._i18n?.locale.language ?? navigator.language
this.hass?.locale.language ?? navigator.language
);
static styles = css`
+3 -8
View File
@@ -6,7 +6,6 @@ import { customElement, property, query, state } from "lit/decorators";
import type { ContextType } from "@lit/context";
import { consume } from "../common/decorators/consume";
import { fireEvent } from "../common/dom/fire_event";
import { localizeYamlErrorReason } from "../common/translations/localize-yaml-error";
import { copyToClipboard } from "../common/util/copy-clipboard";
import { haStyle } from "../resources/styles";
import { showToast } from "../util/toast";
@@ -181,7 +180,7 @@ export class HaYamlEditor extends LitElement {
let errorMsg: string | undefined;
let yamlError: {
mark?: { position: number; line: number; column: number };
reason?: string;
message?: string;
} | null = null;
if (this._yaml) {
@@ -190,12 +189,8 @@ export class HaYamlEditor extends LitElement {
} catch (err: any) {
// Invalid YAML
isValid = false;
const reason = localizeYamlErrorReason(
this._i18n!.localize,
err.reason
);
yamlError = { mark: err.mark, reason };
errorMsg = `${this._i18n!.localize("ui.components.yaml-editor.error", { reason })}${err.mark ? ` (${this._i18n!.localize("ui.components.yaml-editor.error_location", { line: err.mark.line + 1, column: err.mark.column + 1 })})` : ""}`;
yamlError = err;
errorMsg = `${this._i18n!.localize("ui.components.yaml-editor.error", { reason: err.reason })}${err.mark ? ` (${this._i18n!.localize("ui.components.yaml-editor.error_location", { line: err.mark.line + 1, column: err.mark.column + 1 })})` : ""}`;
}
} else {
parsed = {};
+11 -116
View File
@@ -2,8 +2,6 @@ import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html } from "lit";
import { customElement, property, query } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { keyed } from "lit/directives/keyed";
import { isInteractiveElement } from "../../common/dom/is-interactive-element";
import "../ha-ripple";
import { HaListItemBase } from "./ha-list-item-base";
@@ -17,19 +15,6 @@ import { HaListItemBase } from "./ha-list-item-base";
* roving tabindex, the host is the tab stop and the inner element carries
* `tabindex="-1"`. For a non-interactive row, use `ha-list-item-base`.
*
* Only the headline and supporting text are rendered inside the `<a>` or
* `<button>`, and its hit area is stretched over the whole row. The `start`
* and `end` slots sit next to it, so controls placed there stay separate
* controls for assistive technology. Slotted elements are raised above the
* stretched hit area, except for icons, badges, plain text and empty dividers
* without `tabindex`, so clicks and hover on those reach the row. To keep such
* an element clickable on its own, like a drag handle, give it `z-index: 1`.
*
* Subclasses customize the row with `_renderStart()`, `_renderContent()` and
* `_renderEnd()`. `_renderInner()` is not used.
*
* @csspart base - The row container.
* @csspart control - The inner `<a>` or `<button>`.
* @csspart ripple - The ripple effect element.
*
* @attr {string} href - URL. When set, renders an `<a>` instead of a `<button>`.
@@ -55,27 +40,11 @@ export class HaListItemButton extends HaListItemBase {
this._item?.click();
}
protected override render(): TemplateResult {
return this._renderBase(this._renderContent());
}
protected _renderBase(content: TemplateResult): TemplateResult {
// The ripple binds to #item on connect, so render it after the control and
// recreate it with the control
return html`<div part="base" class="base" @click=${this._handleBaseClick}>
${this._renderStart()}${this._renderControl(content)}${keyed(
`${this.href !== undefined}-${this.interactive}`,
this._renderRipple()
)}${this._renderEnd()}
</div>`;
}
/** Renders the native `<a>` or `<button>` around the row content. */
protected _renderControl(content: TemplateResult): TemplateResult {
protected _renderBase(inner: TemplateResult): TemplateResult {
if (this.href !== undefined) {
return html`<a
part="control"
class="control"
part="base"
class="base interactive"
id="item"
href=${ifDefined(this.disabled ? undefined : this.href)}
target=${ifDefined(this.target)}
@@ -84,18 +53,18 @@ export class HaListItemButton extends HaListItemBase {
tabindex="-1"
aria-disabled=${this.disabled ? "true" : "false"}
>
${content}
${this._renderRipple()}${inner}
</a>`;
}
return html`<button
part="control"
class="control"
part="base"
class="base interactive"
id="item"
type="button"
?disabled=${this.disabled}
tabindex="-1"
>
${content}
${this._renderRipple()}${inner}
</button>`;
}
@@ -107,48 +76,18 @@ export class HaListItemButton extends HaListItemBase {
></ha-ripple>`;
}
// Raised slot content that is not a control, like a wrapper without
// controls, still activates the row
private _handleBaseClick(ev: MouseEvent): void {
const item = this._item;
if (!item || this.disabled) {
return;
}
const path = ev.composedPath();
const baseIndex = path.indexOf(ev.currentTarget as EventTarget);
for (const node of path.slice(0, baseIndex)) {
if (node === item || isInteractiveElement(node)) {
return;
}
}
ev.stopPropagation();
// A copy of the event keeps modifier keys, so links can open in a new tab
item.dispatchEvent(new MouseEvent("click", ev));
}
static styles: CSSResultGroup = [
HaListItemBase.styles,
css`
:host {
cursor: pointer;
--ha-ripple-color: var(--primary-text-color);
/* Smooth the hover when moving between controls in the row */
--ha-ripple-hover-duration: var(--ha-animation-duration-fast);
}
:host([disabled]) {
cursor: default;
}
.base {
isolation: isolate;
}
.control {
display: flex;
align-items: center;
align-self: stretch;
flex: 1 1 auto;
min-width: 0;
margin: 0;
padding: 0;
.base.interactive {
width: 100%;
border: none;
background: transparent;
color: inherit;
@@ -158,52 +97,8 @@ export class HaListItemButton extends HaListItemBase {
appearance: none;
cursor: inherit;
}
/* Stretch the hit area of the control over the whole row */
.control::before {
content: "";
position: absolute;
inset: 0;
border-radius: var(--ha-list-item-focus-radius);
}
.control:focus-visible {
outline: none;
}
.control:focus-visible::before {
outline: var(--ha-list-item-focus-width) solid var(--ha-color-focus);
outline-offset: var(--ha-list-item-focus-offset);
}
/*
* Slotted content is painted above the hit area, so it can be clicked.
* Icons, badges, text and empty dividers go below it, so clicks on
* them reach the row.
* Some icons are positioned, so they need a negative z-index.
*/
::slotted([slot="start"]),
::slotted([slot="end"]) {
position: relative;
z-index: 1;
}
::slotted(
:is(
ha-svg-icon,
ha-icon,
ha-icon-next,
ha-state-icon,
ha-domain-icon,
ha-floor-icon,
ha-spinner,
ha-progress-ring,
ha-user-badge,
ha-person-badge,
ha-tree-indicator,
ha-app-icon,
state-badge,
img,
span,
div:empty
):not([tabindex])
) {
z-index: -1;
:host([disabled]) .base.interactive {
color: var(--disabled-text-color);
}
`,
];
+11 -13
View File
@@ -84,21 +84,19 @@ export class HaRowItem extends LitElement {
}
protected _renderInner(): TemplateResult {
return html`
${this._renderStart()}${this._renderContent()}${this._renderEnd()}
`;
}
protected _renderContent(): TemplateResult {
const hasContent = this._slotController.test("content");
return html`<div part="content" class="content">
${
hasContent
? html`<slot name="content"></slot>`
: this._renderDefaultContent()
}
</div>`;
return html`
${this._renderStart()}
<div part="content" class="content">
${
hasContent
? html`<slot name="content"></slot>`
: this._renderDefaultContent()
}
</div>
${this._renderEnd()}
`;
}
protected _renderStart(): TemplateResult {
@@ -1,6 +1,6 @@
import type { ContextType } from "@lit/context";
import type { LitVirtualizer } from "@lit-labs/virtualizer";
import { grid } from "@lit-labs/virtualizer/layouts/grid";
import type { ContextType } from "@lit/context";
import {
mdiArrowUpRight,
@@ -19,6 +19,7 @@ import {
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 { transform } from "../../common/decorators/transform";
import { fireEvent } from "../../common/dom/fire_event";
@@ -55,6 +56,7 @@ import {
} from "../../data/media_source";
import { isTTSMediaSource } from "../../data/tts";
import { showAlertDialog } from "../../dialogs/generic/show-dialog-box";
import { getWsErrorMessage } from "../../util/ws-error";
import { panelIsReady } from "../../layouts/panel-ready";
import { haStyle, haStyleScrollbar } from "../../resources/styles";
import { loadVirtualizer } from "../../resources/virtualizer";
@@ -63,7 +65,6 @@ import type {
HomeAssistantInternationalization,
} from "../../types";
import { documentationUrlForVersion } from "../../util/documentation-url";
import { getWsErrorMessage } from "../../util/ws-error";
import "../entity/ha-entity-picker";
import "../ha-alert";
import "../ha-button";
@@ -72,22 +73,18 @@ import "../ha-dropdown";
import type { HaDropdownSelectEvent } from "../ha-dropdown";
import "../ha-dropdown-item";
import "../ha-icon-button";
import "../ha-list";
import "../ha-list-item";
import "../input/ha-input-search";
import type { HaInputSearch } from "../input/ha-input-search";
import "./ha-media-browser-thumbnail";
import "../ha-spinner";
import "../ha-svg-icon";
import "../ha-tooltip";
import "../input/ha-input-search";
import type { HaInputSearch } from "../input/ha-input-search";
import { HaListItemButton } from "../item/ha-list-item-button";
import "../list/ha-list-virtualized";
import type {
HaListVirtualized,
HaListVirtualizedItem,
} from "../list/ha-list-virtualized";
import "./ha-browse-media-manual";
import type { ManualMediaPickedEvent } from "./ha-browse-media-manual";
import "./ha-browse-media-tts";
import type { TtsMediaPickedEvent } from "./ha-browse-media-tts";
import "./ha-media-browser-thumbnail";
declare global {
interface HASSDomEvents {
@@ -110,115 +107,6 @@ export interface MediaPlayerItemId {
type MediaClass = MediaPlayerItem["media_class"];
type MediaBrowseListRow =
| (HaListVirtualizedItem & {
type: "item";
item: MediaPlayerItem;
})
| (HaListVirtualizedItem & {
type: "not-shown";
count: number;
});
@customElement("ha-media-player-browse-list-item")
export class HaMediaPlayerBrowseListItem extends HaListItemButton {
@property() public thumbnail?: string;
// The "not shown" row is plain text, not a button
protected override _renderControl(content: TemplateResult): TemplateResult {
if (!this.interactive) {
return content;
}
return super._renderControl(content);
}
// Always reserve the graphic, so titles line up across rows
protected override _renderStart(): TemplateResult {
return html`<div part="start" class="start">
<div class="graphic">
${
this.thumbnail
? html`<ha-media-browser-thumbnail
.url=${this.thumbnail}
></ha-media-browser-thumbnail>`
: nothing
}
<slot name="start"></slot>
</div>
</div>`;
}
static styles: CSSResultGroup = [
HaListItemButton.styles,
css`
:host {
direction: var(--direction);
--ha-row-item-padding-block: 0;
--ha-row-item-min-height: 48px;
}
:host(.show-images) {
--ha-row-item-padding-block: var(--ha-space-1);
--ha-row-item-min-height: 64px;
}
:host(.not-shown) {
font-style: italic;
color: var(--secondary-text-color);
cursor: default;
}
::slotted(ha-svg-icon) {
color: var(--secondary-text-color);
}
.graphic {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border-radius: var(--ha-border-radius-sm);
overflow: hidden;
}
:host(.show-images) .graphic {
width: 56px;
height: 56px;
}
ha-media-browser-thumbnail {
position: absolute;
inset: 0;
}
::slotted(.play) {
position: absolute;
inset: 0;
margin: auto;
width: 40px;
height: 40px;
opacity: 0;
transition: all 0.5s;
background-color: rgba(var(--rgb-card-background-color), 0.5);
border-radius: var(--ha-border-radius-circle);
--ha-icon-button-size: 40px;
}
:host(:hover) ::slotted(.play) {
opacity: 1;
color: var(--primary-text-color);
}
::slotted(.play.show) {
opacity: 1;
background-color: transparent;
}
`,
];
}
/** Folders with at least this many items get a filter field when their source cannot search. */
const FILTER_MIN_CHILDREN = 10;
@@ -307,10 +195,6 @@ export class HaMediaPlayerBrowse extends LitElement {
@query("lit-virtualizer") private _virtualizer?: LitVirtualizer;
@query("ha-list-virtualized") private _list?: HaListVirtualized;
private _listScroller?: HTMLElement;
private _observed = false;
private _headerOffsetHeight = 0;
@@ -321,9 +205,6 @@ export class HaMediaPlayerBrowse extends LitElement {
public connectedCallback(): void {
super.connectedCallback();
if (this.hasUpdated) {
this._observeListScroll();
}
this.updateComplete.then(() => this._attachResizeObserver());
}
@@ -332,8 +213,6 @@ export class HaMediaPlayerBrowse extends LitElement {
if (this._resizeObserver) {
this._resizeObserver.disconnect();
}
this._listScroller?.removeEventListener("scroll", this._listScrolled);
this._listScroller = undefined;
}
public async refresh() {
@@ -519,8 +398,6 @@ export class HaMediaPlayerBrowse extends LitElement {
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
this._observeListScroll();
if (changedProps.has("_scrolled") || changedProps.has("_currentItem")) {
// Re-measure across frames rather than once: the search input sizes
// asynchronously, so a single measurement can be too small and the
@@ -631,6 +508,7 @@ export class HaMediaPlayerBrowse extends LitElement {
)
: [];
const mediaClass = MediaClassBrowserSettings[currentItem.media_class];
const childrenMediaClass = currentItem.children_media_class
? MediaClassBrowserSettings[currentItem.children_media_class]
: MediaClassBrowserSettings.directory;
@@ -639,21 +517,6 @@ export class HaMediaPlayerBrowse extends LitElement {
currentItem?.can_play ||
(currentItem && this.accept?.includes("directory"));
const listRows: MediaBrowseListRow[] = children.map((item, index) => ({
id: `${index}:${item.media_content_id}`,
type: "item",
interactive: true,
item,
}));
if (notShown) {
listRows.push({
id: "not-shown",
type: "not-shown",
interactive: false,
count: notShown,
});
}
return html`
${
canPickCurrent || showSearch || showFilter
@@ -873,13 +736,39 @@ export class HaMediaPlayerBrowse extends LitElement {
}
`
: html`
<ha-list-virtualized
.rows=${listRows}
.rowRenderer=${this._renderListItem}
@ha-list-visibility-changed=${
this._observeListScroll
<ha-list>
<lit-virtualizer
scroller
.items=${children}
style=${styleMap({
height: `${children.length * 72 + 26}px`,
})}
class="ha-scrollbar"
.renderItem=${this._renderListItem}
></lit-virtualizer>
${
notShown
? html`
<ha-list-item
noninteractive
class="not-shown"
.graphic=${
mediaClass.show_list_images
? "medium"
: "avatar"
}
>
<span class="title">
${this._i18n.localize(
"ui.components.media-browser.not_shown",
{ count: notShown }
)}
</span>
</ha-list-item>
`
: ""
}
></ha-list-virtualized>
</ha-list>
`
}
</div>
@@ -1021,7 +910,6 @@ export class HaMediaPlayerBrowse extends LitElement {
private _handleFilterInput(ev: InputEvent): void {
this._filterQuery = (ev.target as HaInputSearch).value ?? "";
this._virtualizer?.scrollTo(0, 0);
this._list?.scrollElement?.scrollTo(0, 0);
this._content?.scrollTo(0, 0);
}
@@ -1179,64 +1067,63 @@ export class HaMediaPlayerBrowse extends LitElement {
`;
};
private _renderListItem = (row: HaListVirtualizedItem): TemplateResult => {
const listRow = row as MediaBrowseListRow;
const mediaClass =
MediaClassBrowserSettings[this._currentItem!.media_class];
const showImages = mediaClass.show_list_images === true;
if (listRow.type === "not-shown") {
return html`
<ha-media-player-browse-list-item
class=${classMap({ "not-shown": true, "show-images": showImages })}
.interactive=${false}
>
<span slot="headline" class="title">
${this._i18n.localize("ui.components.media-browser.not_shown", {
count: listRow.count,
})}
</span>
</ha-media-player-browse-list-item>
`;
}
const child = listRow.item;
const showImage = showImages && !!child.thumbnail;
private _renderListItem = (child: MediaPlayerItem): TemplateResult => {
const currentItem = this._currentItem;
const mediaClass = MediaClassBrowserSettings[currentItem!.media_class];
const showImage = mediaClass.show_list_images && !!child.thumbnail;
return html`
<ha-media-player-browse-list-item
<ha-list-item
@click=${this._childClicked}
.item=${child}
class=${classMap({ "show-images": showImages })}
.thumbnail=${showImage ? child.thumbnail : undefined}
.graphic=${mediaClass.show_list_images ? "medium" : "avatar"}
>
${
child.can_play
? html`<ha-icon-button
slot="start"
class=${classMap({ play: true, show: !showImage })}
.item=${child}
.label=${this._i18n.localize(
`ui.components.media-browser.${this.action}-media`
)}
.path=${this.action === "play" ? mdiPlay : mdiPlus}
@click=${this._actionClicked}
></ha-icon-button>`
: showImage
? nothing
: html`<ha-svg-icon
slot="start"
.path=${
MediaClassBrowserSettings[
child.media_class === "directory"
? child.children_media_class || child.media_class
: child.media_class
].icon
}
></ha-svg-icon>`
!showImage && !child.can_play
? html`<ha-svg-icon
.path=${
MediaClassBrowserSettings[
child.media_class === "directory"
? child.children_media_class || child.media_class
: child.media_class
].icon
}
slot="graphic"
></ha-svg-icon>`
: html`<div
class=${classMap({
graphic: true,
thumbnail: mediaClass.show_list_images === true,
})}
slot="graphic"
>
${
showImage
? html`<ha-media-browser-thumbnail
.url=${child.thumbnail}
></ha-media-browser-thumbnail>`
: nothing
}
${
child.can_play
? html`<ha-icon-button
class="play ${classMap({
show:
!mediaClass.show_list_images || !child.thumbnail,
})}"
.item=${child}
.label=${this._i18n.localize(
`ui.components.media-browser.${this.action}-media`
)}
.path=${this.action === "play" ? mdiPlay : mdiPlus}
@click=${this._actionClicked}
></ha-icon-button>`
: nothing
}
</div>`
}
<span slot="headline" class="title">${child.title}</span>
</ha-media-player-browse-list-item>
<span class="title">${child.title}</span>
</ha-list-item>
`;
};
@@ -1429,31 +1316,9 @@ export class HaMediaPlayerBrowse extends LitElement {
requestAnimationFrame(animate);
}
// The list scrolls inside its virtualizer, which only exists once the list
// has rendered its rows
private _observeListScroll(): void {
const scroller = this._list?.scrollElement;
if (scroller === this._listScroller) {
return;
}
this._listScroller?.removeEventListener("scroll", this._listScrolled);
scroller?.addEventListener("scroll", this._listScrolled, {
passive: true,
});
this._listScroller = scroller;
// The new scroller starts at the top, like the grid after the list
if (!scroller) {
this.scrolled = false;
}
}
private _listScrolled = (ev: Event): void => {
this._scroll(ev);
};
@eventOptions({ passive: true })
private _scroll(ev: Event): void {
const content = this._listScroller ?? (ev.currentTarget as HTMLElement);
const content = ev.currentTarget as HTMLDivElement;
if (!this.scrolled && content.scrollTop > this._headerOffsetHeight) {
this.scrolled = true;
} else if (this.scrolled && content.scrollTop < this._headerOffsetHeight) {
@@ -1664,14 +1529,23 @@ export class HaMediaPlayerBrowse extends LitElement {
/* ============= CHILDREN ============= */
ha-list-virtualized {
height: calc(100% - 10px);
ha-list {
--mdc-list-vertical-padding: 0;
--mdc-list-item-graphic-margin: 0;
--mdc-theme-text-icon-on-background: var(--secondary-text-color);
margin-top: 10px;
}
ha-list-virtualized::part(base) {
gap: 0;
padding: 0;
ha-list li:last-child {
display: none;
}
ha-list li[divider] {
border-bottom-color: var(--divider-color);
}
ha-list-item {
width: 100%;
}
div.children {
@@ -1806,6 +1680,45 @@ export class HaMediaPlayerBrowse extends LitElement {
padding-left: 16px;
}
ha-list-item .graphic {
position: relative;
border-radius: var(--ha-border-radius-sm);
overflow: hidden;
line-height: initial;
}
ha-list-item .graphic ha-media-browser-thumbnail {
position: absolute;
inset: 0;
}
ha-list-item .graphic .play {
position: absolute;
inset: 0;
margin: auto;
opacity: 0;
transition: all 0.5s;
background-color: rgba(var(--rgb-card-background-color), 0.5);
border-radius: var(--ha-border-radius-circle);
--ha-icon-button-size: 40px;
}
ha-list-item:hover .graphic .play {
opacity: 1;
color: var(--primary-text-color);
}
ha-list-item .graphic .play.show {
opacity: 1;
background-color: transparent;
}
ha-list-item .title {
margin-left: 16px;
margin-inline-start: 16px;
margin-inline-end: initial;
}
/* ============= Narrow ============= */
:host([narrow]) {
@@ -1945,6 +1858,5 @@ export class HaMediaPlayerBrowse extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-media-player-browse": HaMediaPlayerBrowse;
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
}
}
@@ -1,20 +1,11 @@
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { ensureArray } from "../../../common/array/ensure-array";
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 type { LocalizeFunc } from "../../../common/translations/localize";
import {
apiContext,
entitiesContext,
statesContext,
} from "../../../data/context";
import type { DeviceRegistryEntry } from "../../../data/device/device_registry";
import { getDeviceIntegrationLookup } from "../../../data/device/device_registry";
import type { HaEntityPickerEntityFilterFunc } from "../../../data/entity/entity";
@@ -42,16 +33,7 @@ import type { TargetDetailsDialogParams } from "./show-dialog-target-details";
@customElement("ha-dialog-target-details")
class DialogTargetDetails extends LitElement implements HassDialog {
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: entitiesContext, subscribe: true })
private _entities!: ContextType<typeof entitiesContext>;
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: TargetDetailsDialogParams;
@@ -68,8 +50,8 @@ class DialogTargetDetails extends LitElement implements HassDialog {
private _exclusionsRequest = 0;
private _deviceIntegrationLookup = memoizeOne(
(entities: HomeAssistant["entities"] | null) =>
getDeviceIntegrationLookup(Object.values(entities ?? {}))
(entities: HomeAssistant["entities"]) =>
getDeviceIntegrationLookup(Object.values(entities))
);
public showDialog(params: TargetDetailsDialogParams): void {
@@ -77,17 +59,8 @@ class DialogTargetDetails extends LitElement implements HassDialog {
this._initialExclusions = params.exclusions ?? [];
this._exclusions = this._initialExclusions;
this._opened = true;
}
protected willUpdate(changedProperties: PropertyValues): void {
super.willUpdate(changedProperties);
if (
changedProperties.has("_params") &&
this._params &&
!this._params.exclusions &&
this._params.exclude
) {
this._resolveExclusions(this._params);
if (!params.exclusions && params.exclude) {
this._resolveExclusions(params);
}
}
@@ -96,7 +69,7 @@ class DialogTargetDetails extends LitElement implements HassDialog {
let exclusions: TargetExclusion[];
try {
exclusions = await resolveItemExclusions(
this._api.callWS,
this.hass,
{ type: params.type, id: params.itemId },
params.exclude,
params.selector
@@ -155,8 +128,8 @@ class DialogTargetDetails extends LitElement implements HassDialog {
private async _loadEntitySources(): Promise<void> {
try {
this._entitySources = await fetchEntitySourcesWithCache(
this._api.callWS,
this._states ?? {}
this.hass.callWS,
this.hass.states
);
} catch (err) {
// eslint-disable-next-line no-console
@@ -182,7 +155,7 @@ class DialogTargetDetails extends LitElement implements HassDialog {
return true;
}
const deviceIntegrations = this._hasIntegration({ target })
? this._deviceIntegrationLookup(this._entities)
? this._deviceIntegrationLookup(this.hass.entities)
: undefined;
return ensureArray(target.device).some((d) =>
filterSelectorDevices(d, device, deviceIntegrations)
@@ -244,19 +217,19 @@ class DialogTargetDetails extends LitElement implements HassDialog {
return html`
<ha-adaptive-dialog
.open=${this._opened}
header-title=${this._localize(
header-title=${this.hass.localize(
"ui.components.target-picker.target_details"
)}
@closed=${this._dialogClosed}
>
<div class="type-wrapper">
<div class="type-label">
${this._localize(
${this.hass.localize(
`ui.components.target-picker.type.${this._params.type}`
)}
</div>
<ha-list-base
.ariaLabel=${`${this._localize(`ui.components.target-picker.type.${this._params.type}`)}: ${this._params.title}`}
.ariaLabel=${`${this.hass.localize(`ui.components.target-picker.type.${this._params.type}`)}: ${this._params.title}`}
wrap-focus
>
${
@@ -289,10 +262,10 @@ class DialogTargetDetails extends LitElement implements HassDialog {
appearance="plain"
@click=${this.closeDialog}
>
${this._localize("ui.common.cancel")}
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button slot="primaryAction" @click=${this._apply}>
${this._localize("ui.common.apply")}
${this.hass.localize("ui.common.apply")}
</ha-button>
</ha-dialog-footer>
`
@@ -3,24 +3,14 @@ import memoizeOne from "memoize-one";
import {
consumeContext,
ContextController,
ContextSubscriptionController,
} from "../../common/decorators/consume";
import {
apiContext,
registriesContext,
statesContext,
} from "../../data/context";
import type { HaEntityPickerEntityFilterFunc } from "../../data/entity/entity";
import {
explainTarget,
type HassServiceTargetWithExclude,
type TargetItem,
} from "../../data/target";
import type {
HomeAssistant,
HomeAssistantApi,
HomeAssistantRegistries,
} from "../../types";
import type { HomeAssistant } from "../../types";
import type { HaDevicePickerDeviceFilterFunc } from "../device/ha-device-picker";
import { filterTargetEntries } from "./filter-target-entries";
import { targetExpandGroupContext } from "./target-expand-group-context";
@@ -36,6 +26,7 @@ import {
export type TargetExclusionsHost = ReactiveControllerHost &
HTMLElement & {
hass: HomeAssistant;
value?: HassServiceTargetWithExclude;
allowExclude: boolean;
primaryEntitiesOnly?: boolean;
@@ -64,31 +55,11 @@ export class TargetExclusionsController extends ContextController {
@consumeContext({ context: targetExpandGroupContext, subscribe: true })
private _expandGroup?: boolean;
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries;
@consumeContext({
context: apiContext,
subscribe: true,
transform: (api) => api?.callWS,
})
private _callWS?: HomeAssistantApi["callWS"];
private _states?: HomeAssistant["states"] | null;
private _request = 0;
constructor(host: TargetExclusionsHost) {
super(host);
this._host = host;
// States change all the time, so they only resolve again once loaded.
new ContextSubscriptionController(host, statesContext, (states) => {
const loaded = !this._states && !!states;
this._states = states;
if (loaded) {
this.resolve();
}
});
}
protected contextUpdated() {
@@ -107,9 +78,9 @@ export class TargetExclusionsController extends ContextController {
*/
public async resolve({ force = false }: { force?: boolean } = {}) {
const request = ++this._request;
const { value, allowExclude } = this._host;
const { hass, value, allowExclude } = this._host;
if (
!this._ready ||
!hass ||
!value ||
(!force &&
!hasIncludedTargets(value.exclude) &&
@@ -169,7 +140,7 @@ export class TargetExclusionsController extends ContextController {
item: TargetItem
): Promise<TargetExclusion | undefined> {
const { value } = this._host;
if (!this._ready || !value) {
if (!value) {
return undefined;
}
const explained = await this._explain({
@@ -181,19 +152,9 @@ export class TargetExclusionsController extends ContextController {
]?.[0];
}
private get _ready(): boolean {
return !!(
this._callWS &&
this._states &&
this._registries?.entities &&
this._registries.devices &&
this._registries.areas
);
}
private _explain(target: HassServiceTargetWithExclude) {
return explainTarget(
this._callWS!,
this._host.hass.callWS,
target,
this.expandGroup,
this._host.primaryEntitiesOnly ?? true
@@ -209,9 +170,8 @@ export class TargetExclusionsController extends ContextController {
// What the picker's filters leave of a target, narrowed like the target's
// row, so what an exclusion takes out matches what the row counts.
private _keeps(): TargetNarrowing {
const states = this._states!;
const { entities, devices, areas } = this._registries!;
const {
hass,
deviceFilter,
entityFilter,
includeDomains,
@@ -220,10 +180,10 @@ export class TargetExclusionsController extends ContextController {
} = this._host;
return (include) =>
filterTargetEntries(
states,
entities,
devices,
areas,
hass.states,
hass.entities,
hass.devices,
hass.areas,
include,
{
referenced_areas: include.referenced_areas,
@@ -145,7 +145,7 @@ export const computeExclusionsPerTarget = (
* `expandGroup` follows what the target is used for.
*/
export const resolveItemExclusions = async (
callWS: HomeAssistant["callWS"],
hass: HomeAssistant,
item: TargetItem,
exclude: HassServiceTarget | undefined,
primaryEntitiesOnly?: boolean,
@@ -155,7 +155,7 @@ export const resolveItemExclusions = async (
return [];
}
const explained = await explainTarget(
callWS,
hass.callWS,
{ [`${item.type}_id`]: [item.id], exclude },
expandGroup,
primaryEntitiesOnly
+4 -10
View File
@@ -220,30 +220,24 @@ export class ConfigEntryStream {
private _entries: ConfigEntry[] = [];
processMessage(message: ConfigEntryUpdate[]) {
let entries =
message.length === 0 ||
message.some((configEntry) => configEntry.type === null)
? []
: [...this._entries];
message.forEach((configEntry) => {
if (configEntry.type === null || configEntry.type === "added") {
entries.push(configEntry.entry);
this._entries.push(configEntry.entry);
return;
}
if (configEntry.type === "removed") {
entries = entries.filter(
this._entries = this._entries.filter(
(entry) => entry.entry_id !== configEntry.entry.entry_id
);
return;
}
if (configEntry.type === "updated") {
const newEntry = configEntry.entry;
entries = entries.map((entry) =>
this._entries = this._entries.map((entry) =>
entry.entry_id === newEntry.entry_id ? newEntry : entry
);
}
});
this._entries = entries;
return entries;
return this._entries;
}
}
-128
View File
@@ -1,128 +0,0 @@
import type { HassEntities } from "home-assistant-js-websocket";
import type { ConfigEntry } from "./config_entries";
import type { DataEntryFlowProgress } from "./data_entry_flow";
import type { EntityRegistryEntry } from "./entity/entity_registry";
import type { IntegrationSetup } from "./integration";
import type { RepairsIssue } from "./repairs";
import type { LoggedError } from "./system_log";
import { getLoggedErrorIntegration } from "./system_log";
export type HealthStatus = "ok" | "warning" | "error" | "info";
export type OverallHealthStatus = Exclude<HealthStatus, "info">;
export interface ConfigEntryHealth {
status: OverallHealthStatus;
state: HealthStatus;
entities: {
status: HealthStatus;
total: number;
unavailable: EntityRegistryEntry[];
};
repairs: { status: HealthStatus; issues: RepairsIssue[] };
logs: { status: HealthStatus; errors: number; warnings: number };
flows: { status: HealthStatus; flows: DataEntryFlowProgress[] };
setupSeconds?: number;
}
const ATTENTION_SOURCES = ["reauth", "reconfigure"];
const STATE_STATUS: Record<ConfigEntry["state"], HealthStatus> = {
loaded: "ok",
setup_in_progress: "info",
unload_in_progress: "info",
not_loaded: "info",
setup_retry: "warning",
setup_error: "error",
migration_error: "error",
failed_unload: "error",
};
const worst = (statuses: HealthStatus[]): OverallHealthStatus =>
statuses.includes("error")
? "error"
: statuses.includes("warning")
? "warning"
: "ok";
export const computeConfigEntryHealth = (
entry: ConfigEntry,
entities: EntityRegistryEntry[],
states: HassEntities,
issues: RepairsIssue[],
log: LoggedError[],
flows: DataEntryFlowProgress[],
setups: IntegrationSetup[],
// Library loggers from the manifest, so dependency errors count too.
loggers: string[] = []
): ConfigEntryHealth => {
const enabled = entities.filter((entity) => !entity.disabled_by);
// Entities without a state yet (e.g. while the entry is not loaded) count as unavailable.
const unavailable = enabled.filter(
(entity) =>
!states[entity.entity_id] ||
states[entity.entity_id].state === "unavailable"
);
const entryIssues = issues.filter(
(issue) =>
!issue.ignored && (issue.issue_domain ?? issue.domain) === entry.domain
);
const entryLog = log.filter(
(item) =>
getLoggedErrorIntegration(item) === entry.domain ||
loggers.some(
(logger) => item.name === logger || item.name.startsWith(`${logger}.`)
)
);
const sumCount = (levels: LoggedError["level"][]) =>
entryLog
.filter((item) => levels.includes(item.level))
.reduce((total, item) => total + item.count, 0);
const errors = sumCount(["error", "critical"]);
const warnings = sumCount(["warning"]);
const entryFlows = flows.filter(
(flow) =>
flow.handler === entry.domain &&
flow.context.entry_id === entry.entry_id &&
ATTENTION_SOURCES.includes(flow.context.source)
);
// A disabled entry that failed to unload still needs a restart.
const state: HealthStatus =
entry.disabled_by && entry.state !== "failed_unload"
? "info"
: STATE_STATUS[entry.state];
const health: ConfigEntryHealth = {
status: "ok",
state,
entities: {
status: entry.disabled_by || !unavailable.length ? "ok" : "warning",
total: enabled.length,
unavailable,
},
repairs: {
status: entryIssues.some((issue) => issue.severity !== "warning")
? "error"
: entryIssues.length
? "warning"
: "ok",
issues: entryIssues,
},
logs: {
status: errors ? "error" : warnings ? "warning" : "ok",
errors,
warnings,
},
flows: { status: entryFlows.length ? "error" : "ok", flows: entryFlows },
setupSeconds: setups.find((setup) => setup.domain === entry.domain)
?.seconds,
};
health.status = worst([
state,
health.entities.status,
health.repairs.status,
health.logs.status,
health.flows.status,
]);
return health;
};
+7 -7
View File
@@ -1,6 +1,6 @@
import type { Connection } from "home-assistant-js-websocket";
import type { LocalizeFunc } from "../common/translations/localize";
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
import type {
DataEntryFlowProgress,
DataEntryFlowStep,
@@ -30,11 +30,11 @@ const HEADERS = {
};
export const createConfigFlow = (
callApi: HomeAssistant["callApi"],
hass: HomeAssistant,
handler: string,
entry_id?: string
) =>
callApi<DataEntryFlowStep>(
hass.callApi<DataEntryFlowStep>(
"POST",
"config/config_entries/flow",
{
@@ -53,11 +53,11 @@ export const fetchConfigFlow = (hass: HomeAssistant, flowId: string) =>
);
export const handleConfigFlowStep = (
callApi: HomeAssistant["callApi"],
hass: HomeAssistant,
flowId: string,
data: Record<string, any>
) =>
callApi<DataEntryFlowStep>(
hass.callApi<DataEntryFlowStep>(
"POST",
`config/config_entries/flow/${flowId}`,
data,
@@ -78,10 +78,10 @@ export const deleteConfigFlow = (
// The backend indexes a single key, and only these two exist.
export const getConfigFlowHandlers = (
callApi: HomeAssistantApi["callApi"],
hass: HomeAssistant,
type?: "helper" | "integration"
) =>
callApi<string[]>(
hass.callApi<string[]>(
"GET",
`config/config_entries/flow_handlers${type ? `?type=${type}` : ""}`
);
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
export interface Counter {
id: string;
@@ -25,10 +25,10 @@ export const fetchCounter = (hass: HomeAssistant) =>
hass.callWS<Counter[]>({ type: "counter/list" });
export const createCounter = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: CounterMutableParams
) =>
callWS<Counter>({
hass.callWS<Counter>({
type: "counter/create",
...values,
});
+1 -10
View File
@@ -5,17 +5,8 @@ export interface DataTableFilter {
export type DataTableFilters = Record<string, DataTableFilter>;
export interface FloorAreasFilterValue {
floors?: string[];
areas?: string[];
no_area?: boolean;
}
export type DataTableFiltersValue =
| string[]
| Record<"key" | string, string[]>
| FloorAreasFilterValue
| undefined;
string[] | Record<"key" | string, string[]> | undefined;
export type DataTableFiltersValues = Record<string, DataTableFiltersValue>;
+3 -3
View File
@@ -1,6 +1,6 @@
import type { Connection } from "home-assistant-js-websocket";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import type { HomeAssistant, HomeAssistantApi } from "../../types";
import type { HomeAssistant } from "../../types";
import type { ConfigEntry } from "../config_entries";
import type {
EntityRegistryDisplayEntry,
@@ -231,11 +231,11 @@ export const devicesInArea = (devices: DeviceRegistryEntry[], areaId: string) =>
devices.filter((device) => device.area_id === areaId);
export const updateDeviceRegistryEntry = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
deviceId: string,
updates: Partial<DeviceRegistryEntryMutableParams>
) =>
callWS<DeviceRegistryEntry>({
hass.callWS<DeviceRegistryEntry>({
type: "config/device_registry/update",
device_id: deviceId,
...updates,
+3 -81
View File
@@ -345,41 +345,25 @@ const ENERGY_DEVICE_NAME = [
{ type: "device" },
] satisfies EntityNameItem[];
const ENERGY_DEVICE_ENTITY_NAME = [
{ type: "parent_device" },
{ type: "device" },
{ type: "entity" },
] satisfies EntityNameItem[];
/**
* Display name of an individual device. A name set by the user always wins;
* otherwise the device is named like an entity without the entity part, so
* the energy and power sensors of one device share a name. Entities without a
* device and statistics without an entity keep the statistic label.
*
* `includeEntityName` adds the entity name back for devices that would
* otherwise share a name with another device in the same list, see
* `computeAmbiguousEnergyDevices`.
*/
export const computeEnergyLabel = (
states: HomeAssistant["states"],
formatEntityName: HomeAssistant["formatEntityName"],
statisticId: string,
statisticsMetaData?: StatisticsMetaData,
customName?: string,
includeEntityName = false
customName?: string
): string => {
if (customName) {
return customName;
}
const entity = states[statisticId];
const deviceName =
entity &&
formatEntityName(
entity,
includeEntityName ? ENERGY_DEVICE_ENTITY_NAME : ENERGY_DEVICE_NAME
);
const deviceName = entity && formatEntityName(entity, ENERGY_DEVICE_NAME);
if (deviceName) {
return deviceName;
}
@@ -405,61 +389,6 @@ export const computeEnergyStatisticArea = (
return area ? computeAreaName(area) : undefined;
};
/**
* Statistic ids of the devices that would share their label with another
* device in the same list, which happens when one device has several meters of
* the same type. Those are named with the entity name as well, so they stay
* apart in the charts. Lists hold one type of device, so an energy meter and a
* water meter of one device never collide.
*/
export const computeAmbiguousEnergyDevices = (
states: HomeAssistant["states"],
formatEntityName: HomeAssistant["formatEntityName"],
devices: Partial<DeviceConsumptionEnergyPreference>[],
statisticKey: "stat_consumption" | "stat_rate" = "stat_consumption"
): Set<string> => {
const statisticIdsByLabel = new Map<string, Set<string>>();
const named = new Set<string>();
for (const device of devices) {
const statisticId = device[statisticKey];
if (!statisticId) {
continue;
}
const entity = states[statisticId];
// A name set by the user is the label, so it counts towards a collision,
// but it is never the one that gives way. Statistics named after their
// entity or their metadata are distinct enough already.
const label =
device.name || (entity && formatEntityName(entity, ENERGY_DEVICE_NAME));
if (!label) {
continue;
}
if (device.name) {
named.add(statisticId);
}
const statisticIds = statisticIdsByLabel.get(label);
if (statisticIds) {
statisticIds.add(statisticId);
} else {
statisticIdsByLabel.set(label, new Set([statisticId]));
}
}
const ambiguous = new Set<string>();
for (const statisticIds of statisticIdsByLabel.values()) {
if (statisticIds.size > 1) {
for (const statisticId of statisticIds) {
if (!named.has(statisticId)) {
ambiguous.add(statisticId);
}
}
}
}
return ambiguous;
};
/**
* Device labels keyed by statistic id. Cards that show live power or flow
* key their nodes by `stat_rate` instead of `stat_consumption`; devices
@@ -473,12 +402,6 @@ export const computeEnergyDeviceLabels = (
statisticKey: "stat_consumption" | "stat_rate" = "stat_consumption"
): Record<string, string> => {
const labels: Record<string, string> = {};
const ambiguous = computeAmbiguousEnergyDevices(
states,
formatEntityName,
devices,
statisticKey
);
for (const device of devices) {
const statisticId = device[statisticKey];
@@ -488,8 +411,7 @@ export const computeEnergyDeviceLabels = (
formatEntityName,
statisticId,
statsMetadata?.[statisticId],
device.name,
ambiguous.has(statisticId)
device.name
);
}
}
+23 -23
View File
@@ -6,7 +6,6 @@ import {
computeEntitySearchLabels,
} from "../../common/entity/compute_entity_name_display";
import type { RelatedIdSets } from "../../common/search/related-context";
import type { LocalizeFunc } from "../../common/translations/localize";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import type { PickerComboBoxItem } from "../../components/ha-picker-combo-box";
import type { FuseWeightedKey } from "../../resources/fuseMultiTerm";
@@ -52,14 +51,6 @@ export const entityComboBoxKeys: FuseWeightedKey[] = [
];
export interface GetEntitiesOptions {
states: HomeAssistant["states"];
entities: HomeAssistant["entities"];
devices: HomeAssistant["devices"];
areas: HomeAssistant["areas"];
floors: HomeAssistant["floors"];
localize: LocalizeFunc;
language: string;
translationMetadata: HomeAssistant["translationMetadata"];
includeDomains?: string[];
excludeDomains?: string[];
entityFilter?: HaEntityPickerEntityFilterFunc;
@@ -72,11 +63,20 @@ export interface GetEntitiesOptions {
}
export const getEntities = (
options: GetEntitiesOptions
hass: Pick<
HomeAssistant,
| "states"
| "entities"
| "devices"
| "areas"
| "floors"
| "language"
| "translationMetadata"
| "localize"
>,
options?: GetEntitiesOptions
): EntityComboBoxItem[] => {
const {
states,
localize,
includeDomains,
excludeDomains,
entityFilter,
@@ -86,11 +86,11 @@ export const getEntities = (
excludeEntities,
value,
idPrefix = "",
} = options;
} = options ?? {};
let items: EntityComboBoxItem[];
let entityIds = Object.keys(states);
let entityIds = Object.keys(hass.states);
// These run over every entity, so use Sets for O(1) membership instead of
// repeated Array.includes scans.
@@ -126,21 +126,21 @@ export const getEntities = (
// of inside the map over (potentially thousands of) entities.
const domainNames = new Map<string, string>();
const displayOptions = {
entities: options.entities,
devices: options.devices,
areas: options.areas,
floors: options.floors,
language: options.language,
translationMetadata: options.translationMetadata,
entities: hass.entities,
devices: hass.devices,
areas: hass.areas,
floors: hass.floors,
language: hass.language,
translationMetadata: hass.translationMetadata,
};
items = entityIds.map<EntityComboBoxItem>((entityId) => {
const stateObj = states[entityId];
const stateObj = hass.states[entityId];
const domain = computeDomain(entityId);
let domainName = domainNames.get(domain);
if (domainName === undefined) {
domainName = domainToName(localize, domain);
domainName = domainToName(hass.localize, domain);
domainNames.set(domain, domainName);
}
@@ -156,7 +156,7 @@ export const getEntities = (
domain_name: domainName,
sorting_label: [primary, secondary].filter(Boolean).join("_"),
search_labels: {
...computeEntitySearchLabels(stateObj, displayOptions),
...computeEntitySearchLabels(stateObj, hass),
domainName: domainName || null,
entityId: entityId,
},
+10 -17
View File
@@ -5,7 +5,7 @@ import memoizeOne from "memoize-one";
import { computeDomain } from "../../common/entity/compute_domain";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import { debounce } from "../../common/util/debounce";
import type { HomeAssistant, HomeAssistantApi } from "../../types";
import type { HomeAssistant } from "../../types";
import type { LightColor } from "../light";
import type { NextNamePart, RegistryEntry } from "../registry";
import type { Segment } from "../vacuum";
@@ -284,11 +284,11 @@ export const getExtendedEntityRegistryEntries = (
});
export const updateEntityRegistryEntry = (
callWS: HomeAssistantApi["callWS"],
hass: Pick<HomeAssistant, "callWS">,
entityId: string,
updates: Partial<EntityRegistryEntryUpdateParams>
): Promise<UpdateEntityRegistryEntryResult> =>
callWS({
hass.callWS({
type: "config/entity_registry/update",
entity_id: entityId,
...updates,
@@ -382,20 +382,13 @@ export const getEntityPlatformLookup = (
return entityLookup;
};
export interface AutomaticEntityIdOverrides {
name?: string | null;
area_id?: string | null;
}
export const getAutomaticEntityIds = (
callWS: HomeAssistantApi["callWS"],
entity_ids: string[],
overrides?: Record<string, AutomaticEntityIdOverrides>
hass: HomeAssistant,
entity_ids: string[]
) =>
callWS<Record<string, string | null>>({
hass.callWS<Record<string, string | null>>({
type: "config/entity_registry/get_automatic_entity_ids",
entity_ids,
...(overrides && { overrides }),
});
/**
@@ -403,22 +396,22 @@ export const getAutomaticEntityIds = (
* the area. Returns the entity ID of each entity after the change.
*/
export const updateEntitiesArea = async (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
entityIds: string[],
areaId: string
): Promise<Record<string, string>> => {
await Promise.all(
entityIds.map((entityId) =>
updateEntityRegistryEntry(callWS, entityId, { area_id: areaId })
updateEntityRegistryEntry(hass, entityId, { area_id: areaId })
)
);
const newEntityIds = await getAutomaticEntityIds(callWS, entityIds);
const newEntityIds = await getAutomaticEntityIds(hass, entityIds);
const result: Record<string, string> = {};
for (const entityId of entityIds) {
const newEntityId = newEntityIds[entityId];
if (newEntityId) {
// eslint-disable-next-line no-await-in-loop
await updateEntityRegistryEntry(callWS, entityId, {
await updateEntityRegistryEntry(hass, entityId, {
new_entity_id: newEntityId,
});
}
-31
View File
@@ -51,10 +51,6 @@ export interface SecurityFrontendSystemData {
favorite_entities?: string[];
}
export interface MaintenanceFrontendSystemData {
hidden_entities?: string[];
}
export interface EnergyFrontendSystemData {
// Stable "<view>.<card-type>" keys of energy dashboard cards the user has
// hidden. An absent key or array means nothing is hidden (all cards visible),
@@ -73,7 +69,6 @@ declare global {
home: HomeFrontendSystemData;
energy: EnergyFrontendSystemData;
security: SecurityFrontendSystemData;
maintenance: MaintenanceFrontendSystemData;
}
}
@@ -150,32 +145,6 @@ export const saveFrontendSystemData = async <
value,
});
const pendingSystemDataSaves = new Map<ValidSystemDataKey, Promise<void>>();
export const queueFrontendSystemDataSave = <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey,
value: FrontendSystemData[SystemDataKey]
): Promise<void> => {
const save = (pendingSystemDataSaves.get(key) ?? Promise.resolve())
.catch(() => undefined)
.then(() => saveFrontendSystemData(conn, key, value));
pendingSystemDataSaves.set(key, save);
return save;
};
export const fetchFrontendSystemDataAfterSaves = async <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey
): Promise<FrontendSystemData[SystemDataKey] | null> => {
await pendingSystemDataSaves.get(key)?.catch(() => undefined);
return fetchFrontendSystemData(conn, key);
};
export const subscribeFrontendSystemData = <
SystemDataKey extends ValidSystemDataKey,
>(
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
export interface InputBoolean {
id: string;
@@ -17,10 +17,10 @@ export const fetchInputBoolean = (hass: HomeAssistant) =>
hass.callWS<InputBoolean[]>({ type: "input_boolean/list" });
export const createInputBoolean = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: InputBooleanMutableParams
) =>
callWS<InputBoolean>({
hass.callWS<InputBoolean>({
type: "input_boolean/create",
...values,
});
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
export interface InputButton {
id: string;
@@ -15,10 +15,10 @@ export const fetchInputButton = (hass: HomeAssistant) =>
hass.callWS<InputButton[]>({ type: "input_button/list" });
export const createInputButton = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: InputButtonMutableParams
) =>
callWS<InputButton>({
hass.callWS<InputButton>({
type: "input_button/create",
...values,
});
+2 -2
View File
@@ -45,10 +45,10 @@ export const fetchInputDateTime = (hass: HomeAssistant) =>
hass.callWS<InputDateTime[]>({ type: "input_datetime/list" });
export const createInputDateTime = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: InputDateTimeMutableParams
) =>
callWS<InputDateTime>({
hass.callWS<InputDateTime>({
type: "input_datetime/create",
...values,
});
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
export interface InputNumber {
id: string;
@@ -29,10 +29,10 @@ export const fetchInputNumber = (hass: HomeAssistant) =>
hass.callWS<InputNumber[]>({ type: "input_number/list" });
export const createInputNumber = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: InputNumberMutableParams
) =>
callWS<InputNumber>({
hass.callWS<InputNumber>({
type: "input_number/create",
...values,
});
+3 -3
View File
@@ -2,7 +2,7 @@ import type {
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
interface InputSelectEntityAttributes extends HassEntityAttributeBase {
options: string[];
@@ -41,10 +41,10 @@ export const fetchInputSelect = (hass: HomeAssistant) =>
hass.callWS<InputSelect[]>({ type: "input_select/list" });
export const createInputSelect = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: InputSelectMutableParams
) =>
callWS<InputSelect>({
hass.callWS<InputSelect>({
type: "input_select/create",
...values,
});
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HomeAssistant, HomeAssistantApi } from "../types";
import type { HomeAssistant } from "../types";
export interface InputText {
id: string;
@@ -36,10 +36,10 @@ export const fetchInputText = (hass: HomeAssistant) =>
hass.callWS<InputText[]>({ type: "input_text/list" });
export const createInputText = (
callWS: HomeAssistantApi["callWS"],
hass: HomeAssistant,
values: InputTextMutableParams
) =>
callWS<InputText>({
hass.callWS<InputText>({
type: "input_text/create",
...values,
});
+2 -2
View File
@@ -196,8 +196,8 @@ export const fetchIntegrationManifest = (
.callWS<IntegrationManifest>({ type: "manifest/get", integration })
.then(sanitizeManifest);
export const fetchIntegrationSetups = (callWS: HomeAssistant["callWS"]) =>
callWS<IntegrationSetup[]>({ type: "integration/setup_info" });
export const fetchIntegrationSetups = (hass: HomeAssistant) =>
hass.callWS<IntegrationSetup[]>({ type: "integration/setup_info" });
export const fetchIntegrationLogInfo = (conn) =>
conn.sendMessagePromise({
+3 -3
View File
@@ -1,9 +1,9 @@
import type { Connection, HassEventBase } from "home-assistant-js-websocket";
import { getCollection } from "home-assistant-js-websocket";
import type { ConfigPath } from "../common/util/config-path";
import type { HuiBadge } from "../panels/lovelace/badges/hui-badge";
import type { HuiCard } from "../panels/lovelace/cards/hui-card";
import type { HuiSection } from "../panels/lovelace/sections/hui-section";
import type { LovelacePath } from "../panels/lovelace/editor/lovelace-path";
import type { Lovelace } from "../panels/lovelace/types";
import type { HomeAssistant } from "../types";
import type { LovelaceSectionConfig } from "./lovelace/config/section";
@@ -21,7 +21,7 @@ export interface LovelaceViewElement extends HTMLElement {
narrow?: boolean;
// Temporary compatibility: custom view layouts still read the view index
index?: number;
path?: ConfigPath;
path?: LovelacePath;
cards?: HuiCard[];
badges?: HuiBadge[];
sections?: HuiSection[];
@@ -34,7 +34,7 @@ export interface LovelaceSectionElement extends HTMLElement {
hass?: HomeAssistant;
lovelace?: Lovelace;
preview?: boolean;
path?: ConfigPath;
path?: LovelacePath;
cards?: HuiCard[];
badges?: HuiBadge[];
sections?: HuiSection[];
+2 -3
View File
@@ -21,9 +21,8 @@ export const findOTBRInfoForDataset = (
}
const preferredAddress = dataset.preferred_extended_address;
const preferred = preferredAddress ? otbrInfo[preferredAddress] : undefined;
if (preferred?.extended_pan_id === dataset.extended_pan_id) {
return preferred;
if (preferredAddress && otbrInfo[preferredAddress]) {
return otbrInfo[preferredAddress];
}
return Object.values(otbrInfo).find(
+1 -1
View File
@@ -14,7 +14,7 @@ export const subscribePreviewGeneric = (
hass: HomeAssistant,
domain: string,
flow_id: string,
flow_type: "config_flow" | "options_flow" | "config_subentries_flow",
flow_type: "config_flow" | "options_flow",
user_input: Record<string, any>,
callback: (preview: GenericPreview) => void
): Promise<UnsubscribeFunc> =>
Loaded 100 of 353 files, more files were not shown because too many files have changed in this diff. Show more