import DOMPurify from 'dompurify' import { marked } from 'marked' export function splitFrontMatter(markdown: string): { meta: Record body: string } { if (!markdown.startsWith('---\n')) return { meta: {}, body: markdown } const end = markdown.indexOf('\n---\n', 4) if (end < 0) return { meta: {}, body: markdown } const meta: Record = {} for (const line of markdown.slice(4, end).split('\n')) { const index = line.indexOf(':') if (index < 0) continue const key = line.slice(0, index).trim() let value = line.slice(index + 1).trim() if (value.startsWith('"') && value.endsWith('"')) { value = value .slice(1, -1) .replace(/\\"/g, '"') .replace(/\\\\/g, '\\') } meta[key] = value } return { meta, body: markdown.slice(end + 5) } } /** The Markdown body without its front matter, ready for the clipboard. */ export function markdownBody(markdown: string): string { return splitFrontMatter(markdown).body.trim() } /** Rendered, sanitized article HTML. */ export function renderedBody(body: string): string { return DOMPurify.sanitize(marked.parse(body) as string) } /** * Copy Markdown and its rendered HTML in one write. Safari needs the * ClipboardItem built inside the click, before anything is awaited. */ export async function copyArticle(plain: string, html: string): Promise { const clipboard = navigator.clipboard if (typeof ClipboardItem !== 'undefined' && typeof clipboard.write === 'function') { const item = new ClipboardItem({ 'text/plain': new Blob([plain], { type: 'text/plain' }), 'text/html': new Blob([html], { type: 'text/html' }), }) await clipboard.write([item]) return } await clipboard.writeText(plain) }