| 1 | //! Library for sanitizing and converting HTML strings to something that [Pango] can render. |
| 2 | //! |
| 3 | //! This library contains several functions to (pre)process text to [Pango Markup]. |
| 4 | //! What to use and when depends on the type of input and the desired result. This can range from |
| 5 | //! just escaping to converting and sanitizing. See the examples below for what is available |
| 6 | //! based on the input type. |
| 7 | //! |
| 8 | //! The functions below convert strings to strings. If your input can contain several block |
| 9 | //! elements such as headings, lists, code or quote blocks, see the [`block`] module to convert an |
| 10 | //! input string into a list of these blocks. |
| 11 | //! |
| 12 | //! # Markdown/body HTML |
| 13 | //! |
| 14 | //! To handle more HTML, use the [`markup_html`] function. This function supports HTML body markup |
| 15 | //! such as HTML resulting from a [Markdown]-to-HTML conversion. It tries to convert the input to |
| 16 | //! [Pango Markup] such that rendering by Pango will make it similar like what a browser would. |
| 17 | //! This involves adding newlines for paragraphs and lists, converting font styles, etc. |
| 18 | //! |
| 19 | //! ```rust |
| 20 | //! # use html2pango::markup_html; |
| 21 | //! let m = markup_html("<body>this is some <font color=\"#ff0000\">red text</font>!</body>").unwrap(); |
| 22 | //! assert_eq!(m, "this is some <span foreground=\"#ff0000\">red text</span>!"); |
| 23 | //! |
| 24 | //! let m = markup_html("<body>a nice <a href=\"https://gnome.org\">link</a>").unwrap(); |
| 25 | //! assert_eq!(m, "a nice <a href=\"https://gnome.org\">link</a>"); |
| 26 | //! |
| 27 | //! let m = markup_html("<body>some items: <ul><li>first</li><li>second</li></ul><body").unwrap(); |
| 28 | //! assert_eq!(m, "some items: \n • first\n • second\n"); |
| 29 | //! ``` |
| 30 | //! |
| 31 | //! ## Escaping |
| 32 | //! |
| 33 | //! To just escape any HTML reserved characters, use [`html_escape`]: |
| 34 | //! |
| 35 | //! ```rust |
| 36 | //! # use html2pango::html_escape; |
| 37 | //! let s = html_escape("this is a <tag> & this is \"quoted text\""); |
| 38 | //! assert_eq!(s, "this is a <tag> & this is "quoted text""); |
| 39 | //! ``` |
| 40 | //! |
| 41 | //! ## Matrix custom HTML |
| 42 | //! |
| 43 | //! For [Matrix], its [specification][Matrix specification] defines a custom HTML format that |
| 44 | //! specifies the tags and attributes that can be used. Use [`matrix_html_to_markup`] to handle |
| 45 | //! this custom HTML input so that input is sanitized before it is converted. |
| 46 | //! |
| 47 | //! This function is still work-in-progress! |
| 48 | //! |
| 49 | //! # Simple HTML |
| 50 | //! |
| 51 | //! By simple HTML, we mean plain text that only contains some formatting tags such as |
| 52 | //! `<strong>`, `<i>`, `<code>`, etc. |
| 53 | //! For the full list of supported tags and how they are replaced, see [`markup_from_raw`]. |
| 54 | //! |
| 55 | //! |
| 56 | //! ## With sanitization |
| 57 | //! |
| 58 | //! If you use [`markup`], supported tags are replaced (if necessary), malformed tags are removed |
| 59 | //! and HTML reserved characters are escaped. |
| 60 | //! |
| 61 | //! ```rust |
| 62 | //! # use html2pango::markup; |
| 63 | //! let m = markup("<p><strong>this <i>is &sanitized<f;><unsupported/></i></strong></p>"); |
| 64 | //! assert_eq!(m, "<b>this <i>is &sanitized</i></b>"); |
| 65 | //! ``` |
| 66 | //! |
| 67 | //! Other unsupported, but valid tags are escaped. |
| 68 | //! |
| 69 | //! ```rust |
| 70 | //! # use html2pango::markup; |
| 71 | //! let m = markup("this is <span>a tag</span>"); |
| 72 | //! assert_eq!(m, "this is <span>a tag</span>"); |
| 73 | //! ``` |
| 74 | //! |
| 75 | //! URIs are replaced by links. |
| 76 | //! |
| 77 | //! ```rust |
| 78 | //! # use html2pango::markup; |
| 79 | //! let m = markup("go to: https://gnome.org"); |
| 80 | //! assert_eq!(m, "go to: <a href=\"https://gnome.org\">https://gnome.org</a>"); |
| 81 | //! ``` |
| 82 | //! |
| 83 | //! ## Without sanitization |
| 84 | //! |
| 85 | //! Use [`markup_from_raw`] if you have already sanitized input: |
| 86 | //! |
| 87 | //! ```rust |
| 88 | //! # use html2pango::markup_from_raw; |
| 89 | //! let m = markup_from_raw("<p>this is <unsupported>already sanitized</unsupported></p>"); |
| 90 | //! assert_eq!(m, "this is <unsupported>already sanitized</unsupported>"); |
| 91 | //! ``` |
| 92 | //! |
| 93 | //! ## Links |
| 94 | //! |
| 95 | //! To just replace URIs by links, use [`markup_links`]: |
| 96 | //! |
| 97 | //! ```rust |
| 98 | //! # use html2pango::markup_links; |
| 99 | //! let m = markup_links("go to: https://gnome.org"); |
| 100 | //! assert_eq!(m, "go to: <a href=\"https://gnome.org\">https://gnome.org</a>"); |
| 101 | //! ``` |
| 102 | //! |
| 103 | //! [Markdown]: https://daringfireball.net/projects/markdown/ |
| 104 | //! [Matrix]: https://matrix.org/ |
| 105 | //! [Matrix specification]: https://spec.matrix.org/v1.1/client-server-api/#mroommessage-msgtypes |
| 106 | //! [Pango]: https://pango.gnome.org |
| 107 | //! [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html |
| 108 | |
| 109 | use html5ever::tendril::TendrilSink; |
| 110 | use html5ever::tree_builder::TreeBuilderOpts; |
| 111 | use html5ever::{parse_document, ParseOpts}; |
| 112 | use markup5ever_rcdom::Node; |
| 113 | use markup5ever_rcdom::NodeData; |
| 114 | use markup5ever_rcdom::RcDom; |
| 115 | |
| 116 | use linkify::{LinkFinder, LinkKind}; |
| 117 | use maplit::{hashmap, hashset}; |
| 118 | use once_cell::sync::Lazy; |
| 119 | |
| 120 | use regex::{Captures, Regex}; |
| 121 | use std::fmt::Write as _; |
| 122 | |
| 123 | use std::borrow::Cow; |
| 124 | |
| 125 | pub mod block; |
| 126 | |
| 127 | /// Sanitizes and converts simple HTML markup to Pango Markup. |
| 128 | /// |
| 129 | /// This will sanitize the input string using the [`ammonia`][ammonia] crate's defaults and then |
| 130 | /// use [`markup_from_raw`] to convert the sanitized string to [Pango Markup]. |
| 131 | /// |
| 132 | /// # Examples |
| 133 | /// |
| 134 | /// ```rust |
| 135 | /// # use html2pango::markup; |
| 136 | /// let m = markup("this is parsed"); |
| 137 | /// assert_eq!(m, "this is parsed"); |
| 138 | /// |
| 139 | /// let m = markup("<b>this <i>is &ssd<f;</i></b>"); |
| 140 | /// assert_eq!(m, "<b>this <i>is &ssd</i></b>"); |
| 141 | /// |
| 142 | /// let m = markup("this is <span>parsed</span>"); |
| 143 | /// assert_eq!(m, "this is <span>parsed</span>"); |
| 144 | /// |
| 145 | /// let m = markup("with links: http://gnome.org"); |
| 146 | /// assert_eq!(m, "with links: <a href=\"http://gnome.org\">http://gnome.org</a>"); |
| 147 | /// ``` |
| 148 | /// |
| 149 | /// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html |
| 150 | /// [ammonia]: https://docs.rs/ammonia/3.1.2/ammonia/fn.clean.html |
| 151 | pub fn markup(s: &str) -> String { |
| 152 | let sanitized_html = ammonia::Builder::new().link_rel(None).clean(s).to_string(); |
| 153 | markup_from_raw(&sanitized_html) |
| 154 | } |
| 155 | |
| 156 | /// Converts simple HTML markup to Pango Markup. |
| 157 | /// |
| 158 | /// This will convert the input string to [Pango Markup] and replace URIs by links. |
| 159 | /// |
| 160 | /// Currently it support conversion of the following HTML tags: |
| 161 | /// * `<p>` and `</p>` => `""` |
| 162 | /// * `<i>`, `<em>` and `</i>`,` </em>` => `<i>` and `</i>` |
| 163 | /// * `<b>`, `<strong>` and `</b>`, `</strong>` => `<b>` and `</b>` |
| 164 | /// * `<code>` and `</code>` => `<tt>` and `</tt>` |
| 165 | /// * `<sub>` and `</sub>` => `<sub>` and `</sub>` |
| 166 | /// * `<sup>` and `</sup>` => `<sup>` and `</sup>` |
| 167 | /// * `<br>` => `\n` |
| 168 | /// |
| 169 | /// It will also convert the following characters and HTML entities: |
| 170 | /// * `<` => `<` |
| 171 | /// * `>` => `>` |
| 172 | /// * ` ` => ` ` (non breaking space) |
| 173 | /// |
| 174 | /// # Examples |
| 175 | /// |
| 176 | /// ``` |
| 177 | /// # use html2pango::markup_from_raw; |
| 178 | /// let m = markup_from_raw("this is parsed"); |
| 179 | /// assert_eq!(m, "this is parsed"); |
| 180 | /// |
| 181 | /// let m = markup_from_raw("<b>this <i>is &ssd<f;</i></b>"); |
| 182 | /// assert_eq!(m, "<b>this <i>is &ssd<f;</i></b>"); |
| 183 | /// |
| 184 | /// let m = markup_from_raw("this is <span>parsed</span>"); |
| 185 | /// assert_eq!(m, "this is <span>parsed</span>"); |
| 186 | /// |
| 187 | /// let m = markup_from_raw("with links: http://gnome.org"); |
| 188 | /// assert_eq!(m, "with links: <a href=\"http://gnome.org\">http://gnome.org</a>"); |
| 189 | /// ``` |
| 190 | /// |
| 191 | /// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html |
| 192 | pub fn markup_from_raw(s: &str) -> String { |
| 193 | static TAGS: Lazy<Regex> = Lazy::new(|| { |
| 194 | Regex::new(concat![ |
| 195 | r"<p>|</p>|", |
| 196 | r"<br>|", |
| 197 | r"<b>|</b>|", |
| 198 | r"<strong>|</strong>|", |
| 199 | r"<code>|</code>|", |
| 200 | r"<i>|</i>|", |
| 201 | r"<sub>|</sub>|", |
| 202 | r"<sup>|</sup>|", |
| 203 | r"<em>|</em>|", |
| 204 | r"<|>|", |
| 205 | r" |", |
| 206 | // Url |
| 207 | r"https?://", // Protocol |
| 208 | r#"[^\s,)("]+"#, // Domain |
| 209 | r"(\?((&)?\w+(=[\w._-]+)?)*)*", // Parameters |
| 210 | r"(#[\w._-]+)?", // Hash |
| 211 | ]) |
| 212 | .unwrap() |
| 213 | }); |
| 214 | |
| 215 | TAGS.replace_all(s.trim(), |captures: &Captures<'_>| { |
| 216 | let m = captures.get(0).unwrap().as_str(); |
| 217 | // Keep this in sync with the TAGS regex |
| 218 | match m { |
| 219 | "<p>" | "</p>" => Cow::Borrowed(""), |
| 220 | "<br>" => Cow::Borrowed("\n"), |
| 221 | "<b>" | "<strong>" => Cow::Borrowed("<b>"), |
| 222 | "</b>" | "</strong>" => Cow::Borrowed("</b>"), |
| 223 | "<code>" => Cow::Borrowed("<tt>"), |
| 224 | "</code>" => Cow::Borrowed("</tt>"), |
| 225 | "<i>" | "<em>" => Cow::Borrowed("<i>"), |
| 226 | "</i>" | "</em>" => Cow::Borrowed("</i>"), |
| 227 | "<sub>" => Cow::Borrowed("<sub>"), |
| 228 | "</sub>" => Cow::Borrowed("</sub>"), |
| 229 | "<sup>" => Cow::Borrowed("<sup>"), |
| 230 | "</sup>" => Cow::Borrowed("</sup>"), |
| 231 | "<" => Cow::Borrowed("<"), |
| 232 | ">" => Cow::Borrowed(">"), |
| 233 | " " => Cow::Borrowed(" "), |
| 234 | _ => Cow::Owned(format!(r#"<a href="{}">{}</a>"#, m, m)), |
| 235 | } |
| 236 | }) |
| 237 | .into() |
| 238 | } |
| 239 | |
| 240 | /// Sanitizes and convert Matrix custom HTML markup (formatted body) to Pango Markup. |
| 241 | /// |
| 242 | /// First sanitizes the input string by leaving in only the HTML tags and attributes allowed |
| 243 | /// by the [Matrix specification] and then uses [`markup_html`] to convert the sanitized string to |
| 244 | /// [Pango Markup]. |
| 245 | /// |
| 246 | /// # Errors |
| 247 | /// |
| 248 | /// Returns an error if reading from the strings fails. |
| 249 | /// |
| 250 | /// # Examples |
| 251 | /// |
| 252 | /// TODO |
| 253 | /// |
| 254 | /// [Matrix specification]: https://spec.matrix.org/v1.1/client-server-api/#mroommessage-msgtypes |
| 255 | /// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html |
| 256 | // WIP: only allow the html subset that matrix uses. |
| 257 | pub fn matrix_html_to_markup(s: &str) -> String { |
| 258 | // https://github.com/matrix-org/matrix-react-sdk/blob/4bf5e44b2043bbe95faa66943878acad23dfb823/src/HtmlUtils.js#L178-L184 |
| 259 | #[rustfmt::skip] |
| 260 | let allowed_tags = hashset![ |
| 261 | "font", // custom to matrix for IRC-style font coloring |
| 262 | "del", // for markdown |
| 263 | "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "p", "a", "ul", "ol", "sup", "sub", |
| 264 | "nl", "li", "b", "i", "u", "strong", "em", "strike", "code", "hr", "br", "div", |
| 265 | "table", "thead", "caption", "tbody", "tr", "th", "td", "pre", "span", "img", |
| 266 | ]; |
| 267 | |
| 268 | // https://github.com/matrix-org/matrix-react-sdk/blob/4bf5e44b2043bbe95faa66943878acad23dfb823/src/HtmlUtils.js#L185-L193 |
| 269 | let allowed_attributes = hashmap![ |
| 270 | // custom ones first: |
| 271 | "font" => hashset!["color", "data-mx-bg-color", "data-mx-color", "style"], |
| 272 | "span" => hashset!["data-mx-bg-color", "data-mx-color", "style"], |
| 273 | // remote target: custom to matrix |
| 274 | "a" => hashset!["href", "name", "target", "rel"], |
| 275 | "img" => hashset!["src", "width", "height", "alt", "title"], |
| 276 | "ol" => hashset!["start"], |
| 277 | // We don't actually allow all classes, TODO: we should filter them afterwards |
| 278 | "code" => hashset!["class"], |
| 279 | ]; |
| 280 | |
| 281 | // https://github.com/matrix-org/matrix-react-sdk/blob/4bf5e44b2043bbe95faa66943878acad23dfb823/src/HtmlUtils.js#L48 |
| 282 | let allowed_urls = hashset!["http", "https", "ftp", "mailto", "magnet"]; |
| 283 | |
| 284 | let sanitized_html = ammonia::Builder::new() |
| 285 | .url_schemes(allowed_urls) |
| 286 | .tags(allowed_tags) |
| 287 | .tag_attributes(allowed_attributes) |
| 288 | .link_rel(None) |
| 289 | .clean(s) |
| 290 | .to_string(); |
| 291 | |
| 292 | markup_html(&sanitized_html) |
| 293 | .map(|x| x.trim_matches('\n').to_string()) |
| 294 | .unwrap_or_else(|_| markup_from_raw(&sanitized_html)) |
| 295 | } |
| 296 | |
| 297 | /// Escapes the HTML reserved characters. |
| 298 | /// |
| 299 | /// This replaces the HTML reserved characters by their respective entities in the input string. |
| 300 | /// |
| 301 | /// # Examples |
| 302 | /// |
| 303 | /// ```rust |
| 304 | /// # use html2pango::html_escape; |
| 305 | /// let s = html_escape("this is a <tag>"); |
| 306 | /// assert_eq!(s, "this is a <tag>"); |
| 307 | /// |
| 308 | /// let s = html_escape("he says: \"this & that\""); |
| 309 | /// assert_eq!(s, "he says: "this & that""); |
| 310 | /// ``` |
| 311 | pub fn html_escape(s: &str) -> String { |
| 312 | s.to_string() |
| 313 | .replace('&', "&") |
| 314 | .replace('<', "<") |
| 315 | .replace('>', ">") |
| 316 | .replace('"', """) |
| 317 | } |
| 318 | |
| 319 | /// Replaces URIs by HTML link tags. |
| 320 | /// |
| 321 | /// This function assumes that HTML entities in input string have been escaped (see also: |
| 322 | /// [`html_escape`]). It will leave URIs in already existing links alone. |
| 323 | /// |
| 324 | /// # Examples |
| 325 | /// |
| 326 | /// ```rust |
| 327 | /// # use html2pango::{html_escape, markup_links}; |
| 328 | /// let m = markup_links("go to https://gnome.org"); |
| 329 | /// assert_eq!(m, "go to <a href=\"https://gnome.org\">https://gnome.org</a>"); |
| 330 | /// ``` |
| 331 | pub fn markup_links(s: &str) -> String { |
| 332 | let mut parsed = String::with_capacity(s.len()); |
| 333 | let finder = LinkFinder::new(); |
| 334 | let mut prepend_str: Option<String> = None; |
| 335 | |
| 336 | for span in finder.spans(s) { |
| 337 | let mut s = span.as_str().to_string(); |
| 338 | match span.kind() { |
| 339 | Some(&LinkKind::Url) => { |
| 340 | if s.ends_with("&") { |
| 341 | prepend_str = Some("&".to_string()); |
| 342 | let t = s.len() - 4; |
| 343 | s.truncate(t); |
| 344 | } |
| 345 | if s.ends_with("<") { |
| 346 | prepend_str = Some("<".to_string()); |
| 347 | let t = s.len() - 3; |
| 348 | s.truncate(t); |
| 349 | } |
| 350 | if s.ends_with(">") { |
| 351 | prepend_str = Some(">".to_string()); |
| 352 | let t = s.len() - 3; |
| 353 | s.truncate(t); |
| 354 | } |
| 355 | if s.ends_with(""") { |
| 356 | prepend_str = Some(""".to_string()); |
| 357 | let t = s.len() - 5; |
| 358 | s.truncate(t); |
| 359 | } |
| 360 | // This is to manage "> or "< or "& |
| 361 | if s.ends_with(""") { |
| 362 | prepend_str = Some(""".to_string() + &prepend_str.unwrap_or_default()); |
| 363 | let t = s.len() - 6; |
| 364 | s.truncate(t); |
| 365 | } |
| 366 | let _ = write!(parsed, "<a href=\"{0}\">{0}</a>", s); |
| 367 | } |
| 368 | _ => { |
| 369 | if let Some(s) = prepend_str { |
| 370 | parsed.push_str(&s); |
| 371 | prepend_str = None; |
| 372 | } |
| 373 | parsed.push_str(&s); |
| 374 | } |
| 375 | }; |
| 376 | } |
| 377 | |
| 378 | parsed |
| 379 | } |
| 380 | |
| 381 | fn convert_tag(t: &str) -> Option<(&str, &str)> { |
| 382 | let allowed = [ |
| 383 | "a", |
| 384 | "br", |
| 385 | "em", |
| 386 | "i", |
| 387 | "p", |
| 388 | "code", |
| 389 | "strong", |
| 390 | "b", |
| 391 | "blockquote", |
| 392 | "li", |
| 393 | "sub", |
| 394 | "sup", |
| 395 | ]; |
| 396 | |
| 397 | if !allowed.contains(&t) { |
| 398 | return Some(("", "")); |
| 399 | } |
| 400 | |
| 401 | match t { |
| 402 | "em" | "i" => Some(("<i>", "</i>")), |
| 403 | "blockquote" => Some(("<i>", "</i>")), |
| 404 | "p" => Some(("\n", "\n")), |
| 405 | "br" => Some(("\n", "")), |
| 406 | "code" => Some(("<tt>", "</tt>")), |
| 407 | "strong" | "b" => Some(("<b>", "</b>")), |
| 408 | "li" => Some(("", "\n")), |
| 409 | "sub" => Some(("<sub>", "</sub>")), |
| 410 | "sup" => Some(("<sup>", "</sup>")), |
| 411 | _ => None, |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | fn match_tag(node: &Node, tags: &[&str]) -> bool { |
| 416 | match node.data { |
| 417 | NodeData::Element { name: ref n, .. } => { |
| 418 | let node_tag = n.local.to_string(); |
| 419 | tags.contains(&node_tag.as_str()) |
| 420 | } |
| 421 | _ => false, |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | fn convert_node(node: &Node, autolinks: bool) -> String { |
| 426 | let mut output = String::new(); |
| 427 | |
| 428 | match node.data { |
| 429 | NodeData::Text { contents: ref c } => { |
| 430 | let escaped = &html_escape(&c.borrow().replace('\n', "")); |
| 431 | if autolinks { |
| 432 | output.push_str(&markup_links(escaped)); |
| 433 | } else { |
| 434 | output.push_str(escaped); |
| 435 | } |
| 436 | } |
| 437 | NodeData::Element { |
| 438 | name: ref n, |
| 439 | attrs: ref a, |
| 440 | .. |
| 441 | } => { |
| 442 | let mut content = String::new(); |
| 443 | let tag = n.local.to_string(); |
| 444 | |
| 445 | match &tag[..] { |
| 446 | "ul" => { |
| 447 | content.push('\n'); |
| 448 | for child in node.children.borrow().iter() { |
| 449 | if match_tag(child, &["li", "ul", "ol"]) { |
| 450 | let _ = write!(content, " • {}", &convert_node(child, true)); |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | "ol" => { |
| 455 | let mut counter = 1; |
| 456 | content.push('\n'); |
| 457 | for child in node.children.borrow().iter() { |
| 458 | if match_tag(child, &["li", "ul", "ol"]) { |
| 459 | let _ = write!(content, " {}. {}", counter, &convert_node(child, true)); |
| 460 | counter += 1; |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | _ => { |
| 465 | for child in node.children.borrow().iter() { |
| 466 | content.push_str(&convert_node(child, true)); |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | match &tag[..] { |
| 472 | "body" => { |
| 473 | output.push_str(&content); |
| 474 | } |
| 475 | "a" => { |
| 476 | let mut link = String::new(); |
| 477 | let attrs = a.borrow(); |
| 478 | for attr in attrs.iter() { |
| 479 | if &*attr.name.local == "href" { |
| 480 | link = attr.value.to_string(); |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | let mut no_link_content = String::new(); |
| 485 | for child in node.children.borrow().iter() { |
| 486 | no_link_content.push_str(&convert_node(child, false)); |
| 487 | } |
| 488 | |
| 489 | let _ = write!( |
| 490 | output, |
| 491 | "<a href=\"{}\">{}</a>", |
| 492 | html_escape(&link), |
| 493 | no_link_content |
| 494 | ); |
| 495 | } |
| 496 | "font" => { |
| 497 | let attrs = a.borrow(); |
| 498 | let span_attrs = attrs |
| 499 | .iter() |
| 500 | .flat_map(|attr| match &*attr.name.local { |
| 501 | "color" | "data-mx-color" => Some(("foreground", &*attr.value)), |
| 502 | "data-mx-bg-color" => Some(("background", &*attr.value)), |
| 503 | _ => None, |
| 504 | }) |
| 505 | .collect::<Vec<(&str, &str)>>(); |
| 506 | |
| 507 | format_span(&mut output, content, span_attrs); |
| 508 | } |
| 509 | "span" => { |
| 510 | let attrs = a.borrow(); |
| 511 | let span_attrs = attrs |
| 512 | .iter() |
| 513 | .flat_map(|attr| match &*attr.name.local { |
| 514 | "data-mx-color" => Some(("foreground", &*attr.value)), |
| 515 | "data-mx-bg-color" => Some(("background", &*attr.value)), |
| 516 | _ => None, |
| 517 | }) |
| 518 | .collect::<Vec<(&str, &str)>>(); |
| 519 | |
| 520 | format_span(&mut output, content, span_attrs); |
| 521 | } |
| 522 | _ => { |
| 523 | if let Some((t1, t2)) = convert_tag(&tag) { |
| 524 | let _ = write!(output, "{}{}{}", t1, content, t2); |
| 525 | } else { |
| 526 | let _ = write!(output, "<{0}>{1}</{0}>", tag, content); |
| 527 | } |
| 528 | } |
| 529 | }; |
| 530 | } |
| 531 | _ => {} |
| 532 | } |
| 533 | |
| 534 | output |
| 535 | } |
| 536 | |
| 537 | fn format_span(output: &mut String, content: String, attrs: Vec<(&str, &str)>) { |
| 538 | if attrs.is_empty() { |
| 539 | output.push_str(&content); |
| 540 | return; |
| 541 | } |
| 542 | |
| 543 | let _ = write!(output, "<span"); |
| 544 | for (attr, val) in attrs.into_iter() { |
| 545 | let _ = write!(output, " {}=\"{}\"", attr, val); |
| 546 | } |
| 547 | let _ = write!(output, ">{}</span>", content); |
| 548 | } |
| 549 | |
| 550 | /// Converts HTML body markup to Pango Markup. |
| 551 | /// |
| 552 | /// While [`markup`]/[`markup_from_raw`] only supports simple HTML tags such as `<p>`, `<b>` and |
| 553 | /// `<br>`, this function tries to convert HTML body markup so that the resulting [Pango Markup] |
| 554 | /// will render to something that is similar to what a browser would render. |
| 555 | /// |
| 556 | /// # Errors |
| 557 | /// |
| 558 | /// Returns an error if reading from the strings fails. |
| 559 | /// |
| 560 | /// # Examples |
| 561 | /// |
| 562 | /// ```rust |
| 563 | /// # use html2pango::markup_html; |
| 564 | /// let m = markup_html("<body>this is some <font color=\"#ff0000\">red text</font>!</body>").unwrap(); |
| 565 | /// assert_eq!(m, "this is some <span foreground=\"#ff0000\">red text</span>!"); |
| 566 | /// |
| 567 | /// let m = markup_html("<body>a nice <a href=\"https://gnome.org\">link</a>").unwrap(); |
| 568 | /// assert_eq!(m, "a nice <a href=\"https://gnome.org\">link</a>"); |
| 569 | /// |
| 570 | /// let m = markup_html("<body>some items: <ul><li>first</li><li>second</li></ul><body").unwrap(); |
| 571 | /// assert_eq!(m, "some items: \n • first\n • second\n"); |
| 572 | /// ``` |
| 573 | /// |
| 574 | /// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html |
| 575 | pub fn markup_html(s: &str) -> Result<String, anyhow::Error> { |
| 576 | let opts = ParseOpts { |
| 577 | tree_builder: TreeBuilderOpts { |
| 578 | drop_doctype: true, |
| 579 | ..Default::default() |
| 580 | }, |
| 581 | ..Default::default() |
| 582 | }; |
| 583 | let dom = parse_document(RcDom::default(), opts) |
| 584 | .from_utf8() |
| 585 | .read_from(&mut s.as_bytes())?; |
| 586 | |
| 587 | let document = &dom.document; |
| 588 | let html = &document.children.borrow()[0]; |
| 589 | let body = &html.children.borrow()[1]; |
| 590 | |
| 591 | Ok(convert_node(body, true)) |
| 592 | } |
| 593 | |
| 594 | #[cfg(test)] |
| 595 | mod test { |
| 596 | use super::*; |
| 597 | use pretty_assertions::assert_eq; |
| 598 | |
| 599 | #[test] |
| 600 | fn test_markup() { |
| 601 | let m = markup("this is parsed"); |
| 602 | assert_eq!(&m, "this is parsed"); |
| 603 | |
| 604 | let m = markup("this is <span>parsed</span>"); |
| 605 | assert_eq!(&m, "this is <span>parsed</span>"); |
| 606 | |
| 607 | let m = markup("this is &ssdf;"); |
| 608 | assert_eq!(&m, "this is &ssdf;"); |
| 609 | |
| 610 | // TODO: add more tests |
| 611 | let m = markup("<p>this <br>is &ssdf;</p>"); |
| 612 | assert_eq!(&m, "this \nis &ssdf;"); |
| 613 | |
| 614 | let m = markup("<b>this <i>is &ssd<f;</i></b>"); |
| 615 | assert_eq!(&m, "<b>this <i>is &ssd</i></b>"); |
| 616 | |
| 617 | let url = "http://url.com/test?foo1&foo2=test&foo3#hashing"; |
| 618 | let m = markup(&format!("this is &ssdf; {}", url)); |
| 619 | assert_eq!( |
| 620 | &m, |
| 621 | &format!( |
| 622 | "this is &ssdf; <a href=\"{0}\">{0}</a>", |
| 623 | url.replace('&', "&") |
| 624 | ) |
| 625 | ); |
| 626 | |
| 627 | for l in &[ |
| 628 | ("with links: http://gnome.org :D", "http://gnome.org"), |
| 629 | ( |
| 630 | "with links: http://url.com/test.html&stuff :D", |
| 631 | "http://url.com/test.html&stuff", |
| 632 | ), |
| 633 | ] { |
| 634 | let m = markup(l.0); |
| 635 | assert_eq!( |
| 636 | &m, |
| 637 | &format!( |
| 638 | "with links: <a href=\"{0}\">{0}</a> :D", |
| 639 | l.1.replace('&', "&") |
| 640 | ) |
| 641 | ); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | #[test] |
| 646 | // FIXME: Write specific tests instead of copying the above |
| 647 | fn test_matrix() { |
| 648 | let markup = matrix_html_to_markup; |
| 649 | let m = markup("this is parsed"); |
| 650 | assert_eq!(&m, "this is parsed"); |
| 651 | |
| 652 | let m = markup("this is <span>parsed</span>"); |
| 653 | assert_eq!(&m, "this is parsed"); |
| 654 | |
| 655 | let m = markup("this is &ssdf;"); |
| 656 | assert_eq!(&m, "this is &ssdf;"); |
| 657 | |
| 658 | // TODO: add more tests |
| 659 | let m = markup("<p>this <br>is &ssdf;</p>"); |
| 660 | assert_eq!(&m, "this \nis &ssdf;"); |
| 661 | |
| 662 | let m = markup("<b>this <i>is &ssd<f;</i></b>"); |
| 663 | assert_eq!(&m, "<b>this <i>is &ssd</i></b>"); |
| 664 | |
| 665 | let m = markup("hello <font color=\"#112233\">world</font>"); |
| 666 | assert_eq!(&m, "hello <span foreground=\"#112233\">world</span>"); |
| 667 | |
| 668 | let m = markup( |
| 669 | "hello <font data-mx-color=\"#112233\" data-mx-bg-color=\"#332211\">world</font>", |
| 670 | ); |
| 671 | assert_eq!( |
| 672 | &m, |
| 673 | "hello <span foreground=\"#112233\" background=\"#332211\">world</span>" |
| 674 | ); |
| 675 | |
| 676 | let m = markup("hello <em><font color=\"#112233\">http://gnome.org</font></em>"); |
| 677 | assert_eq!(&m, "hello <i><span foreground=\"#112233\"><a href=\"http://gnome.org\">http://gnome.org</a></span></i>"); |
| 678 | |
| 679 | let m = markup( |
| 680 | "added <span data-mx-color=\"#112233\" data-mx-bg-color=\"#332211\">Label</span>", |
| 681 | ); |
| 682 | assert_eq!( |
| 683 | &m, |
| 684 | "added <span foreground=\"#112233\" background=\"#332211\">Label</span>" |
| 685 | ); |
| 686 | |
| 687 | let url = "http://url.com/test?foo1&foo2=test&foo3#hashing"; |
| 688 | let m = markup(&format!("this is &ssdf; {}", url)); |
| 689 | assert_eq!( |
| 690 | &m, |
| 691 | &format!( |
| 692 | "this is &ssdf; <a href=\"{0}\">{0}</a>", |
| 693 | url.replace('&', "&") |
| 694 | ) |
| 695 | ); |
| 696 | |
| 697 | for l in &[ |
| 698 | ("with links: http://gnome.org :D", "http://gnome.org"), |
| 699 | ( |
| 700 | "with links: http://url.com/test.html&stuff :D", |
| 701 | "http://url.com/test.html&stuff", |
| 702 | ), |
| 703 | ] { |
| 704 | let m = markup(l.0); |
| 705 | assert_eq!( |
| 706 | &m, |
| 707 | &format!( |
| 708 | "with links: <a href=\"{0}\">{0}</a> :D", |
| 709 | l.1.replace('&', "&") |
| 710 | ) |
| 711 | ); |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | #[test] |
| 716 | fn test_links() { |
| 717 | let strings = [ |
| 718 | ("clean string without markup", |
| 719 | "clean string without markup"), |
| 720 | |
| 721 | ("clean string with a <b>markup</b>", |
| 722 | "clean string with a <b>markup</b>"), |
| 723 | |
| 724 | ("clean string with a <b>markup</b> and link http://gnome.org/?p=1&q#hash", |
| 725 | "clean string with a <b>markup</b> and link <a href=\"http://gnome.org/?p=1&q#hash\">http://gnome.org/?p=1&q#hash</a>"), |
| 726 | |
| 727 | ("report-bug is: please report bugs with parabola packages on the packaging bug tracker at: https://labs.parabola.nu/projects/issue-tracker/issues?set_filter=1&tracker_id=1", |
| 728 | "report-bug is: please report bugs with parabola packages on the packaging bug tracker at: <a href=\"https://labs.parabola.nu/projects/issue-tracker/issues?set_filter=1&tracker_id=1\">https://labs.parabola.nu/projects/issue-tracker/issues?set_filter=1&tracker_id=1</a>"), |
| 729 | |
| 730 | ( |
| 731 | "bill-auger, isacdaavid: there are two major issues I see with gnome-software. The first issue is that flathub, the largest repo for flatpaks, has nonfree software. If flathub isn't included by default, I think this is fine. The second is archlinux-appstream-data. The [PKGBUILD](https://git.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/archlinux-appstream-data) does not use appstream-generator at all. However, it does require grabbing files from sources.archlinux.org", |
| 732 | "bill-auger, isacdaavid: there are two major issues I see with gnome-software. The first issue is that flathub, the largest repo for flatpaks, has nonfree software. If flathub isn't included by default, I think this is fine. The second is archlinux-appstream-data. The [PKGBUILD](<a href=\"https://git.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/archlinux-appstream-data\">https://git.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/archlinux-appstream-data</a>) does not use appstream-generator at all. However, it does require grabbing files from sources.archlinux.org", |
| 733 | ), |
| 734 | |
| 735 | ("links with problems: http://gnome.org/?p=1&", |
| 736 | "links with problems: <a href=\"http://gnome.org/?p=1\">http://gnome.org/?p=1</a>&"), |
| 737 | ("links with problems: http://gnome.org/?p=1>", |
| 738 | "links with problems: <a href=\"http://gnome.org/?p=1\">http://gnome.org/?p=1</a>>"), |
| 739 | ("links with problems: http://gnome.org/?p=1<", |
| 740 | "links with problems: <a href=\"http://gnome.org/?p=1\">http://gnome.org/?p=1</a><"), |
| 741 | ]; |
| 742 | |
| 743 | for &(s, e) in strings.iter() { |
| 744 | let m = markup_links(&html_escape(s)); |
| 745 | assert_eq!(&m, e); |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | #[test] |
| 750 | fn test_markup_links() { |
| 751 | let strings = [ |
| 752 | ("This is a test message with <em>markdown</em><br /><a href=\"http://gnome.org\">gnome</a><br />and other link http://gnome.org", |
| 753 | "This is a test message with <i>markdown</i>\n<a href=\"http://gnome.org\">gnome</a>\nand other link <a href=\"http://gnome.org\">http://gnome.org</a>"), |
| 754 | ]; |
| 755 | |
| 756 | for &(s, e) in strings.iter() { |
| 757 | let m = markup_html(s).unwrap(); |
| 758 | assert_eq!(&m, e); |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | #[test] |
| 763 | fn test_ending_quote_link() { |
| 764 | let strings = [ |
| 765 | ("<boxes:gnome-boxes xmlns:boxes=\"https://wiki.gnome.org/Apps/Boxes\">", |
| 766 | "<boxes:gnome-boxes xmlns:boxes="<a href=\"https://wiki.gnome.org/Apps/Boxes\">https://wiki.gnome.org/Apps/Boxes</a>">"), |
| 767 | ]; |
| 768 | |
| 769 | for &(s, e) in strings.iter() { |
| 770 | let m = markup_links(&html_escape(s)); |
| 771 | assert_eq!(&m, e); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | #[test] |
| 776 | fn test_link_scape() { |
| 777 | let strings = [ |
| 778 | ("<a href=\"https://forums.transbian.love/?page=thread&id=69\">https://forums.transbian.love/?page=thread&id=69</a>", |
| 779 | "<a href=\"https://forums.transbian.love/?page=thread&id=69\">https://forums.transbian.love/?page=thread&id=69</a>"), |
| 780 | ("<a href=\"https://forums.transbian.love/?page=thread&id=69\">https://forums.transbian.love/?page=thread&id=69</a>", |
| 781 | "<a href=\"https://forums.transbian.love/?page=thread&id=69\">https://forums.transbian.love/?page=thread&id=69</a>"), |
| 782 | ("https://forums.transbian.love/?page=thread&id=69", |
| 783 | "<a href=\"https://forums.transbian.love/?page=thread&id=69\">https://forums.transbian.love/?page=thread&id=69</a>"), |
| 784 | ]; |
| 785 | |
| 786 | for &(s, e) in strings.iter() { |
| 787 | let m = markup_html(s).unwrap(); |
| 788 | assert_eq!(&m, e); |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | #[test] |
| 793 | fn test_superscript() { |
| 794 | let strings = [("Une 2<sup>e</sup> entente", "Une 2<sup>e</sup> entente")]; |
| 795 | |
| 796 | for &(s, e) in strings.iter() { |
| 797 | let m = markup(s); |
| 798 | assert_eq!(&m, e); |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | #[test] |
| 803 | fn test_subscript() { |
| 804 | let strings = [("H<sub>2</sub>O", "H<sub>2</sub>O")]; |
| 805 | |
| 806 | for &(s, e) in strings.iter() { |
| 807 | let m = markup(s); |
| 808 | assert_eq!(&m, e); |
| 809 | } |
| 810 | } |
| 811 | } |