Allow selecting multiple states in state condition (#27453)

* Allow selecting multiple states in state condition

* Make use of the ensureArray function
This commit is contained in:
Niklas Wagner 2025-10-19 14:23:22 +02:00 committed by GitHub
parent 8a42d15bde
commit 4e958302b4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -10,8 +10,10 @@ import {
optional,
string,
union,
array,
} from "superstruct";
import { createDurationData } from "../../../../../common/datetime/create_duration_data";
import { ensureArray } from "../../../../../common/array/ensure-array";
import { fireEvent } from "../../../../../common/dom/fire_event";
import "../../../../../components/ha-form/ha-form";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
@ -25,7 +27,7 @@ const stateConditionStruct = object({
condition: literal("state"),
entity_id: optional(string()),
attribute: optional(string()),
state: optional(string()),
state: optional(union([string(), array(string())])),
for: optional(union([number(), string(), forDictStruct])),
enabled: optional(boolean()),
});
@ -69,7 +71,7 @@ const SCHEMA = [
name: "state",
required: true,
selector: {
state: {},
state: { multiple: true },
},
context: {
filter_entity: "entity_id",
@ -88,7 +90,7 @@ export class HaStateCondition extends LitElement implements ConditionElement {
@property({ type: Boolean }) public disabled = false;
public static get defaultConfig(): StateCondition {
return { condition: "state", entity_id: "", state: "" };
return { condition: "state", entity_id: "", state: [] };
}
public shouldUpdate(changedProperties: PropertyValues) {
@ -105,7 +107,11 @@ export class HaStateCondition extends LitElement implements ConditionElement {
protected render() {
const trgFor = createDurationData(this.condition.for);
const data = { ...this.condition, for: trgFor };
const data = {
...this.condition,
state: ensureArray(this.condition.state) || [],
for: trgFor,
};
return html`
<ha-form
@ -129,10 +135,9 @@ export class HaStateCondition extends LitElement implements ConditionElement {
: {}
);
// We should not cleanup state in the above, as it is required.
// Set it to empty string if it is undefined.
if (!newCondition.state) {
newCondition.state = "";
// Ensure `state` stays an array for multi-select. If absent, set to []
if (newCondition.state === undefined || newCondition.state === "") {
newCondition.state = [];
}
fireEvent(this, "value-changed", { value: newCondition });