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

Migrate entity state content picker to generic picker (#28612)

* Migrate entity state content picker to generic picker

* Use similar primary/secondary as name picker

* Remove redundant func

* Memoize func

* Add custom value label

* Format

* Remove

* Remove renderer, use better translation

* Format

* Cleanup import

* Remove search labels where unused

* Merge
This commit is contained in:
Aidan Timson
2025-12-18 18:12:03 +00:00
committed by GitHub
parent f8ec5d27a4
commit a3921f0559
2 changed files with 240 additions and 200 deletions

View File

@@ -1,16 +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 { IFuseOptions } from "fuse.js";
import Fuse from "fuse.js";
import type { HassEntity } from "home-assistant-js-websocket"; import type { HassEntity } from "home-assistant-js-websocket";
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 { computeDomain } from "../../common/entity/compute_domain"; import { computeDomain } from "../../common/entity/compute_domain";
import { import {
STATE_DISPLAY_SPECIAL_CONTENT, STATE_DISPLAY_SPECIAL_CONTENT,
@@ -20,21 +15,13 @@ 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 type { PickerComboBoxItem } from "../ha-picker-combo-box";
import "../ha-sortable"; import "../ha-sortable";
interface StateContentOption {
primary: string;
value: string;
}
const rowRenderer: ComboBoxLitRenderer<StateContentOption> = (item) => html`
<ha-combo-box-item type="button">
<span slot="headline">${item.primary}</span>
</ha-combo-box-item>
`;
const HIDDEN_ATTRIBUTES = [ const HIDDEN_ATTRIBUTES = [
"access_token", "access_token",
"available_modes", "available_modes",
@@ -111,63 +98,88 @@ export class HaStateContentPicker extends LitElement {
@property() public helper?: string; @property() public helper?: string;
@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;
private _options = memoizeOne( private _getItems = memoizeOne(
(entityId?: string, stateObj?: HassEntity, allowName?: boolean) => { (entityId?: string, stateObj?: HassEntity, allowName?: boolean) => {
const domain = entityId ? computeDomain(entityId) : undefined; const domain = entityId ? computeDomain(entityId) : undefined;
return [ const items: PickerComboBoxItem[] = [
{ {
id: "state",
primary: this.hass.localize( primary: this.hass.localize(
"ui.components.state-content-picker.state" "ui.components.state-content-picker.state"
), ),
value: "state", sorting_label: this.hass.localize(
"ui.components.state-content-picker.state"
),
}, },
...(allowName ...(allowName
? [ ? [
{ {
id: "name",
primary: this.hass.localize( primary: this.hass.localize(
"ui.components.state-content-picker.name" "ui.components.state-content-picker.name"
), ),
value: "name", sorting_label: this.hass.localize(
}, "ui.components.state-content-picker.name"
),
} satisfies PickerComboBoxItem,
] ]
: []), : []),
{ {
id: "last_changed",
primary: this.hass.localize( primary: this.hass.localize(
"ui.components.state-content-picker.last_changed" "ui.components.state-content-picker.last_changed"
), ),
value: "last_changed", sorting_label: this.hass.localize(
"ui.components.state-content-picker.last_changed"
),
}, },
{ {
id: "last_updated",
primary: this.hass.localize( primary: this.hass.localize(
"ui.components.state-content-picker.last_updated" "ui.components.state-content-picker.last_updated"
), ),
value: "last_updated", sorting_label: this.hass.localize(
"ui.components.state-content-picker.last_updated"
),
}, },
...(domain ...(domain
? STATE_DISPLAY_SPECIAL_CONTENT.filter((content) => ? STATE_DISPLAY_SPECIAL_CONTENT.filter((content) =>
STATE_DISPLAY_SPECIAL_CONTENT_DOMAINS[domain]?.includes(content) STATE_DISPLAY_SPECIAL_CONTENT_DOMAINS[domain]?.includes(content)
).map((content) => ({ ).map(
(content) =>
({
id: content,
primary: this.hass.localize( primary: this.hass.localize(
`ui.components.state-content-picker.${content}` `ui.components.state-content-picker.${content}`
), ),
value: content, sorting_label: this.hass.localize(
})) `ui.components.state-content-picker.${content}`
),
}) satisfies PickerComboBoxItem
)
: []), : []),
...Object.keys(stateObj?.attributes ?? {}) ...Object.keys(stateObj?.attributes ?? {})
.filter((a) => !HIDDEN_ATTRIBUTES.includes(a)) .filter((a) => !HIDDEN_ATTRIBUTES.includes(a))
.map((attribute) => ({ .map(
primary: this.hass.formatEntityAttributeName(stateObj!, attribute), (attribute) =>
value: attribute, ({
})), id: attribute,
] satisfies StateContentOption[]; primary: this.hass.formatEntityAttributeName(
stateObj!,
attribute
),
sorting_label: this.hass.formatEntityAttributeName(
stateObj!,
attribute
),
}) satisfies PickerComboBoxItem
),
];
return items;
} }
); );
@@ -178,11 +190,23 @@ export class HaStateContentPicker extends LitElement {
? this.hass.states[this.entityId] ? this.hass.states[this.entityId]
: undefined; : undefined;
const options = this._options(this.entityId, stateObj, this.allowName);
return html` return html`
${this.label ? html`<label>${this.label}</label>` : nothing} ${this.label ? html`<label>${this.label}</label>` : nothing}
<div class="container ${this.disabled ? "disabled" : ""}"> <ha-generic-picker
.hass=${this.hass}
.disabled=${this.disabled}
.required=${this.required && !value.length}
.value=${this._getPickerValue()}
.getItems=${this._getFilteredItems}
.getAdditionalItems=${this._getAdditionalItems}
.notFoundLabel=${this.hass.localize("ui.components.combo-box.no_match")}
allow-custom-value
.customValueLabel=${this.hass.localize(
"ui.components.entity.entity-state-content-picker.custom_state"
)}
@value-changed=${this._pickerValueChanged}
>
<div slot="field" class="container">
<ha-sortable <ha-sortable
no-style no-style
@item-moved=${this._moveItem} @item-moved=${this._moveItem}
@@ -195,7 +219,7 @@ export class HaStateContentPicker extends LitElement {
this._value, this._value,
(item) => item, (item) => item,
(item: string, idx) => { (item: string, idx) => {
const label = options.find((o) => o.value === item)?.primary; const label = this._getItemLabel(item, stateObj);
const isValid = !!label; const isValid = !!label;
return html` return html`
<ha-input-chip <ha-input-chip
@@ -231,69 +255,58 @@ export class HaStateContentPicker extends LitElement {
`} `}
</ha-chip-set> </ha-chip-set>
</ha-sortable> </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 || !this.entityId}
.required=${this.required && !value.length}
.helper=${this.helper}
.items=${options}
allow-custom-value
item-id-path="value"
item-value-path="value"
item-label-path="primary"
.renderer=${rowRenderer}
@opened-changed=${this._openedChanged}
@value-changed=${this._comboBoxValueChanged}
@filter-changed=${this._filterChanged}
>
</ha-combo-box>
</mwc-menu-surface>
</div> </div>
</ha-generic-picker>
${this._renderHelper()}
`; `;
} }
private _onClosed(ev) { private _renderHelper() {
return this.helper
? html`
<ha-input-helper-text .disabled=${this.disabled}>
${this.helper}
</ha-input-helper-text>
`
: nothing;
}
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 _value() { private get _value() {
return !this.value ? [] : ensureArray(this.value); return !this.value ? [] : ensureArray(this.value);
} }
private _getItemLabel = memoizeOne(
(value: string, stateObj?: HassEntity): string | undefined => {
const stateObjForItems = this.entityId
? this.hass.states[this.entityId]
: stateObj;
const items = this._getItems(
this.entityId,
stateObjForItems,
this.allowName
);
return items.find((item) => item.id === value)?.primary;
}
);
private _toValue = memoizeOne((value: string[]): typeof this.value => { private _toValue = memoizeOne((value: string[]): typeof this.value => {
if (value.length === 0) { if (value.length === 0) {
return undefined; return undefined;
@@ -304,64 +317,88 @@ export class HaStateContentPicker extends LitElement {
return value; return value;
}); });
private _openedChanged(ev: ValueChangedEvent<boolean>) { private _getPickerValue(): string | undefined {
const open = ev.detail.value; if (this._editIndex != null) {
if (open) { return this._value[this._editIndex];
const options = this._comboBox.items || [];
const initialValue =
this._editIndex != null ? this._value[this._editIndex] : "";
const filteredItems = this._filterSelectedOptions(options, initialValue);
this._comboBox.filteredItems = filteredItems;
this._comboBox.setInputValue(initialValue);
} else {
this._opened = false;
} }
return undefined;
} }
private _filterSelectedOptions = ( private _customValueOption = memoizeOne(
options: StateContentOption[], (text: string): PickerComboBoxItem => ({
current?: string id: text,
) => { primary: this.hass.localize(
"ui.components.entity.entity-state-content-picker.custom_state"
),
secondary: `"${text}"`,
search_labels: {
primary: text,
secondary: `"${text}"`,
id: text,
},
sorting_label: text,
})
);
private _getFilteredItems = (
searchString?: string,
_section?: string
): PickerComboBoxItem[] => {
const stateObj = this.entityId
? this.hass.states[this.entityId]
: undefined;
const items = this._getItems(this.entityId, stateObj, this.allowName);
const currentValue =
this._editIndex != null ? this._value[this._editIndex] : undefined;
const value = this._value; const value = this._value;
return options.filter( const filteredItems = items.filter(
(option) => !value.includes(option.value) || option.value === current (item) => !value.includes(item.id) || item.id === currentValue
); );
// When editing an existing custom value, include it in the base items
if (
currentValue &&
!items.find((item) => item.id === currentValue) &&
!searchString
) {
filteredItems.push(this._customValueOption(currentValue));
}
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 currentValue = const currentValue =
this._editIndex != null ? this._value[this._editIndex] : ""; this._editIndex != null ? this._value[this._editIndex] : undefined;
this._comboBox.filteredItems = this._filterSelectedOptions( // Don't add if it's the same as the current item being edited
options, if (currentValue && currentValue === searchString) {
currentValue return [];
);
if (!filter) {
return;
} }
const fuseOptions: IFuseOptions<StateContentOption> = { // Check if the search string matches an existing item
keys: ["primary", "secondary", "value"], const stateObj = this.entityId
isCaseSensitive: false, ? this.hass.states[this.entityId]
minMatchCharLength: Math.min(filter.length, 2), : undefined;
threshold: 0.2, const items = this._getItems(this.entityId, stateObj, this.allowName);
ignoreDiacritics: true, const existingItem = items.find((item) => item.id === searchString);
// Only return custom value option if it doesn't match an existing item
if (!existingItem) {
return [this._customValueOption(searchString)];
}
return [];
}; };
const fuse = new Fuse(this._comboBox.filteredItems, fuseOptions);
const filteredItems = fuse.search(filter).map((result) => result.item);
this._comboBox.filteredItems = filteredItems;
}
private async _moveItem(ev: CustomEvent) { private async _moveItem(ev: CustomEvent) {
ev.stopPropagation(); ev.stopPropagation();
const { oldIndex, newIndex } = ev.detail; const { oldIndex, newIndex } = ev.detail;
@@ -370,25 +407,21 @@ export class HaStateContentPicker 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._value]; const value = [...this._value];
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;
} }
@@ -396,11 +429,16 @@ export class HaStateContentPicker extends LitElement {
if (this._editIndex != null) { if (this._editIndex != null) {
newValue[this._editIndex] = value; newValue[this._editIndex] = value;
this._editIndex = undefined;
} else { } else {
newValue.push(value); newValue.push(value);
} }
this._setValue(newValue); this._setValue(newValue);
if (this._picker) {
this._picker.value = undefined;
}
} }
private _setValue(value: string[]) { private _setValue(value: string[]) {
@@ -442,7 +480,7 @@ export class HaStateContentPicker extends LitElement {
height 180ms ease-in-out, height 180ms ease-in-out,
background-color 180ms ease-in-out; background-color 180ms ease-in-out;
} }
.container.disabled:after { :host([disabled]) .container:after {
background-color: var( background-color: var(
--mdc-text-field-disabled-line-color, --mdc-text-field-disabled-line-color,
rgba(0, 0, 0, 0.42) rgba(0, 0, 0, 0.42)
@@ -462,10 +500,6 @@ export class HaStateContentPicker 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);
} }
@@ -486,6 +520,11 @@ export class HaStateContentPicker extends LitElement {
.sortable-drag { .sortable-drag {
cursor: grabbing; cursor: grabbing;
} }
ha-input-helper-text {
display: block;
margin: var(--ha-space-2) 0 0;
}
`; `;
} }

View File

@@ -683,7 +683,8 @@
"state": "State" "state": "State"
}, },
"entity-state-content-picker": { "entity-state-content-picker": {
"add": "Add" "add": "Add",
"custom_state": "Custom state"
} }
}, },
"target-picker": { "target-picker": {