mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-26 14:49:00 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
daa11d4033 | ||
|
|
4657adc2bd | ||
|
|
116afd2065 | ||
|
|
6929509967 | ||
|
|
39a8832c53 | ||
|
|
89b954f04f | ||
|
|
c2432ddf86 |
No files matched your search
@@ -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";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user