Skip to main content

telegram_rich/document/
mod.rs

1//! Intermediate representation of a Telegram rich message document.
2//!
3//! Arbitrary web HTML is first normalized into this tree (see the `html`
4//! module), which only contains constructs that Telegram rich messages can
5//! render. A [`Document`] can also be built by hand. It can then be measured
6//! against [`Limits`](crate::Limits), truncated at block boundaries with
7//! [`Document::fit`] and rendered to Telegram Rich HTML with
8//! [`Document::to_html`].
9
10mod fit;
11mod measure;
12mod render;
13
14pub use fit::FitOptions;
15
16/// A normalized rich message document: an ordered list of top-level blocks.
17#[derive(Debug, Clone, Default, PartialEq)]
18pub struct Document {
19    /// Top-level blocks of the document.
20    pub blocks: Vec<Block>,
21}
22
23/// A block-level element.
24#[derive(Debug, Clone, PartialEq)]
25pub enum Block {
26    /// A text paragraph (`<p>`).
27    Paragraph(Vec<Inline>),
28    /// A section heading (`<h1>`–`<h6>`); `level` is clamped to `1..=6`.
29    Heading {
30        /// Heading level, 1 is the largest.
31        level: u8,
32        /// Heading content.
33        content: Vec<Inline>,
34    },
35    /// A preformatted block (`<pre>` / `<pre><code class="language-…">`).
36    Preformatted {
37        /// Optional programming language.
38        language: Option<String>,
39        /// Raw text, whitespace preserved.
40        text: String,
41    },
42    /// A footer (`<footer>`).
43    Footer(Vec<Inline>),
44    /// A horizontal divider (`<hr/>`).
45    Divider,
46    /// A block formula (`<tg-math-block>`), raw LaTeX.
47    MathBlock(String),
48    /// An anchor target (`<a name="…"></a>`).
49    Anchor(String),
50    /// An ordered or unordered list.
51    List {
52        /// Whether the list is ordered (`<ol>`).
53        ordered: bool,
54        /// Optional start number for ordered lists.
55        start: Option<i64>,
56        /// List items.
57        items: Vec<ListItem>,
58    },
59    /// A block quotation (`<blockquote>`), may contain nested blocks.
60    Quote {
61        /// Quoted content.
62        blocks: Vec<Block>,
63        /// Optional credit (`<cite>`).
64        credit: Option<Vec<Inline>>,
65    },
66    /// An expandable block quotation (`<blockquote expandable>`), inline content only.
67    ExpandableQuote {
68        /// Quoted content; use [`Inline::LineBreak`] for line breaks.
69        content: Vec<Inline>,
70        /// Optional credit (`<cite>`).
71        credit: Option<Vec<Inline>>,
72    },
73    /// A pull quotation (`<aside>`).
74    PullQuote {
75        /// Quoted content.
76        content: Vec<Inline>,
77        /// Optional credit (`<cite>`).
78        credit: Option<Vec<Inline>>,
79    },
80    /// A standalone media element.
81    Media(Media),
82    /// A table; cells contain inline content only.
83    Table(Table),
84    /// A disclosure block (`<details>`).
85    Details {
86        /// Always visible summary.
87        summary: Vec<Inline>,
88        /// Collapsible content.
89        blocks: Vec<Block>,
90        /// Whether the block is expanded by default.
91        open: bool,
92    },
93    /// A row of URL buttons (`<tg-button-row>`), 1–8 buttons.
94    Buttons {
95        /// Horizontal alignment.
96        align: Option<Align>,
97        /// Buttons in the row.
98        buttons: Vec<UrlButton>,
99    },
100}
101
102/// An item of a [`Block::List`].
103#[derive(Debug, Clone, Default, PartialEq)]
104pub struct ListItem {
105    /// Item content.
106    pub blocks: Vec<Block>,
107    /// `Some(checked)` if the item has a checkbox.
108    pub checkbox: Option<bool>,
109}
110
111/// A media element.
112#[derive(Debug, Clone, PartialEq)]
113pub struct Media {
114    /// Media kind, rendered as the matching HTML tag.
115    pub kind: MediaKind,
116    /// Absolute `http(s)://` URL or a `tg://photo?id=…`-style reference.
117    pub src: String,
118    /// Optional caption (`<figcaption>`).
119    pub caption: Option<Vec<Inline>>,
120    /// Optional caption credit (`<cite>` inside `<figcaption>`).
121    pub credit: Option<Vec<Inline>>,
122    /// Whether the media is covered by a spoiler.
123    pub spoiler: bool,
124}
125
126/// Kind of a [`Media`] element.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum MediaKind {
129    /// A photo (`<img>`).
130    Photo,
131    /// A video (`<video>`).
132    Video,
133    /// An animation, e.g. GIF (`<video>` pointing to an animation).
134    Animation,
135    /// An audio file (`<audio>`).
136    Audio,
137    /// A general file (`<tg-document>`).
138    Document,
139}
140
141/// A table block.
142#[derive(Debug, Clone, Default, PartialEq)]
143pub struct Table {
144    /// Rows of cells.
145    pub rows: Vec<Vec<TableCell>>,
146    /// Optional caption.
147    pub caption: Option<Vec<Inline>>,
148    /// Draw borders.
149    pub bordered: bool,
150    /// Striped rows.
151    pub striped: bool,
152    /// Compact cell padding (Bot API 10.3+).
153    pub compact: bool,
154}
155
156/// A table cell.
157#[derive(Debug, Clone, Default, PartialEq)]
158pub struct TableCell {
159    /// Inline content of the cell.
160    pub content: Vec<Inline>,
161    /// Header cell (`<th>`).
162    pub header: bool,
163    /// Column span, if greater than 1.
164    pub colspan: Option<u32>,
165    /// Row span, if greater than 1.
166    pub rowspan: Option<u32>,
167    /// Horizontal alignment.
168    pub align: Option<Align>,
169    /// Vertical alignment.
170    pub valign: Option<VAlign>,
171}
172
173/// Horizontal alignment.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum Align {
176    /// Left.
177    Left,
178    /// Center.
179    Center,
180    /// Right.
181    Right,
182}
183
184/// Vertical alignment.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum VAlign {
187    /// Top.
188    Top,
189    /// Middle.
190    Middle,
191    /// Bottom.
192    Bottom,
193}
194
195/// A URL button inside a [`Block::Buttons`] row.
196#[derive(Debug, Clone, PartialEq)]
197pub struct UrlButton {
198    /// Button label (plain text).
199    pub text: String,
200    /// HTTP(S) or `tg://` URL.
201    pub url: String,
202    /// Optional style.
203    pub style: Option<ButtonStyle>,
204}
205
206/// Style of a [`UrlButton`].
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum ButtonStyle {
209    /// Red.
210    Danger,
211    /// Green.
212    Success,
213    /// Accent color.
214    Primary,
215}
216
217/// Inline (phrasing) content.
218#[derive(Debug, Clone, PartialEq)]
219pub enum Inline {
220    /// Plain text.
221    Text(String),
222    /// Bold.
223    Bold(Vec<Inline>),
224    /// Italic.
225    Italic(Vec<Inline>),
226    /// Underline.
227    Underline(Vec<Inline>),
228    /// Strikethrough.
229    Strikethrough(Vec<Inline>),
230    /// Spoiler.
231    Spoiler(Vec<Inline>),
232    /// Marked / highlighted.
233    Marked(Vec<Inline>),
234    /// Subscript.
235    Subscript(Vec<Inline>),
236    /// Superscript.
237    Superscript(Vec<Inline>),
238    /// Inline monospace code (plain text only).
239    Code(String),
240    /// Inline formula, raw LaTeX.
241    Math(String),
242    /// A link to an `http(s)`, `mailto:`, `tel:`, `tg://user` URL or an in-document `#anchor`.
243    Link {
244        /// Target URL.
245        href: String,
246        /// Link content.
247        content: Vec<Inline>,
248    },
249    /// A line break (`<br>`).
250    LineBreak,
251}
252
253impl Inline {
254    /// Convenience constructor for [`Inline::Text`].
255    pub fn text(s: impl Into<String>) -> Self {
256        Inline::Text(s.into())
257    }
258}
259
260impl Block {
261    /// Convenience constructor for a paragraph containing plain text.
262    pub fn paragraph(s: impl Into<String>) -> Self {
263        Block::Paragraph(vec![Inline::Text(s.into())])
264    }
265
266    /// Convenience constructor for a single-button row linking to `url`.
267    pub fn link_button(text: impl Into<String>, url: impl Into<String>) -> Self {
268        Block::Buttons {
269            align: None,
270            buttons: vec![UrlButton {
271                text: text.into(),
272                url: url.into(),
273                style: None,
274            }],
275        }
276    }
277}
278
279impl Document {
280    /// Creates a document from blocks.
281    pub fn new(blocks: Vec<Block>) -> Self {
282        Self { blocks }
283    }
284
285    /// Returns `true` if the document has no blocks.
286    pub fn is_empty(&self) -> bool {
287        self.blocks.is_empty()
288    }
289
290    /// Visits every media element mutably, e.g. to rewrite URLs to
291    /// `tg://photo?id=…` references for explicit uploads.
292    pub fn for_each_media_mut(&mut self, mut f: impl FnMut(&mut Media)) {
293        fn walk(blocks: &mut [Block], f: &mut dyn FnMut(&mut Media)) {
294            for b in blocks {
295                match b {
296                    Block::Media(m) => f(m),
297                    Block::List { items, .. } => {
298                        for it in items {
299                            walk(&mut it.blocks, f);
300                        }
301                    }
302                    Block::Quote { blocks, .. } | Block::Details { blocks, .. } => walk(blocks, f),
303                    _ => {}
304                }
305            }
306        }
307        walk(&mut self.blocks, &mut f);
308    }
309
310    /// Collects references to every media element in document order.
311    pub fn media(&self) -> Vec<&Media> {
312        fn walk<'a>(blocks: &'a [Block], out: &mut Vec<&'a Media>) {
313            for b in blocks {
314                match b {
315                    Block::Media(m) => out.push(m),
316                    Block::List { items, .. } => {
317                        for it in items {
318                            walk(&it.blocks, out);
319                        }
320                    }
321                    Block::Quote { blocks, .. } | Block::Details { blocks, .. } => {
322                        walk(blocks, out)
323                    }
324                    _ => {}
325                }
326            }
327        }
328        let mut out = Vec::new();
329        walk(&self.blocks, &mut out);
330        out
331    }
332}