src/message/html.rs
1936 lines · 64941 bytes
77 symbols in this file
BulletIteratorwidthItemnextListStylebulletsStyleTreeChildrenCellTypeTableRowgather_linksimage_previewscolumnsTableSectiongather_linksimage_previewscolumnsTablecolumnsgather_linksimage_previewsto_textThemeSelectorstyleImagenewkindpreviewStyleTreeNodeto_textgather_linksimage_previewsprintStyleTreeget_linksimage_previewsto_textrenderTreeGenStatenext_link_charc2cc2tget_nodeli2ttable_celltable_rowtable_sectiontable_cellstable_rowstable_sectionslic2tattrs_to_startattrs_to_imageattrs_to_hrefattrs_to_languageattrs_to_stylemxid2th2tdom_to_style_treeparse_matrix_htmlteststest_headertest_styletest_paragraphtest_blockquotetest_blockquote_adjacenttest_list_unorderedlist_bulletstest_list_ordered_start_overflowtest_list_ordered_start_near_maxtest_list_orderedtest_tabletest_table_without_cellstest_matrix_reply_strippedtest_self_closingtest_embedded_newlinetest_pre_tagtest_emoji_shortcodes
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 matrix_sdk::ruma::OwnedMxcUri;
22use matrix_sdk::ruma::events::room::ImageInfo;
23
24use crate::message::printer::TextPrinter;
25use crate::message::{ProtocolPreview, placeholder_frame};
26use crate::prelude::*;
27use crate::preview::ImageStatus;
28use crate::util::{join_cell_text, space_text, wrapped_text};
29
30/// Generate bullet points from a [ListStyle].
31pub struct BulletIterator {
32 style: ListStyle,
33 pos: usize,
34 /// The number of characters the number takes up
35 len: usize,
36}
37
38impl BulletIterator {
39 fn width(&self) -> usize {
40 match self.style {
41 ListStyle::Unordered => 2,
42 ListStyle::Ordered(_) => self.len + 2,
43 }
44 }
45}
46
47impl Iterator for BulletIterator {
48 type Item = String;
49
50 fn next(&mut self) -> Option<Self::Item> {
51 let bullet = match self.style {
52 ListStyle::Unordered => "- ".to_string(),
53 ListStyle::Ordered(_) => {
54 let w = self.len;
55 format!("{: >w$}. ", self.pos, w = w)
56 },
57 };
58
59 self.pos += 1;
60
61 return Some(bullet);
62 }
63}
64
65/// Whether this list is ordered or unordered.
66#[derive(Clone, Copy, Debug)]
67pub enum ListStyle {
68 /// The `usize` is the start index.
69 Ordered(usize),
70 Unordered,
71}
72
73impl ListStyle {
74 fn bullets(&self, len: usize) -> BulletIterator {
75 let pos = match self {
76 // Restart at 1 if the last number would not fit in a `usize`.
77 Self::Ordered(start) if start.checked_add(len).is_some() => *start,
78 Self::Ordered(_) => 1,
79 Self::Unordered => 0,
80 };
81
82 let len = (pos + len).to_string().len();
83
84 BulletIterator { style: *self, pos, len }
85 }
86}
87
88pub type StyleTreeChildren = Vec<StyleTreeNode>;
89
90/// Type of contents in a table cell.
91#[derive(Debug, Clone, Copy)]
92pub enum CellType {
93 Data,
94 Header,
95}
96
97/// A collection of cells for a single row in a table.
98#[derive(Debug, Clone)]
99pub struct TableRow {
100 cells: Vec<(CellType, StyleTreeNode)>,
101}
102
103impl TableRow {
104 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
105 for (_, cell) in &self.cells {
106 cell.gather_links(urls);
107 }
108 }
109
110 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
111 for (_, cell) in &self.cells {
112 cell.image_previews(previews);
113 }
114 }
115
116 fn columns(&self) -> usize {
117 self.cells.len()
118 }
119}
120
121/// A collection of rows in a table.
122#[derive(Debug, Clone)]
123pub struct TableSection {
124 rows: Vec<TableRow>,
125}
126
127impl TableSection {
128 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
129 for row in &self.rows {
130 row.gather_links(urls);
131 }
132 }
133
134 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
135 for row in &self.rows {
136 row.image_previews(previews);
137 }
138 }
139
140 fn columns(&self) -> usize {
141 self.rows.iter().map(TableRow::columns).max().unwrap_or(0)
142 }
143}
144
145/// A table.
146#[derive(Debug, Clone)]
147pub struct Table {
148 caption: Option<Box<StyleTreeNode>>,
149 sections: Vec<TableSection>,
150}
151
152impl Table {
153 fn columns(&self) -> usize {
154 self.sections.iter().map(TableSection::columns).max().unwrap_or(0)
155 }
156
157 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
158 for section in &self.sections {
159 section.gather_links(urls);
160 }
161 }
162
163 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
164 for section in &self.sections {
165 section.image_previews(previews);
166 }
167 }
168
169 fn to_text<'a>(&'a self, printer: &TextPrinter<'a>, style: Style) -> Text<'a> {
170 let mut text = Text::default();
171 let columns = self.columns();
172 let cell_total = printer.width().saturating_sub(columns).saturating_sub(1);
173 let cell_min = cell_total.checked_div(columns).unwrap_or(0);
174 let mut cell_slop = cell_total - cell_min * columns;
175 let cell_widths = (0..columns)
176 .map(|_| {
177 let slopped = cell_slop.min(1);
178 cell_slop -= slopped;
179 cell_min + slopped
180 })
181 .collect::<Vec<_>>();
182
183 let mut nrows = 0;
184
185 let line_style = style.patch(printer.settings.theme.messages.table);
186 let line = printer.settings.theme.messages.table_line.to_table_set();
187
188 if let Some(caption) = &self.caption {
189 let mut printer = printer.sub(6).align(Alignment::Center);
190 caption.print(&mut printer, style);
191
192 for mut line in printer.finish().0.lines {
193 line.spans.insert(0, Span::styled(" ", style));
194 line.spans.push(Span::styled(" ", style));
195 text.lines.push(line);
196 }
197 }
198
199 if columns == 0 {
200 // There are no cells to draw a grid around.
201 return text;
202 }
203
204 for section in self.sections.iter() {
205 for row in section.rows.iter() {
206 let mut ruler = String::new();
207
208 for (i, w) in cell_widths.iter().enumerate() {
209 let cross = match (nrows, i) {
210 (0, 0) => line.top_left,
211 (0, _) => line.horizontal_down,
212 (_, 0) => line.vertical_right,
213 (_, _) => line.cross,
214 };
215
216 ruler.push_str(cross);
217
218 for _ in 0..*w {
219 ruler.push_str(line.horizontal);
220 }
221 }
222
223 if nrows == 0 {
224 ruler.push_str(line.top_right);
225 } else {
226 ruler.push_str(line.vertical_left);
227 }
228
229 text.lines.push(Line::from(vec![Span::styled(ruler, line_style)]));
230
231 let cells = cell_widths
232 .iter()
233 .enumerate()
234 .map(|(i, w)| {
235 let text = if let Some((kind, cell)) = row.cells.get(i) {
236 let style = match kind {
237 CellType::Header => style.add_modifier(StyleModifier::BOLD),
238 CellType::Data => style,
239 };
240
241 cell.to_text(*w, style, printer.settings, printer.info)
242 } else {
243 space_text(*w, style)
244 };
245
246 (text, *w)
247 })
248 .collect();
249
250 let joined = join_cell_text(cells, Span::styled(line.vertical, line_style), style);
251 text.lines.extend(joined.lines);
252
253 nrows += 1;
254 }
255 }
256
257 if nrows > 0 {
258 let mut ruler = String::new();
259
260 for (i, w) in cell_widths.iter().enumerate() {
261 let cross = if i == 0 {
262 line.bottom_left
263 } else {
264 line.horizontal_up
265 };
266
267 ruler.push_str(cross);
268
269 for _ in 0..*w {
270 ruler.push_str(line.horizontal);
271 }
272 }
273
274 ruler.push_str(line.bottom_right);
275 text.lines.push(Line::from(vec![Span::styled(ruler, line_style)]));
276 }
277
278 text
279 }
280}
281
282#[derive(Debug, Clone)]
283pub enum ThemeSelector {
284 Strong,
285 Emphasis,
286 Strikethrough,
287 Underlined,
288}
289
290impl ThemeSelector {
291 fn style(&self, settings: &ApplicationSettings) -> Style {
292 match self {
293 Self::Strong => settings.theme.messages.strong,
294 Self::Emphasis => settings.theme.messages.emphasis,
295 Self::Strikethrough => settings.theme.messages.strikethrough,
296 Self::Underlined => settings.theme.messages.underlined,
297 }
298 }
299}
300
301#[derive(Debug, Clone)]
302pub struct Image {
303 title: Option<String>,
304 alt: Option<String>,
305 width: Option<u16>,
306 height: Option<u16>,
307 src: Option<MediaSource>,
308 is_emote: bool,
309}
310
311impl Image {
312 pub fn new(src: MediaSource, info: Option<&ImageInfo>) -> Self {
313 let width = info
314 .and_then(|info| info.width)
315 .and_then(|width| u16::try_from(width).ok());
316 let height = info
317 .and_then(|info| info.height)
318 .and_then(|height| u16::try_from(height).ok());
319
320 Self {
321 src: Some(src),
322 width,
323 height,
324
325 title: None,
326 alt: None,
327 is_emote: false,
328 }
329 }
330
331 fn kind(&self) -> PreviewKind {
332 if self.is_emote {
333 return PreviewKind::Emoji;
334 }
335
336 PreviewKind::Custom(self.width, self.height)
337 }
338
339 fn preview<'a>(&self, previews: &'a PreviewManager) -> Option<&'a ImageStatus> {
340 self.src.as_ref().and_then(|src| previews.get(src, self.kind()))
341 }
342}
343
344/// A processed HTML element that we can render to the terminal.
345#[derive(Debug, Clone)]
346pub enum StyleTreeNode {
347 Anchor(Box<StyleTreeNode>, char, Url),
348 Blockquote(Box<StyleTreeNode>),
349 Break,
350 #[allow(dead_code)]
351 Code(Box<StyleTreeNode>, Option<String>),
352 Header(Box<StyleTreeNode>, usize),
353 Image(Image),
354 List(StyleTreeChildren, ListStyle),
355 Paragraph(Box<StyleTreeNode>),
356 Pre(Box<StyleTreeNode>),
357 Ruler,
358 Themed(Box<StyleTreeNode>, ThemeSelector),
359 Style(Box<StyleTreeNode>, Style),
360 Table(Table),
361 Text(Cow<'static, str>),
362 Sequence(StyleTreeChildren),
363 RoomAlias(OwnedRoomAliasId, Option<char>, Option<OwnedEventId>),
364 RoomId(OwnedRoomId, Vec<OwnedServerName>, Option<char>, Option<OwnedEventId>),
365 UserId(OwnedUserId, Option<char>),
366 DisplayName(String, OwnedUserId, Option<char>),
367}
368
369impl StyleTreeNode {
370 pub fn to_text<'a>(
371 &'a self,
372 width: usize,
373 style: Style,
374 settings: &'a ApplicationSettings,
375 info: &'a RoomInfo,
376 ) -> Text<'a> {
377 let mut printer = TextPrinter::new(width, style, settings, info, None);
378 self.print(&mut printer, style);
379 printer.finish().0
380 }
381
382 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
383 match self {
384 StyleTreeNode::Anchor(_, c, url) => {
385 urls.push((*c, url.clone()));
386 },
387
388 StyleTreeNode::Blockquote(child) |
389 StyleTreeNode::Code(child, _) |
390 StyleTreeNode::Header(child, _) |
391 StyleTreeNode::Paragraph(child) |
392 StyleTreeNode::Pre(child) |
393 StyleTreeNode::Style(child, _) |
394 StyleTreeNode::Themed(child, _) => {
395 child.gather_links(urls);
396 },
397
398 StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => {
399 for child in children {
400 child.gather_links(urls);
401 }
402 },
403
404 StyleTreeNode::Table(table) => {
405 table.gather_links(urls);
406 },
407
408 StyleTreeNode::DisplayName(_, user_id, c) | StyleTreeNode::UserId(user_id, c) => {
409 if let Some(c) = c {
410 let to_url = Url::parse(&user_id.matrix_uri(false).to_string()).unwrap();
411 urls.push((*c, to_url));
412 }
413 },
414 StyleTreeNode::RoomId(room_id, via, c, event_id) => {
415 if let Some(c) = c {
416 let uri = if let Some(ev_id) = event_id {
417 room_id.matrix_event_uri(ev_id.to_owned()).to_string()
418 } else {
419 room_id.matrix_uri_via(via.iter().cloned(), false).to_string()
420 };
421 let to_url = Url::parse(&uri).unwrap();
422 urls.push((*c, to_url));
423 }
424 },
425 StyleTreeNode::RoomAlias(alias, c, event_id) => {
426 if let Some(c) = c {
427 let uri = if let Some(ev_id) = event_id {
428 #[expect(
429 deprecated,
430 reason = "we only use this if we received a deprecated link"
431 )]
432 alias.matrix_event_uri(ev_id.to_owned()).to_string()
433 } else {
434 alias.matrix_uri(false).to_string()
435 };
436 let to_url = Url::parse(&uri).unwrap();
437 urls.push((*c, to_url));
438 }
439 },
440
441 StyleTreeNode::Image(..) => {},
442 StyleTreeNode::Ruler => {},
443 StyleTreeNode::Text(_) => {},
444 StyleTreeNode::Break => {},
445 }
446 }
447
448 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
449 match self {
450 StyleTreeNode::Image(img) => {
451 if let Some(source) = &img.src {
452 previews.push((source, img.kind()));
453 }
454 },
455
456 StyleTreeNode::Blockquote(child) |
457 StyleTreeNode::Code(child, _) |
458 StyleTreeNode::Header(child, _) |
459 StyleTreeNode::Paragraph(child) |
460 StyleTreeNode::Pre(child) |
461 StyleTreeNode::Style(child, _) |
462 StyleTreeNode::Themed(child, _) => {
463 child.image_previews(previews);
464 },
465
466 StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => {
467 for child in children {
468 child.image_previews(previews);
469 }
470 },
471
472 StyleTreeNode::Table(table) => {
473 table.image_previews(previews);
474 },
475
476 StyleTreeNode::Ruler |
477 StyleTreeNode::Text(..) |
478 StyleTreeNode::Break |
479 StyleTreeNode::Anchor(..) |
480 StyleTreeNode::RoomAlias(..) |
481 StyleTreeNode::RoomId(..) |
482 StyleTreeNode::UserId(..) |
483 StyleTreeNode::DisplayName(..) => {},
484 }
485 }
486
487 pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) {
488 let width = printer.width();
489
490 match self {
491 StyleTreeNode::Anchor(child, c, _) => {
492 let bold = style.add_modifier(StyleModifier::BOLD);
493 child.print(printer, bold);
494
495 let link = format!("[{c}]");
496 let span = Span::styled(link, style);
497 printer.push_span_nobreak(span);
498 },
499 StyleTreeNode::Blockquote(child) => {
500 let quote_style = style.patch(printer.settings().theme.messages.blockquote);
501 let quote =
502 printer.settings().theme.messages.blockquote_line.to_table_set().vertical;
503
504 let mut subp = printer.sub(3);
505 child.print(&mut subp, style);
506
507 for mut line in subp.finish().0 {
508 line.spans.insert(0, Span::styled(" ", style));
509 line.spans.insert(0, Span::styled(quote, quote_style));
510 line.spans.insert(0, Span::styled(" ", style));
511 printer.push_line(line);
512 }
513 },
514 StyleTreeNode::Code(child, _) => {
515 let style = style.patch(printer.settings().theme.messages.code);
516
517 let old_style = printer.replace_base_style(style);
518
519 child.print(printer, style);
520
521 printer.replace_base_style(old_style);
522 },
523 StyleTreeNode::Header(child, level) => {
524 let style = style.add_modifier(StyleModifier::BOLD);
525
526 for _ in 0..*level {
527 printer.push_str("#", style);
528 }
529
530 printer.push_str(" ", style);
531 child.print(printer, style);
532 },
533 StyleTreeNode::Image(img @ Image { is_emote: true, .. }) => {
534 if let Some(previews) = printer.previews &&
535 let Some(image) = img.preview(previews) &&
536 let ImageStatus::Loaded(image) = image
537 {
538 printer.push_emoji(image, style);
539 } else {
540 let title = img.title.as_deref().unwrap_or("emote");
541 printer.push_span_nobreak(Span::styled(format!(":{title}:"), style));
542 }
543 },
544 StyleTreeNode::Image(img) => {
545 let alt = img.alt.as_deref().or(img.title.as_deref());
546
547 let mut proto = None;
548 let placeholder = match printer.previews.and_then(|previews| img.preview(previews))
549 {
550 None => {
551 if let Some(alt) = alt {
552 format!("[Image Alt: {alt}]")
553 } else {
554 "[Image]".to_string()
555 }
556 },
557 Some(ImageStatus::Queued(image_preview_size)) => {
558 placeholder_frame(Some("Queued..."), width, image_preview_size)
559 },
560 Some(ImageStatus::Downloading(image_preview_size)) => {
561 placeholder_frame(Some("Downloading..."), width, image_preview_size)
562 },
563 Some(ImageStatus::Loaded(backend)) => {
564 proto = Some(backend);
565 placeholder_frame(None, width, &backend.size())
566 },
567 Some(ImageStatus::Error(err)) => format!("[Image error: {err}]\n"),
568 };
569
570 printer.commit();
571 if let Some(proto) = proto {
572 printer.push_image(proto);
573 }
574 printer.push_text(wrapped_text(placeholder, width, style));
575 printer.commit();
576 },
577 StyleTreeNode::List(children, lt) => {
578 let mut bullets = lt.bullets(children.len());
579 let liw = bullets.width();
580
581 for child in children {
582 let mut subp = printer.sub(liw);
583 let mut bullet = bullets.next();
584 child.print(&mut subp, style);
585
586 for mut line in subp.finish().0 {
587 let leading = if let Some(bullet) = bullet.take() {
588 Span::styled(bullet, style)
589 } else {
590 Span::styled(" ".repeat(liw), style)
591 };
592
593 line.spans.insert(0, leading);
594 printer.push_line(line);
595 }
596 }
597 },
598 StyleTreeNode::Paragraph(child) => {
599 printer.push_break();
600 child.print(printer, style);
601 printer.commit();
602 },
603 StyleTreeNode::Pre(child) => {
604 let mut subp = printer.sub(2).literal(true);
605 let code_style = style.patch(subp.settings().theme.messages.code_block);
606 let _ = subp.replace_base_style(code_style);
607 let subw = subp.width();
608 let border = subp.settings().theme.messages.code_block_line.to_border_set();
609
610 child.print(&mut subp, code_style);
611
612 printer.commit();
613 printer.push_line(
614 vec![
615 Span::styled(border.top_left, style),
616 Span::styled(border.horizontal_top.repeat(subw), style),
617 Span::styled(border.top_right, style),
618 ]
619 .into(),
620 );
621
622 for mut line in subp.finish().0 {
623 line.spans.insert(0, Span::styled(border.vertical_left, style));
624 line.spans.push(Span::styled(border.vertical_right, style));
625 printer.push_line(line);
626 }
627
628 printer.push_line(
629 vec![
630 Span::styled(border.bottom_left, style),
631 Span::styled(border.horizontal_bottom.repeat(subw), style),
632 Span::styled(border.bottom_right, style),
633 ]
634 .into(),
635 );
636
637 printer.commit();
638 },
639 StyleTreeNode::Ruler => {
640 let style = style.patch(printer.settings().theme.messages.ruler);
641 let line = printer.settings().theme.messages.ruler_line.to_table_set().horizontal;
642
643 for _ in 0..width {
644 printer.push_str(line, style);
645 }
646 },
647 StyleTreeNode::Table(table) => {
648 let text = table.to_text(printer, style);
649 printer.push_text(text);
650 },
651 StyleTreeNode::Break => {
652 printer.push_break();
653 },
654 StyleTreeNode::Text(s) => {
655 printer.push_str(s.as_ref(), style);
656 },
657
658 StyleTreeNode::Themed(child, patch) => {
659 let patch = patch.style(printer.settings());
660 child.print(printer, style.patch(patch))
661 },
662 StyleTreeNode::Style(child, patch) => child.print(printer, style.patch(*patch)),
663 StyleTreeNode::Sequence(children) => {
664 let mut after_quote = false;
665
666 for child in children {
667 match child {
668 // Whitespace between elements shouldn't affect spacing.
669 StyleTreeNode::Text(text) if text.trim().is_empty() => {},
670 StyleTreeNode::Blockquote(_) => {
671 if after_quote {
672 // Keep adjacent blockquotes from visually merging.
673 printer.commit();
674 printer.push_break();
675 }
676 after_quote = true;
677 },
678 _ => after_quote = false,
679 }
680
681 child.print(printer, style);
682 }
683 },
684
685 StyleTreeNode::UserId(user_id, _) => {
686 let mut span: Span<'a> = printer
687 .settings()
688 .get_user_span(user_id, printer.info.display_names.get(user_id));
689 let style = style.patch(span.style);
690 span.style = style;
691
692 if !span.content.starts_with('@') {
693 printer.push_str("@", style);
694 }
695 printer.push_span_nobreak(span);
696 },
697 StyleTreeNode::DisplayName(display_name, user_id, _) => {
698 let style = printer.settings().get_user_style(user_id);
699 printer.push_str(display_name.as_str(), style);
700 },
701 StyleTreeNode::RoomId(room_id, _, _, event_id) => {
702 let bold = style.add_modifier(StyleModifier::BOLD);
703 if event_id.is_some() {
704 printer.push_str("Event in ", bold);
705 }
706 printer.push_str(room_id.as_str(), bold);
707 },
708 StyleTreeNode::RoomAlias(alias, _, event_id) => {
709 let bold = style.add_modifier(StyleModifier::BOLD);
710 if event_id.is_some() {
711 printer.push_str("Event in ", bold);
712 }
713 printer.push_str(alias.as_str(), bold);
714 },
715 }
716 }
717}
718
719/// A processed HTML document.
720pub struct StyleTree {
721 pub(super) children: StyleTreeChildren,
722}
723
724impl StyleTree {
725 pub fn get_links(&self) -> Vec<(char, Url)> {
726 let mut links = Vec::new();
727
728 for child in &self.children {
729 child.gather_links(&mut links);
730 }
731
732 return links;
733 }
734
735 pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> {
736 let mut previews = vec![];
737
738 for child in &self.children {
739 child.image_previews(&mut previews);
740 }
741
742 return previews;
743 }
744
745 pub fn to_text<'a>(
746 &'a self,
747 width: usize,
748 style: Style,
749 settings: &'a ApplicationSettings,
750 info: &'a RoomInfo,
751 ) -> Text<'a> {
752 let mut printer = TextPrinter::new(width, style, settings, info, None);
753
754 for child in self.children.iter() {
755 child.print(&mut printer, style);
756 }
757
758 printer.finish().0
759 }
760
761 /// The images are in the format `(protocol, x, y)`
762 pub fn render<'a>(
763 &'a self,
764 width: usize,
765 style: Style,
766 settings: &'a ApplicationSettings,
767 info: &'a RoomInfo,
768 previews: &'a PreviewManager,
769 ) -> (Text<'a>, Vec<ProtocolPreview>) {
770 let mut printer = TextPrinter::new(width, style, settings, info, Some(previews));
771
772 for child in self.children.iter() {
773 child.print(&mut printer, style);
774 }
775
776 printer.finish()
777 }
778}
779
780pub struct TreeGenState {
781 pub link_num: u8,
782}
783
784impl TreeGenState {
785 pub fn next_link_char(&mut self) -> Option<char> {
786 let num = self.link_num;
787
788 if num < 62 {
789 self.link_num = num + 1;
790 }
791
792 if num < 10 {
793 Some((num + b'0') as char)
794 } else if num < 36 {
795 Some((num - 10 + b'a') as char)
796 } else if num < 62 {
797 Some((num - 36 + b'A') as char)
798 } else {
799 None
800 }
801 }
802}
803
804fn c2c(handles: &[Handle], state: &mut TreeGenState) -> Vec<StyleTreeNode> {
805 handles.iter().flat_map(|h| h2t(h, state)).collect()
806}
807
808fn c2t(handles: &[Handle], state: &mut TreeGenState) -> Box<StyleTreeNode> {
809 let node = StyleTreeNode::Sequence(c2c(handles, state));
810
811 Box::new(node)
812}
813
814fn get_node(hdl: &Handle, want: &str, state: &mut TreeGenState) -> Option<StyleTreeNode> {
815 let node = hdl.deref();
816
817 if let NodeData::Element { name, .. } = &node.data {
818 if name.local.as_ref() != want {
819 return None;
820 }
821
822 let c = c2c(&node.children.borrow(), state);
823 return Some(StyleTreeNode::Sequence(c));
824 } else {
825 return None;
826 }
827}
828
829fn li2t(hdl: &Handle, state: &mut TreeGenState) -> Option<StyleTreeNode> {
830 get_node(hdl, "li", state)
831}
832
833fn table_cell(hdl: &Handle, state: &mut TreeGenState) -> Option<(CellType, StyleTreeNode)> {
834 if let Some(node) = get_node(hdl, "th", state) {
835 return Some((CellType::Header, node));
836 }
837
838 Some((CellType::Data, get_node(hdl, "td", state)?))
839}
840
841fn table_row(hdl: &Handle, state: &mut TreeGenState) -> Option<TableRow> {
842 let node = hdl.deref();
843
844 if let NodeData::Element { name, .. } = &node.data {
845 if name.local.as_ref() != "tr" {
846 return None;
847 }
848
849 let cells = table_cells(&node.children.borrow(), state);
850 return Some(TableRow { cells });
851 } else {
852 return None;
853 }
854}
855
856fn table_section(hdl: &Handle, state: &mut TreeGenState) -> Option<TableSection> {
857 let node = hdl.deref();
858
859 if let NodeData::Element { name, .. } = &node.data {
860 match name.local.as_ref() {
861 "thead" | "tbody" => {
862 let rows = table_rows(&node.children.borrow(), state);
863
864 Some(TableSection { rows })
865 },
866 _ => None,
867 }
868 } else {
869 return None;
870 }
871}
872
873fn table_cells(handles: &[Handle], state: &mut TreeGenState) -> Vec<(CellType, StyleTreeNode)> {
874 handles.iter().filter_map(|h| table_cell(h, state)).collect()
875}
876
877fn table_rows(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableRow> {
878 handles.iter().filter_map(|h| table_row(h, state)).collect()
879}
880
881fn table_sections(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableSection> {
882 handles.iter().filter_map(|h| table_section(h, state)).collect()
883}
884
885fn lic2t(handles: &[Handle], state: &mut TreeGenState) -> StyleTreeChildren {
886 handles.iter().filter_map(|h| li2t(h, state)).collect()
887}
888
889fn attrs_to_start(attrs: &[Attribute]) -> Option<usize> {
890 for attr in attrs {
891 if attr.name.local.as_ref() != "start" {
892 continue;
893 }
894
895 if let Ok(start) = usize::from_str(attr.value.as_ref()) {
896 return Some(start);
897 }
898 }
899
900 return None;
901}
902
903fn attrs_to_image(attrs: &[Attribute]) -> Image {
904 let mut title = None;
905 let mut alt = None;
906 let mut width = None;
907 let mut height = None;
908 let mut src = None;
909 let mut is_emote = false;
910
911 for attr in attrs {
912 match attr.name.local.as_ref() {
913 "title" => {
914 title = Some(attr.value.to_string());
915 },
916 "alt" => {
917 alt = Some(attr.value.to_string());
918 },
919 "width" => {
920 if let Ok(val) = u16::from_str(attr.value.as_ref()) {
921 width = Some(val);
922 }
923 },
924 "height" => {
925 if let Ok(val) = u16::from_str(attr.value.as_ref()) {
926 height = Some(val);
927 }
928 },
929 "src" => {
930 let uri = OwnedMxcUri::from(attr.value.to_string());
931
932 if uri.is_valid() {
933 src = Some(uri);
934 }
935 },
936 "data-mx-emoticon" => {
937 is_emote = true;
938 },
939 _ => (),
940 }
941 }
942
943 Image {
944 title,
945 alt,
946 width,
947 height,
948 is_emote,
949 src: src.map(MediaSource::Plain),
950 }
951}
952
953fn attrs_to_href(attrs: &[Attribute]) -> Option<String> {
954 for attr in attrs {
955 if attr.name.local.as_ref() != "href" {
956 continue;
957 }
958
959 return Some(attr.value.to_string());
960 }
961
962 return None;
963}
964
965fn attrs_to_language(attrs: &[Attribute]) -> Option<String> {
966 for attr in attrs {
967 if attr.name.local.as_ref() != "class" {
968 continue;
969 }
970
971 for class in attr.value.as_ref().unicode_words() {
972 if class.len() > 9 && class.starts_with("language-") {
973 return Some(class[9..].to_string());
974 }
975 }
976 }
977
978 return None;
979}
980
981fn attrs_to_style(attrs: &[Attribute]) -> Style {
982 let mut style = Style::default();
983
984 for attr in attrs {
985 match attr.name.local.as_ref() {
986 "data-mx-bg-color" => {
987 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
988 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
989 style = style.bg(color);
990 }
991 },
992 "data-mx-color" | "color" => {
993 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
994 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
995 style = style.fg(color);
996 }
997 },
998 _ => continue,
999 }
1000 }
1001
1002 return style;
1003}
1004
1005fn mxid2t(
1006 id: &MatrixId,
1007 via: &[OwnedServerName],
1008 n: Option<char>,
1009 c: &StyleTreeNode,
1010 h: &Url,
1011) -> StyleTreeNode {
1012 match id {
1013 MatrixId::Room(room_id) => {
1014 StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n, None)
1015 },
1016 MatrixId::RoomAlias(alias) => StyleTreeNode::RoomAlias(alias.to_owned(), n, None),
1017 MatrixId::User(user_id) => StyleTreeNode::UserId(user_id.to_owned(), n),
1018 MatrixId::Event(room_or_alias_id, event_id) => {
1019 let room_or_alias_id: &matrix_sdk::ruma::RoomOrAliasId = room_or_alias_id;
1020 let event_id = Some(event_id.to_owned());
1021
1022 if let Ok(alias_id) = <&matrix_sdk::ruma::RoomAliasId>::try_from(room_or_alias_id) {
1023 StyleTreeNode::RoomAlias(alias_id.to_owned(), n, event_id)
1024 } else {
1025 let room_id = <&matrix_sdk::ruma::RoomId>::try_from(room_or_alias_id).unwrap();
1026 StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n, event_id)
1027 }
1028 },
1029 _ => {
1030 if let Some(n) = n {
1031 StyleTreeNode::Anchor(Box::new(c.to_owned()), n, h.to_owned())
1032 } else {
1033 c.clone()
1034 }
1035 },
1036 }
1037}
1038
1039fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
1040 let node = hdl.deref();
1041
1042 let tree = match &node.data {
1043 NodeData::Document => *c2t(node.children.borrow().as_slice(), state),
1044 NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string().into()),
1045 NodeData::Element { name, attrs, .. } => {
1046 match name.local.as_ref() {
1047 // Links
1048 "a" => {
1049 let c = c2t(&node.children.borrow(), state);
1050 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok());
1051
1052 if let Some(h) = h {
1053 let n = state.next_link_char();
1054
1055 if let Ok(uri) = MatrixToUri::parse(h.as_str()) {
1056 mxid2t(uri.id(), uri.via(), n, &c, &h)
1057 } else if let Ok(uri) = MatrixUri::parse(h.as_str()) {
1058 mxid2t(uri.id(), uri.via(), n, &c, &h)
1059 } else if let Some(n) = n {
1060 StyleTreeNode::Anchor(c, n, h)
1061 } else {
1062 *c
1063 }
1064 } else {
1065 *c
1066 }
1067 },
1068
1069 // Style change
1070 "b" | "strong" => {
1071 let c = c2t(&node.children.borrow(), state);
1072 StyleTreeNode::Themed(c, ThemeSelector::Strong)
1073 },
1074 "font" => {
1075 let c = c2t(&node.children.borrow(), state);
1076 let s = attrs_to_style(&attrs.borrow());
1077
1078 StyleTreeNode::Style(c, s)
1079 },
1080 "em" | "i" => {
1081 let c = c2t(&node.children.borrow(), state);
1082 StyleTreeNode::Themed(c, ThemeSelector::Emphasis)
1083 },
1084 "span" => {
1085 let c = c2t(&node.children.borrow(), state);
1086 let s = attrs_to_style(&attrs.borrow());
1087
1088 StyleTreeNode::Style(c, s)
1089 },
1090 "del" | "s" | "strike" => {
1091 let c = c2t(&node.children.borrow(), state);
1092 StyleTreeNode::Themed(c, ThemeSelector::Strikethrough)
1093 },
1094 "u" => {
1095 let c = c2t(&node.children.borrow(), state);
1096 StyleTreeNode::Themed(c, ThemeSelector::Underlined)
1097 },
1098
1099 // Lists
1100 "ol" => {
1101 StyleTreeNode::List(
1102 lic2t(&node.children.borrow(), state),
1103 ListStyle::Ordered(attrs_to_start(&attrs.borrow()).unwrap_or(1)),
1104 )
1105 },
1106 "ul" => {
1107 StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Unordered)
1108 },
1109
1110 // Headers
1111 "h1" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 1),
1112 "h2" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 2),
1113 "h3" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 3),
1114 "h4" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 4),
1115 "h5" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 5),
1116 "h6" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 6),
1117
1118 // Table
1119 "table" => {
1120 let sections = table_sections(&node.children.borrow(), state);
1121 let caption = node
1122 .children
1123 .borrow()
1124 .iter()
1125 .find_map(|hdl| get_node(hdl, "caption", state))
1126 .map(Box::new);
1127 let table = Table { caption, sections };
1128
1129 StyleTreeNode::Table(table)
1130 },
1131
1132 // Code blocks.
1133 "code" => {
1134 let c = c2t(&node.children.borrow(), state);
1135 let l = attrs_to_language(&attrs.borrow());
1136
1137 StyleTreeNode::Code(c, l)
1138 },
1139
1140 // Other text blocks.
1141 "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow(), state)),
1142 "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow(), state)),
1143 "pre" => StyleTreeNode::Pre(c2t(&node.children.borrow(), state)),
1144
1145 // No children.
1146 "hr" => StyleTreeNode::Ruler,
1147 "br" => StyleTreeNode::Break,
1148
1149 "img" => StyleTreeNode::Image(attrs_to_image(&attrs.borrow())),
1150
1151 // These don't render in any special way.
1152 "details" | "html" | "summary" | "sub" | "sup" => {
1153 *c2t(&node.children.borrow(), state)
1154 },
1155
1156 // This is deprecated and should be stripped if encountered.
1157 "mx-reply" => return vec![],
1158
1159 // Treat unknown tags as plain text.
1160 _ => *c2t(&node.children.borrow(), state),
1161 }
1162 },
1163
1164 // These don't render as anything.
1165 NodeData::Doctype { .. } => return vec![],
1166 NodeData::Comment { .. } => return vec![],
1167 NodeData::ProcessingInstruction { .. } => return vec![],
1168 };
1169
1170 vec![tree]
1171}
1172
1173fn dom_to_style_tree(dom: RcDom) -> StyleTree {
1174 let mut state = TreeGenState { link_num: 0 };
1175 let children = h2t(&dom.document, &mut state);
1176
1177 StyleTree { children }
1178}
1179
1180/// Parse an HTML document from a string.
1181pub fn parse_matrix_html(s: &str) -> StyleTree {
1182 let dom = parse_fragment(
1183 RcDom::default(),
1184 ParseOpts::default(),
1185 QualName::new(None, ns!(html), local_name!("body")),
1186 vec![],
1187 false,
1188 )
1189 .one(StrTendril::from(s));
1190
1191 dom_to_style_tree(dom)
1192}
1193
1194#[cfg(test)]
1195pub mod tests {
1196 use super::*;
1197 use pretty_assertions::assert_eq;
1198 use ratatui::symbols::line;
1199 use unicode_width::UnicodeWidthStr;
1200
1201 use crate::tests::{mock_room, mock_settings};
1202 use crate::util::space_span;
1203
1204 #[test]
1205 fn test_header() {
1206 let info = mock_room();
1207 let settings = mock_settings();
1208 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1209
1210 let s = "<h1>Header 1</h1>";
1211 let tree = parse_matrix_html(s);
1212 let text = tree.to_text(20, Style::default(), &settings, &info);
1213 assert_eq!(text.lines, vec![Line::from(vec![
1214 Span::styled("#", bold),
1215 Span::styled(" ", bold),
1216 Span::styled("Header", bold),
1217 Span::styled(" ", bold),
1218 Span::styled("1", bold),
1219 space_span(10, Style::default())
1220 ])]);
1221
1222 let s = "<h2>Header 2</h2>";
1223 let tree = parse_matrix_html(s);
1224 let text = tree.to_text(20, Style::default(), &settings, &info);
1225 assert_eq!(text.lines, vec![Line::from(vec![
1226 Span::styled("#", bold),
1227 Span::styled("#", bold),
1228 Span::styled(" ", bold),
1229 Span::styled("Header", bold),
1230 Span::styled(" ", bold),
1231 Span::styled("2", bold),
1232 space_span(9, Style::default())
1233 ])]);
1234
1235 let s = "<h3>Header 3</h3>";
1236 let tree = parse_matrix_html(s);
1237 let text = tree.to_text(20, Style::default(), &settings, &info);
1238 assert_eq!(text.lines, vec![Line::from(vec![
1239 Span::styled("#", bold),
1240 Span::styled("#", bold),
1241 Span::styled("#", bold),
1242 Span::styled(" ", bold),
1243 Span::styled("Header", bold),
1244 Span::styled(" ", bold),
1245 Span::styled("3", bold),
1246 space_span(8, Style::default())
1247 ])]);
1248
1249 let s = "<h4>Header 4</h4>";
1250 let tree = parse_matrix_html(s);
1251 let text = tree.to_text(20, Style::default(), &settings, &info);
1252 assert_eq!(text.lines, vec![Line::from(vec![
1253 Span::styled("#", bold),
1254 Span::styled("#", bold),
1255 Span::styled("#", bold),
1256 Span::styled("#", bold),
1257 Span::styled(" ", bold),
1258 Span::styled("Header", bold),
1259 Span::styled(" ", bold),
1260 Span::styled("4", bold),
1261 space_span(7, Style::default())
1262 ])]);
1263
1264 let s = "<h5>Header 5</h5>";
1265 let tree = parse_matrix_html(s);
1266 let text = tree.to_text(20, Style::default(), &settings, &info);
1267 assert_eq!(text.lines, vec![Line::from(vec![
1268 Span::styled("#", bold),
1269 Span::styled("#", bold),
1270 Span::styled("#", bold),
1271 Span::styled("#", bold),
1272 Span::styled("#", bold),
1273 Span::styled(" ", bold),
1274 Span::styled("Header", bold),
1275 Span::styled(" ", bold),
1276 Span::styled("5", bold),
1277 space_span(6, Style::default())
1278 ])]);
1279
1280 let s = "<h6>Header 6</h6>";
1281 let tree = parse_matrix_html(s);
1282 let text = tree.to_text(20, Style::default(), &settings, &info);
1283 assert_eq!(text.lines, vec![Line::from(vec![
1284 Span::styled("#", bold),
1285 Span::styled("#", bold),
1286 Span::styled("#", bold),
1287 Span::styled("#", bold),
1288 Span::styled("#", bold),
1289 Span::styled("#", bold),
1290 Span::styled(" ", bold),
1291 Span::styled("Header", bold),
1292 Span::styled(" ", bold),
1293 Span::styled("6", bold),
1294 space_span(5, Style::default())
1295 ])]);
1296 }
1297
1298 #[test]
1299 fn test_style() {
1300 let info = mock_room();
1301 let settings = mock_settings();
1302 let def = Style::default();
1303 let bold = def.add_modifier(StyleModifier::BOLD);
1304 let italic = def.add_modifier(StyleModifier::ITALIC);
1305 let strike = def.add_modifier(StyleModifier::CROSSED_OUT);
1306 let underl = def.add_modifier(StyleModifier::UNDERLINED);
1307 let red = def.fg(Color::Rgb(0xff, 0x00, 0x00));
1308
1309 let s = "<b>Bold!</b>";
1310 let tree = parse_matrix_html(s);
1311 let text = tree.to_text(20, Style::default(), &settings, &info);
1312 assert_eq!(text.lines, vec![Line::from(vec![
1313 Span::styled("Bold", bold),
1314 Span::styled("!", bold),
1315 space_span(15, def)
1316 ])]);
1317
1318 let s = "<strong>Bold!</strong>";
1319 let tree = parse_matrix_html(s);
1320 let text = tree.to_text(20, Style::default(), &settings, &info);
1321 assert_eq!(text.lines, vec![Line::from(vec![
1322 Span::styled("Bold", bold),
1323 Span::styled("!", bold),
1324 space_span(15, def)
1325 ])]);
1326
1327 let s = "<i>Italic!</i>";
1328 let tree = parse_matrix_html(s);
1329 let text = tree.to_text(20, Style::default(), &settings, &info);
1330 assert_eq!(text.lines, vec![Line::from(vec![
1331 Span::styled("Italic", italic),
1332 Span::styled("!", italic),
1333 space_span(13, def)
1334 ])]);
1335
1336 let s = "<em>Italic!</em>";
1337 let tree = parse_matrix_html(s);
1338 let text = tree.to_text(20, Style::default(), &settings, &info);
1339 assert_eq!(text.lines, vec![Line::from(vec![
1340 Span::styled("Italic", italic),
1341 Span::styled("!", italic),
1342 space_span(13, def)
1343 ])]);
1344
1345 let s = "<del>Strikethrough!</del>";
1346 let tree = parse_matrix_html(s);
1347 let text = tree.to_text(20, Style::default(), &settings, &info);
1348 assert_eq!(text.lines, vec![Line::from(vec![
1349 Span::styled("Strikethrough", strike),
1350 Span::styled("!", strike),
1351 space_span(6, def)
1352 ])]);
1353
1354 let s = "<strike>Strikethrough!</strike>";
1355 let tree = parse_matrix_html(s);
1356 let text = tree.to_text(20, Style::default(), &settings, &info);
1357 assert_eq!(text.lines, vec![Line::from(vec![
1358 Span::styled("Strikethrough", strike),
1359 Span::styled("!", strike),
1360 space_span(6, def)
1361 ])]);
1362
1363 let s = "<u>Underline!</u>";
1364 let tree = parse_matrix_html(s);
1365 let text = tree.to_text(20, Style::default(), &settings, &info);
1366 assert_eq!(text.lines, vec![Line::from(vec![
1367 Span::styled("Underline", underl),
1368 Span::styled("!", underl),
1369 space_span(10, def)
1370 ])]);
1371
1372 let s = "<font color=\"#ff0000\">Red!</u>";
1373 let tree = parse_matrix_html(s);
1374 let text = tree.to_text(20, Style::default(), &settings, &info);
1375 assert_eq!(text.lines, vec![Line::from(vec![
1376 Span::styled("Red", red),
1377 Span::styled("!", red),
1378 space_span(16, def)
1379 ])]);
1380
1381 let s = "<font color=\"red\">Red!</u>";
1382 let tree = parse_matrix_html(s);
1383 let text = tree.to_text(20, Style::default(), &settings, &info);
1384 assert_eq!(text.lines, vec![Line::from(vec![
1385 Span::styled("Red", red),
1386 Span::styled("!", red),
1387 space_span(16, def)
1388 ])]);
1389 }
1390
1391 #[test]
1392 fn test_paragraph() {
1393 let info = mock_room();
1394 let settings = mock_settings();
1395 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
1396 let tree = parse_matrix_html(s);
1397 let text = tree.to_text(10, Style::default(), &settings, &info);
1398 assert_eq!(text.lines.len(), 7);
1399 assert_eq!(
1400 text.lines[0],
1401 Line::from(vec![Span::raw("Hello"), Span::raw(" "), Span::raw(" ")])
1402 );
1403 assert_eq!(
1404 text.lines[1],
1405 Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
1406 );
1407 assert_eq!(text.lines[2], Line::from(vec![Span::raw(" ")]));
1408 assert_eq!(text.lines[3], Line::from(vec![Span::raw("Content"), Span::raw(" ")]));
1409 assert_eq!(text.lines[4], Line::from(vec![Span::raw(" ")]));
1410 assert_eq!(
1411 text.lines[5],
1412 Line::from(vec![Span::raw("Goodbye"), Span::raw(" "), Span::raw(" ")])
1413 );
1414 assert_eq!(
1415 text.lines[6],
1416 Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
1417 );
1418 }
1419
1420 #[test]
1421 fn test_blockquote() {
1422 let info = mock_room();
1423 let settings = mock_settings();
1424 let s = "<blockquote>Hello world!</blockquote>";
1425 let tree = parse_matrix_html(s);
1426 let text = tree.to_text(10, Style::default(), &settings, &info);
1427 let style = Style::new().fg(Color::Cyan);
1428 assert_eq!(text.lines.len(), 2);
1429 assert_eq!(
1430 text.lines[0],
1431 Line::from(vec![
1432 Span::raw(" "),
1433 Span::styled(line::THICK_VERTICAL, style),
1434 Span::raw(" "),
1435 Span::raw("Hello"),
1436 Span::raw(" "),
1437 Span::raw(" "),
1438 ])
1439 );
1440 assert_eq!(
1441 text.lines[1],
1442 Line::from(vec![
1443 Span::raw(" "),
1444 Span::styled(line::THICK_VERTICAL, style),
1445 Span::raw(" "),
1446 Span::raw("world"),
1447 Span::raw("!"),
1448 Span::raw(" "),
1449 ])
1450 );
1451 }
1452
1453 #[test]
1454 fn test_blockquote_adjacent() {
1455 let info = mock_room();
1456 let settings = mock_settings();
1457 let s = "<blockquote>\n<p>One</p>\n</blockquote>\n<blockquote>\n<p>Two</p>\n</blockquote>";
1458 let tree = parse_matrix_html(s);
1459 let text = tree.to_text(10, Style::default(), &settings, &info);
1460 let style = Style::new().fg(Color::Cyan);
1461 let quoted = |word: &'static str, pad: &'static str| {
1462 Line::from(vec![
1463 Span::raw(" "),
1464 Span::styled(line::THICK_VERTICAL, style),
1465 Span::raw(" "),
1466 Span::raw(word),
1467 Span::raw(pad),
1468 ])
1469 };
1470 assert_eq!(text.lines.len(), 3);
1471 assert_eq!(text.lines[0], quoted("One", " "));
1472 assert_eq!(text.lines[1], Line::from(vec![Span::raw(" ".repeat(10))]));
1473 assert_eq!(text.lines[2], quoted("Two", " "));
1474 }
1475
1476 #[test]
1477 fn test_list_unordered() {
1478 let info = mock_room();
1479 let settings = mock_settings();
1480 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
1481 let tree = parse_matrix_html(s);
1482 let text = tree.to_text(8, Style::default(), &settings, &info);
1483 assert_eq!(text.lines.len(), 6);
1484 assert_eq!(
1485 text.lines[0],
1486 Line::from(vec![
1487 Span::raw("- "),
1488 Span::raw("List"),
1489 Span::raw(" "),
1490 Span::raw(" ")
1491 ])
1492 );
1493 assert_eq!(
1494 text.lines[1],
1495 Line::from(vec![
1496 Span::raw(" "),
1497 Span::raw("Item"),
1498 Span::raw(" "),
1499 Span::raw("1")
1500 ])
1501 );
1502 assert_eq!(
1503 text.lines[2],
1504 Line::from(vec![
1505 Span::raw("- "),
1506 Span::raw("List"),
1507 Span::raw(" "),
1508 Span::raw(" ")
1509 ])
1510 );
1511 assert_eq!(
1512 text.lines[3],
1513 Line::from(vec![
1514 Span::raw(" "),
1515 Span::raw("Item"),
1516 Span::raw(" "),
1517 Span::raw("2")
1518 ])
1519 );
1520 assert_eq!(
1521 text.lines[4],
1522 Line::from(vec![
1523 Span::raw("- "),
1524 Span::raw("List"),
1525 Span::raw(" "),
1526 Span::raw(" ")
1527 ])
1528 );
1529 assert_eq!(
1530 text.lines[5],
1531 Line::from(vec![
1532 Span::raw(" "),
1533 Span::raw("Item"),
1534 Span::raw(" "),
1535 Span::raw("3")
1536 ])
1537 );
1538 }
1539
1540 fn list_bullets(start: usize) -> Vec<Option<String>> {
1541 let info = mock_room();
1542 let settings = mock_settings();
1543 let s = format!("<ol start=\"{start}\"><li>a</li><li>b</li></ol>");
1544 let tree = parse_matrix_html(&s);
1545 let text = tree.to_text(40, Style::default(), &settings, &info);
1546 assert_eq!(text.lines.len(), 2);
1547
1548 text.lines
1549 .iter()
1550 .map(|line| line.spans.first().map(|span| span.content.to_string()))
1551 .collect()
1552 }
1553
1554 #[test]
1555 fn test_list_ordered_start_overflow() {
1556 // Numbering that would overflow a `usize` restarts at 1.
1557 for start in [usize::MAX, usize::MAX - 1] {
1558 assert_eq!(list_bullets(start), vec![Some("1. ".to_string()), Some("2. ".to_string())]);
1559 }
1560 }
1561
1562 #[test]
1563 fn test_list_ordered_start_near_max() {
1564 // The largest start for which the numbering still fits is left alone.
1565 let start = usize::MAX - 2;
1566 assert_eq!(list_bullets(start), vec![
1567 Some(format!("{}. ", start)),
1568 Some(format!("{}. ", start + 1))
1569 ]);
1570 }
1571
1572 #[test]
1573 fn test_list_ordered() {
1574 let info = mock_room();
1575 let settings = mock_settings();
1576 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
1577 let tree = parse_matrix_html(s);
1578 let text = tree.to_text(9, Style::default(), &settings, &info);
1579 assert_eq!(text.lines.len(), 6);
1580 assert_eq!(
1581 text.lines[0],
1582 Line::from(vec![
1583 Span::raw("1. "),
1584 Span::raw("List"),
1585 Span::raw(" "),
1586 Span::raw(" ")
1587 ])
1588 );
1589 assert_eq!(
1590 text.lines[1],
1591 Line::from(vec![
1592 Span::raw(" "),
1593 Span::raw("Item"),
1594 Span::raw(" "),
1595 Span::raw("1")
1596 ])
1597 );
1598 assert_eq!(
1599 text.lines[2],
1600 Line::from(vec![
1601 Span::raw("2. "),
1602 Span::raw("List"),
1603 Span::raw(" "),
1604 Span::raw(" ")
1605 ])
1606 );
1607 assert_eq!(
1608 text.lines[3],
1609 Line::from(vec![
1610 Span::raw(" "),
1611 Span::raw("Item"),
1612 Span::raw(" "),
1613 Span::raw("2")
1614 ])
1615 );
1616 assert_eq!(
1617 text.lines[4],
1618 Line::from(vec![
1619 Span::raw("3. "),
1620 Span::raw("List"),
1621 Span::raw(" "),
1622 Span::raw(" ")
1623 ])
1624 );
1625 assert_eq!(
1626 text.lines[5],
1627 Line::from(vec![
1628 Span::raw(" "),
1629 Span::raw("Item"),
1630 Span::raw(" "),
1631 Span::raw("3")
1632 ])
1633 );
1634 }
1635
1636 #[test]
1637 fn test_table() {
1638 let info = mock_room();
1639 let settings = mock_settings();
1640 let s = "<table>\
1641 <thead>\
1642 <tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
1643 </thead>\
1644 <tbody>\
1645 <tr><td>a</td><td>b</td><td>c</td></tr>\
1646 <tr><td>a</td><td>b</td><td>c</td></tr>\
1647 <tr><td>a</td><td>b</td><td>c</td></tr>\
1648 </tbody></table>";
1649 let tree = parse_matrix_html(s);
1650 let text = tree.to_text(15, Style::default(), &settings, &info);
1651 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1652 assert_eq!(text.lines.len(), 11);
1653
1654 // Table header
1655 assert_eq!(text.lines[0].spans, vec![Span::raw("┌────┬────┬───┐")]);
1656 assert_eq!(text.lines[1].spans, vec![
1657 Span::raw("│"),
1658 Span::styled("Colu", bold),
1659 Span::raw("│"),
1660 Span::styled("Colu", bold),
1661 Span::raw("│"),
1662 Span::styled("Col", bold),
1663 Span::raw("│")
1664 ]);
1665 assert_eq!(text.lines[2].spans, vec![
1666 Span::raw("│"),
1667 Span::styled("mn", bold),
1668 Span::styled(" ", bold),
1669 Span::styled("1", bold),
1670 Span::raw("│"),
1671 Span::styled("mn", bold),
1672 Span::styled(" ", bold),
1673 Span::styled("2", bold),
1674 Span::raw("│"),
1675 Span::styled("umn", bold),
1676 Span::raw("│")
1677 ]);
1678 assert_eq!(text.lines[3].spans, vec![
1679 Span::raw("│"),
1680 Span::raw(" "),
1681 Span::raw("│"),
1682 Span::raw(" "),
1683 Span::raw("│"),
1684 Span::styled("3", bold),
1685 Span::styled(" ", bold),
1686 Span::raw("│")
1687 ]);
1688
1689 // First row
1690 assert_eq!(text.lines[4].spans, vec![Span::raw("├────┼────┼───┤")]);
1691 assert_eq!(text.lines[5].spans, vec![
1692 Span::raw("│"),
1693 Span::raw("a"),
1694 Span::raw(" "),
1695 Span::raw("│"),
1696 Span::raw("b"),
1697 Span::raw(" "),
1698 Span::raw("│"),
1699 Span::raw("c"),
1700 Span::raw(" "),
1701 Span::raw("│")
1702 ]);
1703
1704 // Second row
1705 assert_eq!(text.lines[6].spans, vec![Span::raw("├────┼────┼───┤")]);
1706 assert_eq!(text.lines[7].spans, vec![
1707 Span::raw("│"),
1708 Span::raw("a"),
1709 Span::raw(" "),
1710 Span::raw("│"),
1711 Span::raw("b"),
1712 Span::raw(" "),
1713 Span::raw("│"),
1714 Span::raw("c"),
1715 Span::raw(" "),
1716 Span::raw("│")
1717 ]);
1718
1719 // Third row
1720 assert_eq!(text.lines[8].spans, vec![Span::raw("├────┼────┼───┤")]);
1721 assert_eq!(text.lines[9].spans, vec![
1722 Span::raw("│"),
1723 Span::raw("a"),
1724 Span::raw(" "),
1725 Span::raw("│"),
1726 Span::raw("b"),
1727 Span::raw(" "),
1728 Span::raw("│"),
1729 Span::raw("c"),
1730 Span::raw(" "),
1731 Span::raw("│")
1732 ]);
1733
1734 // Bottom ruler
1735 assert_eq!(text.lines[10].spans, vec![Span::raw("└────┴────┴───┘")]);
1736 }
1737
1738 #[test]
1739 fn test_table_without_cells() {
1740 let info = mock_room();
1741 let settings = mock_settings();
1742
1743 for s in ["<table></table>", "<table><tbody><tr></tr></tbody></table>"] {
1744 let tree = parse_matrix_html(s);
1745 let text = tree.to_text(15, Style::default(), &settings, &info);
1746 assert!(text.lines.is_empty());
1747 }
1748
1749 let s = "<table><caption>Title</caption></table>";
1750 let tree = parse_matrix_html(s);
1751 let text = tree.to_text(15, Style::default(), &settings, &info);
1752 assert_eq!(text.lines.len(), 1);
1753 }
1754
1755 #[test]
1756 fn test_matrix_reply_stripped() {
1757 let info = mock_room();
1758 let settings = mock_settings();
1759 let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
1760
1761 let tree = parse_matrix_html(s);
1762 let text = tree.to_text(10, Style::default(), &settings, &info);
1763 assert_eq!(text.lines.len(), 2);
1764 assert_eq!(
1765 text.lines[0],
1766 Line::from(vec![
1767 Span::raw("This"),
1768 Span::raw(" "),
1769 Span::raw("is"),
1770 Span::raw(" "),
1771 Span::raw(" ")
1772 ])
1773 );
1774 assert_eq!(
1775 text.lines[1],
1776 Line::from(vec![
1777 Span::raw("the"),
1778 Span::raw(" "),
1779 Span::raw("reply"),
1780 Span::raw(" ")
1781 ])
1782 );
1783 }
1784
1785 #[test]
1786 fn test_self_closing() {
1787 let info = mock_room();
1788 let settings = mock_settings();
1789 let s = "Hello<br>World<br>Goodbye";
1790 let tree = parse_matrix_html(s);
1791 let text = tree.to_text(7, Style::default(), &settings, &info);
1792 assert_eq!(text.lines.len(), 3);
1793 assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),]));
1794 assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),]));
1795 assert_eq!(text.lines[2], Line::from(vec![Span::raw("Goodbye")]),);
1796 }
1797
1798 #[test]
1799 fn test_embedded_newline() {
1800 let info = mock_room();
1801 let settings = mock_settings();
1802 let s = "<p>Hello\nWorld</p>";
1803 let tree = parse_matrix_html(s);
1804 let text = tree.to_text(15, Style::default(), &settings, &info);
1805 assert_eq!(text.lines.len(), 1);
1806 assert_eq!(
1807 text.lines[0],
1808 Line::from(vec![
1809 Span::raw("Hello"),
1810 Span::raw(" "),
1811 Span::raw("World"),
1812 Span::raw(" ")
1813 ])
1814 );
1815 }
1816
1817 #[test]
1818 fn test_pre_tag() {
1819 let info = mock_room();
1820 let settings = mock_settings();
1821 let code_style = settings.theme.messages.code_block;
1822 let s = concat!(
1823 "<pre><code class=\"language-rust\">",
1824 "fn hello() -> usize {\n",
1825 " \t// weired\n",
1826 " return 5;\n",
1827 "}\n",
1828 "</code></pre>\n"
1829 );
1830 let tree = parse_matrix_html(s);
1831 let text = tree.to_text(25, Style::default(), &settings, &info);
1832 assert_eq!(text.lines.len(), 6);
1833 assert_eq!(
1834 text.lines[0],
1835 Line::from(vec![
1836 Span::raw(line::TOP_LEFT),
1837 Span::raw(line::HORIZONTAL.repeat(23)),
1838 Span::raw(line::TOP_RIGHT)
1839 ])
1840 );
1841 assert_eq!(
1842 text.lines[1],
1843 Line::from(vec![
1844 Span::raw(line::VERTICAL),
1845 Span::styled("fn", code_style),
1846 Span::styled(" ", code_style),
1847 Span::styled("hello", code_style),
1848 Span::styled("(", code_style),
1849 Span::styled(")", code_style),
1850 Span::styled(" ", code_style),
1851 Span::styled("-", code_style),
1852 Span::styled(">", code_style),
1853 Span::styled(" ", code_style),
1854 Span::styled("usize", code_style),
1855 Span::styled(" ", code_style),
1856 Span::styled("{", code_style),
1857 Span::styled(" ", code_style),
1858 Span::raw(line::VERTICAL)
1859 ])
1860 );
1861 assert_eq!(
1862 text.lines[2],
1863 Line::from(vec![
1864 Span::raw(line::VERTICAL),
1865 Span::styled(" ", code_style),
1866 Span::styled(" ", code_style),
1867 Span::styled("/", code_style),
1868 Span::styled("/", code_style),
1869 Span::styled(" ", code_style),
1870 Span::styled("weired", code_style),
1871 Span::styled(" ", code_style),
1872 Span::raw(line::VERTICAL)
1873 ])
1874 );
1875 assert_eq!(
1876 text.lines[3],
1877 Line::from(vec![
1878 Span::raw(line::VERTICAL),
1879 Span::styled(" ", code_style),
1880 Span::styled("return", code_style),
1881 Span::styled(" ", code_style),
1882 Span::styled("5", code_style),
1883 Span::styled(";", code_style),
1884 Span::styled(" ", code_style),
1885 Span::raw(line::VERTICAL)
1886 ])
1887 );
1888 assert_eq!(
1889 text.lines[4],
1890 Line::from(vec![
1891 Span::raw(line::VERTICAL),
1892 Span::styled("}", code_style),
1893 Span::styled(" ".repeat(22), code_style),
1894 Span::raw(line::VERTICAL)
1895 ])
1896 );
1897 assert_eq!(
1898 text.lines[5],
1899 Line::from(vec![
1900 Span::raw(line::BOTTOM_LEFT),
1901 Span::raw(line::HORIZONTAL.repeat(23)),
1902 Span::raw(line::BOTTOM_RIGHT)
1903 ])
1904 );
1905 }
1906
1907 #[test]
1908 fn test_emoji_shortcodes() {
1909 let info = mock_room();
1910 let mut enabled = mock_settings();
1911 enabled.tunables.message_shortcode_display = true;
1912 let mut disabled = mock_settings();
1913 disabled.tunables.message_shortcode_display = false;
1914
1915 for shortcode in ["exploding_head", "polar_bear", "canada"] {
1916 let emoji = emojis::get_by_shortcode(shortcode).unwrap().as_str();
1917 let emoji_width = UnicodeWidthStr::width(emoji);
1918 let replacement = format!(":{shortcode}:");
1919 let replacement_width = UnicodeWidthStr::width(replacement.as_str());
1920 let s = format!("<p>{emoji}</p>");
1921 let tree = parse_matrix_html(s.as_str());
1922 // Test with emojis_shortcodes set to false
1923 let text = tree.to_text(20, Style::default(), &disabled, &info);
1924 assert_eq!(text.lines, vec![Line::from(vec![
1925 Span::raw(emoji),
1926 space_span(20 - emoji_width, Style::default()),
1927 ]),]);
1928 // Test with emojis_shortcodes set to true
1929 let text = tree.to_text(20, Style::default(), &enabled, &info);
1930 assert_eq!(text.lines, vec![Line::from(vec![
1931 Span::raw(replacement.as_str()),
1932 space_span(20 - replacement_width, Style::default()),
1933 ])]);
1934 }
1935 }
1936}