Compare commits

..

40 Commits

Author SHA1 Message Date
Petar Petrov 1190dfa4d7 Stop the statistics graph card editor looping while typing a name 2026-08-01 14:52:40 +03:00
karwosts e6df5fd159 Reuse state-display for entities secondary info (#53260)
* Reuse state-content for entities secondary info

* migrate area

* Skip schema calculation when using predefined schema.

* add tooltip, migrate none

* timestamp for weather
2026-07-31 23:07:10 +02:00
Aidan Timson 0da3ec1151 Wait for calendar and media browser readiness (#53367)
* Wrap dashboard loading spinner in a delayed fade in component

* Expose initial view render completion

* Wait for dashboard initial readiness

* Signal initial Lovelace view readiness

* Aggregate dashboard view readiness

* Wait for generated panel readiness

* Test dashboard initial readiness

* Add fade in delay to correct dashboard loading

* Delay generated panel readiness until content

* Test generated dashboard initial readiness

* Guard component spread against undefined for unknown panels

Co-authored-by: timmo001 <28114703+timmo001@users.noreply.github.com>

* Wait for calendar and media browser readiness

* Test calendar and media browser readiness

* Wait for media panel host readiness

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com>
2026-07-31 22:43:56 +02:00
Aidan Timson 46fdf9c91b Wait for dashboard initial readiness (#53357)
* Wrap dashboard loading spinner in a delayed fade in component

* Expose initial view render completion

* Wait for dashboard initial readiness

* Signal initial Lovelace view readiness

* Aggregate dashboard view readiness

* Wait for generated panel readiness

* Test dashboard initial readiness

* Add fade in delay to correct dashboard loading

* Delay generated panel readiness until content

* Test generated dashboard initial readiness

* Guard component spread against undefined for unknown panels

Co-authored-by: timmo001 <28114703+timmo001@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-31 22:00:54 +02:00
Bram Kragten 80a026d9bf Recover from a stale index.html at boot (#53378)
* Recover from a stale index.html at boot

A cached, stale index.html imports the previous build's content-hashed
entry bundles (core.<hash>.js / app.<hash>.js). After an upgrade those
files 404, app.js never runs, <home-assistant> is never defined, and the
launch screen never clears. No bundled JS can recover this, because the
bundle itself failed to load.

Add a tiny, prod-only inline guard in index.html that catches the failed
entry load (capture-phase resource error + unhandledrejection) and does a
single, loop-guarded cache-busting reload, dropping the service worker and
caches on https first. core.ts strips the cache-bust param after a
successful boot.

Part of home-assistant/epics#113.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Share stale-build recovery patterns via a single JSON source

Move the boot guard's chunk-detection regexes into
stale-build-patterns.json and inject them into the inline guard at build
time (entry-html.js), so they stay in sync with the bundled recovery util
(util/recover-stale-build.ts, in the follow-up post-boot recovery) which
reads the same file — no more manually kept-in-sync copies.

Part of home-assistant/epics#113.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Potential fix for pull request finding

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-31 21:45:59 +02:00
Petar Petrov dc5699fec3 Ask which occurrences to change in the recurring event dialog (#53423)
* Ask which occurrences to change in the recurring event dialog

Deleting or updating a recurring event offered "only this event" and "all
future events" as two long buttons, which a 320px dialog footer squeezed
until every word wrapped onto its own line.

Move the choice into the dialog body as a radio group and leave the footer
with Cancel plus a single confirm action. The dialog also becomes an alert,
so it stays a centered card on small viewports, and the confirm action is
only styled as destructive for the delete flows.

* Apply suggestions from code review

Co-authored-by: Aidan Timson <aidan@timmo.dev>

* Update src/panels/calendar/confirm-event-dialog-box.ts

Co-authored-by: Aidan Timson <aidan@timmo.dev>

---------

Co-authored-by: Aidan Timson <aidan@timmo.dev>
Co-authored-by: Paul Bottein <paul.bottein@gmail.com>
2026-07-31 21:42:02 +02:00
Aidan Timson 3a1d330a2f Offer to stop conflicting managed workflows (#53418)
* Offer to stop conflicting managed workflows

* Apply suggestions from code review

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

* Fix syntax error: misplaced brace before finally in confirmStopConflict

Co-authored-by: timmo001 <28114703+timmo001@users.noreply.github.com>

* Potential fix for pull request finding

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

* Format

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-31 16:15:44 +03:00
Petar Petrov c8a29ae2f2 Keep progress button labelled while showing its result (#53426)
While the check or error icon covers the button, the button's content was
hidden with `visibility: hidden`, which also removes the label from the
accessibility tree. For the two seconds the result is shown, a screen
reader announced a button with no accessible name.

Fade the content out instead. It looks the same and reserves the same
space, but the label stays readable to assistive technology. The spinner
part keeps `visibility: hidden`, since a finished spinner should leave
the accessibility tree.
2026-07-31 15:50:36 +03:00
Aidan Timson b1ccb6355d Wait for settings overview readiness (#53352)
* Wait for settings overview readiness

* Move panel readiness setup to constructor

* Apply suggestions from code review

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

* Cache bluetooth config entries fetch in settings navigation

* Fix child panel readiness registration race

* Avoid redundant settings navigation renders

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-31 13:22:00 +03:00
Aidan Timson 5f2086765a Add managed translation fetching to dev servers (#53417) 2026-07-31 13:20:50 +03:00
renovate[bot] 02c51a2789 Update dependency @rspack/core to v2.1.6 (#53420)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-31 11:39:06 +02:00
Paul Bottein 706421f3c5 Fix tile name truncated too early (#53416) 2026-07-31 11:52:23 +03:00
Aidan Timson cbc2e34638 Fix profile theme link colour (#53415) 2026-07-31 10:47:45 +02:00
Yosi Levy 0bc0b08978 RTL fixes (#53414) 2026-07-31 08:41:52 +01:00
karwosts 48394db843 Validate dialog-form on submit (#53381)
* Validate dialog-form on submit

* remove whitespace

* put errors on the stack

* Apply suggestion from @MindFreeze

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

* Apply suggestion from @MindFreeze

* Fix botched suggestion apply in nested submit

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2026-07-31 07:14:40 +00:00
Paul Bottein 83dac08059 Use backend slugify for the entity ID format preview (#53394)
* Use backend slugify for the entity ID format preview

* Update src/panels/config/core/ha-config-entity-id-format.ts

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

* Use top-level slugify websocket command

* Fix formatting

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2026-07-31 09:39:47 +03:00
Aidan Timson 3c6b70ded8 Prevent concurrent managed frontend workflows (#53396)
* Shared build and runner for all build,dev,test flows

* Harden managed process lifecycle

* Make build workflows deterministic

* Test build management contracts

* Queue shared generated output work

* Isolate generated inputs for dev servers

* Preserve dev server child failures

* Make generated lock test deterministic

* Keep test navigator configurable

* Block concurrent frontend workflows

* Simplify workflow lock ownership

* Focus workflow locking on managed commands

* Trim workflow lock unit tests

* Consolidate dev server lifecycle handlers
2026-07-31 09:30:49 +03:00
John G. 1e414f31dc Fix typo in Google Home Matter pairing instructions (#53413)
Corrected a typo in the instructions for pairing a Matter device from Google Home with a pairing code.
2026-07-31 04:27:25 +00:00
karwosts d013051f81 Add a few missing logbook csv fields (#53412) 2026-07-31 06:19:05 +02:00
Bram Kragten eb2efbb669 use defaults provided by core for ports in strings, add url to new lo… (#53407)
* use defaults provided by core for ports in strings, add url to new location after restart

* Apply suggestions from code review

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

---------

Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com>
2026-07-31 06:08:38 +02:00
Bram Kragten 7e4d745b21 Prevent http confirm dialog from getting closed (#53406) 2026-07-31 06:08:18 +02:00
Petar Petrov d01f7d98a5 Reject non-http URLs from integrations before using them as links (#53379) 2026-07-30 23:26:29 +02:00
renovate[bot] 6df6b556bd Update dependency @codemirror/view to v6.43.7 (#53409) 2026-07-30 22:34:36 +02:00
Marcel van der Veldt f5c6420fbc Search a media player's own library from the media browser (#53402)
* Search a media player's own library from the media browser

The media browser search only ever asked the media sources, so searching
inside a media player's own library (Music Assistant, Sonos, Squeezebox,
Jellyfin) failed. Ask the entity instead when the current item belongs to
it, the same way browsing already does.

* Update src/data/media_source.ts

* Remove blank line in media_source.ts

Removed unnecessary blank line at the top of media_source.ts

---------

Co-authored-by: Bram Kragten <mail@bramkragten.nl>
Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com>
2026-07-30 15:44:28 +00:00
karwosts 71ec76185f Fix schedule editor dirty tracking (#53401) 2026-07-30 17:37:18 +02:00
Petar Petrov f08ab2f331 Show which energy power statistic is missing (#53404) 2026-07-30 16:41:28 +02:00
Petar Petrov 77b0b9b5b8 Fix numeric input feature editor showing the wrong default style (#53398) 2026-07-30 16:37:16 +02:00
Aidan Timson 4fcc1adf3a Managed background builds and shared process management (#53374)
* Add managed modern production builds

* Harden managed build process controls

* Update managed process testing guidance

* Harden managed process file operations

* Share generated output process ownership

* Clean stale build state on status

* Address managed build review feedback

Co-authored-by: timmo001 <28114703+timmo001@users.noreply.github.com>

* Use single compress task

* 1

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

* Forward SIGHUP to foreground processes

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
2026-07-30 13:25:10 +03:00
renovate[bot] 9699851c26 Update dependency jsdom to v30 (#53395)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-30 12:15:24 +02:00
Raman Gupta a318593c9f Add live updates to Z-Wave JS node config parameters (#53013)
* Fix Z-Wave JS config parameter value type

Type ZWaveJSNodeConfigParam.value as number | null instead of any,
matching what the backend sends. This surfaced two comparison bugs:

- The enumerated picker no-op check compared the stored number against
  the picker's string value, so it never matched and re-selecting the
  current option re-sent the command to the device.
- The numeric input guard coerced null (unknown value) to 0, so
  entering 0 for a parameter with an unknown value was ignored.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Treat empty numeric input as invalid instead of 0

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add live updates to Z-Wave JS node config parameters

Subscribe to config parameter value updates so the page reflects
changes made outside the UI (Z-Wave JS UI, another browser tab, or
the device itself) and so queued changes to sleeping nodes resolve
to a success message when the node wakes and applies them.

- Manage the subscription across connect/disconnect and device
  navigation, deriving deviceId reactively from the route
- Show success results briefly, then clear them automatically
- Clear stale error results when the parameter changes externally
- Discard fetch responses that arrive after navigating to another node

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Address review comments

- Use slice() instead of deprecated substr()
- Clear pending result timeouts when navigating to another node
- Handle subscription promise rejections so an older backend without
  the subscribe command degrades gracefully instead of logging
  unhandled rejections

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 12:14:26 +02:00
Aidan Timson 749dd180ae Launch screen tweaks (#53380)
* Polish the launch screen

- Use the system sans-serif font so the launch screen no longer blocks on
  loading Roboto
- Reduce the gap between the logo and the loading text
- Dim the loading text to 66% opacity
- Match the OHF logo variant to the applied theme instead of the system
  color scheme
- Make the launch screen text and buttons unselectable

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Drop unit test

* Use classMap

* Drop view transition for css transition to avoid flash

---------

Co-authored-by: marcinbauer85 <marcinbauer85@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 12:13:49 +02:00
Maarten Lakerveld 247780e4c8 Tools > Template use WA Split Panel (#53021)
* Add Web Awesome Split Panel component

* Use SplitPanel for template page. Add vertical/horizontal option. Cleanup, use flexbox.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-30 10:39:41 +02:00
Paul Bottein 7991090313 Allow area card name to wrap to two lines in vertical layout (#53370)
* Allow area card name to wrap to two lines in vertical layout

* Align vertical tile icons in grid sections

* Cut single big word
2026-07-30 10:03:43 +03:00
Aidan Timson 2efa0bd86d Prefetch home dashboard resources concurrently (#53373)
Load Home dashboard resources concurrently
2026-07-30 10:01:13 +03:00
Aidan Timson 0fad4f0097 Remove empty items on narrow data table secondary lines (#53382)
* Skip empty cells on the narrow data table secondary line

In narrow mode the main column renders every other visible column on a
secondary line, but the dot separator was inserted based on the column
index instead of whether the cell rendered anything. A row whose extra
columns are all empty showed a secondary line consisting only of dots,
and an empty column between two filled ones produced a double dot.

Filter empty cells out before joining, and return `nothing` instead of
`html`${nothing}`` for missing timestamps so those cells are detectably
empty too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Extract / clarify data table column visibility

* Fix unbound method and add all-empty secondary line test

Co-authored-by: timmo001 <28114703+timmo001@users.noreply.github.com>

* Fix prettier formatting in ha-data-table test

Co-authored-by: timmo001 <28114703+timmo001@users.noreply.github.com>

---------

Co-authored-by: marcinbauer85 <marcinbauer85@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-30 07:07:43 +02:00
Marcin Bauer 2b90c9a628 Show the automation state on mobile in the automations table (#53375)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 19:48:51 +02:00
renovate[bot] f3848df19d Update dependency globals to v17.8.0 (#53387)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-29 19:48:26 +02:00
renovate[bot] e2a91c358d Update Node.js to v24.18.1 (#53386)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-29 19:48:22 +02:00
Paul Bottein 8793cb58b9 Show integration logo and name in the replace device dialog (#53384) 2026-07-29 19:24:39 +02:00
Bram Kragten 2442bf662a Strip empty strings from http config (#53377) 2026-07-29 15:33:02 +02:00
73 changed files with 3234 additions and 1031 deletions
+23 -2
View File
@@ -20,6 +20,7 @@ yarn lint # ESLint + Prettier + TypeScript + Lit
yarn format # Auto-fix ESLint + Prettier
yarn lint:types # TypeScript compiler, run without file arguments
yarn test # Vitest
yarn build # Full production build
yarn dev # App dev server
yarn dev:serve # Local serving dev server
```
@@ -28,6 +29,26 @@ Never run `tsc` or `yarn lint:types` with file arguments. File arguments make `t
For focused type feedback on one file, use editor diagnostics instead of a file-scoped `tsc` command.
## Production Builds
Production builds support foreground and managed background execution:
```bash
yarn build # Full foreground build
yarn build --background # Full managed background build
yarn build --modern # Modern frontend_latest bundle only
yarn build --modern --background # Modern managed background build
yarn build --status
yarn build --logs [--follow]
yarn build --stop
```
Use `yarn build --modern --background` for production bundle-size or browser performance comparisons that only need modern browser output. It runs the normal metadata and static preparation, minifies and compresses the modern `frontend_latest` bundle and shared static assets, and generates modern-only entry pages and service workers. It deliberately skips the legacy bundle and its service worker.
Do not pass `--help`, `--background`, or `--modern` to `script/build_frontend`; that raw script does not parse arguments and always starts the full foreground build. Use `yarn build` for managed builds. App builds and development servers keep exclusive ownership of `hass_frontend/` for their lifetime.
Managed app, demo, gallery, and E2E app workflows share one lifetime lock, so only one build or development server can run at a time.
## Unit And Utility Tests
- Add or update Vitest tests for data processing, utility code, and behavior that can be tested without a browser.
@@ -41,7 +62,7 @@ For focused type feedback on one file, use editor diagnostics instead of a file-
`yarn dev:serve` also serves locally and supports `-c` for the core URL and `-p` for the port. The default is 8124, or 8123 in a devcontainer.
Dev server commands support `--background`, `--status`, `--stop`, and `--logs [--follow]`. Prefer managed background mode while iterating so the watcher stays available across test runs without occupying the terminal.
Dev server commands support `--background`, `--status`, `--stop`, and `--logs [--follow]`. `yarn dev`, `yarn dev:serve`, `yarn dev:demo`, and `yarn dev:gallery` also support `--fetch-translations`; this runs translation fetching, including first-time GitHub device authentication, under the workflow lock before starting the watcher. It works in foreground and background modes. Prefer managed background mode while iterating so the watcher stays available across test runs without occupying the terminal. `yarn dev` and `yarn dev:serve` share one managed process slot because both write the app output.
## Playwright E2E
@@ -59,7 +80,7 @@ The custom development wrappers use `/__ha_dev_status` to identify and manage th
Local runs against a watched development server do not always match CI's clean build artifacts, environment, sharding, or worker configuration. Use background servers for the fast iteration loop, but confirm the relevant CI jobs complete successfully before considering E2E changes verified.
Use `-g "<title>" --project=chromium` to narrow a run. `yarn test:e2e` runs all three suites in parallel when every managed server is available, otherwise it runs them sequentially to prevent cold builds racing over shared generated assets. Run suites directly; piping through output truncation hides progress and failures.
Use `-g "<title>" --project=chromium` to narrow a run. `yarn test:e2e` runs suites sequentially when managed servers are unavailable to prevent cold builds racing over shared generated assets. Run suites directly; piping through output truncation hides progress and failures.
The app suite uses a stripped-down harness for e2e. Demo and gallery use their normal dev servers.
+1 -1
View File
@@ -1 +1 @@
24.18.0
24.18.1
+1 -1
View File
@@ -12,7 +12,7 @@ This is the repository for the official [Home Assistant](https://home-assistant.
- Initial setup: `script/setup`
- Development: [Instructions](https://developers.home-assistant.io/docs/frontend/development/)
- Production build: `script/build_frontend`
- Production build: `yarn build`
- Gallery: `cd gallery && script/develop_gallery`
## Frontend development
+311
View File
@@ -0,0 +1,311 @@
// Manage a Home Assistant frontend production build with an agent-friendly
// interface, matching build-scripts/dev-server.mjs.
//
// node build-scripts/build-manager.mjs [--modern] [mode]
//
// (no mode) Run in the foreground.
// --background Start detached, print the pid, then exit and leave it
// running.
// --status Report whether a managed build is running.
// --stop Stop a managed build.
// --logs [--follow] Print (or follow) the background build log.
//
// --modern Build only the modern frontend_latest bundle.
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
LIFECYCLE_MODE_FLAGS,
acquireProcessRecord,
isProcessRecordAlive,
outputLog,
offerToStopProcessRecord,
processStartTime,
readProcessRecord,
releaseProcessRecord,
runCli,
spawnDetachedToLog,
spawnForeground,
terminateDetachedProcess,
terminateProcess,
waitFor,
writeProcessRecord,
} from "./managed-process.mjs";
import {
buildCacheDir,
describeOutputOwner,
workflowLockEnv,
workflowLockFile,
} from "./output-lock.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
".."
);
const gulpBin = path.join(repoRoot, "node_modules", ".bin", "gulp");
const stateDir = path.join(buildCacheDir, "ha-build");
const logFile = path.join(stateDir, "build.log");
const lockFile = workflowLockFile;
const usage = () => {
process.stderr.write(
"Usage: node build-scripts/build-manager.mjs [--modern] " +
"[--background | --status | --stop | --logs [--follow]]\n"
);
};
const parseArgs = (argv) => {
const args = {
mode: "foreground",
modes: [],
follow: false,
modern: false,
unknown: [],
};
for (const arg of argv) {
if (LIFECYCLE_MODE_FLAGS.has(arg)) {
args.mode = LIFECYCLE_MODE_FLAGS.get(arg);
args.modes.push(arg);
} else if (arg === "--modern") {
args.modern = true;
} else if (arg === "--follow") {
args.follow = true;
} else {
args.unknown.push(arg);
}
}
return args;
};
const hints = () =>
" Stop: yarn build --stop\n" +
" Status: yarn build --status\n" +
" Logs: yarn build --logs\n";
const devCommand = (suite) => {
switch (suite) {
case "app-serve":
return "dev:serve";
case "demo":
return "dev:demo";
case "gallery":
return "dev:gallery";
case "e2e-app":
return "test:e2e:app:dev";
default:
return "dev";
}
};
const readBuild = () => readProcessRecord(lockFile);
const releaseBuild = (token) => releaseProcessRecord(lockFile, token);
const stopCommandFor = (owner) =>
owner?.kind === "build"
? "yarn build --stop"
: owner?.kind === "dev"
? `yarn ${devCommand(owner.suite)} --stop`
: undefined;
const acquireBuild = async (modern, foreground) => {
const token = `${process.pid}-${Date.now()}-${Math.random()}`;
const record = {
pid: process.pid,
startTime: processStartTime(process.pid),
processGroup: false,
foreground,
kind: "build",
modern,
starting: true,
token,
};
const result = acquireProcessRecord(lockFile, record);
if (result.acquired) {
return { token };
}
reportExisting(result.existing);
return (await offerToStopProcessRecord({
file: lockFile,
owner: result.existing,
ownerDescription: describeOutputOwner(result.existing),
stopCommand: stopCommandFor(result.existing),
}))
? acquireBuild(modern, foreground)
: { existing: result.existing };
};
const updateBuild = (token, child, processGroup) => {
const existing = readBuild();
if (existing?.token !== token) {
throw Error("Frontend build lock ownership was lost during startup.");
}
writeProcessRecord(lockFile, {
...existing,
pid: child.pid,
startTime: processStartTime(child.pid),
processGroup,
starting: false,
});
};
const taskFor = (modern) => (modern ? "build-app-modern" : "build-app");
const reportExisting = (existing) => {
if (existing?.kind === "output") {
process.stdout.write(
`${describeOutputOwner(existing)} already owns the build and development workflow` +
`${existing.pid ? ` (pid ${existing.pid})` : ""}.\n`
);
return;
}
if (existing?.kind === "dev") {
const command = devCommand(existing.suite);
process.stdout.write(
`Dev server (${existing.suite}) already running` +
`${existing.pid ? ` (pid ${existing.pid})` : ""}.\n` +
` Stop: yarn ${command} --stop\n` +
` Status: yarn ${command} --status\n` +
` Logs: yarn ${command} --logs\n`
);
return;
}
process.stdout.write(
`Frontend ${existing?.modern ? "modern " : ""}build already running` +
`${existing?.pid ? ` (pid ${existing.pid})` : ""}.\n${hints()}`
);
};
const runForeground = async (modern) => {
const lock = await acquireBuild(modern, true);
if (!lock.token) {
return 1;
}
try {
return await spawnForeground({
cmd: gulpBin,
args: [taskFor(modern)],
cwd: repoRoot,
env: workflowLockEnv(lock.token),
processGroup: true,
onSpawn: (child) => updateBuild(lock.token, child, true),
});
} finally {
releaseBuild(lock.token);
}
};
const runBackground = async (modern) => {
const lock = await acquireBuild(modern, false);
if (!lock.token) {
return 1;
}
let child;
try {
child = await spawnDetachedToLog({
cmd: gulpBin,
args: [taskFor(modern)],
cwd: repoRoot,
env: workflowLockEnv(lock.token),
logFile,
});
updateBuild(lock.token, child, true);
process.stdout.write(
`Started ${modern ? "modern " : ""}frontend build (pid ${child.pid})\n` +
hints()
);
return 0;
} catch (err) {
if (child) {
await terminateDetachedProcess(child);
}
releaseBuild(lock.token);
throw err;
}
};
const runStatus = () => {
const existing = readBuild();
if (existing?.kind === "build" && isProcessRecordAlive(existing)) {
process.stdout.write(
`Frontend ${existing.modern ? "modern " : ""}build running (pid ${existing.pid}).\n`
);
} else {
if (existing?.kind === "build") {
releaseBuild(existing.token);
}
process.stdout.write("Frontend build not running.\n");
}
return 0;
};
const runStop = async () => {
let existing = readBuild();
if (existing?.kind !== "build") {
process.stdout.write("Frontend build not running.\n");
return 0;
}
if (existing?.starting) {
const token = existing.token;
await waitFor(
() => {
const current = readBuild();
return !current?.starting || current.token !== token;
},
100,
5000
);
existing = readBuild();
}
if (
!existing ||
existing.kind !== "build" ||
!isProcessRecordAlive(existing)
) {
if (existing) releaseBuild(existing.token);
process.stdout.write("Frontend build not running.\n");
return 0;
}
if (
!(await terminateProcess({
pid: existing.pid,
processGroup: existing.processGroup,
isStopped: () => !isProcessRecordAlive(existing),
}))
) {
process.stderr.write(
`Failed to stop frontend build (pid ${existing.pid}). Stop it manually.\n`
);
return 1;
}
releaseBuild(existing.token);
process.stdout.write(`Stopped frontend build (pid ${existing.pid}).\n`);
return 0;
};
const runLogs = (follow) =>
outputLog(logFile, follow, `No frontend build log yet (${logFile}).\n`);
const main = async () => {
const args = parseArgs(process.argv.slice(2));
if (args.unknown.length) {
process.stderr.write(`Unknown arguments: ${args.unknown.join(" ")}\n`);
usage();
return 1;
}
if (args.modes.length > 1 || (args.follow && args.mode !== "logs")) {
process.stderr.write("Invalid combination of build arguments.\n");
usage();
return 1;
}
const handlers = {
foreground: () => runForeground(args.modern),
background: () => runBackground(args.modern),
status: runStatus,
stop: runStop,
logs: () => runLogs(args.follow),
};
return handlers[args.mode]();
};
runCli(main);
File diff suppressed because it is too large Load Diff
+27
View File
@@ -1,5 +1,6 @@
import gulp from "gulp";
import env from "../env.cjs";
import { createWorkflowLockTask } from "../output-lock.mjs";
import "./clean.js";
import "./compress.js";
import "./entry-html.js";
@@ -17,6 +18,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "development";
},
createWorkflowLockTask("develop-app"),
"clean",
gulp.parallel(
"gen-service-worker-app-dev",
@@ -36,6 +38,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "production";
},
createWorkflowLockTask("build-app"),
"clean",
gulp.parallel(
"gen-icons-json",
@@ -51,6 +54,30 @@ gulp.task(
)
);
gulp.task(
"build-app-modern",
gulp.series(
async function setEnv() {
process.env.NODE_ENV = "production";
},
createWorkflowLockTask("build-app-modern"),
"clean",
gulp.parallel(
"gen-icons-json",
"build-translations",
"build-locale-data",
"gen-licenses"
),
"copy-static-app",
"rspack-prod-app-modern",
gulp.parallel(
"gen-pages-app-prod-modern",
"gen-service-worker-app-prod-modern"
),
...(env.isTestBuild() || env.isStatsBuild() ? [] : ["compress-app"])
)
);
gulp.task(
"analyze-app",
gulp.series(
+3
View File
@@ -1,4 +1,5 @@
import gulp from "gulp";
import { createWorkflowLockTask } from "../output-lock.mjs";
import "./clean.js";
import "./entry-html.js";
import "./gather-static.js";
@@ -13,6 +14,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "development";
},
createWorkflowLockTask("develop-demo"),
"clean-demo",
"translations-enable-merge-backend",
gulp.parallel(
@@ -32,6 +34,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "production";
},
createWorkflowLockTask("build-demo"),
"clean-demo",
// Cast needs to be backwards compatible and older HA has no translations
"translations-enable-merge-backend",
+3
View File
@@ -1,4 +1,5 @@
import gulp from "gulp";
import { createWorkflowLockTask } from "../output-lock.mjs";
import "./clean.js";
import "./entry-html.js";
import "./gather-static.js";
@@ -12,6 +13,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "development";
},
createWorkflowLockTask("develop-e2e-test-app"),
"clean-e2e-test-app",
"translations-enable-merge-backend",
gulp.parallel(
@@ -31,6 +33,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "production";
},
createWorkflowLockTask("build-e2e-test-app"),
"clean-e2e-test-app",
"translations-enable-merge-backend",
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
+27 -2
View File
@@ -58,6 +58,12 @@ const getCommonTemplateVars = () => {
return {
modernRegex: compileRegex(browserRegexes.concat(haMacOSRegex)).toString(),
hassUrl: process.env.HASS_URL || "",
// Single source for the stale-build recovery patterns, shared with the
// bundled src/util/recover-stale-build.ts and injected into the inline
// boot guard (_bootstrap_recovery.html.template).
staleBuildPatterns: fs.readJsonSync(
resolve(paths.root_dir, "src/util/stale-build-patterns.json")
),
};
};
@@ -107,6 +113,9 @@ const genPagesDevTask =
resolve(inputRoot, inputSub, `${page}.template`),
{
...commonVars,
// Dev entries are unhashed, so the stale-index recovery guard has
// nothing to key off and rebuild churn could cause spurious reloads.
useCacheRecovery: false,
latestEntryJS: entries.map(
(entry) => `${publicRoot}/frontend_latest/${entry}.js`
),
@@ -146,10 +155,15 @@ const genPagesProdTask =
resolve(inputRoot, inputSub, `${page}.template`),
{
...commonVars,
// Recover from a stale index.html that pins deleted hashed entry
// bundles (see _bootstrap_recovery.html.template).
useCacheRecovery: true,
latestEntryJS: entries.map((entry) => latestManifest[`${entry}.js`]),
es5EntryJS: entries.map((entry) => es5Manifest[`${entry}.js`]),
es5EntryJS: outputES5
? entries.map((entry) => es5Manifest[`${entry}.js`])
: [],
latestCustomPanelJS: latestManifest["custom-panel.js"],
es5CustomPanelJS: es5Manifest["custom-panel.js"],
es5CustomPanelJS: outputES5 ? es5Manifest["custom-panel.js"] : "",
}
);
minifiedHTML.push(
@@ -184,6 +198,17 @@ gulp.task(
)
);
gulp.task(
"gen-pages-app-prod-modern",
genPagesProdTask(
APP_PAGE_ENTRIES,
paths.root_dir,
paths.app_output_root,
paths.app_output_latest,
undefined
)
);
const CAST_PAGE_ENTRIES = {
"faq.html": ["launcher"],
"index.html": ["launcher"],
+3
View File
@@ -4,6 +4,7 @@ import gulp from "gulp";
import { load as loadYaml } from "js-yaml";
import { marked } from "marked";
import path from "path";
import { createWorkflowLockTask } from "../output-lock.mjs";
import paths from "../paths.cjs";
import "./clean.js";
import "./entry-html.js";
@@ -164,6 +165,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "development";
},
createWorkflowLockTask("develop-gallery"),
"clean-gallery",
"translations-enable-merge-backend",
gulp.parallel(
@@ -195,6 +197,7 @@ gulp.task(
async function setEnv() {
process.env.NODE_ENV = "production";
},
createWorkflowLockTask("build-gallery"),
"clean-gallery",
"translations-enable-merge-backend",
gulp.parallel(
+26 -7
View File
@@ -108,7 +108,7 @@ const runDevServer = async ({
}
};
const doneHandler = (done) => (err, stats) => {
const doneHandler = () => (err, stats) => {
if (err) {
log.error(err.stack || err);
if (err.details) {
@@ -122,18 +122,26 @@ const doneHandler = (done) => (err, stats) => {
}
log(`Build done @ ${new Date().toLocaleTimeString()}`);
if (done) {
done();
}
};
const prodBuild = (conf) =>
new Promise((resolve) => {
new Promise((resolve, reject) => {
rspack(
conf,
// Resolve promise when done. Because we pass a callback, rspack closes itself
doneHandler(resolve)
(err, stats) => {
if (err) {
reject(err);
} else if (stats.hasErrors()) {
reject(Error(stats.toString("errors-only")));
} else {
if (stats.hasWarnings()) {
console.log(stats.toString("minimal"));
}
log(`Build done @ ${new Date().toLocaleTimeString()}`);
resolve();
}
}
);
});
@@ -160,6 +168,17 @@ gulp.task("rspack-prod-app", () =>
)
);
gulp.task("rspack-prod-app-modern", () =>
prodBuild(
createAppConfig({
isProdBuild: true,
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
latestBuild: true,
})
)
);
gulp.task("rspack-dev-server-demo", () =>
runDevServer({
compiler: rspack(
+10 -3
View File
@@ -34,9 +34,9 @@ gulp.task("gen-service-worker-app-dev", async () => {
);
});
gulp.task("gen-service-worker-app-prod", () =>
const genServiceWorker = (builds) =>
Promise.all(
Object.entries(SW_MAP).map(async ([outPath, build]) => {
builds.map(async ([outPath, build]) => {
const manifest = JSON.parse(
await readFile(join(outPath, "manifest.json"), "utf-8")
);
@@ -83,5 +83,12 @@ gulp.task("gen-service-worker-app-prod", () =>
await symlink(basename(swDest), swOld);
}
})
)
);
gulp.task("gen-service-worker-app-prod", () =>
genServiceWorker(Object.entries(SW_MAP))
);
gulp.task("gen-service-worker-app-prod-modern", () =>
genServiceWorker([[paths.app_output_latest, "modern"]])
);
-2
View File
@@ -1,5 +1,3 @@
/* eslint-disable max-classes-per-file */
import { deleteAsync } from "del";
import { glob } from "glob";
import gulp from "gulp";
+552
View File
@@ -0,0 +1,552 @@
import { spawn, execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { createInterface } from "node:readline/promises";
export const LIFECYCLE_MODE_FLAGS = new Map([
["--background", "background"],
["--status", "status"],
["--stop", "stop"],
["--logs", "logs"],
]);
const AGENT_PROVIDERS = [
{
id: "opencode",
env: [
"OPENCODE",
"OPENCODE_BIN_PATH",
"OPENCODE_SERVER",
"OPENCODE_APP_INFO",
"OPENCODE_MODES",
],
processes: ["opencode"],
},
{
id: "claude-code",
env: ["CLAUDECODE"],
processes: ["claude"],
},
{
id: "cursor",
env: ["CURSOR_TRACE_ID"],
processes: [],
},
{
id: "github-copilot",
matchesEnv: (env) =>
env.TERM_PROGRAM === "vscode" && env.GIT_PAGER === "cat",
processes: [],
},
{
id: "generic",
env: ["AGENT", "AI_AGENT"],
processes: [],
},
];
const MAX_ANCESTRY_HOPS = 24;
const readProcessParent = (pid) => {
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
const commandEnd = stat.lastIndexOf(")");
const commandStart = stat.indexOf("(");
if (commandStart === -1 || commandEnd === -1) {
return undefined;
}
const parentPid = Number.parseInt(
stat.slice(commandEnd + 2).split(" ")[1] ?? "",
10
);
return Number.isFinite(parentPid)
? {
command: stat.slice(commandStart + 1, commandEnd).toLowerCase(),
parentPid,
}
: undefined;
} catch {
return undefined;
}
};
export const detectCodingAgent = (env = process.env, pid = process.pid) => {
if (env.HA_CODING_AGENT === "0") {
return undefined;
}
const envMatch = AGENT_PROVIDERS.find(
(provider) =>
provider.matchesEnv?.(env) || provider.env?.some((name) => env[name])
);
if (envMatch) {
return envMatch.id;
}
if (env.HA_CODING_AGENT === "1") {
return "unknown";
}
let currentPid = pid;
for (let hop = 0; hop < MAX_ANCESTRY_HOPS; hop++) {
const processInfo = readProcessParent(currentPid);
if (!processInfo) {
return undefined;
}
const processMatch = AGENT_PROVIDERS.find((provider) =>
provider.processes.some((name) => processInfo.command.includes(name))
);
if (processMatch) {
return processMatch.id;
}
if (processInfo.parentPid <= 1) {
return undefined;
}
currentPid = processInfo.parentPid;
}
return undefined;
};
const canPromptForConflict = () =>
Boolean(process.stdin.isTTY && process.stderr.isTTY && !detectCodingAgent());
const formatCommand = (command) =>
!("NO_COLOR" in process.env)
? `\u001b[1;36m${command}\u001b[0m`
: `\`${command}\``;
const confirmStopConflict = async (ownerDescription, stopCommand) => {
const readline = createInterface({
input: process.stdin,
output: process.stderr,
});
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30_000);
try {
process.stderr.write(
`${ownerDescription} can be stopped with ${formatCommand(stopCommand)}.\n`
);
const answer = await readline.question("Stop it and continue? [y/N] ", {
signal: controller.signal,
});
return ["y", "yes"].includes(answer.trim().toLowerCase());
} catch (err) {
if (err?.name !== "AbortError") {
throw err;
}
process.stderr.write("\n");
return false;
} finally {
clearTimeout(timeout);
readline.close();
}
};
export const sleep = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
export const waitFor = async (predicate, intervalMs, timeoutMs) => {
const deadline = Date.now() + timeoutMs;
const poll = async () => {
if (await predicate()) {
return true;
}
if (Date.now() >= deadline) {
return false;
}
await sleep(intervalMs);
return poll();
};
return poll();
};
export const isProcessAlive = (pid) => {
if (!Number.isInteger(pid) || pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch (err) {
// EPERM means the process exists but is owned by someone else.
return err.code === "EPERM";
}
};
export const processStartTime = (pid) => {
if (!isProcessAlive(pid)) {
return undefined;
}
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
} catch {
try {
return execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch {
return undefined;
}
}
};
export const isProcessRecordAlive = ({ pid, startTime }) =>
Boolean(startTime) && processStartTime(pid) === startTime;
export const readProcessRecord = (file) => {
try {
const data = JSON.parse(fs.readFileSync(file, "utf8"));
return data && Number.isInteger(data.pid) ? data : undefined;
} catch (err) {
if (err.code === "ENOENT" || err instanceof SyntaxError) {
return undefined;
}
throw err;
}
};
export const writeProcessRecord = (file, data) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
try {
fs.writeFileSync(temporary, JSON.stringify(data));
fs.renameSync(temporary, file);
} finally {
removeFileIfExists(temporary);
}
};
export const removeProcessRecord = (file) => {
removeFileIfExists(file);
};
export const acquireProcessRecord = (file, data) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
for (let attempt = 0; attempt < 2; attempt++) {
try {
const fd = fs.openSync(file, "wx");
try {
fs.writeFileSync(fd, JSON.stringify(data));
} finally {
fs.closeSync(fd);
}
return { acquired: true };
} catch (err) {
if (err.code !== "EEXIST") {
throw err;
}
const existing = readProcessRecord(file);
if (existing && isProcessRecordAlive(existing)) {
return { acquired: false, existing };
}
if (!existing && isRecentFile(file)) {
return { acquired: false };
}
const removed = withExclusiveFileLockSync(`${file}.cleanup`, () => {
const current = readProcessRecord(file);
if (
current &&
(current.token !== existing?.token || isProcessRecordAlive(current))
) {
return false;
}
removeProcessRecord(file);
return true;
});
if (!removed.acquired || !removed.value) {
return { acquired: false, existing: readProcessRecord(file) };
}
}
}
return { acquired: false, existing: readProcessRecord(file) };
};
export const releaseProcessRecord = (file, token, onRelease) => {
if (!token) {
return;
}
withExclusiveFileLockSync(`${file}.cleanup`, () => {
const existing = readProcessRecord(file);
if (!existing || existing.token === token) {
onRelease?.();
if (existing) {
removeProcessRecord(file);
}
}
});
};
const removeFileIfExists = (file) => {
try {
fs.rmSync(file);
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
};
const isRecentFile = (file) => {
try {
return Date.now() - fs.statSync(file).mtimeMs < 5000;
} catch (err) {
if (err.code === "ENOENT") {
return false;
}
throw err;
}
};
export const withExclusiveFileLockSync = (file, operation) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
for (let attempt = 0; attempt < 2; attempt++) {
let fd;
try {
fd = fs.openSync(file, "wx");
} catch (err) {
if (err.code !== "EEXIST") {
throw err;
}
const owner = readProcessRecord(file);
if (owner && isProcessRecordAlive(owner)) {
return { acquired: false };
}
if (!owner && isRecentFile(file)) {
return { acquired: false };
}
removeFileIfExists(file);
continue;
}
try {
fs.writeFileSync(
fd,
JSON.stringify({
pid: process.pid,
startTime: processStartTime(process.pid),
})
);
return { acquired: true, value: operation() };
} finally {
try {
fs.closeSync(fd);
} finally {
removeFileIfExists(file);
}
}
}
return { acquired: false };
};
export const spawnForeground = ({
cmd,
args,
cwd,
env,
processGroup = false,
onSpawn,
}) =>
new Promise((resolve, reject) => {
const child = spawn(cmd, args, {
cwd,
detached: processGroup,
env,
stdio: "inherit",
});
let settled = false;
const forwardSigint = () =>
signalProcess(child.pid, "SIGINT", processGroup);
const forwardSigterm = () =>
signalProcess(child.pid, "SIGTERM", processGroup);
const forwardSighup = () =>
signalProcess(child.pid, "SIGHUP", processGroup);
const removeSignalHandlers = () => {
process.off("SIGINT", forwardSigint);
process.off("SIGTERM", forwardSigterm);
process.off("SIGHUP", forwardSighup);
};
if (processGroup) {
process.on("SIGINT", forwardSigint);
process.on("SIGTERM", forwardSigterm);
process.on("SIGHUP", forwardSighup);
}
child.once("spawn", () => {
try {
onSpawn?.(child);
} catch (err) {
settled = true;
signalProcess(child.pid, "SIGTERM", processGroup);
removeSignalHandlers();
reject(err);
}
});
child.once("error", (err) => {
if (!settled) {
settled = true;
removeSignalHandlers();
process.stderr.write(`Failed to start ${cmd}: ${err.message}\n`);
resolve(1);
}
});
child.once("exit", (code) => {
if (!settled) {
settled = true;
removeSignalHandlers();
resolve(code ?? 1);
}
});
});
export const spawnDetachedToLog = ({ cmd, args, cwd, env, logFile }) =>
new Promise((resolve, reject) => {
fs.mkdirSync(path.dirname(logFile), { recursive: true });
const fd = fs.openSync(logFile, "w");
let child;
try {
child = spawn(cmd, args, {
cwd,
detached: true,
env,
stdio: ["ignore", fd, fd],
});
} finally {
fs.closeSync(fd);
}
child.once("spawn", () => {
child.unref();
resolve(child);
});
child.once("error", reject);
});
const signalProcess = (pid, signal, processGroup) => {
if (processGroup) {
try {
process.kill(-pid, signal);
return;
} catch {
// Fall back to the process itself.
}
}
try {
process.kill(pid, signal);
} catch {
// Already gone.
}
};
export const terminateProcess = async ({
pid,
isStopped,
processGroup = true,
graceMs = 10_000,
}) => {
signalProcess(pid, "SIGTERM", processGroup);
if (await waitFor(isStopped, 300, graceMs)) {
return true;
}
signalProcess(pid, "SIGKILL", processGroup);
await sleep(300);
return await isStopped();
};
const sameProcessRecord = (current, expected) =>
Boolean(expected?.token) && current?.token === expected.token;
const stopProcessRecord = async (file, owner) => {
let current = readProcessRecord(file);
if (!current) {
return true;
}
if (!sameProcessRecord(current, owner)) {
return false;
}
if (!isProcessRecordAlive(current)) {
releaseProcessRecord(file, current.token);
return true;
}
const stopped = await terminateProcess({
pid: current.pid,
processGroup: current.processGroup ?? false,
isStopped: () => {
const latest = readProcessRecord(file);
return (
!sameProcessRecord(latest, owner) ||
!latest ||
!isProcessRecordAlive(latest)
);
},
});
current = readProcessRecord(file);
if (current && !sameProcessRecord(current, owner)) {
return false;
}
if (!stopped && current) {
return false;
}
releaseProcessRecord(file, owner.token);
return true;
};
export const offerToStopProcessRecord = async ({
file,
owner,
ownerDescription,
stopCommand,
}) => {
if (
!owner ||
!stopCommand ||
!canPromptForConflict() ||
!(await confirmStopConflict(ownerDescription, stopCommand))
) {
return false;
}
return stopProcessRecord(file, owner);
};
export const terminateDetachedProcess = (child) =>
terminateProcess({
pid: child.pid,
processGroup: true,
isStopped: () => !isProcessAlive(child.pid),
});
export const outputLog = (logFile, follow, missingMessage) => {
if (!fs.existsSync(logFile)) {
process.stdout.write(missingMessage);
return Promise.resolve(0);
}
if (!follow) {
process.stdout.write(fs.readFileSync(logFile, "utf8"));
return Promise.resolve(0);
}
return new Promise((resolve) => {
const tail = spawn("tail", ["-f", logFile], { stdio: "inherit" });
let settled = false;
tail.once("error", () => {
if (!settled) {
settled = true;
process.stdout.write(fs.readFileSync(logFile, "utf8"));
resolve(0);
}
});
tail.once("exit", (code) => {
if (!settled) {
settled = true;
resolve(code ?? 1);
}
});
});
};
export const runCli = (main) => {
main().then(
(code) => {
process.exitCode = code;
},
(err) => {
process.stderr.write(`${err?.stack || err}\n`);
process.exitCode = 1;
}
);
};
+127
View File
@@ -0,0 +1,127 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
acquireProcessRecord,
processStartTime,
readProcessRecord,
releaseProcessRecord,
} from "./managed-process.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
".."
);
export const buildCacheDir =
process.env.HA_BUILD_CACHE_DIR ??
path.join(repoRoot, "node_modules", ".cache");
const WORKFLOW_LOCK_TOKEN_ENV = "HA_WORKFLOW_LOCK_TOKEN";
const signalCleanups = new Set();
const cleanupSignals = ["SIGINT", "SIGTERM", "SIGHUP"];
const handleSignal = (signal) => {
for (const cleanup of signalCleanups) {
cleanup();
}
for (const cleanupSignal of cleanupSignals) {
process.off(cleanupSignal, handleSignal);
}
process.kill(process.pid, signal);
};
const registerSignalCleanup = (cleanup) => {
if (signalCleanups.size === 0) {
for (const signal of cleanupSignals) {
process.on(signal, handleSignal);
}
}
signalCleanups.add(cleanup);
};
const unregisterSignalCleanup = (cleanup) => {
signalCleanups.delete(cleanup);
if (signalCleanups.size === 0) {
for (const signal of cleanupSignals) {
process.off(signal, handleSignal);
}
}
};
export const workflowLockFile = path.join(buildCacheDir, "ha-workflow.lock");
export const workflowLockEnv = (token) => ({
...process.env,
[WORKFLOW_LOCK_TOKEN_ENV]: token,
});
export const describeOutputOwner = (owner) => {
if (owner?.kind === "build") {
return `frontend ${owner.modern ? "modern " : ""}build`;
}
if (owner?.kind === "dev") {
return `dev server (${owner.suite ?? "app"})`;
}
return owner?.target ? `Gulp task ${owner.target}` : "another process";
};
const createLockTask = ({ file, inheritedTokenEnv, kind, label, target }) => {
let exitToken;
const cleanup = () => {
if (!exitToken) {
return;
}
releaseProcessRecord(file, exitToken);
exitToken = undefined;
process.off("exit", cleanup);
unregisterSignalCleanup(cleanup);
};
const acquire = async () => {
const inheritedToken = process.env[inheritedTokenEnv];
if (inheritedToken) {
if (readProcessRecord(file)?.token !== inheritedToken) {
throw Error(
`${label} lock ownership was lost before ${target} started.`
);
}
exitToken = inheritedToken;
process.once("exit", cleanup);
registerSignalCleanup(cleanup);
return;
}
const token = `${process.pid}-${Date.now()}-${Math.random()}`;
const record = {
pid: process.pid,
startTime: processStartTime(process.pid),
processGroup: false,
kind,
target,
token,
};
const result = acquireProcessRecord(file, record);
if (!result.acquired) {
const pid = result.existing?.pid;
throw Error(
`Cannot run ${target}: ${describeOutputOwner(result.existing)} ` +
`already owns ${label}${pid ? ` (pid ${pid})` : ""}.`
);
}
exitToken = token;
process.once("exit", cleanup);
registerSignalCleanup(cleanup);
};
acquire.displayName = `lock-${label}:${target}`;
return acquire;
};
export const createWorkflowLockTask = (target) =>
createLockTask({
file: workflowLockFile,
inheritedTokenEnv: WORKFLOW_LOCK_TOKEN_ENV,
kind: "output",
label: "build and development workflow",
target,
});
+7 -7
View File
@@ -7,7 +7,7 @@
"name": "home-assistant-frontend",
"version": "1.0.0",
"scripts": {
"build": "script/build_frontend",
"build": "node build-scripts/build-manager.mjs",
"lint:eslint": "eslint \"**/src/**/*.{js,ts,html}\" --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --ignore-pattern=.gitignore --max-warnings=0",
"format:eslint": "eslint \"**/src/**/*.{js,ts,html}\" --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --ignore-pattern=.gitignore --fix",
"lint:prettier": "prettier . --cache --check",
@@ -49,7 +49,7 @@
"@codemirror/lint": "6.9.7",
"@codemirror/search": "6.7.1",
"@codemirror/state": "6.7.1",
"@codemirror/view": "6.43.6",
"@codemirror/view": "6.43.7",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "7.5.2",
@@ -152,7 +152,7 @@
"@octokit/rest": "22.0.1",
"@playwright/test": "1.62.0",
"@rsdoctor/rspack-plugin": "1.6.1",
"@rspack/core": "2.1.5",
"@rspack/core": "2.1.6",
"@rspack/dev-server": "2.1.0",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "6.0.26",
@@ -186,14 +186,14 @@
"fs-extra": "11.4.0",
"generate-license-file": "4.2.1",
"glob": "13.0.6",
"globals": "17.7.0",
"globals": "17.8.0",
"gulp": "5.0.1",
"gulp-brotli": "3.0.0",
"gulp-json-transform": "0.5.0",
"gulp-rename": "2.1.0",
"html-minifier-terser": "7.2.0",
"husky": "9.1.7",
"jsdom": "29.1.1",
"jsdom": "30.0.0",
"jszip": "3.10.1",
"license-checker-rseidelsohn": "5.0.1",
"lint-staged": "17.2.0",
@@ -224,12 +224,12 @@
"clean-css": "5.3.3",
"@lit/reactive-element": "2.1.2",
"@fullcalendar/daygrid": "6.1.21",
"globals": "17.7.0",
"globals": "17.8.0",
"tslib": "2.8.1",
"@material/mwc-list@^0.27.0": "patch:@material/mwc-list@npm%3A0.27.0#~/.yarn/patches/@material-mwc-list-npm-0.27.0-5344fc9de4.patch"
},
"packageManager": "yarn@4.17.1",
"volta": {
"node": "24.18.0"
"node": "24.18.1"
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20260729.3"
version = "20260729.0"
license = "Apache-2.0"
license-files = ["LICENSE*"]
description = "The Home Assistant frontend"
+37 -3
View File
@@ -61,10 +61,44 @@ fi
echo Core is used from ${coreUrl}
# build the frontend so it connects to the passed core
HASS_URL="$coreUrl" ./script/develop &
HASS_URL="$coreUrl" ./node_modules/.bin/gulp develop-app &
develop_pid=$!
# serve the frontend
./node_modules/.bin/serve -p $frontendPort --single --no-port-switching --config ../script/serve-config.json ./hass_frontend &
serve_pid=$!
# keep the script running while serving
wait
stop_children() {
trap - EXIT INT TERM HUP
kill "$develop_pid" "$serve_pid" 2>/dev/null || true
wait "$develop_pid" 2>/dev/null || true
wait "$serve_pid" 2>/dev/null || true
}
trap stop_children EXIT
trap 'stop_children; exit 130' INT
trap 'stop_children; exit 143' TERM
trap 'stop_children; exit 129' HUP
while kill -0 "$develop_pid" 2>/dev/null && kill -0 "$serve_pid" 2>/dev/null; do
sleep 1
done
develop_status=
serve_status=
if ! kill -0 "$develop_pid" 2>/dev/null; then
if wait "$develop_pid"; then develop_status=0; else develop_status=$?; fi
fi
if ! kill -0 "$serve_pid" 2>/dev/null; then
if wait "$serve_pid"; then serve_status=0; else serve_status=$?; fi
fi
if [ -n "$develop_status" ] && [ "$develop_status" -ne 0 ]; then
status=$develop_status
elif [ -n "$serve_status" ]; then
status=$serve_status
else
status=$develop_status
fi
exit "$status"
+6 -1
View File
@@ -118,10 +118,15 @@ export class HaProgressButton extends LitElement {
width: 100%;
}
/* Fade the content out rather than hiding it, so the button keeps its
accessible name while the result icon covers it. */
ha-button.result::part(start),
ha-button.result::part(end),
ha-button.result::part(label),
ha-button.result::part(caret),
ha-button.result::part(caret) {
opacity: 0;
}
ha-button.result::part(spinner) {
visibility: hidden;
}
+39 -33
View File
@@ -12,6 +12,7 @@ import {
} from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { join } from "lit/directives/join";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { STRINGS_SEPARATOR_DOT } from "../../common/const";
@@ -483,13 +484,7 @@ export class HaDataTable extends LitElement {
: ""
}
${Object.entries(columns).map(([key, column]) => {
if (
column.hidden ||
(this.columnOrder && this.columnOrder.includes(key)
? (this.hiddenColumns?.includes(key) ??
column.defaultHidden)
: column.defaultHidden)
) {
if (!this._isColumnVisible(key, column)) {
return nothing;
}
const sorted = key === this.sortColumn;
@@ -657,10 +652,7 @@ export class HaDataTable extends LitElement {
${Object.entries(columns).map(([key, column]) => {
if (
(narrow && !column.main && !column.showNarrow) ||
column.hidden ||
(this.columnOrder && this.columnOrder.includes(key)
? (this.hiddenColumns?.includes(key) ?? column.defaultHidden)
: column.defaultHidden)
!this._isColumnVisible(key, column)
) {
return nothing;
}
@@ -692,28 +684,19 @@ export class HaDataTable extends LitElement {
: narrow && column.main
? html`<div class="primary">${row[key]}</div>
<div class="secondary">
${Object.entries(columns)
.filter(
([key2, column2]) =>
!column2.hidden &&
!column2.main &&
!column2.showNarrow &&
!(this.columnOrder &&
this.columnOrder.includes(key2)
? (this.hiddenColumns?.includes(key2) ??
column2.defaultHidden)
: column2.defaultHidden)
)
.map(
([key2, column2], i) =>
html`${
i !== 0 ? STRINGS_SEPARATOR_DOT : nothing
}${
column2.template
? column2.template(row)
: row[key2]
}`
)}
${join(
Object.entries(columns)
.filter(([key2, column2]) =>
this._isSecondaryColumnVisible(key2, column2)
)
.map(([key2, column2]) =>
column2.template
? column2.template(row)
: row[key2]
)
.filter(this._hasCellValue),
STRINGS_SEPARATOR_DOT
)}
</div>
${
column.extraTemplate
@@ -733,6 +716,29 @@ export class HaDataTable extends LitElement {
`;
};
private _isColumnVisible(key: string, column: DataTableColumnData): boolean {
if (column.hidden) {
return false;
}
if (!this.columnOrder?.includes(key)) {
return !column.defaultHidden;
}
return !(this.hiddenColumns?.includes(key) ?? column.defaultHidden);
}
private _isSecondaryColumnVisible(
key: string,
column: DataTableColumnData
): boolean {
if (column.main || column.showNarrow) {
return false;
}
return this._isColumnVisible(key, column);
}
private _hasCellValue = (value: unknown): boolean =>
value !== undefined && value !== null && value !== "" && value !== nothing;
private async _sortFilterData() {
const startTime = new Date().getTime();
const timeBetweenUpdate = startTime - this._lastUpdate;
@@ -45,6 +45,7 @@ import {
} from "../../data/media_source";
import { isTTSMediaSource } from "../../data/tts";
import { showAlertDialog } from "../../dialogs/generic/show-dialog-box";
import { panelIsReady } from "../../layouts/panel-ready";
import { haStyle, haStyleScrollbar } from "../../resources/styles";
import { loadVirtualizer } from "../../resources/virtualizer";
import type { HomeAssistant } from "../../types";
@@ -161,6 +162,8 @@ export class HaMediaPlayerBrowse extends LitElement {
private _resizeObserver?: ResizeObserver;
private _initialReady = false;
public connectedCallback(): void {
super.connectedCallback();
this.updateComplete.then(() => this._attachResizeObserver());
@@ -274,6 +277,7 @@ export class HaMediaPlayerBrowse extends LitElement {
ids: navigateIds,
current: this._currentItem,
});
this._signalInitialReady();
} else {
if (!currentProm) {
currentProm = this._fetchData(
@@ -289,6 +293,7 @@ export class HaMediaPlayerBrowse extends LitElement {
ids: navigateIds,
current: item,
});
this._signalInitialReady();
},
(err) => {
// When we change entity ID, we will first try to see if the new entity is
@@ -322,8 +327,10 @@ export class HaMediaPlayerBrowse extends LitElement {
),
code: "entity_not_found",
});
this._signalInitialReady();
} else {
this._setError(err);
this._signalInitialReady();
}
}
);
@@ -1145,6 +1152,21 @@ export class HaMediaPlayerBrowse extends LitElement {
fireEvent(this, "close-dialog");
}
private _signalInitialReady(): void {
if (this._initialReady) {
return;
}
this._initialReady = true;
const root = this.getRootNode();
panelIsReady(
root instanceof ShadowRoot &&
root.host instanceof HTMLElement &&
root.host.tagName.startsWith("HA-PANEL-")
? root.host
: this
);
}
private _setError(error: any) {
if (!this.dialog) {
this._error = error;
@@ -1209,8 +1231,8 @@ export class HaMediaPlayerBrowse extends LitElement {
}
private _animateHeaderHeight() {
let start;
const animate = (time) => {
let start: number | undefined;
const animate = (time: number) => {
if (start === undefined) {
start = time;
}
+1
View File
@@ -23,6 +23,7 @@ export interface LovelaceViewElement extends HTMLElement {
badges?: HuiBadge[];
sections?: HuiSection[];
isStrategy: boolean;
initialRenderComplete?: Promise<void>;
setConfig(config: LovelaceViewConfig): void;
}
+15
View File
@@ -314,6 +314,11 @@ export interface ZWaveJSSetConfigParamResult {
error?: string;
}
export interface ZwaveJSNodeConfigParameterUpdate {
id: string;
value: number | null;
}
export interface ZWaveJSDataCollectionStatus {
enabled: boolean;
opted_in: boolean;
@@ -732,6 +737,16 @@ export const fetchZwaveNodeConfigParameters = (
device_id,
});
export const subscribeZwaveNodeConfigParameterUpdates = (
hass: HomeAssistant,
device_id: string,
callback: (update: ZwaveJSNodeConfigParameterUpdate) => void
): Promise<UnsubscribeFunc> =>
hass.connection.subscribeMessage(callback, {
type: "zwave_js/subscribe_config_parameter_updates",
device_id,
});
export const setZwaveNodeConfigParameter = (
hass: HomeAssistant,
device_id: string,
+27 -2
View File
@@ -1,5 +1,5 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import deepClone from "deep-clone-simple";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
@@ -12,11 +12,13 @@ import { haStyleDialog } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import type { HassDialog, ShowDialogParams } from "../make-dialog-manager";
import type { FormDialogData, FormDialogParams } from "./show-form-dialog";
import type { HaForm } from "../../components/ha-form/ha-form";
interface StackEntry {
params: FormDialogParams;
data: FormDialogData;
nestedField?: string;
error?: Record<string, string>;
}
@customElement("dialog-form")
@@ -36,10 +38,15 @@ export class DialogForm
@state() private _stack: StackEntry[] = [];
@state() private _error?: Record<string, string>;
@query("ha-form") private _form?: HaForm;
public async showDialog(params: FormDialogParams): Promise<void> {
this._params = params;
this._data = params.data || {};
this._open = true;
this._error = undefined;
this._initDirtyTracking({ type: "deep" }, this._data);
}
@@ -59,11 +66,17 @@ export class DialogForm
const origin = ev.composedPath()[0] as HTMLElement & { name?: string };
this._stack = [
...this._stack,
{ params: this._params!, data: this._data, nestedField: origin?.name },
{
params: this._params!,
data: this._data,
nestedField: origin?.name,
error: this._error,
},
];
const nested = ev.detail.dialogParams as FormDialogParams;
this._params = nested;
this._data = nested?.data || {};
this._error = undefined;
this._initDirtyTracking({ type: "deep" }, this._data);
};
@@ -75,6 +88,7 @@ export class DialogForm
this._stack = this._stack.slice(0, -1);
this._params = prev.params;
this._data = prev.data;
this._error = prev.error;
this._initDirtyTracking({ type: "deep" }, this._data);
return prev.nestedField;
}
@@ -88,10 +102,18 @@ export class DialogForm
this._params = undefined;
this._data = {};
this._open = false;
this._error = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
private _submit(): void {
if (this._form && !this._form.reportValidity()) {
this._error = {
base: this.hass!.localize("ui.components.form.validation_failed"),
};
return;
}
this._closeState = "submitted";
const submit = this._params?.submit;
const data = this._data;
@@ -119,6 +141,7 @@ export class DialogForm
: data;
this._data = deepClone({ ...this._data, [nestedField]: newValue });
this._error = undefined;
this._updateDirtyState(this._data);
}
@@ -136,6 +159,7 @@ export class DialogForm
private _valueChanged(ev: CustomEvent): void {
this._data = ev.detail.value;
this._error = undefined;
this._updateDirtyState(this._data);
}
@@ -158,6 +182,7 @@ export class DialogForm
.computeHelper=${this._params.computeHelper}
.data=${this._data}
.schema=${this._params.schema}
.error=${this._error}
@value-changed=${this._valueChanged}
@show-dialog=${this._handleNestedShowDialog}
>
+12 -1
View File
@@ -37,15 +37,26 @@ declare global {
}
const clearUrlParams = () => {
const searchParams = new URLSearchParams(location.search);
let changed = false;
// Clear auth data from url if we have been able to establish a connection
if (location.search.includes("auth_callback=1")) {
const searchParams = new URLSearchParams(location.search);
// https://github.com/home-assistant/home-assistant-js-websocket/blob/master/lib/auth.ts
// Remove all data from QueryCallbackData type
searchParams.delete("auth_callback");
searchParams.delete("code");
searchParams.delete("state");
searchParams.delete("storeToken");
changed = true;
}
// Remove the cache-busting param added by the stale-index recovery guard in
// index.html once we have booted successfully, so it doesn't linger in the
// URL (and stops acting as the guard's one-shot loop marker).
if (searchParams.has("ha_cache_bust")) {
searchParams.delete("ha_cache_bust");
changed = true;
}
if (changed) {
const search = searchParams.toString();
history.replaceState(
null,
+130
View File
@@ -0,0 +1,130 @@
<script>
/*
* Boot-time recovery from a stale index.html.
*
* index.html pins the content-hashed entry bundles (core.<hash>.js /
* app.<hash>.js). After a frontend release those files are deleted from
* disk, so a cached (stale) index.html imports URLs that now 404 and the
* app never boots - the launch screen stays up forever. No bundled JS can
* recover this, because the bundle itself failed to load, so this guard has
* to live inline in the HTML document.
*
* On a failed entry load we navigate once to the same URL with a
* cache-busting query param (and, on https, after dropping the service
* worker + its caches) so the browser fetches a fresh index.html that points
* at the current hashes. The param doubles as a one-shot loop guard: if the
* freshly fetched index still fails we stop and show a message instead of
* reloading forever. core.ts strips the param again after a successful boot.
*/
(function () {
var BUST_PARAM = "ha_cache_bust";
// Only production entry bundles carry a content hash. Requiring the hash
// keeps the guard inert in development (unhashed core.js / app.js) and
// scoped to the entry chunks whose 404 is fatal to boot - not translations
// or lazily loaded panels, which fail non-fatally and are handled elsewhere.
// Injected from stale-build-patterns.json (the single source shared with
// the bundled util/recover-stale-build.ts) so the two never drift.
var HASHED_ENTRY = new RegExp(<%= JSON.stringify(staleBuildPatterns.hashedEntry) %>, "i");
var MODULE_ERROR = new RegExp(<%= JSON.stringify(staleBuildPatterns.moduleError) %>, "i");
function booted() {
// The launch screen is only removed once the app has taken over the
// page. If it is gone, any later chunk failure is post-boot (a lazy
// panel/dialog) and is not the stale-index boot failure this guard
// targets, so we leave it alone.
return !document.getElementById("ha-launch-screen");
}
function showFatal() {
var box = document.getElementById("ha-launch-screen-info-box");
if (box) {
box.textContent =
"Could not load Home Assistant. Please refresh the page, and clear your browser cache if the problem persists.";
}
}
function recover() {
if (location.search.indexOf(BUST_PARAM + "=") !== -1) {
// We already reloaded once with a fresh index and it still failed;
// stop to avoid a reload loop.
showFatal();
return;
}
var target =
location.pathname +
location.search +
(location.search ? "&" : "?") +
BUST_PARAM +
"=" +
Date.now() +
location.hash;
// On https the service worker "/" route ignores the query string
// (ignoreSearch), so a bust param alone would still be answered with the
// stale cached index. Drop the worker and its caches first so the reload
// is served fresh from the network.
if ("serviceWorker" in navigator && navigator.serviceWorker.controller) {
var go = function () {
location.replace(target);
};
Promise.all([
navigator.serviceWorker
.getRegistrations()
.then(function (regs) {
return Promise.all(
regs.map(function (r) {
return r.unregister();
})
);
})
.catch(function () {}),
self.caches
? caches
.keys()
.then(function (keys) {
return Promise.all(
keys.map(function (k) {
return caches.delete(k);
})
);
})
.catch(function () {})
: null,
]).then(go, go);
} else {
location.replace(target);
}
}
function maybeRecover(url, message) {
if (booted()) {
return;
}
if (
(url && HASHED_ENTRY.test(url)) ||
(message && (HASHED_ENTRY.test(message) || MODULE_ERROR.test(message)))
) {
recover();
}
}
// Resource-load errors (<script>, modulepreload <link>) do not bubble, so
// they are only observable in the capture phase at the window.
window.addEventListener(
"error",
function (ev) {
var el = ev.target;
if (el && (el.tagName === "SCRIPT" || el.tagName === "LINK")) {
maybeRecover(el.href || el.src, null);
}
},
true
);
// A failed dynamic import() rejects; the inline entry imports do not catch
// it, so the rejection surfaces here.
window.addEventListener("unhandledrejection", function (ev) {
var reason = ev && ev.reason;
maybeRecover(null, reason && (reason.message || String(reason)));
});
})();
</script>
+1
View File
@@ -2,6 +2,7 @@
<html>
<head>
<title>Home Assistant</title>
<% if (useCacheRecovery) { %><%= renderTemplate("_bootstrap_recovery.html.template") %><% } %>
<%= renderTemplate("_header.html.template") %>
<link rel="mask-icon" href="/static/icons/mask-icon.svg" color="#18bcf2" />
<link
+4 -1
View File
@@ -1,6 +1,7 @@
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import "../components/animation/ha-fade-in";
import "../components/ha-top-app-bar-fixed";
import "../components/ha-spinner";
import type { HomeAssistant } from "../types";
@@ -36,7 +37,9 @@ class HassLoadingScreen extends LitElement {
private _renderContent(): TemplateResult {
return html`
<div class="content">
<ha-spinner></ha-spinner>
<ha-fade-in .delay=${500}>
<ha-spinner></ha-spinner>
</ha-fade-in>
${
this.message
? html`<div id="loading-text">${this.message}</div>`
+57
View File
@@ -1,3 +1,5 @@
import { ContextProvider, createContext } from "@lit/context";
import type { ReactiveController, ReactiveControllerHost } from "lit";
import { ReactiveElement } from "lit";
import { fireEvent } from "../common/dom/fire_event";
@@ -15,6 +17,61 @@ export const panelIsReady = async (element: HTMLElement) => {
fireEvent(element, "hass-panel-ready");
};
export type RegisterChildPanelReady = (ready: Promise<void>) => void;
export const childPanelReadyContext =
createContext<RegisterChildPanelReady>("child-panel-ready");
export class ChildPanelReady implements ReactiveController {
private _promises: Promise<void>[] = [];
private _host: ReactiveControllerHost & HTMLElement;
private _resolveReady?: () => void;
private _completing = false;
public ready = new Promise<void>((resolve) => {
this._resolveReady = resolve;
});
public constructor(host: ReactiveControllerHost & HTMLElement) {
this._host = host;
host.addController(this);
new ContextProvider(host, {
context: childPanelReadyContext,
initialValue: (ready) => this._promises.push(ready),
});
}
public hostUpdated() {
if (this._completing) {
return;
}
this._completing = true;
this._host.removeController(this);
void this._complete();
}
private async _complete() {
// Children created/updated during this render register after the host's
// update commits. Wait for that before snapshotting readiness promises.
await this._host.updateComplete;
await this._waitForPromises();
this._resolveReady?.();
await panelIsReady(this._host);
}
private _waitForPromises(): Promise<void> {
const count = this._promises.length;
return Promise.allSettled(this._promises).then(() =>
this._promises.length > count ? this._waitForPromises() : undefined
);
}
}
export class PanelReady {
public ready?: Promise<void>;
+67 -28
View File
@@ -19,29 +19,66 @@ import { HassRouterPage } from "./hass-router-page";
const CACHE_URL_PATHS = ["lovelace", "home", "config"];
const PANEL_READY_TIMEOUT = 2000;
const DASHBOARD_READY_TIMEOUT = 5000;
const COMPONENTS = {
app: () => import("../panels/app/ha-panel-app"),
energy: () => import("../panels/energy/ha-panel-energy"),
calendar: () => import("../panels/calendar/ha-panel-calendar"),
config: () => import("../panels/config/ha-panel-config"),
custom: () => import("../panels/custom/ha-panel-custom"),
lovelace: () => import("../panels/lovelace/ha-panel-lovelace"),
history: () => import("../panels/history/ha-panel-history"),
iframe: () => import("../panels/iframe/ha-panel-iframe"),
logbook: () => import("../panels/logbook/ha-panel-logbook"),
map: () => import("../panels/map/ha-panel-map"),
my: () => import("../panels/my/ha-panel-my"),
profile: () => import("../panels/profile/ha-panel-profile"),
todo: () => import("../panels/todo/ha-panel-todo"),
"media-browser": () =>
import("../panels/media-browser/ha-panel-media-browser"),
light: () => import("../panels/light/ha-panel-light"),
security: () => import("../panels/security/ha-panel-security"),
climate: () => import("../panels/climate/ha-panel-climate"),
maintenance: () => import("../panels/maintenance/ha-panel-maintenance"),
home: () => import("../panels/home/ha-panel-home"),
notfound: () => import("../panels/notfound/ha-panel-notfound"),
};
app: { load: () => import("../panels/app/ha-panel-app") },
energy: {
load: () => import("../panels/energy/ha-panel-energy"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
calendar: {
load: () => import("../panels/calendar/ha-panel-calendar"),
waitForReady: true,
},
config: { load: () => import("../panels/config/ha-panel-config") },
custom: { load: () => import("../panels/custom/ha-panel-custom") },
lovelace: {
load: () => import("../panels/lovelace/ha-panel-lovelace"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
history: { load: () => import("../panels/history/ha-panel-history") },
iframe: { load: () => import("../panels/iframe/ha-panel-iframe") },
logbook: { load: () => import("../panels/logbook/ha-panel-logbook") },
map: { load: () => import("../panels/map/ha-panel-map") },
my: { load: () => import("../panels/my/ha-panel-my") },
profile: { load: () => import("../panels/profile/ha-panel-profile") },
todo: { load: () => import("../panels/todo/ha-panel-todo") },
"media-browser": {
load: () => import("../panels/media-browser/ha-panel-media-browser"),
waitForReady: true,
},
light: {
load: () => import("../panels/light/ha-panel-light"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
security: {
load: () => import("../panels/security/ha-panel-security"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
climate: {
load: () => import("../panels/climate/ha-panel-climate"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
maintenance: {
load: () => import("../panels/maintenance/ha-panel-maintenance"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
home: {
load: () => import("../panels/home/ha-panel-home"),
waitForReady: true,
readyTimeout: DASHBOARD_READY_TIMEOUT,
},
notfound: { load: () => import("../panels/notfound/ha-panel-notfound") },
} satisfies Record<
string,
Pick<RouteOptions, "load" | "waitForReady"> & { readyTimeout?: number }
>;
@customElement("partial-panel-resolver")
class PartialPanelResolver extends HassRouterPage {
@@ -126,13 +163,12 @@ class PartialPanelResolver extends HassRouterPage {
private _getRoutes(panels: Panels): RouterOptions {
const routes: RouterOptions["routes"] = {};
Object.values(panels).forEach((panel) => {
const component = COMPONENTS[panel.component_name];
const data: RouteOptions = {
tag: `ha-panel-${panel.component_name}`,
cache: CACHE_URL_PATHS.includes(panel.url_path),
...(component ?? {}),
};
if (panel.component_name in COMPONENTS) {
data.load = COMPONENTS[panel.component_name];
}
routes[panel.url_path] = data;
});
@@ -221,9 +257,12 @@ class PartialPanelResolver extends HassRouterPage {
)
) {
await this.rebuild();
await promiseTimeout(PANEL_READY_TIMEOUT, this.pageRendered).catch(
() => undefined
);
const component =
COMPONENTS[this.hass.panels[this._currentPage].component_name];
await promiseTimeout(
component?.readyTimeout ?? PANEL_READY_TIMEOUT,
this.pageRendered
).catch(() => undefined);
// Only fire frontend/loaded when this call actually removed the launch
// screen, so later panel updates do not fire it again. Native apps remove
// it instantly because their own splash screen is still visible.
+64 -48
View File
@@ -1,14 +1,23 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../common/dom/fire_event";
import "../../components/ha-dialog-footer";
import "../../components/ha-svg-icon";
import "../../components/ha-switch";
import {
fireEvent,
type HASSDomCurrentTargetEvent,
} from "../../common/dom/fire_event";
import "../../components/ha-button";
import "../../components/ha-dialog";
import "../../components/ha-dialog-footer";
import "../../components/radio/ha-radio-group";
import type { HaRadioGroup } from "../../components/radio/ha-radio-group";
import "../../components/radio/ha-radio-option";
import { RecurrenceRange } from "../../data/calendar";
import type { HomeAssistant } from "../../types";
import type { ConfirmEventDialogBoxParams } from "./show-confirm-event-dialog-box";
import "../../components/ha-button";
// `RecurrenceRange.THISEVENT` is "", which the radio group treats as unselected
// on its value-attribute and form-reset paths, so keep the options on their own
// literals and map them when confirming.
type RecurrenceScope = "this" | "future";
@customElement("confirm-event-dialog-box")
class ConfirmEventDialogBox extends LitElement {
@@ -18,11 +27,14 @@ class ConfirmEventDialogBox extends LitElement {
@state() private _open = false;
@state()
private _closeState?: "canceled" | "confirmed" | "confirmedFuture";
@state() private _closeState?: "canceled" | "confirmed";
@state() private _scope: RecurrenceScope = "this";
public async showDialog(params: ConfirmEventDialogBoxParams): Promise<void> {
this._params = params;
this._scope = "this";
this._closeState = undefined;
this._open = true;
}
@@ -39,20 +51,27 @@ class ConfirmEventDialogBox extends LitElement {
return nothing;
}
const { destructive, recurring } = this._params;
return html`
<ha-dialog
.open=${this._open}
header-title=${this._params.title}
width="small"
type="alert"
aria-describedby=${recurring ? nothing : "description"}
@closed=${this._dialogClosed}
>
<div>
<p>${this._params.text}</p>
</div>
${
recurring
? this._renderRecurrenceRange()
: html`<p id="description">${this._params.text}</p>`
}
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
@click=${this._dismiss}
?autofocus=${!recurring && destructive}
slot="secondaryAction"
>
${this.hass.localize("ui.common.cancel")}
@@ -60,29 +79,41 @@ class ConfirmEventDialogBox extends LitElement {
<ha-button
slot="primaryAction"
@click=${this._confirm}
autofocus
variant="danger"
?autofocus=${!recurring && !destructive}
variant=${destructive ? "danger" : "brand"}
>
${this._params.confirmText}
</ha-button>
${
this._params.confirmFutureText
? html`
<ha-button
@click=${this._confirmFuture}
slot="primaryAction"
variant="danger"
>
${this._params.confirmFutureText}
</ha-button>
`
: ""
}
</ha-dialog-footer>
</ha-dialog>
`;
}
private _renderRecurrenceRange() {
const thisEvent = this.hass.localize(
"ui.components.calendar.event.recurrence_range.this_event"
);
const thisAndFuture = this.hass.localize(
"ui.components.calendar.event.recurrence_range.this_and_future"
);
return html`
<ha-radio-group
name="recurrence_range"
.label=${this._params!.text ?? this._params!.title}
.value=${this._scope}
@change=${this._scopeChanged}
>
<ha-radio-option value="this" autofocus>${thisEvent}</ha-radio-option>
<ha-radio-option value="future">${thisAndFuture}</ha-radio-option>
</ha-radio-group>
`;
}
private _scopeChanged(ev: HASSDomCurrentTargetEvent<HaRadioGroup>): void {
this._scope = ev.currentTarget.value as RecurrenceScope;
}
private _dismiss(): void {
this._closeState = "canceled";
this.closeDialog();
@@ -90,17 +121,11 @@ class ConfirmEventDialogBox extends LitElement {
private _confirm(): void {
this._closeState = "confirmed";
if (this._params!.confirm) {
this._params!.confirm(RecurrenceRange.THISEVENT);
}
this.closeDialog();
}
private _confirmFuture(): void {
this._closeState = "confirmedFuture";
if (this._params!.confirm) {
this._params!.confirm(RecurrenceRange.THISANDFUTURE);
}
this._params!.confirm?.(
this._scope === "future"
? RecurrenceRange.THISANDFUTURE
: RecurrenceRange.THISEVENT
);
this.closeDialog();
}
@@ -108,10 +133,7 @@ class ConfirmEventDialogBox extends LitElement {
if (!this._params) {
return;
}
if (
this._closeState !== "confirmed" &&
this._closeState !== "confirmedFuture"
) {
if (this._closeState !== "confirmed") {
this._params.cancel?.();
}
this._params = undefined;
@@ -125,18 +147,12 @@ class ConfirmEventDialogBox extends LitElement {
pointer-events: initial !important;
cursor: initial !important;
}
a {
color: var(--primary-color);
}
p {
margin: 0;
color: var(--primary-text-color);
}
.no-bottom-padding {
padding-bottom: 0;
}
.secondary {
color: var(--secondary-text-color);
ha-radio-group::part(form-control-label) {
font-weight: var(--ha-font-weight-medium);
}
ha-dialog {
/* Place above other dialogs */
@@ -224,18 +224,9 @@ class DialogCalendarEventDetail extends LitElement {
: this.hass.localize(
"ui.components.calendar.event.confirm_delete.prompt"
),
confirmText: entry.recurrence_id
? this.hass.localize(
"ui.components.calendar.event.confirm_delete.delete_this"
)
: this.hass.localize(
"ui.components.calendar.event.confirm_delete.delete"
),
confirmFutureText: entry.recurrence_id
? this.hass.localize(
"ui.components.calendar.event.confirm_delete.delete_future"
)
: undefined,
confirmText: this.hass.localize("ui.common.delete"),
recurring: !!entry.recurrence_id,
destructive: true,
});
if (range === undefined) {
// Cancel
@@ -569,12 +569,8 @@ class DialogCalendarEventEditor extends DirtyStateProviderMixin<CalendarEventFor
text: this.hass.localize(
"ui.components.calendar.event.confirm_update.recurring_prompt"
),
confirmText: this.hass.localize(
"ui.components.calendar.event.confirm_update.update_this"
),
confirmFutureText: this.hass.localize(
"ui.components.calendar.event.confirm_update.update_future"
),
confirmText: this.hass.localize("ui.common.update"),
recurring: true,
});
}
if (range === undefined) {
@@ -625,18 +621,9 @@ class DialogCalendarEventEditor extends DirtyStateProviderMixin<CalendarEventFor
: this.hass.localize(
"ui.components.calendar.event.confirm_delete.prompt"
),
confirmText: entry.recurrence_id
? this.hass.localize(
"ui.components.calendar.event.confirm_delete.delete_this"
)
: this.hass.localize(
"ui.components.calendar.event.confirm_delete.delete"
),
confirmFutureText: entry.recurrence_id
? this.hass.localize(
"ui.components.calendar.event.confirm_delete.delete_future"
)
: undefined,
confirmText: this.hass.localize("ui.common.delete"),
recurring: !!entry.recurrence_id,
destructive: true,
});
if (range === undefined) {
// Cancel
+7
View File
@@ -35,6 +35,7 @@ import type { EntityRegistryEntry } from "../../data/entity/entity_registry";
import { subscribeEntityRegistry } from "../../data/entity/entity_registry";
import { fetchIntegrationManifest } from "../../data/integration";
import { showConfigFlowDialog } from "../../dialogs/config-flow/show-dialog-config-flow";
import { panelIsReady } from "../../layouts/panel-ready";
import { SubscribeMixin } from "../../mixins/subscribe-mixin";
import { haStyle } from "../../resources/styles";
import type { CalendarViewChanged, HomeAssistant } from "../../types";
@@ -77,6 +78,8 @@ class PanelCalendar extends SubscribeMixin(LitElement) {
private _mql?: MediaQueryList;
private _initialReady = false;
public connectedCallback() {
super.connectedCallback();
this._mql = window.matchMedia(
@@ -103,6 +106,10 @@ class PanelCalendar extends SubscribeMixin(LitElement) {
this._entityRegistry = entities;
// Refresh calendars when entity registry updates (includes color changes)
this._calendars = getCalendars(this.hass, this, this._entityRegistry);
if (!this._initialReady) {
this._initialReady = true;
panelIsReady(this);
}
// Resubscribe events if view dates are available (handles both initial load and color updates)
if (this._start && this._end) {
this._unsubscribeAll().then(() => {
@@ -1,14 +1,16 @@
import type { TemplateResult } from "lit";
import { fireEvent } from "../../common/dom/fire_event";
import type { RecurrenceRange } from "../../data/calendar";
export interface ConfirmEventDialogBoxParams {
title: string;
// Labels the recurrence range options when `recurring` is set
text?: string;
confirmText?: string;
confirmFutureText?: string; // Prompt for future recurring events
// Let the user pick which occurrences of a recurring event are affected
recurring?: boolean;
destructive?: boolean;
confirm?: (recurrenceRange: RecurrenceRange) => void;
cancel?: () => void;
text?: string | TemplateResult;
title: string;
}
export const loadGenericDialog = () => import("./confirm-event-dialog-box");
+4
View File
@@ -4,6 +4,7 @@ import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
@@ -31,6 +32,8 @@ class PanelClimate extends LitElement {
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
@@ -127,6 +130,7 @@ class PanelClimate extends LitElement {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
@@ -346,17 +346,19 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
maxWidth: "82px",
sortable: true,
groupable: true,
hidden: narrow,
type: "overflow",
title: this.hass.localize("ui.panel.config.automation.picker.state"),
template: (automation) => html`
<ha-switch
@click=${stopPropagation}
@change=${this._handleSwitchToggle}
.automation=${automation}
.checked=${automation.state === "on"}
></ha-switch>
`,
template: (automation) =>
narrow
? automation.formatted_state
: html`
<ha-switch
@click=${stopPropagation}
@change=${this._handleSwitchToggle}
.automation=${automation}
.checked=${automation.state === "on"}
></ha-switch>
`,
},
actions: {
lastFixed: true,
@@ -203,12 +203,10 @@ export function getModifiedAtTableColumn<T>(
}
const renderDateTimeColumn = (valueDateTime: number, hass: HomeAssistant) =>
html`${
valueDateTime
? formatShortDateTimeWithConditionalYear(
new Date(valueDateTime * 1000),
hass.locale,
hass.config
)
: nothing
}`;
valueDateTime
? formatShortDateTimeWithConditionalYear(
new Date(valueDateTime * 1000),
hass.locale,
hass.config
)
: nothing;
@@ -36,6 +36,7 @@ import { showQuickBar } from "../../../dialogs/quick-bar/show-dialog-quick-bar";
import { showRestartDialog } from "../../../dialogs/restart/show-dialog-restart";
import { showShortcutsDialog } from "../../../dialogs/shortcuts/show-shortcuts-dialog";
import type { PageNavigation } from "../../../layouts/hass-tabs-subpage";
import { ChildPanelReady } from "../../../layouts/panel-ready";
import { SubscribeMixin } from "../../../mixins/subscribe-mixin";
import { haStyle } from "../../../resources/styles";
import type { HomeAssistant } from "../../../types";
@@ -157,6 +158,11 @@ class HaConfigDashboard extends SubscribeMixin(LitElement) {
total: 0,
};
public constructor() {
super();
new ChildPanelReady(this);
}
private _pages = memoizeOne(
(
cloudStatus,
@@ -1,12 +1,18 @@
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { consume } from "@lit/context";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { filterNavigationPages } from "../../../common/config/filter_navigation_pages";
import "../../../components/ha-card";
import "../../../components/ha-icon-next";
import type { CloudStatus } from "../../../data/cloud";
import { getConfigEntries } from "../../../data/config_entries";
import type { PageNavigation } from "../../../layouts/hass-tabs-subpage";
import {
childPanelReadyContext,
type RegisterChildPanelReady,
} from "../../../layouts/panel-ready";
import type { HomeAssistant } from "../../../types";
import "../components/ha-config-navigation-list";
@@ -18,21 +24,53 @@ class HaConfigNavigation extends LitElement {
@property({ attribute: false }) public pages!: PageNavigation[];
@state() private _hasBluetoothConfigEntries = false;
@state() private _visiblePages?: PageNavigation[];
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
getConfigEntries(this.hass, {
domain: "bluetooth",
}).then((bluetoothEntries) => {
this._hasBluetoothConfigEntries = bluetoothEntries.length > 0;
});
private _hasBluetoothConfigEntries = false;
private _bluetoothEntriesLoaded?: Promise<void>;
private _childReadyRegistered = false;
private _filterNavigationPages = memoizeOne(
(
hass: HomeAssistant,
pages: PageNavigation[],
hasBluetoothConfigEntries: boolean
) => filterNavigationPages(hass, pages, { hasBluetoothConfigEntries })
);
@consume({ context: childPanelReadyContext, subscribe: true })
private _registerChildPanelReady?: RegisterChildPanelReady;
protected override updated(changedProps: Map<PropertyKey, unknown>) {
super.updated(changedProps);
const pagesOrHassChanged =
changedProps.has("pages") || changedProps.has("hass");
if (pagesOrHassChanged) {
const ready = this._resolveVisiblePages();
if (!this._childReadyRegistered && this._registerChildPanelReady) {
this._registerChildPanelReady(ready);
this._childReadyRegistered = true;
}
return;
}
if (
!this._childReadyRegistered &&
this._registerChildPanelReady &&
this.pages &&
this.hass
) {
this._registerChildPanelReady(this._resolveVisiblePages());
this._childReadyRegistered = true;
}
}
protected render(): TemplateResult {
const pages = filterNavigationPages(this.hass, this.pages, {
hasBluetoothConfigEntries: this._hasBluetoothConfigEntries,
}).map((page) => ({
const pages = (this._visiblePages ?? []).map((page) => ({
...page,
name:
page.name ||
@@ -75,6 +113,42 @@ class HaConfigNavigation extends LitElement {
`;
}
private _loadBluetoothEntries(): Promise<void> {
if (!this._bluetoothEntriesLoaded) {
this._bluetoothEntriesLoaded = getConfigEntries(this.hass, {
domain: "bluetooth",
})
.then((entries) => {
this._hasBluetoothConfigEntries = entries.length > 0;
})
.catch(() => {
this._hasBluetoothConfigEntries = false;
});
}
return this._bluetoothEntriesLoaded;
}
private async _resolveVisiblePages(): Promise<void> {
if (this.pages.some((page) => page.component === "bluetooth")) {
await this._loadBluetoothEntries();
}
const visiblePages = this._filterNavigationPages(
this.hass,
this.pages,
this._hasBluetoothConfigEntries
);
const currentVisiblePages = this._visiblePages;
if (
!currentVisiblePages ||
visiblePages.length !== currentVisiblePages.length ||
visiblePages.some((page, index) => page !== currentVisiblePages[index])
) {
this._visiblePages = visiblePages;
}
await this.updateComplete;
}
static styles: CSSResultGroup = css`
/* Accessibility */
.visually-hidden {
+1
View File
@@ -89,6 +89,7 @@ class HaPanelConfig extends HassRouterPage {
dashboard: {
tag: "ha-config-dashboard",
load: () => import("./dashboard/ha-config-dashboard"),
waitForReady: true,
},
entities: {
tag: "ha-config-entities",
@@ -1395,7 +1395,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
font-size: 32px;
font-weight: 700;
line-height: 40px;
text-align: left;
text-align: start;
text-underline-position: from-font;
text-decoration-skip-ink: none;
margin: 0;
@@ -4,6 +4,7 @@ import {
mdiCloseCircle,
mdiProgressClock,
} from "@mdi/js";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
@@ -26,10 +27,10 @@ import "../../../../../components/ha-settings-row";
import "../../../../../components/ha-svg-icon";
import "../../../../../components/input/ha-input";
import type {
ZWaveJSNodeCapabilities,
ZWaveJSNodeConfigParam,
ZWaveJSNodeConfigParams,
ZWaveJSSetConfigParamResult,
ZwaveJSNodeConfigParameterUpdate,
ZwaveJSNodeMetadata,
} from "../../../../../data/zwave_js";
import {
@@ -38,6 +39,7 @@ import {
fetchZwaveNodeMetadata,
invokeZWaveCCApi,
setZwaveNodeConfigParameter,
subscribeZwaveNodeConfigParameterUpdates,
} from "../../../../../data/zwave_js";
import { showConfirmationDialog } from "../../../../../dialogs/generic/show-dialog-box";
import "../../../../../layouts/hass-error-screen";
@@ -60,7 +62,7 @@ const icons = {
@customElement("zwave_js-node-config")
class ZWaveJSNodeConfig extends LitElement {
public hass!: HomeAssistant;
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public route!: Route;
@@ -84,13 +86,41 @@ class ZWaveJSNodeConfig extends LitElement {
@state() private _resetDialogProgress = false;
private _unsubConfigParamUpdates?: Promise<UnsubscribeFunc>;
private _resultTimeouts: Record<string, number> = {};
public connectedCallback(): void {
super.connectedCallback();
this.deviceId = this.route.path.substr(1);
this._subscribeConfigParameterUpdates();
}
public disconnectedCallback(): void {
super.disconnectedCallback();
this._unsubscribeConfigParameterUpdates();
this._clearAllResultTimeouts();
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (!changedProps.has("route") || !this.route) {
return;
}
const deviceId = this.route.path.slice(1);
if (deviceId !== this.deviceId) {
this.deviceId = deviceId;
this._config = undefined;
this._clearAllResultTimeouts();
this._results = {};
this._error = undefined;
}
}
protected updated(changedProps: PropertyValues<this>): void {
if (!this._config || changedProps.has("deviceId")) {
if (changedProps.has("deviceId")) {
this._fetchData();
this._subscribeConfigParameterUpdates();
} else if (!this._config) {
this._fetchData();
}
}
@@ -445,6 +475,58 @@ class ZWaveJSNodeConfig extends LitElement {
<p>${item.value}</p>`;
}
private _subscribeConfigParameterUpdates(): void {
this._unsubscribeConfigParameterUpdates();
if (!this.isConnected || !this.hass || !this.deviceId) {
return;
}
this._unsubConfigParamUpdates = subscribeZwaveNodeConfigParameterUpdates(
this.hass,
this.deviceId,
this._handleConfigParameterUpdate
);
this._unsubConfigParamUpdates.catch(() => {
// The backend doesn't support the subscription; the page still works,
// it just won't receive live updates
this._unsubConfigParamUpdates = undefined;
});
}
private _unsubscribeConfigParameterUpdates(): void {
if (this._unsubConfigParamUpdates) {
this._unsubConfigParamUpdates
.then((unsub) => unsub())
.catch(() => {
// The subscription never succeeded, so there is nothing to clean up
});
this._unsubConfigParamUpdates = undefined;
}
}
private _handleConfigParameterUpdate = (
update: ZwaveJSNodeConfigParameterUpdate
): void => {
const param = this._config?.[update.id];
if (!param) {
return;
}
const status = this._results[update.id]?.status;
if (status === "queued") {
// The device applied the queued change; the accepted result is cleared
// after a short delay by _setResult so the success message shows.
// The value was already set optimistically when the change was queued,
// so this runs even if the reported value matches the stored one.
this._setResult(update.id, "accepted");
} else if (status === "error" && param.value !== update.value) {
// The parameter changed, so the previous error no longer applies
this._setResult(update.id, undefined);
}
if (param.value !== update.value) {
param.value = update.value;
this._config = { ...this._config };
}
};
private _isEnumeratedBool(item: ZWaveJSNodeConfigParam): boolean {
// Some Z-Wave config values use a states list with two options where index 0 = Disabled and 1 = Enabled
// We want those to be considered boolean and show a toggle switch
@@ -611,16 +693,38 @@ class ZWaveJSNodeConfig extends LitElement {
}
}
private _clearResultTimeout(key: string): void {
if (key in this._resultTimeouts) {
clearTimeout(this._resultTimeouts[key]);
delete this._resultTimeouts[key];
}
}
private _clearAllResultTimeouts(): void {
Object.values(this._resultTimeouts).forEach((timeout) =>
clearTimeout(timeout)
);
this._resultTimeouts = {};
}
private _setResult(key: string, value: string | undefined) {
this._clearResultTimeout(key);
if (value === undefined) {
delete this._results[key];
this.requestUpdate();
} else {
this._results = { ...this._results, [key]: { status: value } };
if (value === "accepted") {
// Show the success message briefly, then clear it
this._resultTimeouts[key] = window.setTimeout(() => {
this._setResult(key, undefined);
}, 2000);
}
}
}
private _setError(key: string, message: string) {
this._clearResultTimeout(key);
const errorParam = { status: "error", error: message };
this._results = { ...this._results, [key]: errorParam };
}
@@ -636,12 +740,17 @@ class ZWaveJSNodeConfig extends LitElement {
return;
}
let capabilities: ZWaveJSNodeCapabilities | undefined;
[this._nodeMetadata, this._config, capabilities] = await Promise.all([
const [nodeMetadata, config, capabilities] = await Promise.all([
fetchZwaveNodeMetadata(this.hass, device.id),
fetchZwaveNodeConfigParameters(this.hass, device.id),
fetchZwaveNodeCapabilities(this.hass, device.id),
]);
if (device.id !== this.deviceId) {
// The user navigated to another node while the data was loading
return;
}
this._nodeMetadata = nodeMetadata;
this._config = config;
this._canResetAll =
capabilities &&
Object.values(capabilities).some((endpoint) =>
+13
View File
@@ -130,6 +130,19 @@ class PanelHome extends LitElement {
}
private async _setup() {
void import("../lovelace/strategies/home/home-dashboard-strategy").catch(
() => undefined
);
void import("../lovelace/strategies/home/home-overview-view-strategy")
.then(({ preloadHomeEnergyPreferences }) => {
const path = this.route?.path?.split("/")[1];
return !path || path === "overview"
? preloadHomeEnergyPreferences(this.hass)
: undefined;
})
.catch(() => undefined);
void import("../lovelace/views/hui-sections-view").catch(() => undefined);
this._updateExtraActionItems();
this._loadConfigPromise = this._loadConfig();
await this._loadConfigPromise;
+4
View File
@@ -4,6 +4,7 @@ import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
@@ -31,6 +32,8 @@ class PanelLight extends LitElement {
@state() private _searchParms = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
@@ -127,6 +130,7 @@ class PanelLight extends LitElement {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
@@ -3,6 +3,7 @@ import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/animation/ha-fade-in";
import "../../../components/ha-card";
import "../../../components/ha-spinner";
import type { LovelaceCardConfig } from "../../../data/lovelace/config/card";
@@ -38,7 +39,9 @@ export class HuiStartingCard extends LitElement implements LovelaceCard {
return html`
<div class="content">
<ha-spinner></ha-spinner>
<ha-fade-in .delay=${500}>
<ha-spinner></ha-spinner>
</ha-fade-in>
${this.hass.localize("ui.panel.lovelace.cards.starting.description")}
</div>
`;
@@ -296,6 +296,10 @@ export class HuiStatisticsGraphCard extends LitElement implements LovelaceCard {
await this._getStatisticsMetaData(this._entityIds);
}
await this._getStatistics();
if (!this.isConnected) {
this._interval = undefined;
return;
}
// statistics are created every hour
if (!this._config?.energy_date_selection) {
this._interval = window.setInterval(
@@ -1,5 +1,6 @@
import { migrateStateColorConfig } from "../common/entity-color-config";
import { migrateTimeFormatConfig } from "../common/entity-time-format-config";
import { migrateSecondaryInfoConfig } from "../common/entity-secondary-info-config";
import type {
ConditionalRowConfig,
LovelaceRowConfig,
@@ -20,11 +21,13 @@ const migrateEntitiesRowConfig = (
let newConf: LovelaceRowConfig = rowConf;
newConf = migrateTimeFormatConfig(newConf as EntitiesCardEntityConfig);
newConf = migrateStateColorConfig(newConf as EntitiesCardEntityConfig);
newConf = migrateSecondaryInfoConfig(newConf as EntitiesCardEntityConfig);
if (newConf.type === "conditional") {
const row = (newConf as ConditionalRowConfig).row;
if (row && typeof row === "object") {
let newRow = migrateTimeFormatConfig(row as EntitiesCardEntityConfig);
newRow = migrateStateColorConfig(newRow);
newRow = migrateSecondaryInfoConfig(newRow);
if (newRow !== row) {
newConf = { ...newConf, row: newRow } as ConditionalRowConfig;
}
+1 -10
View File
@@ -91,16 +91,7 @@ export interface EntityCardConfig extends LovelaceCardConfig {
export interface EntitiesCardEntityConfig extends EntityConfig {
type?: string;
secondary_info?:
| "entity-id"
| "last-changed"
| "last-triggered"
| "last-updated"
| "area"
| "position"
| "state"
| "tilt-position"
| "brightness";
secondary_info?: string | string[];
action_name?: string;
action?: string;
/** @deprecated use "action" instead */
@@ -0,0 +1,40 @@
import { isCustomType } from "../../../data/lovelace_custom_cards";
interface LegacySecondaryInfoConfig {
type?: string;
secondary_info?: string | string[];
}
const SUBSTITUTIONS = {
"last-changed": "last_changed",
"last-updated": "last_updated",
"last-triggered": "last_triggered",
position: "current_position",
"tilt-position": "current_tilt_position",
area: "area_name",
none: undefined,
};
export const migrateSecondaryInfoConfig = <T extends LegacySecondaryInfoConfig>(
config: T
): T => {
// Custom elements own their config schema and may use the same option with
// a different meaning, leave them untouched
if (config.type !== undefined && isCustomType(config.type)) {
return config;
}
if (
config.secondary_info === undefined ||
typeof config.secondary_info !== "string" ||
!(config.secondary_info in SUBSTITUTIONS)
) {
return config;
}
const { secondary_info, ...rest } = config;
return {
...rest,
...(SUBSTITUTIONS[secondary_info] && {
secondary_info: SUBSTITUTIONS[secondary_info],
}),
} as T;
};
@@ -4,13 +4,9 @@ import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { DOMAINS_INPUT_ROW } from "../../../common/const";
import { uid } from "../../../common/util/uid";
import { stopPropagation } from "../../../common/dom/stop_propagation";
import { toggleAttribute } from "../../../common/dom/toggle_attribute";
import { computeDomain } from "../../../common/entity/compute_domain";
import { computeAreaName } from "../../../common/entity/compute_area_name";
import { getEntityContext } from "../../../common/entity/context/get_entity_context";
import { formatDateTimeWithSeconds } from "../../../common/datetime/format_date_time";
import "../../../components/entity/state-badge";
import "../../../components/ha-relative-time";
import "../../../components/ha-tooltip";
@@ -21,6 +17,7 @@ import { actionHandler } from "../common/directives/action-handler-directive";
import { handleAction } from "../common/handle-action";
import { hasAction, hasAnyAction } from "../common/has-action";
import { createEntityNotFoundWarning } from "./hui-warning";
import "../../../state-display/state-display";
@customElement("hui-generic-entity-row")
export class HuiGenericEntityRow extends LitElement {
@@ -40,8 +37,6 @@ export class HuiGenericEntityRow extends LitElement {
@property({ attribute: "catch-interaction", type: Boolean })
public catchInteraction?;
private _secondaryInfoElementId = "-" + uid();
protected render() {
if (!this.hass || !this.config) {
return nothing;
@@ -101,118 +96,15 @@ export class HuiGenericEntityRow extends LitElement {
<div class="secondary">
${
this.secondaryText ||
(this.config.secondary_info === "entity-id"
? stateObj.entity_id
: this.config.secondary_info === "last-changed"
? html`
<ha-tooltip
for="last-changed${
this._secondaryInfoElementId
}"
placement="right"
>
${formatDateTimeWithSeconds(
new Date(stateObj.last_changed),
this.hass.locale,
this.hass.config
)}
</ha-tooltip>
<ha-relative-time
id="last-changed${this._secondaryInfoElementId}"
.datetime=${stateObj.last_changed}
capitalize
></ha-relative-time>
`
: this.config.secondary_info === "last-updated"
? html`
<ha-tooltip
for="last-updated${
this._secondaryInfoElementId
}"
placement="right"
>
${formatDateTimeWithSeconds(
new Date(stateObj.last_updated),
this.hass.locale,
this.hass.config
)}
</ha-tooltip>
<ha-relative-time
id="last-updated${
this._secondaryInfoElementId
}"
.datetime=${stateObj.last_updated}
capitalize
></ha-relative-time>
`
: this.config.secondary_info ===
"last-triggered"
? stateObj.attributes.last_triggered
? html`
<ha-tooltip
for="last-triggered${
this._secondaryInfoElementId
}"
placement="right"
>
${formatDateTimeWithSeconds(
new Date(
stateObj.attributes
.last_triggered
),
this.hass.locale,
this.hass.config
)}
</ha-tooltip>
<ha-relative-time
id="last-triggered${
this._secondaryInfoElementId
}"
.datetime=${
stateObj.attributes.last_triggered
}
capitalize
></ha-relative-time>
`
: this.hass.localize(
"ui.panel.lovelace.cards.entities.never_triggered"
)
: this.config.secondary_info ===
"position" &&
stateObj.attributes.current_position !==
undefined
? `${this.hass.localize(
"ui.card.cover.position"
)}: ${stateObj.attributes.current_position}`
: this.config.secondary_info ===
"tilt-position" &&
stateObj.attributes
.current_tilt_position !== undefined
? `${this.hass.localize(
"ui.card.cover.tilt_position"
)}: ${
stateObj.attributes
.current_tilt_position
}`
: this.config.secondary_info ===
"brightness" &&
stateObj.attributes.brightness
? html`${Math.round(
(stateObj.attributes.brightness /
255) *
100
)}
%`
: this.config.secondary_info ===
"state"
? html`${this.hass.formatEntityState(
stateObj
)}`
: this.config.secondary_info ===
"area"
? (this._getArea(stateObj) ??
nothing)
: nothing)
html`<state-display
.stateObj=${stateObj}
.hass=${this.hass}
.content=${this.config.secondary_info}
.timeFormat=${this.config.time_format}
.name=${name}
timestamp-tooltip
>
</state-display>`
}
</div>
`
@@ -253,17 +145,6 @@ export class HuiGenericEntityRow extends LitElement {
handleAction(this, this.hass!, this.config!, ev.detail.action!);
}
private _getArea(stateObj) {
const context = getEntityContext(
stateObj,
this.hass!.entities,
this.hass!.devices,
this.hass!.areas,
this.hass!.floors
);
return context.area ? computeAreaName(context.area) : undefined;
}
static styles = css`
:host {
display: flex;
@@ -10,6 +10,7 @@ import {
import {
formatDateTime,
formatDateTimeNumeric,
formatDateTimeWithSeconds,
} from "../../../common/datetime/format_date_time";
import {
formatTime,
@@ -29,6 +30,8 @@ import type {
} from "../../../types";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { TimestampRenderingFormat } from "./types";
import { uid } from "../../../common/util/uid";
import "../../../components/ha-tooltip";
const FORMATS: Record<
string,
@@ -60,6 +63,8 @@ class HuiTimestampDisplay extends LitElement {
@property({ type: Boolean }) public capitalize = false;
@property({ type: Boolean }) public tooltip = false;
@state() private _relative?: string;
@state()
@@ -87,6 +92,8 @@ class HuiTimestampDisplay extends LitElement {
private _interval?: number;
private _uid = "timestamp-display-" + uid();
public connectedCallback(): void {
super.connectedCallback();
this._connected = true;
@@ -114,6 +121,14 @@ class HuiTimestampDisplay extends LitElement {
const formatType = this._formatType;
if (INTERVAL_FORMAT.includes(formatType)) {
if (this.tooltip) {
return html`
<ha-tooltip for=${this._uid} placement="right">
${formatDateTimeWithSeconds(this.ts, this._locale, this._config)}
</ha-tooltip>
<span id=${this._uid}> ${this._relative} </span>
`;
}
return html` ${this._relative} `;
}
if (formatType in FORMATS) {
@@ -123,9 +138,20 @@ class HuiTimestampDisplay extends LitElement {
: format.style && format.style in FORMATS[formatType]
? format.style
: "default";
return html`
${FORMATS[formatType][style](this.ts, this._locale, this._config)}
`;
const formatted = FORMATS[formatType][style](
this.ts,
this._locale,
this._config
);
if (this.tooltip) {
return html`
<ha-tooltip for=${this._uid} placement="right">
${formatDateTimeWithSeconds(this.ts, this._locale, this._config)}
</ha-tooltip>
<span id=${this._uid}> ${formatted} </span>
`;
}
return html` ${formatted} `;
}
return html`${this._localize(
"ui.panel.lovelace.components.timestamp-display.invalid_format"
@@ -4,12 +4,8 @@ import memoizeOne from "memoize-one";
import { assert } from "superstruct";
import { fireEvent } from "../../../../common/dom/fire_event";
import { computeDomain } from "../../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-form/ha-form";
import type {
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import type { SchemaUnion } from "../../../../components/ha-form/types";
import type { HomeAssistant } from "../../../../types";
import { SENSOR_TIMESTAMP_DEVICE_CLASSES } from "../../../../data/sensor";
import type { EntitiesCardEntityConfig } from "../../cards/types";
@@ -17,19 +13,7 @@ import type { LovelaceRowEditor } from "../../types";
import { entitiesConfigStruct } from "../structs/entities-struct";
import { DOMAIN_TO_ELEMENT_TYPE } from "../../create-element/create-row-element";
import { TIMESTAMP_STATE_DOMAINS } from "../../../../common/const";
const SECONDARY_INFO_VALUES = {
none: {},
"entity-id": {},
"last-changed": {},
"last-updated": {},
"last-triggered": { domains: ["automation", "script"] },
area: {},
position: { domains: ["cover"] },
state: {},
"tilt-position": { domains: ["cover"] },
brightness: { domains: ["light"] },
};
import { stateContentHasTimestamp } from "../../../../state-display/state-display";
@customElement("hui-generic-entity-row-editor")
export class HuiGenericEntityRowEditor
@@ -47,96 +31,87 @@ export class HuiGenericEntityRowEditor
this._config = config;
}
private _schema = memoizeOne(
(entity: string, localize: LocalizeFunc, showTimeFormat?: boolean) => {
const domain = computeDomain(entity);
return [
{ name: "entity", required: true, selector: { entity: {} } },
{
name: "name",
selector: { entity_name: {} },
context: { entity: "entity" },
},
{
name: "",
type: "grid",
schema: [
{
name: "icon",
selector: {
icon: {},
},
context: {
icon_entity: "entity",
},
private _schema = memoizeOne((showTimeFormat?: boolean) => {
return [
{ name: "entity", required: true, selector: { entity: {} } },
{
name: "name",
selector: { entity_name: {} },
context: { entity: "entity" },
},
{
name: "",
type: "grid",
schema: [
{
name: "icon",
selector: {
icon: {},
},
{
name: "color",
selector: {
ui_color: {
include_state: true,
include_none: true,
},
},
},
],
},
{
name: "secondary_info",
selector: {
select: {
options: (
Object.keys(SECONDARY_INFO_VALUES).filter(
(info) =>
!("domains" in SECONDARY_INFO_VALUES[info]) ||
("domains" in SECONDARY_INFO_VALUES[info] &&
SECONDARY_INFO_VALUES[info].domains!.includes(domain))
) as (keyof typeof SECONDARY_INFO_VALUES)[]
).map((info) => ({
value: info,
label: localize(
`ui.panel.lovelace.editor.card.entities.secondary_info_values.${info}`
),
})),
context: {
icon_entity: "entity",
},
},
},
...(showTimeFormat
? ([
{
name: "time_format",
selector: {
ui_time_format: {},
},
{
name: "color",
selector: {
ui_color: {
include_state: true,
include_none: true,
},
] as const satisfies readonly HaFormSchema[])
: []),
] as const;
}
);
},
},
],
},
{
name: "secondary_info",
selector: {
ui_state_content: {
allow_context: true,
},
},
context: {
filter_entity: "entity",
},
},
{
name: "time_format",
visible: showTimeFormat,
selector: {
ui_time_format: {},
},
},
] as const;
});
protected render() {
if (!this.hass || !this._config) {
return nothing;
}
const entity = this._config.entity;
const domain = entity ? computeDomain(entity) : "";
const simpleEntity =
(DOMAIN_TO_ELEMENT_TYPE[domain] ||
DOMAIN_TO_ELEMENT_TYPE["_domain_not_found"]) === "simple";
const showTimeFormat = simpleEntity
? TIMESTAMP_STATE_DOMAINS.has(domain)
: domain === "event" ||
(domain === "sensor" &&
SENSOR_TIMESTAMP_DEVICE_CLASSES.includes(
this.hass.states[entity]?.attributes.device_class
));
const schema =
this.schema ||
this._schema(this._config.entity, this.hass.localize, showTimeFormat);
let schema = this.schema;
if (!schema) {
const entity = this._config.entity;
const domain = entity ? computeDomain(entity) : "";
const simpleEntity =
(DOMAIN_TO_ELEMENT_TYPE[domain] ||
DOMAIN_TO_ELEMENT_TYPE["_domain_not_found"]) === "simple";
const showTimeFormat =
(this._config.secondary_info &&
stateContentHasTimestamp(
entity,
this.hass.states[entity],
this._config.secondary_info
)) ||
(simpleEntity
? TIMESTAMP_STATE_DOMAINS.has(domain)
: domain === "event" ||
(domain === "sensor" &&
SENSOR_TIMESTAMP_DEVICE_CLASSES.includes(
this.hass.states[entity]?.attributes.device_class
)));
schema = this._schema(showTimeFormat);
}
return html`
<ha-form
@@ -500,13 +500,20 @@ export class HuiStatisticsGraphCardEditor
// update card config with updated entity config
const index = this._subElementEditorConfig!.index!;
const oldEntityConfig = this._config!.entities[index];
const oldEntityId =
typeof oldEntityConfig === "string"
? oldEntityConfig
: oldEntityConfig?.entity;
const newEntities = [...this._config!.entities];
newEntities[index] = newEntityConfig;
let config = this._config!;
config = { ...config, entities: newEntities };
// remove inappropriate stat options dependently on entities
config = await this._cleanConfig(config);
// only a different statistic can invalidate the stat options
if (newEntityConfig.entity !== oldEntityId) {
config = await this._cleanConfig(config);
}
// normalize a generated yaml code
config = this._orderProperties(config);
this._config = config;
@@ -1,4 +1,4 @@
import { union, object, string, optional, boolean } from "superstruct";
import { array, union, object, string, optional, boolean } from "superstruct";
import { timeFormatConfigStruct } from "../../components/types";
import {
actionConfigStruct,
@@ -12,7 +12,7 @@ export const entitiesConfigStruct = union([
name: optional(entityNameStruct),
icon: optional(string()),
image: optional(string()),
secondary_info: optional(string()),
secondary_info: optional(union([string(), array(string())])),
time_format: optional(timeFormatConfigStruct),
color: optional(string()),
tap_action: optional(actionConfigStruct),
@@ -23,6 +23,7 @@ import { hasConfigOrEntityChanged } from "../common/has-changed";
import "../components/hui-generic-entity-row";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import type { LovelaceRow } from "./types";
import "../../../state-display/state-display";
@customElement("hui-weather-entity-row")
class HuiWeatherEntityRow extends LitElement implements LovelaceRow {
@@ -162,25 +163,15 @@ class HuiWeatherEntityRow extends LitElement implements LovelaceRow {
hasSecondary
? html`
<div class="secondary">
${
this._config.secondary_info === "entity-id"
? stateObj.entity_id
: this._config.secondary_info === "last-changed"
? html`
<ha-relative-time
.datetime=${stateObj.last_changed}
capitalize
></ha-relative-time>
`
: this._config.secondary_info === "last-updated"
? html`
<ha-relative-time
.datetime=${stateObj.last_updated}
capitalize
></ha-relative-time>
`
: ""
}
<state-display
.stateObj=${stateObj}
.hass=${this.hass}
.content=${this._config.secondary_info}
.timeFormat=${this._config.time_format}
.name=${name}
timestamp-tooltip
>
</state-display>
</div>
`
: ""
+10 -3
View File
@@ -76,6 +76,7 @@ import { showMoreInfoDialog } from "../../dialogs/more-info/show-ha-more-info-di
import { showQuickBar } from "../../dialogs/quick-bar/show-dialog-quick-bar";
import { showVoiceCommandDialog } from "../../dialogs/voice-command-dialog/show-ha-voice-command-dialog";
import { haStyle } from "../../resources/styles";
import { ChildPanelReady } from "../../layouts/panel-ready";
import type { HomeAssistant, PanelInfo } from "../../types";
import { documentationUrl } from "../../util/documentation-url";
import { isMac } from "../../util/is_mac";
@@ -164,6 +165,8 @@ class HUIRoot extends LitElement {
private _restoreScroll = false;
private _childPanelReady?: ChildPanelReady;
private _undoRedoController = new UndoRedoController<UndoStackItem>(this, {
apply: (config) => this._applyUndoRedo(config),
currentConfig: () => ({
@@ -777,7 +780,7 @@ class HUIRoot extends LitElement {
huiView.narrow = this.narrow;
}
let newSelectView;
let newSelectView: HUIRoot["_curView"];
let viewPath: string | undefined = this.route!.path.split("/")[1];
viewPath = viewPath ? decodeURI(viewPath) : undefined;
@@ -1258,7 +1261,7 @@ class HUIRoot extends LitElement {
return;
}
let view;
let view: HUIView;
const viewConfig = this.config.views[viewIndex];
if (!viewConfig) {
@@ -1269,12 +1272,16 @@ class HUIRoot extends LitElement {
if (this._viewCache[viewIndex]) {
view = this._viewCache[viewIndex];
} else {
if (!this._childPanelReady) {
this._childPanelReady = new ChildPanelReady(this);
this.requestUpdate();
}
view = document.createElement("hui-view");
view.index = viewIndex;
this._viewCache[viewIndex] = view;
}
view.lovelace = this.lovelace;
view.lovelace = this.lovelace!;
view.hass = this.hass;
view.narrow = this.narrow;
@@ -9,6 +9,7 @@ import {
} from "../../../../common/entity/entity_filter";
import { floorDefaultIcon } from "../../../../components/ha-floor-icon";
import type { AreaRegistryEntry } from "../../../../data/area/area_registry";
import type { EnergyPreferences } from "../../../../data/energy";
import { getEnergyPreferences } from "../../../../data/energy";
import type { LovelaceCardConfig } from "../../../../data/lovelace/config/card";
import type {
@@ -50,6 +51,26 @@ export interface HomeOverviewViewStrategyConfig {
shortcuts?: ShortcutItem[];
}
const energyPreferencesPromises = new WeakMap<
HomeAssistant["connection"],
Promise<EnergyPreferences | undefined>
>();
export const preloadHomeEnergyPreferences = (hass: HomeAssistant) => {
if (!isComponentLoaded(hass.config, "energy")) {
return Promise.resolve(undefined);
}
const existing = energyPreferencesPromises.get(hass.connection);
if (existing) {
return existing;
}
const request = getEnergyPreferences(hass).catch(() => undefined);
energyPreferencesPromises.set(hass.connection, request);
return request;
};
const computeAreaCard = (
areaId: string,
hass: HomeAssistant
@@ -305,10 +326,8 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
.filter(weatherFilter)
.sort()[0];
const energyPrefs = isComponentLoaded(hass.config, "energy")
? // It raises if not configured, just swallow that.
await getEnergyPreferences(hass).catch(() => undefined)
: undefined;
const energyPrefs = await preloadHomeEnergyPreferences(hass);
energyPreferencesPromises.delete(hass.connection);
const hasEnergy =
hass.panels.energy &&
+17 -1
View File
@@ -58,6 +58,12 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
private _mqlListenerRef?: () => void;
private _resolveInitialRender?: () => void;
public initialRenderComplete = new Promise<void>((resolve) => {
this._resolveInitialRender = resolve;
});
public connectedCallback() {
super.connectedCallback();
this._initMqls();
@@ -166,7 +172,13 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
root.removeChild(root.lastChild);
}
columns.forEach((column) => root.appendChild(column));
columns.forEach((column) => {
root.appendChild(column);
});
if (this.cards.length === 0 || columns.some((column) => column.lastChild)) {
this._resolveInitialRender?.();
this._resolveInitialRender = undefined;
}
}
private async _createColumns() {
@@ -234,6 +246,10 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
index,
this.lovelace!.editMode
);
if (columnElements.some((column) => column.isConnected)) {
this._resolveInitialRender?.();
this._resolveInitialRender = undefined;
}
}
// Remove empty columns
+26
View File
@@ -1,4 +1,5 @@
import deepClone from "deep-clone-simple";
import { consume } from "@lit/context";
import type { PropertyValues } from "lit";
import { ReactiveElement } from "lit";
import { customElement, property, state } from "lit/decorators";
@@ -19,6 +20,10 @@ import type {
} from "../../../data/lovelace/config/view";
import { isStrategyView } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import {
childPanelReadyContext,
type RegisterChildPanelReady,
} from "../../../layouts/panel-ready";
import "../badges/hui-badge";
import type { HuiBadge } from "../badges/hui-badge";
import "../cards/hui-card";
@@ -95,6 +100,15 @@ export class HUIView extends ReactiveElement {
private _config?: LovelaceViewConfig;
private _resolveInitialRender?: () => void;
private _initialRenderComplete = new Promise<void>((resolve) => {
this._resolveInitialRender = resolve;
});
@consume({ context: childPanelReadyContext })
private _registerChildPanelReady?: RegisterChildPanelReady;
@storage({
key: "dashboardCardClipboard",
state: false,
@@ -152,6 +166,11 @@ export class HUIView extends ReactiveElement {
return this;
}
public connectedCallback(): void {
super.connectedCallback();
this._registerChildPanelReady?.(this._initialRenderComplete);
}
public willUpdate(changedProperties: PropertyValues<this>): void {
super.willUpdate(changedProperties);
@@ -324,6 +343,13 @@ export class HUIView extends ReactiveElement {
const viewConfig = await this._generateConfig(rawConfig);
this._setConfig(viewConfig, isStrategy);
await customElements.whenDefined(this._layoutElement!.localName);
if (this._layoutElement instanceof ReactiveElement) {
await this._layoutElement.updateComplete;
}
await this._layoutElement!.initialRenderComplete;
this._resolveInitialRender?.();
this._resolveInitialRender = undefined;
}
private _createLayoutElement(config: LovelaceViewConfig): void {
@@ -5,6 +5,7 @@ import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-top-app-bar-fixed";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
@@ -31,6 +32,8 @@ class PanelMaintenance extends LitElement {
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
@@ -127,6 +130,7 @@ class PanelMaintenance extends LitElement {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
+4
View File
@@ -5,6 +5,7 @@ import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-top-app-bar-fixed";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
@@ -31,6 +32,8 @@ class PanelSecurity extends LitElement {
@state() private _searchParms = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
@@ -127,6 +130,7 @@ class PanelSecurity extends LitElement {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
+7 -2
View File
@@ -10,7 +10,6 @@ import {
STRINGS_SEPARATOR_DOT,
TIMESTAMP_STATE_DOMAINS,
} from "../common/const";
import "../components/ha-relative-time";
import { UNAVAILABLE, UNKNOWN } from "../data/entity/entity";
import {
SENSOR_TIMESTAMP_DEVICE_CLASSES,
@@ -118,6 +117,9 @@ class StateDisplay extends LitElement {
@property({ attribute: false }) public timeFormat?: string;
@property({ type: Boolean, attribute: "timestamp-tooltip" })
public timestampTooltip = false;
@property({ type: Boolean, attribute: "dash-unavailable" })
public dashUnavailable?: boolean;
@@ -185,7 +187,9 @@ class StateDisplay extends LitElement {
if (content === "name" && this.name) {
return html`${this.name}`;
}
if (content === "entity-id") {
return stateObj.entity_id;
}
if (
content === "device_name" ||
content === "area_name" ||
@@ -214,6 +218,7 @@ class StateDisplay extends LitElement {
.ts=${new Date(relativeDateTime)}
.format=${this.timeFormat}
capitalize
.tooltip=${this.timestampTooltip}
></hui-timestamp-display>`;
}
+9 -6
View File
@@ -522,6 +522,9 @@
"show_password": "Show password",
"hide_password": "Hide password"
},
"form": {
"validation_failed": "Form validation failed."
},
"selectors": {
"serial_port": {
"enter_manually": "Enter manually",
@@ -1309,18 +1312,18 @@
"invalid_duration": "The duration of the event is not valid. Please check start and end date.",
"not_all_required_fields": "Not all required fields are filled in",
"end_auto_adjusted": "Event end was adjusted to prevent negative duration",
"recurrence_range": {
"this_event": "Only this event",
"this_and_future": "This and all future events"
},
"confirm_delete": {
"delete": "Delete event",
"delete_this": "Delete only this event",
"delete_future": "Delete all future events",
"prompt": "Do you want to delete this event?",
"recurring_prompt": "Do you want to delete only this event, or this and all future occurrences of the event?"
"recurring_prompt": "Which events do you want to delete?"
},
"confirm_update": {
"update": "Update event",
"update_this": "Update only this event",
"update_future": "Update all future events",
"recurring_prompt": "Do you want to update only this event, or this and all future occurrences of the event?"
"recurring_prompt": "Which events do you want to update?"
},
"repeat": {
"label": "Repeat",
+4
View File
@@ -0,0 +1,4 @@
{
"hashedEntry": "/frontend_(?:latest|es5)/[^/?#]+\\.[0-9a-f]{8,}\\.js",
"moduleError": "dynamically imported module|Importing a module script failed|error loading dynamically imported|ChunkLoadError"
}
+139
View File
@@ -0,0 +1,139 @@
/**
* @vitest-environment node
*/
import { execFile, spawn } from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { processStartTime } from "../../build-scripts/managed-process.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../.."
);
const temporaryDirectories = [];
const runNode = (args, env = {}) =>
new Promise((resolve) => {
execFile(
process.execPath,
args,
{
cwd: repoRoot,
env: { ...process.env, ...env },
},
(error, stdout, stderr) => {
resolve({ code: error?.code ?? 0, stdout, stderr });
}
);
});
const temporaryDirectory = async () => {
const directory = await mkdtemp(path.join(tmpdir(), "ha-build-cli-test-"));
temporaryDirectories.push(directory);
return directory;
};
const writeOwner = async (owner) => {
const cache = await temporaryDirectory();
const lockFile = path.join(cache, "ha-workflow.lock");
const record = {
pid: process.pid,
startTime: processStartTime(process.pid),
...owner,
};
await writeFile(lockFile, JSON.stringify(record));
return { cache, lockFile, record };
};
afterEach(async () => {
await Promise.all(
temporaryDirectories
.splice(0)
.map((directory) => rm(directory, { recursive: true, force: true }))
);
});
describe("build management CLIs", () => {
it("blocks a managed workflow when another owns the output", async () => {
const { cache } = await writeOwner({ kind: "build", token: "build" });
const result = await runNode(
["build-scripts/dev-server.mjs", "--suite", "app", "--background"],
{ HA_BUILD_CACHE_DIR: cache }
);
expect(result.code).toBe(1);
expect(result.stdout).toContain("Frontend build already running");
});
it("does not stop another development suite", async () => {
const { cache, lockFile, record } = await writeOwner({
kind: "dev",
suite: "demo",
token: "demo",
});
const result = await runNode(
["build-scripts/dev-server.mjs", "--suite", "gallery", "--stop"],
{ HA_BUILD_CACHE_DIR: cache }
);
expect(result.code).toBe(0);
expect(result.stdout).toContain("Dev server (gallery) not running");
expect(JSON.parse(await readFile(lockFile, "utf8"))).toEqual(record);
});
it("keeps an exact process suite start idempotent", async () => {
const { cache } = await writeOwner({
kind: "dev",
suite: "app",
token: "app",
});
const result = await runNode(
["build-scripts/dev-server.mjs", "--suite", "app", "--background"],
{ HA_BUILD_CACHE_DIR: cache }
);
expect(result.code).toBe(0);
expect(result.stdout).toContain("Dev server (app) already running");
});
});
describe("workflow ownership", () => {
it("removes owned locks when the child is terminated", async () => {
const cache = await temporaryDirectory();
const lockFile = path.join(cache, "ha-workflow.lock");
const script = [
'import { createWorkflowLockTask } from "./build-scripts/output-lock.mjs";',
'await createWorkflowLockTask("test")();',
'process.stdout.write("ready\\n");',
"setInterval(() => {}, 10000);",
].join("");
const child = spawn(
process.execPath,
["--input-type=module", "-e", script],
{
cwd: repoRoot,
env: { ...process.env, HA_BUILD_CACHE_DIR: cache },
stdio: ["ignore", "pipe", "inherit"],
}
);
await new Promise((resolve, reject) => {
child.stdout.once("data", resolve);
child.once("error", reject);
});
child.kill("SIGTERM");
await new Promise((resolve) => {
child.once("exit", resolve);
});
await expect(readFile(lockFile)).rejects.toMatchObject({ code: "ENOENT" });
});
});
@@ -0,0 +1,64 @@
/**
* @vitest-environment node
*/
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import process from "node:process";
import { afterEach, describe, expect, it } from "vitest";
import {
acquireProcessRecord,
processStartTime,
readProcessRecord,
releaseProcessRecord,
} from "../../build-scripts/managed-process.mjs";
const temporaryDirectories = [];
const temporaryFile = async (name) => {
const directory = await mkdtemp(path.join(tmpdir(), "ha-build-test-"));
temporaryDirectories.push(directory);
return path.join(directory, name);
};
afterEach(async () => {
await Promise.all(
temporaryDirectories
.splice(0)
.map((directory) => rm(directory, { recursive: true, force: true }))
);
});
describe("managed process records", () => {
it("recovers a stale owner", async () => {
const file = await temporaryFile("stale.lock");
await writeFile(
file,
JSON.stringify({ pid: 2147483647, startTime: "stale", token: "stale" })
);
const owner = {
pid: process.pid,
startTime: processStartTime(process.pid),
token: "current",
};
expect(acquireProcessRecord(file, owner).acquired).toBe(true);
expect(readProcessRecord(file)).toEqual(owner);
});
it("releases only for the owning token", async () => {
const file = await temporaryFile("token.lock");
const owner = {
pid: process.pid,
startTime: processStartTime(process.pid),
token: "owner",
};
acquireProcessRecord(file, owner);
releaseProcessRecord(file, "other");
expect(readProcessRecord(file)).toEqual(owner);
releaseProcessRecord(file, owner.token);
expect(readProcessRecord(file)).toBeUndefined();
});
});
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect } from "vitest";
import { html, nothing, render } from "lit";
import "../../src/components/data-table/ha-data-table";
import type {
DataTableColumnContainer,
DataTableRowData,
HaDataTable,
} from "../../src/components/data-table/ha-data-table";
const columns: DataTableColumnContainer = {
name: { title: "Name", main: true },
area: { title: "Area" },
category: { title: "Category" },
empty_template: { title: "Empty", template: () => nothing },
filled_template: { title: "Filled", template: () => html`filled` },
};
// The narrow row puts every non-main column on a secondary line, joined by dots.
const renderNarrowSecondary = (row: DataTableRowData) => {
const el = document.createElement("ha-data-table") as HaDataTable;
const container = document.createElement("div");
render((el as any)._renderRow(columns, true, row, 0), container);
return container.querySelector(".secondary")!.textContent!.trim();
};
describe("ha-data-table narrow secondary line", () => {
it("does not render separators for empty columns", () => {
expect(renderNarrowSecondary({ id: "1", name: "Test" })).toBe("filled");
});
it("separates only the columns that have a value", () => {
expect(
renderNarrowSecondary({ id: "1", name: "Test", area: "Kitchen" })
).toBe("Kitchen · filled");
});
it("renders a blank secondary line when all secondary columns are empty", () => {
const emptyColumns: DataTableColumnContainer = {
name: { title: "Name", main: true },
area: { title: "Area" },
category: { title: "Category" },
empty_template: { title: "Empty", template: () => nothing },
};
const el = document.createElement("ha-data-table") as HaDataTable;
const container = document.createElement("div");
render(
(el as any)._renderRow(emptyColumns, true, { id: "1", name: "Test" }, 0),
container
);
expect(container.querySelector(".secondary")!.textContent!.trim()).toBe("");
});
});
+96 -1
View File
@@ -4,7 +4,7 @@
* Run with:
* yarn test:e2e:app
*/
import { test, expect } from "@playwright/test";
import { test, expect, type Page } from "@playwright/test";
import {
appSidebar,
appSidebarConfig,
@@ -161,11 +161,106 @@ test.describe("Quick search", () => {
defineRouteSmokeTests(appRouteSmokeGroups);
const assertInitialReadiness = async (
page: Page,
options: {
path: string;
loadingSelector: string;
resolver:
"rejectMediaBrowse" | "resolveCalendarRegistry" | "resolveMediaBrowse";
readySelector: string;
}
) => {
await goToPanel(page, options.path);
const launchScreen = page.locator("#ha-launch-screen");
await expect(launchScreen).toBeAttached({ timeout: QUICK_TIMEOUT });
await expect(page.locator(options.loadingSelector)).toBeAttached({
timeout: QUICK_TIMEOUT,
});
await page.evaluate((resolver) => window[resolver]?.(), options.resolver);
await expect(page.locator(options.readySelector)).toBeAttached({
timeout: PANEL_TIMEOUT,
});
await expect(launchScreen).not.toBeAttached({ timeout: QUICK_TIMEOUT });
};
test.describe("Initial readiness", () => {
test("keeps the launch screen until calendar content renders", async ({
page,
}) => {
await assertInitialReadiness(page, {
path: "/?scenario=delayed-calendar#/calendar",
loadingSelector: "ha-panel-calendar ha-spinner",
resolver: "resolveCalendarRegistry",
readySelector: "ha-full-calendar",
});
});
test("keeps the launch screen until media content renders", async ({
page,
}) => {
await assertInitialReadiness(page, {
path: "/?scenario=delayed-media-browse#/media-browser/browser",
loadingSelector: "ha-media-player-browse > ha-spinner",
resolver: "resolveMediaBrowse",
readySelector: "ha-media-player-browse .no-items",
});
});
test("keeps the launch screen until a media error renders", async ({
page,
}) => {
await assertInitialReadiness(page, {
path: "/?scenario=delayed-media-browse-error#/media-browser/browser",
loadingSelector: "ha-media-player-browse > ha-spinner",
resolver: "rejectMediaBrowse",
readySelector: "ha-media-player-browse ha-alert",
});
});
});
// ---------------------------------------------------------------------------
// Lovelace
// ---------------------------------------------------------------------------
test.describe("Lovelace dashboard", () => {
test("keeps the launch screen until generated content renders", async ({
page,
}) => {
await goToPanel(page, "/?scenario=delayed-generated-dashboard#/climate");
const launchScreen = page.locator("#ha-launch-screen");
await expect(launchScreen).toBeAttached({ timeout: QUICK_TIMEOUT });
await expect(page.locator("hui-view")).not.toBeAttached();
await page.evaluate(() => window.resolveGeneratedDashboard?.());
await expect(page.locator("hui-view")).toBeAttached({
timeout: PANEL_TIMEOUT,
});
await expect(launchScreen).not.toBeAttached({ timeout: QUICK_TIMEOUT });
});
test("keeps the launch screen until initial content renders", async ({
page,
}) => {
await goToPanel(page, "/?scenario=delayed-lovelace#/lovelace");
const launchScreen = page.locator("#ha-launch-screen");
await expect(launchScreen).toBeAttached({ timeout: QUICK_TIMEOUT });
await expect(page.locator("hui-card")).not.toBeAttached();
await page.evaluate(() => window.resolveLovelaceConfig?.());
await expect(page.locator("hui-card").first()).toBeAttached({
timeout: PANEL_TIMEOUT,
});
await expect(launchScreen).not.toBeAttached({ timeout: QUICK_TIMEOUT });
});
test("renders cards", async ({ page }) => {
await goToPanel(page, "/lovelace");
// At least one card should appear
+5
View File
@@ -92,6 +92,11 @@ declare global {
interface Window {
__assistRun?: unknown;
__mockHass: MockHomeAssistant;
rejectMediaBrowse?: () => void;
resolveCalendarRegistry?: () => void;
resolveGeneratedDashboard?: () => void;
resolveLovelaceConfig?: () => void;
resolveMediaBrowse?: () => void;
}
}
+103 -1
View File
@@ -1,5 +1,10 @@
import type { ExtEntityRegistryEntry } from "../../../../../src/data/entity/entity_registry";
import type { AssistPipeline } from "../../../../../src/data/assist_pipeline";
import type {
EntityRegistryEntry,
ExtEntityRegistryEntry,
} from "../../../../../src/data/entity/entity_registry";
import type { LovelaceRawConfig } from "../../../../../src/data/lovelace/config/types";
import type { MediaPlayerItem } from "../../../../../src/data/media-player";
import type { MockHomeAssistant } from "../../../../../src/fake_data/provide_hass";
export type Scenario = (hass: MockHomeAssistant) => Promise<void> | void;
@@ -124,6 +129,98 @@ const quickSearchAssistScenario: Scenario = async (hass) => {
});
};
const addLaunchScreen = () => {
const launchScreen = document.createElement("div");
launchScreen.id = "ha-launch-screen";
document.body.prepend(launchScreen);
};
const delayedLovelaceScenario: Scenario = (hass) => {
addLaunchScreen();
const config: LovelaceRawConfig = {
views: [
{
title: "Home",
cards: [{ type: "markdown", content: "Dashboard ready" }],
},
],
};
let resolveConfig: ((config: LovelaceRawConfig) => void) | undefined;
const configPromise = new Promise<LovelaceRawConfig>((resolve) => {
resolveConfig = resolve;
});
window.resolveLovelaceConfig = () => resolveConfig?.(config);
hass.mockWS("lovelace/config", () => configPromise);
};
const delayedGeneratedDashboardScenario: Scenario = (hass) => {
addLaunchScreen();
const loadFragmentTranslation = hass.loadFragmentTranslation;
let resolveTranslation: (() => void) | undefined;
const translationReady = new Promise<void>((resolve) => {
resolveTranslation = resolve;
});
hass.loadFragmentTranslation = async (fragment) => {
if (fragment === "lovelace") {
await translationReady;
}
return loadFragmentTranslation(fragment);
};
window.resolveGeneratedDashboard = resolveTranslation;
};
const delayedCalendarScenario: Scenario = (hass) => {
addLaunchScreen();
let resolveRegistry: ((entries: EntityRegistryEntry[]) => void) | undefined;
const registryPromise = new Promise<EntityRegistryEntry[]>((resolve) => {
resolveRegistry = resolve;
});
window.resolveCalendarRegistry = () => resolveRegistry?.([]);
hass.mockWS("config/entity_registry/list", () => registryPromise);
};
const delayedMediaBrowseScenario: Scenario = (hass) => {
addLaunchScreen();
const root: MediaPlayerItem = {
title: "Media",
media_content_id: "media-source://media_source",
media_content_type: "app",
media_class: "directory",
can_play: false,
can_expand: true,
can_search: false,
children: [],
};
let resolveBrowse: ((item: MediaPlayerItem) => void) | undefined;
const browsePromise = new Promise<MediaPlayerItem>((resolve) => {
resolveBrowse = resolve;
});
window.resolveMediaBrowse = () => resolveBrowse?.(root);
hass.mockWS("media_source/browse_media", () => browsePromise);
};
const delayedMediaBrowseErrorScenario: Scenario = (hass) => {
addLaunchScreen();
let rejectBrowse:
((reason: { code: string; message: string }) => void) | undefined;
const browsePromise = new Promise<MediaPlayerItem>((_resolve, reject) => {
rejectBrowse = reject;
});
window.rejectMediaBrowse = () =>
rejectBrowse?.({ code: "unknown_error", message: "Browse failed" });
hass.mockWS("media_source/browse_media", () => browsePromise);
};
// ── Registry ──────────────────────────────────────────────────────────────
export const scenarios: Record<string, Scenario> = {
@@ -131,6 +228,11 @@ export const scenarios: Record<string, Scenario> = {
"non-admin": nonAdminScenario,
"dark-theme": darkThemeScenario,
"custom-theme": customThemeScenario,
"delayed-calendar": delayedCalendarScenario,
"delayed-generated-dashboard": delayedGeneratedDashboardScenario,
"delayed-media-browse": delayedMediaBrowseScenario,
"delayed-media-browse-error": delayedMediaBrowseErrorScenario,
"light-more-info": lightMoreInfoScenario,
"quick-search-assist": quickSearchAssistScenario,
"delayed-lovelace": delayedLovelaceScenario,
};
+7 -1
View File
@@ -1,5 +1,11 @@
global.window = (global.window ?? {}) as any;
global.navigator = (global.navigator ?? {}) as any;
if (!global.navigator) {
Object.defineProperty(global, "navigator", {
value: {},
configurable: true,
writable: true,
});
}
global.__DEMO__ = false;
global.__DEV__ = false;
+126 -137
View File
@@ -27,43 +27,28 @@ __metadata:
languageName: node
linkType: hard
"@asamuzakjp/css-color@npm:^5.1.11":
version: 5.1.11
resolution: "@asamuzakjp/css-color@npm:5.1.11"
"@asamuzakjp/css-color@npm:^6.0.5":
version: 6.0.5
resolution: "@asamuzakjp/css-color@npm:6.0.5"
dependencies:
"@asamuzakjp/generational-cache": "npm:^1.0.1"
"@csstools/css-calc": "npm:^3.2.0"
"@csstools/css-color-parser": "npm:^4.1.0"
"@csstools/css-calc": "npm:^3.2.1"
"@csstools/css-color-parser": "npm:^4.1.9"
"@csstools/css-parser-algorithms": "npm:^4.0.0"
"@csstools/css-tokenizer": "npm:^4.0.0"
checksum: 10/2e337cc94b5a3f9741a27f92b4e4b7dc467a76b1dcf66c40e71808fed71695f10c8cf07c8b13313cbb637154314ca1d8626bb9a045fe94b404b242a390cf3bd3
lru-cache: "npm:^11.5.2"
checksum: 10/bd88a9a1d00711f5f63c4288a82489c33e28de43dee37f418cd30a42517d7b7e2040dc79fc223ececf290e7b3f12bbd2dd8ce7450f73b03bf0613df449b9563f
languageName: node
linkType: hard
"@asamuzakjp/dom-selector@npm:^7.1.1":
version: 7.1.1
resolution: "@asamuzakjp/dom-selector@npm:7.1.1"
"@asamuzakjp/dom-selector@npm:^8.2.5":
version: 8.3.0
resolution: "@asamuzakjp/dom-selector@npm:8.3.0"
dependencies:
"@asamuzakjp/generational-cache": "npm:^1.0.1"
"@asamuzakjp/nwsapi": "npm:^2.3.9"
bidi-js: "npm:^1.0.3"
css-tree: "npm:^3.2.1"
is-potential-custom-element-name: "npm:^1.0.1"
checksum: 10/49a065a64db5f53a3008c231d09606e4b67f509fa20148a67419451c2dc91a421202ed17bfc4bc679ad2f0432d7260720d602c1d5c9c5e165931fff5199c3f12
languageName: node
linkType: hard
"@asamuzakjp/generational-cache@npm:^1.0.1":
version: 1.0.1
resolution: "@asamuzakjp/generational-cache@npm:1.0.1"
checksum: 10/e1cf3f1916a334c6153f624982f0eb3d50fa3048435ea5c5b0f441f8f1ab74a0fe992dac214b612d22c0acafad3cd1a1f6b45d99c7b6e3b63cfdf7f6ca5fc144
languageName: node
linkType: hard
"@asamuzakjp/nwsapi@npm:^2.3.9":
version: 2.3.9
resolution: "@asamuzakjp/nwsapi@npm:2.3.9"
checksum: 10/95a6d1c102e1117fe818da087fcc5b914d23e0699855991bae50b891435dd1945ad7d384198f8bcf616207fd85b7ec32e3db6b96e9309d84c6903b8dc4151e34
lru-cache: "npm:^11.5.2"
checksum: 10/458632671954613e1bd653c9c9d2e8ded44701f19ca8a9641ec3fa0df9eb60089769e0c98dd7991afd53b86e40f8a720024653f451af71ee644d6cf3241c9ec0
languageName: node
linkType: hard
@@ -2454,15 +2439,15 @@ __metadata:
languageName: node
linkType: hard
"@codemirror/view@npm:6.43.6, @codemirror/view@npm:^6.0.0, @codemirror/view@npm:^6.17.0, @codemirror/view@npm:^6.23.0, @codemirror/view@npm:^6.27.0, @codemirror/view@npm:^6.37.0, @codemirror/view@npm:^6.42.0":
version: 6.43.6
resolution: "@codemirror/view@npm:6.43.6"
"@codemirror/view@npm:6.43.7, @codemirror/view@npm:^6.0.0, @codemirror/view@npm:^6.17.0, @codemirror/view@npm:^6.23.0, @codemirror/view@npm:^6.27.0, @codemirror/view@npm:^6.37.0, @codemirror/view@npm:^6.42.0":
version: 6.43.7
resolution: "@codemirror/view@npm:6.43.7"
dependencies:
"@codemirror/state": "npm:^6.7.0"
crelt: "npm:^1.0.6"
style-mod: "npm:^4.1.0"
w3c-keyname: "npm:^2.2.4"
checksum: 10/be058e86523d5770921c6bad7963eb5ef0a7db340922db93043394e1e93d1f3125611a3c2dbf143f1ab69b426038cd2034ffa7484d4b55d1ac909f2ceed2ee06
checksum: 10/dbc7c4e9162099dae15be1107e831c955c778fa224e24f4fd02d6eb9e75bc6c6d636e3e9fce3dc5852576c392c5793f4f6c5838f932a9c9e77f32a4ca66f62bf
languageName: node
linkType: hard
@@ -2482,26 +2467,26 @@ __metadata:
languageName: node
linkType: hard
"@csstools/css-calc@npm:^3.2.0, @csstools/css-calc@npm:^3.2.1":
version: 3.2.1
resolution: "@csstools/css-calc@npm:3.2.1"
"@csstools/css-calc@npm:^3.2.1, @csstools/css-calc@npm:^3.3.0":
version: 3.3.0
resolution: "@csstools/css-calc@npm:3.3.0"
peerDependencies:
"@csstools/css-parser-algorithms": ^4.0.0
"@csstools/css-tokenizer": ^4.0.0
checksum: 10/39042a9382cbd7c4fa241c1a6c10d64c23fa7653970fc11df532e9bc42a366a8b50c3ac3036bd5f2a77b94144e7f804f19d2b52800ad2f48bd9a3840377165d8
checksum: 10/46dde1c26c8a62d7b849a616a521cb97abc2d6c8c480f7be6f14c70fe60689a2a58c1f5f905aae237250ad27172968e10c70f6f83864c7dc48d8f8921f55f6a9
languageName: node
linkType: hard
"@csstools/css-color-parser@npm:^4.1.0":
version: 4.1.9
resolution: "@csstools/css-color-parser@npm:4.1.9"
"@csstools/css-color-parser@npm:^4.1.9":
version: 4.1.10
resolution: "@csstools/css-color-parser@npm:4.1.10"
dependencies:
"@csstools/color-helpers": "npm:^6.1.0"
"@csstools/css-calc": "npm:^3.2.1"
"@csstools/css-calc": "npm:^3.3.0"
peerDependencies:
"@csstools/css-parser-algorithms": ^4.0.0
"@csstools/css-tokenizer": ^4.0.0
checksum: 10/6369b601bcd3a8ce58dbcdc389a732b754c8f3fc35421b37169f6d4b07c7261f7b8c23e7d04e457da5e5e0bb082e680acb137d8c86fa1f7d6ff14ea873bf02a2
checksum: 10/92f5f590617a2cc9ff358b2d79716cbe15dd4cc7537cdc45ffc55878282677a9ef6c8bfb215a7dc0731f302c32bf1b0d1b7fc3c550147fd8a6d85f7c3cfb0cdd
languageName: node
linkType: hard
@@ -2514,15 +2499,15 @@ __metadata:
languageName: node
linkType: hard
"@csstools/css-syntax-patches-for-csstree@npm:^1.1.3":
version: 1.1.6
resolution: "@csstools/css-syntax-patches-for-csstree@npm:1.1.6"
"@csstools/css-syntax-patches-for-csstree@npm:^1.1.6":
version: 1.1.7
resolution: "@csstools/css-syntax-patches-for-csstree@npm:1.1.7"
peerDependencies:
css-tree: ^3.2.1
peerDependenciesMeta:
css-tree:
optional: true
checksum: 10/8747268b42f1afbe450d38b7f388a4983c810883f8c0716fa24f5b1eef0f9cbaa3a0f4ea72d1e5cbd015dc4fd5af9cc96ade42792912ed2dcc1d4054de102163
checksum: 10/ba372ab41c351509d47e77f58eb56112fe6fd42e104b70c9c9c797faf4fbb3e837a5df5c9d7e3464b04607ee42e91701e34f935aeec8abb94f24be67cfa1b707
languageName: node
linkType: hard
@@ -2726,7 +2711,7 @@ __metadata:
languageName: node
linkType: hard
"@exodus/bytes@npm:^1.11.0, @exodus/bytes@npm:^1.15.0, @exodus/bytes@npm:^1.6.0":
"@exodus/bytes@npm:^1.11.0, @exodus/bytes@npm:^1.15.1, @exodus/bytes@npm:^1.6.0":
version: 1.15.1
resolution: "@exodus/bytes@npm:1.15.1"
peerDependencies:
@@ -4755,65 +4740,65 @@ __metadata:
languageName: node
linkType: hard
"@rspack/binding-darwin-arm64@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-darwin-arm64@npm:2.1.5"
"@rspack/binding-darwin-arm64@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-darwin-arm64@npm:2.1.6"
conditions: os=darwin & cpu=arm64
languageName: node
linkType: hard
"@rspack/binding-darwin-x64@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-darwin-x64@npm:2.1.5"
"@rspack/binding-darwin-x64@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-darwin-x64@npm:2.1.6"
conditions: os=darwin & cpu=x64
languageName: node
linkType: hard
"@rspack/binding-linux-arm64-gnu@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-linux-arm64-gnu@npm:2.1.5"
"@rspack/binding-linux-arm64-gnu@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-linux-arm64-gnu@npm:2.1.6"
conditions: os=linux & cpu=arm64 & libc=glibc
languageName: node
linkType: hard
"@rspack/binding-linux-arm64-musl@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-linux-arm64-musl@npm:2.1.5"
"@rspack/binding-linux-arm64-musl@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-linux-arm64-musl@npm:2.1.6"
conditions: os=linux & cpu=arm64 & libc=musl
languageName: node
linkType: hard
"@rspack/binding-linux-riscv64-gnu@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-linux-riscv64-gnu@npm:2.1.5"
"@rspack/binding-linux-riscv64-gnu@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-linux-riscv64-gnu@npm:2.1.6"
conditions: os=linux & cpu=riscv64 & libc=glibc
languageName: node
linkType: hard
"@rspack/binding-linux-riscv64-musl@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-linux-riscv64-musl@npm:2.1.5"
"@rspack/binding-linux-riscv64-musl@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-linux-riscv64-musl@npm:2.1.6"
conditions: os=linux & cpu=riscv64 & libc=musl
languageName: node
linkType: hard
"@rspack/binding-linux-x64-gnu@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-linux-x64-gnu@npm:2.1.5"
"@rspack/binding-linux-x64-gnu@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-linux-x64-gnu@npm:2.1.6"
conditions: os=linux & cpu=x64 & libc=glibc
languageName: node
linkType: hard
"@rspack/binding-linux-x64-musl@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-linux-x64-musl@npm:2.1.5"
"@rspack/binding-linux-x64-musl@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-linux-x64-musl@npm:2.1.6"
conditions: os=linux & cpu=x64 & libc=musl
languageName: node
linkType: hard
"@rspack/binding-wasm32-wasi@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-wasm32-wasi@npm:2.1.5"
"@rspack/binding-wasm32-wasi@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-wasm32-wasi@npm:2.1.6"
dependencies:
"@emnapi/core": "npm:1.11.2"
"@emnapi/runtime": "npm:1.11.2"
@@ -4822,43 +4807,43 @@ __metadata:
languageName: node
linkType: hard
"@rspack/binding-win32-arm64-msvc@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-win32-arm64-msvc@npm:2.1.5"
"@rspack/binding-win32-arm64-msvc@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-win32-arm64-msvc@npm:2.1.6"
conditions: os=win32 & cpu=arm64
languageName: node
linkType: hard
"@rspack/binding-win32-ia32-msvc@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-win32-ia32-msvc@npm:2.1.5"
"@rspack/binding-win32-ia32-msvc@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-win32-ia32-msvc@npm:2.1.6"
conditions: os=win32 & cpu=ia32
languageName: node
linkType: hard
"@rspack/binding-win32-x64-msvc@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding-win32-x64-msvc@npm:2.1.5"
"@rspack/binding-win32-x64-msvc@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding-win32-x64-msvc@npm:2.1.6"
conditions: os=win32 & cpu=x64
languageName: node
linkType: hard
"@rspack/binding@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/binding@npm:2.1.5"
"@rspack/binding@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/binding@npm:2.1.6"
dependencies:
"@rspack/binding-darwin-arm64": "npm:2.1.5"
"@rspack/binding-darwin-x64": "npm:2.1.5"
"@rspack/binding-linux-arm64-gnu": "npm:2.1.5"
"@rspack/binding-linux-arm64-musl": "npm:2.1.5"
"@rspack/binding-linux-riscv64-gnu": "npm:2.1.5"
"@rspack/binding-linux-riscv64-musl": "npm:2.1.5"
"@rspack/binding-linux-x64-gnu": "npm:2.1.5"
"@rspack/binding-linux-x64-musl": "npm:2.1.5"
"@rspack/binding-wasm32-wasi": "npm:2.1.5"
"@rspack/binding-win32-arm64-msvc": "npm:2.1.5"
"@rspack/binding-win32-ia32-msvc": "npm:2.1.5"
"@rspack/binding-win32-x64-msvc": "npm:2.1.5"
"@rspack/binding-darwin-arm64": "npm:2.1.6"
"@rspack/binding-darwin-x64": "npm:2.1.6"
"@rspack/binding-linux-arm64-gnu": "npm:2.1.6"
"@rspack/binding-linux-arm64-musl": "npm:2.1.6"
"@rspack/binding-linux-riscv64-gnu": "npm:2.1.6"
"@rspack/binding-linux-riscv64-musl": "npm:2.1.6"
"@rspack/binding-linux-x64-gnu": "npm:2.1.6"
"@rspack/binding-linux-x64-musl": "npm:2.1.6"
"@rspack/binding-wasm32-wasi": "npm:2.1.6"
"@rspack/binding-win32-arm64-msvc": "npm:2.1.6"
"@rspack/binding-win32-ia32-msvc": "npm:2.1.6"
"@rspack/binding-win32-x64-msvc": "npm:2.1.6"
dependenciesMeta:
"@rspack/binding-darwin-arm64":
optional: true
@@ -4884,15 +4869,15 @@ __metadata:
optional: true
"@rspack/binding-win32-x64-msvc":
optional: true
checksum: 10/d1054348d3ba734485f977d574c6311311707adfcc5e53f03c8dbbbdc5778cff9b815e1d675992e2832241606d4cce7678acc3999b259139120b4ec30751f1e1
checksum: 10/0d164b7425f448ed6b8b81e687f4a82377289476cee41553ced9532e211d216fa13429b9125f3e3f025e391709bf752983c16eb4549341a21cbd0c61510afbeb
languageName: node
linkType: hard
"@rspack/core@npm:2.1.5":
version: 2.1.5
resolution: "@rspack/core@npm:2.1.5"
"@rspack/core@npm:2.1.6":
version: 2.1.6
resolution: "@rspack/core@npm:2.1.6"
dependencies:
"@rspack/binding": "npm:2.1.5"
"@rspack/binding": "npm:2.1.6"
peerDependencies:
"@module-federation/runtime-tools": ^0.24.1 || ^2.0.0
"@swc/helpers": ^0.5.23
@@ -4901,7 +4886,7 @@ __metadata:
optional: true
"@swc/helpers":
optional: true
checksum: 10/714064de701211724f7d859bc269d357fa2ad2f7ea0ac34d1e4e48b534981cf3961bd723c0659b9c093330f04e01e16a0c5587d6a18301727e27d717f764ded7
checksum: 10/334f8e13aa3540b7320d3186250fc4e2f128711f765d2073274188f23c692d4262e7cbb88c10571626b55e480186c474bdbcb564e7fa97df803479554de855b4
languageName: node
linkType: hard
@@ -9675,10 +9660,10 @@ __metadata:
languageName: node
linkType: hard
"globals@npm:17.7.0":
version: 17.7.0
resolution: "globals@npm:17.7.0"
checksum: 10/79304ccc4d2ca167ea15bdb25da346aa34ce3847b18fbd6c3cad182e152505305db3c9722fd5e292c62f6db97a8fa06e0c110a1e7703d7325498e5351d08cab4
"globals@npm:17.8.0":
version: 17.8.0
resolution: "globals@npm:17.8.0"
checksum: 10/b7b854b2052d2608d1878884bf730c027e17b9e2d194834f48c3280a7f0005b06d5f51dba362d3149cc05eb90d36d990e5c996728ecd3585a43dc3b4a286ed85
languageName: node
linkType: hard
@@ -9915,7 +9900,7 @@ __metadata:
"@codemirror/lint": "npm:6.9.7"
"@codemirror/search": "npm:6.7.1"
"@codemirror/state": "npm:6.7.1"
"@codemirror/view": "npm:6.43.6"
"@codemirror/view": "npm:6.43.7"
"@date-fns/tz": "npm:1.5.0"
"@egjs/hammerjs": "npm:2.0.17"
"@eslint/js": "npm:10.0.1"
@@ -9955,7 +9940,7 @@ __metadata:
"@playwright/test": "npm:1.62.0"
"@replit/codemirror-indentation-markers": "npm:6.5.3"
"@rsdoctor/rspack-plugin": "npm:1.6.1"
"@rspack/core": "npm:2.1.5"
"@rspack/core": "npm:2.1.6"
"@rspack/dev-server": "npm:2.1.0"
"@swc/helpers": "npm:0.5.23"
"@thomasloven/round-slider": "npm:0.6.0"
@@ -10011,7 +9996,7 @@ __metadata:
fuse.js: "npm:7.5.0"
generate-license-file: "npm:4.2.1"
glob: "npm:13.0.6"
globals: "npm:17.7.0"
globals: "npm:17.8.0"
gulp: "npm:5.0.1"
gulp-brotli: "npm:3.0.0"
gulp-json-transform: "npm:0.5.0"
@@ -10024,7 +10009,7 @@ __metadata:
idb-keyval: "npm:6.3.0"
intl-messageformat: "npm:11.2.12"
js-yaml: "npm:5.2.2"
jsdom: "npm:29.1.1"
jsdom: "npm:30.0.0"
jszip: "npm:3.10.1"
leaflet: "npm:1.9.4"
leaflet-draw: "patch:leaflet-draw@npm%3A1.0.4#./.yarn/patches/leaflet-draw-npm-1.0.4-0ca0ebcf65.patch"
@@ -10979,37 +10964,37 @@ __metadata:
languageName: node
linkType: hard
"jsdom@npm:29.1.1":
version: 29.1.1
resolution: "jsdom@npm:29.1.1"
"jsdom@npm:30.0.0":
version: 30.0.0
resolution: "jsdom@npm:30.0.0"
dependencies:
"@asamuzakjp/css-color": "npm:^5.1.11"
"@asamuzakjp/dom-selector": "npm:^7.1.1"
"@asamuzakjp/css-color": "npm:^6.0.5"
"@asamuzakjp/dom-selector": "npm:^8.2.5"
"@bramus/specificity": "npm:^2.4.2"
"@csstools/css-syntax-patches-for-csstree": "npm:^1.1.3"
"@exodus/bytes": "npm:^1.15.0"
"@csstools/css-syntax-patches-for-csstree": "npm:^1.1.6"
"@exodus/bytes": "npm:^1.15.1"
css-tree: "npm:^3.2.1"
data-urls: "npm:^7.0.0"
decimal.js: "npm:^10.6.0"
html-encoding-sniffer: "npm:^6.0.0"
is-potential-custom-element-name: "npm:^1.0.1"
lru-cache: "npm:^11.3.5"
lru-cache: "npm:^11.5.2"
parse5: "npm:^8.0.1"
saxes: "npm:^6.0.0"
symbol-tree: "npm:^3.2.4"
tough-cookie: "npm:^6.0.1"
undici: "npm:^7.25.0"
tough-cookie: "npm:^6.0.2"
undici: "npm:^8.7.0"
w3c-xmlserializer: "npm:^5.0.0"
webidl-conversions: "npm:^8.0.1"
whatwg-mimetype: "npm:^5.0.0"
whatwg-url: "npm:^16.0.1"
whatwg-url: "npm:^17.1.0"
xml-name-validator: "npm:^5.0.0"
peerDependencies:
canvas: ^3.0.0
canvas: ^3.2.3
peerDependenciesMeta:
canvas:
optional: true
checksum: 10/344aed7f91839b6c7d1b40778c5542d6ded7d42d88e1b787e10bf12d4ccd65464a5f23f774eb84350885c75a48efc99f6972adbb94dffe324a1b065d3650843c
checksum: 10/dc73c071e67224465018733525047d05772667bd8e00a3703a6f6515238c027b6ca768bf86874a53d512fd0bb962d72cc6a6c31c1bc38e52318f9d412ad0bb90
languageName: node
linkType: hard
@@ -11595,7 +11580,7 @@ __metadata:
languageName: node
linkType: hard
"lru-cache@npm:^11.0.0, lru-cache@npm:^11.1.0, lru-cache@npm:^11.2.1, lru-cache@npm:^11.3.5":
"lru-cache@npm:^11.0.0, lru-cache@npm:^11.1.0, lru-cache@npm:^11.2.1, lru-cache@npm:^11.5.2":
version: 11.5.2
resolution: "lru-cache@npm:11.5.2"
checksum: 10/122789c66605ddf29df58ff279e9e2c9499499d0b80b895ec524496f14bcde045d1582e3e38008f3457226d98067556719573b352119d6be8bdb1f8849f85681
@@ -14745,7 +14730,7 @@ __metadata:
languageName: node
linkType: hard
"tough-cookie@npm:^6.0.1":
"tough-cookie@npm:^6.0.2":
version: 6.0.2
resolution: "tough-cookie@npm:6.0.2"
dependencies:
@@ -15071,17 +15056,10 @@ __metadata:
languageName: node
linkType: hard
"undici@npm:^7.25.0":
version: 7.28.0
resolution: "undici@npm:7.28.0"
checksum: 10/154423b280d623278a61decb437f8a7e581fb18b8c95556ef956b32a58cd668eadbb812d28e20678cb2dc545a566f35a3afc0962307ca801da30f4741117986d
languageName: node
linkType: hard
"undici@npm:^8.4.1":
version: 8.7.0
resolution: "undici@npm:8.7.0"
checksum: 10/e9644903bda97f825228b4c7bee95b3586609f94df685b598c32bdaf3ac795928cbd25b0ed2690c3ea0b5abd324f5a9641b63b6c81c9b19f3ef4d5b3e402a48c
"undici@npm:^8.4.1, undici@npm:^8.7.0":
version: 8.9.0
resolution: "undici@npm:8.9.0"
checksum: 10/dfad3e233087eafdf1d361acd17c4d45a9590d5db9400458f1c03f47d8f1ef68647e2109ebb982c862e50c227093abd2d5f44b154904fc0b3d22576b6e95cfe7
languageName: node
linkType: hard
@@ -15710,7 +15688,7 @@ __metadata:
languageName: node
linkType: hard
"whatwg-url@npm:^16.0.0, whatwg-url@npm:^16.0.1":
"whatwg-url@npm:^16.0.0":
version: 16.0.1
resolution: "whatwg-url@npm:16.0.1"
dependencies:
@@ -15721,6 +15699,17 @@ __metadata:
languageName: node
linkType: hard
"whatwg-url@npm:^17.1.0":
version: 17.1.0
resolution: "whatwg-url@npm:17.1.0"
dependencies:
"@exodus/bytes": "npm:^1.15.1"
tr46: "npm:^6.0.0"
webidl-conversions: "npm:^8.0.1"
checksum: 10/52052ba12a63e7665ee49d84d251a3d4776be4777fb259155ea3ca9bc49cdbbd18cbb5fce50f187e8450ce81d7abbbc4c39cfb15207c6d11d5c2539f9b87d426
languageName: node
linkType: hard
"whatwg-url@npm:^5.0.0":
version: 5.0.0
resolution: "whatwg-url@npm:5.0.0"