Compare commits

...
10 changed files with 453 additions and 17 deletions

No files matched your search

+23
View File
@@ -54,6 +54,29 @@ 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.
`,
}),
];
@customElement("demo-misc-ha-markdown")
+2
View File
@@ -110,6 +110,8 @@
"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",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
+30
View File
@@ -408,6 +408,12 @@ importers:
marked:
specifier: 18.3.0
version: 18.3.0
marked-footnote:
specifier: 1.4.0
version: 1.4.0([email protected])
marked-gfm-heading-id:
specifier: 4.1.4
version: 4.1.4([email protected])
memoize-one:
specifier: 7.0.0
version: 7.0.0
@@ -5386,6 +5392,9 @@ packages:
[email protected]:
resolution: {integrity: sha512-2760b1vpJHNmLzZ/ubTtNnEx5WApN/PYWJvXvgS+tL1egTTthayFYIQQNi136FLEDcN/IyEY2EcGpIITD6eYUw==}
[email protected]:
resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==}
[email protected]:
resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==}
@@ -6213,6 +6222,16 @@ packages:
resolution: {integrity: sha512-7manvqXeNoN0mKRzenYDopkb3VW9j7iag45RvopkOVFZ7c+La7CBWtK8eBS5bKrI6NyxqAIxPxIG1PMcotcY1w==}
engines: {node: '>=16.14.0', npm: '>=8.1.0'}
[email protected]:
resolution: {integrity: sha512-fZTxAhI1TcLEs5UOjCfYfTHpyKGaWQevbxaGTEA68B51l7i87SctPFtHETYqPkEN0ka5opvy4Dy1l/yXVC+hmg==}
peerDependencies:
marked: '>=7.0.0'
[email protected]:
resolution: {integrity: sha512-CspnvVfHSkb/znqdPS4jUR8HtCjq3M/DnrsJCrfLBLvdrgbemmoINKpeWKQYkBiXAoBGejw0cV7xzqrPdup3WA==}
peerDependencies:
marked: '>=13 <19'
[email protected]:
resolution: {integrity: sha512-HR0m3bvu0jAPYiIvLUUQtdg1g6D247//lvcekpHO1WMvbwDlwSkZAX9Lw4F4YHE1T0HaaNve0tuAWuV1UJ6vtw==}
engines: {node: '>= 18'}
@@ -13344,6 +13363,8 @@ snapshots:
image-q: 4.0.0
omggif: 1.0.10
[email protected]: {}
[email protected]: {}
[email protected]:
@@ -14245,6 +14266,15 @@ snapshots:
- react
- use-sync-external-store
[email protected]([email protected]):
dependencies:
marked: 18.3.0
[email protected]([email protected]):
dependencies:
github-slugger: 2.0.0
marked: 18.3.0
[email protected]: {}
[email protected]: {}
+121 -1
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,
}
);
@@ -203,6 +241,88 @@ class HaMarkdownElement extends ReactiveElement {
}
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;
}
+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}`;
+118 -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,69 @@ 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>`;
},
},
},
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 +133,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: [],
@@ -100,7 +180,7 @@ const renderMarkdown = async (
...whiteListNormal,
svg: ["xmlns", "height", "width"],
path: ["transform", "stroke", "d"],
img: ["src"],
img: ["src", "align"],
};
}
whiteList = whiteListSvg;
@@ -112,21 +192,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 +234,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" &&
+4
View File
@@ -549,6 +549,10 @@
"subpage_tabs": "Pages"
},
"components": {
"markdown": {
"footnotes": "Footnotes",
"footnote_back_reference": "Back to reference {reference}"
},
"safe_area_tool": {
"title": "Safe area",
"presets": {
+133
View File
@@ -288,6 +288,139 @@ 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("data URLs", () => {
const renderLink = async (
content: string,