| 1 | import { markdownEngine, rules, type MarkdownNode } from '@cloudrac3r/discord-markdown'; |
| 2 | import type { Emote } from './emotes'; |
| 3 | import type { Mention } from './mentions'; |
| 4 | |
| 5 | function escapeHtml(text: string): string { |
| 6 | return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); |
| 7 | } |
| 8 | |
| 9 | function escapeRegExp(text: string): string { |
| 10 | return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 11 | } |
| 12 | |
| 13 | function mentionLinker(mentions: Mention[]): (escaped: string) => string { |
| 14 | const byText = new Map(mentions.filter((m) => m.text).map((m) => [escapeHtml(m.text), m.user_id])); |
| 15 | if (byText.size === 0) return (escaped) => escaped; |
| 16 | const names = [...byText.keys()].sort((a, b) => b.length - a.length); |
| 17 | const pattern = new RegExp(names.map(escapeRegExp).join('|'), 'g'); |
| 18 | return (escaped) => |
| 19 | escaped.replace(pattern, (name) => `<a href="https://matrix.to/#/${escapeHtml(byText.get(name)!)}">${name}</a>`); |
| 20 | } |
| 21 | |
| 22 | function emoteLinker(emotes: Emote[]): (escaped: string) => string { |
| 23 | if (emotes.length === 0) return (escaped) => escaped; |
| 24 | const byCode = new Map(emotes.map((e) => [e.shortcode, e.mxc])); |
| 25 | return (escaped) => |
| 26 | escaped.replace(/:([\w+-]+):/g, (whole, code: string) => { |
| 27 | const mxc = byCode.get(code); |
| 28 | return mxc ? `<img data-mx-emoticon src="${escapeHtml(mxc)}" alt="${whole}" title="${whole}" height="32">` : whole; |
| 29 | }); |
| 30 | } |
| 31 | |
| 32 | function textToHtml(text: string, link: (escaped: string) => string): string { |
| 33 | return link(escapeHtml(text)).replace(/\n/g, '<br>'); |
| 34 | } |
| 35 | |
| 36 | const parseMarkdown = markdownEngine.parserFor( |
| 37 | Object.fromEntries(Object.entries(rules).filter(([name]) => !name.startsWith('discord'))) |
| 38 | ); |
| 39 | const INLINE_TAGS: Record<string, string> = { em: 'em', strong: 'strong', u: 'u', strike: 'del', small: 'sub' }; |
| 40 | const BLOCK_TYPES = new Set(['blockQuote', 'codeBlock', 'heading', 'list', 'paragraph']); |
| 41 | |
| 42 | function renderMarkdown(nodes: MarkdownNode[], link: (escaped: string) => string): string { |
| 43 | let html = ''; |
| 44 | let text = ''; |
| 45 | const flushText = () => { |
| 46 | html += textToHtml(text, link); |
| 47 | text = ''; |
| 48 | }; |
| 49 | for (const node of nodes) { |
| 50 | if (node.type === 'text') { |
| 51 | text += node.content; |
| 52 | continue; |
| 53 | } |
| 54 | flushText(); |
| 55 | const children = () => renderMarkdown(node.content, link); |
| 56 | const tag = INLINE_TAGS[node.type]; |
| 57 | if (tag) { |
| 58 | html += `<${tag}>${children()}</${tag}>`; |
| 59 | continue; |
| 60 | } |
| 61 | switch (node.type) { |
| 62 | case 'br': |
| 63 | case 'newline': |
| 64 | html += '<br>'; |
| 65 | break; |
| 66 | case 'inlineCode': |
| 67 | html += `<code>${escapeHtml(node.content)}</code>`; |
| 68 | break; |
| 69 | case 'codeBlock': { |
| 70 | const lang = /^[\w+#-]+$/.test(node.lang ?? '') ? ` class="language-${escapeHtml(node.lang)}"` : ''; |
| 71 | html += `<pre><code${lang}>${escapeHtml(node.content)}\n</code></pre>`; |
| 72 | break; |
| 73 | } |
| 74 | case 'spoiler': |
| 75 | html += `<span data-mx-spoiler>${renderMarkdown(node.parsed, link)}</span>`; |
| 76 | break; |
| 77 | case 'blockQuote': |
| 78 | html += `<blockquote>${children()}</blockquote>`; |
| 79 | break; |
| 80 | case 'paragraph': |
| 81 | html += `<p>${children()}</p>`; |
| 82 | break; |
| 83 | case 'heading': { |
| 84 | const level = Math.max(1, Math.min(6, node.level)); |
| 85 | html += `<h${level}>${children()}</h${level}>`; |
| 86 | break; |
| 87 | } |
| 88 | case 'list': { |
| 89 | const tag = node.ordered ? 'ol' : 'ul'; |
| 90 | const start = node.ordered && Number.isSafeInteger(node.start) && node.start > 0 ? ` start="${node.start}"` : ''; |
| 91 | html += `<${tag}${start}>${node.items.map((item: MarkdownNode[]) => `<li>${renderMarkdown(item, link)}</li>`).join('')}</${tag}>`; |
| 92 | break; |
| 93 | } |
| 94 | case 'link': |
| 95 | case 'url': |
| 96 | case 'autolink': { |
| 97 | const label = renderMarkdown(node.content, (escaped) => escaped); |
| 98 | const href = markdownEngine.sanitizeUrl(node.target); |
| 99 | const title = node.title ? ` title="${escapeHtml(node.title)}"` : ''; |
| 100 | html += href && /^(https?:|mailto:)/i.test(href) ? `<a href="${escapeHtml(href)}"${title}>${label}</a>` : label; |
| 101 | break; |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | flushText(); |
| 106 | return html; |
| 107 | } |
| 108 | |
| 109 | function markdownToHtml(body: string, link: (escaped: string) => string): string | null { |
| 110 | const nodes = parseMarkdown(body, { inline: true }); |
| 111 | const html = renderMarkdown(nodes, link); |
| 112 | if (html === textToHtml(body, (escaped) => escaped)) return null; |
| 113 | if (nodes.every((node) => node.type === 'text' || node.type === 'br' || node.type === 'newline') || |
| 114 | nodes.some((node) => BLOCK_TYPES.has(node.type))) return html; |
| 115 | return `<p>${html}</p>`; |
| 116 | } |
| 117 | |
| 118 | /** Matrix `formatted_body` for a composed message, or null when plain text says it all. */ |
| 119 | export function formatBody(body: string, mentions: Mention[], markdown: boolean, emotes: Emote[] = []): string | null { |
| 120 | const mention = mentionLinker(mentions); |
| 121 | const emote = emoteLinker(emotes); |
| 122 | const link = (escaped: string) => emote(mention(escaped)); |
| 123 | const html = markdown ? markdownToHtml(body, link) : null; |
| 124 | if (html !== null) return html; |
| 125 | const plain = textToHtml(body, link); |
| 126 | return plain === escapeHtml(body).replace(/\n/g, '<br>') ? null : plain; |
| 127 | } |
| 128 | |
| 129 | export function insideOpenFence(text: string, caret: number): boolean { |
| 130 | return (text.slice(0, caret).match(/^\s*```/gm)?.length ?? 0) % 2 === 1; |
| 131 | } |