src/message/html.rs

1507 lines · 48279 bytes

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