Compare commits

..
Author SHA1 Message Date
Petar Petrov ae75b0fbb3 Keep unchanged registry objects in the collection stores (#56331)
* Keep unchanged registry objects in the collection stores

After a refetch, hass.devices, hass.entities, hass.areas and hass.floors kept
their unchanged objects while the collection stores held the refetched ones,
so every device and entity entry existed twice. Reuse unchanged items in the
stores on every refetch so both share the same objects.

* Move the registry reuse into connection-mixin

core.ts creates the registry collections, so doing the reuse in their
fetch pulled deepEqual and Set polyfills into the core entry and broke
its size budget. connection-mixin now puts the unchanged previous items
back into the store's list before it builds hass.
2026-12-01 20:56:55 +01:00
Petar Petrov f821581318 Drop hass from the location selector (#56325)
* Drop hass from the location selector

Read localize, locale and config from contexts and pass the language to searchPlaces.

* Show a spinner until the location selector has the core config

The map has no marker and ignores clicks without it.
2026-12-01 20:19:31 +01:00
Petar Petrov d2ed5c57de Drop hass from ha-media-item-picker and ha-selector-media (#56326)
Read localize and the media player's browse support from contexts.
2026-12-01 20:18:00 +01:00
Petar Petrov 0c343898e6 Clear the lazy context value when its subscription ends (#56332)
* Clear the lazy context value when its subscription ends

The provider kept the last value, such as the full entity registry, after
the idle teardown. Clear it, as the comment there already described.

* Test that the lazy context value is cleared after the idle teardown
2026-12-01 19:58:12 +01:00
Petar Petrov 7a8696c237 Keep only callWS in the brands token refresh (#56330)
The 30 minute refresh interval kept the hass object it was given. After a
reconnect that was an old copy of every state. Pass callWS instead.
2026-12-01 19:56:55 +01:00
Petar Petrov f1cd21de5d Fix category picker reconnect and pass separate values to alarm helper (#56328)
Clear the category picker's list on disconnect so a reconnect with a new scope shows a loading state instead of the old scope's categories, and give setProtectedAlarmControlPanelMode separate callService, callWS and localize arguments.
2026-12-01 19:56:01 +01:00
Petar Petrov 570a781d60 Pass separate values to panel title helpers (#56327)
getPanelTitle and getPanelTitleFromUrlPath take localize and panels instead of a Pick of HomeAssistant.
2026-12-01 19:53:11 +01:00
Petar Petrov db9e222753 Stop entity rows from keeping old hass objects (#56335)
* Stop entity rows from keeping old hass objects

Rows only re-render when their own entity changes, so the hass bound to
hui-generic-entity-row kept the states map from that render alive. Rows
now pass stateObj, and the generic row and the entities header toggle
read the rest from contexts.

* Handle card actions in gallery demos

Entity rows now fire hass-action, which the standalone gallery demos did not handle, so row taps did nothing there.
2026-12-01 18:49:09 +01:00
renovate[bot] dd29acff7c Update dependency cally to v0.10.1 (#56338)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 19:08:34 +02:00
ljlongwingandClaude Opus 5.5 db8a8b5b41 Push the other setpoint when a temperature range target passes it (#56289)
* Push the other setpoint when a temperature range target passes it

Dragging or stepping the low target of a climate range up to the high
target stopped it there, and the same for high going down. Push the
other target along instead, as thermostats such as Nest do, so the
range can be moved in one gesture. The integration still decides the
minimum gap between the two.

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

* Restore pushed handle on drag back and clamp to min/max

When dragging one handle of the dual circular slider past the other and
back in the same gesture, the pushed handle now returns to where it was
before the push started, so the handles match the displayed and
submitted targets. The dial's target temperature is clamped to the
entity's min/max again before the push is applied, since the slider can
round past the maximum.

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

* Keep stepped slider values within min/max and update gallery

Rounding to the step happens after the value is bounded, so a max that
isn't a multiple of the step (max 35, step 2) left 36 as the slider's
internal value, making the next keyboard step start from 36. Clamp the
stepped value to min/max as well.

The circular slider gallery page now pushes the other handle the same
way, so its stored range stays in order.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 17:32:15 +01:00
85 changed files with 687 additions and 897 deletions

No files matched your search

+2 -1
View File
@@ -73,7 +73,8 @@ class HcLovelace extends LitElement {
if (index !== undefined) {
const title = getPanelTitleFromUrlPath(
this.hass,
this.hass.localize,
this.hass.panels,
this.urlPath || "lovelace"
);
+2 -1
View File
@@ -355,7 +355,8 @@ export class HcMain extends HassElement {
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
const title = getPanelTitleFromUrlPath(
this.hass!,
this.hass!.localize,
this.hass!.panels,
this._urlPath || "lovelace"
);
castContext.setApplicationState(title || "");
+12
View File
@@ -1,6 +1,8 @@
import type { PropertyValues } from "lit";
import { html, css, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../src/components/ha-switch";
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
import type { HomeAssistant } from "../../../src/types";
import "./demo-card";
import type { DemoCardConfig } from "./demo-card";
@@ -14,6 +16,16 @@ class DemoCards extends LitElement {
@state() private _showConfig = false;
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
// Handles card actions like the app's action mixin
this.addEventListener("hass-action", (ev) => {
ev.stopPropagation();
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
});
}
render() {
return html`
<ha-demo-options>
@@ -22,20 +22,27 @@ export class DemoHaCircularSlider extends LitElement {
@state()
private changingHigh?: number;
// A handle that passes the other one pushes it along, like the slider does
private _lowChanged(ev) {
this.low = ev.detail.value;
this.high = Math.max(this.high, this.low);
}
private _lowChanging(ev) {
this.changingLow = ev.detail.value;
const value = ev.detail.value;
this.changingLow = value;
this.changingHigh = value != null && value > this.high ? value : undefined;
}
private _highChanged(ev) {
this.high = ev.detail.value;
this.low = Math.min(this.low, this.high);
}
private _highChanging(ev) {
this.changingHigh = ev.detail.value;
const value = ev.detail.value;
this.changingHigh = value;
this.changingLow = value != null && value < this.low ? value : undefined;
}
private _currentChanged(ev) {
+1 -1
View File
@@ -84,7 +84,7 @@
"@vvo/tzdb": "6.208.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
"barcode-detector": "3.2.5",
"cally": "0.10.0",
"cally": "0.10.1",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
+5 -5
View File
@@ -331,8 +331,8 @@ importers:
specifier: 3.2.5
version: 3.2.5
cally:
specifier: 0.10.0
version: 0.10.0
specifier: 0.10.1
version: 0.10.1
color-name:
specifier: 2.1.1
version: 2.1.1
@@ -4434,8 +4434,8 @@ packages:
resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}
engines: {node: '>= 0.4'}
[email protected].0:
resolution: {integrity: sha512-awpa0UByh5O0bETxTpMX1MpTHiijKVxbPj/+Kgfmpsfh1/onEeYx6ag1swtbKzYFpCci2Zo65H1fU/M2Uwu/eA==}
[email protected].1:
resolution: {integrity: sha512-zBz8ygOnVpkkuaGq0RKa4/j8ZAkrePonivLhuXmm7Qu9bbK2+MXJCGeZX7rlUDWPnd+5GDyoudwjE5uQz/meaA==}
[email protected]:
resolution: {integrity: sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==}
@@ -12289,7 +12289,7 @@ snapshots:
call-bind-apply-helpers: 1.0.2
get-intrinsic: 1.3.1
[email protected].0:
[email protected].1:
dependencies:
atomico: 1.79.2
@@ -37,3 +37,29 @@ export const preserveUnchangedRecord = <T>(
}
return changed ? next : previous;
};
/**
* List variant of {@link preserveUnchangedRecord}: replaces each item in `next`
* with the equal `previous` item that has the same key, in place.
*/
export const preserveUnchangedItems = <T>(
previous: readonly T[] | undefined,
next: T[],
getKey: (item: T) => string,
equal: (a: T, b: T) => boolean
): T[] => {
if (!previous?.length) {
return next;
}
const previousByKey = new Map<string, T>();
for (const item of previous) {
previousByKey.set(getKey(item), item);
}
for (let i = 0; i < next.length; i++) {
const previousItem = previousByKey.get(getKey(next[i]));
if (previousItem !== undefined && equal(previousItem, next[i])) {
next[i] = previousItem;
}
}
return next;
};
+20 -10
View File
@@ -111,6 +111,11 @@ export class HaControlCircularSlider extends LitElement {
@state() public _lastSlider?: ActiveSlider;
// Position of the other handle before the active one started pushing it
private _lowBeforePush?: number;
private _highBeforePush?: number;
private _valueToPercentage(value: number) {
return (
(clamp(value, this.min, this.max) - this.min) / (this.max - this.min)
@@ -122,19 +127,12 @@ export class HaControlCircularSlider extends LitElement {
}
private _steppedValue(value: number) {
return Math.round(value / this.step) * this.step;
// Rounding to the step can overshoot min/max when they aren't multiples of it
return clamp(Math.round(value / this.step) * this.step, this.min, this.max);
}
private _boundedValue(value: number) {
const min =
this._activeSlider === "high"
? Math.min(this._localLow ?? this.max)
: this.min;
const max =
this._activeSlider === "low"
? Math.max(this._localHigh ?? this.min)
: this.max;
return Math.min(Math.max(value, min), max);
return Math.min(Math.max(value, this.min), this.max);
}
protected updated(changedProps: PropertyValues): void {
@@ -152,6 +150,8 @@ export class HaControlCircularSlider extends LitElement {
});
}
if (!this._activeSlider) {
this._lowBeforePush = undefined;
this._highBeforePush = undefined;
if (changedProps.has("value")) {
this._localValue = this.value;
}
@@ -235,9 +235,19 @@ export class HaControlCircularSlider extends LitElement {
switch (this._activeSlider) {
case "high":
this._localHigh = value;
// Push the low handle along instead of stopping at it, and let it
// return to where it was if the drag comes back
if (this._localLow != null) {
this._lowBeforePush ??= this._localLow;
this._localLow = Math.min(this._lowBeforePush, value);
}
break;
case "low":
this._localLow = value;
if (this._localHigh != null) {
this._highBeforePush ??= this._localHigh;
this._localHigh = Math.max(this._highBeforePush, value);
}
break;
case "value":
this._localValue = value;
+47 -31
View File
@@ -1,17 +1,23 @@
import { mdiDelete, mdiPlayBox, mdiPlus } from "@mdi/js";
import type { HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { supportsFeature } from "../common/entity/supports-feature";
import type { LocalizeFunc } from "../common/translations/localize";
import { statesContext } from "../data/context";
import type { MediaPickedEvent } from "../data/media-player";
import {
MediaClassBrowserSettings,
MediaPlayerEntityFeature,
} from "../data/media-player";
import type { MediaSelector, MediaSelectorValue } from "../data/selector";
import type { HomeAssistant } from "../types";
import "./ha-alert";
import "./ha-form/ha-form";
import type { SchemaUnion } from "./ha-form/types";
@@ -31,8 +37,6 @@ const EMPTY_FORM = {};
@customElement("ha-media-item-picker")
export class HaMediaItemPicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: MediaSelector;
@property({ attribute: false }) public value?: MediaSelectorValue;
@@ -51,6 +55,26 @@ export class HaMediaItemPicker extends LitElement {
filter_entity?: string | string[];
};
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HassEntities | null, boolean>({
transformer: function (this: HaMediaItemPicker, states) {
const entityId = this._getActiveEntityId();
if (!entityId) {
return true;
}
const stateObj = states?.[entityId];
return (
!!stateObj &&
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA)
);
},
watch: ["value", "context"],
})
private _supportsBrowse?: boolean;
private _contextEntities: string[] | undefined;
private get _hasAccept(): boolean {
@@ -68,13 +92,6 @@ export class HaMediaItemPicker extends LitElement {
protected render() {
const entityId = this._getActiveEntityId();
const stateObj = entityId ? this.hass.states[entityId] : undefined;
const supportsBrowse =
!entityId ||
(stateObj &&
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA));
if (this.selector.media?.image_upload && !this.value) {
return html`${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-picture-upload
@@ -98,7 +115,7 @@ export class HaMediaItemPicker extends LitElement {
.value=${entityId}
.label=${
this.label ||
this.hass.localize(
this._localize(
"ui.components.selectors.media.pick_media_player"
)
}
@@ -114,20 +131,19 @@ export class HaMediaItemPicker extends LitElement {
`
}
${
!supportsBrowse
this._supportsBrowse === false
? html`
${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-alert>
${this.hass.localize(
${this._localize(
"ui.components.selectors.media.browse_not_supported"
)}
</ha-alert>
<ha-form
.hass=${this.hass}
.data=${this.value || EMPTY_FORM}
.schema=${MANUAL_SCHEMA}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
.computeLabel=${this._computeLabel(this._localize)}
.computeHelper=${this._computeHelper(this._localize)}
></ha-form>
`
: html`${this.label ? html`<label>${this.label}</label>` : nothing}
@@ -137,9 +153,7 @@ export class HaMediaItemPicker extends LitElement {
role="button"
aria-label=${
!this.value?.media_content_id
? this.hass.localize(
"ui.components.selectors.media.pick_media"
)
? this._localize("ui.components.selectors.media.pick_media")
: this.value.metadata?.title || this.value.media_content_id
}
@click=${this._pickMedia}
@@ -196,7 +210,7 @@ export class HaMediaItemPicker extends LitElement {
<div class="title">
${
!this.value?.media_content_id
? this.hass.localize(
? this._localize(
"ui.components.selectors.media.pick_media"
)
: this.value.metadata?.title ||
@@ -209,7 +223,7 @@ export class HaMediaItemPicker extends LitElement {
: html`
<div class="delete">
<ha-icon-button
.label=${this.hass.localize("ui.common.delete")}
.label=${this._localize("ui.common.delete")}
.path=${mdiDelete}
@click=${this._clearValue}
></ha-icon-button>
@@ -227,7 +241,7 @@ export class HaMediaItemPicker extends LitElement {
variant="danger"
@click=${this._clearValue}
>
${this.hass.localize(
${this._localize(
"ui.components.picture-upload.clear_picture"
)}
</ha-button>
@@ -243,15 +257,17 @@ export class HaMediaItemPicker extends LitElement {
`;
}
private _computeLabelCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}`);
private _computeLabel = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}`)
);
private _computeHelperCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}_detail`);
private _computeHelper = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}_detail`)
);
private _entityChanged(ev: CustomEvent) {
ev.stopPropagation();
@@ -1,10 +1,14 @@
import { mdiMagnify, mdiMapSearchOutline } from "@mdi/js";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import { transform } from "../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { configContext, internationalizationContext } from "../../data/context";
import type {
LocationSelector,
LocationSelectorValue,
@@ -14,7 +18,10 @@ import {
formatOpenStreetMapPlace,
searchPlaces,
} from "../../data/openstreetmap";
import type { HomeAssistant } from "../../types";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../types";
import type { SchemaUnion } from "../ha-form/types";
import type { HaListItemButton } from "../item/ha-list-item-button";
import { searchResultsStatus } from "../list/search-results-status";
@@ -28,6 +35,7 @@ import "../ha-alert";
import "../ha-icon-button";
import "../item/ha-list-item-button";
import "../list/ha-list-base";
import "../animation/ha-fade-in";
import "../ha-spinner";
import "../ha-svg-icon";
import "../input/ha-input";
@@ -39,8 +47,6 @@ import {
@customElement("ha-selector-location")
export class HaLocationSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: LocationSelector;
@property({ type: Object }) public value?: LocationSelectorValue;
@@ -51,6 +57,17 @@ export class HaLocationSelector extends LitElement {
@property({ type: Boolean, reflect: true }) public disabled = false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig | undefined>({
transformer: ({ config }) => config ?? undefined,
})
private _hassConfig?: HassConfig;
@state() private _working = false;
@state() private _places?: OpenStreetMapPlace[] | null;
@@ -106,10 +123,10 @@ export class HaLocationSelector extends LitElement {
);
protected willUpdate() {
if (!this.value) {
if (!this.value && this._hassConfig) {
this.value = {
latitude: this.hass.config.latitude,
longitude: this.hass.config.longitude,
latitude: this._hassConfig.latitude,
longitude: this._hassConfig.longitude,
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
};
}
@@ -121,7 +138,7 @@ export class HaLocationSelector extends LitElement {
<div class="location-search" @keydown=${this._searchKeyDown}>
<ha-input
label=${this.hass.localize(
label=${this._i18n.localize(
"ui.components.selectors.location.address_label"
)}
.disabled=${this.disabled}
@@ -137,7 +154,7 @@ export class HaLocationSelector extends LitElement {
: html`<ha-icon-button
slot="end"
.path=${mdiMapSearchOutline}
.label=${this.hass.localize("ui.common.search")}
.label=${this._i18n.localize("ui.common.search")}
.disabled=${this.disabled}
@click=${this._searchButtonClicked}
></ha-icon-button>`
@@ -147,7 +164,7 @@ export class HaLocationSelector extends LitElement {
${
this._searchError
? html`<ha-alert alert-type="error">
${this.hass.localize(
${this._i18n.localize(
"ui.components.selectors.location.search_error"
)}
</ha-alert>`
@@ -165,7 +182,7 @@ export class HaLocationSelector extends LitElement {
Array.isArray(this._places) && this._places.length
? html`
<ha-list-base
aria-label=${this.hass.localize(
aria-label=${this._i18n.localize(
"ui.components.selectors.location.search_results_label"
)}
>
@@ -174,13 +191,13 @@ export class HaLocationSelector extends LitElement {
`
: this._places?.length === 0
? html`<p class="search-no-results">
${this.hass.localize("ui.components.combo-box.no_match")}
${this._i18n.localize("ui.components.combo-box.no_match")}
</p>`
: nothing
}
<p class="attribution">
${this.hass.localize(
${this._i18n.localize(
"ui.components.selectors.location.search_disclosure",
{
openstreetmap: html`<a
@@ -193,7 +210,7 @@ export class HaLocationSelector extends LitElement {
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
target="_blank"
rel="noopener noreferrer"
>${this.hass.localize(
>${this._i18n.localize(
"ui.components.selectors.location.osm_privacy_policy"
)}</a
>`,
@@ -202,18 +219,27 @@ export class HaLocationSelector extends LitElement {
</p>
</div>
<ha-locations-editor
class="flex"
.helper=${this.helper}
.locations=${this._location(this.selector, this.value)}
@location-updated=${this._locationChanged}
@radius-updated=${this._radiusChanged}
pin-on-click
></ha-locations-editor>
${
this._hassConfig
? html`<ha-locations-editor
class="flex"
.helper=${this.helper}
.locations=${this._location(
this.selector,
this._hassConfig,
this.value
)}
@location-updated=${this._locationChanged}
@radius-updated=${this._radiusChanged}
pin-on-click
></ha-locations-editor>`
: html`<ha-fade-in .delay=${500}
><ha-spinner></ha-spinner
></ha-fade-in>`
}
<ha-form
.hass=${this.hass}
.schema=${this._schema(
this.hass.localize,
this._i18n.localize,
this.selector.location?.radius,
this.selector.location?.radius_readonly
)}
@@ -228,6 +254,7 @@ export class HaLocationSelector extends LitElement {
private _location = memoizeOne(
(
selector: LocationSelector,
hassConfig: HassConfig,
value?: LocationSelectorValue
): MarkerLocation[] => {
const computedStyles = getComputedStyle(this);
@@ -240,11 +267,11 @@ export class HaLocationSelector extends LitElement {
id: "location",
latitude:
!value || isNaN(value.latitude)
? this.hass.config.latitude
? hassConfig.latitude
: value.latitude,
longitude:
!value || isNaN(value.longitude)
? this.hass.config.longitude
? hassConfig.longitude
: value.longitude,
radius: selector.location?.radius
? value?.radius || DEFAULT_RADIUS
@@ -286,7 +313,7 @@ export class HaLocationSelector extends LitElement {
entry: SchemaUnion<ReturnType<typeof this._schema>>
): string => {
if (entry.name) {
return this.hass.localize(
return this._i18n.localize(
`ui.components.selectors.location.${entry.name}`
);
}
@@ -337,12 +364,17 @@ export class HaLocationSelector extends LitElement {
this._status = undefined;
try {
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
this._places = await searchPlaces(
searchTerm,
this._i18n.locale.language,
true,
3
);
this._status = searchResultsStatus(
searchTerm,
this._places,
() => true,
this.hass.localize
this._i18n.localize
);
} catch (_err) {
this._places = undefined;
@@ -398,7 +430,7 @@ export class HaLocationSelector extends LitElement {
this._input?.focus({ preventScroll: true });
}
this._places = undefined;
this._status = this.hass.localize(
this._status = this._i18n.localize(
"ui.components.selectors.location.selected_location",
{ location: place.display_name }
);
@@ -1,15 +1,12 @@
import { html, LitElement, type TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import type { MediaSelector, MediaSelectorValue } from "../../data/selector";
import type { HomeAssistant } from "../../types";
import "../ha-media-item-picker";
import { ensureArray } from "../../common/array/ensure-array";
import { fireEvent } from "../../common/dom/fire_event";
@customElement("ha-selector-media")
export class HaMediaSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: MediaSelector;
@property({ attribute: false }) public value?:
@@ -34,7 +31,6 @@ export class HaMediaSelector extends LitElement {
changeCallback?
): TemplateResult {
return html`<ha-media-item-picker
.hass=${this.hass}
.context=${this.context}
.selector=${this.selector}
.value=${value}
+1 -1
View File
@@ -474,7 +474,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
}
private _renderPanel(panel: PanelInfo, isSelected: boolean) {
const title = getPanelTitle(this.hass, panel);
const title = getPanelTitle(this.hass.localize, panel);
const urlPath = panel.url_path;
const icon = getPanelIcon(panel);
const iconPath = getPanelIconPath(panel);
+8 -5
View File
@@ -11,6 +11,7 @@ import type {
HassEntityBase,
} from "home-assistant-js-websocket";
import { supportsFeature } from "../common/entity/supports-feature";
import type { LocalizeFunc } from "../common/translations/localize";
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
import type { HomeAssistant } from "../types";
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
@@ -108,7 +109,9 @@ export const supportedAlarmModes = (stateObj: AlarmControlPanelEntity) =>
export const setProtectedAlarmControlPanelMode = async (
element: HTMLElement,
hass: Pick<HomeAssistant, "callService" | "localize" | "callWS">,
callService: HomeAssistant["callService"],
callWS: HomeAssistant["callWS"],
localize: LocalizeFunc,
stateObj: AlarmControlPanelEntity,
mode: AlarmMode
) => {
@@ -123,7 +126,7 @@ export const setProtectedAlarmControlPanelMode = async (
(mode === "disarmed" && stateObj.attributes.code_format)
) {
const entry = await getExtendedEntityRegistryEntry(
hass.callWS,
callWS,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
@@ -133,10 +136,10 @@ export const setProtectedAlarmControlPanelMode = async (
const response = await showEnterCodeDialog(element, {
codeFormat: stateObj.attributes.code_format,
title: hass.localize(
title: localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
submitText: hass.localize(
submitText: localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
});
@@ -147,7 +150,7 @@ export const setProtectedAlarmControlPanelMode = async (
}
}
await hass.callService("alarm_control_panel", service, {
await callService("alarm_control_panel", service, {
entity_id: stateObj.entity_id,
code,
});
+20
View File
@@ -103,3 +103,23 @@ export const CLIMATE_HVAC_MODE_ICONS: Record<HvacMode, string> = {
export const climateHvacModeIcon = (mode: string) =>
CLIMATE_HVAC_MODE_ICONS[mode] || mdiThermostat;
export type ClimateTarget = "value" | "low" | "high";
/**
* The targets to change when one target is set. A low or high target that
* passes the other one pushes it along, so the range never ends up inverted.
*/
export const pushTargetTemperature = (
current: Partial<Record<ClimateTarget, number>>,
target: ClimateTarget,
value: number
): Partial<Record<ClimateTarget, number>> => {
if (target === "low" && current.high != null && value > current.high) {
return { low: value, high: value };
}
if (target === "high" && current.low != null && value < current.low) {
return { low: value, high: value };
}
return { [target]: value };
};
+6 -1
View File
@@ -158,7 +158,12 @@ export const computeNavigationPathInfo = (
const isDashboard = panel?.component_name === "lovelace";
const panelInfo: NavigationPathInfo = {
label: getPanelTitleFromUrlPath(options, panelUrlPath) || panelUrlPath,
label:
getPanelTitleFromUrlPath(
options.localize,
options.panels,
panelUrlPath
) || panelUrlPath,
icon: panelIcon || (isDashboard ? "mdi:view-dashboard" : undefined),
iconPath: panelIconPath || mdiLink,
};
+2 -1
View File
@@ -4,8 +4,9 @@ export const setDateTimeValue = (
callService: HomeAssistantApi["callService"],
entityId: string,
datetime: Date
) =>
) => {
callService("datetime", "set_value", {
entity_id: entityId,
datetime: datetime.toISOString(),
});
};
+1 -2
View File
@@ -38,8 +38,7 @@ export const setInputDateTimeValue = (
date: string | undefined = undefined
) => {
const param = { entity_id: entityId, time, date };
return callService("input_datetime", "set_datetime", param);
callService("input_datetime", "set_datetime", param);
};
export const fetchInputDateTime = (hass: HomeAssistant) =>
+2 -2
View File
@@ -62,14 +62,14 @@ export const formatOpenStreetMapPlace = (
export const searchPlaces = (
address: string,
hass: HomeAssistant,
language: string,
addressdetails?: boolean,
limit?: number
): Promise<OpenStreetMapPlace[]> => {
const params = new URLSearchParams({
q: address,
format: "jsonv2",
"accept-language": hass.locale.language,
"accept-language": language,
email: "[email protected]",
});
if (limit) {
+12 -8
View File
@@ -8,9 +8,12 @@ import {
mdiMap,
mdiPlayBoxMultiple,
} from "@mdi/js";
import type { LocalizeKeys } from "../common/translations/localize";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../common/translations/localize";
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
import type { HomeAssistant, PanelInfo } from "../types";
import type { HomeAssistant, PanelInfo, Panels } from "../types";
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
export const APP_PANEL = "app";
@@ -66,7 +69,7 @@ export const getPanelNameTranslationKey = (panel: PanelInfo) => {
};
export const getPanelTitle = (
hass: Pick<HomeAssistant, "localize">,
localize: LocalizeFunc,
panel: PanelInfo
): string | undefined => {
if (panel.url_path === "marketplace") {
@@ -75,18 +78,19 @@ export const getPanelTitle = (
const translationKey = getPanelNameTranslationKey(panel);
return hass.localize(translationKey) || panel.title || undefined;
return localize(translationKey) || panel.title || undefined;
};
export const getPanelTitleFromUrlPath = (
hass: Pick<HomeAssistant, "localize" | "panels">,
localize: LocalizeFunc,
panels: Panels,
urlPath: string
): string | undefined => {
if (!hass.panels) {
if (!panels) {
return undefined;
}
const panel = Object.values(hass.panels).find(
const panel = Object.values(panels).find(
(p: PanelInfo): boolean => p.url_path === urlPath
);
@@ -94,7 +98,7 @@ export const getPanelTitleFromUrlPath = (
return undefined;
}
return getPanelTitle(hass, panel);
return getPanelTitle(localize, panel);
};
/**
+1 -1
View File
@@ -57,7 +57,7 @@ const generateNavigationPanelCommands = (
.map(([_panelKey, panel]) => {
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
const primary = getPanelTitle(localize, panel) || panel.url_path;
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
+1 -2
View File
@@ -6,6 +6,5 @@ export const setTimeValue = (
time: string | undefined = undefined
) => {
const param = { entity_id: entityId, time: time };
return callService("time", "set_value", param);
callService("time", "set_value", param);
};
@@ -31,11 +31,9 @@ class MoreInfoAlarmControlPanel extends LitElement {
private async _disarm() {
setProtectedAlarmControlPanelMode(
this,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this._api.callService,
this._api.callWS,
this._localize,
this.stateObj!,
"disarmed"
);
+1 -1
View File
@@ -158,7 +158,7 @@ class DialogEditSidebar extends DirtyStateProviderMixin<SidebarState>()(
].map<DisplayItem>((panel) => ({
value: panel.url_path,
label:
(getPanelTitle(this.hass, panel) || panel.url_path) +
(getPanelTitle(this.hass.localize, panel) || panel.url_path) +
`${defaultPanel === panel.url_path ? ` (${this.hass.localize("ui.sidebar.default")})` : ""}`,
icon: getPanelIcon(panel),
iconPath: getPanelIconPath(panel),
+6 -1
View File
@@ -352,7 +352,12 @@ class OnboardingLocation extends LitElement {
}
);
try {
this._places = await searchPlaces(address, this.hass, true, 3);
this._places = await searchPlaces(
address,
this.hass.locale.language,
true,
3
);
if (this._places?.length) {
this._highlightedMarker = this._places[0].place_id;
this._location = [
@@ -86,6 +86,7 @@ export class HaCategoryPicker extends LitElement {
public disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeCategories();
this._categories = undefined;
}
protected willUpdate(changedProperties: PropertyValues) {
@@ -363,7 +363,8 @@ export class HaConfigLovelaceDashboards extends LitElement {
}
const item: DataTableItem = {
icon: getPanelIcon(panelInfo),
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
title:
getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
show_in_sidebar: panelInfo.show_in_sidebar || false,
mode: "storage",
url_path: panelInfo.url_path,
@@ -547,7 +548,7 @@ export class HaConfigLovelaceDashboards extends LitElement {
const defaultPanel = this.hass.systemData?.default_panel || DEFAULT_PANEL;
showPanelDetailDialog(this, {
urlPath: panelInfo.url_path,
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
title: getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
icon: getPanelIcon(panelInfo),
requireAdmin: panelInfo.require_admin || false,
showInSidebar: panelInfo.show_in_sidebar || false,
@@ -133,11 +133,9 @@ class HuiAlarmModeCardFeature
private async _setMode(mode: AlarmMode) {
await setProtectedAlarmControlPanelMode(
this,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this._api.callService,
this._api.callWS,
this._localize,
this._stateObj!,
mode
);
@@ -19,7 +19,10 @@ import "../../../components/ha-control-button-group";
import "../../../components/ha-control-number-buttons";
import "../../../components/ha-control-slider";
import type { ClimateEntity } from "../../../data/climate";
import { ClimateEntityFeature } from "../../../data/climate";
import {
ClimateEntityFeature,
pushTargetTemperature,
} from "../../../data/climate";
import {
apiContext,
configContext,
@@ -187,17 +190,9 @@ class HuiTargetTemperatureCardFeature
const target =
(ev.currentTarget as HTMLElement & { target?: Target }).target ?? "value";
// Sliders span the full range, so keep low and high from crossing
let newValue = value;
if (target === "low") {
newValue = Math.min(value, this._targetTemperature.high ?? value);
} else if (target === "high") {
newValue = Math.max(value, this._targetTemperature.low ?? value);
}
this._targetTemperature = {
...this._targetTemperature,
[target]: newValue,
...pushTargetTemperature(this._targetTemperature, target, value),
};
this._pendingSync.schedule();
this._debouncedCallService(target);
@@ -380,10 +375,7 @@ class HuiTargetTemperatureCardFeature
.value=${this._targetTemperature.low}
.unit=${this._hassConfig?.unit_system.temperature}
.min=${this._min}
.max=${Math.min(
this._max,
this._targetTemperature.high ?? this._max
)}
.max=${this._max}
.step=${this._step}
@value-changed=${this._valueChanged}
.label=${this._formatters.formatEntityAttributeName(
@@ -402,10 +394,7 @@ class HuiTargetTemperatureCardFeature
.target=${"high"}
.value=${this._targetTemperature.high}
.unit=${this._hassConfig?.unit_system.temperature}
.min=${Math.max(
this._min,
this._targetTemperature.low ?? this._min
)}
.min=${this._min}
.max=${this._max}
.step=${this._step}
@value-changed=${this._valueChanged}
@@ -1,477 +0,0 @@
import { TZDate } from "@date-fns/tz";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { resolveTimeZone } from "../../../common/datetime/resolve-time-zone";
import { useAmPm } from "../../../common/datetime/use_am_pm";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-control-select-menu";
import type { SelectOption } from "../../../components/ha-control-select-menu";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
import {
apiContext,
configContext,
internationalizationContext,
} from "../../../data/context";
import { setDateTimeValue } from "../../../data/datetime";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import { setInputDateTimeValue } from "../../../data/input_datetime";
import { setTimeValue } from "../../../data/time";
import type { FrontendLocaleData, TimeFormat } from "../../../data/translation";
import type {
HomeAssistant,
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../../types";
import type { LovelaceCardFeature, LovelaceCardFeatureEditor } from "../types";
import { cardFeatureStyles } from "./common/card-feature-styles";
import type {
LovelaceCardFeatureContext,
TimeSetCardFeatureConfig,
} from "./types";
interface TimeParts {
hours: number;
minutes: number;
seconds: number;
}
type Period = "AM" | "PM";
const TIME_REGEX = /^(\d{1,2}):(\d{2})(?::(\d{2}))?/;
const supportsTimeSetCardFeatureFromState = (stateObj: HassEntity) => {
const domain = computeDomain(stateObj.entity_id);
return (
domain === "time" ||
domain === "datetime" ||
(domain === "input_datetime" && Boolean(stateObj.attributes.has_time))
);
};
export const supportsTimeSetCardFeature = (
hass: HomeAssistant,
context: LovelaceCardFeatureContext
) => {
const stateObj = context.entity_id
? hass.states[context.entity_id]
: undefined;
if (!stateObj) return false;
return supportsTimeSetCardFeatureFromState(stateObj);
};
// A datetime is shown in the time zone picked in the user's profile, like the
// tile's state, so the time is read and changed in that time zone too.
const toZonedDate = (value: string, timeZone?: string): Date => {
const date = new Date(value);
if (!timeZone) {
return date;
}
const zoned = new TZDate(date, timeZone);
// TZDate is invalid where Intl lacks "longOffset" (Chrome < 95, Safari < 15.4)
return isNaN(zoned.getHours()) ? date : zoned;
};
const parseTime = (
stateObj: HassEntity,
timeZone?: string
): TimeParts | undefined => {
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
if (computeDomain(stateObj.entity_id) === "datetime") {
const dateObj = toZonedDate(stateObj.state, timeZone);
if (isNaN(dateObj.getTime())) {
return undefined;
}
return {
hours: dateObj.getHours(),
minutes: dateObj.getMinutes(),
seconds: dateObj.getSeconds(),
};
}
// input_datetime with a date has a "YYYY-MM-DD HH:MM:SS" state
const match = TIME_REGEX.exec(stateObj.state.split(" ").pop() ?? "");
if (!match) {
return undefined;
}
return {
hours: Number(match[1]),
minutes: Number(match[2]),
seconds: match[3] ? Number(match[3]) : 0,
};
};
const pad = (value: number) => value.toString().padStart(2, "0");
// Seconds are kept as they are, so a time is matched on hours and minutes
const timeKey = (time: TimeParts) => `${time.hours}:${time.minutes}`;
// Each write has its own id, as the same time can be sent more than once
interface Write {
id: number;
key: string;
}
const MINUTE_OPTIONS: SelectOption[] = Array.from({ length: 60 }, (_, i) => ({
value: i.toString(),
label: pad(i),
}));
const HOUR_OPTIONS_24: SelectOption[] = Array.from({ length: 24 }, (_, i) => ({
value: i.toString(),
label: pad(i),
}));
const HOUR_OPTIONS_12: SelectOption[] = [
12,
...Array.from({ length: 11 }, (_, i) => i + 1),
].map((hour) => ({ value: hour.toString(), label: hour.toString() }));
@customElement("hui-time-set-card-feature")
class HuiTimeSetCardFeature extends LitElement implements LovelaceCardFeature {
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
@state()
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
private _stateObj?: HassEntity;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
transformer: ({ locale }) => locale,
})
private _locale?: FrontendLocaleData;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, string>({
transformer: ({ config }) => config.time_zone,
})
private _serverTimeZone?: string;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@state() private _config?: TimeSetCardFeatureConfig;
// The newest selection and the write that sent it, shown instead of the
// entity's time until every write is confirmed, so reports from earlier
// writes don't overwrite it
@state() private _selection?: {
entityId: string;
time: TimeParts;
writeId: number;
};
// Writes the entity hasn't reported back yet, oldest first
private _unconfirmed: Write[] = [];
private _nextWriteId = 0;
// The entity and time last reported, to skip updates that don't change it
private _reported?: string;
private get _timeZone(): string | undefined {
return this._locale && this._serverTimeZone
? resolveTimeZone(this._locale.time_zone, this._serverTimeZone)
: undefined;
}
static getStubConfig(): TimeSetCardFeatureConfig {
return {
type: "time-set",
};
}
public static async getConfigElement(): Promise<LovelaceCardFeatureEditor> {
await import("../editor/config-elements/hui-time-set-card-feature-editor");
return document.createElement("hui-time-set-card-feature-editor");
}
public setConfig(config: TimeSetCardFeatureConfig): void {
if (!config) {
throw new Error("Invalid configuration");
}
this._config = config;
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (!changedProps.has("_stateObj") || !this._stateObj) {
return;
}
const current = parseTime(this._stateObj, this._timeZone);
const key = current ? timeKey(current) : undefined;
const reported = `${this._stateObj.entity_id} ${key}`;
if (reported === this._reported) {
return;
}
this._reported = reported;
if (!this._selection) {
return;
}
// Home Assistant applies writes in order, so a report confirms the oldest
// unconfirmed write with that time, and any written before it
const index = key
? this._unconfirmed.findIndex((write) => write.key === key)
: -1;
this._unconfirmed = index === -1 ? [] : this._unconfirmed.slice(index + 1);
// Once every write is confirmed, or the time changed elsewhere, show the
// entity's time
if (this._unconfirmed.length === 0) {
this._selection = undefined;
}
}
// Worked out from the current entity on each use, as the entity can change
// after willUpdate when the card switches to another one
private get _time(): TimeParts | undefined {
if (!this._stateObj) {
return undefined;
}
return this._selection?.entityId === this._stateObj.entity_id
? this._selection.time
: parseTime(this._stateObj, this._timeZone);
}
private _useAmPm = memoizeOne(
(locale: FrontendLocaleData, timeFormat?: TimeFormat) =>
useAmPm(timeFormat ? { ...locale, time_format: timeFormat } : locale)
);
private _periodOptions = memoizeOne((language: string): SelectOption[] => {
const formatter = new Intl.DateTimeFormat(language, {
hour: "numeric",
hourCycle: "h12",
});
const periodLabel = (hours: number, fallback: Period) =>
formatter
.formatToParts(new Date(2000, 0, 1, hours))
.find((part) => part.type === "dayPeriod")?.value ?? fallback;
return [
{ value: "AM", label: periodLabel(0, "AM") },
{ value: "PM", label: periodLabel(12, "PM") },
];
});
private _hourSelected(ev: HaDropdownSelectEvent): void {
const hour = Number(ev.detail.item.value);
if (
!this._locale ||
!this._useAmPm(this._locale, this._config?.time_format)
) {
this._setTime({ hours: hour });
return;
}
const isPm = (this._time?.hours ?? 0) >= 12;
this._setTime({ hours: (hour % 12) + (isPm ? 12 : 0) });
}
private _minuteSelected(ev: HaDropdownSelectEvent): void {
this._setTime({ minutes: Number(ev.detail.item.value) });
}
private _periodSelected(ev: HaDropdownSelectEvent<Period>): void {
const hours = (this._time?.hours ?? 0) % 12;
this._setTime({
hours: ev.detail.item.value === "PM" ? hours + 12 : hours,
});
}
private async _setTime(change: Partial<TimeParts>) {
if (!this._stateObj) return;
const stateObj = this._stateObj;
const oldTime = this._time;
const time: TimeParts = {
hours: 0,
minutes: 0,
seconds: 0,
...oldTime,
...change,
};
if (
oldTime &&
time.hours === oldTime.hours &&
time.minutes === oldTime.minutes
) {
return;
}
const writeId = this._nextWriteId++;
this._selection = { entityId: stateObj.entity_id, time, writeId };
this._unconfirmed = [
...this._unconfirmed,
{ id: writeId, key: timeKey(time) },
];
const domain = computeDomain(stateObj.entity_id);
const value = `${pad(time.hours)}:${pad(time.minutes)}:${pad(time.seconds)}`;
try {
if (domain === "datetime") {
const dateObj = toZonedDate(stateObj.state, this._timeZone);
dateObj.setHours(time.hours, time.minutes, time.seconds);
await setDateTimeValue(
this._api.callService,
stateObj.entity_id,
new Date(dateObj.getTime())
);
} else if (domain === "input_datetime") {
await setInputDateTimeValue(
this._api.callService,
stateObj.entity_id,
value,
stateObj.attributes.has_date
? stateObj.state.split(" ")[0]
: undefined
);
} else {
await setTimeValue(this._api.callService, stateObj.entity_id, value);
}
} catch {
this._unconfirmed = this._unconfirmed.filter(
(write) => write.id !== writeId
);
// When the write behind the shown selection fails, show the entity's
// time again
if (this._selection?.writeId === writeId) {
this._selection = undefined;
}
}
}
protected render() {
if (
!this._config ||
!this.context ||
!this._stateObj ||
!this._locale ||
!supportsTimeSetCardFeatureFromState(this._stateObj)
) {
return nothing;
}
const disabled = [UNAVAILABLE, UNKNOWN].includes(this._stateObj.state);
const useAMPM = this._useAmPm(this._locale, this._config.time_format);
const time = this._time;
const hour = time
? (useAMPM ? time.hours % 12 || 12 : time.hours).toString()
: undefined;
return html`
<ha-control-select-menu
?hide-label=${hour !== undefined}
.label=${this._localize("ui.card.time.hour")}
.value=${hour}
.options=${useAMPM ? HOUR_OPTIONS_12 : HOUR_OPTIONS_24}
.disabled=${disabled}
@wa-select=${this._hourSelected}
></ha-control-select-menu>
<span class="separator" aria-hidden="true">:</span>
<ha-control-select-menu
?hide-label=${time !== undefined}
.label=${this._localize("ui.card.time.minute")}
.value=${time?.minutes.toString()}
.options=${MINUTE_OPTIONS}
.disabled=${disabled}
@wa-select=${this._minuteSelected}
></ha-control-select-menu>
${
useAMPM
? html`
<ha-control-select-menu
?hide-label=${time !== undefined}
.label=${this._localize("ui.card.time.period")}
.value=${time ? (time.hours >= 12 ? "PM" : "AM") : undefined}
.options=${this._periodOptions(this._locale.language)}
.disabled=${disabled}
@wa-select=${this._periodSelected}
></ha-control-select-menu>
`
: nothing
}
`;
}
static styles = [
cardFeatureStyles,
css`
:host {
display: flex;
align-items: center;
gap: var(--ha-space-1);
/* Times read hour first in every language, like ha-base-time-input */
direction: ltr;
}
ha-control-select-menu {
flex: 1;
min-width: 0;
/* Leave room for "12" or "PM" when the card is narrow */
--control-select-menu-padding: 6px var(--ha-space-1);
}
.separator {
color: var(--secondary-text-color);
font-size: var(--ha-font-size-l);
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"hui-time-set-card-feature": HuiTimeSetCardFeature;
}
}
@@ -41,7 +41,6 @@ import { supportsSelectOptionsCardFeature } from "./hui-select-options-card-feat
import { supportsTemperatureForecastCardFeature } from "./hui-temperature-forecast-card-feature";
import { supportsTargetHumidityCardFeature } from "./hui-target-humidity-card-feature";
import { supportsTargetTemperatureCardFeature } from "./hui-target-temperature-card-feature";
import { supportsTimeSetCardFeature } from "./hui-time-set-card-feature";
import { supportsTimerActionsCardFeature } from "./hui-timer-actions-card-feature";
import { supportsTimerPresetsCardFeature } from "./hui-timer-presets-card-feature";
import { supportsTimerProgressCardFeature } from "./hui-timer-progress-card-feature";
@@ -110,7 +109,6 @@ export const UI_FEATURE_TYPES = [
"trend-graph",
"target-humidity",
"target-temperature",
"time-set",
"timer-actions",
"timer-presets",
"timer-progress",
@@ -171,7 +169,6 @@ export const SUPPORTS_FEATURE_TYPES: Record<UiFeatureType, SupportsFeature> = {
"target-humidity": supportsTargetHumidityCardFeature,
"target-temperature": supportsTargetTemperatureCardFeature,
"temperature-forecast": supportsTemperatureForecastCardFeature,
"time-set": supportsTimeSetCardFeature,
"timer-actions": supportsTimerActionsCardFeature,
"timer-presets": supportsTimerPresetsCardFeature,
"timer-progress": supportsTimerProgressCardFeature,
@@ -1,7 +1,6 @@
import type { AlarmMode } from "../../../data/alarm_control_panel";
import type { HvacMode } from "../../../data/climate";
import type { FanSpeedStyle } from "../../../data/fan";
import type { TimeFormat } from "../../../data/translation";
import type { OperationMode } from "../../../data/water_heater";
import type { ForecastPrecipitationType } from "../../../data/weather";
@@ -214,11 +213,6 @@ export interface TargetTemperatureCardFeatureConfig {
style?: "buttons" | "slider";
}
export interface TimeSetCardFeatureConfig {
type: "time-set";
time_format?: TimeFormat;
}
export interface ToggleCardFeatureConfig {
type: "toggle";
}
@@ -414,7 +408,6 @@ export type LovelaceCardFeatureConfig =
| TrendGraphCardFeatureConfig
| TargetHumidityCardFeatureConfig
| TargetTemperatureCardFeatureConfig
| TimeSetCardFeatureConfig
| TimerActionsCardFeatureConfig
| TimerPresetsCardFeatureConfig
| TimerProgressCardFeatureConfig
@@ -19,14 +19,6 @@ const NUMERIC_INPUT_VARIANTS: TileVariant[] = [TILE_VARIANT, ["numeric-input"]];
const DATE_VARIANTS: TileVariant[] = [TILE_VARIANT, ["date-set"]];
const TIME_VARIANTS: TileVariant[] = [TILE_VARIANT, ["time-set"]];
const DATETIME_VARIANTS: TileVariant[] = [
TILE_VARIANT,
["date-set"],
["time-set"],
];
const BUTTON_VARIANTS: TileVariant[] = [TILE_VARIANT, ["button"]];
const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
@@ -97,16 +89,15 @@ const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
select: SELECT_VARIANTS,
input_number: NUMERIC_INPUT_VARIANTS,
number: NUMERIC_INPUT_VARIANTS,
input_datetime: DATETIME_VARIANTS,
input_datetime: DATE_VARIANTS,
date: DATE_VARIANTS,
time: TIME_VARIANTS,
update: [TILE_VARIANT, ["update-actions"]],
water_heater: [
TILE_VARIANT,
["water-heater-operation-modes"],
["target-temperature"],
],
datetime: DATETIME_VARIANTS,
datetime: DATE_VARIANTS,
button: BUTTON_VARIANTS,
input_button: BUTTON_VARIANTS,
scene: BUTTON_VARIANTS,
@@ -1,6 +1,6 @@
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, query, queryAll, state } from "lit/decorators";
import { customElement, queryAll, state } from "lit/decorators";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { applyThemesOnElement } from "../../../common/dom/apply_themes_on_element";
import { computeDomain } from "../../../common/entity/compute_domain";
@@ -81,8 +81,6 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
@queryAll("#states > div > *") private _rowElements!: NodeListOf<HTMLElement>;
@query("hui-entities-toggle") private _entitiesToggle?: HTMLElement;
private _hass?: HomeAssistant;
private _configEntities?: LovelaceRowConfig[];
@@ -119,9 +117,6 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
if (this._footerElement) {
this._footerElement.hass = hass;
}
if (this._entitiesToggle) {
(this._entitiesToggle as any).hass = hass;
}
}
public async getCardSize(): Promise<number> {
@@ -242,7 +237,6 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
? nothing
: html`
<hui-entities-toggle
.hass=${this._hass}
.entities=${(
this._configEntities!.filter(
(conf) => "entity" in conf
@@ -1,17 +1,18 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { STATES_OFF } from "../../../../common/const";
import { computeDomain } from "../../../../common/entity/compute_domain";
import { computeStateDomain } from "../../../../common/entity/compute_state_domain";
import { getToggleAction } from "../../../../common/entity/get_toggle_action";
import type { HomeAssistant } from "../../../../types";
import type { HomeAssistantApi } from "../../../../types";
export const turnOnOffEntities = (
hass: HomeAssistant,
entityIds: string[],
callService: HomeAssistantApi["callService"],
stateObjs: HassEntity[],
turnOn = true
): void => {
const domainsToCall = {};
entityIds.forEach((entityId) => {
if (STATES_OFF.includes(hass.states[entityId].state) === turnOn) {
const stateDomain = computeDomain(entityId);
stateObjs.forEach((stateObj) => {
if (STATES_OFF.includes(stateObj.state) === turnOn) {
const stateDomain = computeStateDomain(stateObj);
// Entities with non-standard toggle action need separate calls
const serviceDomain =
getToggleAction(stateDomain, true) !== "turn_on"
@@ -21,7 +22,7 @@ export const turnOnOffEntities = (
if (!(serviceDomain in domainsToCall)) {
domainsToCall[serviceDomain] = [];
}
domainsToCall[serviceDomain].push(entityId);
domainsToCall[serviceDomain].push(stateObj.entity_id);
}
});
@@ -29,6 +30,6 @@ export const turnOnOffEntities = (
const service = getToggleAction(domain, turnOn);
const entities = domainsToCall[domain];
hass.callService(domain, service, { entity_id: entities });
callService(domain, service, { entity_id: entities });
});
};
@@ -1,46 +1,59 @@
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityStates,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-switch";
import type { HaSwitch } from "../../../components/ha-switch";
import { apiContext } from "../../../data/context";
import { forwardHaptic } from "../../../data/haptics";
import type { HomeAssistant } from "../../../types";
import { turnOnOffEntities } from "../common/entity/turn-on-off-entities";
@customElement("hui-entities-toggle")
class HuiEntitiesToggle extends LitElement {
@property({ type: Array }) public entities?: string[];
@property({ attribute: false }) public hass?: HomeAssistant;
@state() _toggleEntities?: string[];
@state() private _toggleEntities?: string[];
@state()
@consumeEntityStates({ entityIdPath: ["_toggleEntities"] })
private _stateObjs?: Record<string, HassEntity>;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api?: ContextType<typeof apiContext>;
public willUpdate(changedProperties: PropertyValues<this>): void {
super.willUpdate(changedProperties);
if (changedProperties.has("entities")) {
this._toggleEntities = this.entities!.filter(
(entityId) =>
entityId in this.hass!.states &&
DOMAINS_TOGGLE.has(entityId.split(".", 1)[0])
this._toggleEntities = this.entities!.filter((entityId) =>
DOMAINS_TOGGLE.has(entityId.split(".", 1)[0])
);
}
}
protected render() {
if (!this._toggleEntities?.length) {
const stateObjs = Object.values(this._stateObjs ?? {});
if (!stateObjs.length || !this._localize) {
return nothing;
}
return html`
<ha-switch
.accessibleLabel=${this.hass!.localize(
.accessibleLabel=${this._localize(
"ui.panel.lovelace.card.entities.toggle"
)}
.checked=${this._toggleEntities!.some((entityId) => {
const stateObj = this.hass!.states[entityId];
return stateObj && stateObj.state === "on";
})}
.checked=${stateObjs.some((stateObj) => stateObj.state === "on")}
@change=${this._callService}
></ha-switch>
`;
@@ -59,9 +72,16 @@ class HuiEntitiesToggle extends LitElement {
`;
private _callService(ev: MouseEvent): void {
if (!this._api) {
return;
}
forwardHaptic(this, "light");
const turnOn = (ev.target as HaSwitch).checked;
turnOnOffEntities(this.hass!, this._toggleEntities!, turnOn!);
turnOnOffEntities(
this._api.callService,
Object.values(this._stateObjs ?? {}),
turnOn
);
}
}
@@ -1,27 +1,46 @@
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, eventOptions, property, query } from "lit/decorators";
import {
customElement,
eventOptions,
property,
query,
state,
} from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { DOMAINS_INPUT_ROW } from "../../../common/const";
import { consume } from "../../../common/decorators/consume";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { fireEvent } from "../../../common/dom/fire_event";
import { stopPropagation } from "../../../common/dom/stop_propagation";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/entity/state-badge";
import "../../../components/ha-relative-time";
import "../../../components/ha-tooltip";
import { configContext, formattersContext } from "../../../data/context";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import type {
HomeAssistant,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { EntitiesCardEntityConfig } from "../cards/types";
import { actionHandler } from "../common/directives/action-handler-directive";
import { handleAction } from "../common/handle-action";
import { hasAction, hasAnyAction } from "../common/has-action";
import { createEntityNotFoundWarning } from "./hui-warning";
import "../../../state-display/state-display";
@customElement("hui-generic-entity-row")
export class HuiGenericEntityRow extends LitElement {
// Fallback for custom rows that pass `hass` instead of `stateObj`
@property({ attribute: false }) public hass?: HomeAssistant;
@property({ attribute: false }) public stateObj?: HassEntity;
@property({ attribute: false }) public config?: EntitiesCardEntityConfig;
@property({ attribute: "secondary-text" }) public secondaryText?: string;
@@ -36,22 +55,42 @@ export class HuiGenericEntityRow extends LitElement {
@property({ attribute: "catch-interaction", type: Boolean })
public catchInteraction?;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig?: HassConfig;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters?: HomeAssistantFormatters;
@query(".row > slot") private _controlSlot?: HTMLSlotElement;
private _pressedControl = false;
protected render() {
if (!this.hass || !this.config) {
if (
!this.config ||
!this._localize ||
!this._hassConfig ||
!this._formatters
) {
return nothing;
}
const stateObj = this.config.entity
? this.hass.states[this.config.entity]
: undefined;
const stateObj =
this.stateObj ??
(this.config.entity ? this.hass?.states[this.config.entity] : undefined);
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
</hui-warning>
`;
}
@@ -63,7 +102,7 @@ export class HuiGenericEntityRow extends LitElement {
const pointer = hasAnyAction(this.config);
const hasSecondary = this.secondaryText || this.config.secondary_info;
const name = this.hass.formatEntityName(stateObj, this.config.name);
const name = this._formatters.formatEntityName(stateObj, this.config.name);
return html`
<div
@@ -161,7 +200,10 @@ export class HuiGenericEntityRow extends LitElement {
}
private _handleAction(ev: ActionHandlerEvent) {
handleAction(this, this.hass!, this.config!, ev.detail.action!);
fireEvent(this, "hass-action", {
config: this.config!,
action: ev.detail.action!,
});
}
static styles = css`
@@ -36,7 +36,6 @@ import "../card-features/hui-numeric-input-card-feature";
import "../card-features/hui-select-options-card-feature";
import "../card-features/hui-target-humidity-card-feature";
import "../card-features/hui-target-temperature-card-feature";
import "../card-features/hui-time-set-card-feature";
import "../card-features/hui-timer-actions-card-feature";
import "../card-features/hui-timer-presets-card-feature";
import "../card-features/hui-timer-progress-card-feature";
@@ -104,7 +103,6 @@ const TYPES = new Set<LovelaceCardFeatureConfig["type"]>([
"target-humidity",
"target-temperature",
"temperature-forecast",
"time-set",
"timer-actions",
"timer-presets",
"timer-progress",
@@ -151,7 +151,11 @@ export const addEntitiesToLovelaceView = async (
}
const dashboardPath = viewUrlPath ?? LOVELACE_PANEL;
const viewPath = newConfig.views[viewIndex].path || viewIndex;
const dashboardTitle = getPanelTitleFromUrlPath(hass, dashboardPath);
const dashboardTitle = getPanelTitleFromUrlPath(
hass.localize,
hass.panels,
dashboardPath
);
showToast(element, {
message: dashboardTitle
? {
@@ -65,7 +65,6 @@ import { supportsNumericInputCardFeature } from "../../card-features/hui-numeric
import { supportsSelectOptionsCardFeature } from "../../card-features/hui-select-options-card-feature";
import { supportsTargetHumidityCardFeature } from "../../card-features/hui-target-humidity-card-feature";
import { supportsTargetTemperatureCardFeature } from "../../card-features/hui-target-temperature-card-feature";
import { supportsTimeSetCardFeature } from "../../card-features/hui-time-set-card-feature";
import { supportsTimerActionsCardFeature } from "../../card-features/hui-timer-actions-card-feature";
import { supportsTimerPresetsCardFeature } from "../../card-features/hui-timer-presets-card-feature";
import { supportsTimerProgressCardFeature } from "../../card-features/hui-timer-progress-card-feature";
@@ -136,7 +135,6 @@ const UI_FEATURE_TYPES = [
"target-humidity",
"target-temperature",
"temperature-forecast",
"time-set",
"timer-actions",
"timer-presets",
"timer-progress",
@@ -183,7 +181,6 @@ const EDITABLES_FEATURE_TYPES = new Set<UiFeatureTypes>([
"select-options",
"target-humidity",
"target-temperature",
"time-set",
"timer-actions",
"timer-presets",
"trend-graph",
@@ -242,7 +239,6 @@ const SUPPORTS_FEATURE_TYPES: Record<
"target-humidity": supportsTargetHumidityCardFeature,
"target-temperature": supportsTargetTemperatureCardFeature,
"temperature-forecast": supportsTemperatureForecastCardFeature,
"time-set": supportsTimeSetCardFeature,
"timer-actions": supportsTimerActionsCardFeature,
"timer-presets": supportsTimerPresetsCardFeature,
"timer-progress": supportsTimerProgressCardFeature,
@@ -1,104 +0,0 @@
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-form/ha-form";
import type {
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import { TimeFormat } from "../../../../data/translation";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type {
LovelaceCardFeatureContext,
TimeSetCardFeatureConfig,
} from "../../card-features/types";
import type { LovelaceCardFeatureEditor } from "../../types";
type TimeSetCardFeatureFormData = Omit<
TimeSetCardFeatureConfig,
"time_format"
> & {
// Clearing the select leaves it undefined, which also means "auto"
time_format?: TimeFormat | "auto";
};
@customElement("hui-time-set-card-feature-editor")
export class HuiTimeSetCardFeatureEditor
extends LitElement
implements LovelaceCardFeatureEditor
{
@property({ attribute: false }) public hass?: HomeAssistant;
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
@state() private _config?: TimeSetCardFeatureConfig;
public setConfig(config: TimeSetCardFeatureConfig): void {
this._config = config;
}
private _schema = memoizeOne(
(localize: LocalizeFunc) =>
[
{
name: "time_format",
selector: {
select: {
mode: "dropdown",
options: ["auto", ...Object.values(TimeFormat)].map((value) => ({
value,
label: localize(
`ui.panel.lovelace.editor.features.types.time-set.time_formats.${value}`
),
})),
},
},
},
] as const satisfies readonly HaFormSchema[]
);
protected render() {
if (!this.hass || !this._config) {
return nothing;
}
const data: TimeSetCardFeatureFormData = {
...this._config,
time_format: this._config.time_format ?? "auto",
};
return html`
<ha-form
.hass=${this.hass}
.data=${data}
.schema=${this._schema(this.hass.localize)}
.computeLabel=${this._computeLabelCallback}
@value-changed=${this._valueChanged}
></ha-form>
`;
}
private _valueChanged(ev: ValueChangedEvent<TimeSetCardFeatureFormData>) {
const { time_format, ...rest } = ev.detail.value;
const config: TimeSetCardFeatureConfig =
!time_format || time_format === "auto" ? rest : { ...rest, time_format };
fireEvent(this, "config-changed", { config });
}
private _computeLabelCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) =>
this.hass!.localize(
`ui.panel.lovelace.editor.features.types.time-set.${schema.name}`
);
}
declare global {
interface HTMLElementTagNameMap {
"hui-time-set-card-feature-editor": HuiTimeSetCardFeatureEditor;
}
}
@@ -43,7 +43,7 @@ class HuiButtonEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-button
appearance="plain"
size="s"
@@ -42,7 +42,7 @@ class HuiClimateEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-climate-state .stateObj=${stateObj}> </ha-climate-state>
</hui-generic-entity-row>
`;
@@ -44,7 +44,7 @@ class HuiCoverEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
isTiltOnly(stateObj)
? html`
@@ -47,7 +47,7 @@ class HuiDateEntityRow extends LitElement implements LovelaceRow {
const name = this.hass.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-date-input
.locale=${this.hass.locale}
.disabled=${unavailable}
@@ -57,7 +57,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
hide-name
>
@@ -56,7 +56,7 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
.catchInteraction=${false}
>
@@ -95,7 +95,7 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
stateObj.state === UNKNOWN);
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
supportSpeedPercentage && !supportsOnOff
? html`
@@ -60,7 +60,7 @@ class HuiGroupEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
this._computeCanToggle(this.hass, stateObj.attributes.entity_id)
? html`
@@ -43,7 +43,7 @@ class HuiHumidifierEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-humidifier-state .stateObj=${stateObj}> </ha-humidifier-state>
</hui-generic-entity-row>
`;
@@ -43,7 +43,7 @@ class HuiInputButtonEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-button
appearance="plain"
size="s"
@@ -50,7 +50,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
.hideName=${
stateObj.attributes.has_date && stateObj.attributes.has_time
@@ -74,7 +74,7 @@ class HuiInputNumberEntityRow extends LitElement implements LovelaceRow {
const name = this.hass.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
stateObj.attributes.mode === "slider"
? html`
@@ -52,7 +52,7 @@ class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
hide-name
>
@@ -47,7 +47,7 @@ class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
hide-name
>
@@ -44,7 +44,7 @@ class HuiLockEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-button
appearance="plain"
size="s"
@@ -199,7 +199,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
.secondaryText=${
mediaDescription || this.hass.formatEntityState(stateObj)
@@ -77,7 +77,7 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
const name = this.hass.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
showNumberSlider(stateObj)
? html`
@@ -44,7 +44,7 @@ class HuiSceneEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-button
appearance="plain"
size="s"
@@ -46,7 +46,7 @@ class HuiScriptEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
stateObj.state === "on"
? html`<ha-button
@@ -70,7 +70,7 @@ class HuiSelectEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
hide-name
>
@@ -49,7 +49,7 @@ class HuiSensorEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
SENSOR_TIMESTAMP_DEVICE_CLASSES.includes(
stateObj.attributes.device_class
@@ -45,7 +45,7 @@ class HuiSimpleEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${
TIMESTAMP_STATE_DOMAINS.has(computeDomain(this._config.entity)) &&
stateObj.state !== UNAVAILABLE &&
@@ -49,7 +49,7 @@ class HuiTextEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
hide-name
>
@@ -47,7 +47,7 @@ class HuiTimeEntityRow extends LitElement implements LovelaceRow {
const name = this.hass.formatEntityName(stateObj, this._config.name);
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<ha-time-input
.value=${
stateObj.state === UNAVAILABLE || stateObj.state === UNKNOWN
@@ -37,7 +37,7 @@ class HuiTimerEntityRow extends LitElement {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<div class="text-content">
<ha-timer-remaining-time
.stateObj=${stateObj}
@@ -49,7 +49,7 @@ class HuiToggleEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
.catchInteraction=${!showToggle}
>
@@ -44,7 +44,7 @@ class HuiUpdateEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${computeUpdateStateDisplay(
stateObj,
this.hass.localize,
@@ -49,7 +49,7 @@ class HuiValveEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.hass=${this.hass}
.stateObj=${stateObj}
.config=${this._config}
.catchInteraction=${!showToggle}
>
+4 -2
View File
@@ -472,7 +472,7 @@ class HUIRoot extends KeyboardShortcutMixin(LitElement) {
typeof this._curView === "number" ? views[this._curView] : undefined;
const dashboardTitle = this.panel
? getPanelTitle(this.hass, this.panel)
? getPanelTitle(this.hass.localize, this.panel)
: undefined;
const background = curViewConfig?.background || this.config.background;
@@ -1118,7 +1118,9 @@ class HUIRoot extends KeyboardShortcutMixin(LitElement) {
showDashboardStrategyEditorDialog(this, {
config: this.lovelace!.rawConfig,
title: this.panel ? getPanelTitle(this.hass, this.panel) : undefined,
title: this.panel
? getPanelTitle(this.hass.localize, this.panel)
: undefined,
saveConfig: this.lovelace!.saveConfig,
takeControl: () => {
showSaveDialog(this, {
@@ -55,7 +55,7 @@ class HuiAttributeRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
${this._config.prefix}
${
this._config.time_format && checkValidDate(date)
+2 -2
View File
@@ -74,7 +74,7 @@ class HaPickDashboardRow extends LitElement {
slot="icon"
.icon=${getPanelIcon(panelInfo)}
></ha-icon>
${getPanelTitle(this.hass, panelInfo)}
${getPanelTitle(this.hass.localize, panelInfo)}
</ha-dropdown-item>
`;
})}
@@ -143,7 +143,7 @@ class HaPickDashboardRow extends LitElement {
}
const panelInfo = this.hass.panels[value] as PanelInfo | undefined;
if (panelInfo) {
return getPanelTitle(this.hass, panelInfo);
return getPanelTitle(this.hass.localize, panelInfo);
}
const dashboard = this._dashboards?.find((dash) => dash.url_path === value);
if (dashboard) {
@@ -60,11 +60,9 @@ export class HaStateControlAlarmControlPanelModes extends LitElement {
private async _setMode(mode: AlarmMode) {
await setProtectedAlarmControlPanelMode(
this,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this._api.callService,
this._api.callWS,
this._localize,
this.stateObj,
mode
);
@@ -26,6 +26,7 @@ import type { ClimateEntity, HvacMode } from "../../data/climate";
import {
CLIMATE_HVAC_ACTION_TO_MODE,
ClimateEntityFeature,
pushTargetTemperature,
} from "../../data/climate";
import {
apiContext,
@@ -146,7 +147,12 @@ export class HaStateControlClimateTemperature extends LitElement {
const target = ev.type.replace("-changed", "") as Target;
this._targetTemperature = {
...this._targetTemperature,
[target]: this._clampToRange(target, value),
...pushTargetTemperature(
this._targetTemperature,
target,
// The slider rounds to the step after bounding, which can overshoot
clamp(value, this._min, this._max)
),
};
this._selectTargetTemperature = target;
this._debouncedCallService.cancel();
@@ -159,9 +165,13 @@ export class HaStateControlClimateTemperature extends LitElement {
this._changingTemperature = {};
return;
}
const target = ev.type.replace("-changing", "");
this._changingTemperature = { [target]: value };
this._selectTargetTemperature = target as Target;
const target = ev.type.replace("-changing", "") as Target;
this._changingTemperature = pushTargetTemperature(
this._targetTemperature,
target,
clamp(value, this._min, this._max)
);
this._selectTargetTemperature = target;
}
private get _displayedTemperature() {
@@ -203,22 +213,12 @@ export class HaStateControlClimateTemperature extends LitElement {
this._targetTemperature = {
...this._targetTemperature,
[target]: this._clampToRange(target, temp),
...pushTargetTemperature(this._targetTemperature, target, temp),
};
this._pendingSync.schedule();
this._debouncedCallService(target);
}
private _clampToRange(target: Target, temp: number) {
if (target === "high" && this._targetTemperature.low != null) {
return clamp(temp, this._targetTemperature.low, this._max);
}
if (target === "low" && this._targetTemperature.high != null) {
return clamp(temp, this._min, this._targetTemperature.high);
}
return temp;
}
private _handleSelectTemp(ev) {
const target = ev.currentTarget.target as Target;
this._selectTargetTemperature = target;
+43 -2
View File
@@ -10,8 +10,10 @@ import {
import { fireEvent } from "../common/dom/fire_event";
import { computeEntityNameDisplayWithoutContext } from "../common/entity/compute_entity_name_display";
import { promiseTimeout } from "../common/util/promise-timeout";
import type { AreaRegistryEntry } from "../data/area/area_registry";
import { subscribeAreaRegistry } from "../data/area/area_registry";
import { broadcastConnectionStatus } from "../data/connection-status";
import type { DeviceRegistryEntry } from "../data/device/device_registry";
import { subscribeDeviceRegistry } from "../data/device/device_registry";
import {
subscribeFrontendSystemData,
@@ -29,9 +31,14 @@ import {
TimeFormat,
TimeZone,
} from "../data/translation";
import type { EntityRegistryDisplayEntryResponse } from "../data/entity/entity_registry";
import { subscribeEntityRegistryDisplay } from "../data/ws-entity_registry_display";
import { deepEqual } from "../common/util/deep-equal";
import { preserveUnchangedRecord } from "../common/util/preserve-unchanged-record";
import {
preserveUnchangedItems,
preserveUnchangedRecord,
} from "../common/util/preserve-unchanged-record";
import type { FloorRegistryEntry } from "../data/floor_registry";
import { subscribeFloorRegistry } from "../data/ws-floor_registry";
import { subscribePanels } from "../data/ws-panels";
import { translationMetadata } from "../resources/translations-metadata";
@@ -267,7 +274,21 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
});
subscribeEntities(conn, (states) => this._updateHass({ states }));
// A refetch returns new objects for every entry. Putting the unchanged
// previous ones back into the store's list keeps one copy, shared with
// `hass`.
let entityRegEntries:
EntityRegistryDisplayEntryResponse["entities"] | undefined;
let deviceRegEntries: DeviceRegistryEntry[] | undefined;
let areaRegEntries: AreaRegistryEntry[] | undefined;
let floorRegEntries: FloorRegistryEntry[] | undefined;
subscribeEntityRegistryDisplay(conn, (entityReg) => {
entityRegEntries = preserveUnchangedItems(
entityRegEntries,
entityReg.entities,
(entity) => entity.ei,
deepEqual
);
const entities: HomeAssistant["entities"] = {};
for (const entity of entityReg.entities) {
entities[entity.ei] = {
@@ -301,6 +322,12 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
}
});
subscribeDeviceRegistry(conn, (deviceReg) => {
deviceRegEntries = preserveUnchangedItems(
deviceRegEntries,
deviceReg,
(device) => device.id,
deepEqual
);
const devices: HomeAssistant["devices"] = {};
for (const device of deviceReg) {
devices[device.id] = device;
@@ -315,6 +342,12 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
}
});
subscribeAreaRegistry(conn, (areaReg) => {
areaRegEntries = preserveUnchangedItems(
areaRegEntries,
areaReg,
(area) => area.area_id,
deepEqual
);
const areas: HomeAssistant["areas"] = {};
for (const area of areaReg) {
areas[area.area_id] = area;
@@ -330,6 +363,12 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
}
});
subscribeFloorRegistry(conn, (floorReg) => {
floorRegEntries = preserveUnchangedItems(
floorRegEntries,
floorReg,
(floor) => floor.floor_id,
deepEqual
);
const floors: HomeAssistant["floors"] = {};
for (const floor of floorReg) {
floors[floor.floor_id] = floor;
@@ -422,7 +461,9 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
// fetchAndScheduleBrandsAccessToken retries internally. If the token
// changed, re-render so any brand <img> elements that rendered against a
// different (or missing) token recompute their src and re-fetch.
const changed = await fetchAndScheduleBrandsAccessToken(this.hass!);
const changed = await fetchAndScheduleBrandsAccessToken(
this.hass!.callWS
);
if (changed) {
this._updateHass({});
}
+3 -3
View File
@@ -245,9 +245,9 @@ export class LazyContextProvider<
}
this._loaded = false;
this._subscribing = false;
// Clear the inner provider's value so stale data isn't served.
// The inner provider also holds subscriptions in its map; clearing
// them is not needed since all consumers have already unsubscribed.
// Clear the inner provider's value so stale data isn't served or kept in
// memory. All consumers have already unsubscribed, so nobody is notified.
this._provider.setValue(undefined as ContextType<C>);
}
private _startSubscription(): void {
+5 -1
View File
@@ -46,7 +46,11 @@ export const panelTitleMixin = <T extends Constructor<HassBaseEl>>(
// Fall back to panel title
if (!title) {
title = getPanelTitleFromUrlPath(this.hass, this.hass.panelUrl);
title = getPanelTitleFromUrlPath(
this.hass.localize,
this.hass.panels,
this.hass.panelUrl
);
}
setPageTitle(title);
-16
View File
@@ -340,11 +340,6 @@
"text": {
"empty_value": "(empty value)"
},
"time": {
"hour": "Hour",
"minute": "Minute",
"period": "AM or PM"
},
"timer": {
"actions": {
"start": "Start",
@@ -12457,17 +12452,6 @@
"reset": "Reset"
}
},
"time-set": {
"label": "Set time",
"time_format": "[%key:ui::panel::profile::time_format::dropdown_label%]",
"time_formats": {
"auto": "[%key:ui::panel::lovelace::editor::card::clock::time_formats::auto%]",
"language": "[%key:ui::panel::profile::time_format::formats::language%]",
"system": "[%key:ui::panel::profile::time_format::formats::system%]",
"24": "[%key:ui::panel::profile::time_format::formats::24%]",
"12": "[%key:ui::panel::profile::time_format::formats::12%]"
}
},
"timer-actions": {
"label": "Timer actions",
"customize": "[%key:ui::panel::lovelace::editor::features::types::counter-actions::customize%]",
+9 -7
View File
@@ -34,7 +34,7 @@ const FETCH_DELAYS_MS = [0, 500, 1000, 2000, 5000, 10000, 15000];
// Returns true if the cached token changed as a result of this call, so
// callers can decide whether they need to trigger a re-render.
export const fetchAndScheduleBrandsAccessToken = async (
hass: HomeAssistant
callWS: HomeAssistant["callWS"]
): Promise<boolean> => {
const previousToken = _brandsAccessToken;
/* eslint-disable no-await-in-loop -- retries are intentionally sequential */
@@ -43,8 +43,8 @@ export const fetchAndScheduleBrandsAccessToken = async (
await waitForMs(delay);
}
try {
await fetchBrandsAccessToken(hass);
scheduleBrandsTokenRefresh(hass);
await fetchBrandsAccessToken(callWS);
scheduleBrandsTokenRefresh(callWS);
return _brandsAccessToken !== previousToken;
} catch {
// try next delay
@@ -55,9 +55,9 @@ export const fetchAndScheduleBrandsAccessToken = async (
};
export const fetchBrandsAccessToken = async (
hass: HomeAssistant
callWS: HomeAssistant["callWS"]
): Promise<void> => {
const result = await hass.callWS<{ token: string }>({
const result = await callWS<{ token: string }>({
type: "brands/access_token",
});
if (result.token === _brandsAccessToken) {
@@ -79,10 +79,12 @@ export const subscribeBrandsAccessToken = (
};
};
export const scheduleBrandsTokenRefresh = (hass: HomeAssistant): void => {
export const scheduleBrandsTokenRefresh = (
callWS: HomeAssistant["callWS"]
): void => {
clearBrandsTokenRefresh();
_brandsRefreshInterval = setInterval(() => {
fetchBrandsAccessToken(hass).catch(() => {
fetchBrandsAccessToken(callWS).catch(() => {
// Ignore failures; older backends may not support this command
});
}, TOKEN_REFRESH_MS);
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { deepEqual } from "../../../src/common/util/deep-equal";
import { preserveUnchangedRecord } from "../../../src/common/util/preserve-unchanged-record";
import {
preserveUnchangedItems,
preserveUnchangedRecord,
} from "../../../src/common/util/preserve-unchanged-record";
interface Item {
id: string;
@@ -98,3 +101,29 @@ describe.each([false, true])(
});
}
);
describe("preserveUnchangedItems", () => {
it("swaps equal items for the previous objects by key", () => {
const previous: Item[] = [
{ id: "a", name: "A", labels: ["x"] },
{ id: "b", name: "B" },
];
const next: Item[] = [
{ id: "c", name: "C" },
{ id: "b", name: "B2" },
{ id: "a", name: "A", labels: ["x"] },
];
const [c, b] = next;
const result = preserveUnchangedItems(
previous,
next,
(item) => item.id,
deepEqual
);
expect(result).toBe(next);
expect(result).toEqual([c, b, previous[0]]);
expect(result[0]).toBe(c);
expect(result[1]).toBe(b);
expect(result[2]).toBe(previous[0]);
});
});
@@ -0,0 +1,72 @@
import { afterEach, describe, expect, it } from "vitest";
import "../../src/components/ha-control-circular-slider";
import type { HaControlCircularSlider } from "../../src/components/ha-control-circular-slider";
const setActiveValue = (slider: HaControlCircularSlider, value: number) =>
(slider as unknown as Record<"_setActiveValue", (value: number) => void>)[
"_setActiveValue"
](value);
const createSlider = async (low: number, high: number) => {
const slider = document.createElement("ha-control-circular-slider");
slider.dual = true;
slider.min = 10;
slider.max = 30;
slider.low = low;
slider.high = high;
document.body.append(slider);
await slider.updateComplete;
return slider;
};
const drag = async (
slider: HaControlCircularSlider,
handle: "low" | "high",
values: number[]
) => {
slider._activeSlider = handle;
values.forEach((value) => setActiveValue(slider, value));
const handles = { low: slider._localLow, high: slider._localHigh };
slider._activeSlider = undefined;
await slider.updateComplete;
return handles;
};
describe("ha-control-circular-slider range push", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("pushes high while low passes it and restores it when low comes back", async () => {
const slider = await createSlider(20, 24);
expect(await drag(slider, "low", [26, 22])).toEqual({ low: 22, high: 24 });
});
it("pushes low while high passes it and restores it when high comes back", async () => {
const slider = await createSlider(20, 24);
expect(await drag(slider, "high", [18, 23])).toEqual({ low: 20, high: 23 });
});
it("starts each drag from the handles' current positions", async () => {
const slider = await createSlider(20, 24);
await drag(slider, "low", [26]);
// high now sits at 26, so a second drag of low back down leaves it there
expect(await drag(slider, "low", [22])).toEqual({ low: 22, high: 26 });
});
});
describe("ha-control-circular-slider stepping", () => {
it("keeps a stepped value within min and max", async () => {
const slider = await createSlider(20, 24);
slider.max = 35;
slider.step = 2;
const stepped = (value: number) =>
(slider as unknown as Record<"_steppedValue", (v: number) => number>)[
"_steppedValue"
](value);
// 35 rounds to 36 with a step of 2, past the maximum
expect(stepped(35)).toBe(35);
expect(stepped(33.2)).toBe(34);
document.body.innerHTML = "";
});
});
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { pushTargetTemperature } from "../../src/data/climate";
const range = { low: 20, high: 24 };
describe("pushTargetTemperature", () => {
it("only changes the set target while the range stays in order", () => {
expect(pushTargetTemperature(range, "low", 22)).toEqual({ low: 22 });
expect(pushTargetTemperature(range, "high", 24)).toEqual({ high: 24 });
expect(pushTargetTemperature(range, "low", 24)).toEqual({ low: 24 });
});
it("pushes high up when low passes it", () => {
expect(pushTargetTemperature(range, "low", 26)).toEqual({
low: 26,
high: 26,
});
});
it("pushes low down when high passes it", () => {
expect(pushTargetTemperature(range, "high", 18)).toEqual({
low: 18,
high: 18,
});
});
it("sets a single target as is", () => {
expect(pushTargetTemperature({ value: 21 }, "value", 30)).toEqual({
value: 30,
});
});
});
+1 -4
View File
@@ -4,9 +4,6 @@ import {
searchPlaces,
type OpenStreetMapPlace,
} from "../../src/data/openstreetmap";
import type { HomeAssistant } from "../../src/types";
const hass = { locale: { language: "en" } } as HomeAssistant;
afterEach(() => {
vi.unstubAllGlobals();
@@ -19,7 +16,7 @@ describe("searchPlaces", () => {
.mockResolvedValue(new Response("[]"));
vi.stubGlobal("fetch", fetchMock);
await searchPlaces("10 Downing Street & London", hass, true, 3);
await searchPlaces("10 Downing Street & London", "en", true, 3);
const url = new URL(String(fetchMock.mock.calls[0][0]));
expect(url.searchParams.get("q")).toBe("10 Downing Street & London");
@@ -1,20 +1,44 @@
import { ContextProvider } from "@lit/context";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
configContext,
formattersContext,
internationalizationContext,
} from "../../../../src/data/context";
import "../../../../src/panels/lovelace/components/hui-generic-entity-row";
import type {
HomeAssistantConfig,
HomeAssistantFormatters,
HomeAssistantInternationalization,
} from "../../../../src/types";
import { createMockEntityState, createMockHass } from "../../../fixtures/hass";
const mountRow = async (catchInteraction = false) => {
const row = document.createElement("hui-generic-entity-row");
row.hass = createMockHass({
"input_boolean.porch": createMockEntityState("input_boolean.porch", "off"),
const hass = createMockHass();
const host = document.createElement("div");
new ContextProvider(host, {
context: internationalizationContext,
initialValue: hass as HomeAssistantInternationalization,
});
new ContextProvider(host, {
context: configContext,
initialValue: hass as HomeAssistantConfig,
});
new ContextProvider(host, {
context: formattersContext,
initialValue: hass as HomeAssistantFormatters,
});
const row = document.createElement("hui-generic-entity-row");
row.stateObj = createMockEntityState("input_boolean.porch", "off");
row.config = { entity: "input_boolean.porch" };
row.catchInteraction = catchInteraction;
const control = document.createElement("button");
row.append(control);
document.body.append(row);
host.append(row);
document.body.append(host);
await row.updateComplete;
const moreInfo = vi.fn();
row.addEventListener("hass-more-info", moreInfo);
row.addEventListener("hass-action", moreInfo);
return {
control,
moreInfo,
+26
View File
@@ -119,4 +119,30 @@ describe("LazyContextProvider", () => {
vi.useRealTimers();
}
});
it("clears the value once the last consumer is gone", () => {
vi.useFakeTimers();
try {
const unsubscribe = vi.fn();
const provider = createProvider((_conn, set) => {
set(["a"]);
return unsubscribe;
});
provider.setConnection(connection);
const callback = request(addConsumer());
const [value, dispose] = callback.mock.calls[0];
expect(value).toEqual(["a"]);
dispose();
vi.advanceTimersByTime(5000);
expect(unsubscribe).toHaveBeenCalledTimes(1);
expect(
(provider as unknown as { _provider: { value: unknown } })._provider
.value
).toBeUndefined();
} finally {
vi.useRealTimers();
}
});
});
+17 -17
View File
@@ -77,7 +77,7 @@ describe("Generate brands Url", () => {
const mockHass = {
callWS: async () => ({ token: "test-token-123" }),
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
});
it("Generate logo brands url for cloud component", () => {
@@ -134,7 +134,7 @@ describe("addBrandsAuth", () => {
const mockHass = {
callWS: async () => ({ token: "test-token-123" }),
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
assert.strictEqual(
addBrandsAuth(
@@ -149,7 +149,7 @@ describe("addBrandsAuth", () => {
const mockHass = {
callWS: async () => ({ token: "new-token" }),
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
assert.strictEqual(
addBrandsAuth(
@@ -221,7 +221,7 @@ describe("scheduleBrandsTokenRefresh", () => {
},
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
assert.strictEqual(callCount, 1);
assert.strictEqual(
brandsUrl(
@@ -231,7 +231,7 @@ describe("scheduleBrandsTokenRefresh", () => {
"http://homeassistant.local:8123/api/brands/integration/test/icon.png?token=token-1"
);
scheduleBrandsTokenRefresh(mockHass);
scheduleBrandsTokenRefresh(mockHass.callWS);
// Advance 30 minutes
await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
@@ -255,8 +255,8 @@ describe("scheduleBrandsTokenRefresh", () => {
},
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
scheduleBrandsTokenRefresh(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
scheduleBrandsTokenRefresh(mockHass.callWS);
// Advance 29 minutes — should not have refreshed
await vi.advanceTimersByTimeAsync(29 * 60 * 1000);
@@ -273,8 +273,8 @@ describe("scheduleBrandsTokenRefresh", () => {
},
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
scheduleBrandsTokenRefresh(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
scheduleBrandsTokenRefresh(mockHass.callWS);
clearBrandsTokenRefresh();
// Advance 30 minutes — should not have refreshed because we cleared
@@ -295,25 +295,25 @@ describe("subscribeBrandsAccessToken", () => {
const mockHass = {
callWS: async () => ({ token }),
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
const listener = vi.fn();
const unsubscribe = subscribeBrandsAccessToken(listener);
assert.deepEqual(listener.mock.calls, [["subscribed-token-1"]]);
// Unchanged token: no call
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
assert.strictEqual(listener.mock.calls.length, 1);
// The 30 minute refresh reports the rotated token
token = "subscribed-token-2";
scheduleBrandsTokenRefresh(mockHass);
scheduleBrandsTokenRefresh(mockHass.callWS);
await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
assert.deepEqual(listener.mock.calls[1], ["subscribed-token-2"]);
unsubscribe();
token = "subscribed-token-3";
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
assert.strictEqual(listener.mock.calls.length, 2);
});
});
@@ -338,7 +338,7 @@ describe("fetchAndScheduleBrandsAccessToken", () => {
},
} as unknown as HomeAssistant;
const promise = fetchAndScheduleBrandsAccessToken(mockHass);
const promise = fetchAndScheduleBrandsAccessToken(mockHass.callWS);
// First attempt fires immediately, fails
await vi.advanceTimersByTimeAsync(0);
@@ -369,10 +369,10 @@ describe("fetchAndScheduleBrandsAccessToken", () => {
} as unknown as HomeAssistant;
// Prime the cached token
await fetchBrandsAccessToken(mockHass);
await fetchBrandsAccessToken(mockHass.callWS);
// Same token returned → no change
const changed = await fetchAndScheduleBrandsAccessToken(mockHass);
const changed = await fetchAndScheduleBrandsAccessToken(mockHass.callWS);
assert.strictEqual(changed, false);
});
@@ -386,7 +386,7 @@ describe("fetchAndScheduleBrandsAccessToken", () => {
},
} as unknown as HomeAssistant;
const promise = fetchAndScheduleBrandsAccessToken(mockHass);
const promise = fetchAndScheduleBrandsAccessToken(mockHass.callWS);
// Exhaust all retry delays: 500 + 1000 + 2000 + 5000 + 10000 + 15000
await vi.advanceTimersByTimeAsync(33500);