src/message/html.rs

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