src/message/html.rs

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