src/message/html.rs
1937 lines · 64958 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 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.
720#[derive(Clone)]
721pub struct StyleTree {
722 pub(super) children: StyleTreeChildren,
723}
724
725impl StyleTree {
726 pub fn get_links(&self) -> Vec<(char, Url)> {
727 let mut links = Vec::new();
728
729 for child in &self.children {
730 child.gather_links(&mut links);
731 }
732
733 return links;
734 }
735
736 pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> {
737 let mut previews = vec![];
738
739 for child in &self.children {
740 child.image_previews(&mut previews);
741 }
742
743 return previews;
744 }
745
746 pub fn to_text<'a>(
747 &'a self,
748 width: usize,
749 style: Style,
750 settings: &'a ApplicationSettings,
751 info: &'a RoomInfo,
752 ) -> Text<'a> {
753 let mut printer = TextPrinter::new(width, style, settings, info, None);
754
755 for child in self.children.iter() {
756 child.print(&mut printer, style);
757 }
758
759 printer.finish().0
760 }
761
762 /// The images are in the format `(protocol, x, y)`
763 pub fn render<'a>(
764 &'a self,
765 width: usize,
766 style: Style,
767 settings: &'a ApplicationSettings,
768 info: &'a RoomInfo,
769 previews: &'a PreviewManager,
770 ) -> (Text<'a>, Vec<ProtocolPreview>) {
771 let mut printer = TextPrinter::new(width, style, settings, info, Some(previews));
772
773 for child in self.children.iter() {
774 child.print(&mut printer, style);
775 }
776
777 printer.finish()
778 }
779}
780
781pub struct TreeGenState {
782 pub link_num: u8,
783}
784
785impl TreeGenState {
786 pub fn next_link_char(&mut self) -> Option<char> {
787 let num = self.link_num;
788
789 if num < 62 {
790 self.link_num = num + 1;
791 }
792
793 if num < 10 {
794 Some((num + b'0') as char)
795 } else if num < 36 {
796 Some((num - 10 + b'a') as char)
797 } else if num < 62 {
798 Some((num - 36 + b'A') as char)
799 } else {
800 None
801 }
802 }
803}
804
805fn c2c(handles: &[Handle], state: &mut TreeGenState) -> Vec<StyleTreeNode> {
806 handles.iter().flat_map(|h| h2t(h, state)).collect()
807}
808
809fn c2t(handles: &[Handle], state: &mut TreeGenState) -> Box<StyleTreeNode> {
810 let node = StyleTreeNode::Sequence(c2c(handles, state));
811
812 Box::new(node)
813}
814
815fn get_node(hdl: &Handle, want: &str, state: &mut TreeGenState) -> Option<StyleTreeNode> {
816 let node = hdl.deref();
817
818 if let NodeData::Element { name, .. } = &node.data {
819 if name.local.as_ref() != want {
820 return None;
821 }
822
823 let c = c2c(&node.children.borrow(), state);
824 return Some(StyleTreeNode::Sequence(c));
825 } else {
826 return None;
827 }
828}
829
830fn li2t(hdl: &Handle, state: &mut TreeGenState) -> Option<StyleTreeNode> {
831 get_node(hdl, "li", state)
832}
833
834fn table_cell(hdl: &Handle, state: &mut TreeGenState) -> Option<(CellType, StyleTreeNode)> {
835 if let Some(node) = get_node(hdl, "th", state) {
836 return Some((CellType::Header, node));
837 }
838
839 Some((CellType::Data, get_node(hdl, "td", state)?))
840}
841
842fn table_row(hdl: &Handle, state: &mut TreeGenState) -> Option<TableRow> {
843 let node = hdl.deref();
844
845 if let NodeData::Element { name, .. } = &node.data {
846 if name.local.as_ref() != "tr" {
847 return None;
848 }
849
850 let cells = table_cells(&node.children.borrow(), state);
851 return Some(TableRow { cells });
852 } else {
853 return None;
854 }
855}
856
857fn table_section(hdl: &Handle, state: &mut TreeGenState) -> Option<TableSection> {
858 let node = hdl.deref();
859
860 if let NodeData::Element { name, .. } = &node.data {
861 match name.local.as_ref() {
862 "thead" | "tbody" => {
863 let rows = table_rows(&node.children.borrow(), state);
864
865 Some(TableSection { rows })
866 },
867 _ => None,
868 }
869 } else {
870 return None;
871 }
872}
873
874fn table_cells(handles: &[Handle], state: &mut TreeGenState) -> Vec<(CellType, StyleTreeNode)> {
875 handles.iter().filter_map(|h| table_cell(h, state)).collect()
876}
877
878fn table_rows(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableRow> {
879 handles.iter().filter_map(|h| table_row(h, state)).collect()
880}
881
882fn table_sections(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableSection> {
883 handles.iter().filter_map(|h| table_section(h, state)).collect()
884}
885
886fn lic2t(handles: &[Handle], state: &mut TreeGenState) -> StyleTreeChildren {
887 handles.iter().filter_map(|h| li2t(h, state)).collect()
888}
889
890fn attrs_to_start(attrs: &[Attribute]) -> Option<usize> {
891 for attr in attrs {
892 if attr.name.local.as_ref() != "start" {
893 continue;
894 }
895
896 if let Ok(start) = usize::from_str(attr.value.as_ref()) {
897 return Some(start);
898 }
899 }
900
901 return None;
902}
903
904fn attrs_to_image(attrs: &[Attribute]) -> Image {
905 let mut title = None;
906 let mut alt = None;
907 let mut width = None;
908 let mut height = None;
909 let mut src = None;
910 let mut is_emote = false;
911
912 for attr in attrs {
913 match attr.name.local.as_ref() {
914 "title" => {
915 title = Some(attr.value.to_string());
916 },
917 "alt" => {
918 alt = Some(attr.value.to_string());
919 },
920 "width" => {
921 if let Ok(val) = u16::from_str(attr.value.as_ref()) {
922 width = Some(val);
923 }
924 },
925 "height" => {
926 if let Ok(val) = u16::from_str(attr.value.as_ref()) {
927 height = Some(val);
928 }
929 },
930 "src" => {
931 let uri = OwnedMxcUri::from(attr.value.to_string());
932
933 if uri.is_valid() {
934 src = Some(uri);
935 }
936 },
937 "data-mx-emoticon" => {
938 is_emote = true;
939 },
940 _ => (),
941 }
942 }
943
944 Image {
945 title,
946 alt,
947 width,
948 height,
949 is_emote,
950 src: src.map(MediaSource::Plain),
951 }
952}
953
954fn attrs_to_href(attrs: &[Attribute]) -> Option<String> {
955 for attr in attrs {
956 if attr.name.local.as_ref() != "href" {
957 continue;
958 }
959
960 return Some(attr.value.to_string());
961 }
962
963 return None;
964}
965
966fn attrs_to_language(attrs: &[Attribute]) -> Option<String> {
967 for attr in attrs {
968 if attr.name.local.as_ref() != "class" {
969 continue;
970 }
971
972 for class in attr.value.as_ref().unicode_words() {
973 if class.len() > 9 && class.starts_with("language-") {
974 return Some(class[9..].to_string());
975 }
976 }
977 }
978
979 return None;
980}
981
982fn attrs_to_style(attrs: &[Attribute]) -> Style {
983 let mut style = Style::default();
984
985 for attr in attrs {
986 match attr.name.local.as_ref() {
987 "data-mx-bg-color" => {
988 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
989 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
990 style = style.bg(color);
991 }
992 },
993 "data-mx-color" | "color" => {
994 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
995 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
996 style = style.fg(color);
997 }
998 },
999 _ => continue,
1000 }
1001 }
1002
1003 return style;
1004}
1005
1006fn mxid2t(
1007 id: &MatrixId,
1008 via: &[OwnedServerName],
1009 n: Option<char>,
1010 c: &StyleTreeNode,
1011 h: &Url,
1012) -> StyleTreeNode {
1013 match id {
1014 MatrixId::Room(room_id) => {
1015 StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n, None)
1016 },
1017 MatrixId::RoomAlias(alias) => StyleTreeNode::RoomAlias(alias.to_owned(), n, None),
1018 MatrixId::User(user_id) => StyleTreeNode::UserId(user_id.to_owned(), n),
1019 MatrixId::Event(room_or_alias_id, event_id) => {
1020 let room_or_alias_id: &matrix_sdk::ruma::RoomOrAliasId = room_or_alias_id;
1021 let event_id = Some(event_id.to_owned());
1022
1023 if let Ok(alias_id) = <&matrix_sdk::ruma::RoomAliasId>::try_from(room_or_alias_id) {
1024 StyleTreeNode::RoomAlias(alias_id.to_owned(), n, event_id)
1025 } else {
1026 let room_id = <&matrix_sdk::ruma::RoomId>::try_from(room_or_alias_id).unwrap();
1027 StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n, event_id)
1028 }
1029 },
1030 _ => {
1031 if let Some(n) = n {
1032 StyleTreeNode::Anchor(Box::new(c.to_owned()), n, h.to_owned())
1033 } else {
1034 c.clone()
1035 }
1036 },
1037 }
1038}
1039
1040fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
1041 let node = hdl.deref();
1042
1043 let tree = match &node.data {
1044 NodeData::Document => *c2t(node.children.borrow().as_slice(), state),
1045 NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string().into()),
1046 NodeData::Element { name, attrs, .. } => {
1047 match name.local.as_ref() {
1048 // Links
1049 "a" => {
1050 let c = c2t(&node.children.borrow(), state);
1051 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok());
1052
1053 if let Some(h) = h {
1054 let n = state.next_link_char();
1055
1056 if let Ok(uri) = MatrixToUri::parse(h.as_str()) {
1057 mxid2t(uri.id(), uri.via(), n, &c, &h)
1058 } else if let Ok(uri) = MatrixUri::parse(h.as_str()) {
1059 mxid2t(uri.id(), uri.via(), n, &c, &h)
1060 } else if let Some(n) = n {
1061 StyleTreeNode::Anchor(c, n, h)
1062 } else {
1063 *c
1064 }
1065 } else {
1066 *c
1067 }
1068 },
1069
1070 // Style change
1071 "b" | "strong" => {
1072 let c = c2t(&node.children.borrow(), state);
1073 StyleTreeNode::Themed(c, ThemeSelector::Strong)
1074 },
1075 "font" => {
1076 let c = c2t(&node.children.borrow(), state);
1077 let s = attrs_to_style(&attrs.borrow());
1078
1079 StyleTreeNode::Style(c, s)
1080 },
1081 "em" | "i" => {
1082 let c = c2t(&node.children.borrow(), state);
1083 StyleTreeNode::Themed(c, ThemeSelector::Emphasis)
1084 },
1085 "span" => {
1086 let c = c2t(&node.children.borrow(), state);
1087 let s = attrs_to_style(&attrs.borrow());
1088
1089 StyleTreeNode::Style(c, s)
1090 },
1091 "del" | "s" | "strike" => {
1092 let c = c2t(&node.children.borrow(), state);
1093 StyleTreeNode::Themed(c, ThemeSelector::Strikethrough)
1094 },
1095 "u" => {
1096 let c = c2t(&node.children.borrow(), state);
1097 StyleTreeNode::Themed(c, ThemeSelector::Underlined)
1098 },
1099
1100 // Lists
1101 "ol" => {
1102 StyleTreeNode::List(
1103 lic2t(&node.children.borrow(), state),
1104 ListStyle::Ordered(attrs_to_start(&attrs.borrow()).unwrap_or(1)),
1105 )
1106 },
1107 "ul" => {
1108 StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Unordered)
1109 },
1110
1111 // Headers
1112 "h1" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 1),
1113 "h2" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 2),
1114 "h3" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 3),
1115 "h4" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 4),
1116 "h5" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 5),
1117 "h6" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 6),
1118
1119 // Table
1120 "table" => {
1121 let sections = table_sections(&node.children.borrow(), state);
1122 let caption = node
1123 .children
1124 .borrow()
1125 .iter()
1126 .find_map(|hdl| get_node(hdl, "caption", state))
1127 .map(Box::new);
1128 let table = Table { caption, sections };
1129
1130 StyleTreeNode::Table(table)
1131 },
1132
1133 // Code blocks.
1134 "code" => {
1135 let c = c2t(&node.children.borrow(), state);
1136 let l = attrs_to_language(&attrs.borrow());
1137
1138 StyleTreeNode::Code(c, l)
1139 },
1140
1141 // Other text blocks.
1142 "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow(), state)),
1143 "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow(), state)),
1144 "pre" => StyleTreeNode::Pre(c2t(&node.children.borrow(), state)),
1145
1146 // No children.
1147 "hr" => StyleTreeNode::Ruler,
1148 "br" => StyleTreeNode::Break,
1149
1150 "img" => StyleTreeNode::Image(attrs_to_image(&attrs.borrow())),
1151
1152 // These don't render in any special way.
1153 "details" | "html" | "summary" | "sub" | "sup" => {
1154 *c2t(&node.children.borrow(), state)
1155 },
1156
1157 // This is deprecated and should be stripped if encountered.
1158 "mx-reply" => return vec![],
1159
1160 // Treat unknown tags as plain text.
1161 _ => *c2t(&node.children.borrow(), state),
1162 }
1163 },
1164
1165 // These don't render as anything.
1166 NodeData::Doctype { .. } => return vec![],
1167 NodeData::Comment { .. } => return vec![],
1168 NodeData::ProcessingInstruction { .. } => return vec![],
1169 };
1170
1171 vec![tree]
1172}
1173
1174fn dom_to_style_tree(dom: RcDom) -> StyleTree {
1175 let mut state = TreeGenState { link_num: 0 };
1176 let children = h2t(&dom.document, &mut state);
1177
1178 StyleTree { children }
1179}
1180
1181/// Parse an HTML document from a string.
1182pub fn parse_matrix_html(s: &str) -> StyleTree {
1183 let dom = parse_fragment(
1184 RcDom::default(),
1185 ParseOpts::default(),
1186 QualName::new(None, ns!(html), local_name!("body")),
1187 vec![],
1188 false,
1189 )
1190 .one(StrTendril::from(s));
1191
1192 dom_to_style_tree(dom)
1193}
1194
1195#[cfg(test)]
1196pub mod tests {
1197 use super::*;
1198 use pretty_assertions::assert_eq;
1199 use ratatui::symbols::line;
1200 use unicode_width::UnicodeWidthStr;
1201
1202 use crate::tests::{mock_room, mock_settings};
1203 use crate::util::space_span;
1204
1205 #[test]
1206 fn test_header() {
1207 let info = mock_room();
1208 let settings = mock_settings();
1209 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1210
1211 let s = "<h1>Header 1</h1>";
1212 let tree = parse_matrix_html(s);
1213 let text = tree.to_text(20, Style::default(), &settings, &info);
1214 assert_eq!(text.lines, vec![Line::from(vec![
1215 Span::styled("#", bold),
1216 Span::styled(" ", bold),
1217 Span::styled("Header", bold),
1218 Span::styled(" ", bold),
1219 Span::styled("1", bold),
1220 space_span(10, Style::default())
1221 ])]);
1222
1223 let s = "<h2>Header 2</h2>";
1224 let tree = parse_matrix_html(s);
1225 let text = tree.to_text(20, Style::default(), &settings, &info);
1226 assert_eq!(text.lines, vec![Line::from(vec![
1227 Span::styled("#", bold),
1228 Span::styled("#", bold),
1229 Span::styled(" ", bold),
1230 Span::styled("Header", bold),
1231 Span::styled(" ", bold),
1232 Span::styled("2", bold),
1233 space_span(9, Style::default())
1234 ])]);
1235
1236 let s = "<h3>Header 3</h3>";
1237 let tree = parse_matrix_html(s);
1238 let text = tree.to_text(20, Style::default(), &settings, &info);
1239 assert_eq!(text.lines, vec![Line::from(vec![
1240 Span::styled("#", bold),
1241 Span::styled("#", bold),
1242 Span::styled("#", bold),
1243 Span::styled(" ", bold),
1244 Span::styled("Header", bold),
1245 Span::styled(" ", bold),
1246 Span::styled("3", bold),
1247 space_span(8, Style::default())
1248 ])]);
1249
1250 let s = "<h4>Header 4</h4>";
1251 let tree = parse_matrix_html(s);
1252 let text = tree.to_text(20, Style::default(), &settings, &info);
1253 assert_eq!(text.lines, vec![Line::from(vec![
1254 Span::styled("#", bold),
1255 Span::styled("#", bold),
1256 Span::styled("#", bold),
1257 Span::styled("#", bold),
1258 Span::styled(" ", bold),
1259 Span::styled("Header", bold),
1260 Span::styled(" ", bold),
1261 Span::styled("4", bold),
1262 space_span(7, Style::default())
1263 ])]);
1264
1265 let s = "<h5>Header 5</h5>";
1266 let tree = parse_matrix_html(s);
1267 let text = tree.to_text(20, Style::default(), &settings, &info);
1268 assert_eq!(text.lines, vec![Line::from(vec![
1269 Span::styled("#", bold),
1270 Span::styled("#", bold),
1271 Span::styled("#", bold),
1272 Span::styled("#", bold),
1273 Span::styled("#", bold),
1274 Span::styled(" ", bold),
1275 Span::styled("Header", bold),
1276 Span::styled(" ", bold),
1277 Span::styled("5", bold),
1278 space_span(6, Style::default())
1279 ])]);
1280
1281 let s = "<h6>Header 6</h6>";
1282 let tree = parse_matrix_html(s);
1283 let text = tree.to_text(20, Style::default(), &settings, &info);
1284 assert_eq!(text.lines, vec![Line::from(vec![
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(" ", bold),
1292 Span::styled("Header", bold),
1293 Span::styled(" ", bold),
1294 Span::styled("6", bold),
1295 space_span(5, Style::default())
1296 ])]);
1297 }
1298
1299 #[test]
1300 fn test_style() {
1301 let info = mock_room();
1302 let settings = mock_settings();
1303 let def = Style::default();
1304 let bold = def.add_modifier(StyleModifier::BOLD);
1305 let italic = def.add_modifier(StyleModifier::ITALIC);
1306 let strike = def.add_modifier(StyleModifier::CROSSED_OUT);
1307 let underl = def.add_modifier(StyleModifier::UNDERLINED);
1308 let red = def.fg(Color::Rgb(0xff, 0x00, 0x00));
1309
1310 let s = "<b>Bold!</b>";
1311 let tree = parse_matrix_html(s);
1312 let text = tree.to_text(20, Style::default(), &settings, &info);
1313 assert_eq!(text.lines, vec![Line::from(vec![
1314 Span::styled("Bold", bold),
1315 Span::styled("!", bold),
1316 space_span(15, def)
1317 ])]);
1318
1319 let s = "<strong>Bold!</strong>";
1320 let tree = parse_matrix_html(s);
1321 let text = tree.to_text(20, Style::default(), &settings, &info);
1322 assert_eq!(text.lines, vec![Line::from(vec![
1323 Span::styled("Bold", bold),
1324 Span::styled("!", bold),
1325 space_span(15, def)
1326 ])]);
1327
1328 let s = "<i>Italic!</i>";
1329 let tree = parse_matrix_html(s);
1330 let text = tree.to_text(20, Style::default(), &settings, &info);
1331 assert_eq!(text.lines, vec![Line::from(vec![
1332 Span::styled("Italic", italic),
1333 Span::styled("!", italic),
1334 space_span(13, def)
1335 ])]);
1336
1337 let s = "<em>Italic!</em>";
1338 let tree = parse_matrix_html(s);
1339 let text = tree.to_text(20, Style::default(), &settings, &info);
1340 assert_eq!(text.lines, vec![Line::from(vec![
1341 Span::styled("Italic", italic),
1342 Span::styled("!", italic),
1343 space_span(13, def)
1344 ])]);
1345
1346 let s = "<del>Strikethrough!</del>";
1347 let tree = parse_matrix_html(s);
1348 let text = tree.to_text(20, Style::default(), &settings, &info);
1349 assert_eq!(text.lines, vec![Line::from(vec![
1350 Span::styled("Strikethrough", strike),
1351 Span::styled("!", strike),
1352 space_span(6, def)
1353 ])]);
1354
1355 let s = "<strike>Strikethrough!</strike>";
1356 let tree = parse_matrix_html(s);
1357 let text = tree.to_text(20, Style::default(), &settings, &info);
1358 assert_eq!(text.lines, vec![Line::from(vec![
1359 Span::styled("Strikethrough", strike),
1360 Span::styled("!", strike),
1361 space_span(6, def)
1362 ])]);
1363
1364 let s = "<u>Underline!</u>";
1365 let tree = parse_matrix_html(s);
1366 let text = tree.to_text(20, Style::default(), &settings, &info);
1367 assert_eq!(text.lines, vec![Line::from(vec![
1368 Span::styled("Underline", underl),
1369 Span::styled("!", underl),
1370 space_span(10, def)
1371 ])]);
1372
1373 let s = "<font color=\"#ff0000\">Red!</u>";
1374 let tree = parse_matrix_html(s);
1375 let text = tree.to_text(20, Style::default(), &settings, &info);
1376 assert_eq!(text.lines, vec![Line::from(vec![
1377 Span::styled("Red", red),
1378 Span::styled("!", red),
1379 space_span(16, def)
1380 ])]);
1381
1382 let s = "<font color=\"red\">Red!</u>";
1383 let tree = parse_matrix_html(s);
1384 let text = tree.to_text(20, Style::default(), &settings, &info);
1385 assert_eq!(text.lines, vec![Line::from(vec![
1386 Span::styled("Red", red),
1387 Span::styled("!", red),
1388 space_span(16, def)
1389 ])]);
1390 }
1391
1392 #[test]
1393 fn test_paragraph() {
1394 let info = mock_room();
1395 let settings = mock_settings();
1396 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
1397 let tree = parse_matrix_html(s);
1398 let text = tree.to_text(10, Style::default(), &settings, &info);
1399 assert_eq!(text.lines.len(), 7);
1400 assert_eq!(
1401 text.lines[0],
1402 Line::from(vec![Span::raw("Hello"), Span::raw(" "), Span::raw(" ")])
1403 );
1404 assert_eq!(
1405 text.lines[1],
1406 Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
1407 );
1408 assert_eq!(text.lines[2], Line::from(vec![Span::raw(" ")]));
1409 assert_eq!(text.lines[3], Line::from(vec![Span::raw("Content"), Span::raw(" ")]));
1410 assert_eq!(text.lines[4], Line::from(vec![Span::raw(" ")]));
1411 assert_eq!(
1412 text.lines[5],
1413 Line::from(vec![Span::raw("Goodbye"), Span::raw(" "), Span::raw(" ")])
1414 );
1415 assert_eq!(
1416 text.lines[6],
1417 Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
1418 );
1419 }
1420
1421 #[test]
1422 fn test_blockquote() {
1423 let info = mock_room();
1424 let settings = mock_settings();
1425 let s = "<blockquote>Hello world!</blockquote>";
1426 let tree = parse_matrix_html(s);
1427 let text = tree.to_text(10, Style::default(), &settings, &info);
1428 let style = Style::new().fg(Color::Cyan);
1429 assert_eq!(text.lines.len(), 2);
1430 assert_eq!(
1431 text.lines[0],
1432 Line::from(vec![
1433 Span::raw(" "),
1434 Span::styled(line::THICK_VERTICAL, style),
1435 Span::raw(" "),
1436 Span::raw("Hello"),
1437 Span::raw(" "),
1438 Span::raw(" "),
1439 ])
1440 );
1441 assert_eq!(
1442 text.lines[1],
1443 Line::from(vec![
1444 Span::raw(" "),
1445 Span::styled(line::THICK_VERTICAL, style),
1446 Span::raw(" "),
1447 Span::raw("world"),
1448 Span::raw("!"),
1449 Span::raw(" "),
1450 ])
1451 );
1452 }
1453
1454 #[test]
1455 fn test_blockquote_adjacent() {
1456 let info = mock_room();
1457 let settings = mock_settings();
1458 let s = "<blockquote>\n<p>One</p>\n</blockquote>\n<blockquote>\n<p>Two</p>\n</blockquote>";
1459 let tree = parse_matrix_html(s);
1460 let text = tree.to_text(10, Style::default(), &settings, &info);
1461 let style = Style::new().fg(Color::Cyan);
1462 let quoted = |word: &'static str, pad: &'static str| {
1463 Line::from(vec![
1464 Span::raw(" "),
1465 Span::styled(line::THICK_VERTICAL, style),
1466 Span::raw(" "),
1467 Span::raw(word),
1468 Span::raw(pad),
1469 ])
1470 };
1471 assert_eq!(text.lines.len(), 3);
1472 assert_eq!(text.lines[0], quoted("One", " "));
1473 assert_eq!(text.lines[1], Line::from(vec![Span::raw(" ".repeat(10))]));
1474 assert_eq!(text.lines[2], quoted("Two", " "));
1475 }
1476
1477 #[test]
1478 fn test_list_unordered() {
1479 let info = mock_room();
1480 let settings = mock_settings();
1481 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
1482 let tree = parse_matrix_html(s);
1483 let text = tree.to_text(8, Style::default(), &settings, &info);
1484 assert_eq!(text.lines.len(), 6);
1485 assert_eq!(
1486 text.lines[0],
1487 Line::from(vec![
1488 Span::raw("- "),
1489 Span::raw("List"),
1490 Span::raw(" "),
1491 Span::raw(" ")
1492 ])
1493 );
1494 assert_eq!(
1495 text.lines[1],
1496 Line::from(vec![
1497 Span::raw(" "),
1498 Span::raw("Item"),
1499 Span::raw(" "),
1500 Span::raw("1")
1501 ])
1502 );
1503 assert_eq!(
1504 text.lines[2],
1505 Line::from(vec![
1506 Span::raw("- "),
1507 Span::raw("List"),
1508 Span::raw(" "),
1509 Span::raw(" ")
1510 ])
1511 );
1512 assert_eq!(
1513 text.lines[3],
1514 Line::from(vec![
1515 Span::raw(" "),
1516 Span::raw("Item"),
1517 Span::raw(" "),
1518 Span::raw("2")
1519 ])
1520 );
1521 assert_eq!(
1522 text.lines[4],
1523 Line::from(vec![
1524 Span::raw("- "),
1525 Span::raw("List"),
1526 Span::raw(" "),
1527 Span::raw(" ")
1528 ])
1529 );
1530 assert_eq!(
1531 text.lines[5],
1532 Line::from(vec![
1533 Span::raw(" "),
1534 Span::raw("Item"),
1535 Span::raw(" "),
1536 Span::raw("3")
1537 ])
1538 );
1539 }
1540
1541 fn list_bullets(start: usize) -> Vec<Option<String>> {
1542 let info = mock_room();
1543 let settings = mock_settings();
1544 let s = format!("<ol start=\"{start}\"><li>a</li><li>b</li></ol>");
1545 let tree = parse_matrix_html(&s);
1546 let text = tree.to_text(40, Style::default(), &settings, &info);
1547 assert_eq!(text.lines.len(), 2);
1548
1549 text.lines
1550 .iter()
1551 .map(|line| line.spans.first().map(|span| span.content.to_string()))
1552 .collect()
1553 }
1554
1555 #[test]
1556 fn test_list_ordered_start_overflow() {
1557 // Numbering that would overflow a `usize` restarts at 1.
1558 for start in [usize::MAX, usize::MAX - 1] {
1559 assert_eq!(list_bullets(start), vec![Some("1. ".to_string()), Some("2. ".to_string())]);
1560 }
1561 }
1562
1563 #[test]
1564 fn test_list_ordered_start_near_max() {
1565 // The largest start for which the numbering still fits is left alone.
1566 let start = usize::MAX - 2;
1567 assert_eq!(list_bullets(start), vec![
1568 Some(format!("{}. ", start)),
1569 Some(format!("{}. ", start + 1))
1570 ]);
1571 }
1572
1573 #[test]
1574 fn test_list_ordered() {
1575 let info = mock_room();
1576 let settings = mock_settings();
1577 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
1578 let tree = parse_matrix_html(s);
1579 let text = tree.to_text(9, Style::default(), &settings, &info);
1580 assert_eq!(text.lines.len(), 6);
1581 assert_eq!(
1582 text.lines[0],
1583 Line::from(vec![
1584 Span::raw("1. "),
1585 Span::raw("List"),
1586 Span::raw(" "),
1587 Span::raw(" ")
1588 ])
1589 );
1590 assert_eq!(
1591 text.lines[1],
1592 Line::from(vec![
1593 Span::raw(" "),
1594 Span::raw("Item"),
1595 Span::raw(" "),
1596 Span::raw("1")
1597 ])
1598 );
1599 assert_eq!(
1600 text.lines[2],
1601 Line::from(vec![
1602 Span::raw("2. "),
1603 Span::raw("List"),
1604 Span::raw(" "),
1605 Span::raw(" ")
1606 ])
1607 );
1608 assert_eq!(
1609 text.lines[3],
1610 Line::from(vec![
1611 Span::raw(" "),
1612 Span::raw("Item"),
1613 Span::raw(" "),
1614 Span::raw("2")
1615 ])
1616 );
1617 assert_eq!(
1618 text.lines[4],
1619 Line::from(vec![
1620 Span::raw("3. "),
1621 Span::raw("List"),
1622 Span::raw(" "),
1623 Span::raw(" ")
1624 ])
1625 );
1626 assert_eq!(
1627 text.lines[5],
1628 Line::from(vec![
1629 Span::raw(" "),
1630 Span::raw("Item"),
1631 Span::raw(" "),
1632 Span::raw("3")
1633 ])
1634 );
1635 }
1636
1637 #[test]
1638 fn test_table() {
1639 let info = mock_room();
1640 let settings = mock_settings();
1641 let s = "<table>\
1642 <thead>\
1643 <tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
1644 </thead>\
1645 <tbody>\
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 <tr><td>a</td><td>b</td><td>c</td></tr>\
1649 </tbody></table>";
1650 let tree = parse_matrix_html(s);
1651 let text = tree.to_text(15, Style::default(), &settings, &info);
1652 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1653 assert_eq!(text.lines.len(), 11);
1654
1655 // Table header
1656 assert_eq!(text.lines[0].spans, vec![Span::raw("┌────┬────┬───┐")]);
1657 assert_eq!(text.lines[1].spans, vec![
1658 Span::raw("│"),
1659 Span::styled("Colu", bold),
1660 Span::raw("│"),
1661 Span::styled("Colu", bold),
1662 Span::raw("│"),
1663 Span::styled("Col", bold),
1664 Span::raw("│")
1665 ]);
1666 assert_eq!(text.lines[2].spans, vec![
1667 Span::raw("│"),
1668 Span::styled("mn", bold),
1669 Span::styled(" ", bold),
1670 Span::styled("1", bold),
1671 Span::raw("│"),
1672 Span::styled("mn", bold),
1673 Span::styled(" ", bold),
1674 Span::styled("2", bold),
1675 Span::raw("│"),
1676 Span::styled("umn", bold),
1677 Span::raw("│")
1678 ]);
1679 assert_eq!(text.lines[3].spans, vec![
1680 Span::raw("│"),
1681 Span::raw(" "),
1682 Span::raw("│"),
1683 Span::raw(" "),
1684 Span::raw("│"),
1685 Span::styled("3", bold),
1686 Span::styled(" ", bold),
1687 Span::raw("│")
1688 ]);
1689
1690 // First row
1691 assert_eq!(text.lines[4].spans, vec![Span::raw("├────┼────┼───┤")]);
1692 assert_eq!(text.lines[5].spans, vec![
1693 Span::raw("│"),
1694 Span::raw("a"),
1695 Span::raw(" "),
1696 Span::raw("│"),
1697 Span::raw("b"),
1698 Span::raw(" "),
1699 Span::raw("│"),
1700 Span::raw("c"),
1701 Span::raw(" "),
1702 Span::raw("│")
1703 ]);
1704
1705 // Second row
1706 assert_eq!(text.lines[6].spans, vec![Span::raw("├────┼────┼───┤")]);
1707 assert_eq!(text.lines[7].spans, vec![
1708 Span::raw("│"),
1709 Span::raw("a"),
1710 Span::raw(" "),
1711 Span::raw("│"),
1712 Span::raw("b"),
1713 Span::raw(" "),
1714 Span::raw("│"),
1715 Span::raw("c"),
1716 Span::raw(" "),
1717 Span::raw("│")
1718 ]);
1719
1720 // Third row
1721 assert_eq!(text.lines[8].spans, vec![Span::raw("├────┼────┼───┤")]);
1722 assert_eq!(text.lines[9].spans, vec![
1723 Span::raw("│"),
1724 Span::raw("a"),
1725 Span::raw(" "),
1726 Span::raw("│"),
1727 Span::raw("b"),
1728 Span::raw(" "),
1729 Span::raw("│"),
1730 Span::raw("c"),
1731 Span::raw(" "),
1732 Span::raw("│")
1733 ]);
1734
1735 // Bottom ruler
1736 assert_eq!(text.lines[10].spans, vec![Span::raw("└────┴────┴───┘")]);
1737 }
1738
1739 #[test]
1740 fn test_table_without_cells() {
1741 let info = mock_room();
1742 let settings = mock_settings();
1743
1744 for s in ["<table></table>", "<table><tbody><tr></tr></tbody></table>"] {
1745 let tree = parse_matrix_html(s);
1746 let text = tree.to_text(15, Style::default(), &settings, &info);
1747 assert!(text.lines.is_empty());
1748 }
1749
1750 let s = "<table><caption>Title</caption></table>";
1751 let tree = parse_matrix_html(s);
1752 let text = tree.to_text(15, Style::default(), &settings, &info);
1753 assert_eq!(text.lines.len(), 1);
1754 }
1755
1756 #[test]
1757 fn test_matrix_reply_stripped() {
1758 let info = mock_room();
1759 let settings = mock_settings();
1760 let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
1761
1762 let tree = parse_matrix_html(s);
1763 let text = tree.to_text(10, Style::default(), &settings, &info);
1764 assert_eq!(text.lines.len(), 2);
1765 assert_eq!(
1766 text.lines[0],
1767 Line::from(vec![
1768 Span::raw("This"),
1769 Span::raw(" "),
1770 Span::raw("is"),
1771 Span::raw(" "),
1772 Span::raw(" ")
1773 ])
1774 );
1775 assert_eq!(
1776 text.lines[1],
1777 Line::from(vec![
1778 Span::raw("the"),
1779 Span::raw(" "),
1780 Span::raw("reply"),
1781 Span::raw(" ")
1782 ])
1783 );
1784 }
1785
1786 #[test]
1787 fn test_self_closing() {
1788 let info = mock_room();
1789 let settings = mock_settings();
1790 let s = "Hello<br>World<br>Goodbye";
1791 let tree = parse_matrix_html(s);
1792 let text = tree.to_text(7, Style::default(), &settings, &info);
1793 assert_eq!(text.lines.len(), 3);
1794 assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),]));
1795 assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),]));
1796 assert_eq!(text.lines[2], Line::from(vec![Span::raw("Goodbye")]),);
1797 }
1798
1799 #[test]
1800 fn test_embedded_newline() {
1801 let info = mock_room();
1802 let settings = mock_settings();
1803 let s = "<p>Hello\nWorld</p>";
1804 let tree = parse_matrix_html(s);
1805 let text = tree.to_text(15, Style::default(), &settings, &info);
1806 assert_eq!(text.lines.len(), 1);
1807 assert_eq!(
1808 text.lines[0],
1809 Line::from(vec![
1810 Span::raw("Hello"),
1811 Span::raw(" "),
1812 Span::raw("World"),
1813 Span::raw(" ")
1814 ])
1815 );
1816 }
1817
1818 #[test]
1819 fn test_pre_tag() {
1820 let info = mock_room();
1821 let settings = mock_settings();
1822 let code_style = settings.theme.messages.code_block;
1823 let s = concat!(
1824 "<pre><code class=\"language-rust\">",
1825 "fn hello() -> usize {\n",
1826 " \t// weired\n",
1827 " return 5;\n",
1828 "}\n",
1829 "</code></pre>\n"
1830 );
1831 let tree = parse_matrix_html(s);
1832 let text = tree.to_text(25, Style::default(), &settings, &info);
1833 assert_eq!(text.lines.len(), 6);
1834 assert_eq!(
1835 text.lines[0],
1836 Line::from(vec![
1837 Span::raw(line::TOP_LEFT),
1838 Span::raw(line::HORIZONTAL.repeat(23)),
1839 Span::raw(line::TOP_RIGHT)
1840 ])
1841 );
1842 assert_eq!(
1843 text.lines[1],
1844 Line::from(vec![
1845 Span::raw(line::VERTICAL),
1846 Span::styled("fn", code_style),
1847 Span::styled(" ", code_style),
1848 Span::styled("hello", 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(" ", code_style),
1855 Span::styled("usize", code_style),
1856 Span::styled(" ", code_style),
1857 Span::styled("{", code_style),
1858 Span::styled(" ", code_style),
1859 Span::raw(line::VERTICAL)
1860 ])
1861 );
1862 assert_eq!(
1863 text.lines[2],
1864 Line::from(vec![
1865 Span::raw(line::VERTICAL),
1866 Span::styled(" ", code_style),
1867 Span::styled(" ", code_style),
1868 Span::styled("/", code_style),
1869 Span::styled("/", code_style),
1870 Span::styled(" ", code_style),
1871 Span::styled("weired", code_style),
1872 Span::styled(" ", code_style),
1873 Span::raw(line::VERTICAL)
1874 ])
1875 );
1876 assert_eq!(
1877 text.lines[3],
1878 Line::from(vec![
1879 Span::raw(line::VERTICAL),
1880 Span::styled(" ", code_style),
1881 Span::styled("return", code_style),
1882 Span::styled(" ", code_style),
1883 Span::styled("5", code_style),
1884 Span::styled(";", code_style),
1885 Span::styled(" ", code_style),
1886 Span::raw(line::VERTICAL)
1887 ])
1888 );
1889 assert_eq!(
1890 text.lines[4],
1891 Line::from(vec![
1892 Span::raw(line::VERTICAL),
1893 Span::styled("}", code_style),
1894 Span::styled(" ".repeat(22), code_style),
1895 Span::raw(line::VERTICAL)
1896 ])
1897 );
1898 assert_eq!(
1899 text.lines[5],
1900 Line::from(vec![
1901 Span::raw(line::BOTTOM_LEFT),
1902 Span::raw(line::HORIZONTAL.repeat(23)),
1903 Span::raw(line::BOTTOM_RIGHT)
1904 ])
1905 );
1906 }
1907
1908 #[test]
1909 fn test_emoji_shortcodes() {
1910 let info = mock_room();
1911 let mut enabled = mock_settings();
1912 enabled.tunables.message_shortcode_display = true;
1913 let mut disabled = mock_settings();
1914 disabled.tunables.message_shortcode_display = false;
1915
1916 for shortcode in ["exploding_head", "polar_bear", "canada"] {
1917 let emoji = emojis::get_by_shortcode(shortcode).unwrap().as_str();
1918 let emoji_width = UnicodeWidthStr::width(emoji);
1919 let replacement = format!(":{shortcode}:");
1920 let replacement_width = UnicodeWidthStr::width(replacement.as_str());
1921 let s = format!("<p>{emoji}</p>");
1922 let tree = parse_matrix_html(s.as_str());
1923 // Test with emojis_shortcodes set to false
1924 let text = tree.to_text(20, Style::default(), &disabled, &info);
1925 assert_eq!(text.lines, vec![Line::from(vec![
1926 Span::raw(emoji),
1927 space_span(20 - emoji_width, Style::default()),
1928 ]),]);
1929 // Test with emojis_shortcodes set to true
1930 let text = tree.to_text(20, Style::default(), &enabled, &info);
1931 assert_eq!(text.lines, vec![Line::from(vec![
1932 Span::raw(replacement.as_str()),
1933 space_span(20 - replacement_width, Style::default()),
1934 ])]);
1935 }
1936 }
1937}