Fix display of arrays/objects in attributes (#4836)

* Fix display of arrays/objects in attributes

* async import js-yaml
This commit is contained in:
Bram Kragten 2020-02-13 17:22:41 +01:00 committed by GitHub
parent 6b115bf06a
commit 6feaf64c90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 11 deletions

View File

@ -10,6 +10,9 @@ import {
import { HassEntity } from "home-assistant-js-websocket";
import hassAttributeUtil from "../util/hass-attributes-util";
import { until } from "lit-html/directives/until";
let jsYamlPromise: Promise<typeof import("js-yaml")>;
@customElement("ha-attributes")
class HaAttributes extends LitElement {
@ -32,7 +35,7 @@ class HaAttributes extends LitElement {
<div class="data-entry">
<div class="key">${attribute.replace(/_/g, " ")}</div>
<div class="value">
${this.formatAttributeValue(attribute)}
${this.formatAttribute(attribute)}
</div>
</div>
`
@ -63,6 +66,10 @@ class HaAttributes extends LitElement {
color: var(--secondary-text-color);
text-align: right;
}
pre {
font-family: inherit;
font-size: inherit;
}
`;
}
@ -75,18 +82,31 @@ class HaAttributes extends LitElement {
});
}
private formatAttributeValue(attribute: string): string {
private formatAttribute(attribute: string): string | TemplateResult {
if (!this.stateObj) {
return "-";
}
const value = this.stateObj.attributes[attribute];
return this.formatAttributeValue(value);
}
private formatAttributeValue(value: any): string | TemplateResult {
if (value === null) {
return "-";
}
if (Array.isArray(value)) {
return value.join(", ");
if (
(Array.isArray(value) && value.some((val) => val instanceof Object)) ||
(!Array.isArray(value) && value instanceof Object)
) {
if (!jsYamlPromise) {
jsYamlPromise = import(/* webpackChunkName: "js-yaml" */ "js-yaml");
}
const yaml = jsYamlPromise.then((jsYaml) => jsYaml.safeDump(value));
return html`
<pre>${until(yaml, "")}</pre>
`;
}
return value instanceof Object ? JSON.stringify(value, null, 2) : value;
return Array.isArray(value) ? value.join(", ") : value;
}
}

View File

@ -357,16 +357,22 @@ class HaPanelDevState extends EventsMixin(LocalizeMixin(PolymerElement)) {
for (i = 0, keys = Object.keys(entity.attributes); i < keys.length; i++) {
key = keys[i];
value = entity.attributes[key];
if (!Array.isArray(value) && value instanceof Object) {
value = JSON.stringify(value, null, " ");
}
output += key + ": " + value + "\n";
value = this.formatAttributeValue(entity.attributes[key]);
output += `${key}: ${value}\n`;
}
return output;
}
formatAttributeValue(value) {
if (
(Array.isArray(value) && value.some((val) => val instanceof Object)) ||
(!Array.isArray(value) && value instanceof Object)
) {
return `\n${safeDump(value)}`;
}
return Array.isArray(value) ? value.join(", ") : value;
}
_computeParsedStateAttributes(stateAttributes) {
try {
return stateAttributes.trim() ? safeLoad(stateAttributes) : {};