Format URL attribute as link (#8126)

Co-authored-by: Bram Kragten <mail@bramkragten.nl>
This commit is contained in:
Philip Allgaier 2021-01-11 15:59:26 +01:00 committed by GitHub
parent edcb7e87bb
commit f42587af22
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -12,6 +12,7 @@ import { until } from "lit-html/directives/until";
import hassAttributeUtil, { import hassAttributeUtil, {
formatAttributeName, formatAttributeName,
} from "../util/hass-attributes-util"; } from "../util/hass-attributes-util";
import { haStyle } from "../resources/styles";
let jsYamlPromise: Promise<typeof import("js-yaml")>; let jsYamlPromise: Promise<typeof import("js-yaml")>;
@ -55,33 +56,36 @@ class HaAttributes extends LitElement {
`; `;
} }
static get styles(): CSSResult { static get styles(): CSSResult[] {
return css` return [
.data-entry { haStyle,
display: flex; css`
flex-direction: row; .data-entry {
justify-content: space-between; display: flex;
} flex-direction: row;
.data-entry .value { justify-content: space-between;
max-width: 60%; }
overflow-wrap: break-word; .data-entry .value {
text-align: right; max-width: 60%;
} overflow-wrap: break-word;
.key { text-align: right;
flex-grow: 1; }
} .key {
.attribution { flex-grow: 1;
color: var(--secondary-text-color); }
text-align: center; .attribution {
} color: var(--secondary-text-color);
pre { text-align: center;
font-family: inherit; }
font-size: inherit; pre {
margin: 0px; font-family: inherit;
overflow-wrap: break-word; font-size: inherit;
white-space: pre-line; margin: 0px;
} overflow-wrap: break-word;
`; white-space: pre-line;
}
`,
];
} }
private computeDisplayAttributes(filtersArray: string[]): string[] { private computeDisplayAttributes(filtersArray: string[]): string[] {
@ -105,6 +109,7 @@ class HaAttributes extends LitElement {
if (value === null) { if (value === null) {
return "-"; return "-";
} }
// YAML handling
if ( if (
(Array.isArray(value) && value.some((val) => val instanceof Object)) || (Array.isArray(value) && value.some((val) => val instanceof Object)) ||
(!Array.isArray(value) && value instanceof Object) (!Array.isArray(value) && value instanceof Object)
@ -115,6 +120,19 @@ class HaAttributes extends LitElement {
const yaml = jsYamlPromise.then((jsYaml) => jsYaml.safeDump(value)); const yaml = jsYamlPromise.then((jsYaml) => jsYaml.safeDump(value));
return html` <pre>${until(yaml, "")}</pre> `; return html` <pre>${until(yaml, "")}</pre> `;
} }
// URL handling
if (typeof value === "string" && value.startsWith("http")) {
try {
// If invalid URL, exception will be raised
const url = new URL(value);
if (url.protocol === "http:" || url.protocol === "https:")
return html`<a target="_blank" rel="noreferrer" href="${value}"
>${value}</a
>`;
} catch (_) {
// Nothing to do here
}
}
return Array.isArray(value) ? value.join(", ") : value; return Array.isArray(value) ? value.join(", ") : value;
} }
} }