mirror of
https://github.com/home-assistant/frontend.git
synced 2026-10-21 13:13:39 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5ad2e0cac | ||
|
|
2b0603c431 | ||
|
|
c608ceee21 | ||
|
|
fb9e9ed01d | ||
|
|
fc8a8702b9 | ||
|
|
caa15c26d5 |
No files matched your search
@@ -0,0 +1,89 @@
|
||||
---
|
||||
name: ha-frontend-query-params
|
||||
description: Home Assistant frontend URL query param patterns. Use when keeping page state such as filters, search, sorting or grouping in the URL, adding or reading typed query params, using QueryParamsController or the data table's sync-url and column urlName, building in-app links with a query string, or adding params to My Home Assistant redirects.
|
||||
---
|
||||
|
||||
# HA Frontend Query Params
|
||||
|
||||
Use this skill when implementing or reviewing state kept in the URL's query string, or links that set it. Cross-load `ha-frontend-lit` for the controller and lifecycle work, `ha-frontend-testing` for running tests, and `ha-frontend-review` when reviewing.
|
||||
|
||||
## Typed Params
|
||||
|
||||
`src/common/url/query-params.ts` turns a typed config into values and back:
|
||||
|
||||
- `QueryParamConfig` lists keys by type: `string`, `list` (one comma-separated param, `?label=a,b`), `date` (ISO string) and `boolean` (`{ key, trueValue }`, true only when the param equals `trueValue`).
|
||||
- `QueryParamValues<typeof config>` is the matching partial values type.
|
||||
- `decodeQueryParams(source, config)` reads a `SearchParamsSource` (a `URLSearchParams`, a plain record or a query string). Empty values are skipped.
|
||||
- `createQueryString(values, config)` writes the values, leaving out empty strings, empty lists and false booleans.
|
||||
- `updateQueryString(current, values, config)` replaces only the config's params in an existing query string and keeps every other param exactly as written.
|
||||
- `hasQueryParams(source, config)` tells whether a URL has any of the config's params, which is how a page knows whether a link asked for anything.
|
||||
- `serviceTargetFromQueryParams` and `queryParamsFromServiceTarget` map `HassServiceTarget` keys to list params.
|
||||
|
||||
Give each feature its own `*-query-params.ts` in `src/common/url/` holding its config (`as const satisfies QueryParamConfig`), its values type, and the helpers that turn params into page state and back. Follow the existing ones: `data-table-query-params.ts`, `marketplace-query-params.ts`, `history-logbook-query-params.ts` and `todo-query-params.ts`. Helpers in `src/data/` that build outside links use a local config the same way, as `src/data/integration.ts` and `src/data/system_log_report.ts` do. In new code, prefer these over hand-built `URLSearchParams`, string concatenation or `extractSearchParam` reads from `src/common/url/search-params.ts`.
|
||||
|
||||
## QueryParamsController
|
||||
|
||||
`src/common/controllers/query-params-controller.ts` keeps part of a page's state in the URL. Construct it with the host, the feature's config and options:
|
||||
|
||||
- `enabled()`: whether the host syncs right now. It can change, as on the Marketplace dashboard, which turns it off on the Discover tab.
|
||||
- `navigated()`: called when the page's URL changes while the host is connected (`location-changed` or `popstate`), and when the host reconnects after its first update. Read the URL with `searchParams()`, apply it, then `write()` the state back.
|
||||
|
||||
Methods:
|
||||
|
||||
- `searchParams()` returns the current params, or `undefined` when the controller is disabled or the URL is on another path.
|
||||
- `write(values, debounced?)` updates only the config's params with `replaceCurrentUrl`, so it replaces the current history entry. Pass `debounced` for values that change while typing; the write lands 300 ms after the last one and any later write replaces it.
|
||||
- `flush()` writes a pending debounced write now. The data table calls it when the search box loses focus. Call it before anything that adds its own history entry, such as a dialog.
|
||||
|
||||
The controller binds to `currentPath()` when the host connects and does nothing while the URL is on another path. Navigating away drops a pending write. When a page is reached through a router `defaultPage` (such as `/marketplace` landing on `/marketplace/browse`), check that a link to the bare path still syncs, since the redirect may land after the host connects.
|
||||
|
||||
Read the URL yourself on the first render, after the initial state is set (in `willUpdate` before `hasUpdated`, or `firstUpdated`), and leave later navigations to `navigated()`. `ha-marketplace-dashboard.ts` and `lorawan-devices.ts` show both. When moving a page to the controller, remove its own `location-changed` and `popstate` listeners and any search kept in history state, since the controller replaces them.
|
||||
|
||||
When a router reuses one element for different items, such as one app's tab after another's, key it on the item so the controller binds again to the new path.
|
||||
|
||||
## URL Rules
|
||||
|
||||
- Writes replace the current history entry, so Back leaves the page instead of undoing each change. Push a new entry only for a deliberate navigation, such as picking another log provider.
|
||||
- Debounce search writes. Write sort, group and filter changes straight away.
|
||||
- Leave empty and default values out of the URL, such as an empty search or ascending direction.
|
||||
- A param in the URL wins over stored preferences. A link with none of the page's params keeps what the user picked before; `hasQueryParams` makes that check.
|
||||
- A link with any of the page's params replaces the search and every filter, since a filter left over from before would hide part of what the link shows. Store what the link applied as the user's choice.
|
||||
- The URL is the whole state. Don't add filters while applying a link; a link that needs one, such as showing disabled devices, says so in its params (`status=disabled`).
|
||||
- A link to a page that is already open must apply the new URL. Handle `navigated()`, not only the first render. The router often keeps a page alive, so this is the common case, not an edge case.
|
||||
- Use one comma-separated param for several values (`?status=new,installed`), which `list` params do.
|
||||
- Use the names other pages already use for the same thing: `search`, `sort`, `direction` and `group` for the table, and `floor`, `area`, `device`, `label`, `config_entry`, `sub_entry` and `assistants` for the shared filters.
|
||||
- Keep existing param names so existing links and My Home Assistant links keep working. When renaming, read the old name as well for about six months, with a code comment naming the release it can be removed in, and write only the new name. Keep the old name in the config, use it only as a fallback when reading, and leave it out of the values you write, so the next write removes it from the URL.
|
||||
- Pages opt in. Some use params for other things, such as `?domain=` starting the add integration flow on the integrations dashboard, so check what a page already reads before syncing it.
|
||||
- Collapsed groups, column order and hidden columns stay in storage (`@storage`), not the URL.
|
||||
- Link to a page by its main path, not an alias, so a link to an open page lands on the same path and applies.
|
||||
|
||||
## Data Tables
|
||||
|
||||
`hass-tabs-subpage-data-table` with the `sync-url` attribute keeps `search`, `sort`, `direction` and `group` in the URL through `dataTableQueryParamsFromState` and `dataTableQueryStateFromUrl`. A linked search replaces the current one, and sorting or grouping a link leaves out keeps what was picked before. The table fires `search-changed`, `sorting-changed` and `grouping-changed` when a link changes them, so the page can keep its stored values in step.
|
||||
|
||||
- Give sortable and groupable columns a short public `urlName` (for example `type`, not `translated_category`). Sorting falls back to the column id without one; grouping is only written for columns that have one, so internal ids don't end up in links.
|
||||
- When a column definition is shared between pages, set its `urlName` where the shared column is defined, so every page uses the same name.
|
||||
- The table reads the URL once, as soon as it has columns. When a column only exists once data has loaded, such as Filename on the dashboards page, turn syncing on only after loading succeeds (`?sync-url=${!this._loading && !this._loadFailed}`), or a link that sorts or groups by that column is dropped.
|
||||
- The page owns its filters. Give it a filter config in its `*-query-params.ts`, a helper that turns filter values into params, and one that turns a link back into the search and filter values. The link helper returns `undefined` when the URL has none of the filter params and none of the table's (`dataTableQueryParamConfig`), so stored choices stay. Use a second controller on the page for them, as `ha-marketplace-dashboard.ts` and `lorawan-devices.ts` do. `browseUrl` and `browseLinkFromUrl` in `src/panels/marketplace/dashboards/dashboard-repositories.ts` show the pair.
|
||||
- A memoized filter that also reads async state (anything loaded after the page connects) must take that state as a memoize argument, or a linked filter shows stale results until something else changes.
|
||||
- A filter component that looks up related items asynchronously should drop a lookup whose value has since changed, or two links landing within one lookup apply the older one.
|
||||
|
||||
## Coverage Check
|
||||
|
||||
Before calling a page done:
|
||||
|
||||
1. List every filter, sortable column, groupable column, the search box and any view toggle (such as a tab, raw view or provider). Confirm each one is written to the URL and read back from a link, both on first render and on a page that is already open.
|
||||
2. Search the codebase for in-app links and `navigate()` calls into the page with a query string, and move them to the current param names and the page's main path. `lorawan-connections.ts` and `lorawan-overview.ts` link into `lorawan-devices.ts` this way.
|
||||
|
||||
## My Home Assistant Links
|
||||
|
||||
When a page gains params, add them to its redirect in `getMyRedirects()` in `src/panels/my/ha-panel-my.ts`:
|
||||
|
||||
- List them under `params` as `"string?"`, matching what the page reads. For a data table page that includes `search`, `sort`, `direction` and `group` as well as its filters. Keep the list in a const next to the others, such as `marketplaceTableParams`, which several redirects share.
|
||||
- Point the redirect at the page's main path, the one the page's controller binds to.
|
||||
- Don't add legacy param names.
|
||||
- Add the same params to the redirect's entry in `redirect.json` in `home-assistant/my.home-assistant.io`, in a separate pull request that links the frontend pull request. Merge it only once the frontend pull request is in `dev`.
|
||||
- In the frontend pull request, link the My Home Assistant pull request under "Additional information": `- Link to My Home Assistant pull request: home-assistant/my.home-assistant.io#<n>`.
|
||||
|
||||
## Tests
|
||||
|
||||
Follow `test/common/url/query-params.test.ts`, `test/common/url/data-table-query-params.test.ts` and `test/common/controllers/query-params-controller.test.ts`. For a feature's params file, cover the encode and decode round trip, defaults being left out, and legacy names still being read. Test the helpers, not the page rendering, and only where the logic could break without anyone noticing.
|
||||
@@ -46,6 +46,7 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
|
||||
- `ha-frontend-lit`: reactive fields, DOM queries, lifecycle behavior, and render-derived state.
|
||||
- `ha-frontend-styling`: theme variables, spacing tokens, responsive layout, RTL, and view transitions.
|
||||
- `ha-frontend-testing`: lint, typecheck, Vitest, Playwright e2e dev servers, and benchmarks.
|
||||
- `ha-frontend-query-params`: typed URL query params, `QueryParamsController`, data table URL sync, in-app links, and My Home Assistant redirect params.
|
||||
- `ha-frontend-user-facing-text`: localization, terminology, sentence case, and Home Assistant text style.
|
||||
- `ha-frontend-review`: PR template use, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
|
||||
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Add a value to a most recently used list. The value goes first, also when it
|
||||
* was already in the list, and the list is capped at `max`.
|
||||
* Entries rejected by `isValid` are dropped first, so they don't take up slots.
|
||||
*/
|
||||
export const addRecent = <T>(
|
||||
list: readonly T[] | undefined,
|
||||
value: T,
|
||||
max: number,
|
||||
isValid?: (item: T) => boolean
|
||||
): T[] => {
|
||||
const current = Array.isArray(list)
|
||||
? list.filter((item) => item !== value && (!isValid || isValid(item)))
|
||||
: [];
|
||||
return [value, ...current].slice(0, max);
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
import type {
|
||||
DataTableFiltersValue,
|
||||
DataTableFiltersValues,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
decodeQueryParams,
|
||||
hasQueryParams,
|
||||
type QueryParamConfig,
|
||||
type QueryParamValues,
|
||||
type SearchParamsSource,
|
||||
} from "./query-params";
|
||||
|
||||
// The filter-pane keys of the backups table's filters
|
||||
export const BACKUP_TYPE_FILTER = "ha-filter-states";
|
||||
export const BACKUP_LOCATIONS_FILTER = "backup-locations";
|
||||
|
||||
// The filters of the backups table. Search, sorting and grouping are kept by
|
||||
// the data table, see data-table-query-params.
|
||||
export const backupsFilterQueryParamConfig = {
|
||||
list: ["type", "location"],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type BackupsFilterQueryParams = QueryParamValues<
|
||||
typeof backupsFilterQueryParamConfig
|
||||
>;
|
||||
|
||||
const list = (value: DataTableFiltersValue): string[] | undefined =>
|
||||
Array.isArray(value) ? value : undefined;
|
||||
|
||||
export const backupsFilterQueryParams = (
|
||||
filters: DataTableFiltersValues
|
||||
): BackupsFilterQueryParams => ({
|
||||
type: list(filters[BACKUP_TYPE_FILTER]),
|
||||
location: list(filters[BACKUP_LOCATIONS_FILTER]),
|
||||
});
|
||||
|
||||
// What a link says to show, undefined when it has no table params so what was
|
||||
// picked before stays. A link replaces the search and the filters, ones left
|
||||
// behind would hide part of what it shows. The table applies its sorting and
|
||||
// grouping.
|
||||
export interface BackupsLink {
|
||||
search: string;
|
||||
filters: DataTableFiltersValues;
|
||||
}
|
||||
|
||||
export const backupsLinkFromUrl = (
|
||||
searchParams: SearchParamsSource
|
||||
): BackupsLink | undefined => {
|
||||
if (
|
||||
!hasQueryParams(searchParams, backupsFilterQueryParamConfig) &&
|
||||
!hasQueryParams(searchParams, dataTableQueryParamConfig)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const params = decodeQueryParams(searchParams, backupsFilterQueryParamConfig);
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
return {
|
||||
search: search ?? "",
|
||||
filters: {
|
||||
// `type=all` asks for every type, as the backups overview links do
|
||||
[BACKUP_TYPE_FILTER]:
|
||||
params.type?.filter((type) => type && type !== "all") ?? [],
|
||||
[BACKUP_LOCATIONS_FILTER]: params.location?.filter(Boolean) ?? [],
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -245,6 +245,10 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
|
||||
protected firstUpdated() {
|
||||
this._registerKeyboardShortcuts();
|
||||
// The virtualized list pins the selected row itself.
|
||||
if (this._plainList) {
|
||||
this._scrollToSelectedRow();
|
||||
}
|
||||
}
|
||||
|
||||
public willUpdate() {
|
||||
@@ -265,6 +269,28 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll before the surface animates in, so the list does not jump at the
|
||||
// end of the animation. Wait a frame for the surface to be positioned.
|
||||
private async _scrollToSelectedRow() {
|
||||
await this._list?.updateComplete;
|
||||
await new Promise(requestAnimationFrame);
|
||||
if (!this._list || !this.value || this._search) {
|
||||
return;
|
||||
}
|
||||
const row = this._list.items[this._getInitialSelectedIndex()];
|
||||
const listRect = this._list.getBoundingClientRect();
|
||||
if (!row || !listRect.height) {
|
||||
return;
|
||||
}
|
||||
// The surface scales in, so convert the measured offset to unscaled pixels.
|
||||
const scale = this._list.offsetHeight / listRect.height;
|
||||
const rowRect = row.getBoundingClientRect();
|
||||
// Center the row, like the virtualized list does.
|
||||
this._list.scrollTop +=
|
||||
(rowRect.top - listRect.top) * scale -
|
||||
(this._list.clientHeight - row.offsetHeight) / 2;
|
||||
}
|
||||
|
||||
// The list resets its active row when it takes new rows, so wait for that
|
||||
// first. Skip if the search was cleared or a key already moved the cursor.
|
||||
private async _highlightTopMatch() {
|
||||
|
||||
@@ -66,6 +66,28 @@ type EventTimeFormatter = Extract<
|
||||
(...args: any[]) => string
|
||||
>;
|
||||
|
||||
// FullCalendar sorts events by these fields, with times in calendar time
|
||||
interface EventSortFields {
|
||||
allDay: number;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
// FullCalendar draws a timed event within one day as a dot
|
||||
const isDotEvent = ({ allDay, start, end }: EventSortFields) =>
|
||||
!allDay &&
|
||||
Math.floor(start / DAY_MS) === Math.floor(Math.max(start, end - 1) / DAY_MS);
|
||||
|
||||
const defaultEventOrder = "start,-duration,allDay,title";
|
||||
|
||||
const narrowMonthEventOrder = [
|
||||
(a: EventSortFields, b: EventSortFields) =>
|
||||
Number(isDotEvent(a)) - Number(isDotEvent(b)),
|
||||
...defaultEventOrder.split(","),
|
||||
] as CalendarOptions["eventOrder"];
|
||||
|
||||
const weekTitleFormat: CalendarOptions["titleFormat"] = {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
@@ -86,6 +108,7 @@ const defaultFullCalendarConfig: CalendarOptions = {
|
||||
dayCellTopClass: "ha-fc-day-top",
|
||||
dayCellTopInnerClass: ({ isToday }) =>
|
||||
joinClassNames("ha-fc-day-number", isToday && "ha-fc-day-number-today"),
|
||||
dayCellInnerClass: "ha-fc-day-events",
|
||||
eventClass: "ha-fc-event",
|
||||
rowEventClass: "ha-fc-row-event",
|
||||
rowEventInnerClass: "ha-fc-row-event-inner",
|
||||
@@ -354,6 +377,15 @@ export class HAFullCalendar extends LitElement {
|
||||
this.calendar!.setOption("eventDisplay", this.eventDisplay);
|
||||
}
|
||||
|
||||
const eventOrder = this._eventOrderOptions(this._activeView!);
|
||||
if (
|
||||
this.calendar.getOption("eventOrderStrict") !==
|
||||
eventOrder.eventOrderStrict
|
||||
) {
|
||||
this.calendar.setOption("eventOrder", eventOrder.eventOrder);
|
||||
this.calendar.setOption("eventOrderStrict", eventOrder.eventOrderStrict);
|
||||
}
|
||||
|
||||
if (changedProps.has("autoHeight")) {
|
||||
this.calendar.setOption("height", this._height);
|
||||
this.calendar.setOption("dayMaxEventRows", !this.autoHeight);
|
||||
@@ -386,6 +418,7 @@ export class HAFullCalendar extends LitElement {
|
||||
dayMaxEventRows: !this.autoHeight,
|
||||
eventDisplay: this.eventDisplay,
|
||||
eventTimeFormat: this._formatEventTime,
|
||||
...this._eventOrderOptions(initialView),
|
||||
};
|
||||
|
||||
config.dateClick = (info) => this._handleDateClick(info);
|
||||
@@ -403,6 +436,16 @@ export class HAFullCalendar extends LitElement {
|
||||
return this.autoHeight ? "auto" : defaultFullCalendarConfig.height;
|
||||
}
|
||||
|
||||
// Narrow month dots wrap below the bars, so every bar is placed before them
|
||||
// and no event fills a gap above an earlier one
|
||||
private _eventOrderOptions(view: FullCalendarView) {
|
||||
const narrowMonth = this.narrow && view === "dayGridMonth";
|
||||
return {
|
||||
eventOrder: narrowMonth ? narrowMonthEventOrder : defaultEventOrder,
|
||||
eventOrderStrict: narrowMonth,
|
||||
};
|
||||
}
|
||||
|
||||
// Return if there are calendars that support creating events
|
||||
private get _hasMutableCalendars(): boolean {
|
||||
return this.calendars.some((selCal) => {
|
||||
@@ -891,6 +934,78 @@ export class HAFullCalendar extends LitElement {
|
||||
:host([narrow]) .ha-fc-dayGridMonth .ha-fc-dot-event-text {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:host([narrow]) .ha-fc-dayGridMonth .ha-fc-more-link {
|
||||
justify-content: center;
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
/* Dots sit 4 to a 12px line. FullCalendar stacks each dot 3px below
|
||||
the one before it, so a line takes the height it reserves for 4
|
||||
dots, and a margin lifts each dot back up to the start of its line.
|
||||
Without these selectors the dots stay stacked. Print lays events
|
||||
out in normal flow, so this is for screens only. */
|
||||
@media screen {
|
||||
@supports selector(:nth-child(1 of :has(*))) {
|
||||
:host([narrow]) .ha-fc-dayGridMonth .ha-fc-day-events {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
align-content: flex-start;
|
||||
}
|
||||
|
||||
:host([narrow])
|
||||
.ha-fc-dayGridMonth
|
||||
.ha-fc-day-events
|
||||
> :has(> .ha-fc-dot-event) {
|
||||
height: 3px;
|
||||
}
|
||||
|
||||
/* FullCalendar hides a dot it has not placed or that does not fit */
|
||||
:host([narrow])
|
||||
.ha-fc-dayGridMonth
|
||||
.ha-fc-day-events
|
||||
> :has(> .ha-fc-dot-event):not([style*="hidden"]) {
|
||||
position: relative !important;
|
||||
width: 25% !important;
|
||||
margin-top: calc(var(--dot-column, 0) * -3px);
|
||||
margin-bottom: -3px;
|
||||
}
|
||||
|
||||
:host([narrow])
|
||||
.ha-fc-dayGridMonth
|
||||
.ha-fc-day-events
|
||||
> :nth-child(4n + 2 of :has(> .ha-fc-dot-event)) {
|
||||
--dot-column: 1;
|
||||
}
|
||||
|
||||
:host([narrow])
|
||||
.ha-fc-dayGridMonth
|
||||
.ha-fc-day-events
|
||||
> :nth-child(4n + 3 of :has(> .ha-fc-dot-event)) {
|
||||
--dot-column: 2;
|
||||
}
|
||||
|
||||
:host([narrow])
|
||||
.ha-fc-dayGridMonth
|
||||
.ha-fc-day-events
|
||||
> :nth-child(4n of :has(> .ha-fc-dot-event)) {
|
||||
--dot-column: 3;
|
||||
}
|
||||
|
||||
/* A last line that is not full still needs the room of 3 dots */
|
||||
:host([narrow])
|
||||
.ha-fc-dayGridMonth
|
||||
.ha-fc-day-events
|
||||
> :nth-last-child(1 of :has(> .ha-fc-dot-event)) {
|
||||
height: 9px;
|
||||
}
|
||||
|
||||
:host([narrow]) .ha-fc-dayGridMonth .ha-fc-more-link {
|
||||
padding-top: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -7,9 +7,14 @@ import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { addRecent } from "../../../common/array/add-recent";
|
||||
import { ensureArray } from "../../../common/array/ensure-array";
|
||||
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { storage } from "../../../common/decorators/storage";
|
||||
import type {
|
||||
HASSDomCurrentTargetEvent,
|
||||
HASSDomTargetEvent,
|
||||
} from "../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { mainWindow } from "../../../common/dom/get_main_window";
|
||||
import { computeAreaName } from "../../../common/entity/compute_area_name";
|
||||
@@ -123,6 +128,11 @@ import "./add-automation-element/ha-automation-add-element-paste";
|
||||
import "./add-automation-element/ha-automation-add-from-target";
|
||||
import "./add-automation-element/ha-automation-add-items";
|
||||
import "./add-automation-element/ha-automation-add-search";
|
||||
import {
|
||||
addRecentTarget,
|
||||
RECENT_TARGETS_STORAGE_KEY,
|
||||
} from "./target/recent_targets";
|
||||
import { findElementGroupKey } from "./add-automation-element/element-group";
|
||||
import type { AddAutomationElementDialogParams } from "./show-add-automation-element-dialog";
|
||||
import {
|
||||
ADD_AUTOMATION_ELEMENT_AREA_TARGET_PARAM,
|
||||
@@ -184,6 +194,8 @@ const DYNAMIC_KEYWORDS = ["dynamicGroups", "helpers", "integrationGroups"];
|
||||
|
||||
const DYNAMIC_TO_GENERIC = new Set([`${DYNAMIC_PREFIX}event`]);
|
||||
|
||||
const MAX_RECENT_ELEMENTS = 4;
|
||||
|
||||
// Group keys surfaced in the "Other" section of the "by target" tab because
|
||||
// their elements have no target (time/calendar/schedule, sun). Picking one
|
||||
// drills into its items, like selecting the matching group in the "by type" tab.
|
||||
@@ -246,6 +258,14 @@ class DialogAddAutomationElement
|
||||
|
||||
@state() private _openedFromQuery = false;
|
||||
|
||||
@storage({ key: RECENT_TARGETS_STORAGE_KEY, state: true, subscribe: false })
|
||||
private _recentTargets?: string[];
|
||||
|
||||
@storage({ key: "automation-recent-elements", state: true, subscribe: false })
|
||||
private _recentElements?: Partial<
|
||||
Record<AddAutomationElementDialogParams["type"], string[]>
|
||||
>;
|
||||
|
||||
@state()
|
||||
@consume({ context: labelsContext, subscribe: true })
|
||||
private _labelRegistry!: LabelRegistryEntry[];
|
||||
@@ -625,6 +645,15 @@ class DialogAddAutomationElement
|
||||
this._manifests
|
||||
);
|
||||
|
||||
const recentElements = hideCollections
|
||||
? []
|
||||
: this._getRecentElements(
|
||||
automationElementType,
|
||||
this._recentElements?.[automationElementType],
|
||||
this._currentItems(),
|
||||
collections
|
||||
);
|
||||
|
||||
return html`
|
||||
<div slot="header">
|
||||
${this._renderHeader()}
|
||||
@@ -711,6 +740,8 @@ class DialogAddAutomationElement
|
||||
: this._triggerDescriptions
|
||||
)}
|
||||
.selectedGroup=${this._selectedGroup}
|
||||
.recentTargets=${this._recentTargets}
|
||||
@clear-recent-targets=${this._clearRecentTargets}
|
||||
class=${classMap({
|
||||
"ha-scrollbar": true,
|
||||
hidden:
|
||||
@@ -739,12 +770,46 @@ class DialogAddAutomationElement
|
||||
@paste-element=${this._paste}
|
||||
divider
|
||||
></ha-automation-add-element-paste>
|
||||
${
|
||||
recentElements.length
|
||||
? html`<ha-section-title>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.automation.editor.recently_used"
|
||||
)}
|
||||
<ha-button
|
||||
class="clear-recent"
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.panel.config.automation.editor.clear_recently_used"
|
||||
)}
|
||||
appearance="plain"
|
||||
variant="neutral"
|
||||
size="s"
|
||||
@click=${this._clearRecentElements}
|
||||
>
|
||||
${this.hass.localize("ui.common.clear")}
|
||||
</ha-button>
|
||||
</ha-section-title>
|
||||
${repeat(
|
||||
recentElements,
|
||||
({ item }) => `recent-${item.key}`,
|
||||
({ item, groupName }) =>
|
||||
this._renderRecentButton(item, groupName)
|
||||
)}`
|
||||
: nothing
|
||||
}
|
||||
${collections.map(
|
||||
(collection) => html`
|
||||
${
|
||||
collection.titleKey && collection.groups.length
|
||||
collection.groups.length > 0 &&
|
||||
(!!collection.titleKey || recentElements.length > 0)
|
||||
? html`<ha-section-title>
|
||||
${this.hass.localize(collection.titleKey)}
|
||||
${
|
||||
collection.titleKey
|
||||
? this.hass.localize(collection.titleKey)
|
||||
: this.hass.localize(
|
||||
`ui.panel.config.automation.editor.${automationElementType}s.name`
|
||||
)
|
||||
}
|
||||
</ha-section-title>`
|
||||
: nothing
|
||||
}
|
||||
@@ -1910,6 +1975,125 @@ class DialogAddAutomationElement
|
||||
this.closeDialog();
|
||||
}
|
||||
|
||||
private _renderRecentButton(
|
||||
item: AddAutomationElementListItem,
|
||||
groupName?: string
|
||||
) {
|
||||
return html`
|
||||
<ha-list-item-button .value=${item.key} @click=${this._recentSelected}>
|
||||
<div slot="headline">${item.name}</div>
|
||||
${
|
||||
item.icon
|
||||
? html`<span slot="start">${item.icon}</span>`
|
||||
: item.iconPath
|
||||
? html`<ha-svg-icon
|
||||
slot="start"
|
||||
.path=${item.iconPath}
|
||||
></ha-svg-icon>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
groupName
|
||||
? html`<span slot="end" class="recent-group">${groupName}</span>`
|
||||
: nothing
|
||||
}
|
||||
</ha-list-item-button>
|
||||
`;
|
||||
}
|
||||
|
||||
private _recentSelected = (
|
||||
ev: HASSDomCurrentTargetEvent<HTMLElement & { value: string }>
|
||||
) => {
|
||||
const key = ev.currentTarget.value;
|
||||
this._rememberSelection(key);
|
||||
this._params!.add(key);
|
||||
this.closeDialog();
|
||||
};
|
||||
|
||||
private _currentItems() {
|
||||
return this._items(
|
||||
this._params!.type,
|
||||
this.hass.localize,
|
||||
this.hass.services,
|
||||
this._triggerDescriptions,
|
||||
this._conditionDescriptions,
|
||||
this._manifests
|
||||
);
|
||||
}
|
||||
|
||||
private _getRecentElements = memoizeOne(
|
||||
(
|
||||
type: AddAutomationElementDialogParams["type"],
|
||||
recents: string[] | undefined,
|
||||
items: AddAutomationElementListItem[],
|
||||
collections: CollectionGroup[]
|
||||
) => {
|
||||
if (!Array.isArray(recents)) {
|
||||
return [];
|
||||
}
|
||||
return recents
|
||||
.map((key) => items.find((item) => item.key === key))
|
||||
.filter((item) => item !== undefined)
|
||||
.slice(0, MAX_RECENT_ELEMENTS)
|
||||
.map((item) => ({
|
||||
item,
|
||||
groupName: this._elementGroup(type, item.key, collections)?.name,
|
||||
}));
|
||||
}
|
||||
);
|
||||
|
||||
private _elementGroup(
|
||||
type: AddAutomationElementDialogParams["type"],
|
||||
key: string,
|
||||
collections: CollectionGroup[]
|
||||
) {
|
||||
const groupKey = findElementGroupKey(type, TYPES[type].collections, key);
|
||||
// Elements that are a row of their own resolve to a group that isn't rendered
|
||||
return collections
|
||||
.flatMap((collection) => collection.groups)
|
||||
.find((group) => group.key === groupKey);
|
||||
}
|
||||
|
||||
private _clearRecentElements = () => {
|
||||
this._recentElements = {
|
||||
...this._recentElements,
|
||||
[this._params!.type]: [],
|
||||
};
|
||||
};
|
||||
|
||||
private _clearRecentTargets = () => {
|
||||
this._recentTargets = [];
|
||||
};
|
||||
|
||||
// Existence is only checked when showing recents, data that is still
|
||||
// loading must not remove valid ones
|
||||
private _rememberSelection(key: string, target?: SingleHassServiceTarget) {
|
||||
const type = this._params!.type;
|
||||
|
||||
// Building blocks are rarely reused
|
||||
const blocks =
|
||||
type === "action"
|
||||
? ACTION_BUILDING_BLOCKS_GROUP
|
||||
: type === "condition"
|
||||
? CONDITION_BUILDING_BLOCKS_GROUP
|
||||
: {};
|
||||
if (!(key in blocks)) {
|
||||
this._recentElements = {
|
||||
...this._recentElements,
|
||||
[type]: addRecent(
|
||||
this._recentElements?.[type],
|
||||
key,
|
||||
MAX_RECENT_ELEMENTS,
|
||||
(item) => typeof item === "string"
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (target) {
|
||||
this._recentTargets = addRecentTarget(this._recentTargets, target);
|
||||
}
|
||||
}
|
||||
|
||||
private _selected(ev: ValueChangedEvent<string>) {
|
||||
let target: HassServiceTarget | undefined;
|
||||
if (
|
||||
@@ -1919,6 +2103,10 @@ class DialogAddAutomationElement
|
||||
) {
|
||||
target = this._selectedTarget;
|
||||
}
|
||||
this._rememberSelection(
|
||||
ev.detail.value,
|
||||
target ? this._selectedTarget : undefined
|
||||
);
|
||||
this._params!.add(ev.detail.value, target);
|
||||
this.closeDialog();
|
||||
}
|
||||
@@ -2160,6 +2348,7 @@ class DialogAddAutomationElement
|
||||
(item as AutomationItemComboBoxItem).type &&
|
||||
!["floor", "area"].includes((item as AutomationItemComboBoxItem).type)
|
||||
) {
|
||||
this._rememberSelection(item.id);
|
||||
this._params!.add(item.id);
|
||||
this.closeDialog();
|
||||
return;
|
||||
@@ -2436,6 +2625,19 @@ class DialogAddAutomationElement
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
ha-button.clear-recent {
|
||||
margin-inline-start: auto;
|
||||
margin-inline-end: calc(-1 * var(--ha-space-2));
|
||||
--ha-button-height: var(--ha-space-6);
|
||||
--wa-form-control-padding-inline: var(--ha-space-2);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
|
||||
.recent-group {
|
||||
color: var(--ha-color-on-neutral-quiet);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
|
||||
ha-automation-add-items {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { computeDomain } from "../../../../common/entity/compute_domain";
|
||||
import type { AutomationElementGroupCollection } from "../../../../data/automation";
|
||||
import {
|
||||
DYNAMIC_PREFIX,
|
||||
getValueFromDynamic,
|
||||
isDynamic,
|
||||
} from "../../../../data/automation";
|
||||
import { getConditionDomain } from "../../../../data/condition";
|
||||
import { getTriggerDomain } from "../../../../data/trigger";
|
||||
|
||||
/**
|
||||
* Find the key of the group an element belongs to, independent of how it was
|
||||
* reached (category, target or search). The group may not be rendered, for
|
||||
* example when the integration behind it is not set up.
|
||||
*/
|
||||
export const findElementGroupKey = (
|
||||
type: "trigger" | "condition" | "action",
|
||||
collections: AutomationElementGroupCollection[],
|
||||
key: string
|
||||
): string => {
|
||||
const value = isDynamic(key) ? getValueFromDynamic(key) : key;
|
||||
|
||||
const domain =
|
||||
type === "trigger"
|
||||
? getTriggerDomain(value)
|
||||
: type === "condition"
|
||||
? getConditionDomain(value)
|
||||
: computeDomain(value);
|
||||
|
||||
for (const collection of collections) {
|
||||
for (const [groupKey, options] of Object.entries(collection.groups)) {
|
||||
if (
|
||||
(options.members && value in options.members) ||
|
||||
options.domains?.includes(domain)
|
||||
) {
|
||||
return groupKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return `${DYNAMIC_PREFIX}${domain}`;
|
||||
};
|
||||
+187
-5
@@ -15,8 +15,10 @@ import {
|
||||
} from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { live } from "lit/directives/live";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { computeAreaName } from "../../../../common/entity/compute_area_name";
|
||||
import { computeDeviceName } from "../../../../common/entity/compute_device_name";
|
||||
@@ -24,6 +26,7 @@ import { computeDomain } from "../../../../common/entity/compute_domain";
|
||||
import { computeEntityNameParts } from "../../../../common/entity/compute_entity_name_display";
|
||||
import { getDeviceAreaId } from "../../../../common/entity/context/get_device_context";
|
||||
import { stringCompare } from "../../../../common/string/compare";
|
||||
import "../../../../components/ha-button";
|
||||
import "../../../../components/ha-floor-icon";
|
||||
import "../../../../components/ha-icon";
|
||||
import "../../../../components/ha-icon-next";
|
||||
@@ -64,11 +67,19 @@ import type { LabelRegistryEntry } from "../../../../data/label/label_registry";
|
||||
import {
|
||||
TARGET_SEPARATOR,
|
||||
type SingleHassServiceTarget,
|
||||
type TargetType,
|
||||
} from "../../../../data/target";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { HomeAssistant, HomeAssistantRegistries } from "../../../../types";
|
||||
import { brandsUrl } from "../../../../util/brands-url";
|
||||
import type { AddAutomationElementListItem } from "../add-automation-element-dialog";
|
||||
import type { AddAutomationElementDialogParams } from "../show-add-automation-element-dialog";
|
||||
import { getTargetIcon } from "../target/get_target_icon";
|
||||
import { getTargetText } from "../target/get_target_text";
|
||||
import {
|
||||
MAX_RECENT_TARGETS,
|
||||
parseRecentTarget,
|
||||
} from "../target/recent_targets";
|
||||
import { targetExists } from "../target/target_exists";
|
||||
import "./ha-automation-add-element-paste";
|
||||
|
||||
// All person entities are also listed under "People" in the "Other" section
|
||||
@@ -121,6 +132,8 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
@property({ attribute: "automation-element-type" })
|
||||
public automationElementType!: AddAutomationElementDialogParams["type"];
|
||||
|
||||
@property({ attribute: false }) public recentTargets?: string[];
|
||||
|
||||
// #endregion properties
|
||||
|
||||
// #region context
|
||||
@@ -150,6 +163,14 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
|
||||
@state() private _entries: Record<string, Level1Entries> = {};
|
||||
|
||||
// Nothing is rendered until the tree is built, as recents and preselected
|
||||
// targets open it
|
||||
@state() private _treeLoaded = false;
|
||||
|
||||
private _initialDataLoadStarted = false;
|
||||
|
||||
private _configEntriesLoaded?: Promise<void>;
|
||||
|
||||
@state() private _showShowMoreButton?: boolean;
|
||||
|
||||
@state() private _fullHeight = false;
|
||||
@@ -164,6 +185,15 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
super.willUpdate(changedProps);
|
||||
|
||||
if (!this.hasUpdated) {
|
||||
// Without config entries the tree only lacks integration icons
|
||||
this._configEntriesLoaded = this._loadConfigEntries().catch(
|
||||
() => undefined
|
||||
);
|
||||
}
|
||||
|
||||
// The tree sorts helpers by their manifest, so it waits for them
|
||||
if (!this._initialDataLoadStarted && this.manifests) {
|
||||
this._initialDataLoadStarted = true;
|
||||
this._initialDataLoad();
|
||||
}
|
||||
|
||||
@@ -185,8 +215,9 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
}
|
||||
|
||||
private async _initialDataLoad() {
|
||||
await this._loadConfigEntries();
|
||||
await this._configEntriesLoaded;
|
||||
this._getTreeData();
|
||||
this._treeLoaded = true;
|
||||
}
|
||||
|
||||
private async _setShowTargetShowMoreButton() {
|
||||
@@ -202,7 +233,7 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
|
||||
// #region render
|
||||
protected render() {
|
||||
if (!this.manifests || !this._configEntryLookup) {
|
||||
if (!this._treeLoaded) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -217,6 +248,16 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
.clipboardItem=${this.clipboardItem}
|
||||
></ha-automation-add-element-paste>
|
||||
</ha-list-base>
|
||||
${this._renderRecentTargets(
|
||||
this.narrow,
|
||||
this._getRecentTargets(
|
||||
this.recentTargets,
|
||||
this._registries,
|
||||
this.states,
|
||||
this._labelRegistry
|
||||
),
|
||||
this.value
|
||||
)}
|
||||
${this._renderFloors(this.narrow, this._entries, this.value)}
|
||||
${this._renderTimeLocation(
|
||||
this.narrow,
|
||||
@@ -336,6 +377,97 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
}
|
||||
);
|
||||
|
||||
private _getRecentTargets = memoizeOne(
|
||||
(
|
||||
recentTargets: string[] | undefined,
|
||||
registries: HomeAssistantRegistries,
|
||||
states: HomeAssistant["states"],
|
||||
labels: LabelRegistryEntry[] | undefined
|
||||
): [TargetType, string][] =>
|
||||
Array.isArray(recentTargets)
|
||||
? recentTargets
|
||||
.map(parseRecentTarget)
|
||||
.filter(
|
||||
(target): target is [TargetType, string] =>
|
||||
!!target &&
|
||||
targetExists(registries, states, labels, target[0], target[1])
|
||||
)
|
||||
.slice(0, MAX_RECENT_TARGETS)
|
||||
: []
|
||||
);
|
||||
|
||||
private _renderRecentTargets(
|
||||
narrow: boolean,
|
||||
targets: [TargetType, string][],
|
||||
value?: SingleHassServiceTarget
|
||||
) {
|
||||
if (!targets.length) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const selected = this._getSelectedTargetId(value);
|
||||
|
||||
return html`<ha-section-title>
|
||||
${this._i18n.localize("ui.panel.config.automation.editor.recently_used")}
|
||||
<ha-button
|
||||
class="clear-recent"
|
||||
aria-label=${this._i18n.localize(
|
||||
"ui.panel.config.automation.editor.clear_recently_used"
|
||||
)}
|
||||
appearance="plain"
|
||||
variant="neutral"
|
||||
size="s"
|
||||
@click=${this._clearRecentTargets}
|
||||
>
|
||||
${this._i18n.localize("ui.common.clear")}
|
||||
</ha-button>
|
||||
</ha-section-title>
|
||||
<ha-list-base>
|
||||
${targets.map(([type, id]) => {
|
||||
const target = `${type}${TARGET_SEPARATOR}${id}`;
|
||||
return html`<ha-list-item-button
|
||||
.target=${target}
|
||||
@click=${this._selectRecentTarget}
|
||||
class=${selected === target ? "recent selected" : "recent"}
|
||||
>
|
||||
<div slot="start" class="target-icon">
|
||||
${getTargetIcon(
|
||||
this._registries,
|
||||
this.states,
|
||||
type,
|
||||
id,
|
||||
this._configEntryLookup,
|
||||
this._getLabel
|
||||
)}
|
||||
</div>
|
||||
<div slot="headline">
|
||||
${getTargetText(
|
||||
this._registries,
|
||||
this.states,
|
||||
this._i18n.localize,
|
||||
type,
|
||||
id,
|
||||
this._getLabel
|
||||
)}
|
||||
</div>
|
||||
<span slot="end" class="target-type"
|
||||
>${this._i18n.localize(
|
||||
`ui.components.target-picker.type.${type}`
|
||||
)}</span
|
||||
>
|
||||
${narrow ? html`<ha-icon-next slot="end"></ha-icon-next>` : nothing}
|
||||
</ha-list-item-button>`;
|
||||
})}
|
||||
</ha-list-base>`;
|
||||
}
|
||||
|
||||
private _clearRecentTargets() {
|
||||
fireEvent(this, "clear-recent-targets");
|
||||
}
|
||||
|
||||
private _getLabel = (id: string) =>
|
||||
this._labelRegistry?.find(({ label_id }) => label_id === id);
|
||||
|
||||
private _renderFloors = memoizeOne(
|
||||
(
|
||||
narrow: boolean,
|
||||
@@ -943,7 +1075,7 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
.lazy=${lazy}
|
||||
@wa-lazy-load=${this._expandItem}
|
||||
@wa-collapse=${this._collapseItem}
|
||||
.expanded=${open}
|
||||
.expanded=${live(open)}
|
||||
.title=${label}
|
||||
>
|
||||
${icon?.()} ${label} ${children || nothing}
|
||||
@@ -1431,6 +1563,12 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _selectRecentTarget(
|
||||
ev: HASSDomCurrentTargetEvent<HTMLElement & { target: string }>
|
||||
) {
|
||||
this._valueChanged(ev.currentTarget.target, !this.narrow);
|
||||
}
|
||||
|
||||
private _selectTimeLocationGroup(ev: CustomEvent) {
|
||||
const value = (ev.currentTarget as any).value;
|
||||
if (value) {
|
||||
@@ -1448,9 +1586,19 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
if (expand && id) {
|
||||
this._expandTreeToItem(type, id);
|
||||
await this.updateComplete;
|
||||
// Nested tree items created already expanded collapse themselves again,
|
||||
// one more render lets live() open them before scrolling
|
||||
this.requestUpdate();
|
||||
await this.updateComplete;
|
||||
// Opening rows push the selection down, scroll once they are open
|
||||
await Promise.all(
|
||||
[...this.shadowRoot!.querySelectorAll("wa-tree-item[expanded]")]
|
||||
.flatMap((item) => item.shadowRoot?.getAnimations() ?? [])
|
||||
.map((animation) => animation.finished.catch(() => undefined))
|
||||
);
|
||||
if (type === "label") {
|
||||
this.shadowRoot!.querySelector(
|
||||
"ha-list-item-button.selected"
|
||||
"ha-list-item-button.selected:not(.recent)"
|
||||
)?.scrollIntoView({
|
||||
block: "center",
|
||||
});
|
||||
@@ -1647,6 +1795,39 @@ export default class HaAutomationAddFromTarget extends LitElement {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Icons vary in kind, a fixed box keeps the labels aligned */
|
||||
.target-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
width: var(--ha-space-8);
|
||||
height: var(--ha-space-8);
|
||||
}
|
||||
.target-icon > * {
|
||||
padding: 0;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.target-type {
|
||||
font-size: var(--ha-font-size-s);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
ha-list-item-button.selected::part(end) {
|
||||
color: var(--ha-color-on-primary-normal);
|
||||
}
|
||||
|
||||
ha-button.clear-recent {
|
||||
/* :host tints the quiet fill for the tree items, keep it neutral */
|
||||
--wa-color-neutral-fill-quiet: var(--ha-color-fill-neutral-quiet-hover);
|
||||
margin-inline-start: auto;
|
||||
margin-inline-end: calc(-1 * var(--ha-space-2));
|
||||
--ha-button-height: var(--ha-space-6);
|
||||
--wa-form-control-padding-inline: var(--ha-space-2);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
|
||||
wa-tree-item::part(item) {
|
||||
height: var(--ha-space-10);
|
||||
padding: var(--ha-space-1) var(--ha-space-3);
|
||||
@@ -1758,5 +1939,6 @@ declare global {
|
||||
}
|
||||
interface HASSDomEvents {
|
||||
"time-location-group-selected": { value: string };
|
||||
"clear-recent-targets": undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { addRecent } from "../../../../common/array/add-recent";
|
||||
import {
|
||||
TARGET_SEPARATOR,
|
||||
type SingleHassServiceTarget,
|
||||
type TargetType,
|
||||
} from "../../../../data/target";
|
||||
|
||||
export const RECENT_TARGETS_STORAGE_KEY = "automation-recent-targets";
|
||||
|
||||
export const MAX_RECENT_TARGETS = 4;
|
||||
|
||||
const RECENT_TARGET_TYPES: readonly TargetType[] = [
|
||||
"floor",
|
||||
"area",
|
||||
"device",
|
||||
"entity",
|
||||
"label",
|
||||
];
|
||||
|
||||
/**
|
||||
* Parse a stored "<type>________<id>" recent target, rejecting malformed
|
||||
* entries and structural buckets like unassigned devices.
|
||||
*/
|
||||
export const parseRecentTarget = (
|
||||
value: unknown
|
||||
): [TargetType, string] | undefined => {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const [type, id] = value.split(TARGET_SEPARATOR, 2);
|
||||
if (!id || !RECENT_TARGET_TYPES.includes(type as TargetType)) {
|
||||
return undefined;
|
||||
}
|
||||
return [type as TargetType, id];
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a target picked in the add automation element dialog to the recent
|
||||
* targets.
|
||||
*/
|
||||
export const addRecentTarget = (
|
||||
recents: string[] | undefined,
|
||||
target: SingleHassServiceTarget
|
||||
): string[] | undefined =>
|
||||
RECENT_TARGET_TYPES.flatMap((type) => {
|
||||
const id = target[`${type}_id`];
|
||||
return id ? [`${type}${TARGET_SEPARATOR}${id}`] : [];
|
||||
}).reduce<string[] | undefined>(
|
||||
(list, id) =>
|
||||
addRecent(list, id, MAX_RECENT_TARGETS, (item) =>
|
||||
Boolean(parseRecentTarget(item))
|
||||
),
|
||||
recents
|
||||
);
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { LabelRegistryEntry } from "../../../../data/label/label_registry";
|
||||
import type { TargetType } from "../../../../data/target";
|
||||
import type { HomeAssistant, HomeAssistantRegistries } from "../../../../types";
|
||||
|
||||
const hasKey = (obj: object, key: string) =>
|
||||
Object.prototype.hasOwnProperty.call(obj, key);
|
||||
|
||||
/**
|
||||
* Check whether a target exists and is part of the target tree. Entities need
|
||||
* a registry entry and disabled devices are left out, like in the tree.
|
||||
*/
|
||||
export const targetExists = (
|
||||
registries: HomeAssistantRegistries,
|
||||
states: HomeAssistant["states"],
|
||||
labels: LabelRegistryEntry[] | undefined,
|
||||
targetType: TargetType,
|
||||
targetId: string
|
||||
): boolean => {
|
||||
switch (targetType) {
|
||||
case "entity":
|
||||
return hasKey(states, targetId) && hasKey(registries.entities, targetId);
|
||||
case "device":
|
||||
return (
|
||||
hasKey(registries.devices, targetId) &&
|
||||
!registries.devices[targetId].disabled_by
|
||||
);
|
||||
case "area":
|
||||
return hasKey(registries.areas, targetId);
|
||||
case "floor":
|
||||
return hasKey(registries.floors, targetId);
|
||||
case "label":
|
||||
return !!labels?.some((label) => label.label_id === targetId);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -12,20 +12,12 @@ import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
|
||||
import { relativeTime } from "../../../common/datetime/relative_time";
|
||||
import { storage } from "../../../common/decorators/storage";
|
||||
import { fireEvent, type HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import { navigate } from "../../../common/navigate";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import {
|
||||
BACKUP_LOCATIONS_FILTER,
|
||||
BACKUP_TYPE_FILTER,
|
||||
backupsFilterQueryParamConfig,
|
||||
backupsFilterQueryParams,
|
||||
backupsLinkFromUrl,
|
||||
} from "../../../common/url/backups-query-params";
|
||||
import type {
|
||||
DataTableColumnContainer,
|
||||
DataTableRowData,
|
||||
@@ -87,6 +79,9 @@ interface BackupRow extends DataTableRowData, BackupContent {
|
||||
agent_ids: string[];
|
||||
}
|
||||
|
||||
const TYPE_FILTER = "ha-filter-states";
|
||||
const LOCATIONS_FILTER = "backup-locations";
|
||||
|
||||
@customElement("ha-config-backup-backups")
|
||||
class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@@ -118,7 +113,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
})
|
||||
private _storageFilters: DataTableFiltersValues = {};
|
||||
|
||||
@state() private _search = "";
|
||||
private _fromUrl = false;
|
||||
|
||||
@storage({ key: "backups-table-grouping", state: false, subscribe: false })
|
||||
private _activeGrouping?: string = "formatted_type";
|
||||
@@ -139,25 +134,38 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
|
||||
private _overflowBackup?: BackupRow;
|
||||
|
||||
// The filters are kept in the URL by the page, the search, sorting and
|
||||
// grouping by the table
|
||||
private _filterParams = new QueryParamsController(
|
||||
this,
|
||||
backupsFilterQueryParamConfig,
|
||||
{
|
||||
enabled: () => true,
|
||||
navigated: () => this._applyLink(),
|
||||
}
|
||||
);
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
if (!this.hasUpdated) {
|
||||
this._filters = this._storageFilters;
|
||||
this._applyLink();
|
||||
this._setFiltersFromUrl();
|
||||
}
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// Re-apply the type filter from the URL when the page is (re)displayed,
|
||||
// e.g. when navigating back to a cached instance of this page with a
|
||||
// different `type` query param.
|
||||
this._setFiltersFromUrl();
|
||||
window.addEventListener("location-changed", this._locationChanged);
|
||||
window.addEventListener("popstate", this._popState);
|
||||
}
|
||||
|
||||
disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
window.removeEventListener("location-changed", this._locationChanged);
|
||||
window.removeEventListener("popstate", this._popState);
|
||||
}
|
||||
|
||||
private _locationChanged = () => {
|
||||
this._setFiltersFromUrl();
|
||||
};
|
||||
|
||||
private _popState = () => {
|
||||
this._setFiltersFromUrl();
|
||||
};
|
||||
|
||||
private _columns = memoizeOne(
|
||||
(
|
||||
localize: LocalizeFunc,
|
||||
@@ -189,7 +197,6 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
filterable: true,
|
||||
sortable: true,
|
||||
groupable: true,
|
||||
urlName: "type",
|
||||
},
|
||||
locations: {
|
||||
title: localize("ui.panel.config.backup.locations"),
|
||||
@@ -348,19 +355,16 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
localize: LocalizeFunc,
|
||||
isHassio: boolean
|
||||
): BackupRow[] => {
|
||||
const typeFilter = filters[BACKUP_TYPE_FILTER];
|
||||
const locationFilter = filters[BACKUP_LOCATIONS_FILTER];
|
||||
|
||||
const typeFilter = filters[TYPE_FILTER] as string[] | undefined;
|
||||
const locationFilter = filters[LOCATIONS_FILTER] as string[] | undefined;
|
||||
let filteredBackups = backups;
|
||||
|
||||
if (Array.isArray(typeFilter) && typeFilter.length) {
|
||||
if (typeFilter?.length) {
|
||||
filteredBackups = filteredBackups.filter((backup) => {
|
||||
const type = computeBackupType(backup, isHassio);
|
||||
return typeFilter.includes(type);
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(locationFilter) && locationFilter.length) {
|
||||
if (locationFilter?.length) {
|
||||
filteredBackups = filteredBackups.filter((backup) =>
|
||||
Object.keys(backup.agents).some((agentId) =>
|
||||
locationFilter.includes(agentId)
|
||||
@@ -458,9 +462,6 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
@selection-changed=${this._handleSelectionChanged}
|
||||
@clear-filter=${this._clearFilter}
|
||||
.route=${this.route}
|
||||
sync-url
|
||||
.filter=${this._search}
|
||||
@search-changed=${this._handleSearchChange}
|
||||
@row-click=${this._showBackupDetails}
|
||||
.columns=${this._columns(this.hass.localize, maxDisplayedAgents)}
|
||||
.data=${data}
|
||||
@@ -517,7 +518,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
|
||||
<ha-filter-states
|
||||
.label=${this.hass.localize("ui.panel.config.backup.backup_type")}
|
||||
.value=${this._filters[BACKUP_TYPE_FILTER]}
|
||||
.value=${this._filters[TYPE_FILTER]}
|
||||
.states=${this._states(this.hass.localize, isHassio)}
|
||||
@data-table-filter-changed=${this._typeFilterChanged}
|
||||
slot="filter-pane"
|
||||
@@ -525,7 +526,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
></ha-filter-states>
|
||||
<ha-filter-states
|
||||
.label=${this.hass.localize("ui.panel.config.backup.locations")}
|
||||
.value=${this._filters[BACKUP_LOCATIONS_FILTER]}
|
||||
.value=${this._filters[LOCATIONS_FILTER]}
|
||||
.states=${this._locations(
|
||||
this.hass.localize,
|
||||
this.agents,
|
||||
@@ -588,49 +589,38 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
|
||||
);
|
||||
|
||||
private _typeFilterChanged(ev) {
|
||||
this._filters = { ...this._filters, [BACKUP_TYPE_FILTER]: ev.detail.value };
|
||||
this._storageFilters = this._filters;
|
||||
this._writeFilters();
|
||||
this._filters = { ...this._filters, [TYPE_FILTER]: ev.detail.value };
|
||||
if (!this._fromUrl) {
|
||||
this._storageFilters = this._filters;
|
||||
}
|
||||
}
|
||||
|
||||
private _locationsFilterChanged(ev) {
|
||||
this._filters = {
|
||||
...this._filters,
|
||||
[BACKUP_LOCATIONS_FILTER]: ev.detail.value,
|
||||
};
|
||||
this._storageFilters = this._filters;
|
||||
this._writeFilters();
|
||||
this._filters = { ...this._filters, [LOCATIONS_FILTER]: ev.detail.value };
|
||||
if (!this._fromUrl) {
|
||||
this._storageFilters = this._filters;
|
||||
}
|
||||
}
|
||||
|
||||
private _clearFilter() {
|
||||
this._filters = {};
|
||||
this._storageFilters = {};
|
||||
this._writeFilters();
|
||||
if (!this._fromUrl) {
|
||||
this._storageFilters = {};
|
||||
}
|
||||
}
|
||||
|
||||
private _handleSearchChange(
|
||||
ev: HASSDomEvent<HASSDomEvents["search-changed"]>
|
||||
) {
|
||||
this._search = ev.detail.value;
|
||||
}
|
||||
private _setFiltersFromUrl() {
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const type = searchParams.get("type");
|
||||
|
||||
// Links, like the ones on the backups overview, say in the URL what to show.
|
||||
// The router keeps the page open, so a link can land on it.
|
||||
private _applyLink() {
|
||||
const searchParams = this._filterParams.searchParams();
|
||||
const link = searchParams ? backupsLinkFromUrl(searchParams) : undefined;
|
||||
|
||||
if (link) {
|
||||
this._search = link.search;
|
||||
this._filters = link.filters;
|
||||
this._storageFilters = link.filters;
|
||||
if (!type) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._writeFilters();
|
||||
}
|
||||
|
||||
private _writeFilters() {
|
||||
this._filterParams.write(backupsFilterQueryParams(this._filters));
|
||||
this._fromUrl = true;
|
||||
this._filters = {
|
||||
[TYPE_FILTER]: type === "all" ? [] : [type],
|
||||
};
|
||||
}
|
||||
|
||||
private get _needsOnboarding() {
|
||||
|
||||
@@ -101,6 +101,7 @@ export class HaConfigUsers extends LitElement {
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
groupable: true,
|
||||
urlName: "group",
|
||||
},
|
||||
is_active: {
|
||||
title: this.hass.localize(
|
||||
@@ -202,6 +203,7 @@ export class HaConfigUsers extends LitElement {
|
||||
@collapsed-changed=${this._handleCollapseChanged}
|
||||
.filter=${this._filter}
|
||||
@search-changed=${this._handleSearchChange}
|
||||
sync-url
|
||||
@row-click=${this._editUser}
|
||||
has-fab
|
||||
clickable
|
||||
|
||||
@@ -119,22 +119,13 @@ export class HuiSectionEditMode extends LitElement {
|
||||
${
|
||||
this._clipboard
|
||||
? html`
|
||||
<ha-dropdown-item value="paste-above">
|
||||
<ha-dropdown-item value="paste">
|
||||
<ha-svg-icon
|
||||
slot="icon"
|
||||
.path=${mdiContentPaste}
|
||||
></ha-svg-icon>
|
||||
${this.hass.localize(
|
||||
"ui.panel.lovelace.editor.section.paste_above"
|
||||
)}
|
||||
</ha-dropdown-item>
|
||||
<ha-dropdown-item value="paste-below">
|
||||
<ha-svg-icon
|
||||
slot="icon"
|
||||
.path=${mdiContentPaste}
|
||||
></ha-svg-icon>
|
||||
${this.hass.localize(
|
||||
"ui.panel.lovelace.editor.section.paste_below"
|
||||
"ui.panel.lovelace.editor.section.paste"
|
||||
)}
|
||||
</ha-dropdown-item>
|
||||
`
|
||||
@@ -188,11 +179,8 @@ export class HuiSectionEditMode extends LitElement {
|
||||
case "cut":
|
||||
this._cutSection();
|
||||
break;
|
||||
case "paste-above":
|
||||
this._pasteSection(0);
|
||||
break;
|
||||
case "paste-below":
|
||||
this._pasteSection(1);
|
||||
case "paste":
|
||||
this._pasteSection();
|
||||
break;
|
||||
case "delete":
|
||||
this._deleteSection();
|
||||
@@ -264,14 +252,14 @@ export class HuiSectionEditMode extends LitElement {
|
||||
});
|
||||
}
|
||||
|
||||
private async _pasteSection(offset: 0 | 1): Promise<void> {
|
||||
private async _pasteSection(): Promise<void> {
|
||||
if (!this._clipboard) return;
|
||||
const index = this.path[this.path.length - 1] as number;
|
||||
try {
|
||||
await this.lovelace!.saveConfig(
|
||||
insertAtPath(
|
||||
this.lovelace!.config,
|
||||
[...getParentPath(this.path), index + offset],
|
||||
[...getParentPath(this.path), index + 1],
|
||||
deepClone(this._clipboard)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -21,6 +21,14 @@ import { documentationUrl } from "../../util/documentation-url";
|
||||
// That's why redirects should be sorted with more specific ones first
|
||||
// Or else pressing "M" will link to the higher level page.
|
||||
|
||||
// The users table reads these from the link
|
||||
const usersTableParams = {
|
||||
search: "string?",
|
||||
sort: "string?",
|
||||
direction: "string?",
|
||||
group: "string?",
|
||||
} satisfies Redirect["params"];
|
||||
|
||||
// The Marketplace tabs with a table read these from the link
|
||||
const marketplaceTableParams = {
|
||||
search: "string?",
|
||||
@@ -317,6 +325,7 @@ export const getMyRedirects = (): Redirects => ({
|
||||
},
|
||||
users: {
|
||||
redirect: "/config/users",
|
||||
params: usersTableParams,
|
||||
},
|
||||
general: {
|
||||
redirect: "/config/general",
|
||||
@@ -404,7 +413,6 @@ export const getMyRedirects = (): Redirects => ({
|
||||
backup_list: {
|
||||
component: "backup",
|
||||
redirect: "/config/backup/backups",
|
||||
params: backupsTableParams,
|
||||
},
|
||||
backup_config: {
|
||||
component: "backup",
|
||||
@@ -519,16 +527,6 @@ export const getMyRedirects = (): Redirects => ({
|
||||
const getRedirect = (path: string): Redirect | undefined =>
|
||||
getMyRedirects()?.[path];
|
||||
|
||||
// The backups table reads these from the link
|
||||
const backupsTableParams = {
|
||||
search: "string?",
|
||||
sort: "string?",
|
||||
direction: "string?",
|
||||
group: "string?",
|
||||
type: "string?",
|
||||
location: "string?",
|
||||
} satisfies Redirect["params"];
|
||||
|
||||
export type ParamType = "url" | "string" | "string?";
|
||||
|
||||
export type Redirects = Record<string, Redirect>;
|
||||
|
||||
@@ -5585,6 +5585,8 @@
|
||||
"home": "Home",
|
||||
"unassigned": "Unassigned",
|
||||
"other": "Other",
|
||||
"recently_used": "Recently used",
|
||||
"clear_recently_used": "Clear recently used",
|
||||
"blocks": "Blocks",
|
||||
"tabs": {
|
||||
"target": "By target",
|
||||
@@ -10303,8 +10305,7 @@
|
||||
"automatic": "Automatic section",
|
||||
"edit_automatic": "Edit automatic section",
|
||||
"cut": "[%key:ui::panel::lovelace::editor::edit_card::cut%]",
|
||||
"paste_above": "Paste above",
|
||||
"paste_below": "Paste below",
|
||||
"paste": "Paste",
|
||||
"copied_to_clipboard": "Section copied to clipboard",
|
||||
"cut_to_clipboard": "Section cut to clipboard",
|
||||
"cut_error": "Error while cutting section",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { addRecent } from "../../../src/common/array/add-recent";
|
||||
|
||||
describe("addRecent", () => {
|
||||
it("works", () => {
|
||||
expect(addRecent(undefined, "a", 3)).toEqual(["a"]);
|
||||
expect(addRecent(["a", "b", "c"], "b", 3)).toEqual(["b", "a", "c"]);
|
||||
expect(addRecent(["a", "b", "c", "d"], "b", 3)).toEqual(["b", "a", "c"]);
|
||||
expect(addRecent(["a", "b", "c"], "d", 3)).toEqual(["d", "a", "b"]);
|
||||
expect(addRecent(["a", "x", "b"], "d", 3, (item) => item !== "x")).toEqual([
|
||||
"d",
|
||||
"a",
|
||||
"b",
|
||||
]);
|
||||
expect(addRecent("broken" as unknown as string[], "a", 3)).toEqual(["a"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DYNAMIC_PREFIX } from "../../../../src/data/automation";
|
||||
import { CONDITION_COLLECTIONS } from "../../../../src/data/condition";
|
||||
import { TRIGGER_COLLECTIONS } from "../../../../src/data/trigger";
|
||||
import { findElementGroupKey } from "../../../../src/panels/config/automation/add-automation-element/element-group";
|
||||
|
||||
describe("findElementGroupKey", () => {
|
||||
const forTrigger = (key: string) =>
|
||||
findElementGroupKey("trigger", TRIGGER_COLLECTIONS, key);
|
||||
|
||||
it("puts a member of a curated group in that group", () => {
|
||||
expect(forTrigger("state")).toBe("entity");
|
||||
expect(forTrigger("numeric_state")).toBe("entity");
|
||||
expect(forTrigger("time_pattern")).toBe("time");
|
||||
});
|
||||
|
||||
it("strips the dynamic prefix a backend element carries", () => {
|
||||
expect(forTrigger(`${DYNAMIC_PREFIX}sun.sunrise`)).toBe("sun");
|
||||
expect(forTrigger(`${DYNAMIC_PREFIX}calendar.event`)).toBe("time");
|
||||
});
|
||||
|
||||
it("falls back to the generated group for a domain no group curates", () => {
|
||||
expect(forTrigger(`${DYNAMIC_PREFIX}light.turned_on`)).toBe(
|
||||
`${DYNAMIC_PREFIX}light`
|
||||
);
|
||||
});
|
||||
|
||||
it("gives an element that is a row of its own no other category", () => {
|
||||
// Resolves to a generated group that is never rendered
|
||||
expect(forTrigger("template")).toBe(`${DYNAMIC_PREFIX}template`);
|
||||
expect(forTrigger("webhook")).toBe(`${DYNAMIC_PREFIX}webhook`);
|
||||
});
|
||||
|
||||
it("reads a condition's domain with the condition helper", () => {
|
||||
expect(
|
||||
findElementGroupKey("condition", CONDITION_COLLECTIONS, "numeric_state")
|
||||
).toBe("entity");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
addRecentTarget,
|
||||
parseRecentTarget,
|
||||
} from "../../../../src/panels/config/automation/target/recent_targets";
|
||||
|
||||
describe("parseRecentTarget", () => {
|
||||
it("works", () => {
|
||||
expect(parseRecentTarget("area________kitchen")).toEqual([
|
||||
"area",
|
||||
"kitchen",
|
||||
]);
|
||||
expect(parseRecentTarget(null)).toBeUndefined();
|
||||
expect(parseRecentTarget("device________")).toBeUndefined();
|
||||
expect(parseRecentTarget("entity_light________")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("addRecentTarget", () => {
|
||||
it("works", () => {
|
||||
expect(
|
||||
addRecentTarget(["area________kitchen"], { entity_id: "light.a" })
|
||||
).toEqual(["entity________light.a", "area________kitchen"]);
|
||||
expect(addRecentTarget(undefined, { floor_id: "ground" })).toEqual([
|
||||
"floor________ground",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { targetExists } from "../../../../src/panels/config/automation/target/target_exists";
|
||||
import type { HomeAssistantRegistries } from "../../../../src/types";
|
||||
|
||||
describe("targetExists", () => {
|
||||
it("works", () => {
|
||||
const registries = {
|
||||
entities: { "light.kitchen": {} },
|
||||
devices: { enabled: {}, disabled: { disabled_by: "user" } },
|
||||
areas: { kitchen: {} },
|
||||
floors: {},
|
||||
} as unknown as HomeAssistantRegistries;
|
||||
const states = {
|
||||
"light.kitchen": {},
|
||||
"light.yaml": {},
|
||||
} as unknown as Parameters<typeof targetExists>[1];
|
||||
|
||||
expect(
|
||||
targetExists(registries, states, [], "entity", "light.kitchen")
|
||||
).toBe(true);
|
||||
expect(targetExists(registries, states, [], "area", "kitchen")).toBe(true);
|
||||
expect(targetExists(registries, states, [], "device", "enabled")).toBe(
|
||||
true
|
||||
);
|
||||
expect(targetExists(registries, states, [], "device", "disabled")).toBe(
|
||||
false
|
||||
);
|
||||
// Entities without a registry entry are not part of the target tree
|
||||
expect(targetExists(registries, states, [], "entity", "light.yaml")).toBe(
|
||||
false
|
||||
);
|
||||
// Inherited object properties don't count as targets
|
||||
expect(targetExists(registries, states, [], "entity", "toString")).toBe(
|
||||
false
|
||||
);
|
||||
expect(targetExists(registries, states, [], "area", "constructor")).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user