Coverage for custom_components/appliance_autonotify/dashboards.py: 100%
22 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-28 12:19 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-28 12:19 +0000
1"""The dashboards a notification can open when tapped, chosen from those there are so never a URL of anyone's making"""
3from __future__ import annotations
5import re
6from typing import TYPE_CHECKING
8from .const import DEFAULT_DASHBOARD, DEFAULT_DASHBOARD_TITLE, LOVELACE_DOMAIN
9from .words import name_type
11if TYPE_CHECKING:
12 from homeassistant.core import HomeAssistant
15def dashboards(hass: HomeAssistant) -> dict[str, str]:
16 """The title of each dashboard, by the path it's found at"""
17 found: dict[str, str] = {}
18 for url_path, dashboard in getattr(hass.data.get(LOVELACE_DOMAIN), "dashboards", {}).items():
19 if url_path is None:
20 found[DEFAULT_DASHBOARD] = DEFAULT_DASHBOARD_TITLE
21 else:
22 found[url_path] = (getattr(dashboard, "config", None) or {}).get("title") or url_path
23 # those that would look the same in a list are told apart by their paths
24 titles = [title.lower() for title in found.values()]
25 found = {path: f"{title} ({path})" if titles.count(title.lower()) > 1 else title for path, title in found.items()}
26 return dict(sorted(found.items(), key=lambda item: item[1].lower()))
29def _plain(text: str) -> str:
30 """Letters and digits alone, so "Dish Washer", "dishwasher" and the path `dashboard-dish-washer` are alike"""
31 return re.sub(r"[^0-9a-z]", "", text.lower().removeprefix("dashboard-"))
34def matching_dashboard(hass: HomeAssistant, name: str, kind: str | None) -> str | None:
35 """The one dashboard named for the appliance, or failing that the one named for its type, such as "Washing
36 Machine" for a washer, by its title or its path, and None where there's none or no telling which"""
37 found = {path: title for path, title in dashboards(hass).items() if path != DEFAULT_DASHBOARD}
38 tiers = [
39 [path for path, title in found.items() if _plain(name) in (_plain(title), _plain(path))],
40 [
41 path
42 for path, title in found.items()
43 if kind is not None and kind in (name_type(hass, title), name_type(hass, path.replace("-", " ")))
44 ],
45 ]
46 return next((matches[0] for matches in tiers if len(matches) == 1), None)
49def dashboard_url(hass: HomeAssistant, path: str | None) -> str | None:
50 """Where to send a tap, only ever to a dashboard that exists"""
51 return f"/{path}" if path and path in dashboards(hass) else None