markdown.ts

2.6 KB · raw

1import MarkdownIt from "markdown-it";2import { type Html, trusted } from "./html.ts";3import { pathUrl } from "./layout.ts";45/** Where a Markdown file lives, so its relative links and images can point at the repo's raw files. */6export type MarkdownBase = { repo: string; dir: string; at: string | null };78const SCHEME = /^([a-z][a-z0-9+.-]*):/i;9const ALLOWED_SCHEMES = ["http", "https", "mailto"];1011// §25: raw HTML is off, so markdown-it's own escaping is the whole sanitizer.12const md = new MarkdownIt({ html: false, linkify: true });13md.validateLink = (url) => {14	const scheme = SCHEME.exec(url.trim());15	return !scheme || ALLOWED_SCHEMES.includes((scheme[1] as string).toLowerCase());16};17md.core.ruler.push("kepr_raw_links", (state) => {18	const base = state.env as MarkdownBase;19	const visit = (tokens: typeof state.tokens) => {20		for (const token of tokens) {21			const attr = token.type === "link_open" ? "href" : token.type === "image" ? "src" : null;22			const url = attr && token.attrGet(attr);23			if (attr && typeof url === "string") token.attrSet(attr, rawUrl(url, base));24			if (token.children) visit(token.children);25		}26	};27	visit(state.tokens);28});2930function rawUrl(url: string, base: MarkdownBase): string {31	if (SCHEME.test(url) || url.startsWith("#") || url.startsWith("//")) return url;32	// A leading `/` means the repo root, as it does on a code host.33	const resolved = new URL(url, `http://repo/${base.dir ? `${pathUrl(base.dir)}/` : ""}`);34	const at = base.at ? `?at=${base.at}` : "";35	return `/${base.repo}/raw${resolved.pathname}${at}${resolved.hash}`;36}3738export function renderMarkdown(source: string, base: MarkdownBase): Html {39	return trusted(md.render(source, base));40}4142/**43 * A paragraph of Markdown source (the README's first paragraph, found as the Atlas finds it) as44 * inline markup, and as plain text for link previews.45 */46export function renderParagraph(source: string, base: MarkdownBase): { html: Html; text: string } {47	const children = md.parseInline(source, base)[0]?.children ?? [];48	const text = children49		.map((token) =>50			token.type === "text" || token.type === "code_inline"51				? token.content52				: token.type === "softbreak"53					? " "54					: "",55		)56		.join("");57	return { html: trusted(md.renderer.renderInline(children, md.options, base)), text };58}5960/** One line of Markdown with links and images flattened away, for a row that is itself a link. */61export function renderLine(source: string, base: MarkdownBase): Html {62	const tokens = md.parseInline(source, base)[0]?.children ?? [];63	const kept = tokens.filter((token) => !/^(link_open|link_close|image)$/.test(token.type));64	return trusted(md.renderer.renderInline(kept, md.options, base));65}