Compare commits

...
17 Commits
Author SHA1 Message Date
Aidan Timson daa11d4033 Let a demo thermostat in heat or cool mode only heat or cool for its range 2026-11-26 11:01:54 +00:00
Aidan Timson 4657adc2bd Check demo visibility conditions as Core does, also with the demo's own updateHass 2026-11-26 10:36:24 +00:00
Aidan Timson 116afd2065 Fit the large date to the size of the date card 2026-11-26 10:13:29 +00:00
Aidan Timson 6929509967 Add the battery level icons of sensors to the demo 2026-11-26 10:13:00 +00:00
Aidan Timson 39a8832c53 Redraw the button row when hass changes 2026-11-26 10:12:30 +00:00
Aidan Timson 89b954f04f Answer state visibility conditions in the demo's mock backend 2026-11-26 10:12:00 +00:00
Aidan Timson c2432ddf86 Give the demo's heating and cooling thermostats their action from the temperatures 2026-11-26 10:11:52 +00:00
Aidan Timson 771eaa70ff Add a skill for browser checks and pull request screenshots (#56142)
* Add a skill for browser checks and pull request screenshots

* Point the screenshot reminder to the browser checks skill

* Cover light and dark, long text and recorded demos in the browser checks skill

* Check RTL with an RTL profile language in the browser checks skill

* Keep a before capture for every change to an existing screen

* Have agents add pull request screenshots themselves when they can
2026-11-26 11:02:29 +02:00
darkrain-nl aff47efe5e 2026.12 beta - Fix add integration search focus (#56151)
* Focus autofocus elements slotted into an adaptive dialog

* Test focusing autofocus elements slotted into a dialog
2026-11-26 09:50:16 +01:00
Erwin Douna f13470719c Restore dismissed energy meter suggestions (#56156)
* Restore dismissed energy meter suggestions

* Use a toolbar menu for dismissed meter suggestions and fix save races
2026-11-26 08:50:27 +02:00
Martin Salinas 5f769d613c Show the entity's value in number controls after the device puts it back (#56148)
* Show the entity's value in number controls after the device puts it back

The numeric input card feature and the number entity row bound the state straight to the control's value. When the entity came back to the value it had, Lit skipped the unchanged binding and the control kept the requested value. Bind with live() so the control is compared with the entity's value on each render.

* Remove the number row tests

They only check that the template puts the entity's value back on the controls, which is a rendering test. The gallery reproduction in the PR covers the change.
2026-11-26 08:44:12 +02:00
renovate[bot] f214ef8667 Update dependency @versatiles/style to v9.1.1 (#56158)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 08:32:28 +02:00
renovate[bot] 528ebe6b27 Update dependency memoize-one to v7 (#56160)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 08:32:20 +02:00
Gerd Naschenweng 82e6f1106f Cap the bar width in the statistics graph (#56097) 2026-11-26 08:04:48 +02:00
Martin Salinas f02656da54 Keep the color wheel drawn when only the cold white value is set (#56149)
With cw set and ww undefined, the ww !== null check let undefined through to rgbww2rgb, which returned NaN and made addColorStop throw, leaving the wheel blank. Moving the cold white slider of an RGBWW light that is off or in another color mode did that.
2026-11-26 07:52:12 +02:00
Matthias de BaatandClaude Opus 5.5 25307e427d Show when backup retention is paused for a location (#56088)
Automatic backup retention no longer deletes backups from locations
that are turned off for automatic backups (home-assistant/core#192788).
Show "Retention paused" in the locations list and an info alert on the
location page for those locations.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 22:17:03 +01:00
Paul Bottein 207cbcc585 Show the connection error when logged out and the server is offline (#56139)
* Show the connection error when logged out and the server is offline

* Show the connection error when the server responds with a 5xx

* Time out the server check before the login redirect

* Give the server check 10 seconds
2026-11-25 19:44:23 +02:00
27 changed files with 850 additions and 109 deletions

No files matched your search

@@ -0,0 +1,43 @@
---
name: ha-frontend-browser-checks
description: Check a Home Assistant frontend change in a browser and show it in a pull request. Use when checking how a change looks or behaves at different screen sizes, in light and dark mode, right to left (RTL) or with long translations, or when taking before and after screenshots or recording a demo of a feature for a pull request.
---
# HA Frontend Browser Checks
Use this skill to check a visible change in a browser and to show it in a pull request. Any browser tool you already have works if it can open a page, set its size, run a script in it, take screenshots and record video. Load `ha-frontend-testing` for the dev servers, and `ha-frontend-loading` for loading states.
Screenshots and recordings help reviewers see what changed, but they don't make a large change easy to review. [Keep pull requests small](https://contributors.home-assistant.io/start/pull-requests/#keep-it-small), and make sure you have reviewed and understood the change and can explain it, as the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks.
## Check Real Devices
Check the sizes the change affects rather than one fixed size, such as a phone, a tablet in both orientations, a laptop and a large desktop monitor. Include a small phone. Take each device's viewport in CSS pixels, its pixel ratio and touch support from the device presets your tools have, rather than from memory, and check the page really has that size once it's set.
## Check Light And Dark
When the change can look different in light and dark mode, such as a colour, border, background or image, check it in both. Switch the colour scheme in your browser tool, with the profile's theme following it, or pick light and dark in the profile. A fix for one mode only needs that mode.
## Check Right To Left (RTL)
Check layout, alignment, icons and anything with a direction in RTL. In the app, set your profile language to one written right to left, then set it back: many components take their direction from the language, so setting the page to RTL in your browser tool leaves them left to right. The gallery's RTL toggle checks styling only.
## Check Long Text
When a change adds or changes text, check it in a language with long words or long translations too, so labels, descriptions and buttons don't overflow or wrap badly. When the new string isn't translated yet, try a rough translation to check its length.
## Show It In The Pull Request
- When the change alters something that exists already, capture the same screen on `dev` and on your branch, in the same state, and put them side by side. Only a new screen, with nothing before it, needs just the after.
- Keep the size of every capture fixed, screenshots as well as videos. Set the page size before you capture and don't change it in between, and capture the same area each time, so the subject sits in the same place in before and after. For a card or other part of the page, work out a fixed area around it for each size you test, and use that same area on both branches.
- Say which device, size or mode each capture shows.
- Make the change easy to see: capture the part of the screen it affects rather than a whole page where it's a few pixels.
- Save captures outside the repository, so they can't be committed by accident.
- Keep personal details out: use demo data, such as the demo or the Demo integration, and mask anything else before you capture, such as names, addresses, IP and MAC addresses, hostnames, serial numbers and tokens. Check each capture before you attach it.
Record a video when it shows the change better than a still, such as an animation, a drag, a loading sequence (hold the loading state as "Checking It" in `ha-frontend-loading` shows) or a flow across several screens. Keep each video short and small: GitHub limits upload sizes, and reviewers have to watch it. You can record it yourself with the tools you have; it doesn't need a person.
- Use the recording tools at hand: your browser tool's recorder for a page, or a desktop screen recorder for a window, such as a phone emulator, so the device frame shows.
- Don't resize, zoom or take screenshots while recording, which redraw the page at another size and make the video jump.
- Check the whole recording before you attach it. For a short clip, look at a frame every second or half second, not only the first and last, since the page can jump to another size partway through. Record again if it does. Take stills from the same frames, so they match the video.
- Keep the window drawn on a screen. A hidden or minimised window records only a frame every few seconds.
- Label each video, such as **Before** and **After**, and say what it shows and how you set it up. Say what you didn't record and why.
+1 -1
View File
@@ -20,7 +20,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
- Do not omit, reorder, or rewrite template sections.
- Check the appropriate "Type of change" box based on the actual change.
- Do not check checklist items on behalf of the user.
- If the PR includes UI changes, remind the user to add screenshots or a short video.
- If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
- Explain what the change does for users, not only implementation details.
- Use Markdown.
+2 -1
View File
@@ -53,10 +53,11 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
## Pull Requests
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, remind the user to add screenshots or a short video.
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
## AI policy
+2 -2
View File
@@ -79,7 +79,7 @@
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.4",
"@tsparticles/preset-links": "4.5.4",
"@versatiles/style": "9.1.0",
"@versatiles/style": "9.1.1",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.204.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
@@ -110,7 +110,7 @@
"lit-html": "3.3.3",
"maplibre-gl": "6.19.0",
"marked": "18.2.1",
"memoize-one": "6.0.0",
"memoize-one": "7.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
+15 -15
View File
@@ -316,8 +316,8 @@ importers:
specifier: 4.5.4
version: 4.5.4
'@versatiles/style':
specifier: 9.1.0
version: 9.1.0([email protected])
specifier: 9.1.1
version: 9.1.1([email protected])
'@vibrant/color':
specifier: 4.0.4
version: 4.0.4
@@ -409,8 +409,8 @@ importers:
specifier: 18.2.1
version: 18.2.1
memoize-one:
specifier: 6.0.0
version: 6.0.0
specifier: 7.0.0
version: 7.0.0
nanoid:
specifier: 6.0.2
version: 6.0.2
@@ -2353,8 +2353,8 @@ packages:
leaflet: ^1.9.3
maplibre-gl: ^2.4.0 || ^3.3.1 || ^4.3.2 || ^5.0.0 || ^6.0.0
'@maplibre/maplibre-gl-style-spec@26.8.0':
resolution: {integrity: sha512-EClj+0m624zGw5gdCOsI5f88bYzkXfgoP2Sj5VGs2AYg9hZaPxvCumX5KDDs6aKFwl2ut+3jAeLhvrSz7hEsBQ==}
'@maplibre/maplibre-gl-style-spec@26.9.0':
resolution: {integrity: sha512-cQZK2lG3d6I5FjriPZCgJx/LiVMpWqoVibF+cgp2mkQ/P4BIGOsrA3WsvLw1wB28Q9JU9v2fapsQUJUbjjwa6g==}
hasBin: true
'@maplibre/[email protected]':
@@ -3838,8 +3838,8 @@ packages:
cpu: [x64]
os: [win32]
'@versatiles/[email protected].0':
resolution: {integrity: sha512-P2gLER3/VAOLGCMiumZ1hjHenlsAiI4mz1gPSak9ZAci0BgPYVfY+oo01MIYIfN4A+AvL1gfwZ3eC2vYQVqtlQ==}
'@versatiles/[email protected].1':
resolution: {integrity: sha512-JMOuqOq+uOX2PQZORX5rm0fxrvEx5KUvz/Oxr1JIOtuWRjdO5izpXPfg9/s+DeImd3Xpt8BG05X/hL5rkmY+9Q==}
engines: {node: '>=20'}
peerDependencies:
maplibre-gl: '>=5.5.0'
@@ -6197,8 +6197,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}
memoize-one@6.0.0:
resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==}
memoize-one@7.0.0:
resolution: {integrity: sha512-2N/rFuzS9eTTDXVmo/PO86KmapXPCOqDgR3eOnmWW1NVW8YXGzXcTWMKiGq/VAsYVl42Pd8rQ2DMsoYunIATLw==}
[email protected]:
resolution: {integrity: sha512-+y4mDxU4rvXXu5UDSGCGNiesFmwCHuefGMoPCO1WYucNYj7DsLqrFaa2fXVI0H+NNiPTwwzKwspn9yTZqUGqng==}
@@ -10228,7 +10228,7 @@ snapshots:
leaflet: 1.9.4
maplibre-gl: 6.19.0
'@maplibre/maplibre-gl-style-spec@26.8.0':
'@maplibre/maplibre-gl-style-spec@26.9.0':
dependencies:
'@mapbox/jsonlint-lines-primitives': 2.0.3
'@mapbox/unitbezier': 1.0.0
@@ -11670,9 +11670,9 @@ snapshots:
'@unrs/[email protected]':
optional: true
'@versatiles/[email protected].0([email protected])':
'@versatiles/[email protected].1([email protected])':
dependencies:
'@maplibre/maplibre-gl-style-spec': 26.8.0
'@maplibre/maplibre-gl-style-spec': 26.9.0
optionalDependencies:
maplibre-gl: 6.19.0
@@ -14150,7 +14150,7 @@ snapshots:
'@mapbox/unitbezier': 1.0.0
'@mapbox/vector-tile': 3.0.0
'@maplibre/geojson-vt': 6.3.2
'@maplibre/maplibre-gl-style-spec': 26.8.0
'@maplibre/maplibre-gl-style-spec': 26.9.0
'@maplibre/mlt': 1.3.0
'@maplibre/vt-pbf': 4.3.3
'@types/geojson': 7946.0.16
@@ -14180,7 +14180,7 @@ snapshots:
[email protected]: {}
memoize-one@6.0.0: {}
memoize-one@7.0.0: {}
[email protected]: {}
@@ -328,6 +328,11 @@ export function generateStatisticsChartData(
: undefined,
color: chartType === "bar" ? backgroundColor : borderColor,
};
if (chartType === "bar") {
// echarts sizes bars from the smallest gap between points, so sparse
// data (one point, or points far apart) gets huge bars without a cap
(series as BarSeriesOption).barMaxWidth = 50;
}
if (chartStacked) {
series.stack = `band-stacked`;
series.stackStrategy = "samesign";
+23 -3
View File
@@ -250,8 +250,8 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
this._hassConfig?.auth.external &&
isIosApp(this._hassConfig.auth.external)
) {
const element = this.querySelector("[autofocus]");
if (element !== null) {
const element = this._autofocusElement();
if (element) {
if (!element.id) {
element.id = "ha-dialog-autofocus";
}
@@ -264,10 +264,30 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
}
return;
}
(this.querySelector("[autofocus]") as HTMLElement | null)?.focus();
this._autofocusElement()?.focus();
});
};
// Wrappers like ha-adaptive-dialog pass their content in through slots
private _autofocusElement(): HTMLElement | null {
const element = this.querySelector<HTMLElement>("[autofocus]");
if (element) {
return element;
}
for (const slot of this.querySelectorAll("slot")) {
for (const assigned of slot.assignedElements({ flatten: true })) {
if (assigned.matches("[autofocus]")) {
return assigned as HTMLElement;
}
const nested = assigned.querySelector<HTMLElement>("[autofocus]");
if (nested) {
return nested;
}
}
}
return null;
}
private _handleAfterShow = (ev: Event) => {
if (ev.eventPhase !== Event.AT_TARGET) {
return;
+1 -1
View File
@@ -45,7 +45,7 @@ function adjustRgb(
if (wv != null) {
return rgbw2rgb([...rgb, wv] as [number, number, number, number]);
}
if (cw != null && ww !== null) {
if (cw != null && ww != null) {
return rgbww2rgb(
[...rgb, cw, ww] as [number, number, number, number, number],
minKelvin,
+6
View File
@@ -167,3 +167,9 @@ export const updateDismissedSuggestions = (
statisticId,
];
};
/** The dismissed statistics without the restored one. */
export const restoreDismissedSuggestion = (
dismissed: string[],
statisticId: string
): string[] => dismissed.filter((id) => id !== statisticId);
+29 -1
View File
@@ -75,11 +75,39 @@ const clearUrlParams = () => {
}
};
const SERVER_CHECK_TIMEOUT = 10_000;
const checkServer = async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), SERVER_CHECK_TIMEOUT);
try {
const response = await fetch(`${hassUrl}/manifest.json`, {
mode: "no-cors",
cache: "no-store",
signal: controller.signal,
});
if (response.status >= 500) {
throw new Error(`Home Assistant responded with ${response.status}`);
}
} finally {
clearTimeout(timeout);
}
};
// The login page is never cached, so check the server is up before getAuth redirects to it.
const loadTokensOrCheckServer = async () => {
const tokens = loadTokens();
if (!tokens || tokens.hassUrl !== hassUrl) {
await checkServer();
}
return tokens;
};
const authOptions = {
hassUrl,
limitHassInstance: true,
saveTokens,
loadTokens: () => Promise.resolve(loadTokens()),
loadTokens: loadTokensOrCheckServer,
};
const getAuthDroppingStaleCallback = async () => {
+14 -19
View File
@@ -1,21 +1,9 @@
import { supportsFeatureFromAttributes } from "../../common/entity/supports-feature";
import {
CLIMATE_HVAC_ACTION_TO_MODE,
ClimateEntityFeature,
} from "../../data/climate";
import { ClimateEntityFeature } from "../../data/climate";
import type { HvacAction } from "../../data/climate";
import { MockBaseEntity } from "./base-entity";
import type { EntityAttributes } from "./types";
// Reverse mapping: mode → action (e.g. "cool" → "cooling")
const HVAC_MODE_TO_ACTION: Partial<Record<string, HvacAction>> =
Object.fromEntries(
Object.entries(CLIMATE_HVAC_ACTION_TO_MODE).map(([action, mode]) => [
mode,
action as HvacAction,
])
);
export class MockClimateEntity extends MockBaseEntity {
public async handleService(
domain: string,
@@ -243,10 +231,13 @@ export class MockClimateEntity extends MockBaseEntity {
return "off";
}
// Use the reverse mapping for direct mode → action (e.g. "fan_only" → "fan", "dry" → "drying")
const directAction = HVAC_MODE_TO_ACTION[state];
if (directAction && directAction !== "idle" && directAction !== "off") {
return directAction;
// Heat and cool get their action from the temperatures below
if (state === "dry") {
return "drying";
}
if (state === "fan_only") {
return "fan";
}
if (
@@ -276,13 +267,17 @@ export class MockClimateEntity extends MockBaseEntity {
const current = attrs.current_temperature;
const lowTarget = attrs.target_temp_low;
const highTarget = attrs.target_temp_high;
// Heat mode can only heat and cool mode only cool, while auto and
// heat_cool use both ends of the range
if (current != null) {
if (lowTarget != null && lowTarget > current) {
if (state !== "cool" && lowTarget != null && lowTarget > current) {
return "heating";
}
if (highTarget != null && highTarget < current) {
if (state !== "heat" && highTarget != null && highTarget < current) {
return "cooling";
}
return "idle";
}
}
+16
View File
@@ -607,6 +607,22 @@ export const ENTITY_COMPONENT_ICONS: Record<string, ComponentIcons> = {
atmospheric_pressure: {
default: "mdi:thermometer-lines",
},
battery: {
default: "mdi:battery-unknown",
range: {
"0": "mdi:battery-alert",
"10": "mdi:battery-10",
"20": "mdi:battery-20",
"30": "mdi:battery-30",
"40": "mdi:battery-40",
"50": "mdi:battery-50",
"60": "mdi:battery-60",
"70": "mdi:battery-70",
"80": "mdi:battery-80",
"90": "mdi:battery-90",
"100": "mdi:battery",
},
},
carbon_dioxide: {
default: "mdi:molecule-co2",
},
+71
View File
@@ -27,6 +27,12 @@ import {
import { updateHassGroups } from "../data/context/updateContext";
import type { IconCategory } from "../data/icons";
import type { EntityRegistryDisplayEntry } from "../data/entity/entity_registry";
import { evaluateConditionsLocally } from "../common/condition/evaluate-locally";
import {
isLogicalCondition,
logicalChildren,
} from "../common/condition/translate";
import type { VisibilityCondition } from "../panels/lovelace/common/validate-condition";
import {
DateFormat,
FirstWeekday,
@@ -53,6 +59,24 @@ import type { EntityInput } from "./entities/types";
const ensureArray = <T>(val: T | T[]): T[] =>
Array.isArray(val) ? val : [val];
// Core's `not` passes when none of its conditions pass, and the frontend's
// unless all of them pass, so each `not` gets one `or` of its conditions
const withCoreNot = (condition: VisibilityCondition): VisibilityCondition => {
if (!isLogicalCondition(condition) || condition.conditions === undefined) {
return condition;
}
const conditions = logicalChildren(condition).map(withCoreNot);
return {
...condition,
conditions:
condition.condition === "not"
? [{ condition: "or", conditions }]
: conditions,
};
};
type MockServiceCallback = (
data: Record<string, any> | undefined,
target: Record<string, any> | undefined,
@@ -221,6 +245,8 @@ export const provideHass = (
return lazyLoaderPromise;
};
const eventListeners: Record<string, ((event) => void)[]> = {};
// Checks each subscribed condition again, for when the states change.
const conditionChecks = new Set<() => void>();
const entities = {};
let localResources: Resources = {};
@@ -664,6 +690,51 @@ export const provideHass = (
resources: category === "entity_component" ? ENTITY_COMPONENT_ICONS : {},
}));
// Core answers the visibility conditions of cards and rows that depend on
// states. Here they are checked against the mock states, as the frontend
// does itself before Core answers, and again each time the states change.
// A condition only Core can check, such as a template, gets an error, so
// a `not` around it can't show the card.
hassObj.mockWS(
"subscribe_condition",
({ condition }: { condition: VisibilityCondition }, _hass, onChange) => {
const check = () => {
const result = evaluateConditionsLocally(
[withCoreNot(condition)],
hass(),
{}
);
onChange?.(
result === undefined
? {
error: {
code: "not_supported",
message: "The demo can't check this condition",
},
}
: { result }
);
};
conditionChecks.add(check);
check();
return () => conditionChecks.delete(check);
}
);
// Check the conditions again after each state update, also when the host
// passed its own updateHass, as the demo does
const applyUpdate = hassObj.updateHass;
hassObj.updateHass = (obj: Partial<MockHomeAssistant>) => {
applyUpdate(obj);
if (obj.states) {
conditionChecks.forEach((check) => check());
}
};
// Set hass if required
if (setHassProperty) {
elements.forEach((el) => {
@@ -89,7 +89,11 @@ class HaBackupConfigAgents extends LitElement {
const retention = this.agentsConfig?.[agentId]?.retention;
if (retention) {
if (retention && !this._value.includes(agentId)) {
texts.push(
this.hass.localize("ui.panel.config.backup.agents.retention_inactive")
);
} else if (retention) {
if (retention.copies === null && retention.days === null) {
texts.push(
this.hass.localize("ui.panel.config.backup.agents.retention_all")
@@ -120,21 +120,34 @@ class HaConfigBackupDetails extends LitElement {
</p>
</div>
`
: html`<ha-backup-config-retention
location-specific
.headline=${this.hass.localize(
`ui.panel.config.backup.location.retention_for_${isLocalAgent(this.agentId) ? "this_system" : "location"}`,
{ location: agentName }
)}
.hass=${this.hass}
.retention=${
!this.config
? undefined
: this.config.agents[this.agentId]
?.retention || null
}
@value-changed=${this._retentionChanged}
></ha-backup-config-retention>`
: html`${
this.config &&
!this.config.create_backup.agent_ids.includes(
this.agentId
)
? html`<div class="card-content">
<ha-alert alert-type="info">
${this.hass.localize(
"ui.panel.config.backup.location.retention_inactive"
)}
</ha-alert>
</div>`
: nothing
}<ha-backup-config-retention
location-specific
.headline=${this.hass.localize(
`ui.panel.config.backup.location.retention_for_${isLocalAgent(this.agentId) ? "this_system" : "location"}`,
{ location: agentName }
)}
.hass=${this.hass}
.retention=${
!this.config
? undefined
: this.config.agents[this.agentId]
?.retention || null
}
@value-changed=${this._retentionChanged}
></ha-backup-config-retention>`
}
</ha-card>
<ha-card>
@@ -1,12 +1,13 @@
import { mdiFire, mdiFlash, mdiLightbulbOnOutline, mdiWater } from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import { fireEvent } from "../../../../common/dom/fire_event";
import { consumeEntityStates } from "../../../../common/decorators/consume-context-entry";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import { getEntityAreaId } from "../../../../common/entity/context/get_entity_context";
@@ -35,6 +36,7 @@ import type {
import {
computeEnergySuggestions,
ENERGY_SUGGESTION_EDITORS,
restoreDismissedSuggestion,
updateDismissedSuggestions,
} from "../../../../data/energy_suggestions";
import {
@@ -65,6 +67,8 @@ export class EnergySuggestions extends LitElement {
@property() public tab: EnergySuggestionTab = "electricity";
@property({ type: Boolean, attribute: false }) public showDismissed = false;
@state() private _statistics?: StatisticsMetaData[];
@state() private _dismissed?: string[];
@@ -72,6 +76,11 @@ export class EnergySuggestions extends LitElement {
// Dismissals not yet echoed by the subscription, so an older echo can't drop them
@state() private _pendingDismissed: string[] = [];
// Restores not yet echoed by the subscription
@state() private _pendingRestored: string[] = [];
private _reportedDismissedCount?: number;
@state() private _slots: Record<string, EnergySuggestionSlot> = {};
@state() private _loadFailed = false;
@@ -114,27 +123,46 @@ export class EnergySuggestions extends LitElement {
(
statistics: StatisticsMetaData[],
preferences: EnergyPreferences,
dismissed: string[],
states: HomeAssistant["states"],
tab: EnergySuggestionTab
) =>
computeEnergySuggestions({
statistics,
preferences,
dismissed,
states,
}).filter((suggestion) => suggestion.tab === tab)
computeEnergySuggestions({ statistics, preferences, states }).filter(
(suggestion) => suggestion.tab === tab
)
);
private _allDismissed = memoizeOne((stored: string[], pending: string[]) =>
pending.length
? [...stored, ...pending.filter((id) => !stored.includes(id))]
: stored
private _splitSuggestions = memoizeOne(
(all: EnergyMeterSuggestion[], dismissed: string[]) => ({
suggestions: all.filter(
(suggestion) => !dismissed.includes(suggestion.statisticId)
),
dismissedSuggestions: all.filter((suggestion) =>
dismissed.includes(suggestion.statisticId)
),
})
);
private _allDismissed = memoizeOne(
(stored: string[], pending: string[], restored: string[]) =>
[...stored, ...pending.filter((id) => !stored.includes(id))].filter(
(id) => !restored.includes(id)
)
);
private get _currentDismissed(): string[] {
return this._allDismissed(
this._dismissed!,
this._pendingDismissed,
this._pendingRestored
);
}
// Kept live so a dismiss in another tab isn't overwritten by this one.
private _unsubDismissed?: Promise<UnsubscribeFunc>;
// Each save builds on the list the previous one stored
private _saveQueue: Promise<unknown> = Promise.resolve();
connectedCallback() {
super.connectedCallback();
this._load();
@@ -161,6 +189,9 @@ export class EnergySuggestions extends LitElement {
this._pendingDismissed = this._pendingDismissed.filter(
(id) => !dismissed.includes(id)
);
this._pendingRestored = this._pendingRestored.filter((id) =>
dismissed.includes(id)
);
}
);
try {
@@ -203,14 +234,8 @@ export class EnergySuggestions extends LitElement {
if (!this._statistics || !this._dismissed) {
return nothing;
}
const suggestions = this._computeSuggestions(
this._statistics,
this.preferences,
this._allDismissed(this._dismissed, this._pendingDismissed),
this._states,
this.tab
);
if (!suggestions.length) {
const { suggestions, dismissedSuggestions, showDismissed } = this._view()!;
if (!suggestions.length && !showDismissed) {
return nothing;
}
@@ -218,27 +243,67 @@ export class EnergySuggestions extends LitElement {
<ha-card>
<h1 class="card-header">
<ha-svg-icon .path=${mdiLightbulbOnOutline}></ha-svg-icon>
${this._i18n.localize("ui.panel.config.energy.suggestions.title", {
count: suggestions.length,
})}
${
suggestions.length
? this._i18n.localize(
"ui.panel.config.energy.suggestions.title",
{
count: suggestions.length,
}
)
: this._i18n.localize(
"ui.panel.config.energy.suggestions.dismissed_title"
)
}
</h1>
<div class="card-content">
<p>
${this._i18n.localize("ui.panel.config.energy.suggestions.sub")}
</p>
<div class="items-container">
${repeat(
suggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion)
${this._i18n.localize(
suggestions.length
? "ui.panel.config.energy.suggestions.sub"
: "ui.panel.config.energy.suggestions.dismissed_sub"
)}
</div>
</p>
${
suggestions.length
? html`<div class="items-container">
${repeat(
suggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion, false)
)}
</div>`
: nothing
}
${
showDismissed
? html`${
suggestions.length
? html`<h3>
${this._i18n.localize(
"ui.panel.config.energy.suggestions.dismissed"
)}
</h3>`
: nothing
}
<div class="items-container">
${repeat(
dismissedSuggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion, true)
)}
</div>`
: nothing
}
</div>
</ha-card>
`;
}
private _renderSuggestion(suggestion: EnergyMeterSuggestion) {
private _renderSuggestion(
suggestion: EnergyMeterSuggestion,
dismissed: boolean
) {
const slot = this._slotFor(suggestion);
const label = getStatisticLabel(
this._states,
@@ -300,9 +365,11 @@ export class EnergySuggestions extends LitElement {
appearance="plain"
variant="neutral"
.suggestion=${suggestion}
@click=${this._dismiss}
@click=${dismissed ? this._restore : this._dismiss}
>${this._i18n.localize(
"ui.panel.config.energy.suggestions.dismiss"
dismissed
? "ui.panel.config.energy.suggestions.restore"
: "ui.panel.config.energy.suggestions.dismiss"
)}</ha-button
>
</div>
@@ -341,14 +408,13 @@ export class EnergySuggestions extends LitElement {
.suggestion;
const statisticId = suggestion.statisticId;
this._pendingDismissed = [...this._pendingDismissed, statisticId];
this._pendingRestored = this._pendingRestored.filter(
(id) => id !== statisticId
);
try {
await saveFrontendUserData(this._connection.connection, "energy", {
dismissed_suggestions: updateDismissedSuggestions(
this._allDismissed(this._dismissed!, this._pendingDismissed),
statisticId,
this._statistics!
),
});
await this._saveDismissed((dismissed) =>
updateDismissedSuggestions(dismissed, statisticId, this._statistics!)
);
} catch (err: any) {
this._pendingDismissed = this._pendingDismissed.filter(
(id) => id !== statisticId
@@ -362,6 +428,70 @@ export class EnergySuggestions extends LitElement {
}
}
private _view() {
if (this._loadFailed || !this._statistics || !this._dismissed) {
return undefined;
}
const { suggestions, dismissedSuggestions } = this._splitSuggestions(
this._computeSuggestions(
this._statistics,
this.preferences,
this._states,
this.tab
),
this._currentDismissed
);
return {
suggestions,
dismissedSuggestions,
showDismissed: this.showDismissed && dismissedSuggestions.length > 0,
};
}
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
const count = this._view()?.dismissedSuggestions.length ?? 0;
if (count !== this._reportedDismissedCount) {
this._reportedDismissedCount = count;
fireEvent(this, "energy-suggestions-dismissed-count", { count });
}
}
private async _restore(ev: Event) {
const suggestion: EnergyMeterSuggestion = (ev.currentTarget as any)
.suggestion;
const statisticId = suggestion.statisticId;
this._pendingRestored = [...this._pendingRestored, statisticId];
this._pendingDismissed = this._pendingDismissed.filter(
(id) => id !== statisticId
);
try {
await this._saveDismissed((dismissed) =>
restoreDismissedSuggestion(dismissed, statisticId)
);
} catch (err: any) {
this._pendingRestored = this._pendingRestored.filter(
(id) => id !== statisticId
);
showAlertDialog(this, {
title: this._i18n.localize(
"ui.panel.config.energy.suggestions.restore_failed"
),
text: err.message,
});
}
}
private _saveDismissed(update: (dismissed: string[]) => string[]) {
const save = this._saveQueue.then(() =>
saveFrontendUserData(this._connection.connection, "energy", {
dismissed_suggestions: update(this._dismissed!),
})
);
this._saveQueue = save.catch(() => undefined);
return save;
}
static get styles(): CSSResultGroup {
return [
haStyle,
@@ -407,4 +537,8 @@ declare global {
interface HTMLElementTagNameMap {
"ha-energy-suggestions": EnergySuggestions;
}
interface HASSDomEvents {
"energy-suggestions-dismissed-count": { count: number };
}
}
@@ -1,6 +1,9 @@
import "../../../layouts/hass-error-screen";
import {
mdiDotsVertical,
mdiDownload,
mdiEye,
mdiEyeOff,
mdiFire,
mdiLightningBolt,
mdiViewDashboardEdit,
@@ -10,6 +13,7 @@ import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { cache } from "lit/directives/cache";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { navigate } from "../../../common/navigate";
import type {
EnergyPreferencesValidation,
@@ -38,6 +42,9 @@ import "./components/ha-energy-battery-settings";
import "./components/ha-energy-gas-settings";
import "./components/ha-energy-water-settings";
import "./components/ha-energy-suggestions";
import "../../../components/ha-dropdown";
import "../../../components/ha-dropdown-item";
import "../../../components/ha-svg-icon";
import { fileDownload } from "../../../util/file_download";
import { showToast } from "../../../util/toast";
import type { PageNavigation } from "../../../layouts/hass-tabs-subpage";
@@ -98,6 +105,11 @@ class HaConfigEnergy extends LitElement {
@state() private _statsMetadata?: Record<string, StatisticsMetaData>;
// Dismissed meters on the current tab, as counted by the suggestions card
@state() private _dismissedSuggestions = 0;
@state() private _showDismissedSuggestions = false;
private get _currTab(): string {
return this.route.path.split("/")[1] || "electricity";
}
@@ -105,6 +117,10 @@ class HaConfigEnergy extends LitElement {
protected willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has("route")) {
const [, tab, kind, ...key] = this.route.path.split("/");
const oldTab = changedProperties.get("route")?.path.split("/")[1];
if (oldTab !== undefined && oldTab !== tab) {
this._showDismissedSuggestions = false;
}
if (!tab || !TABS.some((t) => t.path.endsWith(`/${tab}`))) {
navigate(`${this.route.prefix}/electricity${location.search}`, {
replace: true,
@@ -175,6 +191,35 @@ class HaConfigEnergy extends LitElement {
)}
@click=${this._downloadDiagnostics}
></ha-icon-button>
${
this._dismissedSuggestions
? html`<ha-dropdown
@wa-select=${this._toggleDismissedSuggestions}
>
<ha-icon-button
slot="trigger"
.label=${this.hass.localize("ui.common.menu")}
.path=${mdiDotsVertical}
></ha-icon-button>
<ha-dropdown-item value="toggle_dismissed">
<ha-svg-icon
slot="icon"
.path=${this._showDismissedSuggestions ? mdiEyeOff : mdiEye}
></ha-svg-icon>
${
this._showDismissedSuggestions
? this.hass.localize(
"ui.panel.config.energy.suggestions.hide_dismissed"
)
: this.hass.localize(
"ui.panel.config.energy.suggestions.show_dismissed",
{ count: this._dismissedSuggestions }
)
}
</ha-dropdown-item>
</ha-dropdown>`
: nothing
}
</div>
<ha-alert>
${this.hass.localize("ui.panel.config.energy.new_device_info")}
@@ -184,6 +229,8 @@ class HaConfigEnergy extends LitElement {
.preferences=${this._preferences!}
.listPath=${`${this.route.prefix}/${this._currTab}`}
.tab=${this._currTab}
.showDismissed=${this._showDismissedSuggestions}
@energy-suggestions-dismissed-count=${this._dismissedSuggestionsChanged}
></ha-energy-suggestions>
${cache(this._renderTabContent())}
</div>
@@ -446,6 +493,19 @@ class HaConfigEnergy extends LitElement {
this._statsMetadata = statsMetadata;
}
private _dismissedSuggestionsChanged(
ev: HASSDomEvent<HASSDomEvents["energy-suggestions-dismissed-count"]>
) {
this._dismissedSuggestions = ev.detail.count;
if (!this._dismissedSuggestions) {
this._showDismissedSuggestions = false;
}
}
private _toggleDismissedSuggestions() {
this._showDismissedSuggestions = !this._showDismissedSuggestions;
}
private _customise() {
if (!this._preferences) {
return;
@@ -2,6 +2,7 @@ import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { live } from "lit/directives/live";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
@@ -139,7 +140,7 @@ class HuiNumericInputCardFeature
return html`
<ha-control-number-buttons
.label=${label}
.value=${value}
.value=${live(value)}
.min=${stateObj.attributes.min}
.max=${stateObj.attributes.max}
.step=${stateObj.attributes.step}
@@ -153,7 +154,7 @@ class HuiNumericInputCardFeature
return html`
<ha-control-slider
.label=${label}
.value=${value}
.value=${live(value)}
.min=${stateObj.attributes.min}
.max=${stateObj.attributes.max}
.step=${stateObj.attributes.step}
+73 -1
View File
@@ -1,7 +1,8 @@
import { ResizeController } from "@lit-labs/observers/resize-controller";
import type { HassConfig } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { customElement, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { consume } from "../../../common/decorators/consume";
import { transform } from "../../../common/decorators/transform";
@@ -29,8 +30,21 @@ import {
isValidTimeZone,
} from "./hui-date-card-helpers";
// The smallest size the large date shrinks to, in pixels
const MIN_LARGE_DATE_FONT_SIZE = 12;
@customElement("hui-date-card")
export class HuiDateCard extends LitElement implements LovelaceCard {
// Each resize of the date updates the card, which fits the large date again.
// The card itself is inline, which a resize observer can't follow.
private _resizeController = new ResizeController(this, { target: null });
@query(".date-wrapper") private _wrapper?: HTMLElement;
@query(".date-title") private _title?: HTMLElement;
@query(".date-text") private _text?: HTMLElement;
public static async getConfigElement(): Promise<LovelaceCardEditor> {
await import("../editor/config-elements/hui-date-card-editor");
return document.createElement("hui-date-card-editor");
@@ -160,6 +174,63 @@ export class HuiDateCard extends LitElement implements LovelaceCard {
}
}
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
this._fitLargeDate();
}
// A long date at the large size can be wider and higher than the card, so
// it shrinks until it fits, as large as it can be
private _fitLargeDate() {
const wrapper = this._wrapper;
const text = this._text;
if (!wrapper || !text) {
return;
}
text.style.removeProperty("font-size");
if (this._config?.date_size !== "large") {
return;
}
const wrapperStyle = getComputedStyle(wrapper);
// The full height of the title, as a large date squeezes it
const availableHeight =
wrapper.clientHeight -
parseFloat(wrapperStyle.paddingTop) -
parseFloat(wrapperStyle.paddingBottom) -
(this._title
? this._title.scrollHeight + parseFloat(wrapperStyle.rowGap)
: 0);
const fits = () =>
text.scrollWidth <= text.clientWidth &&
text.scrollHeight <= availableHeight;
if (fits()) {
return;
}
let fitting = MIN_LARGE_DATE_FONT_SIZE;
let tooLarge = parseFloat(getComputedStyle(text).fontSize);
while (tooLarge - fitting > 0.5) {
const size = (fitting + tooLarge) / 2;
text.style.fontSize = `${size}px`;
if (fits()) {
fitting = size;
} else {
tooLarge = size;
}
}
text.style.fontSize = `${fitting}px`;
}
private _clearMidnightTimer() {
if (this._midnightTimer) {
clearTimeout(this._midnightTimer);
@@ -219,6 +290,7 @@ export class HuiDateCard extends LitElement implements LovelaceCard {
class="date-wrapper ${
this._config.date_size ? `size-${this._config.date_size}` : ""
}"
${this._resizeController.target()}
>
${
this._config.title !== undefined
@@ -1,6 +1,7 @@
import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { live } from "lit/directives/live";
import { debounce } from "../../../common/util/debounce";
import "../../../components/ha-slider";
import "../../../components/input/ha-input";
@@ -88,7 +89,7 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
.step=${Number(stateObj.attributes.step)}
.min=${Number(stateObj.attributes.min)}
.max=${Number(stateObj.attributes.max)}
.value=${Number(stateObj.state)}
.value=${live(Number(stateObj.state))}
@change=${this._selectedValueChanged}
></ha-slider>
<span class="state">
@@ -111,7 +112,7 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
.step=${Number(stateObj.attributes.step)}
.min=${Number(stateObj.attributes.min)}
.max=${Number(stateObj.attributes.max)}
.value=${Number(stateObj.state).toString()}
.value=${live(Number(stateObj.state).toString())}
type="number"
@change=${this._selectedValueChanged}
>
@@ -1,6 +1,6 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import "../../../components/ha-button";
@@ -29,7 +29,7 @@ const EMPTY_STATE_OBJ = {
@customElement("hui-button-row")
export class HuiButtonRow extends LitElement implements LovelaceRow {
public hass?: HomeAssistant;
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: ButtonRowConfig;
+11 -2
View File
@@ -3993,7 +3993,8 @@
"location_settings": "Location settings",
"retention_all": "Keep all backups",
"retention_backups": "Keep {count} {count, plural,\n one {backup}\n other {backups}\n}",
"retention_days": "Keep {count} {count, plural,\n one {day}\n other {days}\n}"
"retention_days": "Keep {count} {count, plural,\n one {day}\n other {days}\n}",
"retention_inactive": "Retention paused"
},
"data": {
"ha_settings": "Home Assistant settings",
@@ -4049,7 +4050,7 @@
"retention": "Retention",
"custom_retention": "Custom retention",
"custom_retention_label": "Keep only",
"retention_description": "Based on the maximum number of backups or how many days they should be kept.",
"retention_description": "Based on the maximum number of backups or how many days they should be kept. Only applies to automatic backups, in the locations they are stored in.",
"retention_presets": {
"global": "Use global settings",
"copies_3": "3 backups",
@@ -4324,6 +4325,7 @@
"save_error": "Error saving configuration: {error}",
"retention_for_this_system": "Retention for this system",
"retention_for_location": "Retention for {location}",
"retention_inactive": "Automatic backups aren't stored in this location, so its retention settings are paused. Backups already in this location are kept until you delete them. Retention applies again when you turn the location back on for automatic backups.",
"not_found": "Not found",
"not_found_description": "Location matching ''{backupId}'' not found",
"error": "Could not fetch location details",
@@ -4793,6 +4795,13 @@
"add": "Add",
"dismiss": "Dismiss",
"dismiss_failed": "Couldn't dismiss this meter",
"show_dismissed": "Show dismissed meters ({count})",
"hide_dismissed": "Hide dismissed meters",
"dismissed": "Dismissed",
"dismissed_title": "Dismissed meters",
"dismissed_sub": "Restore a meter to have it suggested again, or add it right away.",
"restore": "Restore",
"restore_failed": "Couldn't restore this meter",
"load_failed": "Couldn't check for meters that aren't in your energy dashboard yet.",
"slots": {
"grid_import": "Grid consumption",
@@ -177,6 +177,7 @@ exports[`generateStatisticsChartData > matches snapshot for a bar chart with sum
"datasets": [
{
"animationDurationUpdate": 0,
"barMaxWidth": 50,
"color": "#4269d07F",
"cursor": "default",
"data": [
@@ -347,6 +348,7 @@ exports[`generateStatisticsChartData > matches snapshot for a bar chart with sum
},
{
"animationDurationUpdate": 0,
"barMaxWidth": 50,
"color": "#f4bd4a7F",
"cursor": "default",
"data": [
@@ -1380,6 +1382,7 @@ exports[`generateStatisticsChartData > matches snapshot for a stacked bar chart
"datasets": [
{
"animationDurationUpdate": 0,
"barMaxWidth": 50,
"color": "#4269d07F",
"cursor": "default",
"data": [
@@ -1444,6 +1447,7 @@ exports[`generateStatisticsChartData > matches snapshot for a stacked bar chart
},
{
"animationDurationUpdate": 0,
"barMaxWidth": 50,
"color": "#f4bd4a7F",
"cursor": "default",
"data": [
+77
View File
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { HaDialog } from "../../src/components/ha-dialog";
import "../../src/components/ha-dialog";
vi.mock("@home-assistant/webawesome/dist/components/dialog/dialog", () => {
customElements.define("wa-dialog", class extends HTMLElement {});
return {};
});
vi.mock("../../src/components/ha-dialog-header", () => {
customElements.define("ha-dialog-header", class extends HTMLElement {});
return {};
});
vi.mock("../../src/components/ha-icon-button", () => {
customElements.define("ha-icon-button", class extends HTMLElement {});
return {};
});
// Lit counts the test run as a server, so this never gets an observer
vi.mock("@lit-labs/observers/resize-controller", () => ({
ResizeController: class {
observe = vi.fn();
unobserve = vi.fn();
},
}));
let host: HTMLElement | undefined;
afterEach(() => {
host?.remove();
host = undefined;
});
// Shows the dialog the way wa-dialog announces it opened
const showDialog = async (dialog: HaDialog) => {
await dialog.updateComplete;
dialog
.shadowRoot!.querySelector("wa-dialog")!
.dispatchEvent(new Event("wa-show"));
};
describe("ha-dialog", () => {
it("focuses its own autofocus child", async () => {
host = document.createElement("ha-dialog");
host.innerHTML = "<input /><input autofocus />";
document.body.append(host);
await showDialog(host as HaDialog);
await vi.waitFor(() =>
expect(document.activeElement).toBe(host!.querySelector("[autofocus]"))
);
});
it.each([
["slotted in by a wrapper", "<input /><input autofocus />"],
[
"nested in content a wrapper slots in",
"<input /><div><input autofocus /></div>",
],
])("focuses an autofocus element %s", async (_, content) => {
// A wrapper like ha-adaptive-dialog passes its content through a slot
host = document.createElement("div");
host.attachShadow({ mode: "open" }).innerHTML =
"<ha-dialog><slot></slot></ha-dialog>";
host.innerHTML = content;
document.body.append(host);
await showDialog(host.shadowRoot!.querySelector("ha-dialog")!);
await vi.waitFor(() =>
expect(document.activeElement).toBe(host!.querySelector("[autofocus]"))
);
});
});
+9
View File
@@ -10,6 +10,7 @@ import {
import type { EnergySuggestionInput } from "../../src/data/energy_suggestions";
import {
computeEnergySuggestions,
restoreDismissedSuggestion,
updateDismissedSuggestions,
} from "../../src/data/energy_suggestions";
import type { StatisticsMetaData } from "../../src/data/recorder";
@@ -230,3 +231,11 @@ describe("updateDismissedSuggestions", () => {
).toEqual(["sensor.kept", "sensor.new"]);
});
});
describe("restoreDismissedSuggestion", () => {
it("removes only the restored statistic", () => {
expect(
restoreDismissedSuggestion(["sensor.a", "sensor.b"], "sensor.a")
).toEqual(["sensor.b"]);
});
});
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import { ClimateEntityFeature } from "../../../src/data/climate";
import { MockClimateEntity } from "../../../src/fake_data/entities/climate-entity";
const hvacAction = (state: string, current: number, target: number) =>
new MockClimateEntity({
entity_id: "climate.demo",
state,
attributes: {
supported_features: ClimateEntityFeature.TARGET_TEMPERATURE,
current_temperature: current,
temperature: target,
},
}).toState().attributes.hvac_action;
// A range of 20° to 24° only, like climate.upstairs in the arsaboo demo
const rangeHvacAction = (state: string, current: number) =>
new MockClimateEntity({
entity_id: "climate.demo",
state,
attributes: {
supported_features:
ClimateEntityFeature.TARGET_TEMPERATURE +
ClimateEntityFeature.TARGET_TEMPERATURE_RANGE,
current_temperature: current,
temperature: null,
target_temp_low: 20,
target_temp_high: 24,
},
}).toState().attributes.hvac_action;
describe("MockClimateEntity", () => {
it.each([
["heat", 18, 21, "heating"],
["heat", 21, 21, "idle"],
["cool", 25, 21, "cooling"],
["cool", 20, 21, "idle"],
["dry", 20, 21, "drying"],
["fan_only", 20, 21, "fan"],
["off", 18, 21, "off"],
])(
"in %s at %d° with a target of %d° is %s",
(state, current, target, action) => {
expect(hvacAction(state, current, target)).toBe(action);
}
);
it.each([
["heat", 18, "heating"],
["heat", 25, "idle"],
["cool", 25, "cooling"],
["cool", 18, "idle"],
["heat_cool", 18, "heating"],
["heat_cool", 25, "cooling"],
["auto", 22, "idle"],
])(
"in %s at %d° with a range of 20° to 24° is %s",
(state, current, action) => {
expect(rangeHvacAction(state, current)).toBe(action);
}
);
});
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import type { Condition } from "../../src/data/automation";
import type { MockHomeAssistant } from "../../src/fake_data/provide_hass";
import { provideHass } from "../../src/fake_data/provide_hass";
type Host = HTMLElement & { hass?: Partial<MockHomeAssistant> };
// `ownUpdateHass` replaces updateHass as the full demo does, see
// demo/src/ha-demo.ts
const setup = (ownUpdateHass = false) => {
const host: Host = document.createElement("div");
const overrides: Partial<MockHomeAssistant> = ownUpdateHass
? {
updateHass: (update: Partial<MockHomeAssistant>) => {
host.hass = { ...host.hass, ...update };
},
}
: {};
const hass = provideHass(host, overrides);
hass.addEntities([
{ entity_id: "light.kitchen", state: "on", attributes: {} },
{ entity_id: "light.hallway", state: "off", attributes: {} },
]);
return hass;
};
const subscribe = async (hass: MockHomeAssistant, condition: Condition) => {
const messages: unknown[] = [];
await hass.connection.subscribeMessage(
(message) => {
messages.push(message);
},
{ type: "subscribe_condition", condition }
);
return messages;
};
const kitchenOn: Condition = {
condition: "state",
entity_id: "light.kitchen",
state: "on",
};
const hallwayOn: Condition = {
condition: "state",
entity_id: "light.hallway",
state: "on",
};
describe("subscribe_condition in the mock backend", () => {
it.each([
["its own", false],
["the host's", true],
])(
"checks a condition again when a state changes, with %s updateHass",
async (_name, ownUpdateHass) => {
const hass = setup(ownUpdateHass);
const messages = await subscribe(hass, hallwayOn);
hass.addEntities({
entity_id: "light.hallway",
state: "on",
attributes: {},
});
expect(messages).toEqual([{ result: false }, { result: true }]);
}
);
it("passes a not only when none of its conditions pass, as in Core", async () => {
const hass = setup();
expect(
await subscribe(hass, {
condition: "not",
conditions: [kitchenOn, hallwayOn],
})
).toEqual([{ result: false }]);
});
it("skips disabled conditions", async () => {
const hass = setup();
expect(
await subscribe(hass, {
condition: "and",
conditions: [kitchenOn, { ...hallwayOn, enabled: false }],
})
).toEqual([{ result: true }]);
});
it("answers a not around a template with an error", async () => {
const hass = setup();
const [message] = await subscribe(hass, {
condition: "not",
conditions: [{ condition: "template", value_template: "{{ true }}" }],
});
expect(message).toHaveProperty("error");
});
});