Use new entity naming in statistic picker

This commit is contained in:
Paul Bottein 2025-04-22 18:59:56 +02:00
parent fcab356639
commit 7e894a4e62
No known key found for this signature in database
2 changed files with 228 additions and 88 deletions

View File

@ -1,30 +1,56 @@
import { mdiChartLine } from "@mdi/js";
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit"; import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit";
import Fuse, { type IFuseOptions } from "fuse.js";
import type { HassEntity } from "home-assistant-js-websocket"; import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues, TemplateResult } from "lit"; import type { PropertyValues, TemplateResult } from "lit";
import { html, LitElement, nothing } from "lit"; import { html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators"; import { customElement, property, query, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { ensureArray } from "../../common/array/ensure-array"; import { ensureArray } from "../../common/array/ensure-array";
import { fireEvent } from "../../common/dom/fire_event"; import { fireEvent } from "../../common/dom/fire_event";
import { stringCompare } from "../../common/string/compare"; import { computeAreaName } from "../../common/entity/compute_area_name";
import type { ScorableTextItem } from "../../common/string/filter/sequence-matching"; import { computeDeviceName } from "../../common/entity/compute_device_name";
import { fuzzyFilterSort } from "../../common/string/filter/sequence-matching"; import { computeEntityName } from "../../common/entity/compute_entity_name";
import { computeStateName } from "../../common/entity/compute_state_name";
import { getEntityContext } from "../../common/entity/get_entity_context";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import { computeRTL } from "../../common/util/compute_rtl";
import type { StatisticsMetaData } from "../../data/recorder"; import type { StatisticsMetaData } from "../../data/recorder";
import { getStatisticIds, getStatisticLabel } from "../../data/recorder"; import { getStatisticIds, getStatisticLabel } from "../../data/recorder";
import type { HomeAssistant, ValueChangedEvent } from "../../types"; import type { HomeAssistant, ValueChangedEvent } from "../../types";
import { documentationUrl } from "../../util/documentation-url";
import "../ha-combo-box"; import "../ha-combo-box";
import type { HaComboBox } from "../ha-combo-box"; import type { HaComboBox } from "../ha-combo-box";
import "../ha-combo-box-item"; import "../ha-combo-box-item";
import "../ha-svg-icon"; import "../ha-svg-icon";
import "./state-badge"; import "./state-badge";
import { domainToName } from "../../data/integration";
interface StatisticItem extends ScorableTextItem { type StatisticItemType = "entity" | "external" | "no_state";
interface StatisticItem {
id: string; id: string;
name: string; label: string;
primary: string;
secondary?: string;
show_entity_id?: boolean;
entity_name?: string;
area_name?: string;
device_name?: string;
friendly_name?: string;
sorting_label?: string;
state?: HassEntity; state?: HassEntity;
type?: StatisticItemType;
iconPath?: string;
} }
const TYPE_ORDER = ["entity", "external", "no_state"] as StatisticItemType[];
const ENTITY_ID_STYLE = styleMap({
fontFamily: "var(--code-font-family, monospace)",
fontSize: "11px",
});
@customElement("ha-statistic-picker") @customElement("ha-statistic-picker")
export class HaStatisticPicker extends LitElement { export class HaStatisticPicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@ -88,44 +114,56 @@ export class HaStatisticPicker extends LitElement {
@property({ attribute: false }) public helpMissingEntityUrl = @property({ attribute: false }) public helpMissingEntityUrl =
"/more-info/statistics/"; "/more-info/statistics/";
@state() private _opened?: boolean; @state() private _opened = false;
@query("ha-combo-box", true) public comboBox!: HaComboBox; @query("ha-combo-box", true) public comboBox!: HaComboBox;
private _init = false; private _initialItems = false;
private _statistics: StatisticItem[] = []; private _items: StatisticItem[] = [];
@state() private _filteredItems?: StatisticItem[] = undefined; protected firstUpdated(changedProperties: PropertyValues): void {
super.firstUpdated(changedProperties);
this.hass.loadBackendTranslation("title");
}
private _rowRenderer: ComboBoxLitRenderer<StatisticItem> = (item) => private _rowRenderer: ComboBoxLitRenderer<StatisticItem> = (
html`<ha-combo-box-item type="button"> item,
${item.state { index }
? html` ) => html`
<ha-combo-box-item type="button" compact .borderTop=${index !== 0}>
${!item.state
? html`<ha-svg-icon
style="margin: 0 4px"
slot="start"
.path=${item.iconPath}
></ha-svg-icon>`
: html`
<state-badge <state-badge
slot="start" slot="start"
.stateObj=${item.state} .stateObj=${item.state}
.hass=${this.hass} .hass=${this.hass}
></state-badge> ></state-badge>
` `}
: html`<span slot="start" style="width: 32px"></span>`}
<span slot="headline">${item.name}</span>
<span slot="supporting-text"
>${item.id === "" || item.id === "__missing"
? html`<a
target="_blank"
rel="noopener noreferrer"
href=${documentationUrl(this.hass, this.helpMissingEntityUrl)}
>${this.hass.localize(
"ui.components.statistic-picker.learn_more"
)}</a
>`
: item.id}</span
>
</ha-combo-box-item>`;
private _getStatistics = memoizeOne( <span slot="headline">${item.primary} </span>
${item.secondary
? html`<span slot="supporting-text">${item.secondary}</span>`
: nothing}
${item.id && item.show_entity_id
? html`
<span slot="supporting-text" style=${ENTITY_ID_STYLE}>
${item.id}
</span>
`
: nothing}
</ha-combo-box-item>
`;
private _getItems = memoizeOne(
( (
_opened: boolean,
hass: this["hass"],
statisticIds: StatisticsMetaData[], statisticIds: StatisticsMetaData[],
includeStatisticsUnitOfMeasurement?: string | string[], includeStatisticsUnitOfMeasurement?: string | string[],
includeUnitClass?: string | string[], includeUnitClass?: string | string[],
@ -138,10 +176,12 @@ export class HaStatisticPicker extends LitElement {
return [ return [
{ {
id: "", id: "",
name: this.hass.localize( label: this.hass.localize(
"ui.components.statistic-picker.no_statistics"
),
primary: this.hass.localize(
"ui.components.statistic-picker.no_statistics" "ui.components.statistic-picker.no_statistics"
), ),
strings: [],
}, },
]; ];
} }
@ -175,6 +215,8 @@ export class HaStatisticPicker extends LitElement {
}); });
} }
const isRTL = computeRTL(this.hass);
const output: StatisticItem[] = []; const output: StatisticItem[] = [];
statisticIds.forEach((meta) => { statisticIds.forEach((meta) => {
if ( if (
@ -188,22 +230,67 @@ export class HaStatisticPicker extends LitElement {
if (!entityState) { if (!entityState) {
if (!entitiesOnly) { if (!entitiesOnly) {
const id = meta.statistic_id; const id = meta.statistic_id;
const name = getStatisticLabel(this.hass, meta.statistic_id, meta); const label = getStatisticLabel(this.hass, meta.statistic_id, meta);
output.push({ const type =
id, meta.statistic_id.includes(":") &&
name, !meta.statistic_id.includes(".")
strings: [id, name], ? "external"
}); : "no_state";
if (type === "no_state") {
output.push({
id,
primary: label,
secondary: this.hass.localize(
"ui.components.statistic-picker.no_state"
),
label,
type,
sorting_label: label,
});
} else if (type === "external") {
const domain = id.split(":")[0];
const domainName = domainToName(this.hass.localize, domain);
output.push({
id,
primary: label,
secondary: domainName,
label,
type,
sorting_label: label,
iconPath: mdiChartLine,
});
}
} }
return; return;
} }
const id = meta.statistic_id; const id = meta.statistic_id;
const name = getStatisticLabel(this.hass, meta.statistic_id, meta);
const { area, device } = getEntityContext(entityState, hass);
const friendlyName = computeStateName(entityState); // Keep this for search
const entityName = computeEntityName(entityState, hass);
const deviceName = device ? computeDeviceName(device) : undefined;
const areaName = area ? computeAreaName(area) : undefined;
const primary = entityName || deviceName || id;
const secondary = [areaName, entityName ? deviceName : undefined]
.filter(Boolean)
.join(isRTL ? " ◂ " : " ▸ ");
output.push({ output.push({
id, id,
name, primary,
secondary,
label: friendlyName,
state: entityState, state: entityState,
strings: [id, name], type: "entity",
sorting_label: [deviceName, entityName].join("_"),
entity_name: entityName || deviceName,
area_name: areaName,
device_name: deviceName,
friendly_name: friendlyName,
show_entity_id: hass.userData?.showEntityIdPicker,
}); });
}); });
@ -211,36 +298,62 @@ export class HaStatisticPicker extends LitElement {
return [ return [
{ {
id: "", id: "",
name: this.hass.localize("ui.components.statistic-picker.no_match"), primary: this.hass.localize(
strings: [], "ui.components.statistic-picker.no_match"
),
label: this.hass.localize(
"ui.components.statistic-picker.no_match"
),
}, },
]; ];
} }
if (output.length > 1) { if (output.length > 1) {
output.sort((a, b) => output.sort((a, b) => {
stringCompare(a.name || "", b.name || "", this.hass.locale.language) const aPrefix = TYPE_ORDER.indexOf(a.type || "no_state");
); const bPrefix = TYPE_ORDER.indexOf(b.type || "no_state");
return caseInsensitiveStringCompare(
`${aPrefix}_${a.sorting_label || ""}`,
`${bPrefix}_${b.sorting_label || ""}`,
this.hass.locale.language
);
});
} }
output.push({ output.push({
id: "__missing", id: "__missing",
name: this.hass.localize( primary: this.hass.localize(
"ui.components.statistic-picker.missing_entity"
),
label: this.hass.localize(
"ui.components.statistic-picker.missing_entity" "ui.components.statistic-picker.missing_entity"
), ),
strings: [],
}); });
return output; return output;
} }
); );
public open() { public async open() {
this.comboBox?.open(); await this.updateComplete;
await this.comboBox?.open();
} }
public focus() { public async focus() {
this.comboBox?.focus(); await this.updateComplete;
await this.comboBox?.focus();
}
protected shouldUpdate(changedProps: PropertyValues) {
if (
changedProps.has("value") ||
changedProps.has("label") ||
changedProps.has("disabled")
) {
return true;
}
return !(!changedProps.has("_opened") && this._opened);
} }
public willUpdate(changedProps: PropertyValues) { public willUpdate(changedProps: PropertyValues) {
@ -250,39 +363,28 @@ export class HaStatisticPicker extends LitElement {
) { ) {
this._getStatisticIds(); this._getStatisticIds();
} }
if (
(!this._init && this.statisticIds) || if (!this._initialItems || (changedProps.has("_opened") && this._opened)) {
(changedProps.has("_opened") && this._opened) this._items = this._getItems(
) { this._opened,
this._init = true; this.hass,
if (this.hasUpdated) { this.statisticIds!,
this._statistics = this._getStatistics( this.includeStatisticsUnitOfMeasurement,
this.statisticIds!, this.includeUnitClass,
this.includeStatisticsUnitOfMeasurement, this.includeDeviceClass,
this.includeUnitClass, this.entitiesOnly,
this.includeDeviceClass, this.excludeStatistics,
this.entitiesOnly, this.value
this.excludeStatistics, );
this.value if (this._initialItems) {
); this.comboBox.filteredItems = this._items;
} else {
this.updateComplete.then(() => {
this._statistics = this._getStatistics(
this.statisticIds!,
this.includeStatisticsUnitOfMeasurement,
this.includeUnitClass,
this.includeDeviceClass,
this.entitiesOnly,
this.excludeStatistics,
this.value
);
});
} }
this._initialItems = true;
} }
} }
protected render(): TemplateResult | typeof nothing { protected render(): TemplateResult | typeof nothing {
if (this._statistics.length === 0) { if (this._items.length === 0) {
return nothing; return nothing;
} }
@ -296,11 +398,10 @@ export class HaStatisticPicker extends LitElement {
.renderer=${this._rowRenderer} .renderer=${this._rowRenderer}
.disabled=${this.disabled} .disabled=${this.disabled}
.allowCustomValue=${this.allowCustomEntity} .allowCustomValue=${this.allowCustomEntity}
.items=${this._statistics} .filteredItems=${this._items}
.filteredItems=${this._filteredItems ?? this._statistics}
item-value-path="id" item-value-path="id"
item-id-path="id" item-id-path="id"
item-label-path="name" item-label-path="label"
@opened-changed=${this._openedChanged} @opened-changed=${this._openedChanged}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
@filter-changed=${this._filterChanged} @filter-changed=${this._filterChanged}
@ -332,11 +433,49 @@ export class HaStatisticPicker extends LitElement {
this._opened = ev.detail.value; this._opened = ev.detail.value;
} }
private _fuseKeys = [
"label",
"entity_name",
"device_name",
"area_name",
"friendly_name", // for backwards compatibility
"id", // for technical search
];
private _fuseIndex = memoizeOne((states: StatisticItem[]) =>
Fuse.createIndex(this._fuseKeys, states)
);
private _filterChanged(ev: CustomEvent): void { private _filterChanged(ev: CustomEvent): void {
const filterString = ev.detail.value.toLowerCase(); const target = ev.target as HaComboBox;
this._filteredItems = filterString.length const filterString = ev.detail.value.trim().toLowerCase() as string;
? fuzzyFilterSort<StatisticItem>(filterString, this._statistics)
: undefined; const minLength = 2;
const searchTerms = (filterString.split(" ") ?? []).filter(
(term) => term.length >= minLength
);
if (searchTerms.length > 0) {
const index = this._fuseIndex(this._items);
const options: IFuseOptions<StatisticItem> = {
isCaseSensitive: false,
threshold: 0.3,
ignoreDiacritics: true,
minMatchCharLength: minLength,
};
const fuse = new Fuse(this._items, options, index);
const results = fuse.search({
$and: searchTerms.map((term) => ({
$or: this._fuseKeys.map((key) => ({ [key]: term })),
})),
});
target.filteredItems = results.map((result) => result.item);
} else {
target.filteredItems = this._items;
}
} }
private _setValue(value: string) { private _setValue(value: string) {

View File

@ -722,6 +722,7 @@
"statistic": "Statistic", "statistic": "Statistic",
"no_statistics": "You don't have any statistics", "no_statistics": "You don't have any statistics",
"no_match": "No matching statistics found", "no_match": "No matching statistics found",
"no_state": "Entity without state",
"missing_entity": "Why is my entity not listed?", "missing_entity": "Why is my entity not listed?",
"learn_more": "Learn more about statistics" "learn_more": "Learn more about statistics"
}, },