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