Map GitHub block quotes to our ha-alert component (#16757)

This commit is contained in:
Joakim Sørensen 2023-06-21 11:35:02 +02:00 committed by GitHub
parent 07d37dd89f
commit 5aa6ffe2e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 1 deletions

View File

@ -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

View File

@ -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);
}
}
}
}