| 1 | //! Module for converting HTML markup to blocks with Pango Markup formatted content. |
| 2 | //! |
| 3 | //! The functions in this module turn the HTML input to a list of block elements (see |
| 4 | //! [`HtmlBlock`]) rather then an output string. This can be useful if the blocks are rendered |
| 5 | //! separately, for example if you have some text followed by a code block. The former may be |
| 6 | //! rendered using a different widget than the latter. |
| 7 | //! |
| 8 | //! The main function of this module is [`markup_html`]. |
| 9 | //! It yields HTML blocks for the following tags: |
| 10 | //! * `<h1>`, `<h2>`, `<h3>`, `<h4>`, `<h5>`, `<h6>` => [`HtmlBlock::Heading`] |
| 11 | //! * `<pre>` => [`HtmlBlock::Code`] |
| 12 | //! * `<ul>` => [`HtmlBlock::UList`] |
| 13 | //! * `<ol>` => [`HtmlBlock::OList`] |
| 14 | //! * `<blockquote>` => [`HtmlBlock::Quote`] |
| 15 | //! |
| 16 | //! It handles the following tags as text, yielding an [`HtmlBlock::Text`] with the contents: |
| 17 | //! * `<a>` => `<a>` with only the `href` attribute set |
| 18 | //! * `<b>` and `<strong>` => `<b>` |
| 19 | //! * `<body>` and `<mx-reply>` => removed |
| 20 | //! * `<br>` => `\n` |
| 21 | //! * `<code>` => `<tt>` |
| 22 | //! * `<del>` and `<s>` => `<s>` |
| 23 | //! * `<em>` and `<i>` => `<i>` |
| 24 | //! * `<span>` and `<font>` => `<span>` |
| 25 | //! * `<p>` => contents followed by `\n` |
| 26 | //! * `<u>` => `<u>` |
| 27 | //! |
| 28 | //! Finally, it removes all other tags and replaces URIs by HTML link tags. and merges |
| 29 | //! subsequent text HTML blocks into a single one. |
| 30 | //! |
| 31 | //! # Examples |
| 32 | //! |
| 33 | //! Converting HTML markup with a heading and two paragraphs: |
| 34 | //! |
| 35 | //! ```rust |
| 36 | //! # use html2pango::block::*; |
| 37 | //! let blks = |
| 38 | //! markup_html("<h1>Heading</h1><p>This is paragraph 1.</p><p>Paragraph 2</p>").unwrap(); |
| 39 | //! assert_eq!(blks[0], HtmlBlock::Heading(1, String::from("Heading"))); |
| 40 | //! assert_eq!(blks[1], HtmlBlock::Text(String::from("This is paragraph 1.\n\nParagraph 2"))); |
| 41 | //! ``` |
| 42 | //! |
| 43 | //! Converting HTML markup with an unordered list and some formatting: |
| 44 | //! |
| 45 | //! ```rust |
| 46 | //! # use html2pango::block::*; |
| 47 | //! let blks = |
| 48 | //! markup_html("<ul><li>This is <b>bold</b></li><li><code>Some code</code></ul>").unwrap(); |
| 49 | //! assert_eq!( |
| 50 | //! blks[0], |
| 51 | //! HtmlBlock::UList(vec![ |
| 52 | //! String::from("This is <b>bold</b>"), |
| 53 | //! String::from("<tt>Some code</tt>"), |
| 54 | //! ]) |
| 55 | //! ); |
| 56 | //! ``` |
| 57 | //! |
| 58 | //! Converting HTML markup links and URIs that are converted into links: |
| 59 | //! |
| 60 | //! ```rust |
| 61 | //! # use html2pango::block::*; |
| 62 | //! let blks = markup_html("a <a href=\"https://gnome.org\" rel=\"nofollow\">link</a> and \ |
| 63 | //! another: https://gnome.org").unwrap(); |
| 64 | //! assert_eq!( |
| 65 | //! blks[0], |
| 66 | //! HtmlBlock::Text( |
| 67 | //! String::from( |
| 68 | //! "a <a href=\"https://gnome.org\" title=\"https://gnome.org\">link</a> and \ |
| 69 | //! another: <a href=\"https://gnome.org\">https://gnome.org</a>" |
| 70 | //! ) |
| 71 | //! ) |
| 72 | //! ); |
| 73 | //! ``` |
| 74 | //! |
| 75 | //! For more examples, see [`markup_html`]. |
| 76 | |
| 77 | use std::cell::RefCell; |
| 78 | use std::rc::Rc; |
| 79 | |
| 80 | use super::html_escape; |
| 81 | use super::markup_links; |
| 82 | |
| 83 | use html5ever::tendril::TendrilSink; |
| 84 | use html5ever::tree_builder::Attribute; |
| 85 | use html5ever::tree_builder::TreeBuilderOpts; |
| 86 | use html5ever::{parse_document, ParseOpts}; |
| 87 | use markup5ever_rcdom::Node; |
| 88 | use markup5ever_rcdom::NodeData; |
| 89 | use markup5ever_rcdom::RcDom; |
| 90 | |
| 91 | /// Supported HTML block elements. |
| 92 | /// |
| 93 | /// Each block element contains a textual representation of the contained inline HTML elements in |
| 94 | /// [Pango Markup]. The exception is [`HtmlBlock::Quote`], which contains the list of block |
| 95 | /// elements that are contained in the quote. |
| 96 | /// |
| 97 | /// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html |
| 98 | #[derive(Debug, Clone, PartialEq)] |
| 99 | pub enum HtmlBlock { |
| 100 | /// Just some text. |
| 101 | Text(String), |
| 102 | /// Heading with its level and text. |
| 103 | Heading(u32, String), |
| 104 | /// Unordered list of text. |
| 105 | UList(Vec<String>), |
| 106 | /// Ordered list of text. |
| 107 | OList(Vec<String>), |
| 108 | /// Code block with its contained (preformatted) text. |
| 109 | Code(String), |
| 110 | /// (Block)quote with its contained block elements. |
| 111 | Quote(Rc<Vec<HtmlBlock>>), |
| 112 | /// Vertical separator (i.e. horizontal rule) |
| 113 | Separator, |
| 114 | } |
| 115 | |
| 116 | /// Converts HTML body markup into a list of HTML blocks while ignoring some tags. |
| 117 | /// |
| 118 | /// The provided tags are ignored while parsing as if they are not there, i.e. the parser just |
| 119 | /// descends into them and leaves them out of the result. |
| 120 | /// |
| 121 | /// For more details on what is actually converted, see the [module documentation](crate::block). |
| 122 | /// |
| 123 | /// # Errors |
| 124 | /// |
| 125 | /// Returns an error if reading from the strings fails or if parsing somehow fails. |
| 126 | /// |
| 127 | /// # Examples |
| 128 | /// |
| 129 | /// ```rust |
| 130 | /// # use html2pango::block::*; |
| 131 | /// let blks = |
| 132 | /// markup_html_ignore_tags("<reply>this is <em>nice</em></reply>", &["body"]).unwrap(); |
| 133 | /// assert_eq!(blks, vec![HtmlBlock::Text(String::from("this is <i>nice</i>"))]); |
| 134 | /// ``` |
| 135 | /// |
| 136 | /// For more examples about the markup conversion, see [`markup_html`]. |
| 137 | pub fn markup_html_ignore_tags(s: &str, tags: &[&str]) -> Result<Vec<HtmlBlock>, anyhow::Error> { |
| 138 | let opts = ParseOpts { |
| 139 | tree_builder: TreeBuilderOpts { |
| 140 | drop_doctype: true, |
| 141 | ..Default::default() |
| 142 | }, |
| 143 | ..Default::default() |
| 144 | }; |
| 145 | let dom = parse_document(RcDom::default(), opts) |
| 146 | .from_utf8() |
| 147 | .read_from(&mut s.as_bytes())?; |
| 148 | |
| 149 | let document = &dom.document; |
| 150 | let mut html = document.children.borrow().clone(); |
| 151 | // TODO: When writing `<i>...</i>` in markdown, the first children is of type |
| 152 | // Comment { contents: "raw HTML omitted" } |
| 153 | // This should be handled more gracefully |
| 154 | html.retain(|x| !matches!(x.data, NodeData::Comment { .. })); |
| 155 | |
| 156 | if let Some(h) = &html.get(0) { |
| 157 | if let Some(node) = &h.children.borrow().get(1) { |
| 158 | let markup = convert_node(node, tags); |
| 159 | return Ok(trim_text_blocks(markup)); |
| 160 | } |
| 161 | } |
| 162 | Err(anyhow::anyhow!(format!("Could not parse {:?}", html))) |
| 163 | } |
| 164 | |
| 165 | /// Converts HTML body markup into a list of HTML blocks. |
| 166 | /// |
| 167 | /// Calls [`markup_html_ignore_tags`] to do the actual work instructing it to ignore the `<body>` |
| 168 | /// and `mx-reply` (for Matrix) tags. |
| 169 | /// |
| 170 | /// For more details on what is actually converted, see the [module documentation](crate::block). |
| 171 | /// |
| 172 | /// # Errors |
| 173 | /// |
| 174 | /// Returns an error if reading from the string fails or if parsing fails. |
| 175 | /// |
| 176 | /// # Examples |
| 177 | /// |
| 178 | /// Some HTML markup of a heading and an unordered list: |
| 179 | /// |
| 180 | /// ```rust |
| 181 | /// # use html2pango::block::*; |
| 182 | /// let blks = |
| 183 | /// markup_html("<body><h1>Heading 1</h1><ul><li>First</li><li>Second</li><body>").unwrap(); |
| 184 | /// assert_eq!(blks[0], HtmlBlock::Heading(1, String::from("Heading 1"))); |
| 185 | /// assert_eq!(blks[1], HtmlBlock::UList(vec![String::from("First"), String::from("Second")])); |
| 186 | /// ``` |
| 187 | /// |
| 188 | /// Pango Markup is applied, paragraphs are handled but merged: |
| 189 | /// |
| 190 | /// ```rust |
| 191 | /// # use html2pango::block::*; |
| 192 | /// let blks = |
| 193 | /// markup_html("<body><p>This is <em>nice</em>!</p><p>Second paragraph.</p></body>").unwrap(); |
| 194 | /// assert_eq!( |
| 195 | /// blks[0], |
| 196 | /// HtmlBlock::Text(String::from("This is <i>nice</i>!\n\nSecond paragraph.")) |
| 197 | /// ); |
| 198 | /// ``` |
| 199 | /// |
| 200 | /// URIs are replaced by links: |
| 201 | /// |
| 202 | /// ```rust |
| 203 | /// # use html2pango::block::*; |
| 204 | /// let blks = |
| 205 | /// markup_html("<body>Go to https://gnome.org</body>").unwrap(); |
| 206 | /// assert_eq!( |
| 207 | /// blks[0], |
| 208 | /// HtmlBlock::Text(String::from("Go to <a href=\"https://gnome.org\">https://gnome.org</a>")) |
| 209 | /// ); |
| 210 | /// ``` |
| 211 | /// |
| 212 | pub fn markup_html(s: &str) -> Result<Vec<HtmlBlock>, anyhow::Error> { |
| 213 | let tags = vec!["body", "mx-reply"]; |
| 214 | markup_html_ignore_tags(s, &tags) |
| 215 | } |
| 216 | |
| 217 | fn to_pango(t: &str) -> Option<(&'static str, &'static str)> { |
| 218 | let allowed = [ |
| 219 | "u", "del", "s", "em", "i", "strong", "b", "code", "a", "br", "sub", "sup", |
| 220 | ]; |
| 221 | |
| 222 | if !allowed.contains(&t) { |
| 223 | return None; |
| 224 | } |
| 225 | |
| 226 | match t { |
| 227 | "a" => Some(("<a>", "</a>")), |
| 228 | "br" => Some(("", "\n")), |
| 229 | "em" | "i" => Some(("<i>", "</i>")), |
| 230 | "strong" | "b" => Some(("<b>", "</b>")), |
| 231 | "del" | "s" => Some(("<s>", "</s>")), |
| 232 | "u" => Some(("<u>", "</u>")), |
| 233 | "code" => Some(("<tt>", "</tt>")), |
| 234 | "sub" => Some(("<sub>", "</sub>")), |
| 235 | "sup" => Some(("<sup>", "</sup>")), |
| 236 | _ => None, |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn parse_link(node: &Node, attrs: &RefCell<Vec<Attribute>>) -> String { |
| 241 | let mut link = "".to_string(); |
| 242 | for attr in attrs.borrow().iter() { |
| 243 | let s = attr.name.local.to_string(); |
| 244 | if &s[..] == "href" { |
| 245 | link = attr.value.to_string(); |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | format!( |
| 250 | "<a href=\"{0}\" title=\"{0}\">{1}</a>", |
| 251 | html_escape(&link), |
| 252 | get_text_content(node) |
| 253 | ) |
| 254 | } |
| 255 | |
| 256 | fn get_text_content(node: &Node) -> String { |
| 257 | let text = node |
| 258 | .children |
| 259 | .borrow() |
| 260 | .iter() |
| 261 | .map(|node| match node.data { |
| 262 | NodeData::Text { contents: ref c } => { |
| 263 | markup_links(&replace_html_whitespace(&html_escape(&c.borrow()))) |
| 264 | } |
| 265 | NodeData::Element { |
| 266 | name: ref n, |
| 267 | attrs: ref a, |
| 268 | .. |
| 269 | } => { |
| 270 | let inside = get_text_content(node); |
| 271 | |
| 272 | if &n.local == "a" { |
| 273 | return parse_link(node, a); |
| 274 | } |
| 275 | |
| 276 | match to_pango(&n.local) { |
| 277 | Some((t1, t2)) => format!("{}{}{}", t1, inside, t2), |
| 278 | None => inside, |
| 279 | } |
| 280 | } |
| 281 | _ => get_text_content(node), |
| 282 | }) |
| 283 | .collect::<Vec<String>>() |
| 284 | .concat(); |
| 285 | |
| 286 | collapse_spaces(&text) |
| 287 | } |
| 288 | |
| 289 | fn get_plain_text_content(node: &Node) -> String { |
| 290 | node.children |
| 291 | .borrow() |
| 292 | .iter() |
| 293 | .map(|node| match node.data { |
| 294 | NodeData::Text { contents: ref c } => c.borrow().to_string(), |
| 295 | NodeData::Element { |
| 296 | name: ref n, |
| 297 | attrs: ref _a, |
| 298 | .. |
| 299 | } => { |
| 300 | let inside = get_plain_text_content(node); |
| 301 | match to_pango(&n.local) { |
| 302 | Some((t1, t2)) => { |
| 303 | // We don't want tt tags inside codeblocks which |
| 304 | // already have <tt>. |
| 305 | if t1 != "<tt>" { |
| 306 | format!("{}{}{}", t1, inside, t2) |
| 307 | } else { |
| 308 | inside |
| 309 | } |
| 310 | } |
| 311 | None => inside, |
| 312 | } |
| 313 | } |
| 314 | _ => get_plain_text_content(node), |
| 315 | }) |
| 316 | .collect::<Vec<String>>() |
| 317 | .concat() |
| 318 | } |
| 319 | |
| 320 | fn get_li_elements(node: &Node) -> Vec<String> { |
| 321 | node.children |
| 322 | .borrow() |
| 323 | .iter() |
| 324 | .filter_map(|node| match node.data { |
| 325 | NodeData::Element { name: ref n, .. } if &n.local == "li" => { |
| 326 | Some(get_text_content(node)) |
| 327 | } |
| 328 | _ => None, |
| 329 | }) |
| 330 | .collect::<Vec<String>>() |
| 331 | } |
| 332 | |
| 333 | fn join_text_blocks(mut blocks: Vec<HtmlBlock>) -> Vec<HtmlBlock> { |
| 334 | use HtmlBlock::Text; |
| 335 | |
| 336 | blocks.drain(..).fold(Vec::<HtmlBlock>::new(), |mut v, b| { |
| 337 | let last = v.last(); |
| 338 | if let (Text(c), Some(Text(a))) = (&b, last) { |
| 339 | let t = join_collapse_spaces(a, c); |
| 340 | v.pop(); |
| 341 | v.push(Text(t)); |
| 342 | } else { |
| 343 | v.push(b); |
| 344 | } |
| 345 | |
| 346 | v |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | fn join_collapse_spaces(s: &str, extra: &str) -> String { |
| 351 | if s.ends_with(' ') && (extra.starts_with('\n') || extra.starts_with(' ')) { |
| 352 | s.trim_end().to_string() + extra |
| 353 | } else if s.ends_with('\n') && extra.starts_with(' ') { |
| 354 | s.to_string() + extra.trim_start() |
| 355 | } else { |
| 356 | s.to_string() + extra |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | fn collapse_spaces(s: &str) -> String { |
| 361 | let mut collapsed_s = String::with_capacity(s.len()); |
| 362 | let mut iter = s.chars().peekable(); |
| 363 | while let Some(c) = iter.next() { |
| 364 | match (c, iter.peek()) { |
| 365 | (' ', Some('\n')) | (' ', Some(' ')) => continue, |
| 366 | ('\n', Some(' ')) => { |
| 367 | iter.next(); // Drop the following space |
| 368 | while iter.peek() == Some(&' ') { |
| 369 | iter.next(); |
| 370 | } |
| 371 | } |
| 372 | _ => {} |
| 373 | } |
| 374 | |
| 375 | collapsed_s.push(c); |
| 376 | } |
| 377 | |
| 378 | collapsed_s |
| 379 | } |
| 380 | |
| 381 | fn replace_html_whitespace(s: &str) -> String { |
| 382 | let mut result = String::new(); |
| 383 | let mut last = 0; |
| 384 | |
| 385 | for (index, matched) in s.match_indices(|c: char| !c.is_ascii_whitespace()) { |
| 386 | if last != index { |
| 387 | result.push(' '); |
| 388 | } |
| 389 | result.push_str(matched); |
| 390 | last = index + matched.len(); |
| 391 | } |
| 392 | if last < s.len() { |
| 393 | result.push(' '); |
| 394 | } |
| 395 | |
| 396 | result |
| 397 | } |
| 398 | |
| 399 | fn html_unescape(s: &str) -> String { |
| 400 | s.to_string() |
| 401 | .replace("&", "&") |
| 402 | .replace("<", "<") |
| 403 | .replace(">", ">") |
| 404 | .replace(""", "\"") |
| 405 | } |
| 406 | |
| 407 | fn trim_text_blocks(mut blocks: Vec<HtmlBlock>) -> Vec<HtmlBlock> { |
| 408 | blocks.drain(..).fold(vec![], |mut v, b| { |
| 409 | if let HtmlBlock::Text(c) = &b { |
| 410 | if !c.trim().is_empty() { |
| 411 | v.push(HtmlBlock::Text(c.trim().to_string())); |
| 412 | } |
| 413 | } else { |
| 414 | v.push(b); |
| 415 | } |
| 416 | v |
| 417 | }) |
| 418 | } |
| 419 | |
| 420 | fn convert_node(node: &Node, tags_to_ignore: &[&str]) -> Vec<HtmlBlock> { |
| 421 | let mut output = vec![]; |
| 422 | |
| 423 | match node.data { |
| 424 | NodeData::Text { contents: ref c } => { |
| 425 | let s = markup_links(&replace_html_whitespace(&html_escape(&c.borrow()))); |
| 426 | output.push(HtmlBlock::Text(s)); |
| 427 | } |
| 428 | |
| 429 | NodeData::Element { |
| 430 | name: ref n, |
| 431 | attrs: ref a, |
| 432 | .. |
| 433 | } => { |
| 434 | match &n.local as &str { |
| 435 | // tags to ignore |
| 436 | tag if tags_to_ignore.contains(&tag) => { |
| 437 | for child in node.children.borrow().iter() { |
| 438 | for block in convert_node(child, tags_to_ignore) { |
| 439 | output.push(block); |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | h if ["h1", "h2", "h3", "h4", "h5", "h6"].contains(&h) => { |
| 445 | let n: u32 = h[1..].parse().unwrap_or(6); |
| 446 | let text = get_text_content(node); |
| 447 | output.push(HtmlBlock::Heading(n, text)); |
| 448 | } |
| 449 | |
| 450 | "a" => { |
| 451 | let link = parse_link(node, a); |
| 452 | output.push(HtmlBlock::Text(link)); |
| 453 | } |
| 454 | |
| 455 | "pre" => { |
| 456 | let text = get_plain_text_content(node); |
| 457 | output.push(HtmlBlock::Code(html_unescape(text.trim()))); |
| 458 | } |
| 459 | |
| 460 | "ul" => { |
| 461 | let elements = get_li_elements(node); |
| 462 | output.push(HtmlBlock::UList(elements)); |
| 463 | } |
| 464 | |
| 465 | "ol" => { |
| 466 | let elements = get_li_elements(node); |
| 467 | output.push(HtmlBlock::OList(elements)); |
| 468 | } |
| 469 | |
| 470 | "blockquote" => { |
| 471 | let mut content = vec![]; |
| 472 | for child in node.children.borrow().iter() { |
| 473 | for block in convert_node(child, tags_to_ignore) { |
| 474 | content.push(block); |
| 475 | } |
| 476 | } |
| 477 | content = trim_text_blocks(join_text_blocks(content)); |
| 478 | output.push(HtmlBlock::Quote(Rc::new(content))); |
| 479 | } |
| 480 | |
| 481 | "p" => { |
| 482 | let content = &get_text_content(node); |
| 483 | output.push(HtmlBlock::Text(format!("\n{}\n", content.trim()))); |
| 484 | } |
| 485 | |
| 486 | "hr" => { |
| 487 | output.push(HtmlBlock::Separator); |
| 488 | } |
| 489 | |
| 490 | "br" => { |
| 491 | output.push(HtmlBlock::Text("\n".to_string())); |
| 492 | } |
| 493 | |
| 494 | "font" | "span" => { |
| 495 | let attrs = a.borrow(); |
| 496 | let span_attrs = attrs |
| 497 | .iter() |
| 498 | .flat_map(|attr| match &*attr.name.local { |
| 499 | "color" | "data-mx-color" => Some(("foreground", &*attr.value)), |
| 500 | "data-mx-bg-color" => Some(("background", &*attr.value)), |
| 501 | _ => None, |
| 502 | }) |
| 503 | .collect::<Vec<(&str, &str)>>(); |
| 504 | let content = get_text_content(node); |
| 505 | let mut span = String::new(); |
| 506 | crate::format_span(&mut span, content, span_attrs); |
| 507 | |
| 508 | output.push(HtmlBlock::Text(span)); |
| 509 | } |
| 510 | |
| 511 | tag => { |
| 512 | let content = get_text_content(node); |
| 513 | let block = match to_pango(tag) { |
| 514 | Some((t1, t2)) => format!("{}{}{}", t1, content, t2), |
| 515 | None => content, |
| 516 | }; |
| 517 | |
| 518 | output.push(HtmlBlock::Text(block)); |
| 519 | } |
| 520 | }; |
| 521 | } |
| 522 | _ => {} |
| 523 | } |
| 524 | |
| 525 | join_text_blocks(output) |
| 526 | } |
| 527 | |
| 528 | #[cfg(test)] |
| 529 | mod test { |
| 530 | use super::*; |
| 531 | use pretty_assertions::assert_eq; |
| 532 | |
| 533 | #[test] |
| 534 | fn test_html_blocks() { |
| 535 | let text = "<h1>heading 1 <em>italic</em></h1>\n<h2>heading 2</h2>\n<p>Some text with <em>markup</em> and <strong>other</strong> and more text and some <code>inline code</code>, that's all. And maybe some links http://google.es or <a href=\"http://gnome.org\">GNOME</a>.</p>\n<pre><code>Block text\n</code></pre>\n<ul>\n<li>This is a list</li>\n<li>second element</li>\n</ul>\n<ol>\n<li>another list</li>\n<li>that's all</li>\n</ol>\n<hr/>"; |
| 536 | let blocks = markup_html(text); |
| 537 | assert!(blocks.is_ok()); |
| 538 | let blocks = blocks.unwrap(); |
| 539 | assert_eq!(blocks.len(), 7); |
| 540 | |
| 541 | assert_eq!( |
| 542 | blocks[0], |
| 543 | HtmlBlock::Heading(1, "heading 1 <i>italic</i>".to_string()) |
| 544 | ); |
| 545 | assert_eq!(blocks[1], HtmlBlock::Heading(2, "heading 2".to_string())); |
| 546 | |
| 547 | assert!(matches!(&blocks[2], HtmlBlock::Text(..))); |
| 548 | assert!(matches!(&blocks[3], HtmlBlock::Code(..))); |
| 549 | assert!(matches!(&blocks[4], HtmlBlock::UList(..))); |
| 550 | assert!(matches!(&blocks[5], HtmlBlock::OList(..))); |
| 551 | assert!(matches!(&blocks[6], HtmlBlock::Separator)); |
| 552 | } |
| 553 | |
| 554 | #[test] |
| 555 | fn test_html_blocks_quote() { |
| 556 | let text = " |
| 557 | <blockquote> |
| 558 | <h1>heading 1 <em>bold</em></h1> |
| 559 | <h2>heading 2</h2> |
| 560 | <p>Some text with <em>markup</em> and <strong>other</strong> and more things ~~strike~~ and more text and some <code>inline code</code>, that's all. And maybe some links http://google.es or <a href="http://gnome.org">GNOME</a>, <a href=\"http://gnome.org\">GNOME</a>.</p> |
| 561 | <pre><code>`Block text |
| 562 | ` |
| 563 | </code></pre> |
| 564 | <ul> |
| 565 | <li>This is a list</li> |
| 566 | <li>second element</li> |
| 567 | </ul> |
| 568 | </blockquote> |
| 569 | <p>quote :D</p> |
| 570 | "; |
| 571 | |
| 572 | let blocks = markup_html(text); |
| 573 | assert!(blocks.is_ok()); |
| 574 | let blocks = blocks.unwrap(); |
| 575 | assert_eq!(blocks.len(), 2); |
| 576 | |
| 577 | if let HtmlBlock::Quote(blks) = &blocks[0] { |
| 578 | assert_eq!(blks.len(), 5); |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | #[test] |
| 583 | fn test_separator() { |
| 584 | let text = "aaa\n<hr/>foobar<hr/>baz<hr></hr>"; |
| 585 | |
| 586 | let blocks = markup_html(text); |
| 587 | assert!(blocks.is_ok()); |
| 588 | let blocks = blocks.unwrap(); |
| 589 | assert_eq!(blocks.len(), 6); |
| 590 | |
| 591 | let expected_blocks = [ |
| 592 | HtmlBlock::Text(String::from("aaa")), |
| 593 | HtmlBlock::Separator, |
| 594 | HtmlBlock::Text(String::from("foobar")), |
| 595 | HtmlBlock::Separator, |
| 596 | HtmlBlock::Text(String::from("baz")), |
| 597 | HtmlBlock::Separator, |
| 598 | ]; |
| 599 | for (block, expected) in blocks.iter().zip(expected_blocks.iter()) { |
| 600 | assert_eq!(block, expected); |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | #[test] |
| 605 | fn test_mxreply() { |
| 606 | let text = "<mx-reply><blockquote><a href=\"https://matrix.to/#/!hwiGbsdSTZIwSRfybq:matrix.org/$1553513281991555ZdMuB:matrix.org\">In reply to</a> <a href=\"https://matrix.to/#/@afranke:matrix.org\">@afranke:matrix.org</a><br><a href=\"https://matrix.to/#/@gergely:polonkai.eu\">Gergely Polonkai</a>: we have https://gitlab.gnome.org/GNOME/fractal/issues/467 and https://gitlab.gnome.org/GNOME/fractal/issues/347 open, does your issue fit any of these two?</blockquote></mx-reply><p>#467 <em>might</em> be it, let me test a bit<p>"; |
| 607 | |
| 608 | let blocks = markup_html(text); |
| 609 | assert!(blocks.is_ok()); |
| 610 | let blocks = blocks.unwrap(); |
| 611 | assert_eq!(blocks.len(), 2); |
| 612 | |
| 613 | if let HtmlBlock::Text(t) = &blocks[0] { |
| 614 | assert_eq!(t, "<a href=\"https://matrix.to/#/!hwiGbsdSTZIwSRfybq:matrix.org/$1553513281991555ZdMuB:matrix.org\">In reply to</a> <a href=\"https://matrix.to/#/@afranke:matrix.org\">@afranke:matrix.org</a><a href=\"https://matrix.to/#/@gergely:polonkai.eu\">Gergely Polonkai</a>: we have <a href=\"https://gitlab.gnome.org/GNOME/fractal/issues/467\">https://gitlab.gnome.org/GNOME/fractal/issues/467</a> and <a href=\"https://gitlab.gnome.org/GNOME/fractal/issues/347\">https://gitlab.gnome.org/GNOME/fractal/issues/347</a> open, does your issue fit any of these two?\n#467 <i>might</i> be it, let me test a bit"); |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | #[test] |
| 619 | fn test_html_lists() { |
| 620 | let text = " |
| 621 | <ul> |
| 622 | <li>item 1</li> |
| 623 | <li>item 2</li> |
| 624 | </ul> |
| 625 | "; |
| 626 | |
| 627 | let blocks = markup_html(text); |
| 628 | assert!(blocks.is_ok()); |
| 629 | let blocks = blocks.unwrap(); |
| 630 | assert_eq!(blocks.len(), 1); |
| 631 | |
| 632 | if let HtmlBlock::UList(t) = &blocks[0] { |
| 633 | assert_eq!(t.len(), 2); |
| 634 | assert_eq!(t[0], "item 1"); |
| 635 | assert_eq!(t[1], "item 2"); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn test_html_paragraphs() { |
| 641 | let text = " |
| 642 | <p>text</p> |
| 643 | <p><i>text2</i></p> |
| 644 | <p><b>text3</b></p> |
| 645 | <ul><li>li<li/></ul> |
| 646 | <p>text4</p> |
| 647 | <p>text5</p> |
| 648 | "; |
| 649 | let blocks = markup_html(text); |
| 650 | assert!(blocks.is_ok()); |
| 651 | let blocks = blocks.unwrap(); |
| 652 | assert!(!blocks.is_empty()); |
| 653 | assert_eq!(blocks.len(), 3); |
| 654 | |
| 655 | if let HtmlBlock::Text(t) = &blocks[0] { |
| 656 | assert_eq!(t, "text\n\n<i>text2</i>\n\n<b>text3</b>"); |
| 657 | } |
| 658 | if let HtmlBlock::Text(t) = &blocks[2] { |
| 659 | assert_eq!(t, "text4\n\ntext5"); |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | #[test] |
| 664 | fn newline_in_blockquote() { |
| 665 | let text = "<blockquote>html was a mistake<br />Indeed</blockquote>"; |
| 666 | let matrix_text = "<blockquote>\n<p>a<br />\nb</p>\n<p>c</p>\nd</blockquote>\n"; |
| 667 | |
| 668 | let blocks = markup_html(text); |
| 669 | assert!(blocks.is_ok()); |
| 670 | let blocks = blocks.unwrap(); |
| 671 | assert_eq!(blocks.len(), 1); |
| 672 | |
| 673 | if let HtmlBlock::Quote(blk) = &blocks[0] { |
| 674 | assert_eq!(blk.len(), 1); |
| 675 | if let HtmlBlock::Text(h) = &blk[0] { |
| 676 | assert_eq!(h, "html was a mistake\nIndeed"); |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | let blocks = markup_html(matrix_text); |
| 681 | assert!(blocks.is_ok()); |
| 682 | let blocks = blocks.unwrap(); |
| 683 | assert_eq!(blocks.len(), 1); |
| 684 | |
| 685 | if let HtmlBlock::Quote(blk) = &blocks[0] { |
| 686 | assert_eq!(blk.len(), 1); |
| 687 | if let HtmlBlock::Text(h) = &blk[0] { |
| 688 | assert_eq!(h, "a\nb\n\nc\nd"); |
| 689 | } |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | #[test] |
| 694 | fn html_blocks_quote_multiple() { |
| 695 | let text = "<blockquote>\n<p>Some</p>\n</blockquote>\n<p>text</p>\n<blockquote>\n<p>No</p>\n</blockquote>\n<p><strong>u</strong></p>\n"; |
| 696 | |
| 697 | let blocks = markup_html(text); |
| 698 | assert!(blocks.is_ok()); |
| 699 | let blocks = blocks.unwrap(); |
| 700 | assert_eq!(blocks.len(), 4); |
| 701 | |
| 702 | if let HtmlBlock::Quote(blk) = &blocks[0] { |
| 703 | assert_eq!(blk.len(), 1); |
| 704 | if let HtmlBlock::Text(h) = &blk[0] { |
| 705 | assert_eq!(h, "Some"); |
| 706 | } |
| 707 | } |
| 708 | if let HtmlBlock::Text(t) = &blocks[1] { |
| 709 | assert_eq!(t, "text"); |
| 710 | } |
| 711 | if let HtmlBlock::Quote(blk) = &blocks[2] { |
| 712 | assert_eq!(blk.len(), 1); |
| 713 | if let HtmlBlock::Text(h) = &blk[0] { |
| 714 | assert_eq!(h, "No"); |
| 715 | } |
| 716 | } |
| 717 | if let HtmlBlock::Text(t) = &blocks[3] { |
| 718 | assert_eq!(t, "<b>u</b>"); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | #[test] |
| 723 | fn html_url_and_text() { |
| 724 | let text = "<a href=\"https://gnome.org\">GNOME</a>text"; |
| 725 | |
| 726 | let blocks = markup_html(text); |
| 727 | assert!(blocks.is_ok()); |
| 728 | let blocks = blocks.unwrap(); |
| 729 | assert_eq!(blocks.len(), 1); |
| 730 | if let HtmlBlock::Text(h) = &blocks[0] { |
| 731 | assert_eq!( |
| 732 | h, |
| 733 | "<a href=\"https://gnome.org\" title=\"https://gnome.org\">GNOME</a>text" |
| 734 | ); |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | #[test] |
| 739 | fn html_font_span() { |
| 740 | let text = "GitLab labels: <span data-mx-color=\"#000000\"\n \ |
| 741 | data-mx-bg-color=\"#ccc063\"\n \ |
| 742 | >1. Enhancement</span>\n and \ |
| 743 | <font data-mx-color=\"#ffffff\"\n \ |
| 744 | data-mx-bg-color=\"#8574cc\"\n \ |
| 745 | >4. Newcomers</span>"; |
| 746 | |
| 747 | let blocks = markup_html(text); |
| 748 | assert!(blocks.is_ok()); |
| 749 | let blocks = blocks.unwrap(); |
| 750 | assert_eq!(blocks.len(), 1); |
| 751 | if let HtmlBlock::Text(h) = &blocks[0] { |
| 752 | assert_eq!(h, "GitLab labels: <span foreground=\"#000000\" background=\"#ccc063\">1. Enhancement</span> and <span foreground=\"#ffffff\" background=\"#8574cc\">4. Newcomers</span>"); |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | #[test] |
| 757 | fn html_non_block_tags() { |
| 758 | let text = |
| 759 | "How about some <u>underlined</u> <del>deleted</del> or <s>strikethrough</s> text? \ |
| 760 | Maybe <em>emphasized</em>, <i>italic</i>, <strong>strong</strong> or <b>bold</b> text? \ |
| 761 | Possibly a newline<br>with some more <code>code</code>? \ |
| 762 | Finally some <sub>sub</sub> or <sup>super</sup> par lines!"; |
| 763 | |
| 764 | let blocks = markup_html(text); |
| 765 | assert!(blocks.is_ok()); |
| 766 | let blocks = blocks.unwrap(); |
| 767 | assert_eq!(blocks.len(), 1); |
| 768 | let HtmlBlock::Text(h) = &blocks[0] else { |
| 769 | panic!("No text block found") |
| 770 | }; |
| 771 | assert_eq!( |
| 772 | h, |
| 773 | "How about some <u>underlined</u> <s>deleted</s> or <s>strikethrough</s> text? \ |
| 774 | Maybe <i>emphasized</i>, <i>italic</i>, <b>strong</b> or <b>bold</b> text? \ |
| 775 | Possibly a newline\nwith some more <tt>code</tt>? \ |
| 776 | Finally some <sub>sub</sub> or <sup>super</sup> par lines!" |
| 777 | ); |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn codeblock_empty_whitespace() { |
| 782 | let text = " |
| 783 | <pre><code> |
| 784 | Block text `a` <i>i</i> |
| 785 | |
| 786 | space? |
| 787 | </code></pre> |
| 788 | "; |
| 789 | |
| 790 | let blocks = markup_html(text); |
| 791 | assert!(blocks.is_ok()); |
| 792 | let blocks = blocks.unwrap(); |
| 793 | assert_eq!(blocks.len(), 1); |
| 794 | if let HtmlBlock::Code(t) = &blocks[0] { |
| 795 | assert_eq!(t, "Block text `a` <i>i</i>\n\nspace?") |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | #[test] |
| 800 | fn escape_amp() { |
| 801 | let text = "text: <code>&</code> was not scaped as <code>&amp;</code>"; |
| 802 | let blocks = markup_html(text); |
| 803 | assert!(blocks.is_ok()); |
| 804 | let blocks = blocks.unwrap(); |
| 805 | assert_eq!(blocks.len(), 1); |
| 806 | |
| 807 | if let HtmlBlock::Text(t) = &blocks[0] { |
| 808 | assert_eq!( |
| 809 | t, |
| 810 | "text: <tt>&</tt> was not scaped as <tt>&amp;</tt>" |
| 811 | ); |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | #[test] |
| 816 | fn dont_escape_codeblocks() { |
| 817 | let text = " |
| 818 | <pre><code> |
| 819 | & |
| 820 | </code></pre> |
| 821 | <code>&<code> |
| 822 | "; |
| 823 | |
| 824 | let blocks = markup_html(text); |
| 825 | assert!(blocks.is_ok()); |
| 826 | let blocks = blocks.unwrap(); |
| 827 | assert_eq!(blocks.len(), 2); |
| 828 | if let HtmlBlock::Code(t) = &blocks[0] { |
| 829 | assert_eq!(t, "&") |
| 830 | } |
| 831 | if let HtmlBlock::Code(t) = &blocks[1] { |
| 832 | assert_eq!(t, "&") |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | #[test] |
| 837 | fn newlines_in_text() { |
| 838 | let text = " |
| 839 | 1 |
| 840 | 2 |
| 841 | <span> 3</span> |
| 842 | |
| 843 | <p> 4 |
| 844 | 5</p> |
| 845 | <p>6 </p> |
| 846 | "; |
| 847 | let text_matrix = "<p>a<br />\nb</p>\n<p>c</p>\nd"; |
| 848 | let text_matrix_gitlab = "<strong>[<a href=\"https://gitlab.gnome.org/GNOME/fractal\">GNOME/fractal</a>]</strong> <a href=\"https://gitlab.gnome.org/user\">user</a>\n added <span title=\"This label is for the rewrite of Fractal, currently under the working name of fractal-next\"\n > Fractal-next </span>\n to\n\n <a href=\"https://gitlab.gnome.org/GNOME/fractal/-/issues/194\" >issue #194</a>: Replies support"; |
| 849 | |
| 850 | let blocks = markup_html(text); |
| 851 | assert!(blocks.is_ok()); |
| 852 | let blocks = blocks.unwrap(); |
| 853 | assert_eq!(blocks.len(), 1); |
| 854 | if let HtmlBlock::Text(t) = &blocks[0] { |
| 855 | assert_eq!(t, "1 2 3\n4 5\n\n6") |
| 856 | } |
| 857 | |
| 858 | let blocks = markup_html(text_matrix); |
| 859 | assert!(blocks.is_ok()); |
| 860 | let blocks = blocks.unwrap(); |
| 861 | assert_eq!(blocks.len(), 1); |
| 862 | if let HtmlBlock::Text(t) = &blocks[0] { |
| 863 | assert_eq!(t, "a\nb\n\nc\nd") |
| 864 | } |
| 865 | |
| 866 | let blocks = markup_html(text_matrix_gitlab); |
| 867 | assert!(blocks.is_ok()); |
| 868 | let blocks = blocks.unwrap(); |
| 869 | assert_eq!(blocks.len(), 1); |
| 870 | if let HtmlBlock::Text(t) = &blocks[0] { |
| 871 | assert_eq!(t, "<b>[<a href=\"https://gitlab.gnome.org/GNOME/fractal\" title=\"https://gitlab.gnome.org/GNOME/fractal\">GNOME/fractal</a>]</b> <a href=\"https://gitlab.gnome.org/user\" title=\"https://gitlab.gnome.org/user\">user</a> added \u{a0}Fractal-next\u{a0} to <a href=\"https://gitlab.gnome.org/GNOME/fractal/-/issues/194\" title=\"https://gitlab.gnome.org/GNOME/fractal/-/issues/194\">issue #194</a>: Replies support"); |
| 872 | } |
| 873 | |
| 874 | let text_h1 = "<h1>foo \n bar</h1>"; |
| 875 | let blocks = markup_html(text_h1).unwrap(); |
| 876 | if let HtmlBlock::Heading(1, t) = &blocks[0] { |
| 877 | assert_eq!(t, "foo bar"); |
| 878 | } |
| 879 | |
| 880 | let text_ul = "<ul><li>first \n element</li><li>second<br/> element</li></ul>"; |
| 881 | let blocks = markup_html(text_ul).unwrap(); |
| 882 | if let HtmlBlock::UList(ts) = &blocks[0] { |
| 883 | assert_eq!(ts[0], "first element"); |
| 884 | assert_eq!(ts[1], "second\nelement"); |
| 885 | } |
| 886 | |
| 887 | let text_ol = "<ol><li>first \n element</li><li>second<br/> element</li></ol>"; |
| 888 | let blocks = markup_html(text_ol).unwrap(); |
| 889 | if let HtmlBlock::OList(ts) = &blocks[0] { |
| 890 | assert_eq!(ts[0], "first element"); |
| 891 | assert_eq!(ts[1], "second\nelement"); |
| 892 | } |
| 893 | |
| 894 | let text_bq = "<blockquote><p>Foo:\n <p><ul><li>First \n item</li></ul></blockquote>"; |
| 895 | let blocks = markup_html(text_bq).unwrap(); |
| 896 | if let HtmlBlock::Quote(contents) = &blocks[0] { |
| 897 | assert_eq!(contents[0], HtmlBlock::Text(String::from("Foo:"))); |
| 898 | assert_eq!( |
| 899 | contents[1], |
| 900 | HtmlBlock::UList(vec![String::from("First item")]) |
| 901 | ); |
| 902 | } |
| 903 | } |
| 904 | |
| 905 | #[test] |
| 906 | fn links_inside_code() { |
| 907 | let text = " |
| 908 | <pre><code>https://gitlab.gnome.org/World/Fractal/</code></pre>\n |
| 909 | "; |
| 910 | let blocks = markup_html(text); |
| 911 | assert!(blocks.is_ok()); |
| 912 | let blocks = blocks.unwrap(); |
| 913 | assert_eq!(blocks.len(), 1); |
| 914 | |
| 915 | if let HtmlBlock::Code(t) = &blocks[0] { |
| 916 | assert_eq!(t, "https://gitlab.gnome.org/World/Fractal/"); |
| 917 | } |
| 918 | } |
| 919 | |
| 920 | #[test] |
| 921 | fn ci_links() { |
| 922 | let text = " |
| 923 | [<a href='https://gitlab.gnome.org/World/Fractal'>World/Fractal</a>] |
| 924 | "; |
| 925 | let blocks = markup_html(text); |
| 926 | assert!(blocks.is_ok()); |
| 927 | let blocks = blocks.unwrap(); |
| 928 | assert_eq!(blocks.len(), 1); |
| 929 | |
| 930 | if let HtmlBlock::Text(s) = &blocks[0] { |
| 931 | assert_eq!(s, "[<a href=\"https://gitlab.gnome.org/World/Fractal\" title=\"https://gitlab.gnome.org/World/Fractal\">World/Fractal</a>]"); |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | #[test] |
| 936 | fn newline_after_quotes() { |
| 937 | let text = "<mx-reply><blockquote><a href=\"https://matrix.org\">In reply to</a> <a href=\"https://matrix.org\">@okias:matrix.org</a><br>Text</blockquote></mx-reply>F"; |
| 938 | let target = "<a href=\"https://matrix.org\" title=\"https://matrix.org\">In reply to</a> <a href=\"https://matrix.org\" title=\"https://matrix.org\">@okias:matrix.org</a>\nText"; |
| 939 | let blocks = markup_html(text); |
| 940 | assert!(blocks.is_ok()); |
| 941 | let blocks = blocks.unwrap(); |
| 942 | assert_eq!(blocks.len(), 2); |
| 943 | |
| 944 | if let HtmlBlock::Quote(blk) = &blocks[0] { |
| 945 | assert_eq!(blk.len(), 1); |
| 946 | if let HtmlBlock::Text(h) = &blk[0] { |
| 947 | assert_eq!(h, target); |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | if let HtmlBlock::Text(t) = &blocks[1] { |
| 952 | assert_eq!(t, "F"); |
| 953 | } |
| 954 | } |
| 955 | } |