1use teloxide_core::types::{MessageEntity, MessageEntityKind as MEK};
4
5use tag::*;
6
7pub use helper::RenderMessageTextHelper;
8
9mod helper;
10mod html;
11mod markdown;
12mod tag;
13
14#[derive(Clone, Eq, PartialEq)]
16pub struct Renderer<'a> {
17 text: &'a str,
18 tags: Vec<Tag<'a>>,
19}
20
21impl<'a> Renderer<'a> {
22 #[must_use]
31 pub fn new(text: &'a str, entities: &'a [MessageEntity]) -> Self {
32 let needed_size: usize = entities
34 .iter()
35 .filter(|e| {
36 matches!(
37 e.kind,
38 MEK::Bold
39 | MEK::Blockquote
40 | MEK::ExpandableBlockquote
41 | MEK::Italic
42 | MEK::Underline
43 | MEK::Strikethrough
44 | MEK::Spoiler
45 | MEK::Code
46 | MEK::Pre { .. }
47 | MEK::TextLink { .. }
48 | MEK::TextMention { .. }
49 | MEK::CustomEmoji { .. }
50 )
51 })
52 .count()
53 * 2; let mut tags = Vec::with_capacity(needed_size);
56
57 for (index, entity) in entities.iter().enumerate() {
58 let kind = match &entity.kind {
59 MEK::Bold => Kind::Bold,
60 MEK::Blockquote => Kind::Blockquote,
61 MEK::ExpandableBlockquote => Kind::ExpandableBlockquote,
62 MEK::Italic => Kind::Italic,
63 MEK::Underline => Kind::Underline,
64 MEK::Strikethrough => Kind::Strikethrough,
65 MEK::Spoiler => Kind::Spoiler,
66 MEK::Code => Kind::Code,
67 MEK::Pre { language } => Kind::Pre(language.as_ref().map(String::as_str)),
68 MEK::TextLink { url } => Kind::TextLink(url.as_str()),
69 MEK::TextMention { user } => Kind::TextMention(user.id.0),
70 MEK::CustomEmoji { custom_emoji_id } => Kind::CustomEmoji(custom_emoji_id),
71 _ => continue,
72 };
73
74 tags.push(Tag::start(kind.clone(), entity.offset, index));
77
78 if matches!(kind, Kind::Blockquote | Kind::ExpandableBlockquote) {
79 let new_lines = text
80 .encode_utf16()
81 .skip(entity.offset)
82 .take(entity.length)
83 .enumerate()
84 .filter_map(|(idx, unit)| (unit == u16::from(b'\n')).then_some(idx));
85
86 for new_line_index in new_lines {
87 tags.push(Tag::mid_new_line(
88 kind.clone(),
89 entity.offset + new_line_index + 1,
90 index,
91 ));
92 }
93 }
94
95 tags.push(Tag::end(kind, entity.offset + entity.length, index));
96 }
97
98 tags.sort_unstable();
99
100 Self { text, tags }
101 }
102
103 #[must_use]
109 fn format(&self, writer: &TagWriter) -> String {
110 let mut buffer =
111 String::with_capacity(self.text.len() + writer.get_extra_size_for_tags(&self.tags));
112 let mut tags = self.tags.iter();
113 let mut current_tag = tags.next();
114
115 let mut prev_point = None;
116
117 for (idx, point) in self.text.encode_utf16().enumerate() {
118 loop {
119 match current_tag {
120 Some(tag) if tag.offset == idx => {
121 (writer.write_tag_fn)(tag, &mut buffer);
122 current_tag = tags.next();
123 }
124 _ => break,
125 }
126 }
127
128 let ch = if let Some(previous) = prev_point.take() {
129 char::decode_utf16([previous, point]).next().unwrap().unwrap()
130 } else {
131 match char::decode_utf16([point]).next().unwrap() {
132 Ok(c) => c,
133 Err(unpaired) => {
134 prev_point = Some(unpaired.unpaired_surrogate());
135 continue;
136 }
137 }
138 };
139
140 (writer.write_char_fn)(ch, &mut buffer);
141 }
142
143 for tag in current_tag.into_iter().chain(tags) {
144 (writer.write_tag_fn)(tag, &mut buffer);
145 }
146
147 buffer
148 }
149
150 #[must_use]
152 #[inline]
153 pub fn as_html(&self) -> String {
154 self.format(&html::HTML)
155 }
156
157 #[must_use]
159 #[inline]
160 pub fn as_markdown(&self) -> String {
161 self.format(&markdown::MARKDOWN)
162 }
163}
164
165#[cfg(test)]
166mod test {
167 use super::*;
168
169 #[test]
170 fn escapes_literal_text_even_without_formatting_tags() {
171 let text = "š <b> & _!";
172 let ignored_entity = [MessageEntity { kind: MEK::Url, offset: 3, length: 3 }];
173 for entities in [&[][..], &ignored_entity[..]] {
174 let renderer = Renderer::new(text, entities);
175 assert_eq!(renderer.as_html(), "š <b> & _!");
176 assert_eq!(renderer.as_markdown(), r"š <b\> & \_\!");
177 }
178 }
179
180 #[test]
181 fn markdown_blockquote_line_breaks_use_utf16_offsets() {
182 let text = "š\nš¬ one\nš” two";
183 let quote = [MessageEntity { kind: MEK::Blockquote, offset: 3, length: 13 }];
184 assert_eq!(Renderer::new(text, "e).as_markdown(), "š\n**>š¬ one\n>š” two");
185 }
186
187 #[test]
188 fn renderer_escapes_html_attributes() {
189 let entities = [
190 MessageEntity {
191 kind: MEK::TextLink {
192 url: reqwest::Url::parse("https://example.org/?a=1&b=2").unwrap(),
193 },
194 offset: 0,
195 length: 1,
196 },
197 MessageEntity {
198 kind: MEK::Pre { language: Some("x\"&<>".to_owned()) },
199 offset: 1,
200 length: 1,
201 },
202 ];
203 assert_eq!(
204 Renderer::new("a<", &entities).as_html(),
205 concat!(
206 "<a href=\"https://example.org/?a=1&b=2\">a</a>",
207 "<pre><code class=\"language-x"&<>\"><</code></pre>"
208 )
209 );
210 }
211
212 #[test]
213 fn test_render_simple() {
214 let text = "Bold italic <underline_";
215 let entities = vec![
216 MessageEntity { kind: MEK::Bold, offset: 0, length: 4 },
217 MessageEntity { kind: MEK::Italic, offset: 5, length: 6 },
218 MessageEntity { kind: MEK::Underline, offset: 12, length: 10 },
219 ];
220
221 let render = Renderer::new(text, &entities);
222
223 assert_eq!(render.as_html(), "<b>Bold</b> <i>italic</i> <u><underline</u>_");
224 assert_eq!(render.as_markdown(), "*Bold* _\ritalic_\r __\r<underline__\r\\_");
225 }
226
227 #[test]
228 fn test_render_pre_with_lang() {
229 let text = "Some pre, normal and rusty code";
230 let entities = vec![
231 MessageEntity { kind: MEK::Pre { language: None }, offset: 5, length: 3 },
232 MessageEntity { kind: MEK::Code, offset: 10, length: 6 },
233 MessageEntity {
234 kind: MEK::Pre { language: Some("rust".to_owned()) },
235 offset: 21,
236 length: 5,
237 },
238 ];
239
240 let render = Renderer::new(text, &entities);
241
242 assert_eq!(
243 render.as_html(),
244 "Some <pre>pre</pre>, <code>normal</code> and <pre><code \
245 class=\"language-rust\">rusty</code></pre> code",
246 );
247 assert_eq!(
248 render.as_markdown(),
249 "Some ```\npre```\n, `normal` and ```rust\nrusty```\n code",
250 );
251 }
252
253 #[test]
254 fn test_render_nested() {
255 let text = "Some bold both italics";
256 let entities = vec![
257 MessageEntity { kind: MEK::Bold, offset: 5, length: 9 },
258 MessageEntity { kind: MEK::Italic, offset: 10, length: 12 },
259 ];
260
261 let render = Renderer::new(text, &entities);
262
263 assert_eq!(render.as_html(), "Some <b>bold <i>both</b> italics</i>");
264 assert_eq!(render.as_markdown(), "Some *bold _\rboth* italics_\r");
265 }
266
267 #[test]
268 fn test_render_complex() {
269 let text = "Hi how are you?\nnested entities are cool\nIm in a Blockquote!\nIm in a \
270 multiline Blockquote!\n\nIm in a multiline Blockquote!\nIm in an expandable \
271 Blockquote!\nIm in an expandable multiline Blockquote!\n\nIm in an expandable \
272 multiline Blockquote!";
273 let entities = vec![
274 MessageEntity { kind: MEK::Bold, offset: 0, length: 2 },
275 MessageEntity { kind: MEK::Italic, offset: 3, length: 3 },
276 MessageEntity { kind: MEK::Underline, offset: 7, length: 3 },
277 MessageEntity { kind: MEK::Strikethrough, offset: 11, length: 3 },
278 MessageEntity { kind: MEK::Bold, offset: 16, length: 1 },
279 MessageEntity { kind: MEK::Bold, offset: 17, length: 5 },
280 MessageEntity { kind: MEK::Underline, offset: 17, length: 4 },
281 MessageEntity { kind: MEK::Strikethrough, offset: 17, length: 4 },
282 MessageEntity {
283 kind: MEK::TextLink { url: reqwest::Url::parse("https://t.me/").unwrap() },
284 offset: 23,
285 length: 8,
286 },
287 MessageEntity {
288 kind: MEK::TextLink { url: reqwest::Url::parse("tg://user?id=1234567").unwrap() },
289 offset: 32,
290 length: 3,
291 },
292 MessageEntity { kind: MEK::Code, offset: 36, length: 4 },
293 MessageEntity { kind: MEK::Blockquote, offset: 41, length: 19 },
294 MessageEntity { kind: MEK::Blockquote, offset: 61, length: 60 },
295 MessageEntity { kind: MEK::ExpandableBlockquote, offset: 122, length: 31 },
296 MessageEntity { kind: MEK::ExpandableBlockquote, offset: 154, length: 84 },
297 ];
298
299 let render = Renderer::new(text, &entities);
300
301 assert_eq!(
302 render.as_html(),
303 "<b>Hi</b> <i>how</i> <u>are</u> <s>you</s>?\n<b>n</b><b><u><s>este</s></u>d</b> \
304 <a href=\"https://t.me/\">entities</a> <a href=\"tg://user?id=1234567\">are</a> <code>cool</code>\n\
305 <blockquote>Im in a Blockquote!</blockquote>\n\
306 <blockquote>Im in a multiline Blockquote!\n\nIm in a multiline Blockquote!</blockquote>\n\
307 <blockquote expandable>Im in an expandable Blockquote!</blockquote>\n\
308 <blockquote expandable>Im in an expandable multiline Blockquote!\n\nIm in an expandable multiline Blockquote!</blockquote>"
309 );
310 assert_eq!(
311 render.as_markdown(),
312 "*Hi* _\rhow_\r __\rare__\r ~you~?\n*n**__\r~este~__\rd* [entities](https://t.me/) \
313 [are](tg://user?id=1234567) `cool`\n**>Im in a Blockquote\\!\n**>Im in a multiline \
314 Blockquote\\!\n>\n>Im in a multiline Blockquote\\!\n**>Im in an expandable \
315 Blockquote\\!||\n**>Im in an expandable multiline Blockquote\\!\n>\n>Im in an \
316 expandable multiline Blockquote\\!||"
317 );
318 }
319}