1
0
mirror of https://github.com/home-assistant/frontend.git synced 2025-12-20 02:38:53 +00:00

Migrate entity name picker to generic picker (#28604)

Co-authored-by: Wendelin <12148533+wendevlin@users.noreply.github.com>
This commit is contained in:
Aidan Timson
2025-12-18 13:31:29 +00:00
committed by GitHub
parent 6ff3b9f761
commit 96be4768d3
3 changed files with 184 additions and 197 deletions

View File

@@ -1,15 +1,11 @@
import "@material/mwc-menu/mwc-menu-surface";
import { mdiDragHorizontalVariant, mdiPlus } from "@mdi/js"; import { mdiDragHorizontalVariant, mdiPlus } from "@mdi/js";
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit"; import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import type { IFuseOptions } from "fuse.js";
import Fuse from "fuse.js";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators"; import { customElement, property, query } from "lit/decorators";
import { repeat } from "lit/directives/repeat"; import { repeat } from "lit/directives/repeat";
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 { stopPropagation } from "../../common/dom/stop_propagation";
import type { EntityNameItem } from "../../common/entity/compute_entity_name_display"; import type { EntityNameItem } from "../../common/entity/compute_entity_name_display";
import { getEntityContext } from "../../common/entity/context/get_entity_context"; import { getEntityContext } from "../../common/entity/context/get_entity_context";
import type { EntityNameType } from "../../common/translations/entity-state"; import type { EntityNameType } from "../../common/translations/entity-state";
@@ -18,20 +14,18 @@ import type { HomeAssistant, ValueChangedEvent } from "../../types";
import "../chips/ha-assist-chip"; import "../chips/ha-assist-chip";
import "../chips/ha-chip-set"; import "../chips/ha-chip-set";
import "../chips/ha-input-chip"; import "../chips/ha-input-chip";
import "../ha-combo-box"; import "../ha-combo-box-item";
import type { HaComboBox } from "../ha-combo-box"; import "../ha-generic-picker";
import type { HaGenericPicker } from "../ha-generic-picker";
import "../ha-input-helper-text"; import "../ha-input-helper-text";
import {
NO_ITEMS_AVAILABLE_ID,
type PickerComboBoxItem,
} from "../ha-picker-combo-box";
import "../ha-sortable"; import "../ha-sortable";
interface EntityNameOption { const rowRenderer: RenderItemFunction<PickerComboBoxItem> = (item) => html`
primary: string; <ha-combo-box-item type="button" compact>
secondary?: string;
field_label: string;
value: string;
}
const rowRenderer: ComboBoxLitRenderer<EntityNameOption> = (item) => html`
<ha-combo-box-item type="button">
<span slot="headline">${item.primary}</span> <span slot="headline">${item.primary}</span>
${item.secondary ${item.secondary
? html`<span slot="supporting-text">${item.secondary}</span>` ? html`<span slot="supporting-text">${item.secondary}</span>`
@@ -79,11 +73,7 @@ export class HaEntityNamePicker extends LitElement {
@property({ type: Boolean, reflect: true }) public disabled = false; @property({ type: Boolean, reflect: true }) public disabled = false;
@query(".container", true) private _container?: HTMLDivElement; @query("ha-generic-picker", true) private _picker?: HaGenericPicker;
@query("ha-combo-box", true) private _comboBox!: HaComboBox;
@state() private _opened = false;
private _editIndex?: number; private _editIndex?: number;
@@ -115,7 +105,7 @@ export class HaEntityNamePicker extends LitElement {
return options; return options;
}); });
private _getOptions = memoizeOne((entityId?: string) => { private _getItems = memoizeOne((entityId?: string) => {
if (!entityId) { if (!entityId) {
return []; return [];
} }
@@ -124,7 +114,7 @@ export class HaEntityNamePicker extends LitElement {
const items = ( const items = (
["entity", "device", "area", "floor"] as const ["entity", "device", "area", "floor"] as const
).map<EntityNameOption>((name) => { ).map<PickerComboBoxItem>((name) => {
const stateObj = this.hass.states[entityId]; const stateObj = this.hass.states[entityId];
const isValid = types.has(name); const isValid = types.has(name);
const primary = this.hass.localize( const primary = this.hass.localize(
@@ -137,25 +127,39 @@ export class HaEntityNamePicker extends LitElement {
`ui.components.entity.entity-name-picker.types.${name}_missing` as LocalizeKeys `ui.components.entity.entity-name-picker.types.${name}_missing` as LocalizeKeys
)) || "-"; )) || "-";
const id = formatOptionValue({ type: name });
return { return {
id,
primary, primary,
secondary, secondary,
field_label: primary, search_labels: {
value: formatOptionValue({ type: name }), primary,
secondary: secondary || null,
id,
},
sorting_label: primary,
}; };
}); });
return items; return items;
}); });
private _customNameOption = memoizeOne((text: string) => ({ private _customNameOption = memoizeOne(
primary: this.hass.localize( (text: string): PickerComboBoxItem => ({
"ui.components.entity.entity-name-picker.custom_name" id: formatOptionValue({ type: "text", text }),
), primary: this.hass.localize(
secondary: `"${text}"`, "ui.components.entity.entity-name-picker.custom_name"
field_label: text, ),
value: formatOptionValue({ type: "text", text }), secondary: `"${text}"`,
})); search_labels: {
primary: text,
secondary: `"${text}"`,
id: formatOptionValue({ type: "text", text }),
},
sorting_label: text,
})
);
private _formatItem = (item: EntityNameItem) => { private _formatItem = (item: EntityNameItem) => {
if (item.type === "text") { if (item.type === "text") {
@@ -171,88 +175,80 @@ export class HaEntityNamePicker extends LitElement {
protected render() { protected render() {
const value = this._items; const value = this._items;
const options = this._getOptions(this.entityId);
const validTypes = this._validTypes(this.entityId); const validTypes = this._validTypes(this.entityId);
return html` return html`
${this.label ? html`<label>${this.label}</label>` : nothing} ${this.label ? html`<label>${this.label}</label>` : nothing}
<div class="container"> <ha-generic-picker
<ha-sortable .hass=${this.hass}
no-style .disabled=${this.disabled}
@item-moved=${this._moveItem} .required=${this.required && !value.length}
.disabled=${this.disabled} .getItems=${this._getFilteredItems}
handle-selector="button.primary.action" .getAdditionalItems=${this._getAdditionalItems}
filter=".add" .rowRenderer=${rowRenderer}
> .searchFn=${this._searchFn}
<ha-chip-set> .notFoundLabel=${this.hass.localize(
${repeat( "ui.components.entity.entity-name-picker.no_match"
this._items, )}
(item) => item, .value=${this._getPickerValue()}
(item: EntityNameItem, idx) => { allow-custom-value
const label = this._formatItem(item); .customValueLabel=${this.hass.localize(
const isValid = validTypes.has(item.type); "ui.components.entity.entity-name-picker.custom_name"
return html` )}
<ha-input-chip @value-changed=${this._pickerValueChanged}
data-idx=${idx} >
@remove=${this._removeItem} <div slot="field" class="container">
@click=${this._editItem} <ha-sortable
.label=${label} no-style
.selected=${!this.disabled} @item-moved=${this._moveItem}
.disabled=${this.disabled}
class=${!isValid ? "invalid" : ""}
>
<ha-svg-icon
slot="icon"
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
<span>${label}</span>
</ha-input-chip>
`;
}
)}
${this.disabled
? nothing
: html`
<ha-assist-chip
@click=${this._addItem}
.disabled=${this.disabled}
label=${this.hass.localize(
"ui.components.entity.entity-name-picker.add"
)}
class="add"
>
<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon>
</ha-assist-chip>
`}
</ha-chip-set>
</ha-sortable>
<mwc-menu-surface
.open=${this._opened}
@closed=${this._onClosed}
@opened=${this._onOpened}
@input=${stopPropagation}
.anchor=${this._container}
>
<ha-combo-box
.hass=${this.hass}
.value=${""}
.autofocus=${this.autofocus}
.disabled=${this.disabled} .disabled=${this.disabled}
.required=${this.required && !value.length} handle-selector="button.primary.action"
.items=${options} filter=".add"
allow-custom-value
item-id-path="value"
item-value-path="value"
item-label-path="field_label"
.renderer=${rowRenderer}
@opened-changed=${this._openedChanged}
@value-changed=${this._comboBoxValueChanged}
@filter-changed=${this._filterChanged}
> >
</ha-combo-box> <ha-chip-set>
</mwc-menu-surface> ${repeat(
</div> this._items,
(item) => item,
(item: EntityNameItem, idx) => {
const label = this._formatItem(item);
const isValid = validTypes.has(item.type);
return html`
<ha-input-chip
data-idx=${idx}
@remove=${this._removeItem}
@click=${this._editItem}
.label=${label}
.selected=${!this.disabled}
.disabled=${this.disabled}
class=${!isValid ? "invalid" : ""}
>
<ha-svg-icon
slot="icon"
.path=${mdiDragHorizontalVariant}
></ha-svg-icon>
<span>${label}</span>
</ha-input-chip>
`;
}
)}
${this.disabled
? nothing
: html`
<ha-assist-chip
@click=${this._addItem}
.disabled=${this.disabled}
label=${this.hass.localize(
"ui.components.entity.entity-name-picker.add"
)}
class="add"
>
<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon>
</ha-assist-chip>
`}
</ha-chip-set>
</ha-sortable>
</div>
</ha-generic-picker>
${this._renderHelper()} ${this._renderHelper()}
`; `;
} }
@@ -267,32 +263,22 @@ export class HaEntityNamePicker extends LitElement {
: nothing; : nothing;
} }
private _onClosed(ev) { private async _addItem(ev: Event) {
ev.stopPropagation(); ev.stopPropagation();
this._opened = false;
this._editIndex = undefined; this._editIndex = undefined;
await this.updateComplete;
await this._picker?.open();
} }
private async _onOpened(ev) { private async _editItem(ev: Event) {
if (!this._opened) {
return;
}
ev.stopPropagation(); ev.stopPropagation();
this._opened = true; const idx = parseInt(
await this._comboBox?.focus(); (ev.currentTarget as HTMLElement).dataset.idx || "",
await this._comboBox?.open(); 10
} );
private async _addItem(ev) {
ev.stopPropagation();
this._opened = true;
}
private async _editItem(ev) {
ev.stopPropagation();
const idx = parseInt(ev.currentTarget.dataset.idx, 10);
this._editIndex = idx; this._editIndex = idx;
this._opened = true; await this.updateComplete;
await this._picker?.open();
} }
private get _items(): EntityNameItem[] { private get _items(): EntityNameItem[] {
@@ -322,78 +308,80 @@ export class HaEntityNamePicker extends LitElement {
} }
); );
private _openedChanged(ev: ValueChangedEvent<boolean>) { private _getPickerValue(): string | undefined {
const open = ev.detail.value; if (this._editIndex != null) {
if (open) { const item = this._items[this._editIndex];
const options = this._comboBox.items || []; return item ? formatOptionValue(item) : undefined;
const initialItem =
this._editIndex != null ? this._items[this._editIndex] : undefined;
const initialValue = initialItem ? formatOptionValue(initialItem) : "";
const filteredItems = this._filterSelectedOptions(options, initialValue);
if (initialItem?.type === "text" && initialItem.text) {
filteredItems.push(this._customNameOption(initialItem.text));
}
this._comboBox.filteredItems = filteredItems;
this._comboBox.setInputValue(initialValue);
} else {
this._opened = false;
this._comboBox.setInputValue("");
} }
return undefined;
} }
private _filterSelectedOptions = ( private _getFilteredItems = (
options: EntityNameOption[], searchString?: string,
current?: string _section?: string
) => { ): PickerComboBoxItem[] => {
const items = this._items; const items = this._getItems(this.entityId);
const currentItem =
this._editIndex != null ? this._items[this._editIndex] : undefined;
const currentValue = currentItem ? formatOptionValue(currentItem) : "";
const excludedValues = new Set( const excludedValues = new Set(
items this._items
.filter((item) => UNIQUE_TYPES.has(item.type)) .filter((item) => UNIQUE_TYPES.has(item.type))
.map((item) => formatOptionValue(item)) .map((item) => formatOptionValue(item))
); );
const filteredOptions = options.filter( const filteredItems = items.filter(
(option) => !excludedValues.has(option.value) || option.value === current (item) => !excludedValues.has(item.id) || item.id === currentValue
); );
return filteredOptions;
// When editing an existing text item, include it in the base items
if (currentItem?.type === "text" && currentItem.text && !searchString) {
filteredItems.push(this._customNameOption(currentItem.text));
}
return filteredItems;
}; };
private _filterChanged(ev: ValueChangedEvent<string>) { private _getAdditionalItems = (
const input = ev.detail.value; searchString?: string
const filter = input?.toLowerCase() || ""; ): PickerComboBoxItem[] => {
const options = this._comboBox.items || []; if (!searchString) {
return [];
}
const currentItem = const currentItem =
this._editIndex != null ? this._items[this._editIndex] : undefined; this._editIndex != null ? this._items[this._editIndex] : undefined;
const currentValue = currentItem ? formatOptionValue(currentItem) : ""; // Don't add if it's the same as the current item being edited
if (
let filteredItems = this._filterSelectedOptions(options, currentValue); currentItem?.type === "text" &&
currentItem.text &&
if (!filter) { currentItem.text === searchString
this._comboBox.filteredItems = filteredItems; ) {
return; return [];
} }
const fuseOptions: IFuseOptions<EntityNameOption> = { // Always return custom name option when there's a search string
keys: ["primary", "secondary", "value"], // This prevents "No matching items found" from showing
isCaseSensitive: false, return [this._customNameOption(searchString)];
minMatchCharLength: Math.min(filter.length, 2), };
threshold: 0.2,
ignoreDiacritics: true,
};
const fuse = new Fuse(filteredItems, fuseOptions); private _searchFn = (
filteredItems = fuse.search(filter).map((result) => result.item); search: string,
filteredItems.push(this._customNameOption(input)); filteredItems: PickerComboBoxItem[],
this._comboBox.filteredItems = filteredItems; _allItems: PickerComboBoxItem[]
} ): PickerComboBoxItem[] => {
// Remove NO_ITEMS_AVAILABLE_ID if we have additional items (custom name option)
// This prevents "No matching items found" from showing when custom values are allowed
const hasAdditionalItems = this._getAdditionalItems(search).length > 0;
if (hasAdditionalItems) {
return filteredItems.filter(
(item) => typeof item !== "string" || item !== NO_ITEMS_AVAILABLE_ID
);
}
return filteredItems;
};
private async _moveItem(ev: CustomEvent) { private async _moveItem(ev: CustomEvent) {
ev.stopPropagation(); ev.stopPropagation();
@@ -403,25 +391,21 @@ export class HaEntityNamePicker extends LitElement {
const element = newValue.splice(oldIndex, 1)[0]; const element = newValue.splice(oldIndex, 1)[0];
newValue.splice(newIndex, 0, element); newValue.splice(newIndex, 0, element);
this._setValue(newValue); this._setValue(newValue);
await this.updateComplete;
this._filterChanged({ detail: { value: "" } } as ValueChangedEvent<string>);
} }
private async _removeItem(ev) { private async _removeItem(ev: Event) {
ev.stopPropagation(); ev.stopPropagation();
const value = [...this._items]; const value = [...this._items];
const idx = parseInt(ev.target.dataset.idx, 10); const idx = parseInt((ev.target as HTMLElement).dataset.idx || "", 10);
value.splice(idx, 1); value.splice(idx, 1);
this._setValue(value); this._setValue(value);
await this.updateComplete;
this._filterChanged({ detail: { value: "" } } as ValueChangedEvent<string>);
} }
private _comboBoxValueChanged(ev: ValueChangedEvent<string>): void { private _pickerValueChanged(ev: ValueChangedEvent<string>): void {
ev.stopPropagation(); ev.stopPropagation();
const value = ev.detail.value; const value = ev.detail.value;
if (this.disabled || value === "") { if (this.disabled || !value) {
return; return;
} }
@@ -431,11 +415,16 @@ export class HaEntityNamePicker extends LitElement {
if (this._editIndex != null) { if (this._editIndex != null) {
newValue[this._editIndex] = item; newValue[this._editIndex] = item;
this._editIndex = undefined;
} else { } else {
newValue.push(item); newValue.push(item);
} }
this._setValue(newValue); this._setValue(newValue);
if (this._picker) {
this._picker.value = undefined;
}
} }
private _setValue(value: EntityNameItem[]) { private _setValue(value: EntityNameItem[]) {
@@ -497,10 +486,6 @@ export class HaEntityNamePicker extends LitElement {
order: 1; order: 1;
} }
mwc-menu-surface {
--mdc-menu-min-width: 100%;
}
ha-chip-set { ha-chip-set {
padding: var(--ha-space-2) var(--ha-space-2); padding: var(--ha-space-2) var(--ha-space-2);
} }

View File

@@ -53,7 +53,8 @@ export interface PickerComboBoxItem {
icon_path?: string; icon_path?: string;
icon?: string; icon?: string;
} }
const NO_ITEMS_AVAILABLE_ID = "___no_items_available___";
export const NO_ITEMS_AVAILABLE_ID = "___no_items_available___";
const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = ( const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = (
item item

View File

@@ -672,7 +672,8 @@
"device_missing": "No related device" "device_missing": "No related device"
}, },
"add": "Add", "add": "Add",
"custom_name": "Custom name" "custom_name": "Custom name",
"no_match": "No entities found"
}, },
"entity-attribute-picker": { "entity-attribute-picker": {
"attribute": "Attribute", "attribute": "Attribute",