From 5aa6ffe2e4412e8332eb3b01710db771fe69ee23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20S=C3=B8rensen?= Date: Wed, 21 Jun 2023 11:35:02 +0200 Subject: [PATCH] Map GitHub block quotes to our ha-alert component (#16757) --- gallery/src/pages/lovelace/markdown-card.ts | 11 +++++++- src/components/ha-markdown-element.ts | 30 +++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/gallery/src/pages/lovelace/markdown-card.ts b/gallery/src/pages/lovelace/markdown-card.ts index 1abca4bdcc..700283b6b8 100644 --- a/gallery/src/pages/lovelace/markdown-card.ts +++ b/gallery/src/pages/lovelace/markdown-card.ts @@ -9,7 +9,7 @@ const CONFIGS = [ heading: "markdown-it demo", config: ` - type: markdown - content: >- + content: | # h1 Heading 8-) ## h2 Heading @@ -65,6 +65,15 @@ const CONFIGS = [ >> ...by using additional greater-than signs right next to each other... > > > ...or with spaces between arrows. + > **Warning** Hey there + > This is a warning with a title + + > **Note** + > This is a note + + > **Note** + > This is a multiline note + > Lorem ipsum... ## Lists diff --git a/src/components/ha-markdown-element.ts b/src/components/ha-markdown-element.ts index 1a4691c917..7a15e35e0b 100644 --- a/src/components/ha-markdown-element.ts +++ b/src/components/ha-markdown-element.ts @@ -3,6 +3,8 @@ import { customElement, property } from "lit/decorators"; import { fireEvent } from "../common/dom/fire_event"; import { renderMarkdown } from "../resources/render-markdown"; +const _blockQuoteToAlert = { Note: "info", Warning: "warning" }; + @customElement("ha-markdown-element") class HaMarkdownElement extends ReactiveElement { @property() public content?; @@ -65,6 +67,34 @@ class HaMarkdownElement extends ReactiveElement { node.loading = "lazy"; } node.addEventListener("load", this._resize); + } else if (node instanceof HTMLQuoteElement) { + // Map GitHub blockquote elements to our ha-alert element + const firstElementChild = node.firstElementChild; + const quoteTitleElement = firstElementChild?.firstElementChild; + const quoteType = + quoteTitleElement?.textContent && + _blockQuoteToAlert[quoteTitleElement.textContent]; + + // GitHub is strict on how these are defined, we need to make sure we know what we have before starting to replace it + if (quoteTitleElement?.nodeName === "STRONG" && quoteType) { + const alertNote = document.createElement("ha-alert"); + alertNote.alertType = quoteType; + alertNote.title = + (firstElementChild!.childNodes[1].nodeName === "#text" && + firstElementChild!.childNodes[1].textContent?.trimStart()) || + ""; + + const childNodes = Array.from(firstElementChild!.childNodes); + for (const child of childNodes.slice( + childNodes.findIndex( + // There is always a line break between the title and the content, we want to skip that + (childNode) => childNode instanceof HTMLBRElement + ) + 1 + )) { + alertNote.appendChild(child); + } + node.firstElementChild!.replaceWith(alertNote); + } } } }