Add support for multiple entities and hide_states option in state and attribute selectors (#26207)

* Add support for multiple entities and target for state selector

* Add support for multiple entities for attribute selector

* Improve context support

* Add combine mode and fix hidden and entity category for service control

* Don't use combine mode

* Refactor options
This commit is contained in:
Paul Bottein 2025-07-21 07:48:25 +02:00 committed by GitHub
parent 713e8e7b71
commit 3d1c908a01
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 169 additions and 80 deletions

View File

@ -2,18 +2,24 @@ import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit"; import type { PropertyValues } from "lit";
import { LitElement, html, nothing } from "lit"; import { LitElement, html, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators"; import { customElement, property, query, state } from "lit/decorators";
import { computeAttributeNameDisplay } from "../../common/entity/compute_attribute_display"; import { ensureArray } from "../../common/array/ensure-array";
import { fireEvent } from "../../common/dom/fire_event";
import type { HomeAssistant, ValueChangedEvent } from "../../types"; import type { HomeAssistant, ValueChangedEvent } from "../../types";
import "../ha-combo-box"; import "../ha-combo-box";
import type { HaComboBox } from "../ha-combo-box"; import type { HaComboBox } from "../ha-combo-box";
export type HaEntityPickerEntityFilterFunc = (entityId: HassEntity) => boolean; export type HaEntityPickerEntityFilterFunc = (entityId: HassEntity) => boolean;
interface AttributeOption {
value: string;
label: string;
}
@customElement("ha-entity-attribute-picker") @customElement("ha-entity-attribute-picker")
class HaEntityAttributePicker extends LitElement { class HaEntityAttributePicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public entityId?: string; @property({ attribute: false }) public entityId?: string | string[];
/** /**
* List of attributes to be hidden. * List of attributes to be hidden.
@ -48,23 +54,40 @@ class HaEntityAttributePicker extends LitElement {
} }
protected updated(changedProps: PropertyValues) { protected updated(changedProps: PropertyValues) {
if (changedProps.has("_opened") && this._opened) { if (
const entityState = this.entityId (changedProps.has("_opened") && this._opened) ||
? this.hass.states[this.entityId] changedProps.has("entityId") ||
: undefined; changedProps.has("attribute")
(this._comboBox as any).items = entityState ) {
? Object.keys(entityState.attributes) const entityIds = this.entityId ? ensureArray(this.entityId) : [];
.filter((key) => !this.hideAttributes?.includes(key)) const entitiesOptions = entityIds.map<AttributeOption[]>((entityId) => {
.map((key) => ({ const stateObj = this.hass.states[entityId];
value: key, if (!stateObj) {
label: computeAttributeNameDisplay( return [];
this.hass.localize, }
entityState,
this.hass.entities, const attributes = Object.keys(stateObj.attributes).filter(
key (a) => !this.hideAttributes?.includes(a)
), );
}))
: []; return attributes.map((a) => ({
value: a,
label: this.hass.formatEntityAttributeName(stateObj, a),
}));
});
const options: AttributeOption[] = [];
const optionsSet = new Set<string>();
for (const entityOptions of entitiesOptions) {
for (const option of entityOptions) {
if (!optionsSet.has(option.value)) {
optionsSet.add(option.value);
options.push(option);
}
}
}
(this._comboBox as any).filteredItems = options;
} }
} }
@ -73,21 +96,10 @@ class HaEntityAttributePicker extends LitElement {
return nothing; return nothing;
} }
const stateObj = this.hass.states[this.entityId!] as HassEntity | undefined;
return html` return html`
<ha-combo-box <ha-combo-box
.hass=${this.hass} .hass=${this.hass}
.value=${this.value .value=${this.value}
? stateObj
? computeAttributeNameDisplay(
this.hass.localize,
stateObj,
this.hass.entities,
this.value
)
: this.value
: ""}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label ?? .label=${this.label ??
this.hass.localize( this.hass.localize(
@ -97,6 +109,7 @@ class HaEntityAttributePicker extends LitElement {
.required=${this.required} .required=${this.required}
.helper=${this.helper} .helper=${this.helper}
.allowCustomValue=${this.allowCustomValue} .allowCustomValue=${this.allowCustomValue}
item-id-path="value"
item-value-path="value" item-value-path="value"
item-label-path="label" item-label-path="label"
@opened-changed=${this._openedChanged} @opened-changed=${this._openedChanged}
@ -106,12 +119,28 @@ class HaEntityAttributePicker extends LitElement {
`; `;
} }
private get _value() {
return this.value || "";
}
private _openedChanged(ev: ValueChangedEvent<boolean>) { private _openedChanged(ev: ValueChangedEvent<boolean>) {
this._opened = ev.detail.value; this._opened = ev.detail.value;
} }
private _valueChanged(ev: ValueChangedEvent<string>) { private _valueChanged(ev: ValueChangedEvent<string>) {
this.value = ev.detail.value; ev.stopPropagation();
const newValue = ev.detail.value;
if (newValue !== this._value) {
this._setValue(newValue);
}
}
private _setValue(value: string) {
this.value = value;
setTimeout(() => {
fireEvent(this, "value-changed", { value });
fireEvent(this, "change");
}, 0);
} }
} }

View File

@ -2,6 +2,7 @@ import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit"; import type { PropertyValues } from "lit";
import { LitElement, html, nothing } from "lit"; import { LitElement, html, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators"; import { customElement, property, query, state } from "lit/decorators";
import { ensureArray } from "../../common/array/ensure-array";
import { fireEvent } from "../../common/dom/fire_event"; import { fireEvent } from "../../common/dom/fire_event";
import { getStates } from "../../common/entity/get_states"; import { getStates } from "../../common/entity/get_states";
import type { HomeAssistant, ValueChangedEvent } from "../../types"; import type { HomeAssistant, ValueChangedEvent } from "../../types";
@ -10,11 +11,16 @@ import type { HaComboBox } from "../ha-combo-box";
export type HaEntityPickerEntityFilterFunc = (entityId: HassEntity) => boolean; export type HaEntityPickerEntityFilterFunc = (entityId: HassEntity) => boolean;
interface StateOption {
value: string;
label: string;
}
@customElement("ha-entity-state-picker") @customElement("ha-entity-state-picker")
class HaEntityStatePicker extends LitElement { class HaEntityStatePicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public entityId?: string; @property({ attribute: false }) public entityId?: string | string[];
@property() public attribute?: string; @property() public attribute?: string;
@ -30,6 +36,9 @@ class HaEntityStatePicker extends LitElement {
@property({ type: Boolean, attribute: "allow-custom-value" }) @property({ type: Boolean, attribute: "allow-custom-value" })
public allowCustomValue; public allowCustomValue;
@property({ attribute: false })
public hideStates?: string[];
@property() public label?: string; @property() public label?: string;
@property() public value?: string; @property() public value?: string;
@ -51,24 +60,42 @@ class HaEntityStatePicker extends LitElement {
changedProps.has("attribute") || changedProps.has("attribute") ||
changedProps.has("extraOptions") changedProps.has("extraOptions")
) { ) {
const stateObj = this.entityId const entityIds = this.entityId ? ensureArray(this.entityId) : [];
? this.hass.states[this.entityId]
: undefined; const entitiesOptions = entityIds.map<StateOption[]>((entityId) => {
(this._comboBox as any).items = [ const stateObj = this.hass.states[entityId];
...(this.extraOptions ?? []), if (!stateObj) {
...(this.entityId && stateObj return [];
? getStates(this.hass, stateObj, this.attribute).map((key) => ({ }
value: key,
label: !this.attribute const states = getStates(this.hass, stateObj, this.attribute).filter(
? this.hass.formatEntityState(stateObj, key) (s) => !this.hideStates?.includes(s)
: this.hass.formatEntityAttributeValue( );
stateObj,
this.attribute, return states.map((s) => ({
key value: s,
), label: this.attribute
})) ? this.hass.formatEntityAttributeValue(stateObj, this.attribute, s)
: []), : this.hass.formatEntityState(stateObj, s),
]; }));
});
const options: StateOption[] = [];
const optionsSet = new Set<string>();
for (const entityOptions of entitiesOptions) {
for (const option of entityOptions) {
if (!optionsSet.has(option.value)) {
optionsSet.add(option.value);
options.push(option);
}
}
}
if (this.extraOptions) {
options.unshift(...this.extraOptions);
}
(this._comboBox as any).filteredItems = options;
} }
} }
@ -88,6 +115,7 @@ class HaEntityStatePicker extends LitElement {
.required=${this.required} .required=${this.required}
.helper=${this.helper} .helper=${this.helper}
.allowCustomValue=${this.allowCustomValue} .allowCustomValue=${this.allowCustomValue}
item-id-path="value"
item-value-path="value" item-value-path="value"
item-label-path="label" item-label-path="label"
@opened-changed=${this._openedChanged} @opened-changed=${this._openedChanged}

View File

@ -5,6 +5,7 @@ import { fireEvent } from "../../common/dom/fire_event";
import type { AttributeSelector } from "../../data/selector"; import type { AttributeSelector } from "../../data/selector";
import type { HomeAssistant } from "../../types"; import type { HomeAssistant } from "../../types";
import "../entity/ha-entity-attribute-picker"; import "../entity/ha-entity-attribute-picker";
import { ensureArray } from "../../common/array/ensure-array";
@customElement("ha-selector-attribute") @customElement("ha-selector-attribute")
export class HaSelectorAttribute extends LitElement { export class HaSelectorAttribute extends LitElement {
@ -23,7 +24,7 @@ export class HaSelectorAttribute extends LitElement {
@property({ type: Boolean }) public required = true; @property({ type: Boolean }) public required = true;
@property({ attribute: false }) public context?: { @property({ attribute: false }) public context?: {
filter_entity?: string; filter_entity?: string | string[];
}; };
protected render() { protected render() {
@ -69,11 +70,16 @@ export class HaSelectorAttribute extends LitElement {
// Validate that that the attribute is still valid for this entity, else unselect. // Validate that that the attribute is still valid for this entity, else unselect.
let invalid = false; let invalid = false;
if (this.context.filter_entity) { if (this.context.filter_entity) {
const stateObj = this.hass.states[this.context.filter_entity]; const entityIds = ensureArray(this.context.filter_entity);
if (!(stateObj && this.value in stateObj.attributes)) { invalid = !entityIds.some((entityId) => {
invalid = true; const stateObj = this.hass.states[entityId];
} return (
stateObj &&
this.value in stateObj.attributes &&
stateObj.attributes[this.value] !== undefined
);
});
} else { } else {
invalid = this.value !== undefined; invalid = this.value !== undefined;
} }

View File

@ -23,7 +23,7 @@ export class HaSelectorState extends SubscribeMixin(LitElement) {
@property({ attribute: false }) public context?: { @property({ attribute: false }) public context?: {
filter_attribute?: string; filter_attribute?: string;
filter_entity?: string; filter_entity?: string | string[];
}; };
protected render() { protected render() {
@ -41,6 +41,7 @@ export class HaSelectorState extends SubscribeMixin(LitElement) {
.disabled=${this.disabled} .disabled=${this.disabled}
.required=${this.required} .required=${this.required}
allow-custom-value allow-custom-value
.hideStates=${this.selector.state?.hide_states}
></ha-entity-state-picker> ></ha-entity-state-picker>
`; `;
} }

View File

@ -314,7 +314,12 @@ export class HaServiceControl extends LitElement {
targetSelector targetSelector
); );
targetDevices.push(...expanded.devices); targetDevices.push(...expanded.devices);
targetEntities.push(...expanded.entities); const primaryEntities = expanded.entities.filter(
(entityId) =>
!this.hass.entities[entityId]?.entity_category &&
!this.hass.entities[entityId]?.hidden
);
targetEntities.push(primaryEntities);
targetAreas.push(...expanded.areas); targetAreas.push(...expanded.areas);
}); });
} }
@ -338,20 +343,29 @@ export class HaServiceControl extends LitElement {
this.hass.entities, this.hass.entities,
targetSelector targetSelector
); );
targetEntities.push(...expanded.entities); const primaryEntities = expanded.entities.filter(
(entityId) =>
!this.hass.entities[entityId]?.entity_category &&
!this.hass.entities[entityId]?.hidden
);
targetEntities.push(...primaryEntities);
targetDevices.push(...expanded.devices); targetDevices.push(...expanded.devices);
}); });
} }
if (targetDevices.length) { if (targetDevices.length) {
targetDevices.forEach((deviceId) => { targetDevices.forEach((deviceId) => {
targetEntities.push( const expanded = expandDeviceTarget(
...expandDeviceTarget(
this.hass, this.hass,
deviceId, deviceId,
this.hass.entities, this.hass.entities,
targetSelector targetSelector
).entities
); );
const primaryEntities = expanded.entities.filter(
(entityId) =>
!this.hass.entities[entityId]?.entity_category &&
!this.hass.entities[entityId]?.hidden
);
targetEntities.push(...primaryEntities);
}); });
} }
return targetEntities; return targetEntities;
@ -675,6 +689,7 @@ export class HaServiceControl extends LitElement {
) || dataField?.description}</span ) || dataField?.description}</span
> >
<ha-selector <ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${this.disabled || .disabled=${this.disabled ||
(showOptional && (showOptional &&
!this._checkedKeys.has(dataField.key) && !this._checkedKeys.has(dataField.key) &&
@ -694,6 +709,10 @@ export class HaServiceControl extends LitElement {
: ""; : "";
}; };
private _selectorContext = memoizeOne((targetEntities: string[] | null) => ({
filter_entity: targetEntities || undefined,
}));
private _localizeValueCallback = (key: string) => { private _localizeValueCallback = (key: string) => {
if (!this._value?.action) { if (!this._value?.action) {
return ""; return "";

View File

@ -719,7 +719,7 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
} }
private _entityRegMeetsFilter(entity: EntityRegistryDisplayEntry): boolean { private _entityRegMeetsFilter(entity: EntityRegistryDisplayEntry): boolean {
if (entity.entity_category) { if (entity.hidden || entity.entity_category) {
return false; return false;
} }

View File

@ -98,7 +98,7 @@ export interface AreasDisplaySelector {
export interface AttributeSelector { export interface AttributeSelector {
attribute: { attribute: {
entity_id?: string; entity_id?: string | string[];
hide_attributes?: readonly string[]; hide_attributes?: readonly string[];
} | null; } | null;
} }
@ -394,8 +394,9 @@ export interface SelectorSelector {
export interface StateSelector { export interface StateSelector {
state: { state: {
extra_options?: { label: string; value: any }[]; extra_options?: { label: string; value: any }[];
entity_id?: string; entity_id?: string | string[];
attribute?: string; attribute?: string;
hide_states?: string[];
} | null; } | null;
} }

View File

@ -24,7 +24,10 @@ import { baseTriggerStruct, forDictStruct } from "../../structs";
import type { TriggerElement } from "../ha-automation-trigger-row"; import type { TriggerElement } from "../ha-automation-trigger-row";
import "../../../../../components/ha-form/ha-form"; import "../../../../../components/ha-form/ha-form";
import { createDurationData } from "../../../../../common/datetime/create_duration_data"; import { createDurationData } from "../../../../../common/datetime/create_duration_data";
import type { SchemaUnion } from "../../../../../components/ha-form/types"; import type {
HaFormSchema,
SchemaUnion,
} from "../../../../../components/ha-form/types";
const stateTriggerStruct = assign( const stateTriggerStruct = assign(
baseTriggerStruct, baseTriggerStruct,
@ -54,7 +57,7 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
} }
private _schema = memoizeOne( private _schema = memoizeOne(
(localize: LocalizeFunc, entityId, attribute) => (localize: LocalizeFunc, attribute) =>
[ [
{ {
name: "entity_id", name: "entity_id",
@ -63,9 +66,11 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
}, },
{ {
name: "attribute", name: "attribute",
context: {
filter_entity: "entity_id",
},
selector: { selector: {
attribute: { attribute: {
entity_id: entityId ? entityId[0] : undefined,
hide_attributes: [ hide_attributes: [
"access_token", "access_token",
"available_modes", "available_modes",
@ -121,6 +126,9 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
}, },
{ {
name: "from", name: "from",
context: {
filter_entity: "entity_id",
},
selector: { selector: {
state: { state: {
extra_options: (attribute extra_options: (attribute
@ -133,13 +141,15 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
value: ANY_STATE_VALUE, value: ANY_STATE_VALUE,
}, },
]) as any, ]) as any,
entity_id: entityId ? entityId[0] : undefined,
attribute: attribute, attribute: attribute,
}, },
}, },
}, },
{ {
name: "to", name: "to",
context: {
filter_entity: "entity_id",
},
selector: { selector: {
state: { state: {
extra_options: (attribute extra_options: (attribute
@ -152,13 +162,12 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
value: ANY_STATE_VALUE, value: ANY_STATE_VALUE,
}, },
]) as any, ]) as any,
entity_id: entityId ? entityId[0] : undefined,
attribute: attribute, attribute: attribute,
}, },
}, },
}, },
{ name: "for", selector: { duration: {} } }, { name: "for", selector: { duration: {} } },
] as const ] as const satisfies HaFormSchema[]
); );
public shouldUpdate(changedProperties: PropertyValues) { public shouldUpdate(changedProperties: PropertyValues) {
@ -204,11 +213,7 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
if (!data.attribute && data.from === null) { if (!data.attribute && data.from === null) {
data.from = ANY_STATE_VALUE; data.from = ANY_STATE_VALUE;
} }
const schema = this._schema( const schema = this._schema(this.hass.localize, this.trigger.attribute);
this.hass.localize,
this.trigger.entity_id,
this.trigger.attribute
);
return html` return html`
<ha-form <ha-form