Open History to see the last commit
1import { createElement, type ReactNode } from "react";
2import { parseDocument } from "htmlparser2";
3type ChildNode = ReturnType<typeof parseDocument>["children"][number];
4import { HN } from "./links";
5const tags = new Set([
6 "p",
7 "br",
8 "pre",
9 "code",
10 "i",
11 "em",
12 "b",
13 "strong",
14 "ul",
15 "ol",
16 "li",
17 "blockquote",
18]);
19export function commentContent(html: string): ReactNode {
20 const render = (node: ChildNode, key: number): ReactNode => {
21 if (node.type === "text") return node.data;
22 if (node.type !== "tag") return null;
23 const element = node;
24 const children = element.children.map(render);
25 if (element.name === "a") {
26 let href: string | undefined;
27 try {
28 const url = new URL(element.attribs.href ?? "", HN);
29 if (
30 ["http:", "https:"].includes(url.protocol) &&
31 !url.username &&
32 !url.password
33 )
34 href = url.href;
35 } catch {}
36 return createElement(
37 href ? "a" : "span",
38 { key, ...(href ? { href, rel: "nofollow noopener noreferrer" } : {}) },
39 children,
40 );
41 }
42 if (!tags.has(element.name))
43 return createElement("span", { key }, children);
44 return createElement(
45 element.name,
46 { key },
47 element.name === "br" ? undefined : children,
48 );
49 };
50 // Construct escaped React elements from a small allowlist. Never inject source HTML.
51 return parseDocument(html, { decodeEntities: true }).children.map(render);
52}