Compare commits

..
27 changed files with 3610 additions and 1563 deletions

No files matched your search

+2 -2
View File
@@ -113,7 +113,7 @@
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"memoize-one": "7.0.0",
"mermaid": "12.4.1",
"mermaid": "12.4.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -191,7 +191,7 @@
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "15.0.0",
"globals": "17.15.0",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
"gulp-rename": "2.1.0",
+10 -10
View File
@@ -419,8 +419,8 @@ importers:
specifier: 7.0.0
version: 7.0.0
mermaid:
specifier: 12.4.1
version: 12.4.1
specifier: 12.4.0
version: 12.4.0
nanoid:
specifier: 6.0.2
version: 6.0.2
@@ -648,8 +648,8 @@ importers:
specifier: 15.0.0
version: 15.0.0
globals:
specifier: 17.15.0
version: 17.15.0
specifier: 17.14.0
version: 17.14.0
gulp:
specifier: 5.0.1
version: 5.0.1
@@ -5747,8 +5747,8 @@ packages:
resolution: {integrity: sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==}
engines: {node: '>=0.10.0'}
[email protected]5.0:
resolution: {integrity: sha512-OyBOdPnzu9B2lFpums9/4wcyNHx4haAxY2X5PgO9LqCvXJgKYMMr/1y4TU7om/vTy4eYqRsVes1ZTJEJYKap8Q==}
[email protected]4.0:
resolution: {integrity: sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==}
engines: {node: '>=18'}
[email protected]:
@@ -6607,8 +6607,8 @@ packages:
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
[email protected].1:
resolution: {integrity: sha512-8uCLCSeow+N6CrNzAB54lbNFipC1DOPXZeOTeSlfvJaNUohg0A9eebmJNxs4Ik/OyEDqmF2thvyCzkwkmNnTtg==}
[email protected].0:
resolution: {integrity: sha512-j2gvsGUFeS/53WdYLl9H5G2YtMZX9G/PlCvV3E5Pf4j5XSnK19DwazU6wki7OTcKeYKed7+qujRDLhy8NV2zBg==}
engines: {node: '>=22.12.0'}
[email protected]:
@@ -14181,7 +14181,7 @@ snapshots:
is-windows: 1.0.2
which: 1.3.1
[email protected]5.0: {}
[email protected]4.0: {}
[email protected]:
dependencies:
@@ -15065,7 +15065,7 @@ snapshots:
[email protected]: {}
[email protected].1:
[email protected].0:
dependencies:
'@braintree/sanitize-url': 7.1.2
'@iconify/utils': 3.1.7
+110
View File
@@ -0,0 +1,110 @@
import type { HassServiceTarget } from "home-assistant-js-websocket";
import type { SourceFilters } from "../../components/ha-sources-picker";
import type { StateColumnFilters } from "../../panels/config/tools/state/tools-state-filter";
import { historyLogbookTargetParamKeys } from "./history-logbook-query-params";
import {
decodeQueryParams,
hasQueryParams,
queryParamsFromServiceTarget,
serviceTargetFromQueryParams,
type QueryParamConfig,
type QueryParamValues,
type SearchParamsSource,
} from "./query-params";
export type ToolsStateFilterMode = "targets" | "columns";
export const toolsStateQueryParamConfig = {
string: [
"search",
"mode",
"entity_filter",
"state_filter",
"device_filter",
"area_filter",
"attribute_filter",
"open",
],
list: [...historyLogbookTargetParamKeys, "entity_type", "integration"],
} as const satisfies QueryParamConfig;
export type ToolsStateQueryParams = QueryParamValues<
typeof toolsStateQueryParamConfig
>;
/** What the States tool shows: its search, filters and open row. */
export interface ToolsStateView {
search: string;
mode: ToolsStateFilterMode;
targets: HassServiceTarget;
sourceFilters: SourceFilters;
columnFilters: StateColumnFilters;
/** The entity whose row is open. */
open?: string;
}
/**
* The URL params for a view. Only the filters of the shown mode are written,
* and Targets, the default mode, is left out.
*/
export const toolsStateParamsFromView = (
view: ToolsStateView
): ToolsStateQueryParams => {
const modeParams: ToolsStateQueryParams =
view.mode === "columns"
? {
mode: "columns",
entity_filter: view.columnFilters.entity,
state_filter: view.columnFilters.state,
device_filter: view.columnFilters.device,
area_filter: view.columnFilters.area,
attribute_filter: view.columnFilters.attribute,
}
: {
...queryParamsFromServiceTarget(
view.targets,
historyLogbookTargetParamKeys
),
entity_type: view.sourceFilters.types,
integration: view.sourceFilters.integrations,
};
return { search: view.search, open: view.open, ...modeParams };
};
/** The view a link asks for, or undefined when it has none of the params. */
export const toolsStateViewFromUrl = (
searchParams: SearchParamsSource
): ToolsStateView | undefined => {
if (!hasQueryParams(searchParams, toolsStateQueryParamConfig)) {
return undefined;
}
const params = decodeQueryParams(searchParams, toolsStateQueryParamConfig);
const sourceFilters: SourceFilters = {};
if (params.entity_type) {
sourceFilters.types = params.entity_type;
}
if (params.integration) {
sourceFilters.integrations = params.integration;
}
return {
search: params.search ?? "",
mode: params.mode === "columns" ? "columns" : "targets",
targets:
serviceTargetFromQueryParams(params, historyLogbookTargetParamKeys) ?? {},
sourceFilters,
columnFilters: {
entity: params.entity_filter,
state: params.state_filter,
device: params.device_filter,
area: params.area_filter,
attribute: params.attribute_filter,
},
open: params.open,
};
};
@@ -0,0 +1,122 @@
---
component: Entity details
element: ha-entity-details
code:
- src/components/entity/ha-entity-details.ts
figma: "[open]"
related:
- src/components/list/ha-grouped-list.record.md
- src/components/ha-attribute-value.record.md
lifecycle: built
status:
requirements: stub
design: stub
implementation: stub
usage: stub
editors: []
---
# Entity details
## 1. Requirements
### Purpose
`[review]`
Shows everything Home Assistant holds for one entity, so More info and the States tool read the same data and show it the same way.
### Scope
`[review]`
The entity's ID, state, timestamps, device, area and attributes, as a list or as read-only YAML. The data comes from `computeEntityDetails` in `src/data/entity/entity_details.ts`.
### Out of scope
`[review]`
- Changing the entity. Set state lives in the States tool.
- The header, tabs and YAML switch around it. The screen that uses it owns those.
### Anatomy
`[review]`
1. **entity group**: a grouped list headed "Entity", with the entity ID, state, device, area, last changed and last updated.
2. **attributes group**: a grouped list headed "Attributes", one row per attribute, sorted by translated name.
3. **row**: a label on the start side and a value on the end side, with an optional copy button.
4. **raw line**: the stored text under the translated label or value.
5. **YAML view**: a read-only YAML editor with the same data.
### Statements
**Function** `[review]`
- `function.1` Shows one entity's details as a list, or as read-only YAML when YAML mode is on.
- `function.2` Copies a value to the clipboard, shows a tick on that row for 4 seconds and a toast.
- `function.3` A copy takes the translated value when only translated text shows, otherwise the stored value.
**Variants** `[review]`
- `variant.1` Display: translated (default), raw, or both.
- `variant.2` Layout: stacked (default) puts the groups under each other. Split puts them side by side when the component is at least 720 px wide.
- `variant.3` Copy values: every value gets its own copy button. Without it, only the entity ID row copies, when the row is pressed.
- `variant.4` Show registry: adds the device and area rows. A row without a device or area is left out.
- `variant.5` Show links: device and area link to their pages, the timestamps link to History from an hour before.
**States** `[review]`
- `state.1` Empty attributes: the attributes group says "None".
- `state.2` Copied: the copy icon on that row is a green tick.
**Behaviour** `[review]`
- `behaviour.1` The details follow the entity's state live.
- `behaviour.2` With display both, the raw line shows only when the stored text differs from the translated text.
- `behaviour.3` With display both, objects and lists of objects show once, as YAML, without a raw line.
**Content** `[review]`
- `content.1` Attribute values use `ha-attribute-value`, except supported features, which are spelled out by name.
- `content.2` Raw labels and values use the code font.
**Accessibility** `[review]`
- `accessibility.1` Each copy control is labelled "Copy {label}: {value}".
- `accessibility.2` The entity ID row without copy values is one button for the whole row.
**Integration** `[review]`
- `integration.1` Reads states, formatters, translations, config and registries from contexts, not `hass`.
- `[open]` Which parts each screen shows. Today More info shows translated text, no device or area rows, no links, and copies only the entity ID. The States tool shows both texts, the registry rows, links and a copy button on every value. Whether people choose this as a preference is not decided.
### Ruled out
`[open]`
## 2. Design
`[open]`
## 3. Implementation
`[review]`
- A `LitElement` that renders two `ha-grouped-list`s of `ha-list-item-base` and `ha-list-item-button` rows, or `ha-yaml-editor`.
- `computeEntityDetails` builds the rows, memoised on its inputs.
- The split layout uses a container query on the host.
## 4. Usage
`[review]`
- More info's Details view (`ha-more-info-details`), with display translated.
## 5. Decision log
| Date | Decision | Reason | By |
| ---------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------- |
| 2026-12-04 | More info and the States tool share one details component | So their details can't drift apart; each screen chooses which parts it shows | States revamp |
| 2026-12-04 | Rows are rendered by the component, not a row element | A wrapper element between the grouped list and its list items would break list semantics | States revamp |
+406
View File
@@ -0,0 +1,406 @@
import { mdiCheck, mdiContentCopy } from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import { consumeEntityState } from "../../common/decorators/consume-context-entry";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import { copyToClipboard } from "../../common/util/copy-clipboard";
import {
configContext,
formattersContext,
internationalizationContext,
registriesContext,
} from "../../data/context";
import {
computeEntityDetails,
type EntityAttributeValue,
type EntityDetailItem,
type EntityDetails,
} from "../../data/entity/entity_details";
import { showToast } from "../../util/toast";
import "../ha-attribute-value";
import "../ha-icon-button";
import "../ha-svg-icon";
import "../ha-yaml-editor";
import "../item/ha-list-item-base";
import "../item/ha-list-item-button";
import "../list/ha-grouped-list";
export type EntityDetailsDisplay = "translated" | "raw" | "both";
const COPY_FEEDBACK_DURATION = 4000;
/** Objects and lists of objects, which `ha-attribute-value` shows as YAML. */
const isStructured = (value: EntityAttributeValue): boolean =>
Array.isArray(value)
? value.some((entry) => entry instanceof Object)
: value instanceof Object;
/**
* @element ha-entity-details
*
* @summary
* The details of one entity: an Entity group (ID, state, timestamps and
* optionally device and area) and an Attributes group, or the same data as
* read-only YAML. Text can show translated, as stored, or both.
*
* @attr {string} entity-id - The entity to show.
* @attr {boolean} yaml-mode - Shows the details as read-only YAML.
* @attr {"translated"|"raw"|"both"} display - Which text to show. `both` shows the stored text under the translated text when they differ.
* @attr {boolean} copy-values - Every value gets its own copy button. Without it, only the entity ID row copies, when the row is pressed.
* @attr {boolean} show-registry - Shows the device and area rows.
* @attr {boolean} show-links - Links the device, area and timestamps to their pages.
* @attr {boolean} in-dialog - Passed to the YAML editor.
* @attr {"stacked"|"split"} layout - `split` puts the groups side by side when there is room.
*/
@customElement("ha-entity-details")
export class HaEntityDetails extends LitElement {
@property({ attribute: "entity-id" }) public entityId?: string;
@property({ type: Boolean, attribute: "yaml-mode" }) public yamlMode = false;
@property() public display: EntityDetailsDisplay = "translated";
@property({ type: Boolean, attribute: "copy-values" }) public copyValues =
false;
@property({ type: Boolean, attribute: "show-registry" })
public showRegistry = false;
@property({ type: Boolean, attribute: "show-links" }) public showLinks =
false;
@property({ type: Boolean, attribute: "in-dialog" }) public inDialog = false;
@property({ reflect: true }) public layout: "stacked" | "split" = "stacked";
@state()
@consumeEntityState({ entityIdPath: ["entityId"] })
private _stateObj?: HassEntityState;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
private _config!: ContextType<typeof configContext>;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@state() private _copiedKey?: string;
private _copyFeedbackTimeout?: number;
private _computeDetails = memoizeOne(computeEntityDetails);
public disconnectedCallback(): void {
super.disconnectedCallback();
window.clearTimeout(this._copyFeedbackTimeout);
this._copyFeedbackTimeout = undefined;
this._copiedKey = undefined;
}
private _getDetails(stateObj: HassEntityState): EntityDetails {
return this._computeDetails(
stateObj,
this._formatters,
this._i18n.localize,
this._i18n.locale,
this._config.config,
this._registries
);
}
protected render() {
const stateObj = this._stateObj;
if (!stateObj) {
return nothing;
}
const details = this._getDetails(stateObj);
if (this.yamlMode) {
return html`<ha-yaml-editor
.value=${details.yaml}
read-only
auto-update
.inDialog=${this.inDialog}
></ha-yaml-editor>`;
}
const entityItems = details.entity.filter(
(item) =>
item.value !== undefined &&
(this.showRegistry || (item.key !== "device" && item.key !== "area"))
);
return html`
<div class="groups">
<ha-grouped-list
.header=${this._i18n.localize("ui.dialogs.more_info_control.entity")}
>
${entityItems.map((item) => this._renderItem(item, stateObj, false))}
</ha-grouped-list>
<ha-grouped-list
.header=${this._i18n.localize(
"ui.dialogs.more_info_control.attributes"
)}
>
${
details.attributes.length === 0
? html`<div class="empty">
${this._i18n.localize("ui.common.none")}
</div>`
: details.attributes.map((item) =>
this._renderItem(item, stateObj, true)
)
}
</ha-grouped-list>
</div>
`;
}
/** The text a copy puts on the clipboard. */
private _copyText(item: EntityDetailItem): string {
return this.display === "translated" && item.value !== undefined
? item.value
: item.rawValue;
}
private _renderItem(
item: EntityDetailItem,
stateObj: HassEntityState,
isAttribute: boolean
) {
const content = html`<div class="row" slot="content">
${this._renderLabel(item)}${this._renderValue(item, stateObj, isAttribute)}
</div>`;
const copied = this._copiedKey === item.key;
const copyLabel = this._i18n.localize(
"ui.dialogs.more_info_control.copy_value",
{ label: item.label, value: this._copyText(item) }
);
if (this.copyValues) {
// Each value copies with its own button, so links in values still work
return html`<ha-list-item-base>
${content}
${
item.rawValue === ""
? nothing
: html`<ha-icon-button
slot="end"
class=${copied ? "copy-success" : ""}
.label=${copyLabel}
.path=${copied ? mdiCheck : mdiContentCopy}
data-key=${item.key}
@click=${this._copyItem}
></ha-icon-button>`
}
</ha-list-item-base>`;
}
if (item.key !== "entity_id") {
return html`<ha-list-item-base>${content}</ha-list-item-base>`;
}
// The entity ID row copies when the whole row is pressed
return html`<ha-list-item-button
aria-label=${copyLabel}
data-key=${item.key}
@click=${this._copyItem}
>
${content}
<ha-svg-icon
class=${copied ? "copy-success" : ""}
slot="end"
.path=${copied ? mdiCheck : mdiContentCopy}
></ha-svg-icon>
</ha-list-item-button>`;
}
private _renderLabel(item: EntityDetailItem): TemplateResult {
if (this.display === "raw") {
return html`<div class="label"><code>${item.rawLabel}</code></div>`;
}
return html`<div class="label">
<span>${item.label}</span>
${
this.display === "both" && item.label !== item.rawLabel
? html`<code class="raw">${item.rawLabel}</code>`
: nothing
}
</div>`;
}
private _renderValue(
item: EntityDetailItem,
stateObj: HassEntityState,
isAttribute: boolean
): TemplateResult {
if (this.display === "raw") {
return html`<div class="value"><code>${item.rawValue}</code></div>`;
}
const translated =
item.value ??
html`<ha-attribute-value
.stateObj=${stateObj}
.attribute=${item.key}
></ha-attribute-value>`;
const main =
this.showLinks && item.href
? html`<a href=${item.href}>${translated}</a>`
: translated;
// Structured values already show as YAML, so the stored text would repeat
// them
const showRaw =
this.display === "both" &&
!(isAttribute && isStructured(stateObj.attributes[item.key])) &&
item.rawValue !==
(item.value ??
this._formatters.formatEntityAttributeValue(stateObj, item.key));
return html`<div class="value">
<span>${main}</span>
${showRaw ? html`<code class="raw">${item.rawValue}</code>` : nothing}
</div>`;
}
private async _copyItem(ev: HASSDomCurrentTargetEvent<HTMLElement>) {
const key = ev.currentTarget.dataset.key;
const details = this._stateObj
? this._getDetails(this._stateObj)
: undefined;
const item = details
? [...details.entity, ...details.attributes].find(
(entry) => entry.key === key
)
: undefined;
if (!key || !item) {
return;
}
await copyToClipboard(this._copyText(item));
this._copiedKey = key;
window.clearTimeout(this._copyFeedbackTimeout);
this._copyFeedbackTimeout = window.setTimeout(() => {
this._copiedKey = undefined;
this._copyFeedbackTimeout = undefined;
}, COPY_FEEDBACK_DURATION);
showToast(this, {
message: this._i18n.localize("ui.common.copied_clipboard"),
duration: COPY_FEEDBACK_DURATION,
});
}
static styles: CSSResultGroup = css`
:host {
display: block;
container-type: inline-size;
}
.groups {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--ha-space-6);
align-items: start;
}
@container (min-width: 720px) {
:host([layout="split"]) .groups {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: var(--ha-space-4);
}
}
ha-list-item-base,
ha-list-item-button {
--ha-row-item-padding-block: var(--ha-space-2);
--ha-row-item-min-height: 40px;
--ha-row-item-gap: var(--ha-space-3);
--mdc-icon-size: 20px;
--ha-icon-button-size: 32px;
}
.row {
display: flex;
flex-direction: row;
align-items: center;
gap: var(--ha-space-3);
}
.label,
.value {
display: flex;
flex-direction: column;
min-width: 0;
}
.label {
flex: 1;
color: var(--secondary-text-color);
}
.value {
align-items: flex-end;
max-width: 60%;
text-align: end;
overflow-wrap: anywhere;
}
code {
font-family: var(--ha-font-family-code);
font-size: var(--ha-font-size-s);
overflow-wrap: anywhere;
white-space: pre-wrap;
}
code.raw {
color: var(--secondary-text-color);
}
a {
color: var(--primary-color);
text-decoration: none;
}
.copy-success {
color: var(--success-color);
}
.empty {
color: var(--secondary-text-color);
text-align: center;
padding: var(--ha-space-3) var(--ha-space-4);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-entity-details": HaEntityDetails;
}
}
@@ -48,6 +48,7 @@ A Web Awesome button group with one `ha-button` per option.
- `variant.2` Variant: `brand` (default), `neutral`, `success`, `warning`, `danger`. The active button can use its own variant.
- `variant.3` Full width: the buttons share the width.
- `variant.4` No wrap: the buttons stay on one line.
- `variant.5` `[open]` Show labels: buttons with an icon show the icon and their label.
**States** `[review]`
@@ -61,6 +62,7 @@ A Web Awesome button group with one `ha-button` per option.
**Content** `[review]`
- `content.1` Each button shows an icon or its label. The label is also the tooltip.
- `content.2` `[open]` With show labels, a button with an icon shows the icon followed by its label. The page decides when to turn labels off, for example when space is short, so a narrow screen shows icons only.
**Accessibility** `[review]`
+15 -5
View File
@@ -17,6 +17,7 @@ import "./ha-svg-icon";
* @attr {string} active - The value of the currently active button.
* @attr {("s"|"m")} size - The size of the buttons in the group.
* @attr {("brand"|"neutral"|"success"|"warning"|"danger")} variant - The variant of the buttons in the group.
* @attr {boolean} show-labels - Buttons with an icon show their label next to it.
*
* @fires value-changed - Dispatched when the active button changes.
*/
@@ -36,6 +37,9 @@ export class HaButtonToggleGroup extends LitElement {
@property({ type: Boolean }) public disabled = false;
@property({ type: Boolean, attribute: "show-labels" }) public showLabels =
false;
@property() public variant:
"brand" | "neutral" | "success" | "warning" | "danger" = "brand";
@@ -64,12 +68,18 @@ export class HaButtonToggleGroup extends LitElement {
.appearance=${this.active === button.value ? "accent" : "filled"}
>
${
button.iconPath
button.iconPath && this.showLabels
? html`<ha-svg-icon
aria-label=${button.label}
.path=${button.iconPath}
></ha-svg-icon>`
: button.label
slot="start"
.path=${button.iconPath}
></ha-svg-icon
>${button.label}`
: button.iconPath
? html`<ha-svg-icon
aria-label=${button.label}
.path=${button.iconPath}
></ha-svg-icon>`
: button.label
}
</ha-button>`
)}
+237
View File
@@ -0,0 +1,237 @@
import type { HassConfig, HassEntityState } from "home-assistant-js-websocket";
import { dump } from "js-yaml";
import checkValidDate from "../../common/datetime/check_valid_date";
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
import { computeAreaName } from "../../common/entity/compute_area_name";
import { computeDeviceName } from "../../common/entity/compute_device_name";
import { computeDomain } from "../../common/entity/compute_domain";
import { getFeatures } from "../../common/entity/get_domain_features";
import { supportsFeature } from "../../common/entity/supports-feature";
import { stringCompare } from "../../common/string/compare";
import { titleCase } from "../../common/string/title-case";
import type { LocalizeFunc } from "../../common/translations/localize";
import {
createQueryString,
type QueryParamConfig,
} from "../../common/url/query-params";
import type {
HomeAssistantFormatters,
HomeAssistantRegistries,
} from "../../types";
import type { FrontendLocaleData } from "../translation";
/** One attribute value, as Home Assistant sends it. */
export type EntityAttributeValue = HassEntityState["attributes"][string];
export interface EntityDetailItem {
/** `entity_id`, `state`, `device`, `area`, `last_changed`, `last_updated`, or an attribute name. */
key: string;
/** The translated label. */
label: string;
/** The label as stored, such as `color_temp_kelvin`. */
rawLabel: string;
/**
* The translated value. Undefined for attributes that are rendered with
* `ha-attribute-value`.
*/
value?: string;
/** The value as stored. */
rawValue: string;
/** Where the value links to: a device, an area or History. */
href?: string;
}
export interface EntityDetails {
entity: EntityDetailItem[];
attributes: EntityDetailItem[];
yaml: {
entity_id: string;
state: string;
last_changed: string;
last_updated: string;
attributes: HassEntityState["attributes"];
};
}
const historyQueryParamConfig = {
list: ["entity_id"],
date: ["start_date"],
} as const satisfies QueryParamConfig;
const HOUR = 60 * 60 * 1000;
/** History for an entity from an hour before a timestamp. */
export const entityHistoryUrl = (entityId: string, timestamp: string): string =>
`/history?${createQueryString(
{
entity_id: [entityId],
start_date: new Date(new Date(timestamp).getTime() - HOUR),
},
historyQueryParamConfig
)}`;
const formatTimestamp = (
value: string,
locale: FrontendLocaleData,
config: HassConfig
): string => {
const date = new Date(value);
return checkValidDate(date)
? formatDateTimeWithSeconds(date, locale, config)
: value;
};
/**
* An attribute value as stored: lists of plain values joined with commas,
* objects and lists of objects as YAML.
*/
export const formatRawAttributeValue = (
value: EntityAttributeValue
): string => {
if (value === null || value === undefined) {
return String(value);
}
if (
(Array.isArray(value) && value.some((item) => item instanceof Object)) ||
(!Array.isArray(value) && value instanceof Object)
) {
return dump(value).trimEnd();
}
return Array.isArray(value) ? value.join(", ") : String(value);
};
/** The supported features an entity has, spelled out. */
export const formatSupportedFeatures = (
stateObj: HassEntityState,
localize: LocalizeFunc
): string | undefined => {
if (stateObj.attributes.supported_features === undefined) {
return undefined;
}
const featureEnum = getFeatures(computeDomain(stateObj.entity_id));
if (!featureEnum) {
return undefined;
}
return (
Object.entries(featureEnum)
.filter(
(entry): entry is [string, number] => typeof entry[1] === "number"
)
.map(([key, value]) =>
supportsFeature(stateObj, value)
? titleCase(key.replaceAll("_", " ").toLowerCase())
: undefined
)
.filter(Boolean)
.join(", ") || localize("ui.common.none")
);
};
/**
* Everything the entity details show for one entity, translated and as
* stored, so every screen that shows them reads the same data.
*/
export const computeEntityDetails = (
stateObj: HassEntityState,
formatters: HomeAssistantFormatters,
localize: LocalizeFunc,
locale: FrontendLocaleData,
config: HassConfig,
registries: Pick<HomeAssistantRegistries, "entities" | "devices" | "areas">
): EntityDetails => {
const entityId = stateObj.entity_id;
const entry = registries.entities[entityId];
const device = entry?.device_id
? registries.devices[entry.device_id]
: undefined;
const areaId = entry?.area_id ?? device?.area_id ?? undefined;
const area = areaId ? registries.areas[areaId] : undefined;
const deviceName = device ? computeDeviceName(device) : undefined;
const areaName = area ? computeAreaName(area) : undefined;
const entity: EntityDetailItem[] = [
{
key: "entity_id",
label: localize("ui.dialogs.more_info_control.entity_id"),
rawLabel: "entity_id",
value: entityId,
rawValue: entityId,
},
{
key: "state",
label: localize("ui.dialogs.more_info_control.state"),
rawLabel: "state",
value: formatters.formatEntityState(stateObj),
rawValue: stateObj.state,
},
{
key: "device",
label: localize("ui.components.entity_details.device"),
rawLabel: "device_id",
value: deviceName,
rawValue: device?.id ?? "",
href: device ? `/config/devices/device/${device.id}` : undefined,
},
{
key: "area",
label: localize("ui.components.entity_details.area"),
rawLabel: "area_id",
value: areaName,
rawValue: areaId ?? "",
href: areaId ? `/config/areas/area/${areaId}` : undefined,
},
{
key: "last_changed",
label: localize("ui.dialogs.more_info_control.last_changed"),
rawLabel: "last_changed",
value: formatTimestamp(stateObj.last_changed, locale, config),
rawValue: stateObj.last_changed,
href: entityHistoryUrl(entityId, stateObj.last_changed),
},
{
key: "last_updated",
label: localize("ui.dialogs.more_info_control.last_updated"),
rawLabel: "last_updated",
value: formatTimestamp(stateObj.last_updated, locale, config),
rawValue: stateObj.last_updated,
href: entityHistoryUrl(entityId, stateObj.last_updated),
},
];
const attributes = Object.keys(stateObj.attributes)
.map((name): EntityDetailItem => ({
key: name,
label: formatters.formatEntityAttributeName(stateObj, name),
rawLabel: name,
value:
name === "supported_features"
? formatSupportedFeatures(stateObj, localize)
: undefined,
rawValue: formatRawAttributeValue(stateObj.attributes[name]),
}))
.sort((a, b) => stringCompare(a.label, b.label, locale.language));
return {
entity,
attributes,
yaml: {
entity_id: entityId,
state: stateObj.state,
last_changed: stateObj.last_changed,
last_updated: stateObj.last_updated,
attributes: stateObj.attributes,
},
};
};
-16
View File
@@ -4,22 +4,6 @@ import type { RecorderInfo } from "./recorder";
export interface WindowWithPreloads extends Window {
llConfProm?: Promise<LovelaceRawConfig>;
llConfUrlPath?: string;
llResProm?: Promise<LovelaceResource[]>;
recorderInfoProm?: Promise<RecorderInfo>;
}
const HYPHENATED_NON_DASHBOARD_PATHS = ["developer-tools", "media-browser"];
export const getPreloadDashboardUrlPath = (
pathname: string
): string | undefined => {
const urlPath = pathname.split("/")[1];
if (urlPath === "lovelace") {
return urlPath;
}
return urlPath?.includes("-") &&
!HYPHENATED_NON_DASHBOARD_PATHS.includes(urlPath)
? urlPath
: undefined;
};
+9 -311
View File
@@ -1,296 +1,34 @@
import { mdiCheck, mdiContentCopy } from "@mdi/js";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues } from "lit";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import checkValidDate from "../../common/datetime/check_valid_date";
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
import "../../components/ha-attribute-value";
import "../../components/ha-svg-icon";
import "../../components/item/ha-list-item-button";
import type { HaListItemButton } from "../../components/item/ha-list-item-button";
import "../../components/item/ha-list-item-value";
import "../../components/list/ha-grouped-list";
import { copyToClipboard } from "../../common/util/copy-clipboard";
import type { LocalizeKeys } from "../../common/translations/localize";
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
import type { HomeAssistant } from "../../types";
import "../../components/ha-yaml-editor";
import { computeDomain } from "../../common/entity/compute_domain";
import type { FeatureEnum } from "../../common/entity/get_domain_features";
import { getFeatures } from "../../common/entity/get_domain_features";
import { supportsFeature } from "../../common/entity/supports-feature";
import { titleCase } from "../../common/string/title-case";
import { stringCompare } from "../../common/string/compare";
import { showToast } from "../../util/toast";
import { customElement, property } from "lit/decorators";
import "../../components/entity/ha-entity-details";
interface DetailsViewParams {
entityId: string;
}
interface DetailEntry {
translationKey: LocalizeKeys;
value: string;
copyable?: boolean;
}
@customElement("ha-more-info-details")
class HaMoreInfoDetails extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
@property({ attribute: false }) public params?: DetailsViewParams;
@property({ attribute: false }) public yamlMode = false;
@state() private _stateObj?: HassEntityState;
@state() private _copiedValue?: string;
private _copyFeedbackTimeout?: number;
public disconnectedCallback(): void {
super.disconnectedCallback();
window.clearTimeout(this._copyFeedbackTimeout);
this._copyFeedbackTimeout = undefined;
this._copiedValue = undefined;
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (changedProps.has("params") || changedProps.has("hass")) {
if (this.params?.entityId && this.hass) {
this._stateObj = this.hass.states[this.params.entityId];
}
}
}
protected render() {
if (!this.params || !this._stateObj) {
if (!this.params) {
return nothing;
}
const {
stateEntries,
attributes,
yamlData: stateYamlData,
} = this._getDetailData(
this._stateObj,
this.hass.formatEntityAttributeName
);
const entityEntries: DetailEntry[] = [
{
translationKey: "ui.dialogs.more_info_control.entity_id",
value: this.params.entityId,
copyable: true,
},
];
const yamlData = {
entity_id: this.params.entityId,
...stateYamlData,
};
return html`
<div class="content">
${
this.yamlMode
? html`<ha-yaml-editor
.value=${yamlData}
read-only
auto-update
in-dialog
></ha-yaml-editor>`
: html`
<ha-grouped-list
.header=${this.hass.localize(
"ui.dialogs.more_info_control.entity"
)}
>
${this._renderEntries(entityEntries)}
${this._renderEntries(stateEntries)}
</ha-grouped-list>
<ha-grouped-list
.header=${this.hass.localize(
"ui.dialogs.more_info_control.attributes"
)}
>
${this._renderAttributes(attributes)}
</ha-grouped-list>
`
}
<ha-entity-details
.entityId=${this.params.entityId}
.yamlMode=${this.yamlMode}
in-dialog
></ha-entity-details>
</div>
`;
}
private _getDetailData = memoizeOne(
(
stateObj: HassEntityState,
// cache key only: a new function is assigned when translation-based
// format functions reload, invalidating results formatted via this.hass
_formatEntityAttributeName: HomeAssistant["formatEntityAttributeName"]
): {
stateEntries: DetailEntry[];
attributes: { name: string; label: string }[];
yamlData: {
state: string;
last_changed: string;
last_updated: string;
attributes: Record<string, string>;
};
} => {
const attributes = Object.keys(stateObj.attributes)
.map((a) => ({
name: a,
label: this.hass.formatEntityAttributeName(stateObj, a),
}))
.sort((a, b) =>
stringCompare(a.label, b.label, this.hass.locale.language)
);
return {
stateEntries: [
{
translationKey: "ui.dialogs.more_info_control.state",
value: this.hass.formatEntityState(stateObj),
},
{
translationKey: "ui.dialogs.more_info_control.last_changed",
value: this._formatTimestamp(stateObj.last_changed),
},
{
translationKey: "ui.dialogs.more_info_control.last_updated",
value: this._formatTimestamp(stateObj.last_updated),
},
],
attributes,
yamlData: {
state: stateObj.state,
last_changed: stateObj.last_changed,
last_updated: stateObj.last_updated,
attributes: stateObj.attributes,
},
};
}
);
private _formatTimestamp(value: string): string {
const date = new Date(value);
return checkValidDate(date)
? formatDateTimeWithSeconds(date, this.hass.locale, this.hass.config)
: value;
}
private _renderEntries(entries: DetailEntry[]) {
return entries.map((entry) => {
const label = this.hass.localize(entry.translationKey);
if (!entry.copyable) {
return html`
<ha-list-item-value .label=${label}
>${entry.value}</ha-list-item-value
>
`;
}
return html`
<ha-list-item-button
aria-label=${this.hass.localize(
"ui.dialogs.more_info_control.copy_value",
{ label, value: entry.value }
)}
data-value=${entry.value}
@click=${this._copyValue}
>
<div class="link-row" slot="content">
<div class="label">${label}</div>
<div class="value">${entry.value}</div>
</div>
<ha-svg-icon
class=${this._copiedValue === entry.value ? "copy-success" : ""}
slot="end"
.path=${
this._copiedValue === entry.value ? mdiCheck : mdiContentCopy
}
></ha-svg-icon>
</ha-list-item-button>
`;
});
}
private async _copyValue(ev: HASSDomCurrentTargetEvent<HaListItemButton>) {
const value = ev.currentTarget.dataset.value;
if (value === undefined) {
return;
}
await copyToClipboard(value);
const duration = 4000;
this._copiedValue = value;
window.clearTimeout(this._copyFeedbackTimeout);
this._copyFeedbackTimeout = window.setTimeout(() => {
this._copiedValue = undefined;
this._copyFeedbackTimeout = undefined;
}, duration);
showToast(this, {
message: this.hass.localize("ui.common.copied_clipboard"),
duration,
});
}
private _renderAttributes(attributes: { name: string; label: string }[]) {
if (attributes.length === 0) {
return html`<div class="empty">
${this.hass.localize("ui.common.none")}
</div>`;
}
let featureEnum: FeatureEnum | undefined;
if (this._stateObj?.attributes.supported_features !== undefined) {
const domain = computeDomain(this.params!.entityId);
featureEnum = getFeatures(domain);
}
return attributes.map(
(attribute) => html`
<ha-list-item-value .label=${attribute.label}>
${
attribute.name === "supported_features" && featureEnum
? this._renderFeatures(featureEnum, this._stateObj!)
: html`
<ha-attribute-value
.attribute=${attribute.name}
.stateObj=${this._stateObj}
></ha-attribute-value>
`
}
</ha-list-item-value>
`
);
}
private _renderFeatures(
featureEnum: FeatureEnum,
stateObj: HassEntityState
): string {
return (
Object.entries(featureEnum)
.filter(([_key, value]) => typeof value === "number")
.map(([key, value]) =>
supportsFeature(stateObj, value as number)
? titleCase(key.replaceAll("_", " ").toLowerCase())
: undefined
)
.filter(Boolean)
.join(", ") || this.hass.localize("ui.common.none")
);
}
static styles: CSSResultGroup = css`
:host {
display: flex;
@@ -302,46 +40,6 @@ class HaMoreInfoDetails extends LitElement {
padding: var(--ha-space-6);
padding-bottom: max(var(--safe-area-inset-bottom), var(--ha-space-6));
}
ha-grouped-list + ha-grouped-list {
margin-top: var(--ha-space-6);
}
ha-list-item-button {
--ha-row-item-padding-block: var(--ha-space-2);
--ha-row-item-min-height: 40px;
--ha-row-item-gap: var(--ha-space-3);
--mdc-icon-size: 20px;
}
.link-row {
display: flex;
flex-direction: row;
align-items: center;
gap: var(--ha-space-3);
}
.link-row .label {
flex: 1;
color: var(--secondary-text-color);
}
.link-row .value {
max-width: 60%;
min-width: 0;
text-align: end;
overflow-wrap: anywhere;
}
ha-svg-icon.copy-success {
color: var(--success-color);
}
.empty {
color: var(--secondary-text-color);
text-align: center;
padding: var(--ha-space-3) var(--ha-space-4);
}
`;
}
@@ -1097,8 +1097,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
: this._currView === "details"
? html`
<ha-more-info-details
.hass=${this.hass}
.entry=${this._entry}
.params=${{ entityId }}
.yamlMode=${this._detailsYamlMode}
></ha-more-info-details>
+4 -9
View File
@@ -14,10 +14,7 @@ import { isExternal } from "../data/external";
import { fetchConfig } from "../data/lovelace/config/types";
import { fetchResources } from "../data/lovelace/resource";
import { MAIN_WINDOW_NAME } from "../data/main_window";
import {
getPreloadDashboardUrlPath,
type WindowWithPreloads,
} from "../data/preloads";
import type { WindowWithPreloads } from "../data/preloads";
import { getRecorderInfo } from "../data/recorder";
import { subscribeRepairsIssueRegistry } from "../data/repairs";
import { subscribeAreaRegistry } from "../data/ws-area_registry";
@@ -196,11 +193,9 @@ window.hassConnection.then(({ conn }) => {
preloadWindow.recorderInfoProm = getRecorderInfo(conn);
// "/" opens the default panel, which is not known yet, so only preload the
// config when a dashboard is opened directly.
const dashboardUrlPath = getPreloadDashboardUrlPath(location.pathname);
if (dashboardUrlPath) {
preloadWindow.llConfUrlPath = dashboardUrlPath;
preloadWindow.llConfProm = fetchConfig(conn, dashboardUrlPath, false);
// config when the "lovelace" dashboard is opened directly.
if (location.pathname.startsWith("/lovelace/")) {
preloadWindow.llConfProm = fetchConfig(conn, "lovelace", false);
preloadWindow.llConfProm.catch(() => {
// Ignore it, it is handled by Lovelace panel.
});
@@ -0,0 +1,383 @@
import { mdiClose, mdiRefresh } from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { HassEntityState } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, query, state } from "lit/decorators";
import { formatDateTimeWithSeconds } from "../../../../common/datetime/format_date_time";
import { consume } from "../../../../common/decorators/consume";
import type { HASSDomTargetEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import type { HaEntityPicker } from "../../../../components/entity/ha-entity-picker";
import "../../../../components/ha-adaptive-popover";
import "../../../../components/ha-alert";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-svg-icon";
import "../../../../components/ha-yaml-editor";
import type { HaYamlEditor } from "../../../../components/ha-yaml-editor";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import {
apiContext,
configContext,
internationalizationContext,
statesContext,
} from "../../../../data/context";
import { entityHistoryUrl } from "../../../../data/entity/entity_details";
import { DialogMixin } from "../../../../dialogs/dialog-mixin";
import { showConfirmationDialog } from "../../../../dialogs/generic/show-dialog-box";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { PreventUnsavedMixin } from "../../../../mixins/prevent-unsaved-mixin";
import type { ToolsSetStateDialogParams } from "./show-dialog-tools-set-state";
type StateAttributes = HassEntityState["attributes"];
interface SetStateForm {
entityId: string;
state: string;
attributes: StateAttributes;
}
/**
* Sets the state Home Assistant holds for an entity, without telling the
* device. Opened from the States tool, anchored to the button that opened it.
*/
@customElement("dialog-tools-set-state")
export class DialogToolsSetState extends PreventUnsavedMixin(
DirtyStateProviderMixin<SetStateForm>()(
DialogMixin<ToolsSetStateDialogParams>(LitElement)
)
) {
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
private _config!: ContextType<typeof configContext>;
@state()
@consume({ context: statesContext, subscribe: true })
private _states!: ContextType<typeof statesContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state() private _entityId = "";
@state() private _state = "";
@state() private _attributes: StateAttributes = {};
@state() private _validYaml = true;
@state() private _error?: string;
@state() private _saving = false;
@query("ha-yaml-editor") private _yamlEditor?: HaYamlEditor;
public connectedCallback() {
super.connectedCallback();
this._loadEntity(this.params?.entityId ?? "");
}
protected firstUpdated(): void {
// The editor only exists once rendered, after the form was loaded
this._yamlEditor?.setValue(this._attributes);
}
public async closeDialog() {
if (this.isDirtyState && !(await this._confirmDiscard())) {
return false;
}
return super.closeDialog();
}
// Replaces the dialog's own close button, which closes without asking
private _closeClicked() {
this.closeDialog();
}
protected async promptDiscardChanges(): Promise<boolean> {
return this._confirmDiscard();
}
protected render() {
const stateObj: HassEntityState | undefined = this._entityId
? this._states[this._entityId]
: undefined;
return html`<ha-adaptive-popover
.dialogAnchor=${this.dialogAnchor}
open
width="medium"
.headerTitle=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.set_state"
)}
.preventScrimClose=${this.isDirtyState}
>
<ha-icon-button
slot="headerNavigationIcon"
.label=${this._i18n.localize("ui.common.close")}
.path=${mdiClose}
@click=${this._closeClicked}
></ha-icon-button>
<div class="content">
<ha-alert alert-type="info">
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.description1"
)}
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.description2"
)}
</ha-alert>
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<ha-entity-picker
.value=${this._entityId}
@value-changed=${this._entityPicked}
show-entity-id
></ha-entity-picker>
${
stateObj
? html`<dl class="current">
<dt>
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.current_state"
)}
</dt>
<dd><code>${stateObj.state}</code></dd>
<dt>
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.last_changed"
)}
</dt>
<dd>
<a
href=${entityHistoryUrl(
stateObj.entity_id,
stateObj.last_changed
)}
>${this._formatTimestamp(stateObj.last_changed)}</a
>
</dd>
<dt>
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.last_updated"
)}
</dt>
<dd>
<a
href=${entityHistoryUrl(
stateObj.entity_id,
stateObj.last_updated
)}
>${this._formatTimestamp(stateObj.last_updated)}</a
>
</dd>
</dl>`
: nothing
}
<ha-input
.label=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.state"
)}
required
autocapitalize="none"
autocomplete="off"
.autocorrect=${false}
.spellcheck=${false}
.value=${this._state}
@input=${this._stateChanged}
></ha-input>
<p class="label">
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.state_attributes"
)}
</p>
<ha-yaml-editor
.value=${this._attributes}
@value-changed=${this._yamlChanged}
dir="ltr"
></ha-yaml-editor>
</div>
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
slot="secondaryAction"
.disabled=${!stateObj}
@click=${this._refresh}
>
<ha-svg-icon slot="start" .path=${mdiRefresh}></ha-svg-icon>
${this._i18n.localize("ui.common.refresh")}
</ha-button>
<ha-button
slot="primaryAction"
.disabled=${!this._entityId || !this._validYaml}
.loading=${this._saving}
@click=${this._setState}
>
${this._i18n.localize("ui.panel.config.tools.tabs.states.set_state")}
</ha-button>
</ha-dialog-footer>
</ha-adaptive-popover>`;
}
private _form(): SetStateForm {
return {
entityId: this._entityId,
state: this._state,
attributes: this._attributes,
};
}
/** Load an entity's current state into the form, as the new baseline. */
private _loadEntity(entityId: string) {
const stateObj = entityId ? this._states?.[entityId] : undefined;
this._entityId = entityId;
this._state = stateObj?.state ?? "";
this._attributes = { ...stateObj?.attributes };
this._validYaml = true;
this._error = undefined;
this._yamlEditor?.setValue(this._attributes);
this._initDirtyTracking({ type: "deep" }, this._form());
}
private _formatTimestamp(value: string) {
return formatDateTimeWithSeconds(
new Date(value),
this._i18n.locale,
this._config.config
);
}
private async _entityPicked(ev: HASSDomTargetEvent<HaEntityPicker>) {
const picker = ev.target;
const entityId = picker.value ?? "";
if (entityId === this._entityId) {
return;
}
if (this.isDirtyState && !(await this._confirmDiscard())) {
// Put the picker back on the entity being edited
picker.value = this._entityId;
return;
}
this._loadEntity(entityId);
}
private _refresh() {
this._loadEntity(this._entityId);
}
private _stateChanged(ev: HASSDomTargetEvent<HaInput>) {
this._state = ev.target.value ?? "";
this._updateDirtyState(this._form());
}
private _yamlChanged(
ev: CustomEvent<{ value: StateAttributes; isValid: boolean }>
) {
this._validYaml = ev.detail.isValid;
if (ev.detail.isValid) {
this._attributes = ev.detail.value ?? {};
this._updateDirtyState(this._form());
}
}
private async _setState() {
this._error = undefined;
this._saving = true;
try {
await this._api.callApi("POST", `states/${this._entityId}`, {
state: this._state,
attributes: this._attributes,
});
// The form stays open so a state can be set again, as the panel did
this._markDirtyStateClean();
} catch (err: any) {
this._error =
err?.body?.message ||
this._i18n.localize("ui.panel.config.tools.tabs.states.set_failed");
} finally {
this._saving = false;
}
}
private _confirmDiscard(): Promise<boolean> {
return showConfirmationDialog(this, {
title: this._i18n.localize(
"ui.panel.config.tools.tabs.states.discard_title"
),
text: this._i18n.localize(
"ui.panel.config.tools.tabs.states.discard_text"
),
confirmText: this._i18n.localize("ui.common.leave"),
dismissText: this._i18n.localize("ui.common.stay"),
destructive: true,
});
}
static styles = css`
.content {
display: flex;
flex-direction: column;
gap: var(--ha-space-3);
}
.current {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: var(--ha-space-1) var(--ha-space-3);
margin: 0;
padding: var(--ha-space-2) var(--ha-space-3);
border-radius: var(--ha-border-radius-md);
background-color: var(--ha-color-fill-neutral-quiet-resting);
font-size: var(--ha-font-size-s);
}
.current dt {
color: var(--secondary-text-color);
}
.current dd {
margin: 0;
min-width: 0;
overflow-wrap: anywhere;
}
code {
font-family: var(--ha-font-family-code);
}
a {
color: var(--primary-color);
text-decoration: none;
}
.label {
margin: 0;
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"dialog-tools-set-state": DialogToolsSetState;
}
}
@@ -0,0 +1,25 @@
import { fireEvent } from "../../../../common/dom/fire_event";
export interface ToolsSetStateDialogParams {
/** The entity to load into the form, if any. */
entityId?: string;
}
export const loadToolsSetStateDialog = () => import("./dialog-tools-set-state");
/**
* Open the Set state popover, anchored to the button that opened it on wide
* screens. On narrow screens it opens as a bottom sheet.
*/
export const showToolsSetStateDialog = (
element: HTMLElement,
dialogParams: ToolsSetStateDialogParams,
dialogAnchor?: Element
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-tools-set-state",
dialogImport: loadToolsSetStateDialog,
dialogParams,
dialogAnchor,
});
};
@@ -0,0 +1,191 @@
import type { ContextType } from "@lit/context";
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import {
fireEvent,
type HASSDomCurrentTargetEvent,
} from "../../../../common/dom/fire_event";
import "../../../../components/ha-generic-picker";
import type { PickerComboBoxItem } from "../../../../components/ha-picker-combo-box";
import "../../../../components/input/ha-input-search";
import type { HaInputSearch } from "../../../../components/input/ha-input-search";
import type { LocalizeKeys } from "../../../../common/translations/localize";
import { internationalizationContext } from "../../../../data/context";
import {
STATE_COLUMN_FILTER_KEYS,
type StateColumnFilters,
} from "./tools-state-filter";
/** The values in the list, offered by the State, Device and Area pickers. */
export interface StateColumnFilterOptions {
state: string[];
device: string[];
area: string[];
}
export type StateColumnFilterField = keyof StateColumnFilters | "spacer";
const PICKER_FIELDS = ["state", "device", "area"] as const;
type PickerField = (typeof PICKER_FIELDS)[number];
const isPickerField = (field: StateColumnFilterField): field is PickerField =>
PICKER_FIELDS.some((picker) => picker === field);
/**
* The States tool's Columns mode filters. Entity and Attributes take typed
* text; State, Device and Area offer the values in the list and still take
* typed text, so `*` wildcards keep working.
*
* @fires tools-state-column-filters-changed - With all the filters, when one changes.
*/
@customElement("tools-state-column-filters")
export class ToolsStateColumnFilters extends LitElement {
@property({ attribute: false }) public filters: StateColumnFilters = {};
@property({ attribute: false }) public options: StateColumnFilterOptions = {
state: [],
device: [],
area: [],
};
/** The fields to show, in order. `spacer` leaves an empty grid cell. */
@property({ attribute: false }) public fields: StateColumnFilterField[] = [
"entity",
"state",
"device",
"area",
"attribute",
];
/**
* `grid` places each field in the parent's grid, `line` puts them in a row,
* and `vertical` stacks them.
*/
@property({ reflect: true }) public layout: "grid" | "line" | "vertical" =
"vertical";
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
private _toItems = (values: string[]): PickerComboBoxItem[] =>
values.map((value) => ({ id: value, primary: value }));
// One memoised list per picker, so each keeps its items between renders
private _items: Record<
PickerField,
(values: string[]) => PickerComboBoxItem[]
> = {
state: memoizeOne(this._toItems),
device: memoizeOne(this._toItems),
area: memoizeOne(this._toItems),
};
private _getItems: Record<PickerField, () => PickerComboBoxItem[]> = {
state: () => this._items.state(this.options.state),
device: () => this._items.device(this.options.device),
area: () => this._items.area(this.options.area),
};
private _label(field: keyof StateColumnFilters): string {
const labels: Record<keyof StateColumnFilters, LocalizeKeys> = {
entity: "ui.panel.config.tools.tabs.states.entity",
state: "ui.panel.config.tools.tabs.states.state",
device: "ui.components.entity_details.device",
area: "ui.components.entity_details.area",
attribute: "ui.panel.config.tools.tabs.states.filter_attributes",
};
return this._i18n.localize(labels[field]);
}
protected render() {
return this.fields.map((field) => {
if (field === "spacer") {
return html`<div></div>`;
}
if (isPickerField(field)) {
return html`<ha-generic-picker
allow-custom-value
.label=${this._label(field)}
.value=${this.filters[field] || undefined}
.getItems=${this._getItems[field]}
.customValueLabel=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.filter_custom_value"
)}
data-field=${field}
@value-changed=${this._pickerChanged}
></ha-generic-picker>`;
}
return html`<ha-input-search
.label=${this._label(field)}
.value=${this.filters[field] ?? ""}
data-field=${field}
@input=${this._inputChanged}
></ha-input-search>`;
});
}
private _setFilter(field: string | undefined, value: string | undefined) {
const key = STATE_COLUMN_FILTER_KEYS.find((filter) => filter === field);
if (!key) {
return;
}
fireEvent(this, "tools-state-column-filters-changed", {
filters: { ...this.filters, [key]: value || undefined },
});
}
private _inputChanged(ev: HASSDomCurrentTargetEvent<HaInputSearch>) {
this._setFilter(ev.currentTarget.dataset.field, ev.currentTarget.value);
}
private _pickerChanged(
ev: HASSDomCurrentTargetEvent<HTMLElement> & CustomEvent<{ value?: string }>
) {
ev.stopPropagation();
this._setFilter(ev.currentTarget.dataset.field, ev.detail.value);
}
static styles = css`
:host([layout="grid"]) {
display: contents;
}
:host([layout="line"]) {
display: flex;
flex-wrap: wrap;
gap: var(--ha-space-2);
}
:host([layout="line"]) > * {
flex: 1 1 200px;
}
:host([layout="vertical"]) {
display: flex;
flex-direction: column;
gap: var(--ha-space-3);
}
ha-input-search {
--ha-input-padding-bottom: 0;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"tools-state-column-filters": ToolsStateColumnFilters;
}
interface HASSDomEvents {
"tools-state-column-filters-changed": { filters: StateColumnFilters };
}
}
@@ -0,0 +1,178 @@
import type {
HassEntityState,
HassEntityStates,
} from "home-assistant-js-websocket";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import { computeDeviceName } from "../../../../common/entity/compute_device_name";
import { escapeRegExp } from "../../../../common/string/escape_regexp";
import type {
HomeAssistantFormatters,
HomeAssistantRegistries,
} from "../../../../types";
/** The Columns mode filters, one per column. Empty means no filter. */
export interface StateColumnFilters {
entity?: string;
state?: string;
device?: string;
area?: string;
attribute?: string;
}
export const STATE_COLUMN_FILTER_KEYS = [
"entity",
"state",
"device",
"area",
"attribute",
] as const satisfies readonly (keyof StateColumnFilters)[];
/** A filter that ignores case, with `*` matching anything. */
export const wildcardRegExp = (filter: string): RegExp =>
RegExp(escapeRegExp(filter).replace(/\\\*/g, ".*"), "i");
export const countColumnFilters = (filters: StateColumnFilters): number =>
STATE_COLUMN_FILTER_KEYS.filter((key) => filters[key]).length;
/** The device of an entity, from the entity registry. */
export const entityDevice = (
entityId: string,
registries: Pick<HomeAssistantRegistries, "entities" | "devices">
) => {
const entry = registries.entities[entityId];
return entry?.device_id ? registries.devices[entry.device_id] : undefined;
};
/** The area of an entity, or of its device when the entity has none. */
export const entityArea = (
entityId: string,
registries: Pick<HomeAssistantRegistries, "entities" | "devices" | "areas">
) => {
const areaId =
registries.entities[entityId]?.area_id ||
entityDevice(entityId, registries)?.area_id;
return areaId ? registries.areas[areaId] : undefined;
};
/**
* The States tool's column filters. Every filter ignores case and takes `*`
* as a wildcard. Entity matches the entity ID or the name: the entity's own
* name while the device column shows, otherwise the full name. Attributes
* match a name with `key`, or a name and its value as JSON with
* `key:value`. Sorted by entity ID.
*/
export const filterStatesByColumns = (
states: HassEntityStates,
filters: StateColumnFilters,
formatEntityName: HomeAssistantFormatters["formatEntityName"],
registries: Pick<HomeAssistantRegistries, "entities" | "devices" | "areas">,
deviceColumnShown: boolean
): HassEntityState[] => {
const entityFilterRegExp = filters.entity && wildcardRegExp(filters.entity);
const stateFilterRegExp = filters.state && wildcardRegExp(filters.state);
const deviceFilterRegExp = filters.device && wildcardRegExp(filters.device);
const areaFilterRegExp = filters.area && wildcardRegExp(filters.area);
let keyFilterRegExp: RegExp | undefined;
let valueFilterRegExp: RegExp | undefined;
let multiMode = false;
if (filters.attribute) {
const colonIndex = filters.attribute.indexOf(":");
multiMode = colonIndex !== -1;
const keyFilter = multiMode
? filters.attribute.substring(0, colonIndex).trim()
: filters.attribute;
const valueFilter = multiMode
? filters.attribute.substring(colonIndex + 1).trim()
: filters.attribute;
keyFilterRegExp = wildcardRegExp(keyFilter);
valueFilterRegExp = multiMode
? wildcardRegExp(valueFilter)
: keyFilterRegExp;
}
return Object.values(states)
.filter((value) => {
if (
entityFilterRegExp &&
!entityFilterRegExp.test(value.entity_id) &&
!entityFilterRegExp.test(
formatEntityName(
value,
deviceColumnShown ? { type: "entity" } : undefined
)
)
) {
return false;
}
if (stateFilterRegExp && !stateFilterRegExp.test(value.state)) {
return false;
}
if (deviceFilterRegExp) {
const device = entityDevice(value.entity_id, registries);
const deviceName = device ? computeDeviceName(device) : undefined;
if (!deviceName || !deviceFilterRegExp.test(deviceName)) {
return false;
}
}
if (areaFilterRegExp) {
const area = entityArea(value.entity_id, registries);
const areaName = area ? computeAreaName(area) : undefined;
if (!areaName || !areaFilterRegExp.test(areaName)) {
return false;
}
}
if (keyFilterRegExp && valueFilterRegExp) {
for (const [key, attributeValue] of Object.entries(value.attributes)) {
const match = keyFilterRegExp.test(key);
if (match && !multiMode) {
// In single mode a matching name is enough
return true;
}
if (!match && multiMode) {
continue;
}
if (
attributeValue !== undefined &&
valueFilterRegExp.test(JSON.stringify(attributeValue))
) {
return true;
}
}
// No attribute matches the name and, with key:value, the value
return false;
}
return true;
})
.sort((entityA, entityB) => {
if (entityA.entity_id < entityB.entity_id) {
return -1;
}
if (entityA.entity_id > entityB.entity_id) {
return 1;
}
return 0;
});
};
@@ -0,0 +1,328 @@
import { ResizeController } from "@lit-labs/observers/resize-controller";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing, type TemplateResult } from "lit";
import { customElement, property, query } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { EntityDetailsDisplay } from "../../../../components/entity/ha-entity-details";
import "../../../../components/item/ha-list-item-base";
import "../../../../components/list/ha-list-virtualized";
import type {
HaListVirtualized,
HaListVirtualizedItem,
} from "../../../../components/list/ha-list-virtualized";
import { internationalizationContext } from "../../../../data/context";
import "./tools-state-column-filters";
import type {
StateColumnFilterField,
StateColumnFilterOptions,
} from "./tools-state-column-filters";
import type { StateColumnFilters } from "./tools-state-filter";
import "./tools-state-row";
import type { StateListColumns, StateRow } from "./tools-state-row";
export type { StateListColumns, StateRow } from "./tools-state-row";
// The list needs this much width before it shows each optional column
const COLUMN_MIN_WIDTH: Record<keyof StateListColumns, number> = {
area: 600,
device: 900,
lastChanged: 1100,
};
/**
* The States tool's list: a header with the column names, and one
* virtualised row per entity, which opens to show its details.
*
* @fires tools-state-toggle - A row was opened or closed, from Enter on a row.
*/
@customElement("tools-state-list")
export class ToolsStateList extends LitElement {
@property({ attribute: false }) public rows: StateRow[] = [];
@property({ attribute: false }) public expanded: ReadonlySet<string> =
new Set();
@property() public display: EntityDetailsDisplay = "both";
@property({ type: Boolean, attribute: "yaml-mode" }) public yamlMode = false;
/** The columns turned on in the View menu. */
@property({ attribute: false }) public columns: StateListColumns = {
device: true,
area: true,
lastChanged: false,
};
@property({ type: Boolean, reflect: true }) public narrow = false;
/** A row to scroll to when the list first shows, like one a link opens. */
@property({ attribute: false }) public pinnedId?: string;
/** The Columns mode filters, shown in the header on wide screens. */
@property({ attribute: false }) public columnFilters?: StateColumnFilters;
@property({ attribute: false })
public columnFilterOptions: StateColumnFilterOptions = {
state: [],
device: [],
area: [],
};
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@query("ha-list-virtualized") private _virtualList?: HaListVirtualized;
private _width = new ResizeController(this, {
callback: (entries) => entries[0]?.contentRect.width ?? 0,
});
/**
* The optional columns that show, given the View menu and the list's
* width, so a tablet that counts as narrow still shows what fits.
*/
private _shownColumns = memoizeOne(
(columns: StateListColumns, width: number): StateListColumns => ({
device: columns.device && width >= COLUMN_MIN_WIDTH.device,
area: columns.area && width >= COLUMN_MIN_WIDTH.area,
lastChanged: columns.lastChanged && width >= COLUMN_MIN_WIDTH.lastChanged,
})
);
private _gridColumns = memoizeOne(
(shown: StateListColumns, narrow: boolean): string =>
[
narrow ? "32px" : "40px",
"minmax(0, 2.2fr)",
"minmax(0, 1fr)",
shown.device ? "minmax(0, 1.4fr)" : undefined,
shown.area ? "minmax(0, 1fr)" : undefined,
shown.lastChanged ? "minmax(0, 1fr)" : undefined,
// Narrow screens put the row's buttons in the open row instead
narrow ? undefined : "120px",
]
.filter(Boolean)
.join(" ")
);
private _pinIndex = memoizeOne(
(rows: StateRow[], pinnedId: string | undefined): number | undefined => {
const index = pinnedId
? rows.findIndex((row) => row.id === pinnedId)
: -1;
// The first row is already in view, and pinning it misplaces it once
// it opens
return index > 0 ? index : undefined;
}
);
private _rowsById = memoizeOne(
(rows: StateRow[]) => new Map(rows.map((row) => [row.id, row]))
);
protected render() {
const shown = this._shownColumns(this.columns, this._width.value ?? 0);
const style = styleMap({
"--tools-state-columns": this._gridColumns(shown, this.narrow),
});
const localize = this._i18n.localize;
return html`
<div class="header" style=${style}>
<div class="grid">
<div></div>
<div>${localize("ui.panel.config.tools.tabs.states.entity")}</div>
<div>${localize("ui.panel.config.tools.tabs.states.state")}</div>
${
shown.device
? html`<div>
${localize("ui.components.entity_details.device")}
</div>`
: nothing
}
${
shown.area
? html`<div>
${localize("ui.components.entity_details.area")}
</div>`
: nothing
}
${
shown.lastChanged
? html`<div>
${localize("ui.panel.config.tools.tabs.states.last_changed")}
</div>`
: nothing
}
${this.narrow ? nothing : html`<div></div>`}
</div>
${
this.columnFilters && !this.narrow
? this._renderColumnFilters(shown, this.columnFilters)
: nothing
}
</div>
${
this.rows.length
? html`<ha-list-virtualized
style=${style}
pin-block="start"
.pinIndex=${this._pinIndex(this.rows, this.pinnedId)}
.rows=${this.rows}
.rowRenderer=${this._renderRow(shown)}
@ha-list-activated=${this._rowActivated}
></ha-list-virtualized>`
: html`<div class="empty">
${localize("ui.panel.config.tools.tabs.states.no_matches")}
</div>`
}
`;
}
protected updated() {
// Rows read `expanded`, `display` and the columns, which are not part of
// `rows`
this._virtualList?.requestRowsUpdate();
}
// Filters for shown columns sit under their headings; Attributes and the
// filters of hidden columns go on a line below
private _renderColumnFilters(
shown: StateListColumns,
filters: StateColumnFilters
) {
const gridFields: StateColumnFilterField[] = [
"spacer",
"entity",
"state",
...(shown.device ? (["device"] as const) : []),
...(shown.area ? (["area"] as const) : []),
...(shown.lastChanged ? (["spacer"] as const) : []),
"spacer",
];
const lineFields: StateColumnFilterField[] = [
"attribute",
...(shown.device ? [] : (["device"] as const)),
...(shown.area ? [] : (["area"] as const)),
];
return html`<div class="grid filters">
<tools-state-column-filters
layout="grid"
.fields=${gridFields}
.filters=${filters}
.options=${this.columnFilterOptions}
></tools-state-column-filters>
</div>
<tools-state-column-filters
class="filter-line"
layout="line"
.fields=${lineFields}
.filters=${filters}
.options=${this.columnFilterOptions}
></tools-state-column-filters>`;
}
// A new function when the shown columns change, so rows render again
private _renderRow = memoizeOne(
(shown: StateListColumns) =>
(item: HaListVirtualizedItem): TemplateResult | typeof nothing => {
const row = this._rowsById(this.rows).get(item.id);
if (!row) {
return nothing;
}
return html`<ha-list-item-base interactive data-entity-id=${row.id}>
<tools-state-row
slot="content"
.row=${row}
.open=${this.expanded.has(row.id)}
.display=${this.display}
.yamlMode=${this.yamlMode}
.columns=${shown}
.narrow=${this.narrow}
></tools-state-row>
</ha-list-item-base>`;
}
);
private _rowActivated(ev: CustomEvent<{ item: HTMLElement }>) {
const entityId = ev.detail.item.dataset.entityId;
if (entityId) {
fireEvent(this, "tools-state-toggle", { entityId });
}
}
static styles = css`
:host {
display: flex;
flex-direction: column;
min-height: 0;
background-color: var(--card-background-color);
border: 1px solid var(--divider-color);
border-radius: var(--ha-border-radius-lg);
overflow: hidden;
}
.header {
flex: none;
border-bottom: 1px solid var(--divider-color);
font-size: var(--ha-font-size-s);
font-weight: var(--ha-font-weight-medium);
color: var(--secondary-text-color);
}
.grid {
display: grid;
grid-template-columns: var(--tools-state-columns);
align-items: center;
column-gap: var(--ha-space-2);
padding-inline: var(--ha-space-2);
min-height: 40px;
}
:host([narrow]) .grid {
padding-inline: var(--ha-space-1) var(--ha-space-2);
}
.filters {
align-items: end;
padding-block-end: var(--ha-space-2);
}
.filter-line {
padding: 0 var(--ha-space-2) var(--ha-space-2) 48px;
}
ha-list-virtualized {
flex: 1;
min-height: 0;
/* The rows lay themselves out */
--ha-row-item-padding-block: 0;
--ha-row-item-padding-inline: 0;
--ha-row-item-gap: 0;
--ha-row-item-min-height: 0;
}
.empty {
padding: var(--ha-space-6) var(--ha-space-4);
text-align: center;
color: var(--secondary-text-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"tools-state-list": ToolsStateList;
}
}
@@ -1,465 +0,0 @@
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import {
mdiClipboardTextMultipleOutline,
mdiInformationOutline,
} from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { HassEntityState } from "home-assistant-js-websocket";
import { dump } from "js-yaml";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { consume } from "../../../../common/decorators/consume";
import { transform } from "../../../../common/decorators/transform";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import { computeDeviceName } from "../../../../common/entity/compute_device_name";
import { copyToClipboard } from "../../../../common/util/copy-clipboard";
import "../../../../components/ha-svg-icon";
import {
formattersContext,
internationalizationContext,
registriesContext,
} from "../../../../data/context";
import { haStyle } from "../../../../resources/styles";
import { loadVirtualizer } from "../../../../resources/virtualizer";
import { showToast } from "../../../../util/toast";
import type { HomeAssistantFormatters } from "../../../../types";
@customElement("tools-state-renderer")
class HaPanelDevStateRenderer extends LitElement {
@property({ attribute: false }) public entities: HassEntityState[] = [];
@property({ type: Boolean, attribute: "narrow" })
public narrow = false;
@property({ type: Boolean, attribute: "virtualize", reflect: true })
public virtualize = true;
@property({ attribute: false })
public showAttributes = true;
@property({ attribute: false })
public showDevice = true;
@property({ attribute: false })
public showArea = true;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (
(!this.hasUpdated && this.virtualize) ||
(changedProps.has("virtualize") && this.virtualize)
) {
loadVirtualizer();
}
}
protected render() {
const showAttributes = !this.narrow && this.showAttributes;
const showDevice = !this.narrow && this.showDevice;
const showArea = !this.narrow && this.showArea;
return html`
<div
class=${classMap({
entities: true,
"hide-attributes": !showAttributes,
"hide-device": !showDevice,
"hide-area": !showArea,
"hide-extra": this.narrow,
})}
role="table"
>
<div class="row" role="row" aria-rowindex="1">
<div class="header" role="columnheader">
<span class="padded">
${this._i18n.localize("ui.panel.config.tools.tabs.states.entity")}
</span>
</div>
<div class="header" role="columnheader">
<span class="padded">
${this._i18n.localize("ui.panel.config.tools.tabs.states.state")}
</span>
</div>
<div class="header" role="columnheader" ?hidden=${!showDevice}>
<span class="padded">
${this._i18n.localize(
"ui.panel.config.entities.picker.headers.device"
)}
</span>
</div>
<div class="header" role="columnheader" ?hidden=${!showArea}>
<span class="padded">
${this._i18n.localize("ui.panel.config.generic.headers.area")}
</span>
</div>
<div class="header" role="columnheader">
<span class="padded">
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.attributes"
)}
</span>
</div>
</div>
<div class="row filters" role="row" aria-rowindex="2">
<div class="header filter-entities" role="columnheader">
<slot name="filter-entities"></slot>
</div>
<div class="header filter-states" role="columnheader">
<slot name="filter-states"></slot>
</div>
<div class="header filter-devices" role="columnheader">
<slot name="filter-devices"></slot>
</div>
<div class="header filter-areas" role="columnheader">
<slot name="filter-areas"></slot>
</div>
<div class="header filter-attributes" role="columnheader">
<slot name="filter-attributes"></slot>
</div>
</div>
${
this.entities.length === 0
? html` <div class="row" role="row" aria-rowindex="3">
<div class="cell" role="cell" aria-colspan="5">
<span class="padded">
${this._i18n.localize(
"ui.panel.config.tools.tabs.states.no_entities"
)}
</span>
</div>
</div>`
: nothing
}
${
this.virtualize
? html`<lit-virtualizer
.items=${this.entities}
.renderItem=${this._renderStateItem}
>
</lit-virtualizer>`
: this.entities.map((item, index) =>
this._renderStateItem(item, index)
)
}
</div>
`;
}
private _renderStateItem: RenderItemFunction<HassEntityState> = (
item: HassEntityState,
index: number
): TemplateResult | any => {
if (!item || index === undefined) {
return nothing;
}
const entry = this._registries?.entities?.[item.entity_id];
const device = entry?.device_id
? this._registries?.devices?.[entry.device_id]
: undefined;
const areaId = entry?.area_id || device?.area_id;
const area = areaId ? this._registries?.areas?.[areaId] : undefined;
const deviceName = device ? computeDeviceName(device) : undefined;
const areaName = area ? computeAreaName(area) : undefined;
return html`
<div
class=${classMap({
row: true,
odd: index % 2 === 0,
even: index % 2 !== 0,
})}
role="row"
aria-rowindex=${index + 3}
>
<div class="cell" role="cell">
<span class="padded">
<div class="id-name-container">
<div class="id-name-row">
<ha-svg-icon
@click=${this._copyEntity}
.entity=${item}
alt=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.copy_id"
)}
title=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.copy_id"
)}
.path=${mdiClipboardTextMultipleOutline}
></ha-svg-icon>
<a href="#" .entity=${item} @click=${this._entitySelected}
>${item.entity_id}</a
>
</div>
<div class="id-name-row">
<ha-svg-icon
@click=${this._entityMoreInfo}
.entity=${item}
alt=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.more_info"
)}
title=${this._i18n.localize(
"ui.panel.config.tools.tabs.states.more_info"
)}
.path=${mdiInformationOutline}
></ha-svg-icon>
<span class="secondary">
${this._formatEntityName(item, { type: "entity" })}
</span>
</div>
</div>
</span>
</div>
<div class="cell" role="cell">
<span class="padded">${item.state}</span>
</div>
<div class="cell" role="cell">
<span class="padded">${deviceName || "\u2014"}</span>
</div>
<div class="cell" role="cell">
<span class="padded">${areaName || "\u2014"}</span>
</div>
<div class="cell" role="cell">
<span class="padded">${this._attributeString(item)}</span>
</div>
</div>
`;
};
private _formatAttributeValue(value) {
if (
(Array.isArray(value) && value.some((val) => val instanceof Object)) ||
(!Array.isArray(value) && value instanceof Object)
) {
return `\n${dump(value)}`;
}
return Array.isArray(value) ? value.join(", ") : value;
}
private _attributeString(entity) {
const output = "";
if (entity && entity.attributes) {
return Object.keys(entity.attributes).map(
(key) =>
`${key}: ${this._formatAttributeValue(entity.attributes[key])}\n`
);
}
return output;
}
private _copyEntity = async (
ev: HASSDomCurrentTargetEvent<HTMLElement & { entity: HassEntityState }>
) => {
ev.preventDefault();
const entity = (
ev.currentTarget as HTMLElement & { entity: HassEntityState }
).entity;
await copyToClipboard(entity.entity_id, document.body);
showToast(this, {
message: this._i18n.localize("ui.common.copied_clipboard"),
});
};
private _entityMoreInfo(
ev: HASSDomCurrentTargetEvent<HTMLElement & { entity: HassEntityState }>
) {
ev.preventDefault();
const entity = (
ev.currentTarget as HTMLElement & { entity: HassEntityState }
).entity;
fireEvent(this, "hass-more-info", { entityId: entity.entity_id });
}
private _entitySelected(
ev: HASSDomCurrentTargetEvent<HTMLElement & { entity: HassEntityState }>
) {
ev.preventDefault();
const entity = (
ev.currentTarget as HTMLElement & { entity: HassEntityState }
).entity;
fireEvent(this, "states-tool-entity-selected", {
entity,
});
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host([virtualize]) {
display: block;
height: 100%;
overflow: auto;
}
.entities {
width: 100%;
}
.entities .row {
display: flex;
width: 100%;
}
.entities .odd .cell {
background-color: var(--table-row-background-color, #fff);
}
.entities .even .cell {
background-color: var(--table-row-alternative-background-color, #eee);
}
.header,
.cell {
min-width: 200px;
flex: 1;
display: flex;
margin: 0 1px 0 1px;
}
.header {
font-weight: bold;
text-align: var(--float-start);
direction: var(--direction);
}
.header .padded {
padding: 0 8px;
}
.filters .header {
background-color: var(--table-row-alternative-background-color, #eee);
--mdc-text-field-fill-color: var(
--table-row-alternative-background-color,
#eee
);
}
.cell {
word-break: break-word;
vertical-align: top;
direction: ltr;
}
.cell .padded {
padding: var(--ha-space-1);
}
.entities .row .header:nth-child(1),
.entities .row .cell:nth-child(1) {
min-width: 300px;
width: 30%;
flex: 2;
}
.entities .row .header:nth-child(5),
.entities .row .cell:nth-child(5) {
flex: 2;
}
.entities .row .cell:nth-child(5) {
white-space: pre-wrap;
}
.hide-device .filter-devices {
display: none;
}
.hide-device .row .header:nth-child(3),
.hide-device .row .cell:nth-child(3) {
display: none;
}
.hide-area .filter-areas {
display: none;
}
.hide-area .row .header:nth-child(4),
.hide-area .row .cell:nth-child(4) {
display: none;
}
.hide-attributes .filter-attributes {
display: none;
}
.hide-attributes .row .header:nth-child(5),
.hide-attributes .row .cell:nth-child(5) {
display: none;
}
.hide-extra .row .header:nth-child(3),
.hide-extra .row .cell:nth-child(3),
.hide-extra .row .header:nth-child(4),
.hide-extra .row .cell:nth-child(4) {
display: none;
}
.hide-extra .filter-devices,
.hide-extra .filter-areas {
display: none;
}
.entities ha-svg-icon {
--mdc-icon-size: 20px;
padding: var(--ha-space-1);
cursor: pointer;
flex-shrink: 0;
margin-right: var(--ha-space-2);
margin-inline-end: var(--ha-space-2);
margin-inline-start: initial;
}
.entities a {
color: var(--primary-color);
}
.entities .id-name-container {
display: flex;
flex-direction: column;
}
.entities .id-name-row {
display: flex;
align-items: center;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"tools-state-renderer": HaPanelDevStateRenderer;
}
interface HASSDomEvents {
"states-tool-entity-selected": {
entity: Partial<HassEntityState>;
};
}
}
@@ -0,0 +1,458 @@
import type { ContextType } from "@lit/context";
import {
mdiChevronDown,
mdiChevronRight,
mdiCodeBraces,
mdiContentCopy,
mdiFormatListBulleted,
mdiHistory,
mdiInformationOutline,
mdiPencil,
} from "@mdi/js";
import type { HassEntityState } from "home-assistant-js-websocket";
import { dump } from "js-yaml";
import { css, html, LitElement, nothing, type TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import {
fireEvent,
type HASSDomCurrentTargetEvent,
} from "../../../../common/dom/fire_event";
import { isInteractiveElement } from "../../../../common/dom/is-interactive-element";
import { copyToClipboard } from "../../../../common/util/copy-clipboard";
import "../../../../components/entity/ha-entity-details";
import type { EntityDetailsDisplay } from "../../../../components/entity/ha-entity-details";
import "../../../../components/ha-button";
import "../../../../components/ha-button-toggle-group";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-relative-time";
import "../../../../components/ha-svg-icon";
import type { HaListVirtualizedItem } from "../../../../components/list/ha-list-virtualized";
import {
formattersContext,
internationalizationContext,
} from "../../../../data/context";
import { entityHistoryUrl } from "../../../../data/entity/entity_details";
import { showToast } from "../../../../util/toast";
/** One row of the States tool's list. */
export interface StateRow extends HaListVirtualizedItem {
/** The entity ID, which keys the row. */
id: string;
interactive: true;
stateObj: HassEntityState;
/** The name shown in the Entity column. */
name: string;
device?: string;
area?: string;
}
/** Which optional columns show. */
export interface StateListColumns {
device: boolean;
area: boolean;
lastChanged: boolean;
}
/**
* One entity in the States tool's list: its columns, its buttons and, when
* open, its details. Laid out on the list's `--tools-state-columns` grid.
*
* @fires tools-state-toggle - The row was opened or closed.
* @fires tools-state-set-state - Set state was pressed.
* @fires tools-state-yaml-mode - The Visual or YAML switch changed.
*/
@customElement("tools-state-row")
export class ToolsStateRow extends LitElement {
@property({ attribute: false }) public row!: StateRow;
@property({ type: Boolean, reflect: true }) public open = false;
@property() public display: EntityDetailsDisplay = "both";
@property({ type: Boolean, attribute: "yaml-mode" }) public yamlMode = false;
@property({ attribute: false }) public columns: StateListColumns = {
device: true,
area: true,
lastChanged: false,
};
@property({ type: Boolean, reflect: true }) public narrow = false;
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
protected render() {
if (!this.row) {
return nothing;
}
const { stateObj } = this.row;
const localize = this._i18n.localize;
return html`
<div class="grid summary" @click=${this._summaryClicked}>
<ha-icon-button
class="chevron"
.path=${this.open ? mdiChevronDown : mdiChevronRight}
.label=${localize(
this.open
? "ui.panel.config.tools.tabs.states.collapse_row"
: "ui.panel.config.tools.tabs.states.expand_row"
)}
aria-expanded=${this.open ? "true" : "false"}
@click=${this._toggleClicked}
></ha-icon-button>
<div class="cell">${this._renderText(this.row.name, this.row.id)}</div>
<div class="cell">
${this._renderText(
this._formatters.formatEntityState(stateObj),
stateObj.state
)}
</div>
${
this.columns.device
? html`<div class="cell">
${this.row.device || html`<span class="muted">-</span>`}
</div>`
: nothing
}
${
this.columns.area
? html`<div class="cell">
${this.row.area || html`<span class="muted">-</span>`}
</div>`
: nothing
}
${
this.columns.lastChanged
? html`<div class="cell secondary">
<ha-relative-time
.datetime=${stateObj.last_changed}
capitalize
></ha-relative-time>
</div>`
: nothing
}
${this.narrow ? nothing : this._renderActions()}
</div>
${this.open ? this._renderDetails(stateObj) : nothing}
`;
}
private _renderText(main: string, raw: string): TemplateResult {
if (this.display === "raw") {
return html`<code class="single">${raw}</code>`;
}
return html`<div class="two">
<span class="main">${main}</span>
${
this.display === "both" && main !== raw
? html`<code class="raw">${raw}</code>`
: nothing
}
</div>`;
}
private _renderActions() {
const localize = this._i18n.localize;
return html`<div class="actions">
<ha-icon-button
.path=${mdiPencil}
.label=${localize("ui.panel.config.tools.tabs.states.set_state")}
@click=${this._setStateClicked}
></ha-icon-button>
<ha-icon-button
.path=${mdiContentCopy}
.label=${localize("ui.panel.config.tools.tabs.states.copy_id")}
@click=${this._copyIdClicked}
></ha-icon-button>
<ha-icon-button
.path=${mdiInformationOutline}
.label=${localize("ui.panel.config.tools.tabs.states.more_info")}
@click=${this._moreInfoClicked}
></ha-icon-button>
</div>`;
}
private _renderDetails(stateObj: HassEntityState) {
const localize = this._i18n.localize;
return html`<div class="details">
<div class="details-bar">
<ha-button-toggle-group
size="s"
?show-labels=${!this.narrow}
no-wrap
.buttons=${[
{
label: localize("ui.panel.config.tools.tabs.states.visual"),
iconPath: mdiFormatListBulleted,
value: "visual",
},
{
label: localize("ui.panel.config.tools.tabs.states.yaml"),
iconPath: mdiCodeBraces,
value: "yaml",
},
]}
.active=${this.yamlMode ? "yaml" : "visual"}
@value-changed=${this._yamlModeChanged}
></ha-button-toggle-group>
<span class="spacer"></span>
${
this.narrow
? html`<ha-button
appearance="outlined"
size="s"
@click=${this._setStateClicked}
>
<ha-svg-icon slot="start" .path=${mdiPencil}></ha-svg-icon>
${localize("ui.panel.config.tools.tabs.states.set_state")}
</ha-button>
<ha-button
appearance="outlined"
size="s"
@click=${this._moreInfoClicked}
>
<ha-svg-icon
slot="start"
.path=${mdiInformationOutline}
></ha-svg-icon>
${localize("ui.panel.config.tools.tabs.states.more_info")}
</ha-button>`
: nothing
}
<ha-button
appearance="outlined"
size="s"
href=${entityHistoryUrl(stateObj.entity_id, stateObj.last_changed)}
>
<ha-svg-icon slot="start" .path=${mdiHistory}></ha-svg-icon>
${localize("ui.panel.config.tools.tabs.states.history")}
</ha-button>
${
this.yamlMode
? html`<ha-button
appearance="outlined"
size="s"
@click=${this._copyYamlClicked}
>
<ha-svg-icon slot="start" .path=${mdiContentCopy}></ha-svg-icon>
${localize("ui.panel.config.tools.tabs.states.copy_yaml")}
</ha-button>`
: nothing
}
</div>
<ha-entity-details
.entityId=${stateObj.entity_id}
.yamlMode=${this.yamlMode}
.display=${this.display}
copy-values
show-registry
show-links
layout="split"
></ha-entity-details>
</div>`;
}
private _toggle() {
fireEvent(this, "tools-state-toggle", { entityId: this.row.id });
}
// Pressing the summary opens the row, unless a button in it was pressed
private _summaryClicked(ev: MouseEvent) {
const summary = ev.currentTarget;
for (const node of ev.composedPath()) {
if (node === summary) {
break;
}
if (isInteractiveElement(node)) {
return;
}
}
this._toggle();
}
private _toggleClicked(ev: MouseEvent) {
ev.stopPropagation();
this._toggle();
}
private _setStateClicked(ev: HASSDomCurrentTargetEvent<HTMLElement>) {
ev.stopPropagation();
fireEvent(this, "tools-state-set-state", {
entityId: this.row.id,
anchor: ev.currentTarget,
});
}
private async _copyIdClicked(ev: MouseEvent) {
ev.stopPropagation();
await copyToClipboard(this.row.id);
showToast(this, {
message: this._i18n.localize("ui.common.copied_clipboard"),
});
}
private _moreInfoClicked(ev: MouseEvent) {
ev.stopPropagation();
fireEvent(this, "hass-more-info", { entityId: this.row.id });
}
private async _copyYamlClicked() {
const { stateObj } = this.row;
await copyToClipboard(
dump({
entity_id: stateObj.entity_id,
state: stateObj.state,
last_changed: stateObj.last_changed,
last_updated: stateObj.last_updated,
attributes: stateObj.attributes,
})
);
showToast(this, {
message: this._i18n.localize("ui.common.copied_clipboard"),
});
}
private _yamlModeChanged(ev: CustomEvent<{ value?: string }>) {
ev.stopPropagation();
fireEvent(this, "tools-state-yaml-mode", {
yamlMode: ev.detail.value === "yaml",
});
}
static styles = css`
:host {
display: block;
width: 100%;
min-width: 0;
border-bottom: 1px solid var(--divider-color);
}
:host([open]) {
background-color: var(--ha-color-fill-neutral-quiet-resting);
}
.grid {
display: grid;
grid-template-columns: var(--tools-state-columns);
align-items: center;
column-gap: var(--ha-space-2);
padding-inline: var(--ha-space-2);
}
:host([narrow]) .grid {
padding-inline: var(--ha-space-1) var(--ha-space-2);
}
.summary {
min-height: 56px;
cursor: pointer;
}
.cell {
min-width: 0;
padding-block: var(--ha-space-2);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.two {
display: flex;
flex-direction: column;
min-width: 0;
}
.two .main,
code {
overflow: hidden;
text-overflow: ellipsis;
}
code {
font-family: var(--ha-font-family-code);
}
code.raw {
font-size: var(--ha-font-size-s);
color: var(--secondary-text-color);
}
.secondary {
color: var(--secondary-text-color);
}
.muted {
color: var(--disabled-text-color);
}
.actions {
display: flex;
justify-content: flex-end;
--ha-icon-button-size: 40px;
--mdc-icon-size: 20px;
color: var(--secondary-text-color);
}
.chevron {
--ha-icon-button-size: 32px;
--mdc-icon-size: 20px;
color: var(--secondary-text-color);
}
.details {
display: flex;
flex-direction: column;
gap: var(--ha-space-3);
padding: 0 var(--ha-space-4) var(--ha-space-4) 52px;
cursor: auto;
}
:host([narrow]) .details {
padding: 0 var(--ha-space-3) var(--ha-space-3);
}
.details-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--ha-space-2);
}
.spacer {
flex: 1;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"tools-state-row": ToolsStateRow;
}
interface HASSDomEvents {
"tools-state-toggle": { entityId: string };
"tools-state-set-state": { entityId: string; anchor: Element };
"tools-state-yaml-mode": { yamlMode: boolean };
}
}
File diff suppressed because it is too large. Load diff
+6 -5
View File
@@ -315,9 +315,7 @@ export class LovelacePanel extends LitElement {
// On first load, we speed up loading page by having LL promise ready
if (preloadWindow.llConfProm) {
if (preloadWindow.llConfUrlPath === this.urlPath) {
confProm = preloadWindow.llConfProm;
}
confProm = preloadWindow.llConfProm;
preloadWindow.llConfProm = undefined;
}
if (!resourcesLoaded) {
@@ -335,9 +333,12 @@ export class LovelacePanel extends LitElement {
const fetchDashboardConfig = () =>
fetchConfig(this.hass!.connection, this.urlPath, forceDiskRefresh);
// The preload is the config of the dashboard in the URL. Fetch it again if
// The preload is the config of the "lovelace" dashboard. Fetch it again if
// it failed, for example because the connection dropped before it came back.
confProm = confProm?.catch(fetchDashboardConfig) ?? fetchDashboardConfig();
confProm =
confProm && this.urlPath === "lovelace"
? confProm.catch(fetchDashboardConfig)
: fetchDashboardConfig();
try {
rawConf = await confProm;
+21
View File
@@ -142,6 +142,25 @@ const statisticsTableParams = {
group: "string?",
} satisfies Redirect["params"];
// The States tool reads these from the link
const toolsStateParams = {
search: "string?",
mode: "string?",
entity_id: "string?",
device_id: "string?",
area_id: "string?",
floor_id: "string?",
label_id: "string?",
entity_type: "string?",
integration: "string?",
entity_filter: "string?",
state_filter: "string?",
device_filter: "string?",
area_filter: "string?",
attribute_filter: "string?",
open: "string?",
} satisfies Redirect["params"];
// The application credentials table reads these from the link
const applicationCredentialsTableParams = {
search: "string?",
@@ -212,6 +231,7 @@ export const getMyRedirects = (): Redirects => ({
},
tools_states: {
redirect: "/config/tools/state",
params: toolsStateParams,
},
tools_action_history: {
component: "logbook",
@@ -247,6 +267,7 @@ export const getMyRedirects = (): Redirects => ({
},
developer_states: {
redirect: "/config/tools/state",
params: toolsStateParams,
},
developer_services: {
redirect: "/config/tools/action",
+30 -6
View File
@@ -853,6 +853,10 @@
"command_sent": "Command sent"
}
},
"entity_details": {
"device": "Device",
"area": "Area"
},
"entity": {
"entity-picker": {
"choose_entity": "Choose entity",
@@ -4581,16 +4585,36 @@
"description2": "If the entity belongs to a device, there will be no actual communication with that device.",
"entity": "Entity",
"state": "State",
"attributes": "Attributes",
"current_state": "Current state",
"state_attributes": "State attributes (YAML, optional)",
"set_state": "Set state",
"current_entities": "Current entity states",
"filter_entities": "Filter entities",
"filter_states": "Filter states",
"set_failed": "The state could not be set",
"discard_title": "Discard changes?",
"discard_text": "The state you were setting hasn't been set yet.",
"search": "Search entities, states and attributes",
"result_count": "{count} of {total}",
"no_matches": "No entities match",
"mode_targets": "Targets",
"mode_columns": "Columns",
"sources": "[%key:ui::panel::history::sources%]",
"sources_count": "[%key:ui::panel::history::sources_count%]",
"no_targets": "Showing all entities. Add targets to narrow it down.",
"filters": "Filters",
"filter_attributes": "Filter attributes",
"no_entities": "No entities",
"filter_custom_value": "Use as typed",
"view": "View",
"show_both": "Translated and raw",
"show_translated": "Translated",
"show_raw": "Raw",
"expand_all": "Expand all",
"collapse_all": "Collapse all",
"expand_row": "Show details",
"collapse_row": "Hide details",
"visual": "Visual",
"yaml": "YAML",
"history": "History",
"copy_yaml": "Copy YAML",
"more_info": "[%key:ui::common::more_info%]",
"alert_entity_field": "Entity is a mandatory field",
"last_updated": "[%key:ui::dialogs::more_info_control::last_updated%]",
"last_changed": "[%key:ui::dialogs::more_info_control::last_changed%]",
"copy_id": "Copy ID to clipboard"
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import {
toolsStateParamsFromView,
toolsStateQueryParamConfig,
toolsStateViewFromUrl,
type ToolsStateView,
} from "../../../src/common/url/tools-state-query-params";
import { createQueryString } from "../../../src/common/url/query-params";
const emptyView: ToolsStateView = {
search: "",
mode: "targets",
targets: {},
sourceFilters: {},
columnFilters: {},
};
const toQueryString = (view: ToolsStateView) =>
createQueryString(toolsStateParamsFromView(view), toolsStateQueryParamConfig);
describe("tools state query params", () => {
it("leaves defaults out of the URL", () => {
expect(toQueryString(emptyView)).toBe("");
});
it("round trips a Targets view", () => {
const view: ToolsStateView = {
...emptyView,
search: "kitchen",
targets: { area_id: ["kitchen"], label_id: ["lighting"] },
sourceFilters: { types: ["light"] },
open: "light.kitchen_ceiling",
};
expect(toolsStateViewFromUrl(toQueryString(view))).toEqual({
...view,
columnFilters: {
entity: undefined,
state: undefined,
device: undefined,
area: undefined,
attribute: undefined,
},
});
});
it("round trips a Columns view, without the targets", () => {
const view: ToolsStateView = {
...emptyView,
mode: "columns",
targets: { area_id: ["kitchen"] },
columnFilters: { entity: "light.*", attribute: "color_mode:color_temp" },
};
const queryString = toQueryString(view);
expect(queryString).toBe(
"mode=columns&entity_filter=light.*&attribute_filter=color_mode%3Acolor_temp"
);
expect(toolsStateViewFromUrl(queryString)?.targets).toEqual({});
expect(toolsStateViewFromUrl(queryString)?.columnFilters).toMatchObject(
view.columnFilters
);
});
it("has no view for a URL without its params", () => {
expect(toolsStateViewFromUrl("other=1")).toBeUndefined();
});
});
-34
View File
@@ -1,34 +0,0 @@
import { describe, expect, it } from "vitest";
import { getPreloadDashboardUrlPath } from "../../src/data/preloads";
describe("getPreloadDashboardUrlPath", () => {
it("returns the lovelace dashboard", () => {
expect(getPreloadDashboardUrlPath("/lovelace")).toBe("lovelace");
expect(getPreloadDashboardUrlPath("/lovelace/0")).toBe("lovelace");
});
it("returns a dashboard with a hyphen in its url path", () => {
expect(getPreloadDashboardUrlPath("/dashboard-test")).toBe(
"dashboard-test"
);
expect(getPreloadDashboardUrlPath("/dashboard-test/kitchen")).toBe(
"dashboard-test"
);
});
it("returns nothing when the default panel is opened", () => {
expect(getPreloadDashboardUrlPath("/")).toBeUndefined();
});
it("returns nothing for panels that cannot be a dashboard", () => {
expect(getPreloadDashboardUrlPath("/home")).toBeUndefined();
expect(getPreloadDashboardUrlPath("/config/dashboard")).toBeUndefined();
expect(getPreloadDashboardUrlPath("/lovelaces")).toBeUndefined();
expect(
getPreloadDashboardUrlPath("/media-browser/browser")
).toBeUndefined();
expect(
getPreloadDashboardUrlPath("/developer-tools/state")
).toBeUndefined();
});
});
@@ -0,0 +1,107 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import { describe, expect, it } from "vitest";
import {
filterStatesByColumns,
type StateColumnFilters,
} from "../../../../../src/panels/config/tools/state/tools-state-filter";
import {
mockArea,
mockDevice,
mockEntity,
mockStateObj,
} from "../../../../common/entity/context/context-mock";
// The rules people already rely on in the States tool's column filters, so
// they survive the move out of the page.
const states = {
"light.kitchen_ceiling": mockStateObj({
entity_id: "light.kitchen_ceiling",
state: "on",
attributes: {
friendly_name: "Ceiling",
color_mode: "color_temp",
brightness: 180,
},
}),
"light.lamp": mockStateObj({
entity_id: "light.lamp",
state: "off",
attributes: { friendly_name: "Lamp", color_mode: null },
}),
"sensor.temperature": mockStateObj({
entity_id: "sensor.temperature",
state: "20.5",
attributes: { friendly_name: "Temperature" },
}),
};
const registries = {
entities: {
"light.kitchen_ceiling": mockEntity({
entity_id: "light.kitchen_ceiling",
device_id: "d1",
}),
"light.lamp": mockEntity({ entity_id: "light.lamp", area_id: "living" }),
},
devices: {
d1: mockDevice({ id: "d1", name: "Kitchen light", area_id: "kitchen" }),
},
areas: {
kitchen: mockArea({ area_id: "kitchen", name: "Kitchen" }),
living: mockArea({ area_id: "living", name: "Living room" }),
},
};
const formatEntityName = (stateObj: HassEntityState) =>
String(stateObj.attributes.friendly_name);
const ids = (filters: StateColumnFilters) =>
filterStatesByColumns(
states,
filters,
formatEntityName,
registries,
true
).map((entity) => entity.entity_id);
describe("filterStatesByColumns", () => {
it("matches entity IDs and names with a wildcard, ignoring case", () => {
expect(ids({ entity: "LIGHT.*" })).toEqual([
"light.kitchen_ceiling",
"light.lamp",
]);
expect(ids({ entity: "lamp" })).toEqual(["light.lamp"]);
});
it("matches the state", () => {
expect(ids({ state: "on" })).toEqual(["light.kitchen_ceiling"]);
});
it("matches the device name", () => {
expect(ids({ device: "kitchen*" })).toEqual(["light.kitchen_ceiling"]);
});
it("matches the entity's area, or its device's area", () => {
expect(ids({ area: "kitchen" })).toEqual(["light.kitchen_ceiling"]);
expect(ids({ area: "living" })).toEqual(["light.lamp"]);
});
it("matches an attribute name, or a name and its value", () => {
expect(ids({ attribute: "brightness" })).toEqual(["light.kitchen_ceiling"]);
expect(ids({ attribute: "color_mode:color_temp" })).toEqual([
"light.kitchen_ceiling",
]);
expect(ids({ attribute: "color_mode:null" })).toEqual(["light.lamp"]);
});
it("combines filters and sorts by entity ID", () => {
expect(ids({ entity: "light.*", state: "off" })).toEqual(["light.lamp"]);
expect(ids({})).toEqual([
"light.kitchen_ceiling",
"light.lamp",
"sensor.temperature",
]);
});
});
@@ -1,8 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { subscribeLovelaceUpdates } from "../../../src/data/lovelace";
import type { LovelaceRawConfig } from "../../../src/data/lovelace/config/types";
import { fetchConfig } from "../../../src/data/lovelace/config/types";
import type { WindowWithPreloads } from "../../../src/data/preloads";
import "../../../src/panels/lovelace/ha-panel-lovelace";
type LovelacePanel = HTMLElement & {
@@ -65,54 +63,9 @@ const openPanel = async (urlPath: string) => {
return { panel, unsub, notifyUpdated: () => notifyUpdated() };
};
const preloadWindow = window as WindowWithPreloads;
const preloadConfig = (
urlPath: string,
confProm: Promise<LovelaceRawConfig>
) => {
confProm.catch(() => undefined);
preloadWindow.llConfUrlPath = urlPath;
preloadWindow.llConfProm = confProm;
};
afterEach(() => {
document.body.replaceChildren();
vi.clearAllMocks();
delete preloadWindow.llConfProm;
delete preloadWindow.llConfUrlPath;
});
describe("ha-panel-lovelace config preload", () => {
it("uses the preloaded config of its own dashboard", async () => {
preloadConfig("dashboard-test", Promise.resolve({ views: [] }));
await openPanel("dashboard-test");
expect(fetchConfig).not.toHaveBeenCalled();
expect(preloadWindow.llConfProm).toBeUndefined();
});
it("ignores the preloaded config of another dashboard", async () => {
preloadConfig("dashboard-other", Promise.resolve({ views: [] }));
await openPanel("dashboard-test");
expect(fetchConfig).toHaveBeenCalledTimes(1);
expect(fetchConfig).toHaveBeenCalledWith(
expect.anything(),
"dashboard-test",
false
);
expect(preloadWindow.llConfProm).toBeUndefined();
});
it("fetches the config again when its preload failed", async () => {
preloadConfig("dashboard-test", Promise.reject(new Error("closed")));
await openPanel("dashboard-test");
expect(fetchConfig).toHaveBeenCalledTimes(1);
expect(fetchConfig).toHaveBeenCalledWith(
expect.anything(),
"dashboard-test",
false
);
});
});
describe("ha-panel-lovelace config updates", () => {