Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/src/goal-markdown.ts

Raw
import { Marked } from "@earendil-works/pi-tui";

function escapeHtml(text: string): string {
	return text
		.replaceAll("&", "&")
		.replaceAll("<", "&lt;")
		.replaceAll(">", "&gt;")
		.replaceAll('"', "&quot;")
		.replaceAll("'", "&#39;");
}

/** One parser and one cached goal per observer, never shared Marked defaults. */
export function createGoalRenderer(): (goal: string) => string {
	const markdown = new Marked({
		gfm: true,
		breaks: false,
		pedantic: false,
		async: false,
		renderer: {
			html({ text }) {
				return escapeHtml(text);
			},
			image({ text }) {
				// Goals are untrusted: images must never trigger automatic requests.
				return escapeHtml(text);
			},
			link({ href, title, tokens }) {
				const label = this.parser.parseInline(tokens);
				let url: URL;
				try {
					url = new URL(href);
				} catch {
					return label;
				}
				if (!["http:", "https:", "mailto:"].includes(url.protocol))
					return label;
				return `<a href="${escapeHtml(url.href)}"${title ? ` title="${escapeHtml(title)}"` : ""} target="_blank" rel="noopener noreferrer">${label}</a>`;
			},
		},
	});
	let previous: string | undefined;
	let html = "";
	return (goal) => {
		if (goal !== previous) {
			html = markdown.parse(goal, { async: false });
			previous = goal;
		}
		return html;
	};
}