BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / markdown.rs

markdown.rs

markdown.rs 5.1 KiB Download Raw
1use std::sync::LazyLock;
2
3use regex::Regex;
4
5use crate::italic::italicize;
6use crate::spans::Span;
7
8static CODE_FENCE: LazyLock<Regex> =
9 LazyLock::new(|| Regex::new(r"(?s)```[^\n`]*\n(.*?)```").unwrap());
10static INLINE_CODE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`([^`\n]+)`").unwrap());
11static BOLD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*([^*\n]+)\*\*").unwrap());
12static LINK: LazyLock<Regex> =
13 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\((https?://[^)\s]+)\)").unwrap());
14
15static MENTION: LazyLock<Regex> =
16 LazyLock::new(|| Regex::new(r"<at>([^<>\n]{1,100})</at>").unwrap());
17
18const LIST_MARKER: &str = "- ";
19
20pub fn escape_html(text: &str) -> String {
21 let mut escaped = String::with_capacity(text.len());
22 for character in text.chars() {
23 match character {
24 '&' => escaped.push_str("&amp;"),
25 '<' => escaped.push_str("&lt;"),
26 '>' => escaped.push_str("&gt;"),
27 '"' => escaped.push_str("&quot;"),
28 '\'' => escaped.push_str("&#x27;"),
29 other => escaped.push(other),
30 }
31 }
32 escaped
33}
34
35pub fn plain_text_to_html(text: &str) -> String {
36 escape_html(text).replace('\n', "<br>")
37}
38
39#[derive(Clone, Copy, PartialEq, Eq)]
40enum Dialect {
41 Message,
42 Card,
43}
44
45/// Teams chat HTML for light markdown, plus `- ` list lines as `<ul><li>`.
46pub fn markdown_to_html(text: &str) -> String {
47 render(text, Dialect::Message)
48}
49
50/// Like `markdown_to_html`, plus `_italic_`, `*italic*` and `<at>Name</at>` mentions.
51pub fn card_markdown_to_html(text: &str) -> String {
52 render(text, Dialect::Card)
53}
54
55fn render(text: &str, dialect: Dialect) -> String {
56 let mut html = String::new();
57 let mut position = 0;
58 for fence in CODE_FENCE.captures_iter(text) {
59 let whole = fence.get(0).expect("group 0 always exists");
60 html.push_str(&block_html(&text[position..whole.start()], dialect));
61 html.push_str("<pre>");
62 html.push_str(&escape_html(fence[1].trim_end_matches('\n')));
63 html.push_str("</pre>");
64 position = whole.end();
65 }
66 html.push_str(&block_html(&text[position..], dialect));
67 html
68}
69
70fn block_html(segment: &str, dialect: Dialect) -> String {
71 if !segment.lines().any(is_list_line) {
72 return inline_html(segment, dialect);
73 }
74 let mut html = String::new();
75 let mut text_run: Vec<&str> = Vec::new();
76 let mut list_run: Vec<&str> = Vec::new();
77 for line in segment.split('\n') {
78 if is_list_line(line) {
79 flush_text(&mut html, &mut text_run, dialect);
80 list_run.push(&line[LIST_MARKER.len()..]);
81 } else {
82 flush_list(&mut html, &mut list_run, dialect);
83 text_run.push(line);
84 }
85 }
86 flush_list(&mut html, &mut list_run, dialect);
87 flush_text(&mut html, &mut text_run, dialect);
88 html
89}
90
91fn is_list_line(line: &str) -> bool {
92 line.starts_with(LIST_MARKER)
93}
94
95fn flush_text(html: &mut String, run: &mut Vec<&str>, dialect: Dialect) {
96 if !run.is_empty() {
97 html.push_str(&inline_html(&run.join("\n"), dialect));
98 run.clear();
99 }
100}
101
102fn flush_list(html: &mut String, run: &mut Vec<&str>, dialect: Dialect) {
103 if run.is_empty() {
104 return;
105 }
106 html.push_str("<ul>");
107 for item in run.drain(..) {
108 html.push_str("<li>");
109 html.push_str(&inline_html(item, dialect));
110 html.push_str("</li>");
111 }
112 html.push_str("</ul>");
113}
114
115pub(crate) fn split_mentions(text: &str) -> Vec<Span> {
116 let mut spans = Vec::new();
117 let mut position = 0;
118 for mention in MENTION.captures_iter(text) {
119 let whole = mention.get(0).expect("group 0 always exists");
120 if whole.start() > position {
121 spans.push(Span::Text(text[position..whole.start()].to_owned()));
122 }
123 spans.push(Span::Mention {
124 name: mention[1].trim().to_owned(),
125 id: None,
126 });
127 position = whole.end();
128 }
129 if position < text.len() {
130 spans.push(Span::Text(text[position..].to_owned()));
131 }
132 spans
133}
134
135fn inline_html(text: &str, dialect: Dialect) -> String {
136 if dialect == Dialect::Message {
137 return inline_markdown(text, dialect);
138 }
139 let mut html = String::new();
140 let mut position = 0;
141 for mention in MENTION.captures_iter(text) {
142 let whole = mention.get(0).expect("group 0 always exists");
143 html.push_str(&inline_markdown(&text[position..whole.start()], dialect));
144 html.push_str("<at>");
145 html.push_str(&escape_html(&mention[1]));
146 html.push_str("</at>");
147 position = whole.end();
148 }
149 html.push_str(&inline_markdown(&text[position..], dialect));
150 html
151}
152
153fn inline_markdown(text: &str, dialect: Dialect) -> String {
154 let escaped = plain_text_to_html(text);
155 let coded = INLINE_CODE.replace_all(&escaped, "<code>${1}</code>");
156 let bolded = BOLD.replace_all(&coded, "<b>${1}</b>");
157 let styled = match dialect {
158 Dialect::Message => bolded.into_owned(),
159 Dialect::Card => italicize(&bolded),
160 };
161 LINK.replace_all(&styled, r#"<a href="${2}">${1}</a>"#)
162 .into_owned()
163}