Compare commits

..
13 changed files with 800 additions and 436 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
@@ -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, 1.35fr);
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;
}
}
+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. */
const historyUrl = (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: historyUrl(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: historyUrl(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.
});
+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;
+4
View File
@@ -853,6 +853,10 @@
"command_sent": "Command sent"
}
},
"entity_details": {
"device": "Device",
"area": "Area"
},
"entity": {
"entity-picker": {
"choose_entity": "Choose entity",
-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();
});
});
@@ -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", () => {