atagen

malice

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