diff --git a/homeassistant/helpers/selector.py b/homeassistant/helpers/selector.py index 0a893aa87c2..938cc6a9246 100644 --- a/homeassistant/helpers/selector.py +++ b/homeassistant/helpers/selector.py @@ -871,6 +871,38 @@ class IconSelector(Selector[IconSelectorConfig]): return icon +class LabelSelectorConfig(TypedDict, total=False): + """Class to represent a label selector config.""" + + multiple: bool + + +@SELECTORS.register("label") +class LabelSelector(Selector[LabelSelectorConfig]): + """Selector of a single or list of labels.""" + + selector_type = "label" + + CONFIG_SCHEMA = vol.Schema( + { + vol.Optional("multiple", default=False): cv.boolean, + } + ) + + def __init__(self, config: LabelSelectorConfig | None = None) -> None: + """Instantiate a selector.""" + super().__init__(config) + + def __call__(self, data: Any) -> str | list[str]: + """Validate the passed selection.""" + if not self.config["multiple"]: + label_id: str = vol.Schema(str)(data) + return label_id + if not isinstance(data, list): + raise vol.Invalid("Value should be a list") + return [vol.Schema(str)(val) for val in data] + + class LanguageSelectorConfig(TypedDict, total=False): """Class to represent an language selector config.""" diff --git a/tests/helpers/test_selector.py b/tests/helpers/test_selector.py index d04882d6802..0dc7e570fc5 100644 --- a/tests/helpers/test_selector.py +++ b/tests/helpers/test_selector.py @@ -1142,3 +1142,19 @@ def test_trigger_selector_schema(schema, valid_selections, invalid_selections) - def test_qr_code_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test QR code selector.""" _test_selector("qr_code", schema, valid_selections, invalid_selections) + + +@pytest.mark.parametrize( + ("schema", "valid_selections", "invalid_selections"), + [ + ({}, ("abc123",), (None,)), + ( + {"multiple": True}, + ((["abc123", "def456"],)), + (None, "abc123", ["abc123", None]), + ), + ], +) +def test_label_selector_schema(schema, valid_selections, invalid_selections) -> None: + """Test label selector.""" + _test_selector("label", schema, valid_selections, invalid_selections)