Files
MySpace/frontend/src/markdown.ts
T

69 lines
2.8 KiB
TypeScript

import { marked } from "marked";
import DOMPurify from "dompurify";
import { publicBlogImagePath } from "./api";
// 仅保留 http(s) 与相对地址的图片;非图片标记的直接不渲染(原型把原始 HTML 当文本,不加载任何外部资源)
DOMPurify.addHook("uponSanitizeElement", (node: Node) => {
if (!(node instanceof Element)) return;
if (node.tagName === "IMG") {
const src = node.getAttribute("src") || "";
if (!/^(https?:)?\/\//i.test(src) && !src.startsWith("/") && !src.startsWith("data:image/")) {
node.remove();
}
return;
}
if (["SCRIPT", "IFRAME", "OBJECT", "EMBED", "STYLE", "LINK", "META", "BASE", "FORM"].includes(node.tagName)) {
node.remove();
}
});
export const markdown = (s: string) =>
DOMPurify.sanitize(marked.parse(s, { async: false }) as string);
// 外部链接在新标签页打开,不传出 window.opener,也不向对方发送完整来源地址(公开博客同样适用)
const assetImage = /^\/api\/v1\/assets\/([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\/content$/;
export const markdownForReading = (s: string, blogSlug?: string) => {
const host = document.createElement("template");
host.innerHTML = markdown(s);
if (blogSlug) {
host.content.querySelectorAll("img[src]").forEach((img) => {
const match = assetImage.exec(img.getAttribute("src") || "");
if (!match?.[1]) return;
img.setAttribute("src", publicBlogImagePath(blogSlug, match[1]));
img.removeAttribute("srcset");
});
}
host.content.querySelectorAll("a[href]").forEach((a) => {
if (!/^https?:\/\//i.test(a.getAttribute("href") || "")) return;
a.setAttribute("target", "_blank");
a.setAttribute("rel", "noopener noreferrer");
});
return host.innerHTML;
};
export function notePreview(text: string) {
const template = document.createElement("template");
template.innerHTML = markdown(text);
const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_TEXT);
const nodes: Text[] = [];
for (let node = walker.nextNode(); node; node = walker.nextNode()) nodes.push(node as Text);
for (const node of nodes) {
if (node.parentElement?.closest("a,pre,code,button")) continue;
const matches = [...node.data.matchAll(/\[\[([^\[\]\r\n]{1,120})\]\]/g)];
if (!matches.length) continue;
const fragment = document.createDocumentFragment();
let start = 0;
for (const match of matches) {
fragment.append(node.data.slice(start, match.index));
const link = document.createElement("button");
link.type = "button";
link.className = "linkbtn";
link.dataset.noteTitle = match[1];
link.textContent = match[1] ?? "";
fragment.append(link);
start = match.index + match[0].length;
}
fragment.append(node.data.slice(start));
node.replaceWith(fragment);
}
return template.innerHTML;
}