Compare commits

..
9 Commits
87 changed files with 1952 additions and 919 deletions

No files matched your search

+1 -2
View File
@@ -73,8 +73,7 @@ class HcLovelace extends LitElement {
if (index !== undefined) {
const title = getPanelTitleFromUrlPath(
this.hass.localize,
this.hass.panels,
this.hass,
this.urlPath || "lovelace"
);
+1 -2
View File
@@ -355,8 +355,7 @@ export class HcMain extends HassElement {
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
const title = getPanelTitleFromUrlPath(
this.hass!.localize,
this.hass!.panels,
this.hass!,
this._urlPath || "lovelace"
);
castContext.setApplicationState(title || "");
-12
View File
@@ -1,8 +1,6 @@
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";
@@ -16,16 +14,6 @@ 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,27 +22,20 @@ 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) {
const value = ev.detail.value;
this.changingLow = value;
this.changingHigh = value != null && value > this.high ? value : undefined;
this.changingLow = ev.detail.value;
}
private _highChanged(ev) {
this.high = ev.detail.value;
this.low = Math.min(this.low, this.high);
}
private _highChanging(ev) {
const value = ev.detail.value;
this.changingHigh = value;
this.changingLow = value != null && value < this.low ? value : undefined;
this.changingHigh = ev.detail.value;
}
private _currentChanged(ev) {
+51
View File
@@ -54,6 +54,57 @@ 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")
+4 -1
View File
@@ -84,7 +84,7 @@
"@vvo/tzdb": "6.208.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
"barcode-detector": "3.2.5",
"cally": "0.10.1",
"cally": "0.10.0",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
@@ -110,7 +110,10 @@
"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",
+847 -5
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -50,6 +50,23 @@ 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,29 +37,3 @@ 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;
};
+10 -20
View File
@@ -111,11 +111,6 @@ 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)
@@ -127,12 +122,19 @@ export class HaControlCircularSlider extends LitElement {
}
private _steppedValue(value: number) {
// 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);
return Math.round(value / this.step) * this.step;
}
private _boundedValue(value: number) {
return Math.min(Math.max(value, this.min), this.max);
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);
}
protected updated(changedProps: PropertyValues): void {
@@ -150,8 +152,6 @@ export class HaControlCircularSlider extends LitElement {
});
}
if (!this._activeSlider) {
this._lowBeforePush = undefined;
this._highBeforePush = undefined;
if (changedProps.has("value")) {
this._localValue = this.value;
}
@@ -235,19 +235,9 @@ 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;
+129 -5
View File
@@ -1,11 +1,20 @@
import type { PropertyValues } from "lit";
import { ReactiveElement, render, html } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } 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}`;
@@ -43,8 +52,35 @@ 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);
@@ -87,6 +123,7 @@ class HaMarkdownElement extends ReactiveElement {
allowDataUrl: this.allowDataUrl,
breaks: this.breaks,
rewriteUrl: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
});
}
@@ -101,6 +138,7 @@ class HaMarkdownElement extends ReactiveElement {
allowSvg: this.allowSvg,
allowDataUrl: this.allowDataUrl,
allowRelativeUrls: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
}
);
@@ -191,18 +229,104 @@ class HaMarkdownElement extends ReactiveElement {
}
} else if (
node instanceof HTMLElement &&
["ha-alert", "ha-qr-code", "ha-icon", "ha-svg-icon"].includes(
node.localName
)
[
"ha-alert",
"ha-qr-code",
"ha-icon",
"ha-svg-icon",
"ha-mermaid-diagram",
].includes(node.localName)
) {
import(
/* webpackInclude: /(ha-alert)|(ha-qr-code)|(ha-icon)|(ha-svg-icon)/ */ `./${node.localName}`
/* webpackInclude: /(ha-alert)|(ha-qr-code)|(ha-icon)|(ha-svg-icon)|(ha-mermaid-diagram)/ */ `./${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,6 +201,21 @@ 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;
}
+31 -47
View File
@@ -1,23 +1,17 @@
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, state } from "lit/decorators";
import { customElement, property } 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";
@@ -37,6 +31,8 @@ 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;
@@ -55,26 +51,6 @@ 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 {
@@ -92,6 +68,13 @@ 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
@@ -115,7 +98,7 @@ export class HaMediaItemPicker extends LitElement {
.value=${entityId}
.label=${
this.label ||
this._localize(
this.hass.localize(
"ui.components.selectors.media.pick_media_player"
)
}
@@ -131,19 +114,20 @@ export class HaMediaItemPicker extends LitElement {
`
}
${
this._supportsBrowse === false
!supportsBrowse
? html`
${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-alert>
${this._localize(
${this.hass.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._computeLabel(this._localize)}
.computeHelper=${this._computeHelper(this._localize)}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
></ha-form>
`
: html`${this.label ? html`<label>${this.label}</label>` : nothing}
@@ -153,7 +137,9 @@ export class HaMediaItemPicker extends LitElement {
role="button"
aria-label=${
!this.value?.media_content_id
? this._localize("ui.components.selectors.media.pick_media")
? this.hass.localize(
"ui.components.selectors.media.pick_media"
)
: this.value.metadata?.title || this.value.media_content_id
}
@click=${this._pickMedia}
@@ -210,7 +196,7 @@ export class HaMediaItemPicker extends LitElement {
<div class="title">
${
!this.value?.media_content_id
? this._localize(
? this.hass.localize(
"ui.components.selectors.media.pick_media"
)
: this.value.metadata?.title ||
@@ -223,7 +209,7 @@ export class HaMediaItemPicker extends LitElement {
: html`
<div class="delete">
<ha-icon-button
.label=${this._localize("ui.common.delete")}
.label=${this.hass.localize("ui.common.delete")}
.path=${mdiDelete}
@click=${this._clearValue}
></ha-icon-button>
@@ -241,7 +227,7 @@ export class HaMediaItemPicker extends LitElement {
variant="danger"
@click=${this._clearValue}
>
${this._localize(
${this.hass.localize(
"ui.components.picture-upload.clear_picture"
)}
</ha-button>
@@ -257,17 +243,15 @@ export class HaMediaItemPicker extends LitElement {
`;
}
private _computeLabel = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}`)
);
private _computeLabelCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}`);
private _computeHelper = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}_detail`)
);
private _computeHelperCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}_detail`);
private _entityChanged(ev: CustomEvent) {
ev.stopPropagation();
+260
View File
@@ -0,0 +1,260 @@
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;
}
}
+1 -9
View File
@@ -7,21 +7,13 @@ 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,14 +1,10 @@
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,
@@ -18,10 +14,7 @@ import {
formatOpenStreetMapPlace,
searchPlaces,
} from "../../data/openstreetmap";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../types";
import type { HomeAssistant } 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";
@@ -35,7 +28,6 @@ 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";
@@ -47,6 +39,8 @@ 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;
@@ -57,17 +51,6 @@ 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;
@@ -123,10 +106,10 @@ export class HaLocationSelector extends LitElement {
);
protected willUpdate() {
if (!this.value && this._hassConfig) {
if (!this.value) {
this.value = {
latitude: this._hassConfig.latitude,
longitude: this._hassConfig.longitude,
latitude: this.hass.config.latitude,
longitude: this.hass.config.longitude,
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
};
}
@@ -138,7 +121,7 @@ export class HaLocationSelector extends LitElement {
<div class="location-search" @keydown=${this._searchKeyDown}>
<ha-input
label=${this._i18n.localize(
label=${this.hass.localize(
"ui.components.selectors.location.address_label"
)}
.disabled=${this.disabled}
@@ -154,7 +137,7 @@ export class HaLocationSelector extends LitElement {
: html`<ha-icon-button
slot="end"
.path=${mdiMapSearchOutline}
.label=${this._i18n.localize("ui.common.search")}
.label=${this.hass.localize("ui.common.search")}
.disabled=${this.disabled}
@click=${this._searchButtonClicked}
></ha-icon-button>`
@@ -164,7 +147,7 @@ export class HaLocationSelector extends LitElement {
${
this._searchError
? html`<ha-alert alert-type="error">
${this._i18n.localize(
${this.hass.localize(
"ui.components.selectors.location.search_error"
)}
</ha-alert>`
@@ -182,7 +165,7 @@ export class HaLocationSelector extends LitElement {
Array.isArray(this._places) && this._places.length
? html`
<ha-list-base
aria-label=${this._i18n.localize(
aria-label=${this.hass.localize(
"ui.components.selectors.location.search_results_label"
)}
>
@@ -191,13 +174,13 @@ export class HaLocationSelector extends LitElement {
`
: this._places?.length === 0
? html`<p class="search-no-results">
${this._i18n.localize("ui.components.combo-box.no_match")}
${this.hass.localize("ui.components.combo-box.no_match")}
</p>`
: nothing
}
<p class="attribution">
${this._i18n.localize(
${this.hass.localize(
"ui.components.selectors.location.search_disclosure",
{
openstreetmap: html`<a
@@ -210,7 +193,7 @@ export class HaLocationSelector extends LitElement {
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
target="_blank"
rel="noopener noreferrer"
>${this._i18n.localize(
>${this.hass.localize(
"ui.components.selectors.location.osm_privacy_policy"
)}</a
>`,
@@ -219,27 +202,18 @@ export class HaLocationSelector extends LitElement {
</p>
</div>
${
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-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>
<ha-form
.hass=${this.hass}
.schema=${this._schema(
this._i18n.localize,
this.hass.localize,
this.selector.location?.radius,
this.selector.location?.radius_readonly
)}
@@ -254,7 +228,6 @@ export class HaLocationSelector extends LitElement {
private _location = memoizeOne(
(
selector: LocationSelector,
hassConfig: HassConfig,
value?: LocationSelectorValue
): MarkerLocation[] => {
const computedStyles = getComputedStyle(this);
@@ -267,11 +240,11 @@ export class HaLocationSelector extends LitElement {
id: "location",
latitude:
!value || isNaN(value.latitude)
? hassConfig.latitude
? this.hass.config.latitude
: value.latitude,
longitude:
!value || isNaN(value.longitude)
? hassConfig.longitude
? this.hass.config.longitude
: value.longitude,
radius: selector.location?.radius
? value?.radius || DEFAULT_RADIUS
@@ -313,7 +286,7 @@ export class HaLocationSelector extends LitElement {
entry: SchemaUnion<ReturnType<typeof this._schema>>
): string => {
if (entry.name) {
return this._i18n.localize(
return this.hass.localize(
`ui.components.selectors.location.${entry.name}`
);
}
@@ -364,17 +337,12 @@ export class HaLocationSelector extends LitElement {
this._status = undefined;
try {
this._places = await searchPlaces(
searchTerm,
this._i18n.locale.language,
true,
3
);
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
this._status = searchResultsStatus(
searchTerm,
this._places,
() => true,
this._i18n.localize
this.hass.localize
);
} catch (_err) {
this._places = undefined;
@@ -430,7 +398,7 @@ export class HaLocationSelector extends LitElement {
this._input?.focus({ preventScroll: true });
}
this._places = undefined;
this._status = this._i18n.localize(
this._status = this.hass.localize(
"ui.components.selectors.location.selected_location",
{ location: place.display_name }
);
@@ -1,12 +1,15 @@
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?:
@@ -31,6 +34,7 @@ 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.localize, panel);
const title = getPanelTitle(this.hass, panel);
const urlPath = panel.url_path;
const icon = getPanelIcon(panel);
const iconPath = getPanelIconPath(panel);
+5 -8
View File
@@ -11,7 +11,6 @@ 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";
@@ -109,9 +108,7 @@ export const supportedAlarmModes = (stateObj: AlarmControlPanelEntity) =>
export const setProtectedAlarmControlPanelMode = async (
element: HTMLElement,
callService: HomeAssistant["callService"],
callWS: HomeAssistant["callWS"],
localize: LocalizeFunc,
hass: Pick<HomeAssistant, "callService" | "localize" | "callWS">,
stateObj: AlarmControlPanelEntity,
mode: AlarmMode
) => {
@@ -126,7 +123,7 @@ export const setProtectedAlarmControlPanelMode = async (
(mode === "disarmed" && stateObj.attributes.code_format)
) {
const entry = await getExtendedEntityRegistryEntry(
callWS,
hass.callWS,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
@@ -136,10 +133,10 @@ export const setProtectedAlarmControlPanelMode = async (
const response = await showEnterCodeDialog(element, {
codeFormat: stateObj.attributes.code_format,
title: localize(
title: hass.localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
submitText: localize(
submitText: hass.localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
});
@@ -150,7 +147,7 @@ export const setProtectedAlarmControlPanelMode = async (
}
}
await callService("alarm_control_panel", service, {
await hass.callService("alarm_control_panel", service, {
entity_id: stateObj.entity_id,
code,
});
-20
View File
@@ -103,23 +103,3 @@ 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 };
};
+1 -6
View File
@@ -158,12 +158,7 @@ export const computeNavigationPathInfo = (
const isDashboard = panel?.component_name === "lovelace";
const panelInfo: NavigationPathInfo = {
label:
getPanelTitleFromUrlPath(
options.localize,
options.panels,
panelUrlPath
) || panelUrlPath,
label: getPanelTitleFromUrlPath(options, 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,
language: string,
hass: HomeAssistant,
addressdetails?: boolean,
limit?: number
): Promise<OpenStreetMapPlace[]> => {
const params = new URLSearchParams({
q: address,
format: "jsonv2",
"accept-language": language,
"accept-language": hass.locale.language,
email: "[email protected]",
});
if (limit) {
+8 -12
View File
@@ -8,12 +8,9 @@ import {
mdiMap,
mdiPlayBoxMultiple,
} from "@mdi/js";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../common/translations/localize";
import type { LocalizeKeys } from "../common/translations/localize";
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
import type { HomeAssistant, PanelInfo, Panels } from "../types";
import type { HomeAssistant, PanelInfo } from "../types";
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
export const APP_PANEL = "app";
@@ -69,7 +66,7 @@ export const getPanelNameTranslationKey = (panel: PanelInfo) => {
};
export const getPanelTitle = (
localize: LocalizeFunc,
hass: Pick<HomeAssistant, "localize">,
panel: PanelInfo
): string | undefined => {
if (panel.url_path === "marketplace") {
@@ -78,19 +75,18 @@ export const getPanelTitle = (
const translationKey = getPanelNameTranslationKey(panel);
return localize(translationKey) || panel.title || undefined;
return hass.localize(translationKey) || panel.title || undefined;
};
export const getPanelTitleFromUrlPath = (
localize: LocalizeFunc,
panels: Panels,
hass: Pick<HomeAssistant, "localize" | "panels">,
urlPath: string
): string | undefined => {
if (!panels) {
if (!hass.panels) {
return undefined;
}
const panel = Object.values(panels).find(
const panel = Object.values(hass.panels).find(
(p: PanelInfo): boolean => p.url_path === urlPath
);
@@ -98,7 +94,7 @@ export const getPanelTitleFromUrlPath = (
return undefined;
}
return getPanelTitle(localize, panel);
return getPanelTitle(hass, 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,9 +31,11 @@ class MoreInfoAlarmControlPanel extends LitElement {
private async _disarm() {
setProtectedAlarmControlPanelMode(
this,
this._api.callService,
this._api.callWS,
this._localize,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: 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.localize, panel) || panel.url_path) +
(getPanelTitle(this.hass, panel) || panel.url_path) +
`${defaultPanel === panel.url_path ? ` (${this.hass.localize("ui.sidebar.default")})` : ""}`,
icon: getPanelIcon(panel),
iconPath: getPanelIconPath(panel),
+1 -6
View File
@@ -352,12 +352,7 @@ class OnboardingLocation extends LitElement {
}
);
try {
this._places = await searchPlaces(
address,
this.hass.locale.language,
true,
3
);
this._places = await searchPlaces(address, this.hass, true, 3);
if (this._places?.length) {
this._highlightedMarker = this._places[0].place_id;
this._location = [
@@ -86,7 +86,6 @@ export class HaCategoryPicker extends LitElement {
public disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeCategories();
this._categories = undefined;
}
protected willUpdate(changedProperties: PropertyValues) {
@@ -28,7 +28,6 @@ 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,
@@ -110,7 +109,6 @@ 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";
@@ -171,9 +169,6 @@ 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;
@@ -191,9 +186,6 @@ 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";
@@ -282,7 +274,6 @@ 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;
@@ -909,47 +900,24 @@ 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 =
showingPickedBrand || showingDiscoveredGroup || this._showDiscovered;
(this._pickedBrand && (!this._integrations || pickedIntegration)) ||
this._showDiscovered;
const brandDomain = showingPickedBrand
? this._pickedBrand
: showingDiscoveredGroup
? this._discoveredDomain
: undefined;
const brandIntegration = showingPickedBrand
? pickedIntegration
: showingDiscoveredGroup
? findIntegration(this._integrations, this._discoveredDomain!)
: undefined;
const flowsInProgress = showingBrandView
? this._getFlowsForCurrentView(pickedIntegration)
: [];
const flowsInProgress = showingPickedBrand
? this._getFlowsForBrand(pickedIntegration)
: showingDiscoveredGroup
? this._getFlowsForDiscoveredGroup(this._discoveredDomain!)
: this._showDiscovered
? this._flowsInProgress || []
: [];
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 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
const headerSubtitle =
!showingBrandView && this._narrow && this._drilled
? this._subcategory
? integrationCategoryName(this.hass.localize, this._category!)
: this.hass.localize(
@@ -970,7 +938,7 @@ class AddIntegrationDialog extends LitElement {
showingBrandView
? html`
${
!this._openedDirectly || this._discoveredDomain
!this._openedDirectly
? html`
<ha-icon-button-prev
slot="headerNavigationIcon"
@@ -979,12 +947,7 @@ class AddIntegrationDialog extends LitElement {
`
: nothing
}
${this._renderBrandView(
brandDomain,
brandIntegration,
flowsInProgress,
!showingPickedBrand && !showingDiscoveredGroup
)}
${this._renderBrandView(pickedIntegration, flowsInProgress)}
`
: html`
${
@@ -1028,15 +991,13 @@ class AddIntegrationDialog extends LitElement {
);
}
private _getFlowsForDiscoveredGroup(domain: string) {
return (this._flowsInProgress || []).filter(
(flow) => flow.handler === domain
);
}
private _getFlowsForBrand(
private _getFlowsForCurrentView(
integration: Brand | Integration | undefined
): DataEntryFlowProgress[] {
if (this._showDiscovered) {
// Show all discovered flows
return this._flowsInProgress || [];
}
if (!this._pickedBrand || !integration) {
return [];
}
@@ -1083,39 +1044,23 @@ class AddIntegrationDialog extends LitElement {
}
private _renderBrandView(
domain: string | undefined,
integration: Brand | Integration | undefined,
flowsInProgress: DataEntryFlowProgress[],
groupFlows: boolean
flowsInProgress: DataEntryFlowProgress[]
): TemplateResult {
return html`<ha-domain-integrations
.hass=${this.hass}
.domain=${domain}
.domain=${this._pickedBrand}
.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;
@@ -1233,12 +1178,7 @@ class AddIntegrationDialog extends LitElement {
${
this._showDiscoveredView && !this._filter
? html`<div class="discovered">
${this._renderBrandView(
undefined,
undefined,
this._flowsInProgress || [],
true
)}
${this._renderBrandView(undefined, this._flowsInProgress || [])}
</div>`
: rows
? html`${
@@ -2123,25 +2063,12 @@ class AddIntegrationDialog extends LitElement {
}
private _prevClicked() {
if (this._pickedBrand) {
this._pickedBrand = this._prevPickedBrand;
this._prevPickedBrand = undefined;
if (this._showDiscovered) {
this._showDiscovered = false;
return;
}
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);
}
this._pickedBrand = this._prevPickedBrand;
this._prevPickedBrand = undefined;
}
static styles = [
@@ -1,8 +1,7 @@
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, queryAll } from "lit/decorators";
import { customElement, property } 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";
@@ -14,10 +13,8 @@ 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";
@@ -25,8 +22,7 @@ import {
domainToName,
fetchIntegrationManifest,
} from "../../../data/integration";
import type { Brand, Brands, Integration } from "../../../data/integrations";
import { findIntegration } from "../../../data/integrations";
import type { Brand, Integration } from "../../../data/integrations";
import { showConfigFlowDialog } from "../../../dialogs/config-flow/show-dialog-config-flow";
import { haStyle } from "../../../resources/styles";
import type { HomeAssistant } from "../../../types";
@@ -37,7 +33,7 @@ import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
export const standardToDomain = { zigbee: "zha", zwave: "zwave_js" } as const;
@customElement("ha-domain-integrations")
export class HaDomainIntegrations extends LitElement {
class HaDomainIntegrations extends LitElement {
public hass!: HomeAssistant;
@property() public domain!: string;
@@ -55,15 +51,6 @@ export 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 =
@@ -76,11 +63,36 @@ export class HaDomainIntegrations extends LitElement {
? html`<h3>
${this.hass.localize("ui.panel.config.integrations.discovered")}
</h3>
${
this.groupFlows
? this._renderFlowGroups(this.flowsInProgress)
: this.flowsInProgress.map((flow) => this._renderFlow(flow))
}
${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>`
)}
<wa-divider></wa-divider>
${
this.integration &&
@@ -291,87 +303,6 @@ export 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 }>
) {
@@ -565,8 +496,4 @@ declare global {
interface HTMLElementTagNameMap {
"ha-domain-integrations": HaDomainIntegrations;
}
interface HASSDomEvents {
"discovered-group-picked": { domain: string };
}
}
@@ -363,8 +363,7 @@ export class HaConfigLovelaceDashboards extends LitElement {
}
const item: DataTableItem = {
icon: getPanelIcon(panelInfo),
title:
getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
show_in_sidebar: panelInfo.show_in_sidebar || false,
mode: "storage",
url_path: panelInfo.url_path,
@@ -548,7 +547,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.localize, panelInfo) || panelInfo.url_path,
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
icon: getPanelIcon(panelInfo),
requireAdmin: panelInfo.require_admin || false,
showInSidebar: panelInfo.show_in_sidebar || false,
@@ -133,9 +133,11 @@ class HuiAlarmModeCardFeature
private async _setMode(mode: AlarmMode) {
await setProtectedAlarmControlPanelMode(
this,
this._api.callService,
this._api.callWS,
this._localize,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this._stateObj!,
mode
);
@@ -19,10 +19,7 @@ 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,
pushTargetTemperature,
} from "../../../data/climate";
import { ClimateEntityFeature } from "../../../data/climate";
import {
apiContext,
configContext,
@@ -190,9 +187,17 @@ 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,
...pushTargetTemperature(this._targetTemperature, target, value),
[target]: newValue,
};
this._pendingSync.schedule();
this._debouncedCallService(target);
@@ -375,7 +380,10 @@ class HuiTargetTemperatureCardFeature
.value=${this._targetTemperature.low}
.unit=${this._hassConfig?.unit_system.temperature}
.min=${this._min}
.max=${this._max}
.max=${Math.min(
this._max,
this._targetTemperature.high ?? this._max
)}
.step=${this._step}
@value-changed=${this._valueChanged}
.label=${this._formatters.formatEntityAttributeName(
@@ -394,7 +402,10 @@ class HuiTargetTemperatureCardFeature
.target=${"high"}
.value=${this._targetTemperature.high}
.unit=${this._hassConfig?.unit_system.temperature}
.min=${this._min}
.min=${Math.max(
this._min,
this._targetTemperature.low ?? 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, queryAll, state } from "lit/decorators";
import { customElement, query, 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,6 +81,8 @@ 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[];
@@ -117,6 +119,9 @@ 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> {
@@ -237,6 +242,7 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
? nothing
: html`
<hui-entities-toggle
.hass=${this._hass}
.entities=${(
this._configEntities!.filter(
(conf) => "entity" in conf
@@ -1,18 +1,17 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { STATES_OFF } from "../../../../common/const";
import { computeStateDomain } from "../../../../common/entity/compute_state_domain";
import { computeDomain } from "../../../../common/entity/compute_domain";
import { getToggleAction } from "../../../../common/entity/get_toggle_action";
import type { HomeAssistantApi } from "../../../../types";
import type { HomeAssistant } from "../../../../types";
export const turnOnOffEntities = (
callService: HomeAssistantApi["callService"],
stateObjs: HassEntity[],
hass: HomeAssistant,
entityIds: string[],
turnOn = true
): void => {
const domainsToCall = {};
stateObjs.forEach((stateObj) => {
if (STATES_OFF.includes(stateObj.state) === turnOn) {
const stateDomain = computeStateDomain(stateObj);
entityIds.forEach((entityId) => {
if (STATES_OFF.includes(hass.states[entityId].state) === turnOn) {
const stateDomain = computeDomain(entityId);
// Entities with non-standard toggle action need separate calls
const serviceDomain =
getToggleAction(stateDomain, true) !== "turn_on"
@@ -22,7 +21,7 @@ export const turnOnOffEntities = (
if (!(serviceDomain in domainsToCall)) {
domainsToCall[serviceDomain] = [];
}
domainsToCall[serviceDomain].push(stateObj.entity_id);
domainsToCall[serviceDomain].push(entityId);
}
});
@@ -30,6 +29,6 @@ export const turnOnOffEntities = (
const service = getToggleAction(domain, turnOn);
const entities = domainsToCall[domain];
callService(domain, service, { entity_id: entities });
hass.callService(domain, service, { entity_id: entities });
});
};
@@ -1,59 +1,46 @@
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[];
@state() _toggleEntities?: string[];
@property({ attribute: false }) public hass?: HomeAssistant;
@state()
@consumeEntityStates({ entityIdPath: ["_toggleEntities"] })
private _stateObjs?: Record<string, HassEntity>;
@state()
@consumeLocalize()
private _localize?: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api?: ContextType<typeof apiContext>;
@state() private _toggleEntities?: string[];
public willUpdate(changedProperties: PropertyValues<this>): void {
super.willUpdate(changedProperties);
if (changedProperties.has("entities")) {
this._toggleEntities = this.entities!.filter((entityId) =>
DOMAINS_TOGGLE.has(entityId.split(".", 1)[0])
this._toggleEntities = this.entities!.filter(
(entityId) =>
entityId in this.hass!.states &&
DOMAINS_TOGGLE.has(entityId.split(".", 1)[0])
);
}
}
protected render() {
const stateObjs = Object.values(this._stateObjs ?? {});
if (!stateObjs.length || !this._localize) {
if (!this._toggleEntities?.length) {
return nothing;
}
return html`
<ha-switch
.accessibleLabel=${this._localize(
.accessibleLabel=${this.hass!.localize(
"ui.panel.lovelace.card.entities.toggle"
)}
.checked=${stateObjs.some((stateObj) => stateObj.state === "on")}
.checked=${this._toggleEntities!.some((entityId) => {
const stateObj = this.hass!.states[entityId];
return stateObj && stateObj.state === "on";
})}
@change=${this._callService}
></ha-switch>
`;
@@ -72,16 +59,9 @@ 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._api.callService,
Object.values(this._stateObjs ?? {}),
turnOn
);
turnOnOffEntities(this.hass!, this._toggleEntities!, turnOn!);
}
}
@@ -1,46 +1,27 @@
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,
state,
} from "lit/decorators";
import { customElement, eventOptions, property, query } 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,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../types";
import type { HomeAssistant } 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;
@@ -55,42 +36,22 @@ 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.config ||
!this._localize ||
!this._hassConfig ||
!this._formatters
) {
if (!this.hass || !this.config) {
return nothing;
}
const stateObj =
this.stateObj ??
(this.config.entity ? this.hass?.states[this.config.entity] : undefined);
const stateObj = this.config.entity
? this.hass.states[this.config.entity]
: undefined;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
</hui-warning>
`;
}
@@ -102,7 +63,7 @@ export class HuiGenericEntityRow extends LitElement {
const pointer = hasAnyAction(this.config);
const hasSecondary = this.secondaryText || this.config.secondary_info;
const name = this._formatters.formatEntityName(stateObj, this.config.name);
const name = this.hass.formatEntityName(stateObj, this.config.name);
return html`
<div
@@ -200,10 +161,7 @@ export class HuiGenericEntityRow extends LitElement {
}
private _handleAction(ev: ActionHandlerEvent) {
fireEvent(this, "hass-action", {
config: this.config!,
action: ev.detail.action!,
});
handleAction(this, this.hass!, this.config!, ev.detail.action!);
}
static styles = css`
@@ -151,11 +151,7 @@ export const addEntitiesToLovelaceView = async (
}
const dashboardPath = viewUrlPath ?? LOVELACE_PANEL;
const viewPath = newConfig.views[viewIndex].path || viewIndex;
const dashboardTitle = getPanelTitleFromUrlPath(
hass.localize,
hass.panels,
dashboardPath
);
const dashboardTitle = getPanelTitleFromUrlPath(hass, dashboardPath);
showToast(element, {
message: dashboardTitle
? {
@@ -43,7 +43,7 @@ class HuiButtonEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
hide-name
>
@@ -56,7 +56,7 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
.catchInteraction=${false}
>
@@ -95,7 +95,7 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
stateObj.state === UNKNOWN);
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
${
supportSpeedPercentage && !supportsOnOff
? html`
@@ -60,7 +60,7 @@ class HuiGroupEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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
.stateObj=${stateObj}
.hass=${this.hass}
.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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
${
stateObj.attributes.mode === "slider"
? html`
@@ -52,7 +52,7 @@ class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
hide-name
>
@@ -47,7 +47,7 @@ class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
hide-name
>
@@ -44,7 +44,7 @@ class HuiLockEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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
.stateObj=${stateObj}
.hass=${this.hass}
.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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
${
showNumberSlider(stateObj)
? html`
@@ -44,7 +44,7 @@ class HuiSceneEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
hide-name
>
@@ -49,7 +49,7 @@ class HuiSensorEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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
.stateObj=${stateObj}
.hass=${this.hass}
.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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
.catchInteraction=${!showToggle}
>
@@ -44,7 +44,7 @@ class HuiUpdateEntityRow extends LitElement implements LovelaceRow {
}
return html`
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
${computeUpdateStateDisplay(
stateObj,
this.hass.localize,
@@ -49,7 +49,7 @@ class HuiValveEntityRow extends LitElement implements LovelaceRow {
return html`
<hui-generic-entity-row
.stateObj=${stateObj}
.hass=${this.hass}
.config=${this._config}
.catchInteraction=${!showToggle}
>
+2 -4
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.localize, this.panel)
? getPanelTitle(this.hass, this.panel)
: undefined;
const background = curViewConfig?.background || this.config.background;
@@ -1118,9 +1118,7 @@ class HUIRoot extends KeyboardShortcutMixin(LitElement) {
showDashboardStrategyEditorDialog(this, {
config: this.lovelace!.rawConfig,
title: this.panel
? getPanelTitle(this.hass.localize, this.panel)
: undefined,
title: this.panel ? getPanelTitle(this.hass, 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 .stateObj=${stateObj} .config=${this._config}>
<hui-generic-entity-row .hass=${this.hass} .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());
// Headings get no ids, so an anchor has nothing to point at on this page
// ha-markdown scrolls to an anchor in the README itself
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.localize, panelInfo)}
${getPanelTitle(this.hass, 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.localize, panelInfo);
return getPanelTitle(this.hass, panelInfo);
}
const dashboard = this._dashboards?.find((dash) => dash.url_path === value);
if (dashboard) {
+6
View File
@@ -0,0 +1,6 @@
// 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}`;
+132 -15
View File
@@ -1,6 +1,8 @@
import { expose } from "comlink";
import type { MarkedOptions } from "marked";
import { marked } from "marked";
import { Marked, Renderer } from "marked";
import markedFootnote from "marked-footnote";
import { gfmHeadingId, resetHeadings } from "marked-gfm-heading-id";
import type { IWhiteList } from "xss";
import {
escapeAttrValue,
@@ -10,6 +12,82 @@ 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;
@@ -68,12 +146,27 @@ 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 = {
...getDefaultWhiteList(),
table: [...(getDefaultWhiteList().table ?? []), "role"],
...defaultWhiteList,
...Object.fromEntries(
["p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "img"].map((tag) => [
tag,
withAlign(tag),
])
),
table: [...(defaultWhiteList.table ?? []), "role"],
input: ["type", "disabled", "checked"],
// Allows <picture>, and <video>/<audio> that have <source> children.
picture: [],
@@ -89,6 +182,7 @@ const renderMarkdown = async (
"error-correction-level",
"center-image",
],
"ha-mermaid-diagram": [],
};
}
@@ -100,7 +194,7 @@ const renderMarkdown = async (
...whiteListNormal,
svg: ["xmlns", "height", "width"],
path: ["transform", "stroke", "d"],
img: ["src"],
img: ["src", "align"],
};
}
whiteList = whiteListSvg;
@@ -112,21 +206,23 @@ const renderMarkdown = async (
whiteList = { ...whiteList, a: [...(whiteList.a ?? []), "download"] };
}
const marked = markedFor(
hassOptions.footnoteLabels ?? DEFAULT_FOOTNOTE_LABELS
);
marked.setOptions(markedOptions);
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>`;
},
},
});
// 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();
const tokens = marked.lexer(content);
if (marked.defaults.walkTokens) {
marked.walkTokens(tokens, marked.defaults.walkTokens);
}
return tokens.map((token) =>
filterXSS(marked.parser([token]), {
whiteList,
@@ -152,6 +248,27 @@ 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,9 +60,11 @@ export class HaStateControlAlarmControlPanelModes extends LitElement {
private async _setMode(mode: AlarmMode) {
await setProtectedAlarmControlPanelMode(
this,
this._api.callService,
this._api.callWS,
this._localize,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this.stateObj,
mode
);
@@ -26,7 +26,6 @@ import type { ClimateEntity, HvacMode } from "../../data/climate";
import {
CLIMATE_HVAC_ACTION_TO_MODE,
ClimateEntityFeature,
pushTargetTemperature,
} from "../../data/climate";
import {
apiContext,
@@ -147,12 +146,7 @@ export class HaStateControlClimateTemperature extends LitElement {
const target = ev.type.replace("-changed", "") as Target;
this._targetTemperature = {
...this._targetTemperature,
...pushTargetTemperature(
this._targetTemperature,
target,
// The slider rounds to the step after bounding, which can overshoot
clamp(value, this._min, this._max)
),
[target]: this._clampToRange(target, value),
};
this._selectTargetTemperature = target;
this._debouncedCallService.cancel();
@@ -165,13 +159,9 @@ export class HaStateControlClimateTemperature extends LitElement {
this._changingTemperature = {};
return;
}
const target = ev.type.replace("-changing", "") as Target;
this._changingTemperature = pushTargetTemperature(
this._targetTemperature,
target,
clamp(value, this._min, this._max)
);
this._selectTargetTemperature = target;
const target = ev.type.replace("-changing", "");
this._changingTemperature = { [target]: value };
this._selectTargetTemperature = target as Target;
}
private get _displayedTemperature() {
@@ -213,12 +203,22 @@ export class HaStateControlClimateTemperature extends LitElement {
this._targetTemperature = {
...this._targetTemperature,
...pushTargetTemperature(this._targetTemperature, target, temp),
[target]: this._clampToRange(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;
+2 -43
View File
@@ -10,10 +10,8 @@ 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,
@@ -31,14 +29,9 @@ 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 {
preserveUnchangedItems,
preserveUnchangedRecord,
} from "../common/util/preserve-unchanged-record";
import type { FloorRegistryEntry } from "../data/floor_registry";
import { preserveUnchangedRecord } from "../common/util/preserve-unchanged-record";
import { subscribeFloorRegistry } from "../data/ws-floor_registry";
import { subscribePanels } from "../data/ws-panels";
import { translationMetadata } from "../resources/translations-metadata";
@@ -274,21 +267,7 @@ 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] = {
@@ -322,12 +301,6 @@ 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;
@@ -342,12 +315,6 @@ 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;
@@ -363,12 +330,6 @@ 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;
@@ -461,9 +422,7 @@ 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!.callWS
);
const changed = await fetchAndScheduleBrandsAccessToken(this.hass!);
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 or kept in
// memory. All consumers have already unsubscribed, so nobody is notified.
this._provider.setValue(undefined as ContextType<C>);
// 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.
}
private _startSubscription(): void {
+1 -5
View File
@@ -46,11 +46,7 @@ export const panelTitleMixin = <T extends Constructor<HassBaseEl>>(
// Fall back to panel title
if (!title) {
title = getPanelTitleFromUrlPath(
this.hass.localize,
this.hass.panels,
this.hass.panelUrl
);
title = getPanelTitleFromUrlPath(this.hass, this.hass.panelUrl);
}
setPageTitle(title);
+5 -1
View File
@@ -549,6 +549,11 @@
"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": {
@@ -8130,7 +8135,6 @@
"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",
+7 -9
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 (
callWS: HomeAssistant["callWS"]
hass: HomeAssistant
): 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(callWS);
scheduleBrandsTokenRefresh(callWS);
await fetchBrandsAccessToken(hass);
scheduleBrandsTokenRefresh(hass);
return _brandsAccessToken !== previousToken;
} catch {
// try next delay
@@ -55,9 +55,9 @@ export const fetchAndScheduleBrandsAccessToken = async (
};
export const fetchBrandsAccessToken = async (
callWS: HomeAssistant["callWS"]
hass: HomeAssistant
): Promise<void> => {
const result = await callWS<{ token: string }>({
const result = await hass.callWS<{ token: string }>({
type: "brands/access_token",
});
if (result.token === _brandsAccessToken) {
@@ -79,12 +79,10 @@ export const subscribeBrandsAccessToken = (
};
};
export const scheduleBrandsTokenRefresh = (
callWS: HomeAssistant["callWS"]
): void => {
export const scheduleBrandsTokenRefresh = (hass: HomeAssistant): void => {
clearBrandsTokenRefresh();
_brandsRefreshInterval = setInterval(() => {
fetchBrandsAccessToken(callWS).catch(() => {
fetchBrandsAccessToken(hass).catch(() => {
// Ignore failures; older backends may not support this command
});
}, TOKEN_REFRESH_MS);
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import { deepEqual } from "../../../src/common/util/deep-equal";
import {
preserveUnchangedItems,
preserveUnchangedRecord,
} from "../../../src/common/util/preserve-unchanged-record";
import { preserveUnchangedRecord } from "../../../src/common/util/preserve-unchanged-record";
interface Item {
id: string;
@@ -101,29 +98,3 @@ 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]);
});
});
@@ -1,72 +0,0 @@
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
@@ -1,32 +0,0 @@
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,
});
});
});
+4 -1
View File
@@ -4,6 +4,9 @@ import {
searchPlaces,
type OpenStreetMapPlace,
} from "../../src/data/openstreetmap";
import type { HomeAssistant } from "../../src/types";
const hass = { locale: { language: "en" } } as HomeAssistant;
afterEach(() => {
vi.unstubAllGlobals();
@@ -16,7 +19,7 @@ describe("searchPlaces", () => {
.mockResolvedValue(new Response("[]"));
vi.stubGlobal("fetch", fetchMock);
await searchPlaces("10 Downing Street & London", "en", true, 3);
await searchPlaces("10 Downing Street & London", hass, true, 3);
const url = new URL(String(fetchMock.mock.calls[0][0]));
expect(url.searchParams.get("q")).toBe("10 Downing Street & London");
@@ -1,44 +1,20 @@
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 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.hass = createMockHass({
"input_boolean.porch": createMockEntityState("input_boolean.porch", "off"),
});
row.config = { entity: "input_boolean.porch" };
row.catchInteraction = catchInteraction;
const control = document.createElement("button");
row.append(control);
host.append(row);
document.body.append(host);
document.body.append(row);
await row.updateComplete;
const moreInfo = vi.fn();
row.addEventListener("hass-action", moreInfo);
row.addEventListener("hass-more-info", moreInfo);
return {
control,
moreInfo,
+161
View File
@@ -288,6 +288,167 @@ 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,30 +119,4 @@ 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.callWS);
await fetchBrandsAccessToken(mockHass);
});
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.callWS);
await fetchBrandsAccessToken(mockHass);
assert.strictEqual(
addBrandsAuth(
@@ -149,7 +149,7 @@ describe("addBrandsAuth", () => {
const mockHass = {
callWS: async () => ({ token: "new-token" }),
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass.callWS);
await fetchBrandsAccessToken(mockHass);
assert.strictEqual(
addBrandsAuth(
@@ -221,7 +221,7 @@ describe("scheduleBrandsTokenRefresh", () => {
},
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass.callWS);
await fetchBrandsAccessToken(mockHass);
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.callWS);
scheduleBrandsTokenRefresh(mockHass);
// Advance 30 minutes
await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
@@ -255,8 +255,8 @@ describe("scheduleBrandsTokenRefresh", () => {
},
} as unknown as HomeAssistant;
await fetchBrandsAccessToken(mockHass.callWS);
scheduleBrandsTokenRefresh(mockHass.callWS);
await fetchBrandsAccessToken(mockHass);
scheduleBrandsTokenRefresh(mockHass);
// 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.callWS);
scheduleBrandsTokenRefresh(mockHass.callWS);
await fetchBrandsAccessToken(mockHass);
scheduleBrandsTokenRefresh(mockHass);
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.callWS);
await fetchBrandsAccessToken(mockHass);
const listener = vi.fn();
const unsubscribe = subscribeBrandsAccessToken(listener);
assert.deepEqual(listener.mock.calls, [["subscribed-token-1"]]);
// Unchanged token: no call
await fetchBrandsAccessToken(mockHass.callWS);
await fetchBrandsAccessToken(mockHass);
assert.strictEqual(listener.mock.calls.length, 1);
// The 30 minute refresh reports the rotated token
token = "subscribed-token-2";
scheduleBrandsTokenRefresh(mockHass.callWS);
scheduleBrandsTokenRefresh(mockHass);
await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
assert.deepEqual(listener.mock.calls[1], ["subscribed-token-2"]);
unsubscribe();
token = "subscribed-token-3";
await fetchBrandsAccessToken(mockHass.callWS);
await fetchBrandsAccessToken(mockHass);
assert.strictEqual(listener.mock.calls.length, 2);
});
});
@@ -338,7 +338,7 @@ describe("fetchAndScheduleBrandsAccessToken", () => {
},
} as unknown as HomeAssistant;
const promise = fetchAndScheduleBrandsAccessToken(mockHass.callWS);
const promise = fetchAndScheduleBrandsAccessToken(mockHass);
// 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.callWS);
await fetchBrandsAccessToken(mockHass);
// Same token returned → no change
const changed = await fetchAndScheduleBrandsAccessToken(mockHass.callWS);
const changed = await fetchAndScheduleBrandsAccessToken(mockHass);
assert.strictEqual(changed, false);
});
@@ -386,7 +386,7 @@ describe("fetchAndScheduleBrandsAccessToken", () => {
},
} as unknown as HomeAssistant;
const promise = fetchAndScheduleBrandsAccessToken(mockHass.callWS);
const promise = fetchAndScheduleBrandsAccessToken(mockHass);
// Exhaust all retry delays: 500 + 1000 + 2000 + 5000 + 10000 + 15000
await vi.advanceTimersByTimeAsync(33500);