Compare commits

..
Author SHA1 Message Date
Petar Petrov 0ed9333dc2 Keep history line after unavailable gap in downsampled charts 2026-11-14 15:59:23 +02:00
renovate[bot] 2706bd89a1 Update dependency vite to v8.3.8 (#55906)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-14 08:55:55 +02:00
renovate[bot] bd434eeb0d Update dependency @rspack/core to v2.3.2 (#55899)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 17:11:21 +02:00
Petar Petrov 16f01e1081 Fix legends fitting as narrow in the card editor preview (#55886) 2026-11-13 14:28:15 +01:00
Dan SpencerandClaude Opus 5.5 050251db23 Offer a blueprint's trigger IDs in Triggered by conditions (#55802)
* Offer a blueprint's trigger IDs in Triggered by conditions

In an automation that uses a blueprint, a Triggered by condition in one
of its inputs listed no triggers, and flagged the IDs it already used as
missing. The editor took the list from the automation's own triggers,
and a blueprint automation has only `use_blueprint`.

For a blueprint automation, fetch the blueprint with its inputs filled
in (`blueprint/substitute`) and list the IDs its triggers set, fetching
again when the inputs change. A trigger without an ID isn't offered,
since the editor can't give one to a blueprint's trigger, and an ID
shared by several triggers is listed once, as the condition matches any
of them.

The condition is in one of the blueprint's inputs, which the trigger
controller doesn't edit, so its `select` returns false there, as
`updateTriggerId` does for a trigger it doesn't own, and the condition
editor saves the pick through `value-changed` instead.

An option shows its trigger number only while trigger rows show theirs
(`showIndices`): the numbers point at trigger rows, and a blueprint
automation has none.

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

* Ignore an empty use_blueprint while editing YAML

`use_blueprint:` with no value parses to null, and requesting its
triggers threw on `.path`, aborting the editor's update.

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

* Hold back trigger warnings until a blueprint's triggers are known

While a blueprint's triggers load, or when its inputs can't be substituted
yet, a Triggered by condition can't tell a missing ID from one it hasn't
seen. The trigger context now carries optionsStatus: "loaded", "loading" or
"failed". Until it's loaded, the condition and the row's summary list the
selected IDs without the missing-trigger warning or chips. An empty
condition shows "Loading", or a hint to set the blueprint's required inputs
once substitution has failed. After a failure the last triggers stay listed.

use_blueprint is also compared by value, since YAML mode parses a new object
on every edit and an edit elsewhere fetched the triggers again.

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

* Address review: spinner, refetch warnings and index badges

- Show a delayed ha-spinner while a blueprint's triggers load, following
  the frontend's loading pattern, instead of visible "Loading" text.
- Mark every request as loading, keeping the last triggers listed, so an
  input change that renames a trigger's ID doesn't read as missing until
  the new triggers arrive.
- Publish showIndices false for a blueprint automation. Switching to YAML
  removes the manual editor's sidebar without reporting it, which left
  the blueprint's condition numbering trigger rows that don't exist.
- Drop inline comments from the blueprint trigger code.

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

* Show trigger IDs when trigger rows aren't numbered

A Triggered by condition tells options apart by description, custom ID or
index. In a blueprint automation there are no indices, so two triggers
that describe the same with generated-prefixed IDs looked identical while
selecting different IDs. Without indices, every option's ID is shown.

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

* Say when a blueprint's triggers have no IDs

A blueprint whose triggers have no IDs loads with nothing to offer, and
the condition said "Add a trigger first", which can't be done in a
blueprint automation. optionsStatus is now blueprintStatus, left out for
an automation with its own triggers, so the condition can tell the two
apart and say the blueprint's triggers have no IDs.

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

* Rename blueprint_triggers_pending to blueprint_triggers_unavailable

It's only shown once substitution has failed, not while loading.

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

* Drop controller tests that cover one-line branches

Keeps the tests for the response race, the statuses and refetching.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-13 06:26:48 +00:00
renovate[bot] 13128609de Update dependency @versatiles/style to v9.1.0 (#55893)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 08:22:31 +02:00
renovate[bot] 0f70813ada Update dependency marked to v18.2.0 (#55894)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 08:22:27 +02:00
Matthias 5762da9d22 Refresh the ingress session when the app panel becomes visible (#54863)
The ingress session is kept alive by a 60 s timer only. Timers do not run
while the device sleeps, so after the browser comes back to the foreground
the session may already be expired, and the Supervisor refuses every
request to the app until the next tick. An app that reconnects its
websocket right away stays unreachable for up to a minute.

Refresh the session on visibilitychange and resume as well. The refresh is
shared with the timer: validate the session, create a new one when that
fails, and never run twice at once. A failed refresh no longer surfaces as
an unhandled rejection, the next one retries.
2026-11-13 06:07:00 +00:00
renovate[bot] 33f709cd21 Update Node.js to v24.22.3 (#55892)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 06:54:27 +01:00
renovate[bot] 1f77e4cd59 Update dependency typescript-eslint to v8.72.2 (#55891)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 06:54:10 +01:00
Paul Bottein 77170b447f Fix favorites centering in the more info dialog (#55884) 2026-11-12 17:26:25 +02:00
c0ffeeca7 e2bb744202 MCP: change AI agent to AI app (#55885) 2026-11-12 17:25:49 +02:00
Wendelin 0eec83448a Revert camera ICE server filter and WebRTC-first memory (#55881)
* Revert camera ICE server filter and WebRTC-first memory

Follow-up to #55861 after review feedback:

- Use the full ICE server list from core again. The slow starts come from
  go2rtc, which stalls while it sets up TURN relays with the cloud ICE
  servers, so filtering in the browser does not help.
- Start HLS and WebRTC together again, remove the per-camera WebRTC-first
  memory and its 12 second HLS delay.
- Retry a WebRTC stream at most once, only after it played or on a backend
  error. A new connection that gets no answer or finds no path fails
  directly, so HLS or MJPEG takes over.

* Ignore stream URL errors of a removed HLS player

Switching cameras while the old HLS player was still fetching its stream
URL could mark HLS as failed for the new camera.
2026-11-12 14:51:53 +01:00
WendelinandClaude Sonnet 5.5 1864f6f802 Move the media browser list item to its own file (#55877)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-11-12 13:26:28 +01:00
renovate[bot] 9a19cc3bf6 Update dependency vite to v8.3.7 (#55880)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 13:24:58 +01:00
WendelinandClaude Fable 5.2 ec51fb4f8d Add attributes to wrap text in list rows (#55864)
The headline and supporting text of ha-row-item are truncated to one
line. Many pages overrode that with white-space rules on the headline
and supporting-text parts.

Add the wrap-headline and wrap-supporting-text attributes and use them
in place of those CSS overrides.

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-12 13:20:40 +02:00
Paul Bottein 6a1a9bfb1b Suggest area icons based on the area name (#55708)
* Suggest area icons from the room in the area name

* Fix stale icon list, closed dialog and AI icon override

* Keep an untouched area dialog clean after the icon prefill

* Keep the suggested section visible when a suggested icon is selected

* Move area icon keywords to the translations

* Move room keywords to a shared translation key

* Remove home cinema and gym from the room list

* Note the Lokalise draft effect of editing room keywords

* Ship room keyword drafts and group keywords under rooms.keywords

* Add more room types for area icon suggestions

* Fetch room keyword drafts through the Lokalise keys API
2026-11-12 10:51:12 +01:00
Maarten Lakerveld 16807d2765 Make "Don't show again" a checkbox on the browser warning (#55863)
As a second button it was easy to press by accident. The reminder now has a
checkbox, and "Continue anyway" applies it.
2026-11-12 09:48:17 +01:00
renovate[bot] 9caad65c91 Update dependency eslint-plugin-import-x to v4.18.1 (#55874)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 08:16:21 +02:00
Bram KragtenandClaude Opus 5.5 af523f1087 Fix Matter add device dialog stuck on the spinner (#55869)
The dialog waited for the companion app's commission finish message on
every step, but only the app's own flow sends it. Steps that commission
through core or another app now advance as soon as the device appears.
A failed finish message after the device appeared also advances now.

The new device watcher unsubscribed twice after a find, which dropped
another subscriber from the device registry collection. After a few
adds the registry stopped updating and the dialog never saw the device.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 08:12:21 +02:00
renovate[bot] 349d5f7125 Update dependency intl-messageformat to v12.1.5 (#55872)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 07:01:41 +01:00
renovate[bot] de64bd3c59 Update formatjs (#55873)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-12 07:01:21 +01:00
Zedas 5253eef284 Allow a few pixels of finger movement in the action handler (#55826)
* Allow a few pixels of finger movement in the action handler

* Cancel the action handler press when the browser takes over the touch

The document scroll listener only hears the page itself, not nested
scrollers. pointercancel is composed and fires when the browser starts
scrolling a touch, so it covers those as well.
2026-11-11 22:51:14 +01:00
WendelinandClaude Fable 5.2 b1164739c3 Make camera WebRTC streams connect faster and more reliably (#55861)
* Make camera WebRTC streams connect faster and more reliably

- Limit the ICE server URLs the browser uses to one STUN, one UDP TURN
  and one TCP TURN URL per host. The last retry uses the full list.
- Start WebRTC first for cameras where it worked before in this browser,
  with HLS as fallback after 12 seconds.
- Always prefer WebRTC over HLS once it plays.
- Restart a WebRTC stream up to two times when it fails, loses its
  connection or does not connect in time, then report the failure so HLS
  takes over.
- Fix the ICE candidates added to the offer.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Address review and connect the microphone over the known path

- Always forget a camera when WebRTC shows no video within the deadline.
- Fall back to MJPEG when a WebRTC only camera delivers audio but no
  video.
- Keep using all ICE servers once a stream only loaded with them.
- Start the microphone connection with only the ICE servers the running
  stream needs for its path.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Keep all ICE servers for a direct microphone path that needed them

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Improve microphone connection handling in WebRTC player

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-11 16:35:47 +01:00
92 changed files with 2734 additions and 1283 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
24.22.2
24.22.3
+107 -42
View File
@@ -157,6 +157,99 @@ async function pollProcess(lokaliseApi, projectId, processId) {
}
/* eslint-enable no-await-in-loop */
const DRAFTS_ACCEPTED_KEYS = [
// Written per language rather than translated from English, so an English edit doesn't make them outdated
"ui.components.rooms.keywords",
];
async function exportTranslations(lokaliseApi, projectId) {
const exportProcess = await lokaliseApi.files().async_download(projectId, {
format: "json",
original_filenames: false,
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
});
const finishedProcess = await pollProcess(
lokaliseApi,
projectId,
exportProcess.process_id
);
const bundleUrl = finishedProcess.details.download_url;
console.log(`Downloading translations from: ${bundleUrl}`);
const response = await fetch(bundleUrl);
if (response.status !== 200 && response.status !== 0) {
throw new Error(response.statusText);
}
console.log(`Extracting translations...`);
const contents = await JSZip.loadAsync(await response.arrayBuffer());
const files = {};
await Promise.all(
Object.keys(contents.files).map(async (filename) => {
const file = contents.file(filename);
if (!file) {
// no file, probably a directory
return;
}
files[filename.split("/").splice(-1)[0]] = await file.async("string");
})
);
return files;
}
async function fetchDrafts(lokaliseApi, projectId) {
const english = JSON.parse(
await fs.readFile("src/translations/en.json", { encoding })
);
const keyNames = DRAFTS_ACCEPTED_KEYS.flatMap((key) => {
const keys = key.split(".");
const drafts = keys.reduce((obj, part) => obj?.[part], english) ?? {};
return Object.keys(drafts).map((name) => [...keys, name].join("::"));
});
if (!keyNames.length) {
return [];
}
const { items } = await lokaliseApi.keys().list({
project_id: projectId,
filter_keys: keyNames.join(","),
include_translations: 1,
limit: keyNames.length,
});
return items.flatMap((key) =>
key.translations
.filter(({ translation }) => translation)
.map(({ language_iso, translation }) => ({
filename: `${language_iso}.json`,
path: key.key_name.web.split("::"),
translation,
}))
);
}
function acceptDrafts(files, drafts) {
const data = {};
drafts.forEach(({ filename, path: keyPath, translation }) => {
data[filename] ??= files[filename] ? JSON.parse(files[filename]) : {};
const parent = keyPath.slice(0, -1).reduce((obj, part) => {
obj[part] ??= {};
return obj[part];
}, data[filename]);
parent[keyPath.at(-1)] = translation;
});
Object.entries(data).forEach(([filename, content]) => {
files[filename] = JSON.stringify(content, null, 2);
});
}
gulp.task("fetch-lokalise", async function () {
let apiKey;
try {
@@ -193,52 +286,24 @@ gulp.task("fetch-lokalise", async function () {
await Promise.all(
projects.map(async ([project, projectId]) => {
try {
const exportProcess = await lokaliseApi
.files()
.async_download(projectId, {
format: "json",
original_filenames: false,
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
});
const finishedProcess = await pollProcess(
lokaliseApi,
projectId,
exportProcess.process_id
);
const bundleUrl = finishedProcess.details.download_url;
console.log(`Downloading translations from: ${bundleUrl}`);
const response = await fetch(bundleUrl);
if (response.status !== 200 && response.status !== 0) {
throw new Error(response.statusText);
const [files, drafts] = await Promise.all([
exportTranslations(lokaliseApi, projectId),
project === "frontend"
? fetchDrafts(lokaliseApi, projectId)
: undefined,
]);
if (drafts) {
acceptDrafts(files, drafts);
}
console.log(`Extracting translations...`);
const contents = await JSZip.loadAsync(await response.arrayBuffer());
await mkdirPromise;
await Promise.all(
Object.keys(contents.files).map(async (filename) => {
const file = contents.file(filename);
if (!file) {
// no file, probably a directory
return;
}
const content = await file.async("nodebuffer");
await fs.writeFile(
path.join(inDir, project, filename.split("/").splice(-1)[0]),
content,
{ flag: "w", encoding }
);
})
Object.entries(files).map(([filename, content]) =>
fs.writeFile(path.join(inDir, project, filename), content, {
flag: "w",
encoding,
})
)
);
} catch (err) {
console.error(err);
+11 -5
View File
@@ -117,11 +117,17 @@ shared slots/attributes below.
**Attributes**
| Name | Type | Default | Description |
| ----------------- | ------- | ------- | --------------------------------------- |
| `headline` | String | — | Primary text. Overridden by the slot. |
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
| Name | Type | Default | Description |
| ---------------------- | ------- | ------- | -------------------------------------------------- |
| `headline` | String | — | Primary text. Overridden by the slot. |
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
| `wrap-headline` | Boolean | `false` | Wrap the headline instead of truncating it. |
| `wrap-supporting-text` | Boolean | `false` | Wrap the supporting text instead of truncating it. |
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
The headline and the supporting text stay on one line and are truncated with an
ellipsis by default. Set `wrap-headline` or `wrap-supporting-text` on rows whose
text has to stay readable in full, like settings with a description.
**CSS parts**
+14
View File
@@ -191,6 +191,20 @@ export class DemoHaList extends LitElement {
<ha-list-item-base headline="Disabled row" disabled>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
<ha-list-item-base
headline="Truncated by default, a long headline stays on one line and ends with an ellipsis"
supporting-text="Long supporting text is truncated as well, so every row in the list keeps the same height"
>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
<ha-list-item-base
wrap-headline
wrap-supporting-text
headline="With wrap-headline, a long headline wraps onto as many lines as it needs"
supporting-text="With wrap-supporting-text, long supporting text wraps too, which suits settings with a description"
>
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
</ha-list-item-base>
</ha-list-base>
</ha-card>
+17 -17
View File
@@ -54,15 +54,15 @@
"@codemirror/view": "6.43.15",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "8.0.2",
"@formatjs/intl-displaynames": "8.0.1",
"@formatjs/intl-durationformat": "0.12.3",
"@formatjs/intl-getcanonicallocales": "3.3.0",
"@formatjs/intl-listformat": "9.0.1",
"@formatjs/intl-locale": "5.4.2",
"@formatjs/intl-numberformat": "10.0.2",
"@formatjs/intl-pluralrules": "7.0.2",
"@formatjs/intl-relativetimeformat": "13.0.1",
"@formatjs/intl-datetimeformat": "8.0.3",
"@formatjs/intl-displaynames": "8.0.2",
"@formatjs/intl-durationformat": "0.12.4",
"@formatjs/intl-getcanonicallocales": "3.3.1",
"@formatjs/intl-listformat": "9.0.2",
"@formatjs/intl-locale": "5.4.3",
"@formatjs/intl-numberformat": "10.0.3",
"@formatjs/intl-pluralrules": "7.0.3",
"@formatjs/intl-relativetimeformat": "13.0.2",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.5",
"@lezer/highlight": "1.2.5",
@@ -79,7 +79,7 @@
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.3",
"@tsparticles/preset-links": "4.5.3",
"@versatiles/style": "9.0.0",
"@versatiles/style": "9.1.0",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.204.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10",
@@ -102,14 +102,14 @@
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.8.1",
"idb-keyval": "6.3.0",
"intl-messageformat": "12.1.4",
"intl-messageformat": "12.1.5",
"js-yaml": "5.5.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.17.0",
"marked": "18.1.3",
"marked": "18.2.0",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
@@ -153,7 +153,7 @@
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.0",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.1",
"@rspack/core": "2.3.2",
"@rspack/dev-server": "2.2.2",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
@@ -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.18.1",
"eslint-plugin-lit": "2.3.1",
"eslint-plugin-lit-a11y": "5.1.3",
"eslint-plugin-unused-imports": "4.4.1",
@@ -214,8 +214,8 @@
"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",
"typescript-eslint": "8.72.2",
"vite": "8.3.8",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.0",
"webpack-stats-plugin": "1.1.3",
@@ -224,6 +224,6 @@
},
"packageManager": "[email protected]",
"volta": {
"node": "24.22.2"
"node": "24.22.3"
}
}
+364 -377
View File
File diff suppressed because it is too large. Load diff
@@ -89,10 +89,19 @@ export class LegendFitController {
private _fit() {
const list = this._element;
const rowWidth = list?.getBoundingClientRect().width;
if (!list || !rowWidth) {
if (!list) {
return;
}
const style = getComputedStyle(list);
const rowWidth = parseFloat(style.width);
// Bounding rects include transforms, such as a dialog scaling in, which
// never resize the list, so measure in layout pixels
const scale = list.getBoundingClientRect().width / rowWidth;
if (!rowWidth || !scale) {
return;
}
const layoutWidth = (element: Element) =>
element.getBoundingClientRect().width / scale;
const children = Array.from(list.children);
const more = children.find((child) =>
child.classList.contains("legend-more")
@@ -107,9 +116,7 @@ export class LegendFitController {
}
this._more = more;
}
const widths = children
.filter((child) => child !== more)
.map((child) => child.getBoundingClientRect().width);
const widths = children.filter((child) => child !== more).map(layoutWidth);
// Values resize the items on every state update. Fitting each item at its
// widest since the last resize keeps the more button from flickering.
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
@@ -122,9 +129,9 @@ export class LegendFitController {
}
const fit = fitInRows(
this._widths,
more?.getBoundingClientRect().width ?? 0,
more ? layoutWidth(more) : 0,
rowWidth,
parseFloat(getComputedStyle(list).columnGap) || 0,
parseFloat(style.columnGap) || 0,
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
);
if (fit !== this.fit) {
+6 -5
View File
@@ -19,6 +19,7 @@ interface MinMaxFrame {
maxPoint: Point;
maxX: number;
maxY: number;
lastX: number;
gapPoint: Point | undefined;
}
@@ -68,6 +69,7 @@ function newFrame(
maxPoint: point,
maxX: x,
maxY: y,
lastX: x,
gapPoint,
};
}
@@ -174,6 +176,7 @@ export function downSampleLineData<
if (!frame) {
frames.set(frameIndex, newFrame(point, x, y, undefined));
} else if (frame.hasValue) {
frame.lastX = x;
// Match the original strict-less / strict-greater comparisons so the
// first occurrence wins on ties.
if (y < frame.minY) {
@@ -189,6 +192,7 @@ export function downSampleLineData<
} else {
// the frame held nothing but a marker so far
frame.hasValue = true;
frame.lastX = x;
frame.minPoint = point;
frame.minX = x;
frame.minY = y;
@@ -213,11 +217,8 @@ export function downSampleLineData<
if (frame.gapPoint !== undefined) {
// A marker followed by a value in its own frame is a gap that closed
// within one frame, which is about one device pixel: too narrow to show.
// The kept points are exactly min and max, so comparing against the
// later of the two catches that without any work on the ingest path. A
// marker-only frame compares against its own x and always passes.
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
// That value may be neither min nor max, so check the frame's last x.
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
result.push(frame.gapPoint as T);
}
}
+55 -94
View File
@@ -6,7 +6,7 @@ import { repeat } from "lit/directives/repeat";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { fireEvent } from "../common/dom/fire_event";
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
import { supportsFeature } from "../common/entity/supports-feature";
import {
CameraEntityFeature,
@@ -17,8 +17,14 @@ import {
STREAM_TYPE_WEB_RTC,
type CameraCapabilities,
type CameraEntity,
type StreamType,
} from "../data/camera";
import {
MJPEG_STREAM,
selectCameraStreams,
type CameraStream,
type CameraStreamTracks,
type CameraStreamType,
} from "../data/camera-streams";
import {
apiContext,
configContext,
@@ -29,14 +35,7 @@ import "./ha-hls-player";
import "./ha-web-rtc-player";
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
const MJPEG_STREAM = "mjpeg";
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
interface Stream {
type: CameraStreamType;
visible: boolean;
}
export type { CameraStreamType } from "../data/camera-streams";
@customElement("ha-camera-stream")
export class HaCameraStream extends LitElement {
@@ -78,13 +77,15 @@ export class HaCameraStream extends LitElement {
@state() private _capabilities?: CameraCapabilities;
@state() private _hlsStreams?: { hasAudio: boolean; hasVideo: boolean };
@state() private _hlsStreams?: CameraStreamTracks;
@state() private _webRtcStreams?: { hasAudio: boolean; hasVideo: boolean };
@state() private _webRtcStreams?: CameraStreamTracks;
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
private _visibleStreamType?: Stream["type"];
private _visibleStreamType?: CameraStreamType;
private _capabilitiesRequest = 0;
private _thumbnailApi = memoizeOne(
(
@@ -132,6 +133,10 @@ export class HaCameraStream extends LitElement {
public connectedCallback() {
super.connectedCallback();
this._connected = true;
if (this.hasUpdated) {
// The players start again when reattached, so their results do as well
this._resetStreams();
}
}
public disconnectedCallback() {
@@ -146,9 +151,8 @@ export class HaCameraStream extends LitElement {
capabilities: this._capabilities,
});
}
const visibleStreamType = this._currentStreams().find(
(stream) => stream.visible
)?.type;
const streams = this._currentStreams();
const visibleStreamType = streams.find((stream) => stream.visible)?.type;
if (visibleStreamType !== this._visibleStreamType) {
this._visibleStreamType = visibleStreamType;
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
@@ -167,7 +171,7 @@ export class HaCameraStream extends LitElement {
)}`;
}
private _renderStream(stream: Stream) {
private _renderStream(stream: CameraStream) {
if (!this.stateObj) {
return nothing;
}
@@ -229,15 +233,14 @@ export class HaCameraStream extends LitElement {
return this._streams(
this._capabilities?.frontend_stream_types,
this._hlsStreams,
this._webRtcStreams,
this.muted
this._webRtcStreams
);
}
private async _getCapabilities() {
this._capabilities = undefined;
this._hlsStreams = undefined;
this._webRtcStreams = undefined;
this._resetStreams();
const request = ++this._capabilitiesRequest;
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
this._capabilities = {
frontend_stream_types: [],
@@ -245,10 +248,19 @@ export class HaCameraStream extends LitElement {
};
return;
}
this._capabilities = await fetchCameraCapabilities(
const capabilities = await fetchCameraCapabilities(
this._api,
this.stateObj!.entity_id
);
if (request !== this._capabilitiesRequest) {
return;
}
this._capabilities = capabilities;
}
private _resetStreams() {
this._hlsStreams = undefined;
this._webRtcStreams = undefined;
}
private async _getPosterUrl(): Promise<void> {
@@ -269,89 +281,38 @@ export class HaCameraStream extends LitElement {
fireEvent(this, "load");
}
private _handleHlsStreams(ev: CustomEvent) {
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
this._hlsStreams = ev.detail;
}
private _handleWebRtcStreams(ev: CustomEvent) {
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
if (
!ev.detail.hasVideo &&
!ev.detail.hasAudio &&
this._capabilities?.frontend_stream_types.length === 1 &&
typeof RTCPeerConnection !== "undefined"
) {
// Without another stream type, keep the player to show why it failed.
// Only a browser without WebRTC falls back to MJPEG.
return;
}
this._webRtcStreams = ev.detail;
}
private _streams = memoizeOne(
(
supportedTypes?: StreamType[],
hlsStreams?: { hasAudio: boolean; hasVideo: boolean },
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean },
muted?: boolean
): Stream[] => {
supportedTypes?: CameraCapabilities["frontend_stream_types"],
hlsStreams?: CameraStreamTracks,
webRtcStreams?: CameraStreamTracks
): CameraStream[] => {
if (__DEMO__) {
return [{ type: MJPEG_STREAM, visible: true }];
}
if (!supportedTypes) {
return [];
}
if (supportedTypes.length === 0) {
// doesn't support any stream type, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
if (supportedTypes.length === 1) {
// only 1 stream type, no need to choose
if (
(supportedTypes[0] === STREAM_TYPE_HLS &&
hlsStreams?.hasVideo === false) ||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
webRtcStreams?.hasVideo === false)
) {
// stream failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
return [{ type: supportedTypes[0], visible: true }];
}
if (hlsStreams && webRtcStreams) {
// fully loaded
if (
hlsStreams.hasVideo &&
hlsStreams.hasAudio &&
!webRtcStreams.hasAudio &&
!muted
) {
// webRTC stream is missing audio and audio is not muted, use HLS
return [{ type: STREAM_TYPE_HLS, visible: true }];
}
if (webRtcStreams.hasVideo) {
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
// both streams failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
if (hlsStreams?.hasVideo !== webRtcStreams?.hasVideo) {
// one of the two streams is loaded, or errored
// choose the one that has video or is still loading
if (hlsStreams?.hasVideo) {
return [
{ type: STREAM_TYPE_HLS, visible: true },
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
}
if (hlsStreams?.hasVideo === false) {
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
if (webRtcStreams?.hasVideo) {
return [
{ type: STREAM_TYPE_WEB_RTC, visible: true },
{ type: STREAM_TYPE_HLS, visible: false },
];
}
if (webRtcStreams?.hasVideo === false) {
return [{ type: STREAM_TYPE_HLS, visible: true }];
}
}
return [
{ type: STREAM_TYPE_HLS, visible: true },
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
return selectCameraStreams({
supportedTypes,
hlsStreams,
webRtcStreams,
});
}
);
+4
View File
@@ -112,6 +112,9 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
@property({ attribute: "pin-block" })
public pinBlock?: "start" | "center" | "end" | "nearest";
// Skip the "unknown value" highlight and note for a value that is not in the
// list but that the value renderer presents on its own.
@property({ type: Boolean, attribute: "no-unknown-state" })
@@ -347,6 +350,7 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
.searchKeys=${this.searchKeys}
.customValueLabel=${this.customValueLabel}
.noSort=${this.noSort}
.pinBlock=${this.pinBlock}
></ha-picker-combo-box>
`;
}
+7 -2
View File
@@ -180,13 +180,14 @@ class HaHLSPlayer extends LitElement {
return;
}
if (!this.entityid) {
const entityId = this.entityid;
if (!entityId) {
return;
}
try {
const { url } = await fetchStreamUrl(
{ callWS: this._api.callWS, hassUrl: this._connection.hassUrl },
this.entityid
entityId
);
this._url = this._connection.hassUrl(url);
@@ -198,6 +199,10 @@ class HaHLSPlayer extends LitElement {
// eslint-disable-next-line
console.error(err);
if (!this.isConnected || entityId !== this.entityid) {
// Removed or switched camera while fetching, the result is outdated
return;
}
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
}
}
+62 -18
View File
@@ -1,13 +1,17 @@
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import type { TemplateResult } from "lit";
import type { PropertyValues, TemplateResult } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import { caseInsensitiveStringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { customIcons } from "../data/custom_icons";
import type { ValueChangedEvent } from "../types";
import "./ha-combo-box-item";
import "./ha-generic-picker";
import type { HaGenericPicker } from "./ha-generic-picker";
import "./ha-icon";
import type { PickerComboBoxItem } from "./ha-picker-combo-box";
@@ -50,16 +54,17 @@ const createIconItem = (icon: IconData, prefix: string): PickerComboBoxItem => {
const loadIcons = async () => {
ICONS_LOADED = true;
const iconList = await import("../../build/mdi/iconList.json");
ICONS = iconList.default.map((icon) => createIconItem(icon, "mdi"));
const sortIcons = (icons: PickerComboBoxItem[]) =>
icons.sort((a, b) => caseInsensitiveStringCompare(a.id, b.id));
const customIconLoads: Promise<PickerComboBoxItem[]>[] = [];
Object.keys(customIcons).forEach((iconSet) => {
customIconLoads.push(loadCustomIconItems(iconSet));
});
(await Promise.all(customIconLoads)).forEach((customIconItems) => {
ICONS.push(...customIconItems);
});
const iconList = await import("../../build/mdi/iconList.json");
const mdiIcons = iconList.default.map((icon) => createIconItem(icon, "mdi"));
ICONS = sortIcons([...mdiIcons]);
const customIconItems = await Promise.all(
Object.keys(customIcons).map(loadCustomIconItems)
);
ICONS = sortIcons([...mdiIcons, ...customIconItems.flat()]);
};
const loadCustomIconItems = async (
@@ -81,8 +86,8 @@ const loadCustomIconItems = async (
const rowRenderer: RenderItemFunction<PickerComboBoxItem> = (item) => html`
<ha-combo-box-item>
<ha-icon .icon=${item.id} slot="start"></ha-icon>
${item.id}
<ha-icon .icon=${item.icon ?? item.id} slot="start"></ha-icon>
${item.icon ?? item.id}
</ha-combo-box-item>
`;
@@ -104,12 +109,32 @@ export class HaIconPicker extends LitElement {
@property({ type: Boolean }) public invalid = false;
private _getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
@property({ attribute: false }) public suggestedIcons?: string[];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@query("ha-generic-picker") private _picker?: HaGenericPicker;
private _getIconPickerItems = () =>
this._itemsWithSuggestions(ICONS, this.suggestedIcons, this._localize);
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
if (changedProps.has("suggestedIcons") || changedProps.has("_localize")) {
this._picker?.refreshItems();
}
}
protected render(): TemplateResult {
return html`
<ha-generic-picker
allow-custom-value
no-sort
.pinBlock=${
this.value && this.suggestedIcons?.includes(this.value)
? "end"
: undefined
}
.getItems=${this._getIconPickerItems}
.helper=${this.helper}
.disabled=${this.disabled}
@@ -128,15 +153,35 @@ export class HaIconPicker extends LitElement {
`;
}
private _itemsWithSuggestions = memoizeOne(
(
icons: PickerComboBoxItem[],
suggestedIcons: string[] | undefined,
localize: LocalizeFunc
): (PickerComboBoxItem | string)[] => {
if (!suggestedIcons?.length) {
return icons;
}
const suggested = new Set(suggestedIcons);
return [
localize("ui.components.icon_picker.suggested"),
...suggestedIcons.map((icon) => ({ id: icon, primary: icon, icon })),
localize("ui.components.icon_picker.all_icons"),
...icons.filter((item) => !suggested.has(item.id)),
];
}
);
// Filter can take a significant chunk of frame (up to 3-5 ms)
private _filterIcons = memoizeOne(
(
filter: string,
filteredItems: PickerComboBoxItem[],
allItems: PickerComboBoxItem[]
_allItems: PickerComboBoxItem[]
): PickerComboBoxItem[] => {
const normalizedFilter = filter.toLowerCase().replace(/\s+/g, "-");
const iconItems = allItems?.length ? allItems : filteredItems;
// The full list also holds the suggestions and their section titles
const iconItems = ICONS.length ? ICONS : filteredItems;
if (!normalizedFilter.length) {
return iconItems;
@@ -175,8 +220,7 @@ export class HaIconPicker extends LitElement {
protected firstUpdated() {
if (!ICONS_LOADED) {
loadIcons().then(() => {
this._getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
this.requestUpdate();
this._picker?.refreshItems();
});
}
}
+12 -2
View File
@@ -201,6 +201,9 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
@property({ attribute: "pin-block" })
public pinBlock?: "start" | "center" | "end" | "nearest";
@query(".list") private _list?: HaListBase;
@query("ha-input-search") private _searchFieldElement?: HaInputSearch;
@@ -453,6 +456,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
this.value
)}
.pinIndex=${this.value ? this._getInitialSelectedIndex() : undefined}
.pinBlock=${this.pinBlock ?? "center"}
@mousedown=${this._preventBlur}
@focus=${this._focusList}
@blur=${this._resetSelectedItem}
@@ -685,6 +689,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
fireEvent(this, "index-selected", { index, item, newTab });
}
// Fuse indexes every row as text when the first one is a section title
private _searchableItems = memoizeOne((items: PickerComboBoxItem[]) =>
items.filter((item) => typeof item !== "string")
);
private _fuseIndex = memoizeOne(
(states: PickerComboBoxItem[], searchKeys?: FuseWeightedKey[]) =>
Fuse.createIndex(searchKeys || DEFAULT_SEARCH_KEYS, states)
@@ -708,10 +717,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
return;
}
const index = this._fuseIndex(this._allItems, this.searchKeys);
const searchableItems = this._searchableItems(this._allItems);
const index = this._fuseIndex(searchableItems, this.searchKeys);
let filteredItems = multiTermSortedSearch<PickerComboBoxItem>(
this._allItems,
searchableItems,
searchString,
(item) => item.id,
index
+129 -12
View File
@@ -24,8 +24,23 @@ import { showToast } from "../util/toast";
const HIDDEN_CLEANUP_DELAY = 60000;
// How long the backend gets to answer the offer, it has to connect to the camera
const ANSWER_TIMEOUT = 20000;
// How long finding a network path gets after the answer. Browsers can take
// minutes to give up on their own, or never do.
const ICE_TIMEOUT = 30000;
// How often a stream that lost its connection or got a backend error is
// started again. A new connection that gets no answer or finds no path is not
// retried, as a retry would most likely end the same way.
const MAX_RETRIES = 1;
// Gives the backend time to tear down the failed session before the next one
const RETRY_DELAY = 1000;
interface WebRtcPlayerError {
type: "not_supported" | "start_failed" | "connect_failed";
type: "not_supported" | "start_failed" | "connect_failed" | "no_connection";
message?: string;
}
@@ -99,7 +114,7 @@ export class HaWebRtcPlayer extends LitElement {
if (this._microphoneDenied) {
return "denied";
}
if (this._microphoneConnecting) {
if (this._microphoneConnecting || this._retryMicrophoneTrack) {
return "connecting";
}
return this._localReturnAudioTrack ? "on" : "off";
@@ -110,11 +125,17 @@ export class HaWebRtcPlayer extends LitElement {
}
public async toggleMicrophone() {
if (this._localReturnAudioTrack || this._microphoneConnecting) {
if (
this._localReturnAudioTrack ||
this._microphoneConnecting ||
this._retryMicrophoneTrack
) {
// Stop (not disable) so the browser releases the microphone, also cancels connecting
this._microphoneRequest++;
this._localReturnAudioTrack?.stop();
this._localReturnAudioTrack = undefined;
this._retryMicrophoneTrack?.stop();
this._retryMicrophoneTrack = undefined;
this._microphoneConnecting = false;
this._fireMicrophoneChanged();
await this._microphoneSender?.replaceTrack(null).catch(() => undefined);
@@ -197,6 +218,18 @@ export class HaWebRtcPlayer extends LitElement {
private _cleanUpCount = 0;
private _connectTimeout?: number;
private _retryTimeout?: number;
private _retryMicrophoneTrack?: MediaStreamTrack;
private _retries = 0;
// The stream showed video since it was started, so a lost connection is
// worth a retry
private _hasPlayed = false;
private _handleVisibilityChange = () => {
if (document.pictureInPictureElement) {
// video is playing in picture-in-picture mode, don't do anything
@@ -212,7 +245,7 @@ export class HaWebRtcPlayer extends LitElement {
clearTimeout(this._hiddenCleanupTimeout);
this._hiddenCleanupTimeout = undefined;
} else {
this._startWebRtc();
this._restartWebRtc();
}
};
@@ -253,7 +286,7 @@ export class HaWebRtcPlayer extends LitElement {
public override connectedCallback() {
super.connectedCallback();
if (this.hasUpdated && this.entityid) {
this._startWebRtc();
this._restartWebRtc();
}
document.addEventListener("visibilitychange", this._handleVisibilityChange);
}
@@ -274,6 +307,13 @@ export class HaWebRtcPlayer extends LitElement {
if (!changedProperties.has("entityid")) {
return;
}
this._restartWebRtc();
}
/** Starts a new stream, not a retry of the current one. */
private _restartWebRtc() {
this._retries = 0;
this._hasPlayed = false;
this._startWebRtc();
}
@@ -415,7 +455,7 @@ export class HaWebRtcPlayer extends LitElement {
while (this._candidatesList.length) {
const candidate = this._candidatesList.pop();
if (candidate) {
candidates += `a=${candidate}\r\n`;
candidates += `a=${candidate.candidate}\r\n`;
}
}
@@ -423,6 +463,8 @@ export class HaWebRtcPlayer extends LitElement {
this._logEvent("start webRtcOffer", offer_sdp);
this._startConnectTimeout(ANSWER_TIMEOUT);
this._unsub = webRtcOffer(
this._connection,
this.entityid,
@@ -443,11 +485,61 @@ export class HaWebRtcPlayer extends LitElement {
"ice connection state change",
this._peerConnection?.iceConnectionState
);
if (this._peerConnection?.iceConnectionState === "failed") {
this._peerConnection.restartIce();
const iceState = this._peerConnection?.iceConnectionState;
if (iceState === "connected" || iceState === "completed") {
clearTimeout(this._connectTimeout);
this._connectTimeout = undefined;
} else if (iceState === "failed") {
// An ICE restart needs a new offer, which the backend answers from a new
// peer that can't continue this connection, so start a new one instead.
this._retryOrFail({ type: "no_connection" });
}
};
private _startConnectTimeout(timeout: number) {
clearTimeout(this._connectTimeout);
this._connectTimeout = window.setTimeout(() => {
this._connectTimeout = undefined;
this._logEvent("connect timeout");
this._retryOrFail({ type: "no_connection" });
}, timeout);
}
private _retryOrFail(error: WebRtcPlayerError) {
if (
this._retries >= MAX_RETRIES ||
// No answer or no path for a stream that never played, a retry would
// most likely end the same way
(error.type === "no_connection" && !this._hasPlayed) ||
// A microphone connect the user started is handled by starting again
// without the microphone. A retry keeps the microphone of the stream.
(this._localReturnAudioTrack &&
this._microphoneConnecting &&
this._retries === 0)
) {
this._failStart(error);
return;
}
this._retries++;
this._logEvent("retry", this._retries, error);
// Keep showing the last frame instead of the poster while starting again
this._captureReconnectFrame();
// Taken out before the clean up, so a running microphone is not stopped
const microphoneTrack = this._localReturnAudioTrack;
this._localReturnAudioTrack = undefined;
this._cleanUp();
if (microphoneTrack) {
this._retryMicrophoneTrack = microphoneTrack;
this._fireMicrophoneChanged();
}
this._retryTimeout = window.setTimeout(() => {
this._retryTimeout = undefined;
const track = this._retryMicrophoneTrack;
this._retryMicrophoneTrack = undefined;
this._startWebRtc(track);
}, RETRY_DELAY);
}
private async _handleOfferEvent(
peerConnection: RTCPeerConnection,
event: WebRtcOfferEvent
@@ -470,6 +562,10 @@ export class HaWebRtcPlayer extends LitElement {
this._candidatesList = [];
}
if (event.type === "answer") {
const iceState = peerConnection.iceConnectionState;
if (iceState !== "connected" && iceState !== "completed") {
this._startConnectTimeout(ICE_TIMEOUT);
}
this._logEvent("answer", event.answer);
this._handleAnswer(peerConnection, event);
@@ -495,7 +591,8 @@ export class HaWebRtcPlayer extends LitElement {
}
}
if (event.type === "error") {
this._failStart({ type: "start_failed", message: event.message });
// Often temporary, like the backend still closing the previous session
this._retryOrFail({ type: "start_failed", message: event.message });
}
}
@@ -587,8 +684,13 @@ export class HaWebRtcPlayer extends LitElement {
}
private _failStart(error: WebRtcPlayerError) {
// The camera can reject the microphone, keep the video running without it
if (this._localReturnAudioTrack && this._microphoneConnecting) {
// The camera can reject the microphone, keep the video running without it.
// After retries it is the connection that failed, not the microphone.
if (
this._localReturnAudioTrack &&
this._microphoneConnecting &&
this._retries === 0
) {
showToast(this, {
message: this._localize(
"ui.components.web-rtc-player.microphone_connect_failed",
@@ -599,12 +701,19 @@ export class HaWebRtcPlayer extends LitElement {
return;
}
this._error = error;
this._reconnectPoster = undefined;
this._cleanUp();
// Tell the camera stream this player has no video, so it can fall back
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
}
private _cleanUp() {
this._cleanUpCount++;
this._microphoneRequest++;
clearTimeout(this._connectTimeout);
this._connectTimeout = undefined;
clearTimeout(this._retryTimeout);
this._retryTimeout = undefined;
if (this._remoteStream) {
this._remoteStream.getTracks().forEach((track) => {
track.stop();
@@ -612,9 +721,15 @@ export class HaWebRtcPlayer extends LitElement {
this._remoteStream = undefined;
}
if (this._localReturnAudioTrack || this._microphoneConnecting) {
if (
this._localReturnAudioTrack ||
this._microphoneConnecting ||
this._retryMicrophoneTrack
) {
this._localReturnAudioTrack?.stop();
this._localReturnAudioTrack = undefined;
this._retryMicrophoneTrack?.stop();
this._retryMicrophoneTrack = undefined;
this._microphoneConnecting = false;
this._fireMicrophoneChanged();
}
@@ -666,6 +781,8 @@ export class HaWebRtcPlayer extends LitElement {
this._logEvent("loadedData", data);
this._stopTimer();
this._retries = 0;
this._hasPlayed = true;
// Without a track the microphone is still waiting for permission
if (this._microphoneConnecting && this._localReturnAudioTrack) {
+12
View File
@@ -34,6 +34,8 @@ import type { HASSDomTargetEvent } from "../../common/dom/fire_event";
*
* @attr {string} headline - Primary text. Overridden by the `headline` slot.
* @attr {string} supporting-text - Secondary text. Overridden by the `supporting-text` slot.
* @attr {boolean} wrap-headline - Wraps the headline onto multiple lines instead of truncating it.
* @attr {boolean} wrap-supporting-text - Wraps the supporting text onto multiple lines instead of truncating it.
* @attr {boolean} disabled - Dims the row and blocks pointer events.
*/
@customElement("ha-row-item")
@@ -43,6 +45,12 @@ export class HaRowItem extends LitElement {
@property({ type: String, attribute: "supporting-text" })
public supportingText?: string;
@property({ type: Boolean, reflect: true, attribute: "wrap-headline" })
public wrapHeadline = false;
@property({ type: Boolean, reflect: true, attribute: "wrap-supporting-text" })
public wrapSupportingText = false;
@property({ type: Boolean, reflect: true }) public disabled = false;
protected readonly _slotController = new HasSlotController(
@@ -192,6 +200,10 @@ export class HaRowItem extends LitElement {
text-overflow: ellipsis;
white-space: nowrap;
}
:host([wrap-headline]) .headline,
:host([wrap-supporting-text]) .supporting {
white-space: normal;
}
`;
}
@@ -0,0 +1,128 @@
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { HaListItemButton } from "../item/ha-list-item-button";
import "./ha-media-browser-thumbnail";
/**
* @element ha-media-player-browse-list-item
* @extends {HaListItemButton}
*
* @summary
* Row of the media browser list. Always reserves a graphic next to the title
* so titles line up, and shows a thumbnail with an optional play button over
* it. Without `interactive` the row is plain text, used for the "not shown"
* row. The row is rendered inside the shadow root of `ha-list-virtualized`, so
* it carries its own styles.
*
* @slot start - Play or pick button, shown over the thumbnail.
* @slot headline - Title of the row.
*
* @csspart start - The graphic container.
*
* @attr {string} thumbnail - URL of the thumbnail. Shown inside the graphic.
*/
@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;
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
}
}
@@ -77,7 +77,6 @@ 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,
@@ -88,6 +87,7 @@ 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";
import "./ha-media-player-browse-list-item";
declare global {
interface HASSDomEvents {
@@ -120,105 +120,6 @@ type MediaBrowseListRow =
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;
@@ -1945,6 +1846,5 @@ export class HaMediaPlayerBrowse extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-media-player-browse": HaMediaPlayerBrowse;
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
}
}
@@ -112,7 +112,7 @@ export class HaTracePathDetails extends LitElement {
initialValue: {
options: [],
showIndices: false,
select: () => undefined,
select: () => true,
fixDuplicateIds: async () => undefined,
updateTriggerId: () => false,
},
+201
View File
@@ -0,0 +1,201 @@
import type { LocalizeFunc } from "../common/translations/localize";
export const ROOM_ICONS = {
living_room: [
"mdi:sofa",
"mdi:sofa-single",
"mdi:television",
"mdi:fireplace",
"mdi:floor-lamp",
],
bedroom: ["mdi:bed", "mdi:bed-king", "mdi:bed-double", "mdi:lamp"],
kids_room: ["mdi:teddy-bear", "mdi:toy-brick", "mdi:bunk-bed", "mdi:cradle"],
kitchen: [
"mdi:stove",
"mdi:fridge",
"mdi:countertop",
"mdi:chef-hat",
"mdi:pot-steam",
"mdi:coffee-maker",
],
dining_room: [
"mdi:silverware-fork-knife",
"mdi:table-chair",
"mdi:table-furniture",
"mdi:glass-wine",
],
bathroom: [
"mdi:shower",
"mdi:bathtub",
"mdi:shower-head",
"mdi:toothbrush",
"mdi:hair-dryer",
],
toilet: ["mdi:toilet", "mdi:paper-roll"],
office: [
"mdi:desk",
"mdi:laptop",
"mdi:monitor",
"mdi:chair-rolling",
"mdi:bookshelf",
],
laundry_room: [
"mdi:washing-machine",
"mdi:tumble-dryer",
"mdi:iron",
"mdi:hanger",
],
hallway: ["mdi:door", "mdi:door-open", "mdi:coat-rack", "mdi:key"],
stairs: ["mdi:stairs", "mdi:stairs-up", "mdi:stairs-down"],
garage: ["mdi:garage", "mdi:garage-variant", "mdi:car", "mdi:tools"],
garden: [
"mdi:flower",
"mdi:tree",
"mdi:grass",
"mdi:sprout",
"mdi:watering-can",
"mdi:greenhouse",
],
terrace: [
"mdi:balcony",
"mdi:grill",
"mdi:umbrella-outline",
"mdi:coach-lamp",
"mdi:patio-heater",
],
basement: [
"mdi:home-floor-negative-1",
"mdi:stairs-down",
"mdi:water-boiler",
],
attic: ["mdi:home-roof", "mdi:package-variant-closed"],
storage: ["mdi:archive", "mdi:package-variant-closed", "mdi:warehouse"],
utility_room: [
"mdi:water-boiler",
"mdi:heat-pump",
"mdi:server-network",
"mdi:flash",
],
pool: ["mdi:pool", "mdi:swim"],
media_room: [
"mdi:theater",
"mdi:projector",
"mdi:television",
"mdi:movie-open",
],
game_room: [
"mdi:gamepad-variant",
"mdi:billiards",
"mdi:cards-playing",
"mdi:dice-multiple",
],
music_room: ["mdi:piano", "mdi:guitar-acoustic", "mdi:music"],
library: ["mdi:bookshelf", "mdi:book-open-variant", "mdi:library"],
bar: [
"mdi:glass-cocktail",
"mdi:glass-mug-variant",
"mdi:bottle-wine",
"mdi:beer",
],
dressing_room: [
"mdi:hanger",
"mdi:wardrobe",
"mdi:tshirt-crew",
"mdi:shoe-heel",
],
workshop: ["mdi:tools", "mdi:hammer-wrench", "mdi:toolbox", "mdi:saw-blade"],
server_room: ["mdi:server-network", "mdi:server", "mdi:router-network"],
safe_room: ["mdi:shield-home", "mdi:shield-lock", "mdi:safe"],
prayer_room: ["mdi:hands-pray", "mdi:meditation", "mdi:candle"],
sauna: ["mdi:spa", "mdi:hot-tub", "mdi:thermometer-high"],
outdoor_kitchen: ["mdi:grill", "mdi:grill-outline", "mdi:pizza"],
driveway: ["mdi:road-variant", "mdi:car", "mdi:gate"],
} as const satisfies Record<string, readonly string[]>;
export type RoomType = keyof typeof ROOM_ICONS;
type RoomKeywords = Partial<Record<RoomType, string[]>>;
export const ROOM_TYPES = Object.keys(ROOM_ICONS) as RoomType[];
export const isRoomType = (value: string): value is RoomType =>
(ROOM_TYPES as string[]).includes(value);
// Languages written without spaces between words
const NO_WORD_SPACING =
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}]/u;
const normalizeRoomText = (text: string): string =>
text
.normalize("NFD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.replace(/['’]/g, "")
.replace(/[^\p{L}\p{N}]+/gu, " ")
.trim();
interface RoomMatch {
room: RoomType;
start: number;
end: number;
}
const findMatches = (name: string, keywords: RoomKeywords): RoomMatch[] => {
const text = ` ${normalizeRoomText(name)} `;
const candidates: RoomMatch[] = [];
for (const room of ROOM_TYPES) {
for (const keyword of keywords[room] ?? []) {
const phrase = normalizeRoomText(keyword);
if (!phrase) {
continue;
}
const needle = NO_WORD_SPACING.test(phrase) ? phrase : ` ${phrase} `;
const start = text.indexOf(needle);
if (start !== -1) {
candidates.push({ room, start, end: start + needle.length });
}
}
}
// The longest phrase wins, so "guest bedroom" is not also read as "bedroom"
candidates.sort((a, b) => b.end - b.start - (a.end - a.start));
const kept: RoomMatch[] = [];
for (const match of candidates) {
const overlaps = kept.some(
(other) => match.start < other.end - 1 && other.start < match.end - 1
);
if (!overlaps) {
kept.push(match);
}
}
return kept.sort((a, b) => a.start - b.start);
};
const matchRoomTypes = (
names: string[],
keywords: RoomKeywords
): RoomType[] => {
const rooms = new Set<RoomType>();
for (const name of names) {
for (const match of findMatches(name, keywords)) {
rooms.add(match.room);
}
}
return [...rooms];
};
const roomIconSuggestions = (rooms: RoomType[]): string[] => [
...new Set(rooms.flatMap((room) => ROOM_ICONS[room])),
];
export const getAreaIconSuggestions = (
names: string[],
localize: LocalizeFunc
): string[] => {
const keywords: RoomKeywords = Object.fromEntries(
ROOM_TYPES.map((room) => [
room,
localize(`ui.components.rooms.keywords.${room}`).split("|"),
])
);
return roomIconSuggestions(matchRoomTypes(names, keywords));
};
+80
View File
@@ -0,0 +1,80 @@
export const STREAM_TYPE_HLS = "hls";
export const STREAM_TYPE_WEB_RTC = "web_rtc";
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
export const MJPEG_STREAM = "mjpeg";
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
export interface CameraStream {
type: CameraStreamType;
visible: boolean;
}
/** What a player reported, `hasVideo: false` means it failed to load. */
export interface CameraStreamTracks {
hasAudio: boolean;
hasVideo: boolean;
}
export interface CameraStreamSelectionOptions {
supportedTypes?: StreamType[];
hlsStreams?: CameraStreamTracks;
webRtcStreams?: CameraStreamTracks;
}
/**
* Decides which players are rendered and which one is shown. Hidden players
* are still loading in the background.
*/
export const selectCameraStreams = ({
supportedTypes,
hlsStreams,
webRtcStreams,
}: CameraStreamSelectionOptions): CameraStream[] => {
if (!supportedTypes) {
return [];
}
if (supportedTypes.length === 0) {
// doesn't support any stream type, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
if (supportedTypes.length === 1) {
// only 1 stream type, no need to choose
if (
(supportedTypes[0] === STREAM_TYPE_HLS &&
hlsStreams?.hasVideo === false) ||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
webRtcStreams?.hasVideo === false)
) {
// stream failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
return [{ type: supportedTypes[0], visible: true }];
}
const hlsFailed = hlsStreams?.hasVideo === false;
if (webRtcStreams?.hasVideo) {
// WebRTC is preferred whenever it plays, it has the lowest latency
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
if (webRtcStreams?.hasVideo === false) {
if (hlsFailed) {
// both streams failed to load, fallback to mjpeg
return [{ type: MJPEG_STREAM, visible: true }];
}
return [{ type: STREAM_TYPE_HLS, visible: true }];
}
// WebRTC is still loading
if (hlsFailed) {
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
}
return [
{ type: STREAM_TYPE_HLS, visible: true },
{ type: STREAM_TYPE_WEB_RTC, visible: false },
];
};
+6 -4
View File
@@ -7,13 +7,15 @@ import { timeCacheEntityPromiseFunc } from "../common/util/time-cache-entity-pro
import type { HomeAssistant, HomeAssistantApi } from "../types";
import { fileDownload } from "../util/file_download";
import { getSignedPath } from "./auth";
import type { StreamType } from "./camera-streams";
export const CAMERA_ORIENTATIONS = [1, 2, 3, 4, 6, 8];
export const STREAM_TYPE_HLS = "hls";
export const STREAM_TYPE_WEB_RTC = "web_rtc";
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
export {
STREAM_TYPE_HLS,
STREAM_TYPE_WEB_RTC,
type StreamType,
} from "./camera-streams";
export { CameraEntityFeature } from "./feature/camera_entity_feature";
+15
View File
@@ -60,3 +60,18 @@ export const validateHassioSession = async (
): Promise<void> => {
await hass.callWS({ type: "supervisor/ingress/validate_session", session });
};
// Extends the session, or replaces it with a new one for the app if it has
// expired. Returns the session to keep using.
export const refreshHassioSession = async (
hass: Pick<HomeAssistant, "callWS">,
slug: string,
session: string
): Promise<string> => {
try {
await validateHassioSession(hass, session);
return session;
} catch (_err: any) {
return createHassioSession(hass, slug);
}
};
+11 -7
View File
@@ -209,7 +209,15 @@ export const watchForNewMatterDevice = (
callback: (device: DeviceRegistryEntry) => void
): UnsubscribeFunc => {
let curMatterDevices: Set<string> | undefined;
const unsubDeviceReg = subscribeDeviceRegistry(hass.connection, (entries) => {
let unsubDeviceReg: UnsubscribeFunc | undefined;
// Callers also unsubscribe after a find. The registry collection counts its
// subscribers, so a second unsubscribe would stop its updates for everyone.
const unsubscribe = () => {
unsubDeviceReg?.();
unsubDeviceReg = undefined;
curMatterDevices = undefined;
};
unsubDeviceReg = subscribeDeviceRegistry(hass.connection, (entries) => {
if (!curMatterDevices) {
curMatterDevices = new Set(
Object.values(entries)
@@ -226,15 +234,11 @@ export const watchForNewMatterDevice = (
!curMatterDevices!.has(device.id)
);
if (newMatterDevices.length) {
unsubDeviceReg();
curMatterDevices = undefined;
unsubscribe();
callback(newMatterDevices[0]);
}
});
return () => {
unsubDeviceReg();
curMatterDevices = undefined;
};
return unsubscribe;
};
export const redirectOnNewMatterDevice = (
@@ -167,16 +167,12 @@ export class HaMoreInfoFavorites extends LitElement {
display: flex;
align-items: center;
justify-content: center;
margin: calc(var(--ha-space-2) * -1);
gap: var(--ha-space-4);
flex-wrap: wrap;
max-width: var(--favorite-items-max-width, 250px);
user-select: none;
}
.container > * {
margin: var(--ha-space-2);
}
.favorite {
display: block;
}
+16 -8
View File
@@ -60,14 +60,25 @@
/* Margins, not flex `gap` (Safari 14.1). */
#ha-launch-screen .ha-launch-screen-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: -4px 16px;
flex-direction: column;
align-items: center;
margin: 0 16px;
}
#ha-launch-screen .ha-launch-screen-actions label {
display: flex;
align-items: center;
margin-top: 8px;
padding: 8px 16px;
font-size: 14px;
cursor: pointer;
}
#ha-launch-screen .ha-launch-screen-actions input {
margin: 0 8px 0 0;
accent-color: #009ac7;
}
#ha-launch-screen .ha-launch-screen-actions button {
margin: 4px;
padding: 8px 16px;
border: 1px solid transparent;
border: 1px solid currentColor;
border-radius: 18px;
background: none;
color: #009ac7;
@@ -76,9 +87,6 @@
font-weight: 500;
cursor: pointer;
}
#ha-launch-screen .ha-launch-screen-actions .ha-launch-screen-continue {
border-color: currentColor;
}
.ohf-logo {
margin: 48px 0;
display: flex;
+25 -22
View File
@@ -116,30 +116,33 @@
actions.className = "ha-launch-screen-actions";
box.appendChild(actions);
function addButton(label, value) {
var button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.addEventListener("click", function () {
try {
localStorage.setItem(ACCEPTED_KEY, value());
} catch (_err) {
// Continue this time only.
}
box.removeChild(actions);
loadApp();
});
actions.appendChild(button);
return button;
}
var always = null;
var button = document.createElement("button");
button.type = "button";
button.textContent = "Continue anyway";
button.addEventListener("click", function () {
try {
localStorage.setItem(
ACCEPTED_KEY,
always && always.checked ? "always" : String(Date.now())
);
} catch (_err) {
// Continue this time only.
}
box.removeChild(actions);
loadApp();
});
actions.appendChild(button);
addButton("Continue anyway", function () {
return String(Date.now());
}).className = "ha-launch-screen-continue";
// From the first reminder on. A checkbox, so it is not chosen by
// accident.
if (acceptedAt) {
addButton("Don't show again", function () {
return "always";
});
var label = document.createElement("label");
always = document.createElement("input");
always.type = "checkbox";
label.appendChild(always);
label.appendChild(document.createTextNode("Don't show again"));
actions.appendChild(label);
}
})();
}
+51 -8
View File
@@ -16,7 +16,7 @@ import type { IngressAppInfo } from "../../data/hassio/ingress";
import {
createHassioSession,
fetchIngressAppInfo,
validateHassioSession,
refreshHassioSession,
} from "../../data/hassio/ingress";
import {
showAlertDialog,
@@ -60,6 +60,10 @@ class HaPanelApp extends LitElement {
private _sessionKeepAlive?: number;
private _session?: { slug: string; session: string };
private _sessionRefresh?: Promise<void>;
private _fetchDataTimeout?: number;
private _autoRetryUntil?: number;
@@ -92,17 +96,22 @@ class HaPanelApp extends LitElement {
super.connectedCallback();
window.addEventListener("message", this._handleIframeMessage);
window.addEventListener("resize", this._handleResize);
document.addEventListener("visibilitychange", this._handleVisibility);
document.addEventListener("resume", this._handleVisibility);
}
public disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener("message", this._handleIframeMessage);
window.removeEventListener("resize", this._handleResize);
document.removeEventListener("visibilitychange", this._handleVisibility);
document.removeEventListener("resume", this._handleVisibility);
if (this._sessionKeepAlive) {
clearInterval(this._sessionKeepAlive);
this._sessionKeepAlive = undefined;
}
this._session = undefined;
if (this._fetchDataTimeout) {
clearTimeout(this._fetchDataTimeout);
this._fetchDataTimeout = undefined;
@@ -342,17 +351,51 @@ class HaPanelApp extends LitElement {
if (this._sessionKeepAlive) {
clearInterval(this._sessionKeepAlive);
}
this._sessionKeepAlive = window.setInterval(async () => {
try {
await validateHassioSession(this.hass, session);
} catch (_err: any) {
session = await createHassioSession(this.hass, addonSlug);
}
}, 60000);
this._session = { slug: addonSlug, session };
this._sessionKeepAlive = window.setInterval(this._refreshSession, 60000);
this._addon = addon;
}
// The keep-alive timer does not run while the device sleeps, so the session
// may have expired by the time the page is visible again. Refresh it right
// away instead of leaving the app unreachable until the next tick.
// "resume" only fires in Chromium after a frozen page, other browsers rely
// on "visibilitychange".
private _handleVisibility = () => {
if (!document.hidden) {
this._refreshSession();
}
};
private _refreshSession = (): Promise<void> => {
const current = this._session;
if (!current) {
return Promise.resolve();
}
if (this._sessionRefresh) {
return this._sessionRefresh;
}
this._sessionRefresh = refreshHassioSession(
this.hass,
current.slug,
current.session
)
.then((session) => {
// the panel may have switched to another app meanwhile
if (this._session === current) {
this._session = { slug: current.slug, session };
}
})
.catch((_err: any) => {
// Connection to Home Assistant is gone, the next refresh will retry
})
.finally(() => {
this._sessionRefresh = undefined;
});
return this._sessionRefresh;
};
private async _checkLoaded(ev: Event): Promise<void> {
const iframe = ev.target as HTMLIFrameElement;
@@ -816,7 +816,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
this._currentAddon.version
? html`
<wa-divider></wa-divider>
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.i18n.localize(
"ui.panel.config.apps.dashboard.option.boot.title"
@@ -842,7 +842,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
${
this._currentAddon.startup !== "once"
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.i18n.localize(
"ui.panel.config.apps.dashboard.option.watchdog.title"
@@ -867,7 +867,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
`
: nothing
}
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.i18n.localize(
"ui.panel.config.apps.dashboard.option.auto_update.title"
@@ -893,7 +893,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
!this._computeCannotIngressSidebar &&
this._currentAddon.ingress
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.i18n.localize(
"ui.panel.config.apps.dashboard.option.ingress_panel.title"
@@ -923,7 +923,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
${
this._computeUsesProtectedOptions
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.i18n.localize(
"ui.panel.config.apps.dashboard.option.protected.title"
@@ -954,7 +954,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
${
this._currentAddon.version && this._currentAddon.state === "started"
? html`<wa-divider></wa-divider>
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="supporting-text">
${this.i18n.localize(
"ui.panel.config.apps.dashboard.hostname"
@@ -1630,10 +1630,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
color: var(--ha-color-text-secondary);
}
.controls ha-row-item::part(supporting-text) {
white-space: normal;
}
.controls .content {
display: flex;
flex-direction: column;
@@ -1,5 +1,5 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { CSSResultGroup } from "lit";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event";
@@ -29,6 +29,10 @@ import type {
AreaRegistryEntryMutableParams,
} from "../../../data/area/area_registry";
import { deleteAreaRegistryEntry } from "../../../data/area/area_registry";
import {
getAreaIconSuggestions,
ROOM_ICONS,
} from "../../../data/area_icon_suggestions";
import {
SENSOR_DEVICE_CLASS_HUMIDITY,
SENSOR_DEVICE_CLASS_TEMPERATURE,
@@ -96,6 +100,10 @@ class DialogAreaDetail
@state() private _submitting = false;
@state() private _suggestedIcons?: string[];
private _iconFollowsName = false;
@state() private _open = false;
@state() private _suggestionInclude: MetadataSuggestionInclude = {
@@ -128,6 +136,7 @@ class DialogAreaDetail
this._temperatureEntity = null;
this._humidityEntity = null;
}
this._iconFollowsName = !this._params.entry;
this._open = true;
this._initDirtyTracking({ type: "deep" }, this._currentState());
await this.updateComplete;
@@ -151,6 +160,30 @@ class DialogAreaDetail
return true;
}
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (changedProps.has("_name") || changedProps.has("_aliases")) {
this._updateSuggestedIcons();
}
}
private _updateSuggestedIcons() {
const icons = getAreaIconSuggestions(
[this._name ?? "", ...(this._aliases ?? [])],
this.hass.localize
);
this._suggestedIcons = icons;
if (this._iconFollowsName) {
const untouched = !this.isDirtyState;
this._icon = icons[0] ?? null;
if (untouched) {
this._initDirtyTracking({ type: "deep" }, this._currentState());
} else {
this._updateDirtyState(this._currentState());
}
}
}
private _entityName(entityId: string | null): string | null {
const stateObj = entityId ? this.hass.states[entityId] : undefined;
return stateObj ? this.hass.formatEntityName(stateObj) : null;
@@ -193,6 +226,7 @@ class DialogAreaDetail
.value=${this._icon}
@value-changed=${this._iconChanged}
.label=${this.hass.localize("ui.panel.config.areas.editor.icon")}
.suggestedIcons=${this._suggestedIcons}
></ha-icon-picker>
<ha-floor-picker
@@ -300,6 +334,7 @@ class DialogAreaDetail
this._suggestionInclude = {
...this._suggestionInclude,
name: this._name.trim() === "",
room: !this._icon || this._iconFollowsName,
};
return generateMetadataSuggestionTask<{
@@ -349,6 +384,11 @@ class DialogAreaDetail
this._floor = processed.floor;
}
if (processed.room && (!this._icon || this._iconFollowsName)) {
this._icon = ROOM_ICONS[processed.room][0];
this._iconFollowsName = false;
}
this._updateDirtyState(this._currentState());
}
@@ -464,6 +504,7 @@ class DialogAreaDetail
private _iconChanged(ev) {
this._error = undefined;
this._icon = ev.detail.value;
this._iconFollowsName = false;
this._updateDirtyState(this._currentState());
}
@@ -6,8 +6,10 @@ import { consume } from "../../../../../common/decorators/consume";
import { ensureArray } from "../../../../../common/array/ensure-array";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { capitalizeFirstLetter } from "../../../../../common/string/capitalize-first-letter";
import "../../../../../components/animation/ha-fade-in";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-button";
import "../../../../../components/ha-spinner";
import "../../../../../components/ha-svg-icon";
import "../../../../../components/ha-trigger-icon";
import "../../../../../components/item/ha-list-item-option";
@@ -17,6 +19,7 @@ import type { TriggerCondition } from "../../../../../data/automation";
import {
automationTriggerContext,
hasCustomTriggerId,
triggerOptionsResolved,
type AutomationTriggerContext,
type TriggerIdOption,
} from "../../trigger/automation-trigger-id";
@@ -53,16 +56,33 @@ export class HaTriggerCondition extends LitElement {
const selectedIds = (ensureArray(this.condition.id) ?? []).filter(Boolean);
const triggerIdOptions = this._triggers?.options ?? [];
const missingIds = this._missingIds(this.condition.id, triggerIdOptions);
const status = this._triggers?.blueprintStatus;
const resolved = triggerOptionsResolved(this._triggers);
if (!triggerIdOptions.length && !selectedIds.length) {
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.no_triggers"
);
switch (status) {
case "loading":
return html`<ha-fade-in .delay=${500}>
<ha-spinner size="small"></ha-spinner>
</ha-fade-in>`;
case "failed":
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.blueprint_triggers_unavailable"
);
case "loaded":
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.blueprint_no_trigger_ids"
);
case undefined:
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.no_triggers"
);
}
}
return html`
${
missingIds.length
resolved && missingIds.length
? html`<ha-alert alert-type="warning">
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_triggers"
@@ -106,7 +126,13 @@ export class HaTriggerCondition extends LitElement {
appearance="checkbox"
>
<span slot="start" class="trigger-row-leading">
<span class="trigger-index-badge">${option.index + 1}</span>
${
this._triggers?.showIndices
? html`<span class="trigger-index-badge"
>${option.index + 1}</span
>`
: nothing
}
<ha-trigger-icon
.trigger=${
"trigger" in option.trigger ? option.trigger.trigger : ""
@@ -119,7 +145,9 @@ export class HaTriggerCondition extends LitElement {
)}
</span>
${
option.duplicate || hasCustomTriggerId(option)
option.duplicate ||
hasCustomTriggerId(option) ||
!this._triggers?.showIndices
? html`<span
slot="supporting-text"
class="trigger-id ${option.duplicate ? "duplicate" : ""}"
@@ -152,14 +180,22 @@ export class HaTriggerCondition extends LitElement {
.disabled=${this.disabled}
appearance="checkbox"
>
<span slot="start" class="missing-trigger-badge">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span class="missing-trigger-id">${id}</span>
</span>
${
resolved
? html`<span slot="start" class="missing-trigger-badge">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span class="missing-trigger-id">${id}</span>
</span>`
: nothing
}
<span slot="headline">
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)}
${
resolved
? this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)
: id
}
</span>
</ha-list-item-option>
`
@@ -197,8 +233,7 @@ export class HaTriggerCondition extends LitElement {
? ids
: [...ids, id]
: ids.filter((_id) => _id !== id);
if (this._triggers) {
this._triggers.select(this.condition, selectedIds);
if (this._triggers?.select(this.condition, selectedIds)) {
return;
}
fireEvent(this, "value-changed", {
@@ -146,6 +146,15 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this._manualEditor?.resetPastedConfig();
this._updateConfig(config);
},
fetchBlueprintTriggers: async ({ path, input }) => {
const result = await substituteBlueprint(
this.hass,
"automation",
path,
input || {}
);
return normalizeAutomationConfig(result.substituted_config).triggers;
},
});
private _newAutomationId?: string;
@@ -3,11 +3,14 @@ import type { LitElement, ReactiveController } from "lit";
import memoizeOne from "memoize-one";
import type {
AutomationConfig,
BlueprintAutomationConfig,
SidebarConfig,
Trigger,
TriggerCondition,
} from "../../../../data/automation";
import { ContextSubscriptionController } from "../../../../common/decorators/consume";
import { debounce } from "../../../../common/util/debounce";
import { deepEqual } from "../../../../common/util/deep-equal";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { internationalizationContext } from "../../../../data/context";
import { showConfirmationDialog } from "../../../../dialogs/generic/show-dialog-box";
@@ -16,12 +19,15 @@ import {
automationTriggerContext,
cleanupRemovedGeneratedTriggerReferences,
cleanupUnusedGeneratedTriggerIds,
getBlueprintTriggerIdOptions,
getTriggerIdOptions,
getExplicitTriggerIds,
isGeneratedTriggerId,
makeDuplicateTriggerIdsUnique,
replaceLeafTrigger,
updateTriggerCondition,
type TriggerIdOption,
type BlueprintTriggersStatus,
} from "./automation-trigger-id";
import { preserveAutomationRowKeys } from "../ha-automation-sortable-list-mixin";
@@ -31,6 +37,10 @@ interface AutomationTriggerControllerOptions {
canEdit: () => boolean;
/** Apply one complete change through the editor's undo and dirty-state handling. */
commit: (config: AutomationConfig) => void;
/** Resolve a blueprint automation's triggers, with its inputs substituted. */
fetchBlueprintTriggers: (
useBlueprint: BlueprintAutomationConfig["use_blueprint"]
) => Promise<Trigger | Trigger[] | undefined>;
}
/**
@@ -43,6 +53,9 @@ interface AutomationTriggerControllerOptions {
*
* The transformation helpers only change configuration. This controller preserves
* the corresponding row keys so an open sidebar continues to track the edited row.
*
* A blueprint automation has no triggers of its own: options come from the
* blueprint's substituted triggers, and conditions in its inputs change themselves.
*/
export class AutomationTriggerController implements ReactiveController {
// Only read in event handlers, so it does not need to rerender the host.
@@ -54,6 +67,18 @@ export class AutomationTriggerController implements ReactiveController {
// changes, so rendering and selection use the same IDs across host updates.
private _getTriggerIdOptions = memoizeOne(getTriggerIdOptions);
private _getBlueprintTriggerIdOptions = memoizeOne(
getBlueprintTriggerIdOptions
);
/** The blueprint use whose triggers were last requested. */
private _blueprintRequested?: BlueprintAutomationConfig["use_blueprint"];
private _blueprintTriggers?: Trigger | Trigger[];
/** "failed" while required inputs are empty. */
private _blueprintStatus: BlueprintTriggersStatus = "loading";
constructor(
private _host: LitElement,
private _options: AutomationTriggerControllerOptions
@@ -78,15 +103,39 @@ export class AutomationTriggerController implements ReactiveController {
_host.addController(this);
}
public hostDisconnected() {
this._fetchBlueprintTriggers.cancel();
this._blueprintRequested = undefined;
}
/** Publish options before descendants render, including after undo or redo. */
public hostUpdate() {
const config = this._options.getConfig();
if (!config) {
return;
}
const options = this._getTriggerIdOptions(config.triggers);
if (options !== this._provider.value.options) {
this._provider.setValue({ ...this._provider.value, options });
let options: TriggerIdOption[];
let blueprintStatus: BlueprintTriggersStatus | undefined;
let showIndices = this._provider.value.showIndices;
if ("use_blueprint" in config && config.use_blueprint) {
this._requestBlueprintTriggers(config.use_blueprint);
options = this._getBlueprintTriggerIdOptions(this._blueprintTriggers);
blueprintStatus = this._blueprintStatus;
showIndices = false;
} else {
options = this._getTriggerIdOptions(config.triggers);
}
if (
options !== this._provider.value.options ||
blueprintStatus !== this._provider.value.blueprintStatus ||
showIndices !== this._provider.value.showIndices
) {
this._provider.setValue({
...this._provider.value,
options,
blueprintStatus,
showIndices,
});
}
}
@@ -138,11 +187,55 @@ export class AutomationTriggerController implements ReactiveController {
return cleaned;
}
private _selectTriggerIds = (condition: TriggerCondition, ids: string[]) => {
const config = this._options.getConfig();
if (!config || !this._options.canEdit()) {
/** Request the blueprint's triggers again whenever its path or inputs change. */
private _requestBlueprintTriggers(
useBlueprint: BlueprintAutomationConfig["use_blueprint"]
) {
if (deepEqual(useBlueprint, this._blueprintRequested)) {
return;
}
if (useBlueprint.path !== this._blueprintRequested?.path) {
this._blueprintTriggers = undefined;
}
this._blueprintStatus = "loading";
this._blueprintRequested = useBlueprint;
this._fetchBlueprintTriggers(useBlueprint);
}
private _fetchBlueprintTriggers = debounce(
async (useBlueprint: BlueprintAutomationConfig["use_blueprint"]) => {
let triggers: Trigger | Trigger[] | undefined;
try {
triggers = await this._options.fetchBlueprintTriggers(useBlueprint);
} catch (_err) {
if (useBlueprint === this._blueprintRequested) {
this._blueprintStatus = "failed";
this._host.requestUpdate();
}
return;
}
if (useBlueprint !== this._blueprintRequested) {
return;
}
this._blueprintTriggers = triggers;
this._blueprintStatus = "loaded";
this._host.requestUpdate();
},
500,
true
);
private _selectTriggerIds = (
condition: TriggerCondition,
ids: string[]
): boolean => {
const config = this._options.getConfig();
if (config && "use_blueprint" in config) {
return false;
}
if (!config || !this._options.canEdit()) {
return true;
}
const triggers = assignGeneratedTriggerIds(
config.triggers,
this._getTriggerIdOptions(config.triggers),
@@ -157,6 +250,7 @@ export class AutomationTriggerController implements ReactiveController {
// Generated IDs that no condition or action references are no longer in use.
// Strip them so the YAML does not accumulate stale identifiers.
this._commit(cleanupUnusedGeneratedTriggerIds(updated));
return true;
};
private _fixDuplicateTriggerIds = async () => {
@@ -38,13 +38,28 @@ export interface TriggerIdOption {
duplicate: boolean;
}
/**
* Whether a blueprint's substituted triggers are known. While "loading" or
* "failed", options keep the last triggers fetched, if any.
*/
export type BlueprintTriggersStatus = "loaded" | "loading" | "failed";
/** Controller-provided options and operations for editors, sidebars, and row summaries. */
export interface AutomationTriggerContext {
options: TriggerIdOption[];
/**
* Left out for an automation with its own triggers. Set for a blueprint
* automation, whose missing IDs can only be flagged once "loaded".
*/
blueprintStatus?: BlueprintTriggersStatus;
/** True while the user is editing a `triggered_by` condition; trigger rows show their index badges only in this state. */
showIndices: boolean;
/** Pass the original condition object so identical conditions remain distinguishable. */
select: (condition: TriggerCondition, ids: string[]) => void;
/**
* Pass the original condition object so identical conditions remain distinguishable.
* Return false when the condition is not one of the automation's conditions, as in
* a blueprint automation, whose conditions live in its inputs.
*/
select: (condition: TriggerCondition, ids: string[]) => boolean;
/** Requests confirmation before migrating duplicate IDs throughout the automation. */
fixDuplicateIds: () => Promise<void>;
/**
@@ -54,6 +69,13 @@ export interface AutomationTriggerContext {
updateTriggerId: (original: Trigger, updated: Trigger) => boolean;
}
/** Whether options list every trigger, so an ID not among them is really missing. */
export const triggerOptionsResolved = (
context: AutomationTriggerContext | undefined
): boolean =>
context?.blueprintStatus === undefined ||
context.blueprintStatus === "loaded";
export const automationTriggerContext =
createContext<AutomationTriggerContext>("automationTriggers");
@@ -140,6 +162,27 @@ export const getTriggerIdOptions = (
});
};
/**
* Build options from a blueprint's substituted triggers. The blueprint owns its
* triggers, so only those with a stored ID can be referenced, and triggers sharing
* an ID are one option: a condition on that ID matches any of them.
*/
export const getBlueprintTriggerIdOptions = (
triggers: Trigger | Trigger[] | undefined
): TriggerIdOption[] => {
const options: TriggerIdOption[] = [];
const seenIds = new Set<string>();
flattenTriggers(triggers).forEach((trigger, index) => {
const id = getTriggerId(trigger);
if (!id || seenIds.has(id)) {
return;
}
seenIds.add(id);
options.push({ id, trigger, index, draft: false, duplicate: false });
});
return options;
};
/**
* Transform leaf triggers recursively, retaining list wrappers and scalar/array shape.
* Copy only changed branches; callbacks must return replacements rather than mutate leaves.
@@ -14,6 +14,7 @@ import type { EntityRegistryEntry } from "../../../../data/entity/entity_registr
import type { HomeAssistant } from "../../../../types";
import {
automationTriggerContext,
triggerOptionsResolved,
type AutomationTriggerContext,
} from "./automation-trigger-id";
@@ -41,6 +42,7 @@ export class HaAutomationTriggerReferences extends LitElement {
const missingIds = selectedIds.filter(
(id) => !options.some((option) => option.id === id)
);
const resolved = triggerOptionsResolved(this._triggers);
if (options.length && !selectedIds.length) {
return html`<span class="trigger-reference no-selection">
@@ -87,17 +89,21 @@ export class HaAutomationTriggerReferences extends LitElement {
</span>
`
),
missingIds.map(
() => html`
<span class="trigger-reference missing">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span>
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)}
</span>
</span>
`
missingIds.map((id) =>
resolved
? html`
<span class="trigger-reference missing">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span>
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)}
</span>
</span>
`
: html`<span class="trigger-reference">
<span class="trigger-reference-label">${id}</span>
</span>`
),
];
}
@@ -21,7 +21,7 @@ class HaBackupConfigAddon extends LitElement {
protected render() {
return html`
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
`ui.panel.config.backup.schedule.update_preference.label`
@@ -55,7 +55,7 @@ class HaBackupConfigAddon extends LitElement {
]}
></ha-select>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(`ui.panel.config.backup.schedule.retention`)}
</span>
@@ -113,10 +113,6 @@ class HaBackupConfigAddon extends LitElement {
ha-list-base {
--ha-row-item-padding-inline: 0;
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: wrap;
}
ha-select {
min-width: 210px;
}
@@ -197,7 +197,7 @@ class HaBackupConfigAgents extends LitElement {
!this.cloudStatus.active_subscription;
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
${this._renderAgentIcon(agentId)}
<div slot="headline" class="name">${name}</div>
${
@@ -248,7 +248,7 @@ class HaBackupConfigAgents extends LitElement {
);
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline>
${this._renderAgentIcon(agentId)}
<div slot="headline" class="name">${name}</div>
<ha-icon-button
@@ -317,10 +317,6 @@ class HaBackupConfigAgents extends LitElement {
--mdc-icon-size: 48px;
color: var(--primary-text-color);
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: wrap;
}
ha-list-item-base::part(end) {
gap: var(--ha-space-2);
}
@@ -239,7 +239,7 @@ class HaBackupConfigData extends LitElement {
return html`
${this._renderSizeEstimate()}
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<ha-svg-icon slot="start" .path=${mdiCog}></ha-svg-icon>
<span slot="headline">
${this.hass.localize("ui.panel.config.backup.data.ha_settings")}
@@ -266,7 +266,7 @@ class HaBackupConfigData extends LitElement {
${
this._showDbOption
? html`<ha-list-item-base>
? html`<ha-list-item-base wrap-headline wrap-supporting-text>
<ha-svg-icon slot="start" .path=${mdiChartBox}></ha-svg-icon>
<span slot="headline">
${this.hass.localize("ui.panel.config.backup.data.history")}
@@ -288,7 +288,7 @@ class HaBackupConfigData extends LitElement {
${
isHassio
? html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<ha-svg-icon
slot="start"
.path=${mdiPlayBoxMultiple}
@@ -309,7 +309,7 @@ class HaBackupConfigData extends LitElement {
></ha-switch>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<ha-svg-icon slot="start" .path=${mdiFolder}></ha-svg-icon>
<span slot="headline">
${this.hass.localize(
@@ -332,7 +332,7 @@ class HaBackupConfigData extends LitElement {
${
this._hasLocalAddons(this._addons)
? html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<ha-svg-icon
slot="start"
.path=${mdiFolder}
@@ -360,7 +360,7 @@ class HaBackupConfigData extends LitElement {
${
this._addons.length
? html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<ha-svg-icon
slot="start"
.path=${mdiPuzzle}
@@ -566,10 +566,6 @@ class HaBackupConfigData extends LitElement {
ha-list-base {
--ha-row-item-padding-inline: 0;
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: wrap;
}
ha-list-item-base::part(start) {
color: var(--ha-color-text-secondary);
}
@@ -25,7 +25,7 @@ class HaBackupConfigEncryptionKey extends LitElement {
if (this._value) {
return html`
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.encryption_key.download_emergency_kit"
@@ -48,7 +48,7 @@ class HaBackupConfigEncryptionKey extends LitElement {
)}
</ha-button>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.encryption_key.show_encryption_key"
@@ -70,7 +70,7 @@ class HaBackupConfigEncryptionKey extends LitElement {
)}
</ha-button>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.encryption_key.change_encryption_key"
@@ -99,7 +99,7 @@ class HaBackupConfigEncryptionKey extends LitElement {
return html`
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.encryption_key.set_encryption_key"
@@ -152,10 +152,6 @@ class HaBackupConfigEncryptionKey extends LitElement {
ha-list-base {
--ha-row-item-padding-inline: 0;
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: wrap;
}
ha-button[size="s"] ha-svg-icon {
--mdc-icon-size: 16px;
}
@@ -105,7 +105,7 @@ class HaBackupConfigRetention extends LitElement {
}
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${
this.headline ??
@@ -256,11 +256,6 @@ class HaBackupConfigRetention extends LitElement {
ha-row-item::part(end) {
align-items: flex-start;
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: wrap;
}
ha-select {
min-width: 210px;
}
@@ -121,7 +121,7 @@ class HaBackupConfigSchedule extends LitElement {
return html`
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.schedule.schedule"
@@ -154,7 +154,7 @@ class HaBackupConfigSchedule extends LitElement {
)}
outlined
>
<ha-row-item class="days">
<ha-row-item wrap-headline class="days">
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.schedule.backup_every"
@@ -186,7 +186,7 @@ class HaBackupConfigSchedule extends LitElement {
(data.recurrence === BackupScheduleRecurrence.CUSTOM_DAYS &&
data.days.length > 0)
? html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.schedule.time"
@@ -231,7 +231,7 @@ class HaBackupConfigSchedule extends LitElement {
)}
outlined
>
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.schedule.custom_time_label"
@@ -266,7 +266,7 @@ class HaBackupConfigSchedule extends LitElement {
${
this.supervisor
? html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
`ui.panel.config.backup.schedule.update_preference.label`
@@ -415,12 +415,6 @@ class HaBackupConfigSchedule extends LitElement {
ha-list-base {
--ha-row-item-padding-inline: 0;
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text),
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: wrap;
}
ha-select {
min-width: 210px;
}
@@ -65,7 +65,7 @@ class HaBackupOverviewBackups extends LitElement {
return html`
<ha-backup-summary-card .heading=${heading} .status=${status}>
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline>
<ha-svg-icon slot="start" .path=${mdiBackupRestore}></ha-svg-icon>
<span slot="headline" class=${headline === null ? "skeleton" : ""}
>${headline}</span
@@ -74,7 +74,7 @@ class HaBackupOverviewBackups extends LitElement {
${
description || description === null
? html`
<ha-list-item-base>
<ha-list-item-base wrap-headline>
<ha-svg-icon
slot="start"
.path=${mdiCalendar}
@@ -367,9 +367,6 @@ class HaBackupOverviewBackups extends LitElement {
ha-list-item-base::part(start) {
color: var(--ha-color-text-secondary);
}
ha-list-item-base::part(headline) {
white-space: wrap;
}
span.skeleton {
position: relative;
display: block;
@@ -152,7 +152,7 @@ class HaConfigBackupDetails extends LitElement {
${
CLOUD_AGENT === this.agentId
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.location.encryption.location_encrypted"
@@ -179,7 +179,7 @@ class HaConfigBackupDetails extends LitElement {
`
: encrypted
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.location.encryption.location_encrypted"
@@ -213,7 +213,7 @@ class HaConfigBackupDetails extends LitElement {
"ui.panel.config.backup.location.encryption.warning_encryption_turn_off_description"
)}
</ha-alert>
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.backup.location.encryption.location_unencrypted"
@@ -364,9 +364,6 @@ class HaConfigBackupDetails extends LitElement {
ha-backup-data-picker {
display: block;
}
ha-row-item::part(supporting-text) {
white-space: wrap;
}
.dot {
display: block;
position: relative;
@@ -170,7 +170,7 @@ export class CloudRemotePref extends LitElement {
>
<div class="card-content">
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.cloud.account.remote.external_activation"
@@ -187,7 +187,7 @@ export class CloudRemotePref extends LitElement {
@change=${this._toggleAllowRemoteEnabledChanged}
></ha-switch>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.cloud.account.remote.certificate_info"
@@ -311,9 +311,6 @@ export class CloudRemotePref extends LitElement {
ha-list-base {
--ha-row-item-padding-inline: 0;
}
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
ha-tip {
max-width: 600px;
margin: 0 auto;
@@ -199,7 +199,7 @@ export class CloudWebhooks extends LitElement {
private _renderHookRow(entry: Webhook) {
return html`
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${entry.name}
${
@@ -374,7 +374,6 @@ export class CloudWebhooks extends LitElement {
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text) {
white-space: wrap;
word-break: break-all;
}
`,
@@ -1,5 +1,7 @@
import { dump } from "js-yaml";
import type { AITaskStructure, GenDataTaskResult } from "../../../data/ai_task";
import type { RoomType } from "../../../data/area_icon_suggestions";
import { isRoomType, ROOM_TYPES } from "../../../data/area_icon_suggestions";
import type { HomeAssistant } from "../../../types";
import type { SuggestWithAIGenerateTask } from "../../../components/ha-suggest-with-ai-button";
import {
@@ -14,6 +16,7 @@ export interface MetadataSuggestionResult {
category?: string;
labels?: string[];
floor?: string;
room?: RoomType;
}
export type MetadataSuggestionDomain =
@@ -25,6 +28,7 @@ export interface MetadataSuggestionInclude {
categories?: boolean;
labels?: boolean;
floor?: boolean;
room?: boolean;
}
export const SUGGESTION_INCLUDE_DEFAULT: MetadataSuggestionInclude = {
@@ -86,6 +90,7 @@ export async function generateMetadataSuggestionTask<T>(
// providers reject a select/enum schema with an empty options list.
const includeCategories = categoryOptions.length > 0;
const includeFloor = floorOptions.length > 0;
const includeRoom = Boolean(include.room) && domain === "area";
const structure: AITaskStructure = {
...(include.name && {
@@ -139,6 +144,20 @@ export async function generateMetadataSuggestionTask<T>(
},
},
}),
...(includeRoom && {
room: {
description: `The type of room that best matches the ${domain}`,
required: false,
selector: {
select: {
options: ROOM_TYPES.map((room) => ({
value: room,
label: room.replace(/_/g, " "),
})),
},
},
},
}),
};
const requestedParts = [
@@ -147,6 +166,7 @@ export async function generateMetadataSuggestionTask<T>(
includeCategories ? "a category" : null,
include.labels ? "labels" : null,
includeFloor ? "a floor" : null,
includeRoom ? "a room type" : null,
].filter((entry): entry is string => entry !== null);
const categoryLabels: string[] = [
@@ -233,6 +253,10 @@ export async function processMetadataSuggestion(
const processed: MetadataSuggestionResult = {
name: include.name ? result.data.name : undefined,
description: include.description ? result.data.description : undefined,
room:
include.room && result.data.room && isRoomType(result.data.room)
? result.data.room
: undefined,
};
// Convert category name to ID
@@ -542,7 +542,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
return html`
${
!this.hideName && this._device
? html`<ha-row-item class="main-entity">
? html`<ha-row-item wrap-supporting-text class="main-entity">
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.main_entity",
@@ -740,7 +740,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
${
SWITCH_AS_DOMAINS_INVERT.includes(this._switchAsDomain)
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.invert.label"
@@ -1017,7 +1017,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
${
this._cameraPrefs
? html`
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.stream.preload_stream"
@@ -1035,7 +1035,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
@change=${this._handleCameraPrefsChanged}
></ha-switch>
</ha-row-item>
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.stream.stream_orientation"
@@ -1074,6 +1074,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
this.helperConfigEntry.domain !== "switch_as_x"
? html`
<ha-list-item-button
wrap-supporting-text
class="menu-item"
.disabled=${this.disabled}
@click=${this._showOptionsFlow}
@@ -1106,6 +1107,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
: nothing
}
<ha-list-item-button
wrap-supporting-text
class="menu-item"
.disabled=${this.disabled}
@click=${this._handleVoiceAssistantsClicked}
@@ -1134,6 +1136,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
supportsFeature(stateObj, VacuumEntityFeature.CLEAN_AREA)
? html`
<ha-list-item-button
wrap-supporting-text
class="menu-item"
.disabled=${this.disabled}
@click=${this._handleVacuumSegmentMappingClicked}
@@ -1171,7 +1174,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
: nothing
}
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.enabled_label"
@@ -1211,7 +1214,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
: nothing
}
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.visible_label"
@@ -1233,7 +1236,7 @@ export class EntityRegistrySettingsEditor extends LitElement {
${
this.entry.device_id
? html`
<ha-row-item class="device-area">
<ha-row-item wrap-supporting-text class="device-area">
<span slot="headline"
>${this.hass.localize(
"ui.dialogs.entity_registry.editor.use_device_area"
@@ -2013,11 +2016,6 @@ export class EntityRegistrySettingsEditor extends LitElement {
ha-input.entityId ha-icon-button:last-child {
margin-inline-start: 0;
}
ha-row-item::part(supporting-text),
ha-list-item-button::part(supporting-text) {
white-space: normal;
}
ha-row-item {
--ha-row-item-padding-inline: 0;
}
@@ -127,7 +127,8 @@ class DialogMatterAddDevice extends LitElement {
private get _waitForCommissioningFinish(): boolean {
// When the app supports reporting Matter commissioning status, defer
// advancing past the spinner until we receive matter/commission/finish.
// advancing past the spinner of its own flow until we receive
// matter/commission/finish.
return !!this.hass.auth.external?.config.hasMatterStatusReport;
}
@@ -135,7 +136,13 @@ class DialogMatterAddDevice extends LitElement {
if (!this._newDevice) {
return;
}
if (this._waitForCommissioningFinish && !this._commissioningFinished) {
// Only the app's own flow, started from the "new" step, reports back.
// The other steps commission through core or another app.
if (
this._step === "new" &&
this._waitForCommissioningFinish &&
!this._commissioningFinished
) {
return;
}
this._step = "device_added";
@@ -149,6 +156,8 @@ class DialogMatterAddDevice extends LitElement {
if (this._newDevice) {
// Device already showed up in the registry — ignore the failure signal
// and let the user finish the rename flow.
this._commissioningFinished = true;
this._maybeShowDeviceAdded();
return;
}
showToast(this, {
@@ -178,6 +178,7 @@ export class MatterConfigDashboard extends LitElement {
)}
>
<ha-list-item-button
wrap-headline
href=${`/config/devices/dashboard?historyBack=1&config_entry=${this._configEntry?.entry_id}&status=disabled`}
>
<ha-svg-icon slot="start" .path=${mdiDevices}></ha-svg-icon>
@@ -190,6 +191,7 @@ export class MatterConfigDashboard extends LitElement {
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button
wrap-headline
href=${`/config/entities?historyBack=1&config_entry=${this._configEntry?.entry_id}`}
>
<ha-svg-icon slot="start" .path=${mdiShape}></ha-svg-icon>
@@ -216,7 +218,11 @@ export class MatterConfigDashboard extends LitElement {
"ui.panel.config.matter.panel.options_title"
)}
>
<ha-list-item-button href="/config/matter/options">
<ha-list-item-button
wrap-headline
wrap-supporting-text
href="/config/matter/options"
>
<ha-svg-icon slot="start" .path=${mdiTune}></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
@@ -232,7 +238,11 @@ export class MatterConfigDashboard extends LitElement {
</ha-list-item-button>
${
isComponentLoaded(this.hass.config, "thread")
? html`<ha-list-item-button href="/config/thread">
? html`<ha-list-item-button
wrap-headline
wrap-supporting-text
href="/config/thread"
>
<ha-svg-icon
slot="start"
.path=${THREAD_ICON}
@@ -299,11 +309,6 @@ export class MatterConfigDashboard extends LitElement {
max-width: var(--ha-content-width-narrow);
}
ha-list-item-button::part(headline),
ha-list-item-button::part(supporting-text) {
white-space: normal;
}
.nav-card {
overflow: hidden;
}
@@ -56,7 +56,7 @@ class MatterOptionsPage extends LitElement {
}
${
canCommissionMatterExternal(this.hass)
? html`<ha-row-item>
? html`<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.matter.panel.mobile_app_commisioning"
@@ -80,7 +80,7 @@ class MatterOptionsPage extends LitElement {
</ha-row-item>`
: nothing
}
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.matter.panel.commission_device"
@@ -102,7 +102,7 @@ class MatterOptionsPage extends LitElement {
)}
</ha-button>
</ha-row-item>
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.matter.panel.add_shared_device"
@@ -124,7 +124,7 @@ class MatterOptionsPage extends LitElement {
)}
</ha-button>
</ha-row-item>
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.matter.panel.set_wifi_credentials"
@@ -146,7 +146,7 @@ class MatterOptionsPage extends LitElement {
)}
</ha-button>
</ha-row-item>
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.matter.panel.set_thread_credentials"
@@ -320,11 +320,6 @@ class MatterOptionsPage extends LitElement {
max-width: var(--ha-content-width-narrow);
margin: auto;
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text) {
white-space: normal;
}
`,
];
}
@@ -221,6 +221,7 @@ export class MQTTConfigPanel extends LitElement {
)}
>
<ha-list-item-button
wrap-headline
href=${`/config/devices/dashboard?historyBack=1&config_entry=${this._configEntry?.entry_id}&status=disabled`}
>
<ha-svg-icon slot="start" .path=${mdiDevices}></ha-svg-icon>
@@ -232,6 +233,7 @@ export class MQTTConfigPanel extends LitElement {
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button
wrap-headline
href=${`/config/entities?historyBack=1&config_entry=${this._configEntry?.entry_id}`}
>
<ha-svg-icon slot="start" .path=${mdiShape}></ha-svg-icon>
@@ -253,7 +255,11 @@ export class MQTTConfigPanel extends LitElement {
<ha-card class="nav-card">
<div class="card-content">
<ha-list-base>
<ha-list-item-button @click=${this._openOptionFlow}>
<ha-list-item-button
wrap-headline
wrap-supporting-text
@click=${this._openOptionFlow}
>
<ha-svg-icon slot="start" .path=${mdiTune}></ha-svg-icon>
<div slot="headline">
${this.hass.localize("ui.panel.config.mqtt.option_flow")}
@@ -265,7 +271,11 @@ export class MQTTConfigPanel extends LitElement {
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button @click=${this._openConfigFlow}>
<ha-list-item-button
wrap-headline
wrap-supporting-text
@click=${this._openConfigFlow}
>
<ha-svg-icon slot="start" .path=${mdiMqttLogo}></ha-svg-icon>
<div slot="headline">
${this.hass.localize("ui.panel.config.mqtt.config_flow")}
@@ -440,10 +450,6 @@ export class MQTTConfigPanel extends LitElement {
margin: 0 auto var(--ha-space-4);
max-width: var(--ha-content-width-narrow);
}
ha-list-item-button::part(headline),
ha-list-item-button::part(supporting-text) {
white-space: normal;
}
ha-select {
width: 96px;
margin: 0 8px;
@@ -159,7 +159,7 @@ class ThreadNetworkInfoPage extends LitElement {
if (value === null) {
return nothing;
}
return html`<ha-list-item-base>
return html`<ha-list-item-base wrap-supporting-text>
<span slot="headline">${label}</span>
<span slot="supporting-text">${value}</span>
</ha-list-item-base>`;
@@ -180,7 +180,6 @@ class ThreadNetworkInfoPage extends LitElement {
ha-list-item-base::part(supporting-text) {
font-size: var(--ha-font-size-m);
white-space: normal;
overflow-wrap: anywhere;
}
`,
@@ -237,6 +237,7 @@ class ZHAConfigDashboard extends LitElement {
)}
>
<ha-list-item-button
wrap-headline
href=${`/config/devices/dashboard?historyBack=1&config_entry=${this._configEntry?.entry_id}&status=disabled`}
>
<ha-svg-icon slot="start" .path=${mdiDevices}></ha-svg-icon>
@@ -249,6 +250,7 @@ class ZHAConfigDashboard extends LitElement {
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button
wrap-headline
href=${`/config/entities?historyBack=1&config_entry=${this._configEntry?.entry_id}`}
>
<ha-svg-icon slot="start" .path=${mdiShape}></ha-svg-icon>
@@ -260,7 +262,7 @@ class ZHAConfigDashboard extends LitElement {
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button href="/config/zha/groups">
<ha-list-item-button wrap-headline href="/config/zha/groups">
<ha-svg-icon
slot="start"
.path=${mdiFolderMultipleOutline}
@@ -307,7 +309,11 @@ class ZHAConfigDashboard extends LitElement {
"ui.panel.config.zha.configuration_page.options_title"
)}
>
<ha-list-item-button href="/config/zha/options">
<ha-list-item-button
wrap-headline
wrap-supporting-text
href="/config/zha/options"
>
<ha-svg-icon slot="start" .path=${mdiTune}></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
@@ -321,7 +327,11 @@ class ZHAConfigDashboard extends LitElement {
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button href="/config/zha/network-info">
<ha-list-item-button
wrap-headline
wrap-supporting-text
href="/config/zha/network-info"
>
<ha-svg-icon
slot="start"
.path=${mdiInformationOutline}
@@ -340,7 +350,10 @@ class ZHAConfigDashboard extends LitElement {
</ha-list-item-button>
${dynamicSections.map(
(section) => html`
<ha-list-item-button href=${`/config/zha/section/${section}`}>
<ha-list-item-button
wrap-headline
href=${`/config/zha/section/${section}`}
>
<ha-svg-icon slot="start" .path=${mdiTune}></ha-svg-icon>
<div slot="headline">
${
@@ -364,7 +377,7 @@ class ZHAConfigDashboard extends LitElement {
<ha-card class="nav-card">
<div class="card-content">
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zha.configuration_page.download_backup"
@@ -389,7 +402,7 @@ class ZHAConfigDashboard extends LitElement {
)}
</ha-progress-button>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zha.configuration_page.migrate_radio"
@@ -523,13 +536,6 @@ class ZHAConfigDashboard extends LitElement {
max-width: var(--ha-content-width-narrow);
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text),
ha-list-item-button::part(headline),
ha-list-item-button::part(supporting-text) {
white-space: normal;
}
.nav-card .card-header {
display: flex;
align-items: center;
@@ -54,7 +54,7 @@ class ZHANetworkInfoPage extends LitElement {
${
this._networkSettings
? html`<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.channel_label"
@@ -74,7 +74,7 @@ class ZHANetworkInfoPage extends LitElement {
@click=${this._showChannelMigrationDialog}
></ha-icon-button>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">PAN ID</span>
<span slot="supporting-text"
>${
@@ -82,7 +82,7 @@ class ZHANetworkInfoPage extends LitElement {
}</span
>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">Extended PAN ID</span>
<span slot="supporting-text"
>${
@@ -91,13 +91,13 @@ class ZHANetworkInfoPage extends LitElement {
}</span
>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">Coordinator IEEE</span>
<span slot="supporting-text"
>${this._networkSettings.settings.node_info.ieee}</span
>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.radio_type"
@@ -107,7 +107,7 @@ class ZHANetworkInfoPage extends LitElement {
>${this._networkSettings.radio_type}</span
>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.serial_port"
@@ -121,7 +121,7 @@ class ZHANetworkInfoPage extends LitElement {
this._networkSettings.device.baudrate &&
!this._networkSettings.device.path.startsWith("socket://")
? html`
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.baudrate"
@@ -177,7 +177,6 @@ class ZHANetworkInfoPage extends LitElement {
ha-list-item-base::part(supporting-text) {
font-size: var(--ha-font-size-m);
white-space: normal;
}
`,
];
@@ -116,7 +116,7 @@ class ZHAOptionsPage extends LitElement {
this._configuration
? html`
<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.enable_identify_on_join_label"
@@ -136,7 +136,7 @@ class ZHAOptionsPage extends LitElement {
@change=${this._enableIdentifyOnJoinChanged}
></ha-switch>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.default_light_transition_label"
@@ -161,7 +161,7 @@ class ZHAOptionsPage extends LitElement {
<span slot="end">s</span>
</ha-input>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.enhanced_light_transition_label"
@@ -181,7 +181,7 @@ class ZHAOptionsPage extends LitElement {
@change=${this._enhancedLightTransitionChanged}
></ha-switch>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.light_transitioning_flag_label"
@@ -201,7 +201,7 @@ class ZHAOptionsPage extends LitElement {
@change=${this._lightTransitioningFlagChanged}
></ha-switch>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.group_members_assume_state_label"
@@ -221,7 +221,7 @@ class ZHAOptionsPage extends LitElement {
@change=${this._groupMembersAssumeStateChanged}
></ha-switch>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.consider_unavailable_mains_label"
@@ -265,7 +265,7 @@ class ZHAOptionsPage extends LitElement {
`
: nothing
}
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.consider_unavailable_battery_label"
@@ -309,7 +309,7 @@ class ZHAOptionsPage extends LitElement {
`
: nothing
}
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.zha.configuration_page.enable_mains_startup_polling_label"
@@ -463,11 +463,6 @@ class ZHAOptionsPage extends LitElement {
margin: auto;
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
ha-select,
ha-input {
min-width: 210px;
@@ -78,7 +78,7 @@ class ZWaveJSControllerStatistics extends SubscribeMixin(LitElement) {
private _renderStat(key: string) {
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
`ui.panel.config.zwave_js.dashboard.statistics.${key}.label`
@@ -104,11 +104,6 @@ class ZWaveJSControllerStatistics extends SubscribeMixin(LitElement) {
max-width: var(--ha-content-width-narrow);
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
span[slot="end"] {
font-size: 0.95em;
color: var(--primary-text-color);
@@ -50,7 +50,7 @@ class ZWaveJSNetworkInfoPage extends LitElement {
${
this._network
? html`<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zwave_js.dashboard.home_id"
@@ -66,7 +66,7 @@ class ZWaveJSNetworkInfoPage extends LitElement {
}
</span>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zwave_js.dashboard.driver_version"
@@ -76,7 +76,7 @@ class ZWaveJSNetworkInfoPage extends LitElement {
${this._network.client.driver_version}
</span>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zwave_js.dashboard.server_version"
@@ -86,7 +86,7 @@ class ZWaveJSNetworkInfoPage extends LitElement {
${this._network.client.server_version}
</span>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zwave_js.dashboard.server_url"
@@ -120,7 +120,6 @@ class ZWaveJSNetworkInfoPage extends LitElement {
ha-list-item-base::part(supporting-text) {
font-size: var(--ha-font-size-m);
white-space: normal;
}
`,
];
@@ -62,7 +62,7 @@ class ZWaveJSOptionsPage extends LitElement {
${
this._network
? html`<ha-list-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zwave_js.common.rebuild_network_routes"
@@ -85,7 +85,7 @@ class ZWaveJSOptionsPage extends LitElement {
)}
</ha-button>
</ha-list-item-base>
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline">
${this.hass.localize(
"ui.panel.config.zwave_js.common.remove_node"
@@ -149,11 +149,6 @@ class ZWaveJSOptionsPage extends LitElement {
max-width: var(--ha-content-width-narrow);
margin: auto;
}
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
`,
];
}
@@ -64,7 +64,11 @@ class HaConfigSectionNetwork extends LitElement {
>
${NETWORK_BROWSERS.map(
(domain) => html`
<ha-list-item-button href="/config/${domain}">
<ha-list-item-button
wrap-headline
wrap-supporting-text
href="/config/${domain}"
>
<div slot="headline">
${this.hass.localize(
`ui.panel.config.network.discovery.${domain}`
@@ -104,10 +108,6 @@ class HaConfigSectionNetwork extends LitElement {
display: block;
margin-bottom: 24px;
}
.discovery-card ha-list-item-button::part(headline),
.discovery-card ha-list-item-button::part(supporting-text) {
white-space: normal;
}
`;
}
@@ -1,5 +1,5 @@
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import "../../../../components/item/ha-list-item-base";
import "../../../../components/ha-switch";
@@ -14,7 +14,7 @@ class HaDebugConnectionRow extends LitElement {
protected render(): TemplateResult {
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.tools.tabs.debug.debug_connection.title"
@@ -43,13 +43,6 @@ class HaDebugConnectionRow extends LitElement {
setDebugConnection(debugConnection);
storeState(this.hass);
}
static styles = css`
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
`;
}
declare global {
@@ -1,5 +1,5 @@
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { storage } from "../../../../common/decorators/storage";
import { setViewTransitionDisabled } from "../../../../common/util/view-transition";
@@ -17,7 +17,7 @@ class HaDebugDisableViewTransitionRow extends LitElement {
protected render(): TemplateResult {
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.tools.tabs.debug.disable_view_transition.title"
@@ -41,13 +41,6 @@ class HaDebugDisableViewTransitionRow extends LitElement {
this._disabled = (ev.target as HaSwitch).checked;
setViewTransitionDisabled(this._disabled);
}
static styles = css`
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
`;
}
declare global {
@@ -1,4 +1,4 @@
import { css, html, LitElement } from "lit";
import { html, LitElement } from "lit";
import { customElement, state } from "lit/decorators";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { storage } from "../../../../common/decorators/storage";
@@ -19,7 +19,7 @@ class HaDebugSafeAreaToolRow extends LitElement {
protected render() {
return html`
<ha-list-item-base>
<ha-list-item-base wrap-headline wrap-supporting-text>
<span slot="headline"
>${this._localize(
"ui.panel.config.tools.tabs.debug.safe_area_tool.title"
@@ -42,13 +42,6 @@ class HaDebugSafeAreaToolRow extends LitElement {
private _checkedChanged(ev: Event) {
this._enabled = (ev.target as HaSwitch).checked;
}
static styles = css`
ha-list-item-base::part(headline),
ha-list-item-base::part(supporting-text) {
white-space: normal;
}
`;
}
declare global {
@@ -212,7 +212,7 @@ export class AssistPref extends LitElement {
)}
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
</ha-button>
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass!.localize(
"ui.panel.config.voice_assistants.expose.expose_new_entities"
@@ -415,10 +415,6 @@ export class AssistPref extends LitElement {
a {
color: var(--primary-color);
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text) {
white-space: normal;
}
.header-actions {
position: absolute;
right: 0px;
@@ -139,7 +139,7 @@ export class CloudAlexaPref extends LitElement {
</ha-alert>`
: nothing
}
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass!.localize(
"ui.panel.config.cloud.account.alexa.expose_new_entities"
@@ -160,7 +160,7 @@ export class CloudAlexaPref extends LitElement {
${
alexa_registered
? html`
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass!.localize(
"ui.panel.config.cloud.account.alexa.enable_state_reporting"
@@ -265,10 +265,6 @@ export class CloudAlexaPref extends LitElement {
ha-row-item {
--ha-row-item-padding-inline: 0;
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text) {
white-space: normal;
}
.header-actions {
position: absolute;
right: 24px;
@@ -138,7 +138,7 @@ export class CloudGooglePref extends LitElement {
`
: nothing
}
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass!.localize(
"ui.panel.config.cloud.account.google.expose_new_entities"
@@ -183,7 +183,7 @@ export class CloudGooglePref extends LitElement {
`
: nothing
}
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass!.localize(
"ui.panel.config.cloud.account.google.enable_state_reporting"
@@ -201,7 +201,7 @@ export class CloudGooglePref extends LitElement {
></ha-switch>
</ha-row-item>
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.config.cloud.account.google.security_devices"
@@ -347,10 +347,6 @@ export class CloudGooglePref extends LitElement {
ha-row-item {
--ha-row-item-padding-inline: 0;
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text) {
white-space: normal;
}
ha-input {
width: 250px;
margin-top: 8px;
@@ -193,7 +193,7 @@ export class EntityVoiceSettings extends SubscribeMixin(LitElement) {
const exposedToAssist = this.exposed.conversation;
return html`
<ha-row-item>
<ha-row-item wrap-headline>
<h3 slot="headline">
${this.hass.localize("ui.dialogs.voice-settings.expose_header")}
</h3>
@@ -227,7 +227,7 @@ export class EntityVoiceSettings extends SubscribeMixin(LitElement) {
this._googleEntity?.might_2fa;
return html`
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<voice-assistant-brand-icon
slot="start"
.voiceAssistantId=${key}
@@ -324,7 +324,7 @@ export class EntityVoiceSettings extends SubscribeMixin(LitElement) {
)}
</ha-alert>`
: html`
<ha-row-item>
<ha-row-item wrap-headline wrap-supporting-text>
<span slot="headline">${this._computedName(this.entry)}</span>
<span slot="supporting-text">
${this.hass.localize(
@@ -457,10 +457,6 @@ export class EntityVoiceSettings extends SubscribeMixin(LitElement) {
ha-row-item {
--ha-row-item-padding-inline: 0;
}
ha-row-item::part(headline),
ha-row-item::part(supporting-text) {
white-space: normal;
}
img {
height: 32px;
width: 32px;
@@ -16,7 +16,6 @@ import "../../../components/ha-svg-icon";
import "../components/hui-badge-edit-mode";
import { moveAtPath } from "../editor/lovelace-path";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import type { HuiBadge } from "./hui-badge";
const BADGE_SORTABLE_OPTIONS: HaSortableOptions = {
@@ -47,8 +46,7 @@ export class HuiViewBadges extends LitElement {
private _checkAllHidden() {
const allHidden =
!isLayoutEditMode(this.lovelace) &&
this.badges.every((section) => section.hidden);
!this.lovelace.editMode && this.badges.every((section) => section.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -127,7 +125,7 @@ export class HuiViewBadges extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = isLayoutEditMode(this.lovelace);
const editMode = this.lovelace.editMode;
const badges = this.badges;
@@ -0,0 +1,193 @@
import { mdiEye, mdiEyeOff } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon";
import type { HomeAssistant } from "../../../types";
import "./hui-card";
import type { HuiCard } from "./hui-card";
import type { LovelaceCard, LovelaceGridOptions } from "../types";
import type { EntityVisibilityCardConfig } from "./types";
@customElement("hui-entity-visibility-card")
export class HuiEntityVisibilityCard
extends LitElement
implements LovelaceCard
{
@property({ attribute: false }) public hass?: HomeAssistant;
@property({ type: Boolean }) public preview = false;
@state() private _config?: EntityVisibilityCardConfig;
private _card?: HuiCard;
public setConfig(config: EntityVisibilityCardConfig): void {
if (!config.entity) {
throw new Error("No entity configured");
}
if (!config.card) {
throw new Error("No card configured");
}
this._config = config;
this._card = document.createElement("hui-card");
this._card.hass = this.hass;
this._card.preview = this.preview;
this._card.config = config.card;
this._card.inert = true;
this._card.load();
}
public getCardSize(): number | Promise<number> {
return this._card?.getCardSize() ?? 1;
}
public getGridOptions(): LovelaceGridOptions {
return this._card?.getGridOptions() ?? {};
}
public connectedCallback(): void {
super.connectedCallback();
window.addEventListener(
"entity-visibility-changed",
this._entityVisibilityChanged
);
}
public disconnectedCallback(): void {
super.disconnectedCallback();
window.removeEventListener(
"entity-visibility-changed",
this._entityVisibilityChanged
);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (!this._card) {
return;
}
if (changedProps.has("hass")) {
this._card.hass = this.hass;
}
if (changedProps.has("preview")) {
this._card.preview = this.preview;
}
}
protected render() {
if (!this._config || !this.hass || !this._card) {
return nothing;
}
const hidden = Boolean(this._config.hidden);
const stateObj = this.hass.states[this._config.entity];
const name = stateObj
? this.hass.formatEntityName(stateObj)
: this._config.entity;
return html`
<div class="wrapper" ?hidden-entity=${hidden}>
${this._card}
<button
class="control"
aria-label=${this.hass.localize(
`ui.components.items-display-editor.${hidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon .path=${hidden ? mdiEyeOff : mdiEye}></ha-svg-icon>
</button>
</div>
`;
}
private _entityVisibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["entity-visibility-changed"]>
) => {
if (
this._config?.hidden === undefined ||
ev.detail.entity !== this._config.entity ||
ev.detail.hidden === this._config.hidden
) {
return;
}
this._config = { ...this._config, hidden: ev.detail.hidden };
};
private _toggle(): void {
if (!this._config) {
return;
}
const hidden = !this._config.hidden;
this._config = { ...this._config, hidden };
fireEvent(this, "entity-visibility-changed", {
entity: this._config.entity,
hidden,
});
}
static styles: CSSResultGroup = css`
.wrapper {
position: relative;
height: 100%;
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
}
hui-card {
display: block;
height: 100%;
}
.wrapper[hidden-entity] hui-card {
opacity: 0.8;
}
.wrapper[hidden-entity]::after {
content: "";
position: absolute;
inset: 0;
border: 2px dotted var(--secondary-text-color);
border-radius: inherit;
pointer-events: none;
}
.control {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: flex-end;
margin: 0;
padding: var(--ha-space-2);
border: none;
background: none;
border-radius: inherit;
cursor: pointer;
color: var(--primary-text-color);
}
.control:focus-visible {
outline: 2px solid var(--primary-color);
}
.control ha-svg-icon {
display: flex;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-circle);
background: var(--secondary-background-color);
box-shadow: var(--ha-box-shadow-s);
--mdc-icon-size: 20px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-entity-visibility-card": HuiEntityVisibilityCard;
}
interface GlobalEventHandlersEventMap {
"entity-visibility-changed": HASSDomEvent<
HASSDomEvents["entity-visibility-changed"]
>;
}
interface HASSDomEvents {
"entity-visibility-changed": { entity: string; hidden: boolean };
}
}
+6
View File
@@ -71,6 +71,12 @@ export interface ConditionalCardConfig extends LovelaceCardConfig {
conditions: VisibilityCondition[];
}
export interface EntityVisibilityCardConfig extends LovelaceCardConfig {
entity: string;
hidden?: boolean;
card: LovelaceCardConfig;
}
export interface EmptyStateButtonConfig {
text: string;
icon?: string;
@@ -36,6 +36,10 @@ declare global {
const DOUBLE_CLICK_TIME = 250;
// How far (px) a finger may move before a press counts as a drag or scroll,
// in line with the touch slop of the native platforms.
const TOUCH_SLOP = 10;
// The coordinates of the pointer that changed: for touch events the finger
// that just went down/up (touches[0] would be the *first* finger during a
// multi-touch), for mouse events the pointer itself.
@@ -59,6 +63,9 @@ class ActionHandler extends HTMLElement implements ActionHandlerType {
private cancelled = false;
// Where the finger of the touch in flight went down.
private touchStart?: { x: number; y: number };
private dblClickTimeout?: number;
// The double-tap window only pairs two taps on the same target; a quick tap
@@ -85,28 +92,47 @@ class ActionHandler extends HTMLElement implements ActionHandlerType {
transition: "transform 180ms ease-in-out",
});
const cancel = () => {
this.cancelled = true;
if (this.timer) {
this._stopAnimation();
clearTimeout(this.timer);
this.timer = undefined;
}
};
// pointercancel is how the browser says it took over the touch, e.g. to
// scroll a nested scroller whose scroll event never reaches the document.
[
"touchcancel",
"pointercancel",
"mouseout",
"mouseup",
"touchmove",
"mousewheel",
"wheel",
"scroll",
].forEach((ev) => {
document.addEventListener(
ev,
() => {
this.cancelled = true;
if (this.timer) {
this._stopAnimation();
clearTimeout(this.timer);
this.timer = undefined;
}
},
{ passive: true }
);
document.addEventListener(ev, cancel, { passive: true });
});
// A finger always moves a little while it is down, so only movement past
// the touch slop turns a tap or hold into a drag.
document.addEventListener(
"touchmove",
(ev: TouchEvent) => {
if (this.touchStart && activeTouchCount(ev) <= 1) {
const { x, y } = eventCoordinates(ev);
if (
Math.hypot(x - this.touchStart.x, y - this.touchStart.y) <=
TOUCH_SLOP
) {
return;
}
}
cancel();
},
{ passive: true }
);
}
public bind(
@@ -166,6 +192,7 @@ class ActionHandler extends HTMLElement implements ActionHandlerType {
element.actionHandler.start = (ev: Event) => {
this.cancelled = false;
const { x, y } = eventCoordinates(ev);
this.touchStart = ev.type === "touchstart" ? { x, y } : undefined;
if (options.resolve) {
this.resolved = undefined;
@@ -1,127 +0,0 @@
import { mdiEye, mdiEyeOff } from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { CSSResultGroup } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-svg-icon";
import { formattersContext } from "../../../data/context";
import type { HomeAssistantFormatters } from "../../../types";
@customElement("hui-card-visibility-edit-mode")
export class HuiCardVisibilityEditMode extends LitElement {
@property() public entity!: string;
@property({ type: Boolean, reflect: true, attribute: "entity-hidden" })
public entityHidden = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consumeEntityState({ entityIdPath: ["entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
protected render() {
const name = this._stateObj
? this._formatters.formatEntityName(this._stateObj)
: this.entity;
return html`
<div class="card-wrapper" inert><slot></slot></div>
<button
class="control"
aria-label=${this._localize(
`ui.components.items-display-editor.${this.entityHidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon
.path=${this.entityHidden ? mdiEyeOff : mdiEye}
></ha-svg-icon>
</button>
`;
}
private _toggle(): void {
fireEvent(this, "entity-visibility-changed", {
entity: this.entity,
hidden: !this.entityHidden,
});
}
static styles: CSSResultGroup = css`
:host {
display: block;
position: relative;
height: 100%;
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
}
.card-wrapper {
height: 100%;
}
:host([entity-hidden]) .card-wrapper {
opacity: 0.8;
}
:host([entity-hidden])::after {
content: "";
position: absolute;
inset: 0;
border: 2px dotted var(--secondary-text-color);
border-radius: inherit;
pointer-events: none;
}
.control {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: flex-end;
margin: 0;
padding: var(--ha-space-2);
border: none;
background: none;
border-radius: inherit;
cursor: pointer;
color: var(--primary-text-color);
}
.control:focus-visible {
outline: 2px solid var(--primary-color);
}
.control ha-svg-icon {
display: flex;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-circle);
background: var(--secondary-background-color);
box-shadow: var(--ha-box-shadow-s);
--mdc-icon-size: 20px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-card-visibility-edit-mode": HuiCardVisibilityEditMode;
}
interface GlobalEventHandlersEventMap {
"entity-visibility-changed": HASSDomEvent<
HASSDomEvents["entity-visibility-changed"]
>;
}
interface HASSDomEvents {
"entity-visibility-changed": { entity: string; hidden: boolean };
}
}
@@ -38,6 +38,7 @@ const LAZY_LOAD_TYPES = {
area: () => import("../cards/hui-area-card"),
calendar: () => import("../cards/hui-calendar-card"),
conditional: () => import("../cards/hui-conditional-card"),
"entity-visibility": () => import("../cards/hui-entity-visibility-card"),
"empty-state": () => import("../cards/hui-empty-state-card"),
"energy-compare": () => import("../cards/energy/hui-energy-compare-card"),
"energy-carbon-consumed-gauge": () =>
@@ -118,7 +118,7 @@ export class HuiCardLayoutEditor extends LitElement {
`
: nothing
}
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.lovelace.editor.edit_card.layout.recommended_size"
@@ -151,7 +151,7 @@ export class HuiCardLayoutEditor extends LitElement {
.columnMax=${gridOptions.max_columns}
.step=${this._preciseMode ? 1 : GRID_COLUMN_MULTIPLIER}
></ha-grid-size-picker>
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.lovelace.editor.edit_card.layout.fit_content"
@@ -169,7 +169,7 @@ export class HuiCardLayoutEditor extends LitElement {
name="auto-height"
></ha-switch>
</ha-row-item>
<ha-row-item>
<ha-row-item wrap-supporting-text>
<span slot="headline"
>${this.hass.localize(
"ui.panel.lovelace.editor.edit_card.layout.full_width"
@@ -425,9 +425,6 @@ export class HuiCardLayoutEditor extends LitElement {
opacity: 0.5;
pointer-events: none;
}
ha-row-item::part(supporting-text) {
white-space: normal;
}
ha-grid-size-picker {
display: block;
margin: 16px auto;
@@ -18,10 +18,8 @@ import type { HomeAssistant } from "../../../types";
import type { HuiCard } from "../cards/hui-card";
import { computeCardGridSize } from "../common/compute-card-grid-size";
import "../components/hui-card-edit-mode";
import "../components/hui-card-visibility-edit-mode";
import { moveAtPath } from "../editor/lovelace-path";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
const CARD_SORTABLE_OPTIONS: HaSortableOptions = {
delay: 100,
@@ -80,10 +78,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
const cardsConfig = this._config?.cards ?? [];
const editMode = isLayoutEditMode(this.lovelace) && !this.isStrategy;
const visibility = this.lovelace?.editMode
? this.lovelace.entityVisibility
: undefined;
const editMode = Boolean(this.lovelace?.editMode && !this.isStrategy);
const sortableOptions = this.importOnly
? IMPORT_MODE_CARD_SORTABLE_OPTIONS
@@ -109,7 +104,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${repeat(
cardsConfig,
(cardConfig) => this._getKey(cardConfig),
(cardConfig, idx) => {
(_cardConfig, idx) => {
const card = this.cards![idx];
card.layout = "grid";
const gridOptions = card.getGridOptions();
@@ -131,10 +126,6 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
"full-width": columns === "full",
hidden: !editMode && card.hidden,
})}"
?inert=${
visibility !== undefined &&
typeof cardConfig.entity !== "string"
}
.sortableData=${cardPath}
>
${
@@ -150,18 +141,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${card}
</hui-card-edit-mode>
`
: visibility && typeof cardConfig.entity === "string"
? html`
<hui-card-visibility-edit-mode
.entity=${cardConfig.entity}
.entityHidden=${visibility.hiddenEntities.includes(
cardConfig.entity
)}
>
${card}
</hui-card-visibility-edit-mode>
`
: card
: card
}
</div>
`;
@@ -0,0 +1,13 @@
import type { LovelaceCardConfig } from "../../../../data/lovelace/config/card";
import type { EntityVisibilityCardConfig } from "../../cards/types";
export type ComputeEntityCard = (entityId: string) => LovelaceCardConfig;
export const wrapEntityVisibility =
(hiddenEntities: Set<string>, computeCard: ComputeEntityCard) =>
(entityId: string): EntityVisibilityCardConfig => ({
type: "entity-visibility",
entity: entityId,
hidden: hiddenEntities.has(entityId),
card: computeCard(entityId),
});
-8
View File
@@ -48,16 +48,8 @@ export interface Lovelace {
* window's history and scroll position.
*/
embedded?: boolean;
/**
* Limits edit mode to showing and hiding the entity cards of a generated
* view, instead of editing its layout.
*/
entityVisibility?: { hiddenEntities: string[] };
}
export const isLayoutEditMode = (lovelace?: Lovelace): boolean =>
Boolean(lovelace?.editMode && !lovelace.entityVisibility);
export interface LovelaceBadge extends HTMLElement {
hass?: HomeAssistant;
preview?: boolean;
@@ -37,7 +37,6 @@ import {
sectionContainerStyles,
} from "../sections/section-container";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import { generateDefaultSection } from "./default-section";
import "./hui-view-footer";
import "./hui-view-header";
@@ -192,7 +191,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
if (!this.lovelace) return nothing;
const sections = this.sections;
const editMode = isLayoutEditMode(this.lovelace);
const editMode = this.lovelace.editMode;
const hasSidebar =
this._config?.sidebar && (this._sidebarVisible || editMode);
const singleColumn = this._maxColumns <= 1;
+4 -5
View File
@@ -19,7 +19,6 @@ import { showCreateCardDialog } from "../editor/card-editor/show-create-card-dia
import { setAtPath } from "../editor/lovelace-path";
import { showEditViewFooterDialog } from "../editor/view-footer/show-edit-view-footer-dialog";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
@customElement("hui-view-footer")
export class HuiViewFooter extends LitElement {
@@ -54,7 +53,7 @@ export class HuiViewFooter extends LitElement {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = isLayoutEditMode(this.lovelace);
this.card.preview = this.lovelace.editMode;
}
}
@@ -70,7 +69,7 @@ export class HuiViewFooter extends LitElement {
private _checkHidden() {
const hidden =
!isLayoutEditMode(this.lovelace) &&
!this.lovelace?.editMode &&
(!this.card || this.card.hasAttribute("hidden"));
this.toggleAttribute("hidden", hidden);
this.toggleAttribute("sticky", Boolean(this.card));
@@ -79,7 +78,7 @@ export class HuiViewFooter extends LitElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
element.layout = "grid";
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
@@ -151,7 +150,7 @@ export class HuiViewFooter extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = isLayoutEditMode(this.lovelace);
const editMode = Boolean(this.lovelace?.editMode);
const card = this.card;
if (!editMode && !card) {
+5 -7
View File
@@ -22,7 +22,6 @@ import { showEditCardDialog } from "../editor/card-editor/show-edit-card-dialog"
import { setAtPath } from "../editor/lovelace-path";
import { showEditViewHeaderDialog } from "../editor/view-header/show-edit-view-header-dialog";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
export const DEFAULT_VIEW_HEADER_LAYOUT = "center";
export const DEFAULT_VIEW_HEADER_BADGES_POSITION = "bottom";
@@ -45,7 +44,7 @@ export class HuiViewHeader extends LitElement {
private _checkHidden() {
const allHidden =
!this.card &&
!isLayoutEditMode(this.lovelace) &&
!this.lovelace.editMode &&
this.badges.every((badges) => badges.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -88,8 +87,7 @@ export class HuiViewHeader extends LitElement {
if (changedProperties.has("config") || changedProperties.has("lovelace")) {
this._dragScrollController.enabled =
!isLayoutEditMode(this.lovelace) &&
this.config?.badges_wrap === "scroll";
!this.lovelace.editMode && this.config?.badges_wrap === "scroll";
}
if (changedProperties.has("config")) {
@@ -107,7 +105,7 @@ export class HuiViewHeader extends LitElement {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = isLayoutEditMode(this.lovelace);
this.card.preview = this.lovelace.editMode;
}
}
}
@@ -115,7 +113,7 @@ export class HuiViewHeader extends LitElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
element.config = cardConfig;
element.load();
return element;
@@ -165,7 +163,7 @@ export class HuiViewHeader extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = isLayoutEditMode(this.lovelace);
const editMode = Boolean(this.lovelace?.editMode);
const card = this.card;
@@ -13,7 +13,6 @@ import {
sectionContainerStyles,
} from "../sections/section-container";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import type { LovelaceSectionConfig } from "../../../data/lovelace/config/section";
export const DEFAULT_VIEW_SIDEBAR_LAYOUT = "start";
@@ -75,7 +74,7 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
<hui-section
.config=${section}
.hass=${this.hass}
.preview=${isLayoutEditMode(this.lovelace)}
.preview=${this.lovelace.editMode}
.path=${sectionPath}
></hui-section>
`;
+6 -7
View File
@@ -66,7 +66,6 @@ import {
generateLovelaceViewStrategy,
} from "../strategies/get-strategy";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import { PANEL_VIEW_LAYOUT, SIDEBAR_VIEW_LAYOUT } from "./const";
import { getViewType } from "./get-view-type";
@@ -379,7 +378,7 @@ export class HUIView extends ReactiveElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
ev.stopPropagation();
@@ -392,7 +391,7 @@ export class HUIView extends ReactiveElement {
public createBadgeElement(badgeConfig: LovelaceBadgeConfig) {
const element = document.createElement("hui-badge");
element.hass = this.hass;
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
element.config = badgeConfig;
element.addEventListener("badge-updated", (ev: Event) => {
ev.stopPropagation();
@@ -408,7 +407,7 @@ export class HUIView extends ReactiveElement {
element.hass = this.hass;
element.lovelace = this.lovelace;
element.config = sectionConfig;
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
element.addEventListener(
"ll-rebuild",
(ev: Event) => {
@@ -517,16 +516,16 @@ export class HUIView extends ReactiveElement {
try {
element.hass = this.hass;
element.lovelace = this.lovelace;
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
} catch (e: any) {
this._rebuildSection(element, createErrorSectionConfig(e.message));
}
});
this._cards.forEach((element) => {
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
});
this._badges.forEach((element) => {
element.preview = isLayoutEditMode(this.lovelace);
element.preview = this.lovelace.editMode;
});
}
if (changedProperties.has("_cards")) {
+22 -48
View File
@@ -13,7 +13,6 @@ import {
queueFrontendSystemDataSave,
type MaintenanceFrontendSystemData,
} from "../../data/frontend";
import type { LovelaceConfig } from "../../data/lovelace/config/types";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
@@ -43,7 +42,7 @@ class PanelMaintenance extends LitElement {
@state() private _config?: MaintenanceFrontendSystemData;
@state() private _editMode = false;
@state() private _editVisibility = false;
@state() private _searchParams = new URLSearchParams(window.location.search);
@@ -123,7 +122,7 @@ class PanelMaintenance extends LitElement {
if (revision !== this._loadConfigRevision) {
return;
}
this._editMode = false;
this._editVisibility = false;
// eslint-disable-next-line no-console
console.error("Failed to load maintenance configuration:", err);
showToast(this, {
@@ -153,12 +152,12 @@ class PanelMaintenance extends LitElement {
${
!this.hass.user?.is_admin
? nothing
: this._editMode
: this._editVisibility
? html`<ha-button
slot="actionItems"
appearance="filled"
size="s"
@click=${this._exitEditMode}
@click=${this._stopEditVisibility}
>
${this.hass.localize("ui.panel.lovelace.menu.exit_edit_mode")}
</ha-button>`
@@ -167,7 +166,7 @@ class PanelMaintenance extends LitElement {
slot="actionItems"
.path=${mdiPencil}
.label=${this.hass.localize("ui.panel.maintenance.editor.title")}
@click=${this._enterEditMode}
@click=${this._startEditVisibility}
></ha-icon-button>`
: nothing
}
@@ -202,9 +201,8 @@ class PanelMaintenance extends LitElement {
{
strategy: {
...MAINTENANCE_LOVELACE_VIEW_CONFIG.strategy,
hidden_entities: this._editMode
? undefined
: this._config?.hidden_entities,
hidden_entities: this._config?.hidden_entities,
edit_visibility: this._editVisibility || undefined,
},
},
this.hass
@@ -214,61 +212,40 @@ class PanelMaintenance extends LitElement {
return;
}
const config =
!force &&
this._lovelace &&
deepEqual(viewConfig, this._lovelace.config.views[0])
? this._lovelace.config
: { views: [viewConfig] };
const config = { views: [viewConfig] };
const rawConfig = { views: [MAINTENANCE_LOVELACE_VIEW_CONFIG] };
if (
config === this._lovelace?.config &&
this._lovelace.editMode === this._editMode &&
deepEqual(
this._lovelace.entityVisibility?.hiddenEntities,
this._config?.hidden_entities ?? []
)
) {
if (!force && deepEqual(config, this._lovelace?.config)) {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = this._createLovelace(config);
}
private _createLovelace(config: LovelaceConfig): Lovelace {
return {
this._lovelace = {
config: config,
rawConfig: { views: [MAINTENANCE_LOVELACE_VIEW_CONFIG] },
editMode: this._editMode,
entityVisibility: {
hiddenEntities: this._config?.hidden_entities ?? [],
},
rawConfig: rawConfig,
editMode: false,
urlPath: "maintenance",
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: this._setEditMode,
setEditMode: () => undefined,
showToast: () => undefined,
};
}
private _setEditMode = (editMode: boolean) => {
this._editMode = editMode;
if (!editMode && !this._config) {
this._loadConfigPromise = this._loadConfig();
}
private _startEditVisibility = () => {
this._editVisibility = true;
this._setLovelace();
};
private _enterEditMode = () => {
this._setEditMode(true);
};
private _exitEditMode = () => {
this._setEditMode(false);
private _stopEditVisibility = () => {
this._editVisibility = false;
if (!this._config) {
this._loadConfigPromise = this._loadConfig();
}
this._setLovelace();
};
private _visibilityChanged = (
@@ -288,9 +265,6 @@ class PanelMaintenance extends LitElement {
...this._config,
hidden_entities: hiddenEntities.length ? hiddenEntities : undefined,
});
if (this._lovelace) {
this._lovelace = this._createLovelace(this._lovelace.config);
}
};
private _saveConfig(config: MaintenanceFrontendSystemData): Promise<void> {
@@ -14,6 +14,10 @@ import type { LovelaceSectionRawConfig } from "../../../data/lovelace/config/sec
import type { LovelaceViewConfig } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import type { TileCardConfig } from "../../lovelace/cards/types";
import {
wrapEntityVisibility,
type ComputeEntityCard,
} from "../../lovelace/strategies/helpers/entity-visibility";
import { BINARY_STATE_ON } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import { getDeviceEntityDisplayLookup } from "../../../data/device/device_registry";
@@ -22,6 +26,7 @@ import { findBatteryChargingEntity } from "../../../data/entity/entity_registry"
export interface MaintenanceViewStrategyConfig {
type: "maintenance";
hidden_entities?: string[];
edit_visibility?: boolean;
}
export const maintenanceEntityFilters: EntityFilter[] = [
@@ -122,7 +127,8 @@ const computeMaintenanceTileCard = (
const processAreasForBattery = (
areaIds: string[],
hass: HomeAssistant,
entities: string[]
entities: string[],
computeCard: ComputeEntityCard
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
@@ -144,9 +150,7 @@ const processAreasForBattery = (
const areaCards: LovelaceCardConfig[] = [];
for (const entityId of areaBatteryEntities) {
areaCards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
);
areaCards.push(computeCard(entityId));
}
if (areaCards.length > 0) {
@@ -170,7 +174,8 @@ const processAreasForBattery = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[]
entities: string[],
computeCard: ComputeEntityCard
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -186,9 +191,7 @@ const processUnassignedEntities = (
const cards: LovelaceCardConfig[] = [];
for (const entityId of unassignedEntities) {
cards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
);
cards.push(computeCard(entityId));
}
return cards;
@@ -206,7 +209,16 @@ export class MaintenanceViewStrategy extends ReactiveElement {
const sections: LovelaceSectionRawConfig[] = [];
const entities = findMaintenanceEntities(hass, config.hidden_entities);
const entities = findMaintenanceEntities(
hass,
config.edit_visibility ? undefined : config.hidden_entities
);
const computeTileCard = (entityId: string) =>
computeMaintenanceTileCard(hass.states, hass.entities, entityId);
const computeCard: ComputeEntityCard = config.edit_visibility
? wrapEntityVisibility(new Set(config.hidden_entities), computeTileCard)
: computeTileCard;
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -232,7 +244,12 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(areaIds, hass, entities);
const areaCards = processAreasForBattery(
areaIds,
hass,
entities,
computeCard
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -258,7 +275,12 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(hierarchy.areas, hass, entities);
const areaCards = processAreasForBattery(
hierarchy.areas,
hass,
entities,
computeCard
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -267,7 +289,11 @@ export class MaintenanceViewStrategy extends ReactiveElement {
}
// Process unassigned entities
const unassignedCards = processUnassignedEntities(hass, entities);
const unassignedCards = processUnassignedEntities(
hass,
entities,
computeCard
);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
+46 -3
View File
@@ -1106,6 +1106,46 @@
"failed_create_floor": "Failed to create floor.",
"unknown": "Unknown floor selected"
},
"rooms": {
"keywords": {
"living_room": "living room|lounge|family room|sitting room|den|living",
"bedroom": "bedroom|guest room|master bedroom|master suite|bed room",
"kids_room": "kids room|kids' room|kid's room|children's room|nursery|playroom|baby room",
"kitchen": "kitchen|kitchenette",
"dining_room": "dining room|dining area|dining",
"bathroom": "bathroom|bath|shower room|ensuite|washroom",
"toilet": "toilet|wc|restroom|powder room|loo|lavatory",
"office": "office|study|home office|workspace|workroom",
"laundry_room": "laundry|laundry room",
"hallway": "hallway|hall|corridor|entrance|entryway|foyer|mudroom",
"stairs": "stairs|staircase|stairway|stairwell|landing",
"garage": "garage|carport",
"garden": "garden|yard|backyard|front yard|lawn|greenhouse",
"terrace": "terrace|patio|balcony|deck|porch|veranda",
"basement": "basement|cellar",
"attic": "attic|loft",
"storage": "storage|storage room|pantry|closet|shed|storeroom",
"utility_room": "utility room|boiler room|technical room|plant room",
"pool": "pool|swimming pool|pool house",
"media_room": "media room|home cinema|home theater|home theatre|cinema room|movie room|tv room",
"game_room": "game room|games room|gaming room|recreation room|rec room|billiard room",
"music_room": "music room|music studio|piano room|practice room",
"library": "library|reading room|book room",
"bar": "bar|home bar|pub|wine room|wine cellar",
"dressing_room": "dressing room|walk-in closet|walk-in wardrobe",
"workshop": "workshop|tool room|craft room|hobby room",
"server_room": "server room|network room|rack room",
"safe_room": "safe room|panic room|shelter|storm shelter|bunker",
"prayer_room": "prayer room|chapel|meditation room",
"sauna": "sauna|steam room",
"outdoor_kitchen": "outdoor kitchen|summer kitchen|barbecue area|bbq area|grill area",
"driveway": "driveway|parking|parking space"
}
},
"icon_picker": {
"suggested": "Suggested",
"all_icons": "All icons"
},
"area-filter": {
"title": "Areas",
"no_areas": "No areas",
@@ -1333,6 +1373,7 @@
"not_supported": "WebRTC is not supported in this browser.",
"start_failed": "Failed to start the WebRTC stream: {message}",
"connect_failed": "Failed to connect the WebRTC stream: {message}",
"no_connection": "Could not connect the WebRTC stream.",
"microphone_failed": "Could not access the microphone: {message}",
"microphone_connect_failed": "Could not connect the microphone to the camera: {message}"
},
@@ -3244,13 +3285,13 @@
},
"mcp": {
"header": "Model Context Protocol",
"description": "Add one of the URLs below to your AI agent. See the {documentation_link} for agent-specific instructions.",
"description_disabled": "See the {documentation_link} to learn how to connect your AI agent to Home Assistant.",
"description": "Add one of the URLs below to your AI app. See the {documentation_link} for app-specific instructions.",
"description_disabled": "See the {documentation_link} to learn how to connect your AI app to Home Assistant.",
"documentation": "documentation",
"enable": "[%key:ui::common::enable%]",
"disable": "[%key:ui::common::disable%]",
"disable_confirm_title": "Disable the Model Context Protocol server?",
"disable_confirm_text": "AI agents connected to the server will lose access to Home Assistant.",
"disable_confirm_text": "AI apps connected to the server will lose access to Home Assistant.",
"your_api_header": "Main URL",
"apis_header": "Individual URLs",
"copy_url": "Copy URL",
@@ -6401,6 +6442,8 @@
"label": "Triggered by",
"no_triggers": "There are no triggers in this automation. Add a trigger first.",
"no_triggers_selected": "No triggers selected.",
"blueprint_no_trigger_ids": "This blueprint has no triggers with IDs, so there is nothing to choose.",
"blueprint_triggers_unavailable": "Complete all of the blueprint's required inputs to see its triggers.",
"id": "Trigger",
"missing_trigger": "Missing trigger",
"missing_triggers": "This condition references a trigger that no longer exists. Uncheck it to clear it.",
+17
View File
@@ -264,6 +264,23 @@ describe("downSampleLineData", () => {
]);
});
it("drops a marker followed by a value that is neither min nor max", () => {
// The reading after the gap repeats the one before it, so it loses the
// min/max ties. The series then holds still for hours (#55896).
const points: GappedPoint[] = [
[FIXED_EPOCH_MS, 1.2],
[FIXED_EPOCH_MS + 1_000, 1.2],
[FIXED_EPOCH_MS + 1_001, 1.2],
[FIXED_EPOCH_MS + 1_001, null],
[FIXED_EPOCH_MS + 2_000, 1.2],
[FIXED_EPOCH_MS + 30_000, 1.2],
[FIXED_EPOCH_MS + 31_000, 1.2],
];
expect(
downSampleLineData(points, 3).some((point) => point[1] === null)
).toBe(false);
});
it("keeps a marker sharing its x with a value after that value", () => {
// statistics-chart-data.ts ends the line and breaks it at the same x
const points: GappedPoint[] = [
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import {
selectCameraStreams,
type CameraStreamSelectionOptions,
} from "../../src/data/camera-streams";
const ok = { hasVideo: true, hasAudio: true };
const silent = { hasVideo: true, hasAudio: false };
const failed = { hasVideo: false, hasAudio: false };
const select = (
options: Omit<CameraStreamSelectionOptions, "supportedTypes">
) =>
selectCameraStreams({ supportedTypes: ["web_rtc", "hls"], ...options })
.map((stream) => (stream.visible ? stream.type : `(${stream.type})`))
.join(" ");
// The player has no other fallback: a wrong choice here shows a broken or
// silent stream while a working one is available.
describe("selectCameraStreams", () => {
it("works", () => {
expect(selectCameraStreams({})).toEqual([]);
expect(selectCameraStreams({ supportedTypes: [] })).toEqual([
{ type: "mjpeg", visible: true },
]);
expect(
selectCameraStreams({ supportedTypes: ["hls"], hlsStreams: failed })
).toEqual([{ type: "mjpeg", visible: true }]);
// Loading: HLS is shown until WebRTC is ready
expect(select({})).toBe("hls (web_rtc)");
expect(select({ hlsStreams: ok })).toBe("hls (web_rtc)");
expect(select({ hlsStreams: failed })).toBe("web_rtc");
// WebRTC loaded: always preferred, also when only HLS has audio
expect(select({ webRtcStreams: ok })).toBe("web_rtc");
expect(select({ webRtcStreams: silent, hlsStreams: ok })).toBe("web_rtc");
expect(select({ webRtcStreams: ok, hlsStreams: failed })).toBe("web_rtc");
// WebRTC failed
expect(select({ webRtcStreams: failed })).toBe("hls");
expect(select({ webRtcStreams: failed, hlsStreams: ok })).toBe("hls");
expect(select({ webRtcStreams: failed, hlsStreams: failed })).toBe("mjpeg");
});
});
+69 -1
View File
@@ -1,12 +1,80 @@
import { describe, expect, it } from "vitest";
import type { Connection } from "home-assistant-js-websocket";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { MatterCommissioningParameters } from "../../src/data/matter";
import {
matterShareRemainingSeconds,
matterShareTargetExternal,
watchForNewMatterDevice,
} from "../../src/data/matter";
import { subscribeDeviceRegistry } from "../../src/data/ws-device_registry";
import type { ExternalConfig } from "../../src/external_app/external_messaging";
import type { HomeAssistant } from "../../src/types";
// The device registry collection unsubscribes from its updates once no
// subscriber is left, so an extra unsubscribe silently breaks every other one.
describe("watchForNewMatterDevice", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
const fakeRegistry = () => {
const devices: string[] = ["existing"];
const eventCallbacks = new Set<() => void>();
const connection = {
connected: true,
sendMessagePromise: vi.fn(async () =>
devices.map((id) => ({
id,
identifiers: [["matter", id]],
connections: [],
}))
),
subscribeEvents: vi.fn(async (callback: () => void) => {
eventCallbacks.add(callback);
return async () => {
eventCallbacks.delete(callback);
};
}),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
} as unknown as Connection;
return {
connection,
eventCallbacks,
addDevice: (id: string) => {
devices.push(id);
eventCallbacks.forEach((callback) => callback());
},
};
};
it("keeps the registry subscribed when the caller unsubscribes after a find", async () => {
const registry = fakeRegistry();
const hass = { connection: registry.connection } as HomeAssistant;
subscribeDeviceRegistry(registry.connection, () => undefined);
const found = vi.fn();
const unsub = watchForNewMatterDevice(hass, found);
await vi.advanceTimersByTimeAsync(10);
registry.addDevice("new");
await vi.advanceTimersByTimeAsync(600);
expect(found).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ id: "new" })
);
// The add device dialog unsubscribes again when it closes.
unsub();
// Past the collection's grace period for unsubscribing.
await vi.advanceTimersByTimeAsync(6000);
expect(registry.eventCallbacks.size).toBe(1);
});
});
const codesOnly: MatterCommissioningParameters = {
setup_pin_code: 20202021,
setup_manual_code: "34970112332",
+78
View File
@@ -0,0 +1,78 @@
import { afterEach, assert, describe, it, vi } from "vitest";
import { refreshHassioSession } from "../../src/data/hassio/ingress";
import type { HomeAssistant } from "../../src/types";
interface IngressMessage {
type: string;
slug?: string;
session?: string;
}
describe("Refresh hassio session", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("keeps the session when it is still valid", async () => {
const calls: IngressMessage[] = [];
const hass = {
callWS: async (msg: IngressMessage) => {
calls.push(msg);
return {};
},
} as unknown as Pick<HomeAssistant, "callWS">;
const session = await refreshHassioSession(hass, "my_app", "old-session");
assert.strictEqual(session, "old-session");
assert.deepEqual(calls, [
{ type: "supervisor/ingress/validate_session", session: "old-session" },
]);
});
it("creates a new session for the app when validation fails", async () => {
vi.stubGlobal("document", {});
vi.stubGlobal("location", { protocol: "http:" });
const calls: IngressMessage[] = [];
const hass = {
callWS: async (msg: IngressMessage) => {
calls.push(msg);
if (msg.type === "supervisor/ingress/validate_session") {
throw new Error("Unauthorized");
}
return { session: "new-session" };
},
} as unknown as Pick<HomeAssistant, "callWS">;
const session = await refreshHassioSession(hass, "my_app", "old-session");
assert.strictEqual(session, "new-session");
assert.deepEqual(calls, [
{ type: "supervisor/ingress/validate_session", session: "old-session" },
{ type: "supervisor/ingress/session", slug: "my_app" },
]);
assert.strictEqual(
global.document.cookie,
"ingress_session=new-session;path=/api/hassio_ingress/;SameSite=Strict"
);
});
it("rejects when neither validation nor creation works", async () => {
const hass = {
callWS: async () => {
throw new Error("Connection lost");
},
} as unknown as Pick<HomeAssistant, "callWS">;
const result = await refreshHassioSession(
hass,
"my_app",
"old-session"
).then(
() => "resolved",
() => "rejected"
);
assert.strictEqual(result, "rejected");
});
});
+21 -19
View File
@@ -105,6 +105,7 @@ const run = ({
tag === "dialog"
? { showModal: dialog ? () => undefined : undefined }
: fakeElement(tag),
createTextNode: (text) => ({ tag: "#text", textContent: text }),
getElementById: (id) => (id === "ha-launch-screen-info-box" ? box : null),
};
// eslint-disable-next-line no-new-func
@@ -124,13 +125,15 @@ const run = ({
{ now: () => now },
(src) => started.push(src)
);
const buttons = Object.fromEntries(
(box.children.find((child) => child.tag === "div")?.children ?? []).map(
(button) => [button.textContent, button.listeners.click]
)
);
const actions =
box.children.find((child) => child.tag === "div")?.children ?? [];
const continueAnyway = actions.find((child) => child.tag === "button")
?.listeners.click;
const checkbox = actions
.find((child) => child.tag === "label")
?.children.find((child) => child.tag === "input");
const shown = box.children.map((child) => child.tag);
return { started, box, store, buttons, shown };
return { started, box, store, continueAnyway, checkbox, shown };
};
describe("index.html legacy browser check", () => {
@@ -144,11 +147,11 @@ describe("index.html legacy browser check", () => {
["BigInt", { bigInt: false, dialog: true }],
["native dialog", { bigInt: true, dialog: false }],
])("offers to continue without %s", (_, browser) => {
const { started, box, store, buttons } = run(browser);
const { started, box, store, continueAnyway, checkbox } = run(browser);
expect(started).toEqual([]);
expect(Object.keys(buttons)).toEqual(["Continue anyway"]);
expect(checkbox).toBeUndefined();
buttons["Continue anyway"]();
continueAnyway();
expect(started).toEqual([ENTRY]);
expect(store[ACCEPTED_KEY]).toBe(String(NOW));
// The message stays up while the app loads.
@@ -165,17 +168,16 @@ describe("index.html legacy browser check", () => {
const stored = String(NOW - 30 * DAY);
const reminder = run({ stored });
expect(reminder.started).toEqual([]);
expect(Object.keys(reminder.buttons)).toEqual([
"Continue anyway",
"Don't show again",
]);
expect(reminder.checkbox.type).toBe("checkbox");
// Unchecked: starts the next month.
const continued = run({ stored });
continued.buttons["Continue anyway"]();
continued.continueAnyway();
expect(continued.started).toEqual([ENTRY]);
expect(continued.store[ACCEPTED_KEY]).toBe(String(NOW));
reminder.buttons["Don't show again"]();
reminder.checkbox.checked = true;
reminder.continueAnyway();
expect(reminder.started).toEqual([ENTRY]);
expect(reminder.store[ACCEPTED_KEY]).toBe("always");
expect(run({ stored: "always", now: NOW + 3650 * DAY }).started).toEqual([
@@ -185,15 +187,15 @@ describe("index.html legacy browser check", () => {
// A tablet that lost its clock.
it("asks again when the clock is behind the stored time", () => {
const { started, buttons } = run({ stored: String(NOW + DAY) });
const { started, continueAnyway } = run({ stored: String(NOW + DAY) });
expect(started).toEqual([]);
expect(buttons["Continue anyway"]).toBeDefined();
expect(continueAnyway).toBeDefined();
});
it("still continues when storage is unavailable", () => {
const { started, buttons } = run({ storageThrows: true });
const { started, continueAnyway } = run({ storageThrows: true });
expect(started).toEqual([]);
buttons["Continue anyway"]();
continueAnyway();
expect(started).toEqual([ENTRY]);
});
});
@@ -0,0 +1,195 @@
import { ContextEvent } from "@lit/context";
import { LitElement } from "lit";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
AutomationConfig,
BlueprintAutomationConfig,
Trigger,
} from "../../../../../src/data/automation";
import { AutomationTriggerController } from "../../../../../src/panels/config/automation/trigger/automation-trigger-controller";
import {
automationTriggerContext,
type AutomationTriggerContext,
} from "../../../../../src/panels/config/automation/trigger/automation-trigger-id";
class TestHost extends LitElement {}
customElements.define("test-automation-trigger-host", TestHost);
declare global {
interface HTMLElementTagNameMap {
"test-automation-trigger-host": TestHost;
}
}
// A stored blueprint automation: only `use_blueprint`, with input values.
const blueprint = (path: string, input: Record<string, unknown> = {}) =>
({ use_blueprint: { path, input } }) as unknown as BlueprintAutomationConfig;
const trigger = (id: string): Trigger => ({
trigger: "event",
event_type: id,
id,
});
/** A fetch whose responses the test resolves or rejects in any order. */
const createFetch = () => {
const pending: {
resolve: (triggers: Trigger[] | undefined) => void;
reject: (err: Error) => void;
}[] = [];
const fetch = vi.fn(
() =>
new Promise<Trigger[] | undefined>((resolve, reject) => {
pending.push({ resolve, reject });
})
);
return { fetch, pending };
};
describe("AutomationTriggerController with a blueprint automation", () => {
let host: TestHost;
let config: AutomationConfig;
let fetch: ReturnType<typeof createFetch>;
let controller: AutomationTriggerController;
// What a condition editor inside the automation receives.
const context = (): AutomationTriggerContext => {
let value: AutomationTriggerContext | undefined;
const child = document.createElement("div");
host.appendChild(child);
child.dispatchEvent(
new ContextEvent(automationTriggerContext, child, (v) => {
value = v;
})
);
child.remove();
return value!;
};
const ids = () => context().options.map((option) => option.id);
// The host's update after the editor's config changes.
const update = (next: AutomationConfig) => {
config = next;
controller.hostUpdate();
};
// Let timers and answered fetches run, then the update they request.
const settle = async () => {
await vi.runAllTimersAsync();
controller.hostUpdate();
};
beforeEach(() => {
vi.useFakeTimers();
// Left out of the document, so only the test runs the host's updates.
host = document.createElement("test-automation-trigger-host");
fetch = createFetch();
config = blueprint("motion.yaml");
controller = new AutomationTriggerController(host, {
getConfig: () => config,
canEdit: () => true,
commit: vi.fn(),
fetchBlueprintTriggers: fetch.fetch,
});
});
afterEach(() => {
controller.hostDisconnected();
vi.useRealTimers();
});
it("offers the IDs of the blueprint's substituted triggers", async () => {
update(blueprint("motion.yaml", { sensor: "binary_sensor.hall" }));
expect(fetch.fetch).toHaveBeenCalledWith({
path: "motion.yaml",
input: { sensor: "binary_sensor.hall" },
});
fetch.pending[0].resolve([trigger("motion_on"), trigger("motion_off")]);
await settle();
expect(ids()).toEqual(["motion_on", "motion_off"]);
});
it("reports the options as loading until the triggers arrive", async () => {
update(blueprint("motion.yaml"));
expect(context().blueprintStatus).toBe("loading");
fetch.pending[0].resolve([trigger("motion_on")]);
await settle();
expect(context().blueprintStatus).toBe("loaded");
});
it("reports a blueprint whose triggers have no IDs as loaded", async () => {
update(blueprint("motion.yaml"));
fetch.pending[0].resolve([{ trigger: "event", event_type: "motion" }]);
await settle();
expect(ids()).toEqual([]);
expect(context().blueprintStatus).toBe("loaded");
});
it("reports a blueprint that never substituted as failed", async () => {
update(blueprint("motion.yaml"));
fetch.pending[0].reject(new Error("Missing input sensor"));
await settle();
expect(ids()).toEqual([]);
expect(context().blueprintStatus).toBe("failed");
});
it("keeps the last triggers listed, as loading, while new inputs load", async () => {
update(blueprint("motion.yaml", { id: "motion_on" }));
fetch.pending[0].resolve([trigger("motion_on")]);
await settle();
update(blueprint("motion.yaml", { id: "motion_detected" }));
expect(ids()).toEqual(["motion_on"]);
expect(context().blueprintStatus).toBe("loading");
await vi.runAllTimersAsync();
fetch.pending[1].resolve([trigger("motion_detected")]);
await settle();
expect(ids()).toEqual(["motion_detected"]);
expect(context().blueprintStatus).toBe("loaded");
});
it("fetches again only when `use_blueprint` changes by value", async () => {
update(blueprint("motion.yaml", { wait: 1 }));
// YAML mode parses a new, equal object when another key is edited.
update({ ...blueprint("motion.yaml", { wait: 1 }), alias: "Hall" });
await vi.runAllTimersAsync();
expect(fetch.fetch).toHaveBeenCalledOnce();
});
it("uses only the response for the latest inputs", async () => {
update(blueprint("motion.yaml", { wait: 1 }));
update(blueprint("motion.yaml", { wait: 2 }));
await vi.runAllTimersAsync();
expect(fetch.fetch).toHaveBeenCalledTimes(2);
fetch.pending[1].resolve([trigger("latest")]);
fetch.pending[0].resolve([trigger("stale")]);
await settle();
expect(ids()).toEqual(["latest"]);
});
it("keeps the last triggers when the inputs fail to substitute", async () => {
update(blueprint("motion.yaml", { wait: 1 }));
fetch.pending[0].resolve([trigger("motion_on")]);
await settle();
update(blueprint("motion.yaml", { wait: undefined }));
await vi.runAllTimersAsync();
fetch.pending[1].reject(new Error("Missing input wait"));
await settle();
expect(ids()).toEqual(["motion_on"]);
expect(context().blueprintStatus).toBe("failed");
});
});
@@ -10,6 +10,7 @@ import {
cleanupRemovedGeneratedTriggerReferences,
cleanupUnusedGeneratedTriggerIds,
GENERATED_TRIGGER_ID_PREFIX,
getBlueprintTriggerIdOptions,
getExplicitTriggerIds,
getTriggerIdOptions,
hasCustomTriggerId,
@@ -25,6 +26,40 @@ const GENERATED_TRIGGER_ID_PATTERN = new RegExp(
);
describe("automation trigger IDs", () => {
it("offers a blueprint's stored trigger IDs once each, without generating any", () => {
const motion: Trigger = {
trigger: "state",
entity_id: "binary_sensor.motion",
id: "motion_on",
};
const triggers = [
motion,
{ trigger: "time_pattern", minutes: "/5" },
{
trigger: "state",
entity_id: "binary_sensor.presence",
id: "motion_on",
},
{ triggers: [{ trigger: "sun", event: "sunset", id: "sunset" }] },
] as Trigger[];
const options = getBlueprintTriggerIdOptions(triggers);
expect(
options.map(({ id, index, draft, duplicate }) => ({
id,
index,
draft,
duplicate,
}))
).toEqual([
{ id: "motion_on", index: 0, draft: false, duplicate: false },
{ id: "sunset", index: 3, draft: false, duplicate: false },
]);
expect(options[0].trigger).toBe(motion);
expect(getBlueprintTriggerIdOptions(undefined)).toEqual([]);
});
it("ignores null trigger entries from incomplete YAML", () => {
const triggers = [
null,
@@ -209,6 +209,76 @@ describe("action-handler container (resolve) bindings", () => {
});
});
describe("action-handler touch movement", () => {
let el: HTMLElement;
let actions: string[];
beforeEach(() => {
vi.useFakeTimers();
el = document.createElement("div");
document.body.appendChild(el);
actions = actionsOn(el);
actionHandlerBind(el, { hasHold: true });
});
afterEach(() => {
vi.runOnlyPendingTimers();
vi.useRealTimers();
el.remove();
});
it("still taps when the finger moves a few pixels", () => {
el.dispatchEvent(touch("touchstart", { x: 10, y: 10 }));
el.dispatchEvent(touch("touchmove", { x: 14, y: 17 }));
const end = touch("touchend", { x: 14, y: 17 });
el.dispatchEvent(end);
expect(actions).toEqual(["tap"]);
// No emulated click follows, so the tap fires once.
expect(end.defaultPrevented).toBe(true);
});
it("still holds when the finger moves a few pixels", () => {
el.dispatchEvent(touch("touchstart", { x: 10, y: 10 }));
el.dispatchEvent(touch("touchmove", { x: 12, y: 18 }));
vi.advanceTimersByTime(500);
el.dispatchEvent(touch("touchend", { x: 12, y: 18 }));
expect(actions).toEqual(["hold"]);
});
it("drops the press once the finger moves past the slop", () => {
el.dispatchEvent(touch("touchstart", { x: 10, y: 10 }));
el.dispatchEvent(touch("touchmove", { x: 14, y: 17 }));
el.dispatchEvent(touch("touchmove", { x: 10, y: 40 }));
el.dispatchEvent(touch("touchend", { x: 10, y: 40 }));
vi.advanceTimersByTime(500);
expect(actions).toEqual([]);
});
it("drops the press when the page scrolls", () => {
el.dispatchEvent(touch("touchstart", { x: 10, y: 10 }));
document.dispatchEvent(new Event("scroll"));
el.dispatchEvent(touch("touchend", { x: 10, y: 10 }));
expect(actions).toEqual([]);
});
it("drops the press when the browser takes over the touch", () => {
// A nested scroller: its scroll event never reaches the document, but the
// composed pointercancel does.
const host = document.createElement("div");
const inner = document.createElement("div");
host.attachShadow({ mode: "open" }).appendChild(inner);
el.appendChild(host);
el.dispatchEvent(touch("touchstart", { x: 10, y: 10 }));
el.dispatchEvent(touch("touchmove", { x: 14, y: 14 }));
inner.dispatchEvent(
new Event("pointercancel", { bubbles: true, composed: true })
);
el.dispatchEvent(touch("touchend", { x: 14, y: 14 }));
vi.advanceTimersByTime(500);
expect(actions).toEqual([]);
});
});
describe("action-handler keyboard-only bindings", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
@@ -311,4 +311,40 @@ describe("MaintenanceViewStrategy.generate", () => {
},
]);
});
it("keeps hidden entities as hidden visibility wrappers while editing", async () => {
const view = await MaintenanceViewStrategy.generate(
{
type: "maintenance",
hidden_entities: ["sensor.car_target_charge"],
edit_visibility: true,
},
createBatteryHass()
);
const section = view.sections?.[0] as LovelaceSectionConfig;
expect(section.cards?.slice(1)).toEqual([
{
type: "entity-visibility",
entity: "sensor.car_target_charge",
hidden: true,
card: {
type: "tile",
entity: "sensor.car_target_charge",
name: { type: "entity" },
},
},
{
type: "entity-visibility",
entity: "sensor.remote_battery",
hidden: false,
card: {
type: "tile",
entity: "sensor.remote_battery",
name: { type: "entity" },
},
},
]);
});
});