Skip to main content

telegram_rich/document/
render.rs

1//! Rendering a [`Document`] to Telegram Rich HTML.
2
3use std::fmt::Write as _;
4
5use super::{
6    Align, Block, ButtonStyle, Document, Inline, ListItem, Media, MediaKind, Table, VAlign,
7};
8use crate::types::InputRichMessage;
9
10impl Document {
11    /// Renders the document to Telegram Rich HTML, suitable for
12    /// [`InputRichMessage::html`].
13    pub fn to_html(&self) -> String {
14        let mut out = String::new();
15        render_blocks(&mut out, &self.blocks);
16        out
17    }
18
19    /// Renders the document and wraps it into an [`InputRichMessage`].
20    pub fn to_input_rich_message(&self) -> InputRichMessage {
21        InputRichMessage::html(self.to_html())
22    }
23}
24
25/// Escapes text content. Only `&`, `<` and `>` need escaping; the API supports
26/// a limited set of named entities, so no others are produced.
27pub(crate) fn escape_text(out: &mut String, s: &str) {
28    for c in s.chars() {
29        match c {
30            '&' => out.push_str("&amp;"),
31            '<' => out.push_str("&lt;"),
32            '>' => out.push_str("&gt;"),
33            _ => out.push(c),
34        }
35    }
36}
37
38fn escape_attr(out: &mut String, s: &str) {
39    for c in s.chars() {
40        match c {
41            '&' => out.push_str("&amp;"),
42            '<' => out.push_str("&lt;"),
43            '>' => out.push_str("&gt;"),
44            '"' => out.push_str("&quot;"),
45            _ => out.push(c),
46        }
47    }
48}
49
50fn attr(out: &mut String, name: &str, value: &str) {
51    out.push(' ');
52    out.push_str(name);
53    out.push_str("=\"");
54    escape_attr(out, value);
55    out.push('"');
56}
57
58fn render_blocks(out: &mut String, blocks: &[Block]) {
59    for b in blocks {
60        render_block(out, b);
61    }
62}
63
64/// Renders block content; a lone paragraph is rendered inline to keep list
65/// items and quotes compact.
66fn render_flow(out: &mut String, blocks: &[Block]) {
67    match blocks {
68        [Block::Paragraph(inl)] => render_inlines(out, inl),
69        _ => render_blocks(out, blocks),
70    }
71}
72
73fn wrap_inlines(out: &mut String, tag: &str, inl: &[Inline]) {
74    let _ = write!(out, "<{tag}>");
75    render_inlines(out, inl);
76    let _ = write!(out, "</{tag}>");
77}
78
79fn render_cite(out: &mut String, credit: &Option<Vec<Inline>>) {
80    if let Some(c) = credit {
81        wrap_inlines(out, "cite", c);
82    }
83}
84
85fn render_block(out: &mut String, b: &Block) {
86    match b {
87        Block::Paragraph(inl) => wrap_inlines(out, "p", inl),
88        Block::Heading { level, content } => {
89            let tag = format!("h{}", (*level).clamp(1, 6));
90            wrap_inlines(out, &tag, content);
91        }
92        Block::Preformatted { language, text } => {
93            out.push_str("<pre>");
94            match language {
95                Some(lang) => {
96                    out.push_str("<code");
97                    attr(out, "class", &format!("language-{lang}"));
98                    out.push('>');
99                    escape_text(out, text);
100                    out.push_str("</code>");
101                }
102                None => escape_text(out, text),
103            }
104            out.push_str("</pre>");
105        }
106        Block::Footer(inl) => wrap_inlines(out, "footer", inl),
107        Block::Divider => out.push_str("<hr/>"),
108        Block::MathBlock(src) => {
109            out.push_str("<tg-math-block>");
110            escape_text(out, src);
111            out.push_str("</tg-math-block>");
112        }
113        Block::Anchor(name) => {
114            out.push_str("<a");
115            attr(out, "name", name);
116            out.push_str("></a>");
117        }
118        Block::List {
119            ordered,
120            start,
121            items,
122        } => {
123            if *ordered {
124                out.push_str("<ol");
125                if let Some(s) = start {
126                    attr(out, "start", &s.to_string());
127                }
128                out.push('>');
129            } else {
130                out.push_str("<ul>");
131            }
132            for it in items {
133                render_list_item(out, it);
134            }
135            out.push_str(if *ordered { "</ol>" } else { "</ul>" });
136        }
137        Block::Quote { blocks, credit } => {
138            out.push_str("<blockquote>");
139            render_flow(out, blocks);
140            render_cite(out, credit);
141            out.push_str("</blockquote>");
142        }
143        Block::ExpandableQuote { content, credit } => {
144            out.push_str("<blockquote expandable>");
145            render_inlines(out, content);
146            render_cite(out, credit);
147            out.push_str("</blockquote>");
148        }
149        Block::PullQuote { content, credit } => {
150            out.push_str("<aside>");
151            render_inlines(out, content);
152            render_cite(out, credit);
153            out.push_str("</aside>");
154        }
155        Block::Media(m) => render_media(out, m),
156        Block::Table(t) => render_table(out, t),
157        Block::Details {
158            summary,
159            blocks,
160            open,
161        } => {
162            out.push_str(if *open { "<details open>" } else { "<details>" });
163            wrap_inlines(out, "summary", summary);
164            render_blocks(out, blocks);
165            out.push_str("</details>");
166        }
167        Block::Buttons { align, buttons } => {
168            out.push_str("<tg-button-row");
169            if let Some(a) = align {
170                attr(out, "align", align_str(*a));
171            }
172            out.push('>');
173            for btn in buttons {
174                out.push_str("<tg-button type=\"url\"");
175                if let Some(s) = btn.style {
176                    attr(
177                        out,
178                        "style",
179                        match s {
180                            ButtonStyle::Danger => "danger",
181                            ButtonStyle::Success => "success",
182                            ButtonStyle::Primary => "primary",
183                        },
184                    );
185                }
186                attr(out, "url", &btn.url);
187                out.push('>');
188                escape_text(out, &btn.text);
189                out.push_str("</tg-button>");
190            }
191            out.push_str("</tg-button-row>");
192        }
193    }
194}
195
196fn render_list_item(out: &mut String, it: &ListItem) {
197    out.push_str("<li>");
198    match it.checkbox {
199        Some(true) => out.push_str("<input type=\"checkbox\" checked>"),
200        Some(false) => out.push_str("<input type=\"checkbox\">"),
201        None => {}
202    }
203    render_flow(out, &it.blocks);
204    out.push_str("</li>");
205}
206
207fn render_media(out: &mut String, m: &Media) {
208    let has_caption = m.caption.is_some() || m.credit.is_some();
209    if has_caption {
210        out.push_str("<figure>");
211    }
212    match m.kind {
213        MediaKind::Photo => {
214            out.push_str("<img");
215            attr(out, "src", &m.src);
216            if m.spoiler {
217                out.push_str(" tg-spoiler");
218            }
219            out.push_str("/>");
220        }
221        MediaKind::Video | MediaKind::Animation => {
222            out.push_str("<video");
223            attr(out, "src", &m.src);
224            if m.spoiler {
225                out.push_str(" tg-spoiler");
226            }
227            out.push_str("></video>");
228        }
229        MediaKind::Audio => {
230            out.push_str("<audio");
231            attr(out, "src", &m.src);
232            out.push_str("></audio>");
233        }
234        MediaKind::Document => {
235            out.push_str("<tg-document");
236            attr(out, "src", &m.src);
237            out.push_str("></tg-document>");
238        }
239    }
240    if has_caption {
241        out.push_str("<figcaption>");
242        if let Some(c) = &m.caption {
243            render_inlines(out, c);
244        }
245        render_cite(out, &m.credit);
246        out.push_str("</figcaption></figure>");
247    }
248}
249
250fn align_str(a: Align) -> &'static str {
251    match a {
252        Align::Left => "left",
253        Align::Center => "center",
254        Align::Right => "right",
255    }
256}
257
258fn render_table(out: &mut String, t: &Table) {
259    out.push_str("<table");
260    if t.bordered {
261        out.push_str(" bordered");
262    }
263    if t.striped {
264        out.push_str(" striped");
265    }
266    if t.compact {
267        out.push_str(" compact");
268    }
269    out.push('>');
270    if let Some(c) = &t.caption {
271        wrap_inlines(out, "caption", c);
272    }
273    for row in &t.rows {
274        out.push_str("<tr>");
275        for cell in row {
276            let tag = if cell.header { "th" } else { "td" };
277            out.push('<');
278            out.push_str(tag);
279            if let Some(n) = cell.colspan.filter(|n| *n > 1) {
280                attr(out, "colspan", &n.to_string());
281            }
282            if let Some(n) = cell.rowspan.filter(|n| *n > 1) {
283                attr(out, "rowspan", &n.to_string());
284            }
285            if let Some(a) = cell.align {
286                attr(out, "align", align_str(a));
287            }
288            if let Some(v) = cell.valign {
289                attr(
290                    out,
291                    "valign",
292                    match v {
293                        VAlign::Top => "top",
294                        VAlign::Middle => "middle",
295                        VAlign::Bottom => "bottom",
296                    },
297                );
298            }
299            out.push('>');
300            render_inlines(out, &cell.content);
301            let _ = write!(out, "</{tag}>");
302        }
303        out.push_str("</tr>");
304    }
305    out.push_str("</table>");
306}
307
308pub(crate) fn render_inlines(out: &mut String, inl: &[Inline]) {
309    for i in inl {
310        render_inline(out, i);
311    }
312}
313
314fn render_inline(out: &mut String, i: &Inline) {
315    match i {
316        Inline::Text(t) => escape_text(out, t),
317        Inline::Bold(c) => wrap_inlines(out, "b", c),
318        Inline::Italic(c) => wrap_inlines(out, "i", c),
319        Inline::Underline(c) => wrap_inlines(out, "u", c),
320        Inline::Strikethrough(c) => wrap_inlines(out, "s", c),
321        Inline::Spoiler(c) => wrap_inlines(out, "tg-spoiler", c),
322        Inline::Marked(c) => wrap_inlines(out, "mark", c),
323        Inline::Subscript(c) => wrap_inlines(out, "sub", c),
324        Inline::Superscript(c) => wrap_inlines(out, "sup", c),
325        Inline::Code(t) => {
326            out.push_str("<code>");
327            escape_text(out, t);
328            out.push_str("</code>");
329        }
330        Inline::Math(t) => {
331            out.push_str("<tg-math>");
332            escape_text(out, t);
333            out.push_str("</tg-math>");
334        }
335        Inline::Link { href, content } => {
336            out.push_str("<a");
337            attr(out, "href", href);
338            out.push('>');
339            render_inlines(out, content);
340            out.push_str("</a>");
341        }
342        Inline::LineBreak => out.push_str("<br/>"),
343    }
344}