src/message/html.rs

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