Compare commits

...
9 Commits
13 changed files with 1623 additions and 30 deletions

No files matched your search

+51
View File
@@ -54,6 +54,57 @@ lorem | ipsum
`,
})
),
mdContentwithDefaults({
content: `
<p align="center">
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
</p>
- [Installation](#installation)
- [Configuration](#configuration)
## Installation
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
## Configuration
Add the integration from the integrations page.
[Back to the top](#installation)
[^marketplace]: Settings > Marketplace.
[^restart]: Only needed the first time.
`,
}),
mdContentwithDefaults({
content: `
\`\`\`mermaid
flowchart LR
router[Router] --> switch[Switch]
switch --> nas[(NAS)]
switch --> ha[[Home Assistant]]
ha -. Zigbee .-> lights([Lights])
\`\`\`
\`\`\`mermaid
sequenceDiagram
Door sensor->>Home Assistant: Opened
Home Assistant->>Hallway light: Turn on
Hallway light-->>Home Assistant: On
\`\`\`
`,
}),
mdContentwithDefaults({
content: `
A diagram that doesn't parse shows the error and its source:
\`\`\`mermaid
flowchart LR
A -->
\`\`\`
`,
}),
];
@customElement("demo-misc-ha-markdown")
+3
View File
@@ -110,7 +110,10 @@
"lit-html": "3.3.3",
"maplibre-gl": "6.20.0",
"marked": "18.3.0",
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"memoize-one": "7.0.0",
"mermaid": "12.4.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
+842
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -50,6 +50,23 @@ export const getRGBContrastRatio = (
rgb2: [number, number, number]
) => Math.round((rgbContrast(rgb1, rgb2) + Number.EPSILON) * 100) / 100;
/**
* Parses an `--rgb-*` theme variable, such as `--rgb-primary-text-color`
* @param value - The variable's value, such as `33, 33, 33`
* @returns The red, green and blue values, or undefined when it isn't three numbers
*/
export const parseRgbVariable = (
value: string
): [number, number, number] | undefined => {
const parts = value.split(",").map((part) => parseInt(part, 10));
if (parts.length !== 3 || parts.some((part) => Number.isNaN(part))) {
return undefined;
}
return [parts[0], parts[1], parts[2]];
};
/**
* Tells whether a color can be measured, which a CSS function that is passed
* through unevaluated cannot, and whether it covers what is behind it
+129 -5
View File
@@ -1,11 +1,20 @@
import type { PropertyValues } from "lit";
import { ReactiveElement, render, html } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import hash from "object-hash";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { rewriteHtmlUrls } from "../common/dom/rewrite-html-urls";
import { internationalizationContext } from "../data/context";
import type { FootnoteLabels } from "../resources/markdown-worker";
import {
USER_CONTENT_PREFIX,
userContentId,
} from "../resources/markdown-user-content";
import { renderMarkdown } from "../resources/render-markdown";
import type { HomeAssistantInternationalization } from "../types";
import { CacheManager } from "../util/cache-manager";
const h = (template: ReturnType<typeof unsafeHTML>) => html`${template}`;
@@ -43,8 +52,35 @@ class HaMarkdownElement extends ReactiveElement {
// For content whose relative addresses belong elsewhere, like a README
@property({ attribute: false }) public rewriteUrl?: (url: string) => string;
// Without translations, like on the auth pages, the worker uses English
@state({
hasChanged: (value?: FootnoteLabels, oldValue?: FootnoteLabels) =>
value?.heading !== oldValue?.heading ||
value?.backReference !== oldValue?.backReference,
})
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FootnoteLabels>({
transformer: ({ localize }) => {
const heading = localize("ui.components.markdown.footnotes");
const backReference = localize(
"ui.components.markdown.footnote_back_reference",
{ reference: "{0}" }
);
return heading && backReference ? { heading, backReference } : undefined;
},
})
private _footnoteLabels?: FootnoteLabels;
public connectedCallback() {
super.connectedCallback();
this.addEventListener("click", this._handleAnchorClick);
}
public disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("click", this._handleAnchorClick);
if (this.cache) {
const key = this._computeCacheKey();
markdownCache.set(key, this.innerHTML);
@@ -87,6 +123,7 @@ class HaMarkdownElement extends ReactiveElement {
allowDataUrl: this.allowDataUrl,
breaks: this.breaks,
rewriteUrl: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
});
}
@@ -101,6 +138,7 @@ class HaMarkdownElement extends ReactiveElement {
allowSvg: this.allowSvg,
allowDataUrl: this.allowDataUrl,
allowRelativeUrls: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
}
);
@@ -191,18 +229,104 @@ class HaMarkdownElement extends ReactiveElement {
}
} else if (
node instanceof HTMLElement &&
["ha-alert", "ha-qr-code", "ha-icon", "ha-svg-icon"].includes(
node.localName
)
[
"ha-alert",
"ha-qr-code",
"ha-icon",
"ha-svg-icon",
"ha-mermaid-diagram",
].includes(node.localName)
) {
import(
/* webpackInclude: /(ha-alert)|(ha-qr-code)|(ha-icon)|(ha-svg-icon)/ */ `./${node.localName}`
/* webpackInclude: /(ha-alert)|(ha-qr-code)|(ha-icon)|(ha-svg-icon)|(ha-mermaid-diagram)/ */ `./${node.localName}`
);
}
}
}
private _resize = () => fireEvent(this, "content-resize");
// The content is in a shadow root, so the browser can't scroll to a `#` link
// in it, and the app would navigate to it instead
private _handleAnchorClick = (ev: MouseEvent) => {
// Leave opening the link in a new tab or window to the browser
if (
ev.defaultPrevented ||
ev.button !== 0 ||
ev.metaKey ||
ev.ctrlKey ||
ev.shiftKey
) {
return;
}
const anchor = ev
.composedPath()
.find((node) => node instanceof HTMLAnchorElement);
// Or one the author set to open somewhere else
if (anchor?.target && anchor.target !== "_self") {
return;
}
const href = anchor?.getAttribute("href");
if (!href?.startsWith("#") || href.length === 1) {
return;
}
const fragment = href.slice(1);
// Browsers take #top as the top of the page, READMEs use it for the top
const target =
this._findAnchorTarget(fragment) ??
(fragment.toLowerCase() === "top" ? this : undefined);
// An anchor that isn't in the content does what it did before
if (target) {
ev.preventDefault();
target.scrollIntoView({ block: "start" });
// Move focus there too, like the browser does, so Tab carries on from
// the target. -1 makes a heading focusable without adding it to Tab.
if (target instanceof HTMLElement) {
if (!target.hasAttribute("tabindex") && target.tabIndex < 0) {
target.tabIndex = -1;
}
target.focus({ preventScroll: true });
}
}
};
// Links like `#Setup` and `#%C3%BCber` still find `user-content-setup` and
// `user-content-über`, like on GitHub
private _findAnchorTarget(fragment: string) {
let decoded = fragment;
try {
decoded = decodeURIComponent(fragment);
} catch {
// Not encoded, look for it as written
}
const ids = [fragment, decoded, decoded.toLowerCase()].flatMap((id) => [
userContentId(id),
// Heading ids always get the prefix, so `## user-content-setup` has
// `user-content-user-content-setup`
`${USER_CONTENT_PREFIX}${id}`,
]);
for (const id of new Set(ids)) {
const target = this.querySelector(`[id="${CSS.escape(id)}"]`);
if (target) {
return target;
}
}
return undefined;
}
}
declare global {
+15
View File
@@ -201,6 +201,21 @@ export class HaMarkdown extends LitElement {
margin-inline: 0;
padding-inline: 1em;
}
section[data-footnotes] {
border-top: 1px solid var(--divider-color);
margin-top: var(--ha-space-4);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
/* Read out by screen readers but not shown, like on GitHub */
section[data-footnotes] > h2 {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
` as CSSResultGroup;
}
+260
View File
@@ -0,0 +1,260 @@
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { rgb2hex } from "../common/color/convert-color";
import { parseRgbVariable } from "../common/color/rgb";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import type { LocalizeFunc } from "../common/translations/localize";
import { internationalizationContext, uiContext } from "../data/context";
import type {
HomeAssistantInternationalization,
HomeAssistantUI,
} from "../types";
import "./ha-alert";
type Rgb = [number, number, number];
// How much of the primary colour tints the boxes, so their text stays readable
const PRIMARY_TINT = 0.15;
const MAX_CACHED_DIAGRAMS = 50;
// The drawn SVG for each theme and source, so a card that renders its markdown
// again, like on every template update, doesn't redraw and flicker
const svgCache = new Map<string, string>();
let mermaidQueue: Promise<unknown> = Promise.resolve();
let diagramCount = 0;
// mermaid.initialize() sets global options, so diagrams are drawn one at a
// time, or two with different theme colours would pick up each other's
const drawDiagram = (
source: string,
themeVariables: Record<string, string | boolean>
): Promise<string> => {
const result = mermaidQueue.then(async () => {
const { default: mermaid } = await import("mermaid");
mermaid.initialize({
startOnLoad: false,
// Sanitises the SVG, encodes HTML in labels and turns off click handlers.
// Templates can put entity names and states in the source.
securityLevel: "strict",
// Show our own error instead of Mermaid's error picture
suppressErrorRendering: true,
// Mermaid 12 lays diagrams out with ELK by default, which adds 1.5 MB
// to every flowchart. A diagram can still ask for it in its config.
layout: "dagre",
theme: "base",
themeVariables,
});
diagramCount++;
const { svg } = await mermaid.render(`ha-mermaid-${diagramCount}`, source);
return svg;
});
// A diagram that fails must not stop the ones after it
mermaidQueue = result.catch(() => undefined);
return result;
};
const tint = (background: number, primary: number) =>
Math.round(background + (primary - background) * PRIMARY_TINT);
interface ThemeState {
theme?: string;
darkMode?: boolean;
}
@customElement("ha-mermaid-diagram")
export class HaMermaidDiagram extends LitElement {
// The markdown is rendered again as a whole when it changes, so the source
// of one element never changes
@state() private _source?: string;
@state() private _svg?: string;
@state() private _error?: string;
// A theme or dark mode switch draws the diagram again in the new colours
@state({
hasChanged: (value?: ThemeState, oldValue?: ThemeState) =>
value?.theme !== oldValue?.theme ||
value?.darkMode !== oldValue?.darkMode,
})
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, ThemeState>({
transformer: ({ themes }) => ({
theme: themes?.theme,
darkMode: themes?.darkMode,
}),
})
private _theme?: ThemeState;
// Without translations, like on the auth pages, the error has no title
@state()
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, LocalizeFunc>({
transformer: ({ localize }) => localize,
})
private _localize?: LocalizeFunc;
public connectedCallback() {
super.connectedCallback();
this._source ??= this.textContent ?? "";
}
protected updated(changedProperties: PropertyValues) {
super.updated(changedProperties);
if (changedProperties.has("_source") || changedProperties.has("_theme")) {
this._draw();
}
if (changedProperties.has("_svg") || changedProperties.has("_error")) {
fireEvent(this, "content-resize");
}
}
private async _draw() {
const source = this._source;
if (!source?.trim()) {
return;
}
const themeVariables = this._themeVariables();
const key = `${JSON.stringify(themeVariables)}\n${source}`;
const cached = svgCache.get(key);
if (cached) {
this._svg = cached;
this._error = undefined;
return;
}
try {
const svg = await drawDiagram(source, themeVariables);
svgCache.set(key, svg);
// A Map keeps insertion order, so the first key is the oldest
const oldest = svgCache.keys().next().value;
if (svgCache.size > MAX_CACHED_DIAGRAMS && oldest !== undefined) {
svgCache.delete(oldest);
}
this._svg = svg;
this._error = undefined;
} catch (err) {
this._svg = undefined;
this._error = err instanceof Error ? err.message : String(err);
}
}
// Mermaid works out its other colours from these, but not the edge label
// background. It can't read var() or rgba(), so use the --rgb-* variables.
// They come from this element, so a card or view theme applies too.
private _themeVariables() {
const style = getComputedStyle(this);
const rgbVariable = (name: string, fallback: Rgb): Rgb =>
parseRgbVariable(style.getPropertyValue(name)) ?? fallback;
const background = rgbVariable(
"--rgb-card-background-color",
[255, 255, 255]
);
const primary = rgbVariable("--rgb-primary-color", [0, 154, 199]);
const text = rgbVariable("--rgb-primary-text-color", [33, 33, 33]);
const secondaryText = rgbVariable(
"--rgb-secondary-text-color",
[114, 114, 114]
);
const boxes: Rgb = [
tint(background[0], primary[0]),
tint(background[1], primary[1]),
tint(background[2], primary[2]),
];
return {
darkMode: Boolean(this._theme?.darkMode),
background: rgb2hex(background),
edgeLabelBackground: rgb2hex(background),
mainBkg: rgb2hex(boxes),
primaryColor: rgb2hex(boxes),
primaryBorderColor: rgb2hex(primary),
primaryTextColor: rgb2hex(text),
textColor: rgb2hex(text),
lineColor: rgb2hex(secondaryText),
fontFamily: style.fontFamily,
};
}
protected render() {
if (this._error) {
return html`
<ha-alert
alert-type="warning"
.title=${
this._localize?.("ui.components.markdown.diagram_error") ?? ""
}
>
<span class="error">${this._error}</span>
</ha-alert>
<pre><code>${this._source}</code></pre>
`;
}
return this._svg ? unsafeHTML(this._svg) : nothing;
}
static styles = css`
:host {
display: block;
overflow-x: auto;
}
svg {
display: block;
margin: 0 auto;
}
/* Mermaid points at the error with a ^ under the line, which only lines
up in a monospace font */
.error {
white-space: pre-wrap;
font-family: var(--ha-font-family-code);
font-size: var(--ha-font-size-s);
}
pre {
background-color: var(--markdown-code-background-color, none);
border-radius: var(--ha-border-radius-sm);
color: var(--markdown-code-text-color, inherit);
padding: var(--ha-space-4);
overflow: auto;
line-height: var(--ha-line-height-condensed);
font-family: var(--ha-font-family-code);
}
code {
font-size: var(--ha-font-size-s);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-mermaid-diagram": HaMermaidDiagram;
}
}
+1 -9
View File
@@ -7,21 +7,13 @@ import { rgb2hex } from "../common/color/convert-color";
import {
getContrastedColorHex,
getRGBContrastRatio,
parseRgbVariable,
} from "../common/color/rgb";
// Minimum contrast ratio (WCAG non-text minimum) below which we substitute a
// legible foreground so the QR code never renders unscannable.
const MIN_CONTRAST_RATIO = 3;
const parseRgbVariable = (
value: string
): [number, number, number] | undefined => {
const parts = value.split(",").map((part) => parseInt(part, 10));
return parts.length === 3 && parts.every((part) => !Number.isNaN(part))
? (parts as [number, number, number])
: undefined;
};
@customElement("ha-qr-code")
export class HaQrCode extends LitElement {
@property() public data?: string;
+1 -1
View File
@@ -40,7 +40,7 @@ export const repositoryUrl =
// A browser trims it, "https:" can follow a space
const destination = rawGitHubFile(url.trim());
// Headings get no ids, so an anchor has nothing to point at on this page
// ha-markdown scrolls to an anchor in the README itself
if (
!repository ||
destination.startsWith("#") ||
+6
View File
@@ -0,0 +1,6 @@
// Every id in rendered markdown starts with this, like on GitHub, so it can't
// clash with the ids of the page around it
export const USER_CONTENT_PREFIX = "user-content-";
export const userContentId = (id: string) =>
id.startsWith(USER_CONTENT_PREFIX) ? id : `${USER_CONTENT_PREFIX}${id}`;
+132 -15
View File
@@ -1,6 +1,8 @@
import { expose } from "comlink";
import type { MarkedOptions } from "marked";
import { marked } from "marked";
import { Marked, Renderer } from "marked";
import markedFootnote from "marked-footnote";
import { gfmHeadingId, resetHeadings } from "marked-gfm-heading-id";
import type { IWhiteList } from "xss";
import {
escapeAttrValue,
@@ -10,6 +12,82 @@ import {
safeAttrValue,
} from "xss";
import { URL_ATTRIBUTES } from "../common/dom/rewrite-html-urls";
import { USER_CONTENT_PREFIX, userContentId } from "./markdown-user-content";
export interface FootnoteLabels {
// Read out by screen readers above the footnotes
heading: string;
// The label of the link back to a reference, "{0}" is its number
backReference: string;
}
const DEFAULT_FOOTNOTE_LABELS: FootnoteLabels = {
heading: "Footnotes",
backReference: "Back to reference {0}",
};
// The footnote labels are set when the extension is created and an extension
// can't be removed again, so each language gets its own instance
const markedInstances = new Map<string, Marked>();
const markedFor = (labels: FootnoteLabels) => {
const key = `${labels.heading}\n${labels.backReference}`;
let instance = markedInstances.get(key);
if (!instance) {
instance = new Marked(
{
renderer: {
table(...args) {
const defaultRenderer = new Renderer();
// Wrap the table with block element because the property 'overflow'
// cannot be applied to elements of display type 'table'.
// https://www.w3.org/TR/css-overflow-3/#overflow-control
return `<div>${defaultRenderer.table.apply(this, args)}</div>`;
},
// xss drops the language class, so mark diagrams with their own tag.
// false leaves every other code block to the default renderer.
code({ text, lang }) {
// The first word of the info string, like GitHub
if (lang?.match(/^\S*/)?.[0].toLowerCase() !== "mermaid") {
return false;
}
return `<ha-mermaid-diagram>${text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</ha-mermaid-diagram>`;
},
},
},
gfmHeadingId({ prefix: USER_CONTENT_PREFIX }),
markedFootnote({
prefixId: `${USER_CONTENT_PREFIX}fn-`,
description: labels.heading,
backRefLabel: labels.backReference,
// [1] like on GitHub, so references next to each other don't read as 12
refMarkers: true,
// xss drops classes, the styles use data-footnotes instead
sectionClass: "",
headingClass: "",
})
);
markedInstances.set(key, instance);
}
return instance;
};
// Decode an attribute value like the browser would. friendlyAttrValue leaves
// `&amp;` as it is.
const decodeAttribute = (value: string) =>
friendlyAttrValue(value).replace(/&amp;/g, "&");
// Write a decoded value back so the browser reads what was checked: escape `&`
// too, or the browser would decode it a second time
const attribute = (name: string, decoded: string) =>
`${name}="${escapeAttrValue(decoded.replace(/&/g, "&amp;"))}"`;
let whiteListNormal: IWhiteList | undefined;
let whiteListSvg: IWhiteList | undefined;
@@ -68,12 +146,27 @@ const renderMarkdown = async (
allowSvg?: boolean;
allowDataUrl?: boolean;
allowRelativeUrls?: boolean;
footnoteLabels?: FootnoteLabels;
} = {}
): Promise<string[]> => {
if (!whiteListNormal) {
const defaultWhiteList = getDefaultWhiteList();
// READMEs centre their logo and badges with align
const withAlign = (tag: string) => [
...(defaultWhiteList[tag] ?? []),
"align",
];
whiteListNormal = {
...getDefaultWhiteList(),
table: [...(getDefaultWhiteList().table ?? []), "role"],
...defaultWhiteList,
...Object.fromEntries(
["p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "img"].map((tag) => [
tag,
withAlign(tag),
])
),
table: [...(defaultWhiteList.table ?? []), "role"],
input: ["type", "disabled", "checked"],
// Allows <picture>, and <video>/<audio> that have <source> children.
picture: [],
@@ -89,6 +182,7 @@ const renderMarkdown = async (
"error-correction-level",
"center-image",
],
"ha-mermaid-diagram": [],
};
}
@@ -100,7 +194,7 @@ const renderMarkdown = async (
...whiteListNormal,
svg: ["xmlns", "height", "width"],
path: ["transform", "stroke", "d"],
img: ["src"],
img: ["src", "align"],
};
}
whiteList = whiteListSvg;
@@ -112,21 +206,23 @@ const renderMarkdown = async (
whiteList = { ...whiteList, a: [...(whiteList.a ?? []), "download"] };
}
const marked = markedFor(
hassOptions.footnoteLabels ?? DEFAULT_FOOTNOTE_LABELS
);
marked.setOptions(markedOptions);
marked.use({
renderer: {
table(...args) {
const defaultRenderer = new marked.Renderer();
// Wrap the table with block element because the property 'overflow'
// cannot be applied to elements of display type 'table'.
// https://www.w3.org/TR/css-overflow-3/#overflow-control
return `<div>${defaultRenderer.table.apply(this, args)}</div>`;
},
},
});
// The blocks are parsed one by one, which skips what marked's own parse()
// runs around them: the heading ids would keep counting up from the last
// render, and the footnotes would stay at the top and break the next render
resetHeadings();
const tokens = marked.lexer(content);
if (marked.defaults.walkTokens) {
marked.walkTokens(tokens, marked.defaults.walkTokens);
}
return tokens.map((token) =>
filterXSS(marked.parser([token]), {
whiteList,
@@ -152,6 +248,27 @@ const renderMarkdown = async (
if (tag === "source" && name === "srcset") {
return sanitizeSrcset(value);
}
// Ids keep the user-content- prefix, which a raw id or <a name> gets
// too, so links written for GitHub work and can't clash with the page
if (name === "id" || (tag === "a" && name === "name")) {
const id = decodeAttribute(value).trim();
return id && !/\s/.test(id) ? attribute("id", userContentId(id)) : "";
}
// What the footnotes extension writes, for styles and screen readers
if (tag === "section" && name === "data-footnotes") {
return "data-footnotes";
}
if (
tag === "a" &&
(name === "aria-describedby" || name === "aria-label")
) {
return attribute(name, decodeAttribute(value));
}
if (
hassOptions.allowDataUrl &&
tag === "a" &&
+5
View File
@@ -549,6 +549,11 @@
"subpage_tabs": "Pages"
},
"components": {
"markdown": {
"footnotes": "Footnotes",
"footnote_back_reference": "Back to reference {reference}",
"diagram_error": "Couldn't draw this diagram"
},
"safe_area_tool": {
"title": "Safe area",
"presets": {
+161
View File
@@ -288,6 +288,167 @@ describe("renderMarkdown", () => {
});
});
describe("footnotes", () => {
const content = ["Text with a note[^note].", "", "[^note]: The note."].join(
"\n"
);
// Twice, because the second render breaks if the first one leaves the
// footnotes extension's state behind
it.each([1, 2])("renders footnotes at the end (render %s)", async () => {
const fragment = parse(await render(content));
const ref = fragment.querySelector("sup > a");
expect(ref?.getAttribute("id")).toBe("user-content-fn-ref-note");
expect(ref?.getAttribute("href")).toBe("#user-content-fn-note");
expect(ref?.getAttribute("aria-describedby")).toBe(
"user-content-fn-label"
);
const section = fragment.lastElementChild;
expect(section?.matches("section[data-footnotes]")).toBe(true);
expect(section?.querySelector("li")?.getAttribute("id")).toBe(
"user-content-fn-note"
);
const backReference = section?.querySelector("li a");
expect(backReference?.getAttribute("href")).toBe(
"#user-content-fn-ref-note"
);
expect(backReference?.getAttribute("aria-label")).toBe(
"Back to reference note"
);
});
it("uses the labels it's given", async () => {
const fragment = parse(
(
await renderMarkdown(
content,
{},
{
footnoteLabels: {
heading: "Fußnoten",
backReference: "Zurück zu {0}",
},
}
)
).join("")
);
expect(fragment.querySelector("section h2")?.textContent).toBe(
"Fußnoten"
);
expect(
fragment.querySelector("section li a")?.getAttribute("aria-label")
).toBe("Zurück zu note");
});
it("leaves a reference without a footnote as text", async () => {
const html = await render("Text[^missing].");
expect(parse(html).querySelector("section, sup")).toBeNull();
expect(html).toContain("[^missing]");
});
});
describe("ids", () => {
const ids = async (content: string) =>
Array.from(parse(await render(content)).querySelectorAll("[id]")).map(
(element) => element.id
);
it("gives headings ids like GitHub", async () => {
expect(await ids("# Setup\n\n## Setup\n\n## Über uns")).toEqual([
"user-content-setup",
"user-content-setup-1",
"user-content-über-uns",
]);
});
it("starts the heading ids again on every render", async () => {
await render("# Setup");
expect(await ids("# Setup")).toEqual(["user-content-setup"]);
});
it("adds the prefix to an id or a link name in the content", async () => {
expect(
await ids(
'<a name="top"></a><span id="location">x</span><span id="user-content-kept">x</span>'
)
).toEqual([
"user-content-top",
"user-content-location",
"user-content-kept",
]);
});
// A link to #a&b has to find it, so the id can't keep the entity
it("decodes an ampersand in an id once", async () => {
expect(await ids('<span id="a&amp;b">x</span>')).toEqual([
"user-content-a&b",
]);
});
it("drops an id with a space", async () => {
expect(await ids('<span id="a b">x</span>')).toEqual([]);
});
});
describe("align", () => {
it.each(["p", "div", "h1", "h6"])("keeps align on %s", async (tag) => {
const element = parse(
await render(`<${tag} align="center" onclick="alert(1)">x</${tag}>`)
).querySelector(tag);
expect(element?.getAttributeNames()).toEqual(["align"]);
expect(element?.getAttribute("align")).toBe("center");
});
// SVG content has its own allowlist for img
it.each([false, true])(
"keeps align on img with allowSvg %s",
async (allowSvg) => {
expect(
parse(
await render(
'<img src="https://example.com/a.png" align="right">',
allowSvg
)
)
.querySelector("img")
?.getAttribute("align")
).toBe("right");
}
);
});
describe("mermaid", () => {
// The element reads its source back as text, so raw HTML in the source
// must stay text and the source must come back exactly as written
it("turns a mermaid block into a diagram with its source as text", async () => {
const source = 'flowchart LR\n A["<b onclick=alert(1)>&amp;</b>"] --> B';
const content = parse(
await render(`\`\`\`mermaid title\n${source}\n\`\`\``)
);
const diagram = content.querySelector("ha-mermaid-diagram");
expect(diagram?.getAttributeNames()).toEqual([]);
expect(diagram?.children).toHaveLength(0);
expect(diagram?.textContent).toBe(source);
expect(content.querySelector("pre")).toBeNull();
});
it("leaves other code blocks alone", async () => {
const content = parse(await render("```js\nconst a = 1;\n```"));
expect(content.querySelector("ha-mermaid-diagram")).toBeNull();
expect(content.querySelector("pre code")?.textContent).toBe(
"const a = 1;\n"
);
});
});
describe("data URLs", () => {
const renderLink = async (
content: string,