src/message/html.rs
1423 lines · 44771 bytes
1//! # Rendering for formatted bodies
2//!
3//! This module contains the code for rendering messages that contained an
4//! "org.matrix.custom.html"-formatted body.
5//!
6//! The Matrix specification recommends limiting rendered tags and attributes to a safe subset of
7//! HTML. You can read more in section 11.2.1.1, "m.room.message msgtypes":
8//!
9//! <https://spec.matrix.org/unstable/client-server-api/#mroommessage-msgtypes>
10//!
11//! This isn't as important for iamb, since it isn't a browser environment, but we do still map
12//! input onto an enum of the safe list of tags to keep it easy to understand and process.
13use std::ops::Deref;
14
15use css_color_parser::Color as CssColor;
16use markup5ever_rcdom::{Handle, NodeData, RcDom};
17use unicode_segmentation::UnicodeSegmentation;
18use url::Url;
19
20use html5ever::{
21 driver::{parse_fragment, ParseOpts},
22 interface::{Attribute, QualName},
23 local_name,
24 namespace_url,
25 ns,
26 tendril::{StrTendril, TendrilSink},
27};
28
29use modalkit::tui::{
30 layout::Alignment,
31 style::{Color, Modifier as StyleModifier, Style},
32 symbols::line,
33 text::{Line, Span, Text},
34};
35
36use crate::{
37 message::printer::TextPrinter,
38 util::{join_cell_text, space_text},
39};
40
41/// Generate bullet points from a [ListStyle].
42pub struct BulletIterator {
43 style: ListStyle,
44 pos: usize,
45 len: usize,
46}
47
48impl BulletIterator {
49 fn width(&self) -> usize {
50 match self.style {
51 ListStyle::Unordered => 2,
52 ListStyle::Ordered => self.len.to_string().len() + 2,
53 }
54 }
55}
56
57impl Iterator for BulletIterator {
58 type Item = String;
59
60 fn next(&mut self) -> Option<Self::Item> {
61 if self.pos == self.len {
62 return None;
63 }
64
65 self.pos += 1;
66
67 let bullet = match self.style {
68 ListStyle::Unordered => "- ".to_string(),
69 ListStyle::Ordered => {
70 let w = self.len.to_string().len();
71 format!("{: >w$}. ", self.pos, w = w)
72 },
73 };
74
75 return Some(bullet);
76 }
77}
78
79/// Whether this list is ordered or unordered.
80#[derive(Clone, Copy, Debug)]
81pub enum ListStyle {
82 Ordered,
83 Unordered,
84}
85
86impl ListStyle {
87 fn bullets(&self, len: usize) -> BulletIterator {
88 BulletIterator { style: *self, pos: 0, len }
89 }
90}
91
92pub type StyleTreeChildren = Vec<StyleTreeNode>;
93
94/// Type of contents in a table cell.
95pub enum CellType {
96 Data,
97 Header,
98}
99
100/// A collection of cells for a single row in a table.
101pub struct TableRow {
102 cells: Vec<(CellType, StyleTreeNode)>,
103}
104
105impl TableRow {
106 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
107 for (_, cell) in &self.cells {
108 cell.gather_links(urls);
109 }
110 }
111
112 fn columns(&self) -> usize {
113 self.cells.len()
114 }
115}
116
117/// A collection of rows in a table.
118pub struct TableSection {
119 rows: Vec<TableRow>,
120}
121
122impl TableSection {
123 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
124 for row in &self.rows {
125 row.gather_links(urls);
126 }
127 }
128
129 fn columns(&self) -> usize {
130 self.rows.iter().map(TableRow::columns).max().unwrap_or(0)
131 }
132}
133
134/// A table.
135pub struct Table {
136 caption: Option<Box<StyleTreeNode>>,
137 sections: Vec<TableSection>,
138}
139
140impl Table {
141 fn columns(&self) -> usize {
142 self.sections.iter().map(TableSection::columns).max().unwrap_or(0)
143 }
144
145 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
146 for section in &self.sections {
147 section.gather_links(urls);
148 }
149 }
150
151 fn to_text(&self, width: usize, style: Style) -> Text {
152 let mut text = Text::default();
153 let columns = self.columns();
154 let cell_total = width.saturating_sub(columns).saturating_sub(1);
155 let cell_min = cell_total / columns;
156 let mut cell_slop = cell_total - cell_min * columns;
157 let cell_widths = (0..columns)
158 .map(|_| {
159 let slopped = cell_slop.min(1);
160 cell_slop -= slopped;
161 cell_min + slopped
162 })
163 .collect::<Vec<_>>();
164
165 let mut nrows = 0;
166
167 if let Some(caption) = &self.caption {
168 let subw = width.saturating_sub(6);
169 let mut printer = TextPrinter::new(subw, style, true).align(Alignment::Center);
170 caption.print(&mut printer, style);
171
172 for mut line in printer.finish().lines {
173 line.spans.insert(0, Span::styled(" ", style));
174 line.spans.push(Span::styled(" ", style));
175 text.lines.push(line);
176 }
177 }
178
179 for section in self.sections.iter() {
180 for row in section.rows.iter() {
181 let mut ruler = String::new();
182
183 for (i, w) in cell_widths.iter().enumerate() {
184 let cross = match (nrows, i) {
185 (0, 0) => line::TOP_LEFT,
186 (0, _) => line::HORIZONTAL_DOWN,
187 (_, 0) => line::VERTICAL_RIGHT,
188 (_, _) => line::CROSS,
189 };
190
191 ruler.push_str(cross);
192
193 for _ in 0..*w {
194 ruler.push_str(line::HORIZONTAL);
195 }
196 }
197
198 if nrows == 0 {
199 ruler.push_str(line::TOP_RIGHT);
200 } else {
201 ruler.push_str(line::VERTICAL_LEFT);
202 }
203
204 text.lines.push(Line::from(vec![Span::styled(ruler, style)]));
205
206 let cells = cell_widths
207 .iter()
208 .enumerate()
209 .map(|(i, w)| {
210 let text = if let Some((kind, cell)) = row.cells.get(i) {
211 let style = match kind {
212 CellType::Header => style.add_modifier(StyleModifier::BOLD),
213 CellType::Data => style,
214 };
215
216 cell.to_text(*w, style)
217 } else {
218 space_text(*w, style)
219 };
220
221 (text, *w)
222 })
223 .collect();
224
225 let joined = join_cell_text(cells, Span::styled(line::VERTICAL, style), style);
226 text.lines.extend(joined.lines);
227
228 nrows += 1;
229 }
230 }
231
232 if nrows > 0 {
233 let mut ruler = String::new();
234
235 for (i, w) in cell_widths.iter().enumerate() {
236 let cross = if i == 0 {
237 line::BOTTOM_LEFT
238 } else {
239 line::HORIZONTAL_UP
240 };
241
242 ruler.push_str(cross);
243
244 for _ in 0..*w {
245 ruler.push_str(line::HORIZONTAL);
246 }
247 }
248
249 ruler.push_str(line::BOTTOM_RIGHT);
250 text.lines.push(Line::from(vec![Span::styled(ruler, style)]));
251 }
252
253 text
254 }
255}
256
257/// A processed HTML element that we can render to the terminal.
258pub enum StyleTreeNode {
259 Anchor(Box<StyleTreeNode>, char, Url),
260 Blockquote(Box<StyleTreeNode>),
261 Break,
262 Code(Box<StyleTreeNode>, Option<String>),
263 Header(Box<StyleTreeNode>, usize),
264 Image(Option<String>),
265 List(StyleTreeChildren, ListStyle),
266 Paragraph(Box<StyleTreeNode>),
267 Pre(Box<StyleTreeNode>),
268 Reply(Box<StyleTreeNode>),
269 Ruler,
270 Style(Box<StyleTreeNode>, Style),
271 Table(Table),
272 Text(String),
273 Sequence(StyleTreeChildren),
274}
275
276impl StyleTreeNode {
277 pub fn to_text(&self, width: usize, style: Style) -> Text {
278 let mut printer = TextPrinter::new(width, style, true);
279 self.print(&mut printer, style);
280 printer.finish()
281 }
282
283 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
284 match self {
285 StyleTreeNode::Anchor(_, c, url) => {
286 urls.push((*c, url.clone()));
287 },
288
289 StyleTreeNode::Blockquote(child) |
290 StyleTreeNode::Code(child, _) |
291 StyleTreeNode::Header(child, _) |
292 StyleTreeNode::Paragraph(child) |
293 StyleTreeNode::Pre(child) |
294 StyleTreeNode::Reply(child) |
295 StyleTreeNode::Style(child, _) => {
296 child.gather_links(urls);
297 },
298
299 StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => {
300 for child in children {
301 child.gather_links(urls);
302 }
303 },
304
305 StyleTreeNode::Table(table) => {
306 table.gather_links(urls);
307 },
308
309 StyleTreeNode::Image(_) => {},
310 StyleTreeNode::Ruler => {},
311 StyleTreeNode::Text(_) => {},
312 StyleTreeNode::Break => {},
313 }
314 }
315
316 pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) {
317 let width = printer.width();
318
319 match self {
320 StyleTreeNode::Anchor(child, c, _) => {
321 let bold = style.add_modifier(StyleModifier::BOLD);
322 child.print(printer, bold);
323
324 let link = format!("[{c}]");
325 let span = Span::styled(link, style);
326 printer.push_span_nobreak(span);
327 },
328 StyleTreeNode::Blockquote(child) => {
329 let mut subp = printer.sub(4);
330 child.print(&mut subp, style);
331
332 for mut line in subp.finish() {
333 line.spans.insert(0, Span::styled(" ", style));
334 printer.push_line(line);
335 }
336 },
337 StyleTreeNode::Code(child, _) => {
338 child.print(printer, style);
339 },
340 StyleTreeNode::Header(child, level) => {
341 let style = style.add_modifier(StyleModifier::BOLD);
342
343 for _ in 0..*level {
344 printer.push_str("#", style);
345 }
346
347 printer.push_str(" ", style);
348 child.print(printer, style);
349 },
350 StyleTreeNode::Image(None) => {},
351 StyleTreeNode::Image(Some(alt)) => {
352 printer.commit();
353 printer.push_str("Image Alt: ", Style::default());
354 printer.push_str(alt, Style::default());
355 printer.commit();
356 },
357 StyleTreeNode::List(children, lt) => {
358 let mut bullets = lt.bullets(children.len());
359 let liw = bullets.width();
360
361 for child in children {
362 let mut subp = printer.sub(liw);
363 let mut bullet = bullets.next();
364 child.print(&mut subp, style);
365
366 for mut line in subp.finish() {
367 let leading = if let Some(bullet) = bullet.take() {
368 Span::styled(bullet, style)
369 } else {
370 Span::styled(" ".repeat(liw), style)
371 };
372
373 line.spans.insert(0, leading);
374 printer.push_line(line);
375 }
376 }
377 },
378 StyleTreeNode::Paragraph(child) => {
379 printer.push_break();
380 child.print(printer, style);
381 printer.commit();
382 },
383 StyleTreeNode::Pre(child) => {
384 let mut subp = printer.sub(2).literal(true);
385 let subw = subp.width();
386
387 child.print(&mut subp, style);
388
389 printer.commit();
390 printer.push_line(
391 vec![
392 Span::styled(line::TOP_LEFT, style),
393 Span::styled(line::HORIZONTAL.repeat(subw), style),
394 Span::styled(line::TOP_RIGHT, style),
395 ]
396 .into(),
397 );
398
399 for mut line in subp.finish() {
400 line.spans.insert(0, Span::styled(line::VERTICAL, style));
401 line.spans.push(Span::styled(line::VERTICAL, style));
402 printer.push_line(line);
403 }
404
405 printer.push_line(
406 vec![
407 Span::styled(line::BOTTOM_LEFT, style),
408 Span::styled(line::HORIZONTAL.repeat(subw), style),
409 Span::styled(line::BOTTOM_RIGHT, style),
410 ]
411 .into(),
412 );
413
414 printer.commit();
415 },
416 StyleTreeNode::Reply(child) => {
417 if printer.hide_reply() {
418 return;
419 }
420
421 printer.push_break();
422 child.print(printer, style);
423 printer.commit();
424 },
425 StyleTreeNode::Ruler => {
426 for _ in 0..width {
427 printer.push_str(line::HORIZONTAL, style);
428 }
429 },
430 StyleTreeNode::Table(table) => {
431 let text = table.to_text(width, style);
432 printer.push_text(text);
433 },
434 StyleTreeNode::Break => {
435 printer.push_break();
436 },
437 StyleTreeNode::Text(s) => {
438 printer.push_str(s.as_str(), style);
439 },
440
441 StyleTreeNode::Style(child, patch) => child.print(printer, style.patch(*patch)),
442 StyleTreeNode::Sequence(children) => {
443 for child in children {
444 child.print(printer, style);
445 }
446 },
447 }
448 }
449}
450
451/// A processed HTML document.
452pub struct StyleTree {
453 children: StyleTreeChildren,
454}
455
456impl StyleTree {
457 pub fn get_links(&self) -> Vec<(char, Url)> {
458 let mut links = Vec::new();
459
460 for child in &self.children {
461 child.gather_links(&mut links);
462 }
463
464 return links;
465 }
466
467 pub fn to_text(&self, width: usize, style: Style, hide_reply: bool) -> Text<'_> {
468 let mut printer = TextPrinter::new(width, style, hide_reply);
469
470 for child in self.children.iter() {
471 child.print(&mut printer, style);
472 }
473
474 printer.finish()
475 }
476}
477
478pub struct TreeGenState {
479 link_num: u8,
480}
481
482impl TreeGenState {
483 fn next_link_char(&mut self) -> Option<char> {
484 let num = self.link_num;
485
486 if num < 62 {
487 self.link_num = num + 1;
488 }
489
490 if num < 10 {
491 Some((num + b'0') as char)
492 } else if num < 36 {
493 Some((num - 10 + b'a') as char)
494 } else if num < 62 {
495 Some((num - 36 + b'A') as char)
496 } else {
497 None
498 }
499 }
500}
501
502fn c2c(handles: &[Handle], state: &mut TreeGenState) -> Vec<StyleTreeNode> {
503 handles.iter().flat_map(|h| h2t(h, state)).collect()
504}
505
506fn c2t(handles: &[Handle], state: &mut TreeGenState) -> Box<StyleTreeNode> {
507 let node = StyleTreeNode::Sequence(c2c(handles, state));
508
509 Box::new(node)
510}
511
512fn get_node(hdl: &Handle, want: &str, state: &mut TreeGenState) -> Option<StyleTreeNode> {
513 let node = hdl.deref();
514
515 if let NodeData::Element { name, .. } = &node.data {
516 if name.local.as_ref() != want {
517 return None;
518 }
519
520 let c = c2c(&node.children.borrow(), state);
521 return Some(StyleTreeNode::Sequence(c));
522 } else {
523 return None;
524 }
525}
526
527fn li2t(hdl: &Handle, state: &mut TreeGenState) -> Option<StyleTreeNode> {
528 get_node(hdl, "li", state)
529}
530
531fn table_cell(hdl: &Handle, state: &mut TreeGenState) -> Option<(CellType, StyleTreeNode)> {
532 if let Some(node) = get_node(hdl, "th", state) {
533 return Some((CellType::Header, node));
534 }
535
536 Some((CellType::Data, get_node(hdl, "td", state)?))
537}
538
539fn table_row(hdl: &Handle, state: &mut TreeGenState) -> Option<TableRow> {
540 let node = hdl.deref();
541
542 if let NodeData::Element { name, .. } = &node.data {
543 if name.local.as_ref() != "tr" {
544 return None;
545 }
546
547 let cells = table_cells(&node.children.borrow(), state);
548 return Some(TableRow { cells });
549 } else {
550 return None;
551 }
552}
553
554fn table_section(hdl: &Handle, state: &mut TreeGenState) -> Option<TableSection> {
555 let node = hdl.deref();
556
557 if let NodeData::Element { name, .. } = &node.data {
558 match name.local.as_ref() {
559 "thead" | "tbody" => {
560 let rows = table_rows(&node.children.borrow(), state);
561
562 Some(TableSection { rows })
563 },
564 _ => None,
565 }
566 } else {
567 return None;
568 }
569}
570
571fn table_cells(handles: &[Handle], state: &mut TreeGenState) -> Vec<(CellType, StyleTreeNode)> {
572 handles.iter().filter_map(|h| table_cell(h, state)).collect()
573}
574
575fn table_rows(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableRow> {
576 handles.iter().filter_map(|h| table_row(h, state)).collect()
577}
578
579fn table_sections(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableSection> {
580 handles.iter().filter_map(|h| table_section(h, state)).collect()
581}
582
583fn lic2t(handles: &[Handle], state: &mut TreeGenState) -> StyleTreeChildren {
584 handles.iter().filter_map(|h| li2t(h, state)).collect()
585}
586
587fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> {
588 for attr in attrs {
589 if attr.name.local.as_ref() != "alt" {
590 continue;
591 }
592
593 return Some(attr.value.to_string());
594 }
595
596 return None;
597}
598
599fn attrs_to_href(attrs: &[Attribute]) -> Option<String> {
600 for attr in attrs {
601 if attr.name.local.as_ref() != "href" {
602 continue;
603 }
604
605 return Some(attr.value.to_string());
606 }
607
608 return None;
609}
610
611fn attrs_to_language(attrs: &[Attribute]) -> Option<String> {
612 for attr in attrs {
613 if attr.name.local.as_ref() != "class" {
614 continue;
615 }
616
617 for class in attr.value.as_ref().unicode_words() {
618 if class.len() > 9 && class.starts_with("language-") {
619 return Some(class[9..].to_string());
620 }
621 }
622 }
623
624 return None;
625}
626
627fn attrs_to_style(attrs: &[Attribute]) -> Style {
628 let mut style = Style::default();
629
630 for attr in attrs {
631 match attr.name.local.as_ref() {
632 "data-mx-bg-color" => {
633 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
634 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
635 style = style.bg(color);
636 }
637 },
638 "data-mx-color" | "color" => {
639 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
640 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
641 style = style.fg(color);
642 }
643 },
644 _ => continue,
645 }
646 }
647
648 return style;
649}
650
651fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
652 let node = hdl.deref();
653
654 let tree = match &node.data {
655 NodeData::Document => *c2t(node.children.borrow().as_slice(), state),
656 NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string()),
657 NodeData::Element { name, attrs, .. } => {
658 match name.local.as_ref() {
659 // Message that this one replies to.
660 "mx-reply" => StyleTreeNode::Reply(c2t(&node.children.borrow(), state)),
661
662 // Links
663 "a" => {
664 let c = c2t(&node.children.borrow(), state);
665 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok());
666
667 if let Some(h) = h {
668 if let Some(n) = state.next_link_char() {
669 StyleTreeNode::Anchor(c, n, h)
670 } else {
671 *c
672 }
673 } else {
674 *c
675 }
676 },
677
678 // Style change
679 "b" | "strong" => {
680 let c = c2t(&node.children.borrow(), state);
681 let s = Style::default().add_modifier(StyleModifier::BOLD);
682
683 StyleTreeNode::Style(c, s)
684 },
685 "font" => {
686 let c = c2t(&node.children.borrow(), state);
687 let s = attrs_to_style(&attrs.borrow());
688
689 StyleTreeNode::Style(c, s)
690 },
691 "em" | "i" => {
692 let c = c2t(&node.children.borrow(), state);
693 let s = Style::default().add_modifier(StyleModifier::ITALIC);
694
695 StyleTreeNode::Style(c, s)
696 },
697 "span" => {
698 let c = c2t(&node.children.borrow(), state);
699 let s = attrs_to_style(&attrs.borrow());
700
701 StyleTreeNode::Style(c, s)
702 },
703 "del" | "strike" => {
704 let c = c2t(&node.children.borrow(), state);
705 let s = Style::default().add_modifier(StyleModifier::CROSSED_OUT);
706
707 StyleTreeNode::Style(c, s)
708 },
709 "u" => {
710 let c = c2t(&node.children.borrow(), state);
711 let s = Style::default().add_modifier(StyleModifier::UNDERLINED);
712
713 StyleTreeNode::Style(c, s)
714 },
715
716 // Lists
717 "ol" => {
718 StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Ordered)
719 },
720 "ul" => {
721 StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Unordered)
722 },
723
724 // Headers
725 "h1" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 1),
726 "h2" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 2),
727 "h3" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 3),
728 "h4" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 4),
729 "h5" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 5),
730 "h6" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 6),
731
732 // Table
733 "table" => {
734 let sections = table_sections(&node.children.borrow(), state);
735 let caption = node
736 .children
737 .borrow()
738 .iter()
739 .find_map(|hdl| get_node(hdl, "caption", state))
740 .map(Box::new);
741 let table = Table { caption, sections };
742
743 StyleTreeNode::Table(table)
744 },
745
746 // Code blocks.
747 "code" => {
748 let c = c2t(&node.children.borrow(), state);
749 let l = attrs_to_language(&attrs.borrow());
750
751 StyleTreeNode::Code(c, l)
752 },
753
754 // Other text blocks.
755 "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow(), state)),
756 "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow(), state)),
757 "pre" => StyleTreeNode::Pre(c2t(&node.children.borrow(), state)),
758
759 // No children.
760 "hr" => StyleTreeNode::Ruler,
761 "br" => StyleTreeNode::Break,
762
763 "img" => StyleTreeNode::Image(attrs_to_alt(&attrs.borrow())),
764
765 // These don't render in any special way.
766 "details" | "html" | "summary" | "sub" | "sup" => {
767 *c2t(&node.children.borrow(), state)
768 },
769
770 _ => return vec![],
771 }
772 },
773
774 // These don't render as anything.
775 NodeData::Doctype { .. } => return vec![],
776 NodeData::Comment { .. } => return vec![],
777 NodeData::ProcessingInstruction { .. } => return vec![],
778 };
779
780 vec![tree]
781}
782
783fn dom_to_style_tree(dom: RcDom) -> StyleTree {
784 let mut state = TreeGenState { link_num: 0 };
785 let children = h2t(&dom.document, &mut state);
786
787 StyleTree { children }
788}
789
790/// Parse an HTML document from a string.
791pub fn parse_matrix_html(s: &str) -> StyleTree {
792 let dom = parse_fragment(
793 RcDom::default(),
794 ParseOpts::default(),
795 QualName::new(None, ns!(html), local_name!("body")),
796 vec![],
797 )
798 .one(StrTendril::from(s));
799
800 dom_to_style_tree(dom)
801}
802
803#[cfg(test)]
804pub mod tests {
805 use super::*;
806 use crate::util::space_span;
807 use pretty_assertions::assert_eq;
808
809 #[test]
810 fn test_header() {
811 let bold = Style::default().add_modifier(StyleModifier::BOLD);
812
813 let s = "<h1>Header 1</h1>";
814 let tree = parse_matrix_html(s);
815 let text = tree.to_text(20, Style::default(), false);
816 assert_eq!(text.lines, vec![Line::from(vec![
817 Span::styled("#", bold),
818 Span::styled(" ", bold),
819 Span::styled("Header", bold),
820 Span::styled(" ", bold),
821 Span::styled("1", bold),
822 space_span(10, Style::default())
823 ])]);
824
825 let s = "<h2>Header 2</h2>";
826 let tree = parse_matrix_html(s);
827 let text = tree.to_text(20, Style::default(), false);
828 assert_eq!(text.lines, vec![Line::from(vec![
829 Span::styled("#", bold),
830 Span::styled("#", bold),
831 Span::styled(" ", bold),
832 Span::styled("Header", bold),
833 Span::styled(" ", bold),
834 Span::styled("2", bold),
835 space_span(9, Style::default())
836 ])]);
837
838 let s = "<h3>Header 3</h3>";
839 let tree = parse_matrix_html(s);
840 let text = tree.to_text(20, Style::default(), false);
841 assert_eq!(text.lines, vec![Line::from(vec![
842 Span::styled("#", bold),
843 Span::styled("#", bold),
844 Span::styled("#", bold),
845 Span::styled(" ", bold),
846 Span::styled("Header", bold),
847 Span::styled(" ", bold),
848 Span::styled("3", bold),
849 space_span(8, Style::default())
850 ])]);
851
852 let s = "<h4>Header 4</h4>";
853 let tree = parse_matrix_html(s);
854 let text = tree.to_text(20, Style::default(), false);
855 assert_eq!(text.lines, vec![Line::from(vec![
856 Span::styled("#", bold),
857 Span::styled("#", bold),
858 Span::styled("#", bold),
859 Span::styled("#", bold),
860 Span::styled(" ", bold),
861 Span::styled("Header", bold),
862 Span::styled(" ", bold),
863 Span::styled("4", bold),
864 space_span(7, Style::default())
865 ])]);
866
867 let s = "<h5>Header 5</h5>";
868 let tree = parse_matrix_html(s);
869 let text = tree.to_text(20, Style::default(), false);
870 assert_eq!(text.lines, vec![Line::from(vec![
871 Span::styled("#", bold),
872 Span::styled("#", bold),
873 Span::styled("#", bold),
874 Span::styled("#", bold),
875 Span::styled("#", bold),
876 Span::styled(" ", bold),
877 Span::styled("Header", bold),
878 Span::styled(" ", bold),
879 Span::styled("5", bold),
880 space_span(6, Style::default())
881 ])]);
882
883 let s = "<h6>Header 6</h6>";
884 let tree = parse_matrix_html(s);
885 let text = tree.to_text(20, Style::default(), false);
886 assert_eq!(text.lines, vec![Line::from(vec![
887 Span::styled("#", bold),
888 Span::styled("#", bold),
889 Span::styled("#", bold),
890 Span::styled("#", bold),
891 Span::styled("#", bold),
892 Span::styled("#", bold),
893 Span::styled(" ", bold),
894 Span::styled("Header", bold),
895 Span::styled(" ", bold),
896 Span::styled("6", bold),
897 space_span(5, Style::default())
898 ])]);
899 }
900
901 #[test]
902 fn test_style() {
903 let def = Style::default();
904 let bold = def.add_modifier(StyleModifier::BOLD);
905 let italic = def.add_modifier(StyleModifier::ITALIC);
906 let strike = def.add_modifier(StyleModifier::CROSSED_OUT);
907 let underl = def.add_modifier(StyleModifier::UNDERLINED);
908 let red = def.fg(Color::Rgb(0xff, 0x00, 0x00));
909
910 let s = "<b>Bold!</b>";
911 let tree = parse_matrix_html(s);
912 let text = tree.to_text(20, Style::default(), false);
913 assert_eq!(text.lines, vec![Line::from(vec![
914 Span::styled("Bold", bold),
915 Span::styled("!", bold),
916 space_span(15, def)
917 ])]);
918
919 let s = "<strong>Bold!</strong>";
920 let tree = parse_matrix_html(s);
921 let text = tree.to_text(20, Style::default(), false);
922 assert_eq!(text.lines, vec![Line::from(vec![
923 Span::styled("Bold", bold),
924 Span::styled("!", bold),
925 space_span(15, def)
926 ])]);
927
928 let s = "<i>Italic!</i>";
929 let tree = parse_matrix_html(s);
930 let text = tree.to_text(20, Style::default(), false);
931 assert_eq!(text.lines, vec![Line::from(vec![
932 Span::styled("Italic", italic),
933 Span::styled("!", italic),
934 space_span(13, def)
935 ])]);
936
937 let s = "<em>Italic!</em>";
938 let tree = parse_matrix_html(s);
939 let text = tree.to_text(20, Style::default(), false);
940 assert_eq!(text.lines, vec![Line::from(vec![
941 Span::styled("Italic", italic),
942 Span::styled("!", italic),
943 space_span(13, def)
944 ])]);
945
946 let s = "<del>Strikethrough!</del>";
947 let tree = parse_matrix_html(s);
948 let text = tree.to_text(20, Style::default(), false);
949 assert_eq!(text.lines, vec![Line::from(vec![
950 Span::styled("Strikethrough", strike),
951 Span::styled("!", strike),
952 space_span(6, def)
953 ])]);
954
955 let s = "<strike>Strikethrough!</strike>";
956 let tree = parse_matrix_html(s);
957 let text = tree.to_text(20, Style::default(), false);
958 assert_eq!(text.lines, vec![Line::from(vec![
959 Span::styled("Strikethrough", strike),
960 Span::styled("!", strike),
961 space_span(6, def)
962 ])]);
963
964 let s = "<u>Underline!</u>";
965 let tree = parse_matrix_html(s);
966 let text = tree.to_text(20, Style::default(), false);
967 assert_eq!(text.lines, vec![Line::from(vec![
968 Span::styled("Underline", underl),
969 Span::styled("!", underl),
970 space_span(10, def)
971 ])]);
972
973 let s = "<font color=\"#ff0000\">Red!</u>";
974 let tree = parse_matrix_html(s);
975 let text = tree.to_text(20, Style::default(), false);
976 assert_eq!(text.lines, vec![Line::from(vec![
977 Span::styled("Red", red),
978 Span::styled("!", red),
979 space_span(16, def)
980 ])]);
981
982 let s = "<font color=\"red\">Red!</u>";
983 let tree = parse_matrix_html(s);
984 let text = tree.to_text(20, Style::default(), false);
985 assert_eq!(text.lines, vec![Line::from(vec![
986 Span::styled("Red", red),
987 Span::styled("!", red),
988 space_span(16, def)
989 ])]);
990 }
991
992 #[test]
993 fn test_paragraph() {
994 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
995 let tree = parse_matrix_html(s);
996 let text = tree.to_text(10, Style::default(), false);
997 assert_eq!(text.lines.len(), 7);
998 assert_eq!(
999 text.lines[0],
1000 Line::from(vec![Span::raw("Hello"), Span::raw(" "), Span::raw(" ")])
1001 );
1002 assert_eq!(
1003 text.lines[1],
1004 Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
1005 );
1006 assert_eq!(text.lines[2], Line::from(vec![Span::raw(" ")]));
1007 assert_eq!(text.lines[3], Line::from(vec![Span::raw("Content"), Span::raw(" ")]));
1008 assert_eq!(text.lines[4], Line::from(vec![Span::raw(" ")]));
1009 assert_eq!(
1010 text.lines[5],
1011 Line::from(vec![Span::raw("Goodbye"), Span::raw(" "), Span::raw(" ")])
1012 );
1013 assert_eq!(
1014 text.lines[6],
1015 Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
1016 );
1017 }
1018
1019 #[test]
1020 fn test_blockquote() {
1021 let s = "<blockquote>Hello world!</blockquote>";
1022 let tree = parse_matrix_html(s);
1023 let text = tree.to_text(10, Style::default(), false);
1024 assert_eq!(text.lines.len(), 2);
1025 assert_eq!(
1026 text.lines[0],
1027 Line::from(vec![Span::raw(" "), Span::raw("Hello"), Span::raw(" ")])
1028 );
1029 assert_eq!(
1030 text.lines[1],
1031 Line::from(vec![Span::raw(" "), Span::raw("world"), Span::raw("!")])
1032 );
1033 }
1034
1035 #[test]
1036 fn test_list_unordered() {
1037 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
1038 let tree = parse_matrix_html(s);
1039 let text = tree.to_text(8, Style::default(), false);
1040 assert_eq!(text.lines.len(), 6);
1041 assert_eq!(
1042 text.lines[0],
1043 Line::from(vec![
1044 Span::raw("- "),
1045 Span::raw("List"),
1046 Span::raw(" "),
1047 Span::raw(" ")
1048 ])
1049 );
1050 assert_eq!(
1051 text.lines[1],
1052 Line::from(vec![
1053 Span::raw(" "),
1054 Span::raw("Item"),
1055 Span::raw(" "),
1056 Span::raw("1")
1057 ])
1058 );
1059 assert_eq!(
1060 text.lines[2],
1061 Line::from(vec![
1062 Span::raw("- "),
1063 Span::raw("List"),
1064 Span::raw(" "),
1065 Span::raw(" ")
1066 ])
1067 );
1068 assert_eq!(
1069 text.lines[3],
1070 Line::from(vec![
1071 Span::raw(" "),
1072 Span::raw("Item"),
1073 Span::raw(" "),
1074 Span::raw("2")
1075 ])
1076 );
1077 assert_eq!(
1078 text.lines[4],
1079 Line::from(vec![
1080 Span::raw("- "),
1081 Span::raw("List"),
1082 Span::raw(" "),
1083 Span::raw(" ")
1084 ])
1085 );
1086 assert_eq!(
1087 text.lines[5],
1088 Line::from(vec![
1089 Span::raw(" "),
1090 Span::raw("Item"),
1091 Span::raw(" "),
1092 Span::raw("3")
1093 ])
1094 );
1095 }
1096
1097 #[test]
1098 fn test_list_ordered() {
1099 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
1100 let tree = parse_matrix_html(s);
1101 let text = tree.to_text(9, Style::default(), false);
1102 assert_eq!(text.lines.len(), 6);
1103 assert_eq!(
1104 text.lines[0],
1105 Line::from(vec![
1106 Span::raw("1. "),
1107 Span::raw("List"),
1108 Span::raw(" "),
1109 Span::raw(" ")
1110 ])
1111 );
1112 assert_eq!(
1113 text.lines[1],
1114 Line::from(vec![
1115 Span::raw(" "),
1116 Span::raw("Item"),
1117 Span::raw(" "),
1118 Span::raw("1")
1119 ])
1120 );
1121 assert_eq!(
1122 text.lines[2],
1123 Line::from(vec![
1124 Span::raw("2. "),
1125 Span::raw("List"),
1126 Span::raw(" "),
1127 Span::raw(" ")
1128 ])
1129 );
1130 assert_eq!(
1131 text.lines[3],
1132 Line::from(vec![
1133 Span::raw(" "),
1134 Span::raw("Item"),
1135 Span::raw(" "),
1136 Span::raw("2")
1137 ])
1138 );
1139 assert_eq!(
1140 text.lines[4],
1141 Line::from(vec![
1142 Span::raw("3. "),
1143 Span::raw("List"),
1144 Span::raw(" "),
1145 Span::raw(" ")
1146 ])
1147 );
1148 assert_eq!(
1149 text.lines[5],
1150 Line::from(vec![
1151 Span::raw(" "),
1152 Span::raw("Item"),
1153 Span::raw(" "),
1154 Span::raw("3")
1155 ])
1156 );
1157 }
1158
1159 #[test]
1160 fn test_table() {
1161 let s = "<table>\
1162 <thead>\
1163 <tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
1164 </thead>\
1165 <tbody>\
1166 <tr><td>a</td><td>b</td><td>c</td></tr>\
1167 <tr><td>a</td><td>b</td><td>c</td></tr>\
1168 <tr><td>a</td><td>b</td><td>c</td></tr>\
1169 </tbody></table>";
1170 let tree = parse_matrix_html(s);
1171 let text = tree.to_text(15, Style::default(), false);
1172 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1173 assert_eq!(text.lines.len(), 11);
1174
1175 // Table header
1176 assert_eq!(text.lines[0].spans, vec![Span::raw("┌────┬────┬───┐")]);
1177 assert_eq!(text.lines[1].spans, vec![
1178 Span::raw("│"),
1179 Span::styled("Colu", bold),
1180 Span::raw("│"),
1181 Span::styled("Colu", bold),
1182 Span::raw("│"),
1183 Span::styled("Col", bold),
1184 Span::raw("│")
1185 ]);
1186 assert_eq!(text.lines[2].spans, vec![
1187 Span::raw("│"),
1188 Span::styled("mn", bold),
1189 Span::styled(" ", bold),
1190 Span::styled("1", bold),
1191 Span::raw("│"),
1192 Span::styled("mn", bold),
1193 Span::styled(" ", bold),
1194 Span::styled("2", bold),
1195 Span::raw("│"),
1196 Span::styled("umn", bold),
1197 Span::raw("│")
1198 ]);
1199 assert_eq!(text.lines[3].spans, vec![
1200 Span::raw("│"),
1201 Span::raw(" "),
1202 Span::raw("│"),
1203 Span::raw(" "),
1204 Span::raw("│"),
1205 Span::styled("3", bold),
1206 Span::styled(" ", bold),
1207 Span::raw("│")
1208 ]);
1209
1210 // First row
1211 assert_eq!(text.lines[4].spans, vec![Span::raw("├────┼────┼───┤")]);
1212 assert_eq!(text.lines[5].spans, vec![
1213 Span::raw("│"),
1214 Span::raw("a"),
1215 Span::raw(" "),
1216 Span::raw("│"),
1217 Span::raw("b"),
1218 Span::raw(" "),
1219 Span::raw("│"),
1220 Span::raw("c"),
1221 Span::raw(" "),
1222 Span::raw("│")
1223 ]);
1224
1225 // Second row
1226 assert_eq!(text.lines[6].spans, vec![Span::raw("├────┼────┼───┤")]);
1227 assert_eq!(text.lines[7].spans, vec![
1228 Span::raw("│"),
1229 Span::raw("a"),
1230 Span::raw(" "),
1231 Span::raw("│"),
1232 Span::raw("b"),
1233 Span::raw(" "),
1234 Span::raw("│"),
1235 Span::raw("c"),
1236 Span::raw(" "),
1237 Span::raw("│")
1238 ]);
1239
1240 // Third row
1241 assert_eq!(text.lines[8].spans, vec![Span::raw("├────┼────┼───┤")]);
1242 assert_eq!(text.lines[9].spans, vec![
1243 Span::raw("│"),
1244 Span::raw("a"),
1245 Span::raw(" "),
1246 Span::raw("│"),
1247 Span::raw("b"),
1248 Span::raw(" "),
1249 Span::raw("│"),
1250 Span::raw("c"),
1251 Span::raw(" "),
1252 Span::raw("│")
1253 ]);
1254
1255 // Bottom ruler
1256 assert_eq!(text.lines[10].spans, vec![Span::raw("└────┴────┴───┘")]);
1257 }
1258
1259 #[test]
1260 fn test_matrix_reply() {
1261 let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
1262
1263 let tree = parse_matrix_html(s);
1264 let text = tree.to_text(10, Style::default(), false);
1265 assert_eq!(text.lines.len(), 4);
1266 assert_eq!(
1267 text.lines[0],
1268 Line::from(vec![
1269 Span::raw("This"),
1270 Span::raw(" "),
1271 Span::raw("was"),
1272 Span::raw(" "),
1273 Span::raw(" ")
1274 ])
1275 );
1276 assert_eq!(
1277 text.lines[1],
1278 Line::from(vec![Span::raw("replied"), Span::raw(" "), Span::raw("to")])
1279 );
1280 assert_eq!(
1281 text.lines[2],
1282 Line::from(vec![
1283 Span::raw("This"),
1284 Span::raw(" "),
1285 Span::raw("is"),
1286 Span::raw(" "),
1287 Span::raw(" ")
1288 ])
1289 );
1290 assert_eq!(
1291 text.lines[3],
1292 Line::from(vec![
1293 Span::raw("the"),
1294 Span::raw(" "),
1295 Span::raw("reply"),
1296 Span::raw(" ")
1297 ])
1298 );
1299
1300 let tree = parse_matrix_html(s);
1301 let text = tree.to_text(10, Style::default(), true);
1302 assert_eq!(text.lines.len(), 2);
1303 assert_eq!(
1304 text.lines[0],
1305 Line::from(vec![
1306 Span::raw("This"),
1307 Span::raw(" "),
1308 Span::raw("is"),
1309 Span::raw(" "),
1310 Span::raw(" ")
1311 ])
1312 );
1313 assert_eq!(
1314 text.lines[1],
1315 Line::from(vec![
1316 Span::raw("the"),
1317 Span::raw(" "),
1318 Span::raw("reply"),
1319 Span::raw(" ")
1320 ])
1321 );
1322 }
1323
1324 #[test]
1325 fn test_self_closing() {
1326 let s = "Hello<br>World<br>Goodbye";
1327 let tree = parse_matrix_html(s);
1328 let text = tree.to_text(7, Style::default(), true);
1329 assert_eq!(text.lines.len(), 3);
1330 assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),]));
1331 assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),]));
1332 assert_eq!(text.lines[2], Line::from(vec![Span::raw("Goodbye")]),);
1333 }
1334
1335 #[test]
1336 fn test_embedded_newline() {
1337 let s = "<p>Hello\nWorld</p>";
1338 let tree = parse_matrix_html(s);
1339 let text = tree.to_text(15, Style::default(), true);
1340 assert_eq!(text.lines.len(), 1);
1341 assert_eq!(
1342 text.lines[0],
1343 Line::from(vec![
1344 Span::raw("Hello"),
1345 Span::raw(" "),
1346 Span::raw("World"),
1347 Span::raw(" ")
1348 ])
1349 );
1350 }
1351
1352 #[test]
1353 fn test_pre_tag() {
1354 let s = concat!(
1355 "<pre><code class=\"language-rust\">",
1356 "fn hello() -> usize {\n",
1357 " return 5;\n",
1358 "}\n",
1359 "</code></pre>\n"
1360 );
1361 let tree = parse_matrix_html(s);
1362 let text = tree.to_text(25, Style::default(), true);
1363 assert_eq!(text.lines.len(), 5);
1364 assert_eq!(
1365 text.lines[0],
1366 Line::from(vec![
1367 Span::raw(line::TOP_LEFT),
1368 Span::raw(line::HORIZONTAL.repeat(23)),
1369 Span::raw(line::TOP_RIGHT)
1370 ])
1371 );
1372 assert_eq!(
1373 text.lines[1],
1374 Line::from(vec![
1375 Span::raw(line::VERTICAL),
1376 Span::raw("fn"),
1377 Span::raw(" "),
1378 Span::raw("hello"),
1379 Span::raw("("),
1380 Span::raw(")"),
1381 Span::raw(" "),
1382 Span::raw("-"),
1383 Span::raw(">"),
1384 Span::raw(" "),
1385 Span::raw("usize"),
1386 Span::raw(" "),
1387 Span::raw("{"),
1388 Span::raw(" "),
1389 Span::raw(line::VERTICAL)
1390 ])
1391 );
1392 assert_eq!(
1393 text.lines[2],
1394 Line::from(vec![
1395 Span::raw(line::VERTICAL),
1396 Span::raw(" "),
1397 Span::raw("return"),
1398 Span::raw(" "),
1399 Span::raw("5"),
1400 Span::raw(";"),
1401 Span::raw(" "),
1402 Span::raw(line::VERTICAL)
1403 ])
1404 );
1405 assert_eq!(
1406 text.lines[3],
1407 Line::from(vec![
1408 Span::raw(line::VERTICAL),
1409 Span::raw("}"),
1410 Span::raw(" ".repeat(22)),
1411 Span::raw(line::VERTICAL)
1412 ])
1413 );
1414 assert_eq!(
1415 text.lines[4],
1416 Line::from(vec![
1417 Span::raw(line::BOTTOM_LEFT),
1418 Span::raw(line::HORIZONTAL.repeat(23)),
1419 Span::raw(line::BOTTOM_RIGHT)
1420 ])
1421 );
1422 }
1423}