Compare commits

...
10 Commits
Author SHA1 Message Date
Paul Bottein da96e343e7 Preview the cover while dragging in the cover dialog (#56433) 2026-12-04 13:16:02 +01:00
Bram Kragten 457c3563dd Bumped version to 20261125.5 2026-12-04 13:12:37 +01:00
Lazizbek Ergashev f3c6a7f8dd Keep pinging the backend after a reconnect (#56452) 2026-12-04 13:12:10 +01:00
9512bcc727 Don't list disabled entities under the Unavailable status filter (#56438)
Claude-Session: https://claude.ai/code/session_01CDc15sh8fUNmnB9T6EqcML

Co-authored-by: stoppyz0r <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 13:12:09 +01:00
Paul Bottein 850b636228 Keep the cover moving arrows clear of the handle (#56435) 2026-12-04 13:12:08 +01:00
Paul Bottein f69fe36efb Use a round handle with chevrons in the cover drawing (#56420)
* Use a round handle with chevrons in the cover drawing

* Keep the cover handle centered on the edge at the ends
2026-12-04 13:12:07 +01:00
Balloob BotandPaulus Schoutsen fde05319ef Collapse long lists of energy meter suggestions (#56390)
* Collapse long energy suggestion lists

* Preserve keyboard focus when expanding energy suggestions

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
2026-12-04 13:12:05 +01:00
Bram Kragten 088640642c Bumped version to 20261125.4 2026-12-02 13:44:49 +01:00
WendelinandClaude Opus 5.5 0819c80044 Fix plural forms being ignored in many languages (#56347)
* Keep the native Intl.PluralRules so plural forms work in every language

@formatjs/intl-pluralrules 7.1 and @formatjs/intl-numberformat 10.1 added a
should-polyfill check for formatting numeric strings with
trailingZeroDisplay: "stripToMinimum", which current browsers lack. Every
browser then replaced its native Intl.PluralRules with the polyfill, which
only carries English data, so languages like Russian and Polish lost their
"few" and "many" plural forms. Use our own checks without that feature, as
Home Assistant only passes numbers.

Fixes #56345

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Kv7eFTWUj93p4Bx4NdNA9

* Trim the Intl polyfill check comments and test

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

* Remove the unused FormatJS should-polyfill paths from tsconfig

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

---------

Co-authored-by: Claude <[email protected]>
2026-12-02 13:44:35 +01:00
Lazizbek Ergashev bb0c3bcd80 Keep visibility when an or matches despite an error in another branch (#56336) 2026-12-02 13:44:34 +01:00
20 changed files with 329 additions and 95 deletions

No files matched your search

-4
View File
@@ -508,12 +508,8 @@ const createRspackConfig = ({
"@formatjs/intl-locale/should-polyfill.js",
"@formatjs/intl-locale/polyfill-force":
"@formatjs/intl-locale/polyfill-force.js",
"@formatjs/intl-numberformat/should-polyfill":
"@formatjs/intl-numberformat/should-polyfill.js",
"@formatjs/intl-numberformat/polyfill-force":
"@formatjs/intl-numberformat/polyfill-force.js",
"@formatjs/intl-pluralrules/should-polyfill":
"@formatjs/intl-pluralrules/should-polyfill.js",
"@formatjs/intl-pluralrules/polyfill-force":
"@formatjs/intl-pluralrules/polyfill-force.js",
"@formatjs/intl-relativetimeformat/should-polyfill":
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20261125.3"
version = "20261125.5"
license = "Apache-2.0"
license-files = ["LICENSE*"]
description = "The Home Assistant frontend"
@@ -244,7 +244,7 @@ export class ConditionEvaluatorController implements ReactiveController {
return;
}
if (message.error !== undefined) {
this._serverResults[subtree.id] = false;
this._serverResults[subtree.id] = undefined;
this._subtreeErrors[subtree.id] =
typeof message.error === "string"
? message.error
@@ -265,7 +265,7 @@ export class ConditionEvaluatorController implements ReactiveController {
if (generation !== this._generation) {
return;
}
this._serverResults[subtree.id] = false;
this._serverResults[subtree.id] = undefined;
this._subtreeErrors[subtree.id] =
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
this._recompute();
@@ -299,18 +299,19 @@ export class ConditionEvaluatorController implements ReactiveController {
}
};
// A failed subtree stays unknown, so it only hides the card when the
// result depends on it (a true `or` sibling still wins).
const value = this._split.evaluate(clientEvaluator, this._serverResults);
const error = firstDefined(this._subtreeErrors);
// Don't treat a server error as `false` that a client `not` would invert.
if (error !== undefined) {
if (value === undefined && error !== undefined) {
this._setResult("hidden", error);
return;
}
const value = this._split.evaluate(clientEvaluator, this._serverResults);
const result: ConditionEvaluation =
value === undefined ? "unknown" : value ? "visible" : "hidden";
this._setResult(result, firstDefined(this._subtreeTemplateErrors));
this._setResult(result, error ?? firstDefined(this._subtreeTemplateErrors));
}
private _setResult(
@@ -3,7 +3,7 @@ import type { ContextType } from "@lit/context";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
@@ -88,6 +88,11 @@ export class EnergySuggestions extends LitElement {
@state() private _loadFailed = false;
@state() private _expanded = false;
@query(".items-container .suggestion:nth-child(4) button.link")
private _firstRevealedSuggestion?: HTMLButtonElement;
// Read by the @consumeEntityStates decorator below.
@state() protected _statisticIds: string[] = [];
@@ -217,6 +222,13 @@ export class EnergySuggestions extends LitElement {
}
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (changedProps.has("tab")) {
this._expanded = false;
}
}
protected render(): TemplateResult | typeof nothing {
if (this._loadFailed) {
return html`
@@ -242,6 +254,11 @@ export class EnergySuggestions extends LitElement {
return nothing;
}
const visibleSuggestions =
!this._expanded && suggestions.length >= 6
? suggestions.slice(0, 3)
: suggestions;
return html`
<ha-card>
<h1 class="card-header">
@@ -286,10 +303,26 @@ export class EnergySuggestions extends LitElement {
suggestions.length
? html`<div class="items-container">
${repeat(
suggestions,
visibleSuggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion, false)
)}
${
visibleSuggestions.length < suggestions.length
? html`<ha-button
appearance="plain"
@click=${this._showMore}
>
${this._i18n.localize(
"ui.panel.config.energy.suggestions.show_more",
{
count:
suggestions.length - visibleSuggestions.length,
}
)}
</ha-button>`
: nothing
}
</div>`
: nothing
}
@@ -318,6 +351,12 @@ export class EnergySuggestions extends LitElement {
`;
}
private async _showMore() {
this._expanded = true;
await this.updateComplete;
this._firstRevealedSuggestion?.focus();
}
private _renderSuggestion(
suggestion: EnergyMeterSuggestion,
dismissed: boolean
@@ -726,14 +726,15 @@ export class HaConfigEntities extends LitElement {
const hidden = !!entry.hidden_by;
const disabled = !!entry.disabled_by;
const readonly = entry.readonly;
// Entities without a state (disabled ones) count as unavailable too,
// so the Available and Unavailable filters are exact opposites. An
// empty state, like that of a cleared text helper, is a valid one.
// An empty state, like that of a cleared text helper, is a valid one.
// Entities without a state (disabled ones) are neither available nor
// unavailable, so the Unavailable filter only lists entities that are
// enabled but not working, matching the Status column.
const available = !!entity && entity.state !== UNAVAILABLE;
if (!(
(showAvailable && available) ||
(showUnavailable && !available) ||
(showUnavailable && unavailable) ||
(showRestored && restored) ||
(showVisible && !hidden) ||
(showHidden && hidden) ||
+4 -2
View File
@@ -3,12 +3,14 @@ import { shouldPolyfill as shouldPolyfillDisplayNames } from "@formatjs/intl-dis
import { shouldPolyfill as shouldPolyfillGetCanonicalLocales } from "@formatjs/intl-getcanonicallocales/should-polyfill";
import { shouldPolyfill as shouldPolyfillListFormat } from "@formatjs/intl-listformat/should-polyfill";
import { shouldPolyfill as shouldPolyfillLocale } from "@formatjs/intl-locale/should-polyfill";
import { shouldPolyfill as shouldPolyfillNumberFormat } from "@formatjs/intl-numberformat/should-polyfill";
import { shouldPolyfill as shouldPolyfillPluralRules } from "@formatjs/intl-pluralrules/should-polyfill";
import { shouldPolyfill as shouldPolyfillRelativeTimeFormat } from "@formatjs/intl-relativetimeformat/should-polyfill";
import { shouldPolyfill as shouldPolyfillDurationFormat } from "@formatjs/intl-durationformat/should-polyfill";
import { getLocalLanguage } from "../../util/common-translation";
import {
shouldPolyfillNumberFormat,
shouldPolyfillPluralRules,
} from "./intl-should-polyfill";
import {
polyfillLocaleData,
polyfillTimeZoneData,
@@ -0,0 +1,63 @@
// FormatJS 7.1 / 10.1 also probe for formatting numeric strings with
// trailingZeroDisplay: "stripToMinimum", which current browsers fail.
// That swapped in the English-only PluralRules polyfill everywhere; we only
// pass numbers, so leave that probe out.
const supportsLocale = (
supportedLocalesOf: (locales: string[]) => string[],
locale: string
) => supportedLocalesOf([locale]).length === 1;
export const shouldPolyfillPluralRules = (locale: string): boolean => {
try {
return !(
typeof Intl.PluralRules === "function" &&
// Older engines ignore the fraction digits when choosing the category
new Intl.PluralRules("en", { minimumFractionDigits: 2 }).select(1) !==
"one" &&
supportsLocale(Intl.PluralRules.supportedLocalesOf, locale)
);
} catch (_err) {
return true;
}
};
// Newer than the TypeScript lib this project targets
type NumberFormatMethods = Partial<
Record<"formatRange" | "formatRangeToParts" | "formatToParts", unknown>
>;
type RoundingPriorityOptions = Intl.NumberFormatOptions & {
roundingPriority?: "auto" | "morePrecision" | "lessPrecision";
};
export const shouldPolyfillNumberFormat = (locale: string): boolean => {
try {
const prototype: NumberFormatMethods = Intl.NumberFormat.prototype;
const roundingPriority: RoundingPriorityOptions = {
notation: "compact",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3,
minimumFractionDigits: 2,
maximumFractionDigits: 2,
roundingPriority: "morePrecision",
};
return !(
typeof Intl.NumberFormat === "function" &&
new Intl.NumberFormat("en", {
style: "unit",
unit: "bit",
unitDisplay: "long",
notation: "scientific",
}).format(10000) === "1E4 bits" &&
new Intl.NumberFormat("en", roundingPriority).format(100000000) ===
"100.00M" &&
typeof prototype.formatRange === "function" &&
typeof prototype.formatRangeToParts === "function" &&
typeof prototype.formatToParts === "function" &&
Intl.NumberFormat.supportedLocalesOf(["es"]).length === 1 &&
supportsLocale(Intl.NumberFormat.supportedLocalesOf, locale)
);
} catch (_err) {
return true;
}
};
@@ -18,11 +18,11 @@ export const coverDrawingStyles = css`
--cover-drawing-lift: #f5f5f5;
--cover-drawing-stripe: #ffffff;
--cover-drawing-slot: #cfe8fb;
--cover-drawing-ghost: #e1e1e1;
--cover-drawing-metal: #6f7a84;
--cover-drawing-grass-top: #a8d49a;
--cover-drawing-grass-bottom: #7fb071;
--cover-drawing-handle: #ffffff;
--cover-drawing-handle-icon: #5f6a74;
--cover-drawing-gauge: rgba(0, 0, 0, 0.12);
--cover-drawing-handle-shadow: rgba(0, 0, 0, 0.28);
}
@@ -38,11 +38,11 @@ export const coverDrawingStyles = css`
--cover-drawing-lift: #6e757e;
--cover-drawing-stripe: #676e78;
--cover-drawing-slot: #3b5f96;
--cover-drawing-ghost: #9aa3ad;
--cover-drawing-metal: #9aa5b0;
--cover-drawing-grass-top: #3f6b45;
--cover-drawing-grass-bottom: #2b4a31;
--cover-drawing-handle: #f2f4f6;
--cover-drawing-handle-icon: #3a4149;
--cover-drawing-gauge: rgba(0, 0, 0, 0.28);
--cover-drawing-handle-shadow: rgba(0, 0, 0, 0.6);
}
@@ -104,9 +104,6 @@ export const coverDrawingStyles = css`
.panel-shadow {
fill: #000;
}
.ghost {
fill: var(--cover-drawing-ghost);
}
.target-line {
fill: none;
stroke: var(--cover-drawing-handle);
@@ -124,8 +121,15 @@ export const coverDrawingStyles = css`
fill: var(--cover-drawing-handle);
filter: drop-shadow(0 0.5px 1.5px var(--cover-drawing-handle-shadow));
}
.pill-handle {
.knob-handle {
fill: var(--cover-drawing-handle);
filter: drop-shadow(0 1px 2px var(--cover-drawing-handle-shadow));
}
.knob-chevron {
fill: none;
stroke: var(--cover-drawing-handle-icon);
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
`;
@@ -51,14 +51,18 @@ import { WaveMotion } from "./wave";
type HandleMotion = "follow" | "drag" | "swipe" | "request" | "return";
type DrawnMotion = "follow" | "drag" | "return";
type ModeSprings = Record<CoverControlMode, PercentSpring>;
type ModeMotions = Record<CoverControlMode, HandleMotion>;
const SWIPE_SPRING: SpringOptions = { stiffness: 22, damping: 0.8 };
const RETURN_SPRING: SpringOptions = { stiffness: 30 };
const KEY_COMMIT_DELAY = 500;
const SWIPE_RESISTANCE = 20;
const GAUGE_WIDTH = 16;
const KNOB_RADIUS = 12;
const MODES = ["position", "tilt"] as const;
const MOVING_HINT_ANGLE: Record<OpeningDirection, number> = {
@@ -69,10 +73,12 @@ const MOVING_HINT_ANGLE: Record<OpeningDirection, number> = {
const SKY_LAYERS = ["sky", "sky-warm", "sky-cool"];
const pillHandle = (cx: number, cy: number, vertical: boolean) =>
vertical
? svg`<rect class="pill-handle" x=${cx - 4} y=${cy - 22} width="8" height="44" rx="4"></rect>`
: svg`<rect class="pill-handle" x=${cx - 24} y=${cy - 4} width="48" height="8" rx="4"></rect>`;
const knobHandle = (cx: number, cy: number, horizontal: boolean) => svg`
<g transform="translate(${cx} ${cy}) rotate(${horizontal ? 0 : 90})">
<circle class="knob-handle" r=${KNOB_RADIUS}></circle>
<path class="knob-chevron" d="M-2.5 -3.5 L-6 0 L-2.5 3.5 M2.5 -3.5 L6 0 L2.5 3.5"></path>
</g>
`;
const swipeResistance = (distance: number) =>
SWIPE_RESISTANCE * (1 - Math.exp(-Math.max(0, distance) / 30));
@@ -134,6 +140,10 @@ export class HaStateControlCover extends LitElement {
private _handleSprings = modeSprings();
private _drawnPosition = new PercentSpring();
private _drawnMotion: DrawnMotion = "follow";
private _handleMotions = modeMotions();
private _wave = new WaveMotion();
@@ -183,6 +193,8 @@ export class HaStateControlCover extends LitElement {
this._coverSprings[mode].jumpTo(value);
this._handleSprings[mode].jumpTo(value);
}
this._drawnPosition.jumpTo(this._coverSprings.position.value);
this._drawnMotion = "follow";
this._handleMotions = modeMotions();
this._wave.reset(this._coverSprings.position.value);
}
@@ -262,8 +274,9 @@ export class HaStateControlCover extends LitElement {
for (const mode of MODES) {
const goal = this._drawingGoal(mode);
changed = this._moveSpring(this._coverSprings[mode], goal, dt) || changed;
changed = this._moveHandle(mode, goal, dt) || changed;
changed = this._moveHandle(mode, dt) || changed;
}
changed = this._moveDrawnPosition(dt) || changed;
if (this._shape.usesWave) {
changed = this._moveWave(dt) || changed;
}
@@ -273,6 +286,34 @@ export class HaStateControlCover extends LitElement {
}
};
private _nextDrawnMotion(): DrawnMotion {
if (this._drag && this.mode === "position") {
return "drag";
}
const afterDrag = this._drawnMotion !== "follow";
const distance = Math.abs(
this._drawnPosition.value - this._coverSprings.position.value
);
if (afterDrag && distance > 0.5) {
return "return";
}
return "follow";
}
private _moveDrawnPosition(dt: number): boolean {
const drawn = this._drawnPosition;
const cover = this._coverSprings.position.value;
this._drawnMotion = this._nextDrawnMotion();
switch (this._drawnMotion) {
case "drag":
return drawn.jumpTo(this._handleSprings.position.value);
case "return":
return this._moveSpring(drawn, cover, dt, RETURN_SPRING);
default:
return drawn.jumpTo(cover);
}
}
private _moveSpring(
spring: PercentSpring,
goal: number,
@@ -311,11 +352,7 @@ export class HaStateControlCover extends LitElement {
return "follow";
}
private _moveHandle(
mode: CoverControlMode,
goal: number,
dt: number
): boolean {
private _moveHandle(mode: CoverControlMode, dt: number): boolean {
const handle = this._handleSprings[mode];
const motion = this._handleMotion(mode);
this._handleMotions[mode] = motion;
@@ -327,7 +364,12 @@ export class HaStateControlCover extends LitElement {
case "request":
return this._moveSpring(handle, this.request!.value, dt);
case "return":
return this._moveSpring(handle, goal, dt);
return this._moveSpring(
handle,
this._coverSprings[mode].value,
dt,
RETURN_SPRING
);
default:
return handle.jumpTo(this._coverSprings[mode].value);
}
@@ -625,17 +667,17 @@ export class HaStateControlCover extends LitElement {
);
}
private _renderTarget(shape: CoverShape, value: number) {
return svg`
${shape.targetShape?.(value) ?? nothing}
${shape.targetLine ? svg`<path class="target-line" d=${shape.targetLine(value)}></path>` : nothing}
`;
private _renderTargetLine(shape: CoverShape, value: number) {
if (!shape.targetLine) {
return nothing;
}
return svg`<path class="target-line" d=${shape.targetLine(value)}></path>`;
}
private _renderHandle(shape: CoverShape, value: number) {
const [cx, cy] = shape.handleAt(value);
if (shape.handle !== "gauge") {
return pillHandle(cx, cy, isHorizontal(shape));
return knobHandle(cx, cy, isHorizontal(shape));
}
const [, railTop] = shape.handleAt(100);
const [, railBottom] = shape.handleAt(0);
@@ -653,9 +695,20 @@ export class HaStateControlCover extends LitElement {
`;
}
private _renderMovingHint(angle: number) {
private _movingHintAnchor(): number {
if (this.request?.mode === this.mode) {
return this.request.value;
}
return this._coverSprings[this.mode].value;
}
private _renderMovingHint(shape: CoverShape, angle: number) {
const anchor = this._movingHintAnchor();
const [x, y] = shape.handleAt(
anchor >= 50 ? anchor / 2 : (anchor + 100) / 2
);
return svg`
<g transform="translate(${FRAME.centerX} ${FRAME.centerY}) rotate(${angle})">
<g transform="translate(${x} ${y}) rotate(${angle})">
<g class="moving-hint">
<path class="chevron back" d="M-6 6.5 L0 0.5 L6 6.5"></path>
<path class="chevron" d="M-6 -0.5 L0 -6.5 L6 -0.5"></path>
@@ -693,7 +746,7 @@ export class HaStateControlCover extends LitElement {
const withHandle = interactive && (!unknown || changing);
const withTarget = changing && (unknown || Math.abs(handle - cover) > 1);
const parts = shape.render({
position: this._coverSprings.position.value,
position: this._drawnPosition.value,
tiltOpenness: this._drawnTiltOpenness(),
wave: this._wave,
});
@@ -738,8 +791,9 @@ export class HaStateControlCover extends LitElement {
>
<g clip-path="url(#opening-clip)">
${this._renderSky()} ${parts.back ?? nothing}
${unknown ? nothing : parts.cover} ${parts.front ?? nothing}
${withTarget ? this._renderTarget(shape, handle) : nothing}
${unknown && this._drawnMotion === "follow" ? nothing : parts.cover}
${parts.front ?? nothing}
${withTarget ? this._renderTargetLine(shape, handle) : nothing}
</g>
<rect
class="opening-edge"
@@ -749,7 +803,7 @@ export class HaStateControlCover extends LitElement {
height=${height + 1}
rx="12.5"
></rect>
${movingHintAngle !== undefined ? this._renderMovingHint(movingHintAngle) : nothing}
${movingHintAngle !== undefined ? this._renderMovingHint(shape, movingHintAngle) : nothing}
${withHandle ? this._renderHandle(shape, handle) : nothing}
</g>
</svg>
@@ -794,6 +848,7 @@ export class HaStateControlCover extends LitElement {
display: block;
width: 100%;
height: 100%;
overflow: visible;
}
.moving-hint {
animation: drift 1.4s linear infinite;
+1 -2
View File
@@ -1,6 +1,6 @@
import { svg } from "lit";
import type { CoverShape } from "./shared";
import { FRAME, ghost, headrail, valueAxis } from "./shared";
import { FRAME, headrail, valueAxis } from "./shared";
const SCALLOPS = 8;
const SCALLOP_WIDTH = FRAME.width / SCALLOPS;
@@ -44,5 +44,4 @@ export const awningShape: CoverShape = {
const bottom = hemY(value);
return `M${FRAME.right},${bottom}${scallops(bottom)}`;
},
targetShape: (value) => ghost(svg`<path d=${outline(hemY(value))}></path>`),
};
+1 -5
View File
@@ -1,7 +1,7 @@
import { svg } from "lit";
import { clamp } from "../../../common/number/clamp";
import type { CoverShape } from "./shared";
import { FRAME, ghost, headrail, valueAxis } from "./shared";
import { FRAME, headrail, valueAxis } from "./shared";
const GATHERED = 22;
const ROWS = 12;
@@ -103,8 +103,4 @@ export const curtainShape: CoverShape = {
valueAt: (x) => freeEdge.valueAt(x),
targetLine: (value) =>
`M${freeEdge.coordAt(value).toFixed(1)} ${FRAME.top} V${FRAME.bottom}`,
targetShape: (value) =>
ghost(
svg`<rect x=${FRAME.left} y=${FRAME.top} width=${(freeEdge.coordAt(value) - FRAME.left).toFixed(1)} height=${FRAME.height}></rect>`
),
};
+2 -6
View File
@@ -1,7 +1,7 @@
import type { SVGTemplateResult } from "lit";
import { svg } from "lit";
import type { CoverShape } from "./shared";
import { FRAME, ghost, headrail, horizontalLine, valueAxis } from "./shared";
import { FRAME, headrail, horizontalLine, valueAxis } from "./shared";
const HEADRAIL = 10.4;
const ROLL = 10;
@@ -17,16 +17,12 @@ const handleY = (value: number) => coverBottom.coordAt(value) - HANDLE_INSET;
export const rollingGeometry: Pick<
CoverShape,
"opens" | "handleAt" | "valueAt" | "targetLine" | "targetShape"
"opens" | "handleAt" | "valueAt" | "targetLine"
> = {
opens: "up",
handleAt: (value) => [FRAME.centerX, handleY(value)],
valueAt: (_x, y) => coverBottom.valueAt(y + HANDLE_INSET),
targetLine: (value) => horizontalLine(handleY(value)),
targetShape: (value) =>
ghost(
svg`<rect x=${FRAME.left} y=${FRAME.top} width=${FRAME.width} height=${(coverBottom.coordAt(value) - FRAME.top).toFixed(1)}></rect>`
),
};
const fabric = (bottom: number) =>
+1 -5
View File
@@ -38,13 +38,12 @@ export type OpeningDirection = "up" | "down" | "left";
export interface CoverShape {
opens: OpeningDirection;
handle?: "pill" | "gauge";
handle?: "knob" | "gauge";
usesWave?: boolean;
render(input: CoverShapeInput): CoverShapeParts;
handleAt(value: number): [number, number];
valueAt(x: number, y: number): number;
targetLine?(value: number): string;
targetShape?(value: number): SVGTemplateResult;
}
export const isHorizontal = (shape: CoverShape) => shape.opens === "left";
@@ -68,9 +67,6 @@ export const tiltGeometry: Pick<
valueAt: (_x, y) => tiltAxis.valueAt(y),
};
export const ghost = (shape: SVGTemplateResult, opacity = 0.22) =>
svg`<g class="ghost" opacity=${opacity}>${shape}</g>`;
export const horizontalLine = (y: number, inset = 0) =>
`M${FRAME.left + inset} ${y.toFixed(1)} H${FRAME.right - inset}`;
+1 -5
View File
@@ -1,6 +1,6 @@
import { svg } from "lit";
import type { CoverShape } from "./shared";
import { FRAME, ghost, valueAxis } from "./shared";
import { FRAME, valueAxis } from "./shared";
const TRAVEL = FRAME.width - 28;
const GATE_TOP = FRAME.top + FRAME.height * 0.36;
@@ -50,8 +50,4 @@ export const slideShape: CoverShape = {
valueAt: (x) => leadingEdge.valueAt(x),
targetLine: (value) =>
`M${leadingEdge.coordAt(value).toFixed(1)} ${GATE_TOP} V${GROUND}`,
targetShape: (value) =>
ghost(
svg`<rect x=${gateLeft(value)} y=${GATE_TOP} width=${FRAME.width} height=${GATE_HEIGHT} rx="2"></rect>`
),
};
+24 -17
View File
@@ -367,26 +367,10 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
);
this._updateHass({ systemData: {} });
});
clearInterval(this.__backendPingInterval);
this._refreshBrandsAccessToken();
this.__backendPingInterval = setInterval(() => {
if (this.hass?.connected) {
// If the backend is busy, or the connection is latent,
// it can take more than 10 seconds for the ping to return.
// We give it a 15 second timeout to be safe.
promiseTimeout(15000, this.hass?.connection.ping()).catch(() => {
if (!this.hass?.connected) {
return;
}
// eslint-disable-next-line no-console
console.log("Websocket died, forcing reconnect...");
this.hass?.connection.reconnect(true);
});
}
}, 30000);
this._startBackendPing();
}
protected hassReconnected() {
@@ -397,6 +381,8 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
this._refreshBrandsAccessToken();
this._startBackendPing();
// on reconnect always fetch config as we might miss an update while we were disconnected
// @ts-ignore
this.hass!.callWS({ type: "get_config" }).then((config: HassConfig) => {
@@ -417,6 +403,27 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
clearBrandsTokenRefresh();
}
private _startBackendPing() {
clearInterval(this.__backendPingInterval);
this.__backendPingInterval = setInterval(() => {
if (this.hass?.connected) {
// If the backend is busy, or the connection is latent,
// it can take more than 10 seconds for the ping to return.
// We give it a 15 second timeout to be safe.
promiseTimeout(15000, this.hass?.connection.ping()).catch(() => {
if (!this.hass?.connected) {
return;
}
// eslint-disable-next-line no-console
console.log("Websocket died, forcing reconnect...");
this.hass?.connection.reconnect(true);
});
}
}, 30000);
}
private async _refreshBrandsAccessToken() {
// The brands WS handler may not be registered yet after a server restart;
// fetchAndScheduleBrandsAccessToken retries internally. If the token
+1
View File
@@ -4804,6 +4804,7 @@
"dismiss_failed": "Couldn't dismiss this meter",
"dismiss_all": "Dismiss all",
"dismiss_all_failed": "Couldn't dismiss these meters",
"show_more": "Show {count} more",
"show_dismissed": "Show dismissed meters ({count})",
"hide_dismissed": "Hide dismissed meters",
"dismissed": "Dismissed",
@@ -173,7 +173,7 @@ describe("ConditionEvaluatorController", () => {
cond({
condition: "not",
conditions: [
{ condition: "user", users: ["other"] },
{ condition: "user", users: ["user1"] },
{ condition: "template", value_template: "{{ broken" },
],
}),
@@ -184,6 +184,27 @@ describe("ConditionEvaluatorController", () => {
expect(controller.error).toBe("bad");
});
it("shows when an or matches despite a subscription error in another branch", async () => {
const { controller } = await setup([
cond({
condition: "or",
conditions: [
{ condition: "user", users: ["user1"] },
{
condition: "or",
conditions: [
{ condition: "state", entity: "person.a", state: "home" },
{ condition: "state", entity: "sensor.missing", state: "on" },
],
},
],
}),
]);
expect(subs).toHaveLength(1);
subs[0].push({ error: "In 'or': unknown entity sensor.missing" });
expect(controller.result).toBe("visible");
});
it("surfaces template errors without overriding the result", async () => {
// Template render errors are flagged; they don't force hidden.
const { controller, last } = await setup([
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import {
shouldPolyfillNumberFormat,
shouldPolyfillPluralRules,
} from "../../../src/resources/polyfills/intl-should-polyfill";
// The PluralRules polyfill only has English data, so replacing a working
// native Intl.PluralRules drops plural forms like "few" and "many"
describe("Intl polyfill checks", () => {
it("works", () => {
for (const locale of ["en", "de", "ru", "pl", "ar"]) {
expect(shouldPolyfillPluralRules(locale)).toBe(false);
expect(shouldPolyfillNumberFormat(locale)).toBe(false);
}
expect(shouldPolyfillPluralRules("xx")).toBe(true);
expect(shouldPolyfillNumberFormat("xx")).toBe(true);
});
});
+49
View File
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { connectionMixin } from "../../src/state/connection-mixin";
import { HassBaseEl } from "../../src/state/hass-base-mixin";
import type { HomeAssistant } from "../../src/types";
vi.mock("../../src/util/brands-url", async (importOriginal) => ({
...(await importOriginal<object>()),
clearBrandsTokenRefresh: vi.fn(),
fetchAndScheduleBrandsAccessToken: vi.fn(() => Promise.resolve(false)),
}));
class ConnectionElement extends connectionMixin(HassBaseEl) {
public reconnect() {
this.hassDisconnected();
this.hassReconnected();
}
}
customElements.define("test-connection-element", ConnectionElement);
declare global {
interface HTMLElementTagNameMap {
"test-connection-element": ConnectionElement;
}
}
describe("connection mixin backend ping", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("pings the backend again after a reconnect", () => {
const ping = vi.fn(() => Promise.resolve());
const element = new ConnectionElement();
element.hass = {
connected: true,
connection: { ping },
callWS: vi.fn(() => Promise.resolve({})),
} as unknown as HomeAssistant;
element.reconnect();
vi.advanceTimersByTime(30000);
expect(ping).toHaveBeenCalledTimes(1);
});
});
-6
View File
@@ -118,15 +118,9 @@
"@formatjs/intl-locale/polyfill-force": [
"./node_modules/@formatjs/intl-locale/polyfill-force.js"
],
"@formatjs/intl-numberformat/should-polyfill": [
"./node_modules/@formatjs/intl-numberformat/should-polyfill.js"
],
"@formatjs/intl-numberformat/polyfill-force": [
"./node_modules/@formatjs/intl-numberformat/polyfill-force.js"
],
"@formatjs/intl-pluralrules/should-polyfill": [
"./node_modules/@formatjs/intl-pluralrules/should-polyfill.js"
],
"@formatjs/intl-pluralrules/polyfill-force": [
"./node_modules/@formatjs/intl-pluralrules/polyfill-force.js"
],