forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

rich-text.ts88 lines, 3.7 KiBHistoryRawDownload
1import DOMPurify from "dompurify";
2
3// Note bodies are stored as HTML written by the contentEditable editor, and
4// course notes render for every enrolled student — so anything that reaches
5// `innerHTML`, stored or pasted, goes through this allow-list first.
6const ALLOWED_TAGS = ["p", "div", "br", "h2", "h3", "strong", "b", "em", "i", "u", "s", "strike", "ul", "ol", "li", "blockquote", "pre", "code", "a", "span"];
7const ALLOWED_ATTR = ["href", "target", "rel"];
8
9export function sanitizeRichText(html: string): string {
10 const clean = DOMPurify.sanitize(html, { ALLOWED_TAGS, ALLOWED_ATTR, ALLOW_DATA_ATTR: false });
11 // Links open outside the app without handing it the opener.
12 const template = document.createElement("template");
13 template.innerHTML = clean;
14 for (const link of template.content.querySelectorAll("a")) {
15 link.setAttribute("target", "_blank");
16 link.setAttribute("rel", "noopener noreferrer");
17 }
18 return template.innerHTML;
19}
20
21/** Plain text of a stored body, whitespace collapsed — for card excerpts, never rendered as HTML. */
22export function richTextExcerpt(html: string, maxLength = 280): string {
23 const doc = new DOMParser().parseFromString(html.replace(/<\/(p|div|h2|h3|li|blockquote|pre)>|<br\s*\/?>/gi, "$& "), "text/html");
24 const text = (doc.body.textContent ?? "").replace(/\s+/g, " ").trim();
25 return text.length > maxLength ? `${text.slice(0, maxLength).trimEnd()}…` : text;
26}
27
28/** True when a body holds no visible text — an editor left with `<p><br></p>` counts as empty. */
29export function isRichTextEmpty(html: string): boolean {
30 return richTextExcerpt(html, 1) === "";
31}
32
33const HTML_TAG = /<\/?[a-z][a-z0-9]*(\s[^>]*)?>/i;
34
35const escapeHtml = (text: string) =>
36 text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
37
38/**
39 * HTML for a stored note body. Editor-written bodies are HTML already; bodies
40 * from the Note Import Assistant (and older plain-text notes) are Markdown-ish
41 * text, which used to be shown with `pre-wrap`. Those get their headings,
42 * lists and paragraphs back as real blocks instead of one run-on line.
43 */
44export function toRichTextHtml(stored: string | null | undefined): string {
45 if (!stored?.trim()) return "";
46 if (HTML_TAG.test(stored)) return sanitizeRichText(stored);
47
48 const out: string[] = [];
49 type OpenList = { tag: "ul" | "ol"; items: string[] };
50 let list = null as OpenList | null;
51 let paragraph: string[] = [];
52 const flushParagraph = () => {
53 if (paragraph.length) out.push(`<p>${paragraph.join("<br>")}</p>`);
54 paragraph = [];
55 };
56 const flushList = () => {
57 if (list) out.push(`<${list.tag}>${list.items.map((item) => `<li>${item}</li>`).join("")}</${list.tag}>`);
58 list = null;
59 };
60
61 for (const raw of stored.replace(/\r\n?/g, "\n").split("\n")) {
62 const line = raw.trimEnd();
63 const heading = /^(#{1,6})\s+(.*)$/.exec(line);
64 const bullet = /^\s*[-*•]\s+(.*)$/.exec(line);
65 const numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line);
66 if (!line.trim()) {
67 flushParagraph();
68 flushList();
69 } else if (heading) {
70 flushParagraph();
71 flushList();
72 out.push(`<${heading[1].length <= 2 ? "h2" : "h3"}>${escapeHtml(heading[2])}</${heading[1].length <= 2 ? "h2" : "h3"}>`);
73 } else if (bullet || numbered) {
74 flushParagraph();
75 const tag = bullet ? "ul" : "ol";
76 if ((list as OpenList | null)?.tag !== tag) flushList();
77 const open: OpenList = (list as OpenList | null) ?? { tag, items: [] };
78 list = open;
79 open.items.push(escapeHtml((bullet ?? numbered)![1]));
80 } else {
81 flushList();
82 paragraph.push(escapeHtml(line));
83 }
84 }
85 flushParagraph();
86 flushList();
87 return out.join("");
88}