From f42587af220a1629a533fc6463d8043297adc925 Mon Sep 17 00:00:00 2001 From: Philip Allgaier Date: Mon, 11 Jan 2021 15:59:26 +0100 Subject: [PATCH] Format URL attribute as link (#8126) Co-authored-by: Bram Kragten --- src/components/ha-attributes.ts | 72 ++++++++++++++++++++------------- 1 file changed, 45 insertions(+), 27 deletions(-) diff --git a/src/components/ha-attributes.ts b/src/components/ha-attributes.ts index 9eefbeb111..6d5556cef2 100644 --- a/src/components/ha-attributes.ts +++ b/src/components/ha-attributes.ts @@ -12,6 +12,7 @@ import { until } from "lit-html/directives/until"; import hassAttributeUtil, { formatAttributeName, } from "../util/hass-attributes-util"; +import { haStyle } from "../resources/styles"; let jsYamlPromise: Promise; @@ -55,33 +56,36 @@ class HaAttributes extends LitElement { `; } - static get styles(): CSSResult { - return css` - .data-entry { - display: flex; - flex-direction: row; - justify-content: space-between; - } - .data-entry .value { - max-width: 60%; - overflow-wrap: break-word; - text-align: right; - } - .key { - flex-grow: 1; - } - .attribution { - color: var(--secondary-text-color); - text-align: center; - } - pre { - font-family: inherit; - font-size: inherit; - margin: 0px; - overflow-wrap: break-word; - white-space: pre-line; - } - `; + static get styles(): CSSResult[] { + return [ + haStyle, + css` + .data-entry { + display: flex; + flex-direction: row; + justify-content: space-between; + } + .data-entry .value { + max-width: 60%; + overflow-wrap: break-word; + text-align: right; + } + .key { + flex-grow: 1; + } + .attribution { + color: var(--secondary-text-color); + text-align: center; + } + pre { + font-family: inherit; + font-size: inherit; + margin: 0px; + overflow-wrap: break-word; + white-space: pre-line; + } + `, + ]; } private computeDisplayAttributes(filtersArray: string[]): string[] { @@ -105,6 +109,7 @@ class HaAttributes extends LitElement { if (value === null) { return "-"; } + // YAML handling if ( (Array.isArray(value) && value.some((val) => val instanceof Object)) || (!Array.isArray(value) && value instanceof Object) @@ -115,6 +120,19 @@ class HaAttributes extends LitElement { const yaml = jsYamlPromise.then((jsYaml) => jsYaml.safeDump(value)); return html`
${until(yaml, "")}
`; } + // 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`${value}`; + } catch (_) { + // Nothing to do here + } + } return Array.isArray(value) ? value.join(", ") : value; } }