Compare commits

..
11 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
WendelinandClaude Opus 5.5 4fbaf8c0a8 Group discovered devices by integration in the add dialog (#56315)
* Group discovered devices by integration in the add dialog

An integration with more than one discovered device now shows one row
with a count, which opens a page with all its discovered devices.
Discovered flows also show the integration's name instead of its domain
when it has no translated title.

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

* Use nextRender to focus after the discovered group changes

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

* Remove an unneeded comment

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

* Remove the count badge from discovered groups

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 16:29:25 +01:00
87 changed files with 919 additions and 1952 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) {
-51
View File
@@ -54,57 +54,6 @@ lorem | ipsum
`,
})
),
mdContentwithDefaults({
content: `
<p align="center">
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
</p>
- [Installation](#installation)
- [Configuration](#configuration)
## Installation
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
## Configuration
Add the integration from the integrations page.
[Back to the top](#installation)
[^marketplace]: Settings > Marketplace.
[^restart]: Only needed the first time.
`,
}),
mdContentwithDefaults({
content: `
\`\`\`mermaid
flowchart LR
router[Router] --> switch[Switch]
switch --> nas[(NAS)]
switch --> ha[[Home Assistant]]
ha -. Zigbee .-> lights([Lights])
\`\`\`
\`\`\`mermaid
sequenceDiagram
Door sensor->>Home Assistant: Opened
Home Assistant->>Hallway light: Turn on
Hallway light-->>Home Assistant: On
\`\`\`
`,
}),
mdContentwithDefaults({
content: `
A diagram that doesn't parse shows the error and its source:
\`\`\`mermaid
flowchart LR
A -->
\`\`\`
`,
}),
];
@customElement("demo-misc-ha-markdown")
+1 -4
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",
@@ -110,10 +110,7 @@
"lit-html": "3.3.3",
"maplibre-gl": "6.20.0",
"marked": "18.3.0",
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"memoize-one": "7.0.0",
"mermaid": "12.4.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
+5 -847
View File
File diff suppressed because it is too large. Load diff
-17
View File
@@ -50,23 +50,6 @@ export const getRGBContrastRatio = (
rgb2: [number, number, number]
) => Math.round((rgbContrast(rgb1, rgb2) + Number.EPSILON) * 100) / 100;
/**
* Parses an `--rgb-*` theme variable, such as `--rgb-primary-text-color`
* @param value - The variable's value, such as `33, 33, 33`
* @returns The red, green and blue values, or undefined when it isn't three numbers
*/
export const parseRgbVariable = (
value: string
): [number, number, number] | undefined => {
const parts = value.split(",").map((part) => parseInt(part, 10));
if (parts.length !== 3 || parts.some((part) => Number.isNaN(part))) {
return undefined;
}
return [parts[0], parts[1], parts[2]];
};
/**
* Tells whether a color can be measured, which a CSS function that is passed
* through unevaluated cannot, and whether it covers what is behind it
@@ -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;
+5 -129
View File
@@ -1,20 +1,11 @@
import type { PropertyValues } from "lit";
import { ReactiveElement, render, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property } from "lit/decorators";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import hash from "object-hash";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { rewriteHtmlUrls } from "../common/dom/rewrite-html-urls";
import { internationalizationContext } from "../data/context";
import type { FootnoteLabels } from "../resources/markdown-worker";
import {
USER_CONTENT_PREFIX,
userContentId,
} from "../resources/markdown-user-content";
import { renderMarkdown } from "../resources/render-markdown";
import type { HomeAssistantInternationalization } from "../types";
import { CacheManager } from "../util/cache-manager";
const h = (template: ReturnType<typeof unsafeHTML>) => html`${template}`;
@@ -52,35 +43,8 @@ class HaMarkdownElement extends ReactiveElement {
// For content whose relative addresses belong elsewhere, like a README
@property({ attribute: false }) public rewriteUrl?: (url: string) => string;
// Without translations, like on the auth pages, the worker uses English
@state({
hasChanged: (value?: FootnoteLabels, oldValue?: FootnoteLabels) =>
value?.heading !== oldValue?.heading ||
value?.backReference !== oldValue?.backReference,
})
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FootnoteLabels>({
transformer: ({ localize }) => {
const heading = localize("ui.components.markdown.footnotes");
const backReference = localize(
"ui.components.markdown.footnote_back_reference",
{ reference: "{0}" }
);
return heading && backReference ? { heading, backReference } : undefined;
},
})
private _footnoteLabels?: FootnoteLabels;
public connectedCallback() {
super.connectedCallback();
this.addEventListener("click", this._handleAnchorClick);
}
public disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("click", this._handleAnchorClick);
if (this.cache) {
const key = this._computeCacheKey();
markdownCache.set(key, this.innerHTML);
@@ -123,7 +87,6 @@ class HaMarkdownElement extends ReactiveElement {
allowDataUrl: this.allowDataUrl,
breaks: this.breaks,
rewriteUrl: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
});
}
@@ -138,7 +101,6 @@ class HaMarkdownElement extends ReactiveElement {
allowSvg: this.allowSvg,
allowDataUrl: this.allowDataUrl,
allowRelativeUrls: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
}
);
@@ -229,104 +191,18 @@ class HaMarkdownElement extends ReactiveElement {
}
} else if (
node instanceof HTMLElement &&
[
"ha-alert",
"ha-qr-code",
"ha-icon",
"ha-svg-icon",
"ha-mermaid-diagram",
].includes(node.localName)
["ha-alert", "ha-qr-code", "ha-icon", "ha-svg-icon"].includes(
node.localName
)
) {
import(
/* webpackInclude: /(ha-alert)|(ha-qr-code)|(ha-icon)|(ha-svg-icon)|(ha-mermaid-diagram)/ */ `./${node.localName}`
/* webpackInclude: /(ha-alert)|(ha-qr-code)|(ha-icon)|(ha-svg-icon)/ */ `./${node.localName}`
);
}
}
}
private _resize = () => fireEvent(this, "content-resize");
// The content is in a shadow root, so the browser can't scroll to a `#` link
// in it, and the app would navigate to it instead
private _handleAnchorClick = (ev: MouseEvent) => {
// Leave opening the link in a new tab or window to the browser
if (
ev.defaultPrevented ||
ev.button !== 0 ||
ev.metaKey ||
ev.ctrlKey ||
ev.shiftKey
) {
return;
}
const anchor = ev
.composedPath()
.find((node) => node instanceof HTMLAnchorElement);
// Or one the author set to open somewhere else
if (anchor?.target && anchor.target !== "_self") {
return;
}
const href = anchor?.getAttribute("href");
if (!href?.startsWith("#") || href.length === 1) {
return;
}
const fragment = href.slice(1);
// Browsers take #top as the top of the page, READMEs use it for the top
const target =
this._findAnchorTarget(fragment) ??
(fragment.toLowerCase() === "top" ? this : undefined);
// An anchor that isn't in the content does what it did before
if (target) {
ev.preventDefault();
target.scrollIntoView({ block: "start" });
// Move focus there too, like the browser does, so Tab carries on from
// the target. -1 makes a heading focusable without adding it to Tab.
if (target instanceof HTMLElement) {
if (!target.hasAttribute("tabindex") && target.tabIndex < 0) {
target.tabIndex = -1;
}
target.focus({ preventScroll: true });
}
}
};
// Links like `#Setup` and `#%C3%BCber` still find `user-content-setup` and
// `user-content-über`, like on GitHub
private _findAnchorTarget(fragment: string) {
let decoded = fragment;
try {
decoded = decodeURIComponent(fragment);
} catch {
// Not encoded, look for it as written
}
const ids = [fragment, decoded, decoded.toLowerCase()].flatMap((id) => [
userContentId(id),
// Heading ids always get the prefix, so `## user-content-setup` has
// `user-content-user-content-setup`
`${USER_CONTENT_PREFIX}${id}`,
]);
for (const id of new Set(ids)) {
const target = this.querySelector(`[id="${CSS.escape(id)}"]`);
if (target) {
return target;
}
}
return undefined;
}
}
declare global {
-15
View File
@@ -201,21 +201,6 @@ export class HaMarkdown extends LitElement {
margin-inline: 0;
padding-inline: 1em;
}
section[data-footnotes] {
border-top: 1px solid var(--divider-color);
margin-top: var(--ha-space-4);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
/* Read out by screen readers but not shown, like on GitHub */
section[data-footnotes] > h2 {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
` as CSSResultGroup;
}
+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();
-260
View File
@@ -1,260 +0,0 @@
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { rgb2hex } from "../common/color/convert-color";
import { parseRgbVariable } from "../common/color/rgb";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import type { LocalizeFunc } from "../common/translations/localize";
import { internationalizationContext, uiContext } from "../data/context";
import type {
HomeAssistantInternationalization,
HomeAssistantUI,
} from "../types";
import "./ha-alert";
type Rgb = [number, number, number];
// How much of the primary colour tints the boxes, so their text stays readable
const PRIMARY_TINT = 0.15;
const MAX_CACHED_DIAGRAMS = 50;
// The drawn SVG for each theme and source, so a card that renders its markdown
// again, like on every template update, doesn't redraw and flicker
const svgCache = new Map<string, string>();
let mermaidQueue: Promise<unknown> = Promise.resolve();
let diagramCount = 0;
// mermaid.initialize() sets global options, so diagrams are drawn one at a
// time, or two with different theme colours would pick up each other's
const drawDiagram = (
source: string,
themeVariables: Record<string, string | boolean>
): Promise<string> => {
const result = mermaidQueue.then(async () => {
const { default: mermaid } = await import("mermaid");
mermaid.initialize({
startOnLoad: false,
// Sanitises the SVG, encodes HTML in labels and turns off click handlers.
// Templates can put entity names and states in the source.
securityLevel: "strict",
// Show our own error instead of Mermaid's error picture
suppressErrorRendering: true,
// Mermaid 12 lays diagrams out with ELK by default, which adds 1.5 MB
// to every flowchart. A diagram can still ask for it in its config.
layout: "dagre",
theme: "base",
themeVariables,
});
diagramCount++;
const { svg } = await mermaid.render(`ha-mermaid-${diagramCount}`, source);
return svg;
});
// A diagram that fails must not stop the ones after it
mermaidQueue = result.catch(() => undefined);
return result;
};
const tint = (background: number, primary: number) =>
Math.round(background + (primary - background) * PRIMARY_TINT);
interface ThemeState {
theme?: string;
darkMode?: boolean;
}
@customElement("ha-mermaid-diagram")
export class HaMermaidDiagram extends LitElement {
// The markdown is rendered again as a whole when it changes, so the source
// of one element never changes
@state() private _source?: string;
@state() private _svg?: string;
@state() private _error?: string;
// A theme or dark mode switch draws the diagram again in the new colours
@state({
hasChanged: (value?: ThemeState, oldValue?: ThemeState) =>
value?.theme !== oldValue?.theme ||
value?.darkMode !== oldValue?.darkMode,
})
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, ThemeState>({
transformer: ({ themes }) => ({
theme: themes?.theme,
darkMode: themes?.darkMode,
}),
})
private _theme?: ThemeState;
// Without translations, like on the auth pages, the error has no title
@state()
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, LocalizeFunc>({
transformer: ({ localize }) => localize,
})
private _localize?: LocalizeFunc;
public connectedCallback() {
super.connectedCallback();
this._source ??= this.textContent ?? "";
}
protected updated(changedProperties: PropertyValues) {
super.updated(changedProperties);
if (changedProperties.has("_source") || changedProperties.has("_theme")) {
this._draw();
}
if (changedProperties.has("_svg") || changedProperties.has("_error")) {
fireEvent(this, "content-resize");
}
}
private async _draw() {
const source = this._source;
if (!source?.trim()) {
return;
}
const themeVariables = this._themeVariables();
const key = `${JSON.stringify(themeVariables)}\n${source}`;
const cached = svgCache.get(key);
if (cached) {
this._svg = cached;
this._error = undefined;
return;
}
try {
const svg = await drawDiagram(source, themeVariables);
svgCache.set(key, svg);
// A Map keeps insertion order, so the first key is the oldest
const oldest = svgCache.keys().next().value;
if (svgCache.size > MAX_CACHED_DIAGRAMS && oldest !== undefined) {
svgCache.delete(oldest);
}
this._svg = svg;
this._error = undefined;
} catch (err) {
this._svg = undefined;
this._error = err instanceof Error ? err.message : String(err);
}
}
// Mermaid works out its other colours from these, but not the edge label
// background. It can't read var() or rgba(), so use the --rgb-* variables.
// They come from this element, so a card or view theme applies too.
private _themeVariables() {
const style = getComputedStyle(this);
const rgbVariable = (name: string, fallback: Rgb): Rgb =>
parseRgbVariable(style.getPropertyValue(name)) ?? fallback;
const background = rgbVariable(
"--rgb-card-background-color",
[255, 255, 255]
);
const primary = rgbVariable("--rgb-primary-color", [0, 154, 199]);
const text = rgbVariable("--rgb-primary-text-color", [33, 33, 33]);
const secondaryText = rgbVariable(
"--rgb-secondary-text-color",
[114, 114, 114]
);
const boxes: Rgb = [
tint(background[0], primary[0]),
tint(background[1], primary[1]),
tint(background[2], primary[2]),
];
return {
darkMode: Boolean(this._theme?.darkMode),
background: rgb2hex(background),
edgeLabelBackground: rgb2hex(background),
mainBkg: rgb2hex(boxes),
primaryColor: rgb2hex(boxes),
primaryBorderColor: rgb2hex(primary),
primaryTextColor: rgb2hex(text),
textColor: rgb2hex(text),
lineColor: rgb2hex(secondaryText),
fontFamily: style.fontFamily,
};
}
protected render() {
if (this._error) {
return html`
<ha-alert
alert-type="warning"
.title=${
this._localize?.("ui.components.markdown.diagram_error") ?? ""
}
>
<span class="error">${this._error}</span>
</ha-alert>
<pre><code>${this._source}</code></pre>
`;
}
return this._svg ? unsafeHTML(this._svg) : nothing;
}
static styles = css`
:host {
display: block;
overflow-x: auto;
}
svg {
display: block;
margin: 0 auto;
}
/* Mermaid points at the error with a ^ under the line, which only lines
up in a monospace font */
.error {
white-space: pre-wrap;
font-family: var(--ha-font-family-code);
font-size: var(--ha-font-size-s);
}
pre {
background-color: var(--markdown-code-background-color, none);
border-radius: var(--ha-border-radius-sm);
color: var(--markdown-code-text-color, inherit);
padding: var(--ha-space-4);
overflow: auto;
line-height: var(--ha-line-height-condensed);
font-family: var(--ha-font-family-code);
}
code {
font-size: var(--ha-font-size-s);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-mermaid-diagram": HaMermaidDiagram;
}
}
+9 -1
View File
@@ -7,13 +7,21 @@ import { rgb2hex } from "../common/color/convert-color";
import {
getContrastedColorHex,
getRGBContrastRatio,
parseRgbVariable,
} from "../common/color/rgb";
// Minimum contrast ratio (WCAG non-text minimum) below which we substitute a
// legible foreground so the QR code never renders unscannable.
const MIN_CONTRAST_RATIO = 3;
const parseRgbVariable = (
value: string
): [number, number, number] | undefined => {
const parts = value.split(",").map((part) => parseInt(part, 10));
return parts.length === 3 && parts.every((part) => !Number.isNaN(part))
? (parts as [number, number, number])
: undefined;
};
@customElement("ha-qr-code")
export class HaQrCode extends LitElement {
@property() public data?: string;
@@ -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 -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);
@@ -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) {
@@ -28,6 +28,7 @@ import {
} from "../../../common/integrations/protocolIntegrationPicked";
import { navigate } from "../../../common/navigate";
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
import { nextRender } from "../../../common/util/render-status";
import type {
LocalizeFunc,
LocalizeKeys,
@@ -109,6 +110,7 @@ import {
} from "./add-integration-list";
import "./ha-integration-list-item";
import "./ha-integration-list-title";
import type { HaDomainIntegrations } from "./ha-domain-integrations";
import type { HaIntegrationListItem } from "./ha-integration-list-item";
import type { AddIntegrationDialogParams } from "./show-add-integration-dialog";
import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
@@ -169,6 +171,9 @@ class AddIntegrationDialog extends LitElement {
@state() private _showDiscovered = false;
// The discovered devices of one integration
@state() private _discoveredDomain?: string;
@state() private _openedDirectly = false;
@state() private _navigateToResult = false;
@@ -186,6 +191,9 @@ class AddIntegrationDialog extends LitElement {
@query("ha-input-search") private _searchInput?: HaInputSearch;
@query("ha-domain-integrations")
private _domainIntegrations?: HaDomainIntegrations;
// The focused row is gone after drilling
private _focusAfterDrill?: "in" | "out";
@@ -274,6 +282,7 @@ class AddIntegrationDialog extends LitElement {
this._prevPickedBrand = undefined;
this._flowsInProgress = undefined;
this._showDiscovered = false;
this._discoveredDomain = undefined;
this._openedDirectly = false;
this._navigateToResult = false;
this._filter = undefined;
@@ -900,24 +909,47 @@ class AddIntegrationDialog extends LitElement {
findIntegration(this._integrations, this._pickedBrand)
: undefined;
const showingPickedBrand = Boolean(
this._pickedBrand && (!this._integrations || pickedIntegration)
);
const showingDiscoveredGroup =
!showingPickedBrand && !!this._discoveredDomain;
const showingBrandView =
(this._pickedBrand && (!this._integrations || pickedIntegration)) ||
this._showDiscovered;
showingPickedBrand || showingDiscoveredGroup || this._showDiscovered;
const flowsInProgress = showingBrandView
? this._getFlowsForCurrentView(pickedIntegration)
: [];
const brandDomain = showingPickedBrand
? this._pickedBrand
: showingDiscoveredGroup
? this._discoveredDomain
: undefined;
const brandIntegration = showingPickedBrand
? pickedIntegration
: showingDiscoveredGroup
? findIntegration(this._integrations, this._discoveredDomain!)
: undefined;
const headerTitle = showingBrandView
? this._getBrandHeading(pickedIntegration, flowsInProgress)
: this._narrow && this._drilled
? this._browsingTitle()
: this.hass.localize(
"ui.panel.config.integrations.add_device_or_integration"
);
const flowsInProgress = showingPickedBrand
? this._getFlowsForBrand(pickedIntegration)
: showingDiscoveredGroup
? this._getFlowsForDiscoveredGroup(this._discoveredDomain!)
: this._showDiscovered
? this._flowsInProgress || []
: [];
const headerSubtitle =
!showingBrandView && this._narrow && this._drilled
const headerTitle = showingDiscoveredGroup
? brandIntegration?.name ||
domainToName(this.hass.localize, this._discoveredDomain!)
: showingBrandView
? this._getBrandHeading(pickedIntegration, flowsInProgress)
: this._narrow && this._drilled
? this._browsingTitle()
: this.hass.localize(
"ui.panel.config.integrations.add_device_or_integration"
);
const headerSubtitle = showingDiscoveredGroup
? this.hass.localize("ui.panel.config.integrations.discovered")
: !showingBrandView && this._narrow && this._drilled
? this._subcategory
? integrationCategoryName(this.hass.localize, this._category!)
: this.hass.localize(
@@ -938,7 +970,7 @@ class AddIntegrationDialog extends LitElement {
showingBrandView
? html`
${
!this._openedDirectly
!this._openedDirectly || this._discoveredDomain
? html`
<ha-icon-button-prev
slot="headerNavigationIcon"
@@ -947,7 +979,12 @@ class AddIntegrationDialog extends LitElement {
`
: nothing
}
${this._renderBrandView(pickedIntegration, flowsInProgress)}
${this._renderBrandView(
brandDomain,
brandIntegration,
flowsInProgress,
!showingPickedBrand && !showingDiscoveredGroup
)}
`
: html`
${
@@ -991,13 +1028,15 @@ class AddIntegrationDialog extends LitElement {
);
}
private _getFlowsForCurrentView(
private _getFlowsForDiscoveredGroup(domain: string) {
return (this._flowsInProgress || []).filter(
(flow) => flow.handler === domain
);
}
private _getFlowsForBrand(
integration: Brand | Integration | undefined
): DataEntryFlowProgress[] {
if (this._showDiscovered) {
// Show all discovered flows
return this._flowsInProgress || [];
}
if (!this._pickedBrand || !integration) {
return [];
}
@@ -1044,23 +1083,39 @@ class AddIntegrationDialog extends LitElement {
}
private _renderBrandView(
domain: string | undefined,
integration: Brand | Integration | undefined,
flowsInProgress: DataEntryFlowProgress[]
flowsInProgress: DataEntryFlowProgress[],
groupFlows: boolean
): TemplateResult {
return html`<ha-domain-integrations
.hass=${this.hass}
.domain=${this._pickedBrand}
.domain=${domain}
.integration=${integration}
.flowsInProgress=${flowsInProgress}
.navigateToResult=${this._navigateToResult}
.showManageLink=${this._showDiscovered || this._showDiscoveredView}
.boxed=${!integration}
.groupFlows=${groupFlows}
.brands=${this._integrations}
@close-dialog=${this.closeDialog}
@supported-by=${this._handleSupportedByEvent}
@select-brand=${this._handleSelectBrandEvent}
@discovered-group-picked=${this._handleDiscoveredGroupPicked}
></ha-domain-integrations>`;
}
private async _handleDiscoveredGroupPicked(
ev: HASSDomEvent<HASSDomEvents["discovered-group-picked"]>
) {
this._discoveredDomain = ev.detail.domain;
// The picked row is gone, and the back button renders after this element
await nextRender();
if (this._discoveredDomain) {
this._backButton?.focus();
}
}
private _handleSelectBrandEvent(ev: CustomEvent) {
this._prevPickedBrand = this._pickedBrand;
this._pickedBrand = ev.detail.brand;
@@ -1178,7 +1233,12 @@ class AddIntegrationDialog extends LitElement {
${
this._showDiscoveredView && !this._filter
? html`<div class="discovered">
${this._renderBrandView(undefined, this._flowsInProgress || [])}
${this._renderBrandView(
undefined,
undefined,
this._flowsInProgress || [],
true
)}
</div>`
: rows
? html`${
@@ -2063,12 +2123,25 @@ class AddIntegrationDialog extends LitElement {
}
private _prevClicked() {
if (this._showDiscovered) {
this._showDiscovered = false;
if (this._pickedBrand) {
this._pickedBrand = this._prevPickedBrand;
this._prevPickedBrand = undefined;
return;
}
this._pickedBrand = this._prevPickedBrand;
this._prevPickedBrand = undefined;
if (this._discoveredDomain) {
const domain = this._discoveredDomain;
this._discoveredDomain = undefined;
this._focusFlowGroupAfterBack(domain);
return;
}
this._showDiscovered = false;
}
private async _focusFlowGroupAfterBack(domain: string) {
await nextRender();
if (this._open && !this._discoveredDomain) {
this._domainIntegrations?.focusFlowGroup(domain);
}
}
static styles = [
@@ -1,7 +1,8 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import { mdiPlus } from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, queryAll } from "lit/decorators";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
@@ -13,8 +14,10 @@ import {
import { navigate } from "../../../common/navigate";
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
import "../../../components/ha-button";
import "../../../components/ha-icon-next";
import "../../../components/ha-svg-icon";
import "../../../components/item/ha-list-item-button";
import type { HaListItemButton } from "../../../components/item/ha-list-item-button";
import "../../../components/list/ha-list-base";
import { localizeConfigFlowTitle } from "../../../data/config_flow";
import type { DataEntryFlowProgress } from "../../../data/data_entry_flow";
@@ -22,7 +25,8 @@ import {
domainToName,
fetchIntegrationManifest,
} from "../../../data/integration";
import type { Brand, Integration } from "../../../data/integrations";
import type { Brand, Brands, Integration } from "../../../data/integrations";
import { findIntegration } from "../../../data/integrations";
import { showConfigFlowDialog } from "../../../dialogs/config-flow/show-dialog-config-flow";
import { haStyle } from "../../../resources/styles";
import type { HomeAssistant } from "../../../types";
@@ -33,7 +37,7 @@ import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
export const standardToDomain = { zigbee: "zha", zwave: "zwave_js" } as const;
@customElement("ha-domain-integrations")
class HaDomainIntegrations extends LitElement {
export class HaDomainIntegrations extends LitElement {
public hass!: HomeAssistant;
@property() public domain!: string;
@@ -51,6 +55,15 @@ class HaDomainIntegrations extends LitElement {
@property({ type: Boolean, reflect: true }) public boxed = false;
/** An integration with more than one discovered device gets one row. */
@property({ attribute: false }) public groupFlows = false;
/** Names integrations that have no translated title, like most that aren't set up. */
@property({ attribute: false }) public brands?: Brands;
@queryAll("ha-list-item-button.flow-group")
private _flowGroups!: NodeListOf<HaListItemButton & { domain: string }>;
protected render() {
// Only show manage link if not already on the integrations dashboard
const manage =
@@ -63,36 +76,11 @@ class HaDomainIntegrations extends LitElement {
? html`<h3>
${this.hass.localize("ui.panel.config.integrations.discovered")}
</h3>
${this.flowsInProgress.map(
(flow) =>
html`<ha-list-item-button
.flow=${flow}
@click=${this._flowInProgressPicked}
>
<img
alt=""
slot="start"
loading="lazy"
src=${brandsUrl(
{
domain: flow.handler,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
>
<span slot="supporting-text"
>${domainToName(this.hass.localize, flow.handler)}</span
>
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
</ha-list-item-button>`
)}
${
this.groupFlows
? this._renderFlowGroups(this.flowsInProgress)
: this.flowsInProgress.map((flow) => this._renderFlow(flow))
}
<wa-divider></wa-divider>
${
this.integration &&
@@ -303,6 +291,87 @@ class HaDomainIntegrations extends LitElement {
</div>`;
}
public async focusFlowGroup(domain: string) {
await this.updateComplete;
[...this._flowGroups].find((row) => row.domain === domain)?.focus();
}
private _renderFlowGroups(flows: DataEntryFlowProgress[]) {
const groups = new Map<string, DataEntryFlowProgress[]>();
flows.forEach((flow) => {
groups.set(flow.handler, [...(groups.get(flow.handler) || []), flow]);
});
if (groups.size === 1) {
return flows.map((flow) => this._renderFlow(flow));
}
return [...groups.entries()].map(([domain, group]) =>
group.length === 1
? this._renderFlow(group[0])
: html`<ha-list-item-button
class="flow-group"
.domain=${domain}
@click=${this._flowGroupPicked}
>
${this._renderIcon(domain)}
<span slot="headline">${this._domainName(domain)}</span>
<span slot="supporting-text"
>${this.hass.localize(
"ui.panel.config.integrations.discovered_devices",
{ count: group.length }
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
);
}
private _renderFlow(flow: DataEntryFlowProgress) {
return html`<ha-list-item-button
.flow=${flow}
@click=${this._flowInProgressPicked}
>
${this._renderIcon(flow.handler)}
<span slot="headline"
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
>
<span slot="supporting-text">${this._domainName(flow.handler)}</span>
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
</ha-list-item-button>`;
}
private _domainName(domain: string) {
return (
findIntegration(this.brands, domain)?.name ||
domainToName(this.hass.localize, domain)
);
}
private _renderIcon(domain: string): TemplateResult {
return html`<img
alt=""
slot="start"
loading="lazy"
src=${brandsUrl(
{
domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>`;
}
private _flowGroupPicked(
ev: HASSDomCurrentTargetEvent<HTMLElement & { domain: string }>
) {
fireEvent(this, "discovered-group-picked", {
domain: ev.currentTarget.domain,
});
}
private async _integrationPicked(
ev: HASSDomCurrentTargetEvent<HTMLElement & { domain: string }>
) {
@@ -496,4 +565,8 @@ declare global {
interface HTMLElementTagNameMap {
"ha-domain-integrations": HaDomainIntegrations;
}
interface HASSDomEvents {
"discovered-group-picked": { domain: string };
}
}
@@ -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,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`
@@ -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
? {
@@ -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)
+1 -1
View File
@@ -40,7 +40,7 @@ export const repositoryUrl =
// A browser trims it, "https:" can follow a space
const destination = rawGitHubFile(url.trim());
// ha-markdown scrolls to an anchor in the README itself
// Headings get no ids, so an anchor has nothing to point at on this page
if (
!repository ||
destination.startsWith("#") ||
+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) {
-6
View File
@@ -1,6 +0,0 @@
// Every id in rendered markdown starts with this, like on GitHub, so it can't
// clash with the ids of the page around it
export const USER_CONTENT_PREFIX = "user-content-";
export const userContentId = (id: string) =>
id.startsWith(USER_CONTENT_PREFIX) ? id : `${USER_CONTENT_PREFIX}${id}`;
+15 -132
View File
@@ -1,8 +1,6 @@
import { expose } from "comlink";
import type { MarkedOptions } from "marked";
import { Marked, Renderer } from "marked";
import markedFootnote from "marked-footnote";
import { gfmHeadingId, resetHeadings } from "marked-gfm-heading-id";
import { marked } from "marked";
import type { IWhiteList } from "xss";
import {
escapeAttrValue,
@@ -12,82 +10,6 @@ import {
safeAttrValue,
} from "xss";
import { URL_ATTRIBUTES } from "../common/dom/rewrite-html-urls";
import { USER_CONTENT_PREFIX, userContentId } from "./markdown-user-content";
export interface FootnoteLabels {
// Read out by screen readers above the footnotes
heading: string;
// The label of the link back to a reference, "{0}" is its number
backReference: string;
}
const DEFAULT_FOOTNOTE_LABELS: FootnoteLabels = {
heading: "Footnotes",
backReference: "Back to reference {0}",
};
// The footnote labels are set when the extension is created and an extension
// can't be removed again, so each language gets its own instance
const markedInstances = new Map<string, Marked>();
const markedFor = (labels: FootnoteLabels) => {
const key = `${labels.heading}\n${labels.backReference}`;
let instance = markedInstances.get(key);
if (!instance) {
instance = new Marked(
{
renderer: {
table(...args) {
const defaultRenderer = new Renderer();
// Wrap the table with block element because the property 'overflow'
// cannot be applied to elements of display type 'table'.
// https://www.w3.org/TR/css-overflow-3/#overflow-control
return `<div>${defaultRenderer.table.apply(this, args)}</div>`;
},
// xss drops the language class, so mark diagrams with their own tag.
// false leaves every other code block to the default renderer.
code({ text, lang }) {
// The first word of the info string, like GitHub
if (lang?.match(/^\S*/)?.[0].toLowerCase() !== "mermaid") {
return false;
}
return `<ha-mermaid-diagram>${text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</ha-mermaid-diagram>`;
},
},
},
gfmHeadingId({ prefix: USER_CONTENT_PREFIX }),
markedFootnote({
prefixId: `${USER_CONTENT_PREFIX}fn-`,
description: labels.heading,
backRefLabel: labels.backReference,
// [1] like on GitHub, so references next to each other don't read as 12
refMarkers: true,
// xss drops classes, the styles use data-footnotes instead
sectionClass: "",
headingClass: "",
})
);
markedInstances.set(key, instance);
}
return instance;
};
// Decode an attribute value like the browser would. friendlyAttrValue leaves
// `&amp;` as it is.
const decodeAttribute = (value: string) =>
friendlyAttrValue(value).replace(/&amp;/g, "&");
// Write a decoded value back so the browser reads what was checked: escape `&`
// too, or the browser would decode it a second time
const attribute = (name: string, decoded: string) =>
`${name}="${escapeAttrValue(decoded.replace(/&/g, "&amp;"))}"`;
let whiteListNormal: IWhiteList | undefined;
let whiteListSvg: IWhiteList | undefined;
@@ -146,27 +68,12 @@ const renderMarkdown = async (
allowSvg?: boolean;
allowDataUrl?: boolean;
allowRelativeUrls?: boolean;
footnoteLabels?: FootnoteLabels;
} = {}
): Promise<string[]> => {
if (!whiteListNormal) {
const defaultWhiteList = getDefaultWhiteList();
// READMEs centre their logo and badges with align
const withAlign = (tag: string) => [
...(defaultWhiteList[tag] ?? []),
"align",
];
whiteListNormal = {
...defaultWhiteList,
...Object.fromEntries(
["p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "img"].map((tag) => [
tag,
withAlign(tag),
])
),
table: [...(defaultWhiteList.table ?? []), "role"],
...getDefaultWhiteList(),
table: [...(getDefaultWhiteList().table ?? []), "role"],
input: ["type", "disabled", "checked"],
// Allows <picture>, and <video>/<audio> that have <source> children.
picture: [],
@@ -182,7 +89,6 @@ const renderMarkdown = async (
"error-correction-level",
"center-image",
],
"ha-mermaid-diagram": [],
};
}
@@ -194,7 +100,7 @@ const renderMarkdown = async (
...whiteListNormal,
svg: ["xmlns", "height", "width"],
path: ["transform", "stroke", "d"],
img: ["src", "align"],
img: ["src"],
};
}
whiteList = whiteListSvg;
@@ -206,23 +112,21 @@ const renderMarkdown = async (
whiteList = { ...whiteList, a: [...(whiteList.a ?? []), "download"] };
}
const marked = markedFor(
hassOptions.footnoteLabels ?? DEFAULT_FOOTNOTE_LABELS
);
marked.setOptions(markedOptions);
// The blocks are parsed one by one, which skips what marked's own parse()
// runs around them: the heading ids would keep counting up from the last
// render, and the footnotes would stay at the top and break the next render
resetHeadings();
marked.use({
renderer: {
table(...args) {
const defaultRenderer = new marked.Renderer();
// Wrap the table with block element because the property 'overflow'
// cannot be applied to elements of display type 'table'.
// https://www.w3.org/TR/css-overflow-3/#overflow-control
return `<div>${defaultRenderer.table.apply(this, args)}</div>`;
},
},
});
const tokens = marked.lexer(content);
if (marked.defaults.walkTokens) {
marked.walkTokens(tokens, marked.defaults.walkTokens);
}
return tokens.map((token) =>
filterXSS(marked.parser([token]), {
whiteList,
@@ -248,27 +152,6 @@ const renderMarkdown = async (
if (tag === "source" && name === "srcset") {
return sanitizeSrcset(value);
}
// Ids keep the user-content- prefix, which a raw id or <a name> gets
// too, so links written for GitHub work and can't clash with the page
if (name === "id" || (tag === "a" && name === "name")) {
const id = decodeAttribute(value).trim();
return id && !/\s/.test(id) ? attribute("id", userContentId(id)) : "";
}
// What the footnotes extension writes, for styles and screen readers
if (tag === "section" && name === "data-footnotes") {
return "data-footnotes";
}
if (
tag === "a" &&
(name === "aria-describedby" || name === "aria-label")
) {
return attribute(name, decodeAttribute(value));
}
if (
hassOptions.allowDataUrl &&
tag === "a" &&
@@ -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);
+1 -5
View File
@@ -549,11 +549,6 @@
"subpage_tabs": "Pages"
},
"components": {
"markdown": {
"footnotes": "Footnotes",
"footnote_back_reference": "Back to reference {reference}",
"diagram_error": "Couldn't draw this diagram"
},
"safe_area_tool": {
"title": "Safe area",
"presets": {
@@ -8135,6 +8130,7 @@
"description": "Manage integrations with services or devices",
"integration": "integration",
"discovered": "Discovered",
"discovered_devices": "{count} {count, plural,\n one {device}\n other {devices}\n}",
"manage_discovered": "Manage discovered devices",
"manage_discovered_description": "Ignore or configure previously discovered devices",
"disabled": "Disabled",
+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,
-161
View File
@@ -288,167 +288,6 @@ describe("renderMarkdown", () => {
});
});
describe("footnotes", () => {
const content = ["Text with a note[^note].", "", "[^note]: The note."].join(
"\n"
);
// Twice, because the second render breaks if the first one leaves the
// footnotes extension's state behind
it.each([1, 2])("renders footnotes at the end (render %s)", async () => {
const fragment = parse(await render(content));
const ref = fragment.querySelector("sup > a");
expect(ref?.getAttribute("id")).toBe("user-content-fn-ref-note");
expect(ref?.getAttribute("href")).toBe("#user-content-fn-note");
expect(ref?.getAttribute("aria-describedby")).toBe(
"user-content-fn-label"
);
const section = fragment.lastElementChild;
expect(section?.matches("section[data-footnotes]")).toBe(true);
expect(section?.querySelector("li")?.getAttribute("id")).toBe(
"user-content-fn-note"
);
const backReference = section?.querySelector("li a");
expect(backReference?.getAttribute("href")).toBe(
"#user-content-fn-ref-note"
);
expect(backReference?.getAttribute("aria-label")).toBe(
"Back to reference note"
);
});
it("uses the labels it's given", async () => {
const fragment = parse(
(
await renderMarkdown(
content,
{},
{
footnoteLabels: {
heading: "Fußnoten",
backReference: "Zurück zu {0}",
},
}
)
).join("")
);
expect(fragment.querySelector("section h2")?.textContent).toBe(
"Fußnoten"
);
expect(
fragment.querySelector("section li a")?.getAttribute("aria-label")
).toBe("Zurück zu note");
});
it("leaves a reference without a footnote as text", async () => {
const html = await render("Text[^missing].");
expect(parse(html).querySelector("section, sup")).toBeNull();
expect(html).toContain("[^missing]");
});
});
describe("ids", () => {
const ids = async (content: string) =>
Array.from(parse(await render(content)).querySelectorAll("[id]")).map(
(element) => element.id
);
it("gives headings ids like GitHub", async () => {
expect(await ids("# Setup\n\n## Setup\n\n## Über uns")).toEqual([
"user-content-setup",
"user-content-setup-1",
"user-content-über-uns",
]);
});
it("starts the heading ids again on every render", async () => {
await render("# Setup");
expect(await ids("# Setup")).toEqual(["user-content-setup"]);
});
it("adds the prefix to an id or a link name in the content", async () => {
expect(
await ids(
'<a name="top"></a><span id="location">x</span><span id="user-content-kept">x</span>'
)
).toEqual([
"user-content-top",
"user-content-location",
"user-content-kept",
]);
});
// A link to #a&b has to find it, so the id can't keep the entity
it("decodes an ampersand in an id once", async () => {
expect(await ids('<span id="a&amp;b">x</span>')).toEqual([
"user-content-a&b",
]);
});
it("drops an id with a space", async () => {
expect(await ids('<span id="a b">x</span>')).toEqual([]);
});
});
describe("align", () => {
it.each(["p", "div", "h1", "h6"])("keeps align on %s", async (tag) => {
const element = parse(
await render(`<${tag} align="center" onclick="alert(1)">x</${tag}>`)
).querySelector(tag);
expect(element?.getAttributeNames()).toEqual(["align"]);
expect(element?.getAttribute("align")).toBe("center");
});
// SVG content has its own allowlist for img
it.each([false, true])(
"keeps align on img with allowSvg %s",
async (allowSvg) => {
expect(
parse(
await render(
'<img src="https://example.com/a.png" align="right">',
allowSvg
)
)
.querySelector("img")
?.getAttribute("align")
).toBe("right");
}
);
});
describe("mermaid", () => {
// The element reads its source back as text, so raw HTML in the source
// must stay text and the source must come back exactly as written
it("turns a mermaid block into a diagram with its source as text", async () => {
const source = 'flowchart LR\n A["<b onclick=alert(1)>&amp;</b>"] --> B';
const content = parse(
await render(`\`\`\`mermaid title\n${source}\n\`\`\``)
);
const diagram = content.querySelector("ha-mermaid-diagram");
expect(diagram?.getAttributeNames()).toEqual([]);
expect(diagram?.children).toHaveLength(0);
expect(diagram?.textContent).toBe(source);
expect(content.querySelector("pre")).toBeNull();
});
it("leaves other code blocks alone", async () => {
const content = parse(await render("```js\nconst a = 1;\n```"));
expect(content.querySelector("ha-mermaid-diagram")).toBeNull();
expect(content.querySelector("pre code")?.textContent).toBe(
"const a = 1;\n"
);
});
});
describe("data URLs", () => {
const renderLink = async (
content: string,
+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);