Skip to main content

teloxide/utils/
html.rs

1//! Utils for working with the [HTML message style][spec].
2//!
3//! [spec]: https://core.telegram.org/bots/api#html-style
4
5use teloxide_core::types::{User, UserId};
6
7/// Applies the bold font style to the string.
8///
9/// Passed string will not be automatically escaped because it can contain
10/// nested markup.
11#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
12              without using its output does nothing useful"]
13pub fn bold(s: &str) -> String {
14    format!("<b>{s}</b>")
15}
16
17/// Applies the block quotation style to the string.
18///
19/// Passed string will not be automatically escaped because it can contain
20/// nested markup.
21#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
22              without using its output does nothing useful"]
23pub fn blockquote(s: &str) -> String {
24    format!("<blockquote>{s}</blockquote>")
25}
26
27/// Applies the expandable block quotation style to the string.
28///
29/// Passed string will not be automatically escaped because it can contain
30/// nested markup.
31#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
32              without using its output does nothing useful"]
33pub fn expandable_blockquote(s: &str) -> String {
34    format!("<blockquote expandable>{s}</blockquote>")
35}
36
37/// Applies the italic font style to the string.
38///
39/// Passed string will not be automatically escaped because it can contain
40/// nested markup.
41#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
42              without using its output does nothing useful"]
43pub fn italic(s: &str) -> String {
44    format!("<i>{s}</i>")
45}
46
47/// Applies the underline font style to the string.
48///
49/// Passed string will not be automatically escaped because it can contain
50/// nested markup.
51#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
52              without using its output does nothing useful"]
53pub fn underline(s: &str) -> String {
54    format!("<u>{s}</u>")
55}
56
57/// Applies the strikethrough font style to the string.
58///
59/// Passed string will not be automatically escaped because it can contain
60/// nested markup.
61#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
62              without using its output does nothing useful"]
63pub fn strike(s: &str) -> String {
64    format!("<s>{s}</s>")
65}
66
67/// Builds an inline link with an anchor.
68///
69/// Escapes the passed URL and the link text.
70#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
71              without using its output does nothing useful"]
72pub fn link(url: &str, text: &str) -> String {
73    let mut result = String::from("<a href=\"");
74    push_escaped_attr(url, &mut result);
75    result.push_str("\">");
76    result.push_str(&escape(text));
77    result.push_str("</a>");
78    result
79}
80
81/// Builds an inline user mention link with an anchor.
82#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
83              without using its output does nothing useful"]
84pub fn user_mention(user_id: UserId, text: &str) -> String {
85    link(format!("tg://user?id={user_id}").as_str(), text)
86}
87
88/// Formats the code block.
89///
90/// Escapes HTML characters inside the block.
91#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
92              without using its output does nothing useful"]
93pub fn code_block(code: &str) -> String {
94    format!("<pre>{}</pre>", escape(code))
95}
96
97/// Formats the code block with a specific language syntax.
98///
99/// Escapes HTML characters inside the block and the language attribute.
100#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
101              without using its output does nothing useful"]
102pub fn code_block_with_lang(code: &str, lang: &str) -> String {
103    let mut result = String::from("<pre><code class=\"language-");
104    push_escaped_attr(lang, &mut result);
105    result.push_str("\">");
106    result.push_str(&escape(code));
107    result.push_str("</code></pre>");
108    result
109}
110
111/// Formats the string as an inline code.
112///
113/// Escapes HTML characters inside the block.
114#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
115              without using its output does nothing useful"]
116pub fn code_inline(s: &str) -> String {
117    format!("<code>{}</code>", escape(s))
118}
119
120/// Escapes the string to be shown "as is" within the Telegram HTML message
121/// style.
122///
123/// Does not escape ' and " characters (as should be for usual HTML), because
124/// they shouldn't be escaped by the [spec].
125///
126/// [spec]: https://core.telegram.org/bots/api#html-style
127#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
128              without using its output does nothing useful"]
129pub fn escape(s: &str) -> String {
130    let mut result = String::with_capacity(s.len());
131    for ch in s.chars() {
132        push_escaped_char(ch, &mut result);
133    }
134    result
135}
136
137pub(super) fn push_escaped_char(ch: char, buf: &mut String) {
138    match ch {
139        '&' => buf.push_str("&amp;"),
140        '<' => buf.push_str("&lt;"),
141        '>' => buf.push_str("&gt;"),
142        ch => buf.push(ch),
143    }
144}
145
146/// Escapes a value in a double-quoted attribute, not in a text node.
147pub(super) fn push_escaped_attr(value: &str, buf: &mut String) {
148    for ch in value.chars() {
149        if ch == '"' {
150            buf.push_str("&quot;");
151        } else {
152            push_escaped_char(ch, buf);
153        }
154    }
155}
156
157#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
158              without using its output does nothing useful"]
159pub fn user_mention_or_link(user: &User) -> String {
160    match user.mention() {
161        Some(mention) => mention,
162        None => link(user.url().as_str(), &user.full_name()),
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn test_bold() {
172        assert_eq!(bold(" foobar "), "<b> foobar </b>");
173        assert_eq!(bold(" <i>foobar</i> "), "<b> <i>foobar</i> </b>");
174        assert_eq!(bold("<s>(`foobar`)</s>"), "<b><s>(`foobar`)</s></b>");
175    }
176
177    #[test]
178    fn test_italic() {
179        assert_eq!(italic(" foobar "), "<i> foobar </i>");
180        assert_eq!(italic(" <b>foobar</b> "), "<i> <b>foobar</b> </i>");
181        assert_eq!(italic("<s>(`foobar`)</s>"), "<i><s>(`foobar`)</s></i>");
182    }
183
184    #[test]
185    fn test_underline() {
186        assert_eq!(underline(" foobar "), "<u> foobar </u>");
187        assert_eq!(underline(" <b>foobar</b> "), "<u> <b>foobar</b> </u>");
188        assert_eq!(underline("<s>(`foobar`)</s>"), "<u><s>(`foobar`)</s></u>");
189    }
190
191    #[test]
192    fn test_strike() {
193        assert_eq!(strike(" foobar "), "<s> foobar </s>");
194        assert_eq!(strike(" <b>foobar</b> "), "<s> <b>foobar</b> </s>");
195        assert_eq!(strike("<b>(`foobar`)</b>"), "<s><b>(`foobar`)</b></s>");
196    }
197
198    #[test]
199    fn test_link() {
200        assert_eq!(
201            link("https://www.google.com/?q=foo&l=ru", "<google>"),
202            "<a href=\"https://www.google.com/?q=foo&amp;l=ru\">&lt;google&gt;</a>",
203        );
204        assert_eq!(
205            link("https://example.org/?q=\"a\"", "\"anchor\""),
206            "<a href=\"https://example.org/?q=&quot;a&quot;\">\"anchor\"</a>"
207        );
208    }
209
210    #[test]
211    fn test_user_mention() {
212        assert_eq!(
213            user_mention(UserId(123_456_789), "<pwner666>"),
214            "<a href=\"tg://user?id=123456789\">&lt;pwner666&gt;</a>",
215        );
216    }
217
218    #[test]
219    fn test_code_block() {
220        assert_eq!(
221            code_block("<p>pre-'formatted'\n & fixed-width \\code `block`</p>"),
222            "<pre>&lt;p&gt;pre-'formatted'\n &amp; fixed-width \\code `block`&lt;/p&gt;</pre>"
223        );
224    }
225
226    #[test]
227    fn test_code_block_with_lang() {
228        assert_eq!(
229            code_block_with_lang(
230                "<p>pre-'formatted'\n & fixed-width \\code `block`</p>",
231                "<html>\"",
232            ),
233            concat!(
234                "<pre><code class=\"language-&lt;html&gt;&quot;\">",
235                "&lt;p&gt;pre-'formatted'\n &amp; fixed-width \\code `block`&lt;/p&gt;",
236                "</code></pre>",
237            )
238        );
239    }
240
241    #[test]
242    fn test_code_inline() {
243        assert_eq!(
244            code_inline("<span class=\"foo\">foo & bar</span>"),
245            "<code>&lt;span class=\"foo\"&gt;foo &amp; bar&lt;/span&gt;</code>",
246        );
247    }
248
249    #[test]
250    fn test_escape() {
251        assert_eq!(
252            escape("  <title>Foo & Bar</title>   "),
253            "  &lt;title&gt;Foo &amp; Bar&lt;/title&gt;   "
254        );
255        assert_eq!(escape("<p>你好 & 再見</p>"), "&lt;p&gt;你好 &amp; 再見&lt;/p&gt;");
256        assert_eq!(escape("'foo\""), "'foo\"");
257    }
258
259    #[test]
260    fn user_mention_link() {
261        let user_with_username = User {
262            id: UserId(0),
263            is_bot: false,
264            first_name: "".to_string(),
265            last_name: None,
266            username: Some("abcd".to_string()),
267            language_code: None,
268            is_premium: false,
269            added_to_attachment_menu: false,
270        };
271        assert_eq!(user_mention_or_link(&user_with_username), "@abcd");
272        let user_without_username = User {
273            id: UserId(123_456_789),
274            is_bot: false,
275            first_name: "Name".to_string(),
276            last_name: None,
277            username: None,
278            language_code: None,
279            is_premium: false,
280            added_to_attachment_menu: false,
281        };
282        assert_eq!(
283            user_mention_or_link(&user_without_username),
284            r#"<a href="tg://user/?id=123456789">Name</a>"#
285        )
286    }
287}