Add label selector (#111029)

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Franck Nijhof 2024-03-26 20:31:06 +01:00 committed by GitHub
parent dce3bde0ab
commit 9a32d1bbd5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 48 additions and 0 deletions

View File

@ -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."""

View File

@ -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)