//! # Rendering for formatted bodies //! //! This module contains the code for rendering messages that contained an //! "org.matrix.custom.html"-formatted body. //! //! The Matrix specification recommends limiting rendered tags and attributes to a safe subset of //! HTML. You can read more in section 11.2.1.1, "m.room.message msgtypes": //! //! //! //! This isn't as important for iamb, since it isn't a browser environment, but we do still map //! input onto an enum of the safe list of tags to keep it easy to understand and process. use css_color_parser::Color as CssColor; use html5ever::driver::{ParseOpts, parse_fragment}; use html5ever::interface::{Attribute, QualName}; use html5ever::tendril::{StrTendril, TendrilSink}; use html5ever::{local_name, ns}; use markup5ever_rcdom::{Handle, NodeData, RcDom}; use matrix_sdk::OwnedServerName; use matrix_sdk::ruma::OwnedMxcUri; use matrix_sdk::ruma::events::room::ImageInfo; use crate::message::printer::TextPrinter; use crate::message::{ProtocolPreview, placeholder_frame}; use crate::prelude::*; use crate::preview::ImageStatus; use crate::util::{join_cell_text, space_text, wrapped_text}; /// Generate bullet points from a [ListStyle]. pub struct BulletIterator { style: ListStyle, pos: usize, /// The number of characters the number takes up len: usize, } impl BulletIterator { fn width(&self) -> usize { match self.style { ListStyle::Unordered => 2, ListStyle::Ordered(_) => self.len + 2, } } } impl Iterator for BulletIterator { type Item = String; fn next(&mut self) -> Option { let bullet = match self.style { ListStyle::Unordered => "- ".to_string(), ListStyle::Ordered(_) => { let w = self.len; format!("{: >w$}. ", self.pos, w = w) }, }; self.pos += 1; return Some(bullet); } } /// Whether this list is ordered or unordered. #[derive(Clone, Copy, Debug)] pub enum ListStyle { /// The `usize` is the start index. Ordered(usize), Unordered, } impl ListStyle { fn bullets(&self, len: usize) -> BulletIterator { let pos = match self { // Restart at 1 if the last number would not fit in a `usize`. Self::Ordered(start) if start.checked_add(len).is_some() => *start, Self::Ordered(_) => 1, Self::Unordered => 0, }; let len = (pos + len).to_string().len(); BulletIterator { style: *self, pos, len } } } pub type StyleTreeChildren = Vec; /// Type of contents in a table cell. #[derive(Debug, Clone, Copy)] pub enum CellType { Data, Header, } /// A collection of cells for a single row in a table. #[derive(Debug, Clone)] pub struct TableRow { cells: Vec<(CellType, StyleTreeNode)>, } impl TableRow { pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) { for (_, cell) in &self.cells { cell.gather_links(urls); } } pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { for (_, cell) in &self.cells { cell.image_previews(previews); } } fn columns(&self) -> usize { self.cells.len() } } /// A collection of rows in a table. #[derive(Debug, Clone)] pub struct TableSection { rows: Vec, } impl TableSection { pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) { for row in &self.rows { row.gather_links(urls); } } pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { for row in &self.rows { row.image_previews(previews); } } fn columns(&self) -> usize { self.rows.iter().map(TableRow::columns).max().unwrap_or(0) } } /// A table. #[derive(Debug, Clone)] pub struct Table { caption: Option>, sections: Vec, } impl Table { fn columns(&self) -> usize { self.sections.iter().map(TableSection::columns).max().unwrap_or(0) } pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) { for section in &self.sections { section.gather_links(urls); } } pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { for section in &self.sections { section.image_previews(previews); } } fn to_text<'a>(&'a self, printer: &TextPrinter<'a>, style: Style) -> Text<'a> { let mut text = Text::default(); let columns = self.columns(); let cell_total = printer.width().saturating_sub(columns).saturating_sub(1); let cell_min = cell_total.checked_div(columns).unwrap_or(0); let mut cell_slop = cell_total - cell_min * columns; let cell_widths = (0..columns) .map(|_| { let slopped = cell_slop.min(1); cell_slop -= slopped; cell_min + slopped }) .collect::>(); let mut nrows = 0; let line_style = style.patch(printer.settings.theme.messages.table); let line = printer.settings.theme.messages.table_line.to_table_set(); if let Some(caption) = &self.caption { let mut printer = printer.sub(6).align(Alignment::Center); caption.print(&mut printer, style); for mut line in printer.finish().0.lines { line.spans.insert(0, Span::styled(" ", style)); line.spans.push(Span::styled(" ", style)); text.lines.push(line); } } if columns == 0 { // There are no cells to draw a grid around. return text; } for section in self.sections.iter() { for row in section.rows.iter() { let mut ruler = String::new(); for (i, w) in cell_widths.iter().enumerate() { let cross = match (nrows, i) { (0, 0) => line.top_left, (0, _) => line.horizontal_down, (_, 0) => line.vertical_right, (_, _) => line.cross, }; ruler.push_str(cross); for _ in 0..*w { ruler.push_str(line.horizontal); } } if nrows == 0 { ruler.push_str(line.top_right); } else { ruler.push_str(line.vertical_left); } text.lines.push(Line::from(vec![Span::styled(ruler, line_style)])); let cells = cell_widths .iter() .enumerate() .map(|(i, w)| { let text = if let Some((kind, cell)) = row.cells.get(i) { let style = match kind { CellType::Header => style.add_modifier(StyleModifier::BOLD), CellType::Data => style, }; cell.to_text(*w, style, printer.settings, printer.info) } else { space_text(*w, style) }; (text, *w) }) .collect(); let joined = join_cell_text(cells, Span::styled(line.vertical, line_style), style); text.lines.extend(joined.lines); nrows += 1; } } if nrows > 0 { let mut ruler = String::new(); for (i, w) in cell_widths.iter().enumerate() { let cross = if i == 0 { line.bottom_left } else { line.horizontal_up }; ruler.push_str(cross); for _ in 0..*w { ruler.push_str(line.horizontal); } } ruler.push_str(line.bottom_right); text.lines.push(Line::from(vec![Span::styled(ruler, line_style)])); } text } } #[derive(Debug, Clone)] pub enum ThemeSelector { Strong, Emphasis, Strikethrough, Underlined, } impl ThemeSelector { fn style(&self, settings: &ApplicationSettings) -> Style { match self { Self::Strong => settings.theme.messages.strong, Self::Emphasis => settings.theme.messages.emphasis, Self::Strikethrough => settings.theme.messages.strikethrough, Self::Underlined => settings.theme.messages.underlined, } } } #[derive(Debug, Clone)] pub struct Image { title: Option, alt: Option, width: Option, height: Option, src: Option, is_emote: bool, } impl Image { pub fn new(src: MediaSource, info: Option<&ImageInfo>) -> Self { let width = info .and_then(|info| info.width) .and_then(|width| u16::try_from(width).ok()); let height = info .and_then(|info| info.height) .and_then(|height| u16::try_from(height).ok()); Self { src: Some(src), width, height, title: None, alt: None, is_emote: false, } } fn kind(&self) -> PreviewKind { if self.is_emote { return PreviewKind::Emoji; } PreviewKind::Custom(self.width, self.height) } fn preview<'a>(&self, previews: &'a PreviewManager) -> Option<&'a ImageStatus> { self.src.as_ref().and_then(|src| previews.get(src, self.kind())) } } /// A processed HTML element that we can render to the terminal. #[derive(Debug, Clone)] pub enum StyleTreeNode { Anchor(Box, char, Url), Blockquote(Box), Break, #[allow(dead_code)] Code(Box, Option), Header(Box, usize), Image(Image), List(StyleTreeChildren, ListStyle), Paragraph(Box), Pre(Box), Ruler, Themed(Box, ThemeSelector), Style(Box, Style), Table(Table), Text(Cow<'static, str>), Sequence(StyleTreeChildren), RoomAlias(OwnedRoomAliasId, Option, Option), RoomId(OwnedRoomId, Vec, Option, Option), UserId(OwnedUserId, Option), DisplayName(String, OwnedUserId, Option), } impl StyleTreeNode { pub fn to_text<'a>( &'a self, width: usize, style: Style, settings: &'a ApplicationSettings, info: &'a RoomInfo, ) -> Text<'a> { let mut printer = TextPrinter::new(width, style, settings, info, None); self.print(&mut printer, style); printer.finish().0 } pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) { match self { StyleTreeNode::Anchor(_, c, url) => { urls.push((*c, url.clone())); }, StyleTreeNode::Blockquote(child) | StyleTreeNode::Code(child, _) | StyleTreeNode::Header(child, _) | StyleTreeNode::Paragraph(child) | StyleTreeNode::Pre(child) | StyleTreeNode::Style(child, _) | StyleTreeNode::Themed(child, _) => { child.gather_links(urls); }, StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => { for child in children { child.gather_links(urls); } }, StyleTreeNode::Table(table) => { table.gather_links(urls); }, StyleTreeNode::DisplayName(_, user_id, c) | StyleTreeNode::UserId(user_id, c) => { if let Some(c) = c { let to_url = Url::parse(&user_id.matrix_uri(false).to_string()).unwrap(); urls.push((*c, to_url)); } }, StyleTreeNode::RoomId(room_id, via, c, event_id) => { if let Some(c) = c { let uri = if let Some(ev_id) = event_id { room_id.matrix_event_uri(ev_id.to_owned()).to_string() } else { room_id.matrix_uri_via(via.iter().cloned(), false).to_string() }; let to_url = Url::parse(&uri).unwrap(); urls.push((*c, to_url)); } }, StyleTreeNode::RoomAlias(alias, c, event_id) => { if let Some(c) = c { let uri = if let Some(ev_id) = event_id { #[expect( deprecated, reason = "we only use this if we received a deprecated link" )] alias.matrix_event_uri(ev_id.to_owned()).to_string() } else { alias.matrix_uri(false).to_string() }; let to_url = Url::parse(&uri).unwrap(); urls.push((*c, to_url)); } }, StyleTreeNode::Image(..) => {}, StyleTreeNode::Ruler => {}, StyleTreeNode::Text(_) => {}, StyleTreeNode::Break => {}, } } pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { match self { StyleTreeNode::Image(img) => { if let Some(source) = &img.src { previews.push((source, img.kind())); } }, StyleTreeNode::Blockquote(child) | StyleTreeNode::Code(child, _) | StyleTreeNode::Header(child, _) | StyleTreeNode::Paragraph(child) | StyleTreeNode::Pre(child) | StyleTreeNode::Style(child, _) | StyleTreeNode::Themed(child, _) => { child.image_previews(previews); }, StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => { for child in children { child.image_previews(previews); } }, StyleTreeNode::Table(table) => { table.image_previews(previews); }, StyleTreeNode::Ruler | StyleTreeNode::Text(..) | StyleTreeNode::Break | StyleTreeNode::Anchor(..) | StyleTreeNode::RoomAlias(..) | StyleTreeNode::RoomId(..) | StyleTreeNode::UserId(..) | StyleTreeNode::DisplayName(..) => {}, } } pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) { let width = printer.width(); match self { StyleTreeNode::Anchor(child, c, _) => { let bold = style.add_modifier(StyleModifier::BOLD); child.print(printer, bold); let link = format!("[{c}]"); let span = Span::styled(link, style); printer.push_span_nobreak(span); }, StyleTreeNode::Blockquote(child) => { let quote_style = style.patch(printer.settings().theme.messages.blockquote); let quote = printer.settings().theme.messages.blockquote_line.to_table_set().vertical; let mut subp = printer.sub(3); child.print(&mut subp, style); for mut line in subp.finish().0 { line.spans.insert(0, Span::styled(" ", style)); line.spans.insert(0, Span::styled(quote, quote_style)); line.spans.insert(0, Span::styled(" ", style)); printer.push_line(line); } }, StyleTreeNode::Code(child, _) => { let style = style.patch(printer.settings().theme.messages.code); let old_style = printer.replace_base_style(style); child.print(printer, style); printer.replace_base_style(old_style); }, StyleTreeNode::Header(child, level) => { let style = style.add_modifier(StyleModifier::BOLD); for _ in 0..*level { printer.push_str("#", style); } printer.push_str(" ", style); child.print(printer, style); }, StyleTreeNode::Image(img @ Image { is_emote: true, .. }) => { if let Some(previews) = printer.previews && let Some(image) = img.preview(previews) && let ImageStatus::Loaded(image) = image { printer.push_emoji(image, style); } else { let title = img.title.as_deref().unwrap_or("emote"); printer.push_span_nobreak(Span::styled(format!(":{title}:"), style)); } }, StyleTreeNode::Image(img) => { let alt = img.alt.as_deref().or(img.title.as_deref()); let mut proto = None; let placeholder = match printer.previews.and_then(|previews| img.preview(previews)) { None => { if let Some(alt) = alt { format!("[Image Alt: {alt}]") } else { "[Image]".to_string() } }, Some(ImageStatus::Queued(image_preview_size)) => { placeholder_frame(Some("Queued..."), width, image_preview_size) }, Some(ImageStatus::Downloading(image_preview_size)) => { placeholder_frame(Some("Downloading..."), width, image_preview_size) }, Some(ImageStatus::Loaded(backend)) => { proto = Some(backend); placeholder_frame(None, width, &backend.size()) }, Some(ImageStatus::Error(err)) => format!("[Image error: {err}]\n"), }; printer.commit(); if let Some(proto) = proto { printer.push_image(proto); } printer.push_text(wrapped_text(placeholder, width, style)); printer.commit(); }, StyleTreeNode::List(children, lt) => { let mut bullets = lt.bullets(children.len()); let liw = bullets.width(); for child in children { let mut subp = printer.sub(liw); let mut bullet = bullets.next(); child.print(&mut subp, style); for mut line in subp.finish().0 { let leading = if let Some(bullet) = bullet.take() { Span::styled(bullet, style) } else { Span::styled(" ".repeat(liw), style) }; line.spans.insert(0, leading); printer.push_line(line); } } }, StyleTreeNode::Paragraph(child) => { printer.push_break(); child.print(printer, style); printer.commit(); }, StyleTreeNode::Pre(child) => { let mut subp = printer.sub(2).literal(true); let code_style = style.patch(subp.settings().theme.messages.code_block); let _ = subp.replace_base_style(code_style); let subw = subp.width(); let border = subp.settings().theme.messages.code_block_line.to_border_set(); child.print(&mut subp, code_style); printer.commit(); printer.push_line( vec![ Span::styled(border.top_left, style), Span::styled(border.horizontal_top.repeat(subw), style), Span::styled(border.top_right, style), ] .into(), ); for mut line in subp.finish().0 { line.spans.insert(0, Span::styled(border.vertical_left, style)); line.spans.push(Span::styled(border.vertical_right, style)); printer.push_line(line); } printer.push_line( vec![ Span::styled(border.bottom_left, style), Span::styled(border.horizontal_bottom.repeat(subw), style), Span::styled(border.bottom_right, style), ] .into(), ); printer.commit(); }, StyleTreeNode::Ruler => { let style = style.patch(printer.settings().theme.messages.ruler); let line = printer.settings().theme.messages.ruler_line.to_table_set().horizontal; for _ in 0..width { printer.push_str(line, style); } }, StyleTreeNode::Table(table) => { let text = table.to_text(printer, style); printer.push_text(text); }, StyleTreeNode::Break => { printer.push_break(); }, StyleTreeNode::Text(s) => { printer.push_str(s.as_ref(), style); }, StyleTreeNode::Themed(child, patch) => { let patch = patch.style(printer.settings()); child.print(printer, style.patch(patch)) }, StyleTreeNode::Style(child, patch) => child.print(printer, style.patch(*patch)), StyleTreeNode::Sequence(children) => { let mut after_quote = false; for child in children { match child { // Whitespace between elements shouldn't affect spacing. StyleTreeNode::Text(text) if text.trim().is_empty() => {}, StyleTreeNode::Blockquote(_) => { if after_quote { // Keep adjacent blockquotes from visually merging. printer.commit(); printer.push_break(); } after_quote = true; }, _ => after_quote = false, } child.print(printer, style); } }, StyleTreeNode::UserId(user_id, _) => { let mut span: Span<'a> = printer .settings() .get_user_span(user_id, printer.info.display_names.get(user_id)); let style = style.patch(span.style); span.style = style; if !span.content.starts_with('@') { printer.push_str("@", style); } printer.push_span_nobreak(span); }, StyleTreeNode::DisplayName(display_name, user_id, _) => { let style = printer.settings().get_user_style(user_id); printer.push_str(display_name.as_str(), style); }, StyleTreeNode::RoomId(room_id, _, _, event_id) => { let bold = style.add_modifier(StyleModifier::BOLD); if event_id.is_some() { printer.push_str("Event in ", bold); } printer.push_str(room_id.as_str(), bold); }, StyleTreeNode::RoomAlias(alias, _, event_id) => { let bold = style.add_modifier(StyleModifier::BOLD); if event_id.is_some() { printer.push_str("Event in ", bold); } printer.push_str(alias.as_str(), bold); }, } } } /// A processed HTML document. #[derive(Clone)] pub struct StyleTree { pub(super) children: StyleTreeChildren, } impl StyleTree { pub fn get_links(&self) -> Vec<(char, Url)> { let mut links = Vec::new(); for child in &self.children { child.gather_links(&mut links); } return links; } pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> { let mut previews = vec![]; for child in &self.children { child.image_previews(&mut previews); } return previews; } pub fn to_text<'a>( &'a self, width: usize, style: Style, settings: &'a ApplicationSettings, info: &'a RoomInfo, ) -> Text<'a> { let mut printer = TextPrinter::new(width, style, settings, info, None); for child in self.children.iter() { child.print(&mut printer, style); } printer.finish().0 } /// The images are in the format `(protocol, x, y)` pub fn render<'a>( &'a self, width: usize, style: Style, settings: &'a ApplicationSettings, info: &'a RoomInfo, previews: &'a PreviewManager, ) -> (Text<'a>, Vec) { let mut printer = TextPrinter::new(width, style, settings, info, Some(previews)); for child in self.children.iter() { child.print(&mut printer, style); } printer.finish() } } pub struct TreeGenState { pub link_num: u8, } impl TreeGenState { pub fn next_link_char(&mut self) -> Option { let num = self.link_num; if num < 62 { self.link_num = num + 1; } if num < 10 { Some((num + b'0') as char) } else if num < 36 { Some((num - 10 + b'a') as char) } else if num < 62 { Some((num - 36 + b'A') as char) } else { None } } } fn c2c(handles: &[Handle], state: &mut TreeGenState) -> Vec { handles.iter().flat_map(|h| h2t(h, state)).collect() } fn c2t(handles: &[Handle], state: &mut TreeGenState) -> Box { let node = StyleTreeNode::Sequence(c2c(handles, state)); Box::new(node) } fn get_node(hdl: &Handle, want: &str, state: &mut TreeGenState) -> Option { let node = hdl.deref(); if let NodeData::Element { name, .. } = &node.data { if name.local.as_ref() != want { return None; } let c = c2c(&node.children.borrow(), state); return Some(StyleTreeNode::Sequence(c)); } else { return None; } } fn li2t(hdl: &Handle, state: &mut TreeGenState) -> Option { get_node(hdl, "li", state) } fn table_cell(hdl: &Handle, state: &mut TreeGenState) -> Option<(CellType, StyleTreeNode)> { if let Some(node) = get_node(hdl, "th", state) { return Some((CellType::Header, node)); } Some((CellType::Data, get_node(hdl, "td", state)?)) } fn table_row(hdl: &Handle, state: &mut TreeGenState) -> Option { let node = hdl.deref(); if let NodeData::Element { name, .. } = &node.data { if name.local.as_ref() != "tr" { return None; } let cells = table_cells(&node.children.borrow(), state); return Some(TableRow { cells }); } else { return None; } } fn table_section(hdl: &Handle, state: &mut TreeGenState) -> Option { let node = hdl.deref(); if let NodeData::Element { name, .. } = &node.data { match name.local.as_ref() { "thead" | "tbody" => { let rows = table_rows(&node.children.borrow(), state); Some(TableSection { rows }) }, _ => None, } } else { return None; } } fn table_cells(handles: &[Handle], state: &mut TreeGenState) -> Vec<(CellType, StyleTreeNode)> { handles.iter().filter_map(|h| table_cell(h, state)).collect() } fn table_rows(handles: &[Handle], state: &mut TreeGenState) -> Vec { handles.iter().filter_map(|h| table_row(h, state)).collect() } fn table_sections(handles: &[Handle], state: &mut TreeGenState) -> Vec { handles.iter().filter_map(|h| table_section(h, state)).collect() } fn lic2t(handles: &[Handle], state: &mut TreeGenState) -> StyleTreeChildren { handles.iter().filter_map(|h| li2t(h, state)).collect() } fn attrs_to_start(attrs: &[Attribute]) -> Option { for attr in attrs { if attr.name.local.as_ref() != "start" { continue; } if let Ok(start) = usize::from_str(attr.value.as_ref()) { return Some(start); } } return None; } fn attrs_to_image(attrs: &[Attribute]) -> Image { let mut title = None; let mut alt = None; let mut width = None; let mut height = None; let mut src = None; let mut is_emote = false; for attr in attrs { match attr.name.local.as_ref() { "title" => { title = Some(attr.value.to_string()); }, "alt" => { alt = Some(attr.value.to_string()); }, "width" => { if let Ok(val) = u16::from_str(attr.value.as_ref()) { width = Some(val); } }, "height" => { if let Ok(val) = u16::from_str(attr.value.as_ref()) { height = Some(val); } }, "src" => { let uri = OwnedMxcUri::from(attr.value.to_string()); if uri.is_valid() { src = Some(uri); } }, "data-mx-emoticon" => { is_emote = true; }, _ => (), } } Image { title, alt, width, height, is_emote, src: src.map(MediaSource::Plain), } } fn attrs_to_href(attrs: &[Attribute]) -> Option { for attr in attrs { if attr.name.local.as_ref() != "href" { continue; } return Some(attr.value.to_string()); } return None; } fn attrs_to_language(attrs: &[Attribute]) -> Option { for attr in attrs { if attr.name.local.as_ref() != "class" { continue; } for class in attr.value.as_ref().unicode_words() { if class.len() > 9 && class.starts_with("language-") { return Some(class[9..].to_string()); } } } return None; } fn attrs_to_style(attrs: &[Attribute]) -> Style { let mut style = Style::default(); for attr in attrs { match attr.name.local.as_ref() { "data-mx-bg-color" => { if let Ok(rgb) = attr.value.as_ref().parse::() { let color = Color::Rgb(rgb.r, rgb.g, rgb.b); style = style.bg(color); } }, "data-mx-color" | "color" => { if let Ok(rgb) = attr.value.as_ref().parse::() { let color = Color::Rgb(rgb.r, rgb.g, rgb.b); style = style.fg(color); } }, _ => continue, } } return style; } fn mxid2t( id: &MatrixId, via: &[OwnedServerName], n: Option, c: &StyleTreeNode, h: &Url, ) -> StyleTreeNode { match id { MatrixId::Room(room_id) => { StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n, None) }, MatrixId::RoomAlias(alias) => StyleTreeNode::RoomAlias(alias.to_owned(), n, None), MatrixId::User(user_id) => StyleTreeNode::UserId(user_id.to_owned(), n), MatrixId::Event(room_or_alias_id, event_id) => { let room_or_alias_id: &matrix_sdk::ruma::RoomOrAliasId = room_or_alias_id; let event_id = Some(event_id.to_owned()); if let Ok(alias_id) = <&matrix_sdk::ruma::RoomAliasId>::try_from(room_or_alias_id) { StyleTreeNode::RoomAlias(alias_id.to_owned(), n, event_id) } else { let room_id = <&matrix_sdk::ruma::RoomId>::try_from(room_or_alias_id).unwrap(); StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n, event_id) } }, _ => { if let Some(n) = n { StyleTreeNode::Anchor(Box::new(c.to_owned()), n, h.to_owned()) } else { c.clone() } }, } } fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren { let node = hdl.deref(); let tree = match &node.data { NodeData::Document => *c2t(node.children.borrow().as_slice(), state), NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string().into()), NodeData::Element { name, attrs, .. } => { match name.local.as_ref() { // Links "a" => { let c = c2t(&node.children.borrow(), state); let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok()); if let Some(h) = h { let n = state.next_link_char(); if let Ok(uri) = MatrixToUri::parse(h.as_str()) { mxid2t(uri.id(), uri.via(), n, &c, &h) } else if let Ok(uri) = MatrixUri::parse(h.as_str()) { mxid2t(uri.id(), uri.via(), n, &c, &h) } else if let Some(n) = n { StyleTreeNode::Anchor(c, n, h) } else { *c } } else { *c } }, // Style change "b" | "strong" => { let c = c2t(&node.children.borrow(), state); StyleTreeNode::Themed(c, ThemeSelector::Strong) }, "font" => { let c = c2t(&node.children.borrow(), state); let s = attrs_to_style(&attrs.borrow()); StyleTreeNode::Style(c, s) }, "em" | "i" => { let c = c2t(&node.children.borrow(), state); StyleTreeNode::Themed(c, ThemeSelector::Emphasis) }, "span" => { let c = c2t(&node.children.borrow(), state); let s = attrs_to_style(&attrs.borrow()); StyleTreeNode::Style(c, s) }, "del" | "s" | "strike" => { let c = c2t(&node.children.borrow(), state); StyleTreeNode::Themed(c, ThemeSelector::Strikethrough) }, "u" => { let c = c2t(&node.children.borrow(), state); StyleTreeNode::Themed(c, ThemeSelector::Underlined) }, // Lists "ol" => { StyleTreeNode::List( lic2t(&node.children.borrow(), state), ListStyle::Ordered(attrs_to_start(&attrs.borrow()).unwrap_or(1)), ) }, "ul" => { StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Unordered) }, // Headers "h1" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 1), "h2" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 2), "h3" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 3), "h4" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 4), "h5" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 5), "h6" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 6), // Table "table" => { let sections = table_sections(&node.children.borrow(), state); let caption = node .children .borrow() .iter() .find_map(|hdl| get_node(hdl, "caption", state)) .map(Box::new); let table = Table { caption, sections }; StyleTreeNode::Table(table) }, // Code blocks. "code" => { let c = c2t(&node.children.borrow(), state); let l = attrs_to_language(&attrs.borrow()); StyleTreeNode::Code(c, l) }, // Other text blocks. "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow(), state)), "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow(), state)), "pre" => StyleTreeNode::Pre(c2t(&node.children.borrow(), state)), // No children. "hr" => StyleTreeNode::Ruler, "br" => StyleTreeNode::Break, "img" => StyleTreeNode::Image(attrs_to_image(&attrs.borrow())), // These don't render in any special way. "details" | "html" | "summary" | "sub" | "sup" => { *c2t(&node.children.borrow(), state) }, // This is deprecated and should be stripped if encountered. "mx-reply" => return vec![], // Treat unknown tags as plain text. _ => *c2t(&node.children.borrow(), state), } }, // These don't render as anything. NodeData::Doctype { .. } => return vec![], NodeData::Comment { .. } => return vec![], NodeData::ProcessingInstruction { .. } => return vec![], }; vec![tree] } fn dom_to_style_tree(dom: RcDom) -> StyleTree { let mut state = TreeGenState { link_num: 0 }; let children = h2t(&dom.document, &mut state); StyleTree { children } } /// Parse an HTML document from a string. pub fn parse_matrix_html(s: &str) -> StyleTree { let dom = parse_fragment( RcDom::default(), ParseOpts::default(), QualName::new(None, ns!(html), local_name!("body")), vec![], false, ) .one(StrTendril::from(s)); dom_to_style_tree(dom) } #[cfg(test)] pub mod tests { use super::*; use pretty_assertions::assert_eq; use ratatui::symbols::line; use unicode_width::UnicodeWidthStr; use crate::tests::{mock_room, mock_settings}; use crate::util::space_span; #[test] fn test_header() { let info = mock_room(); let settings = mock_settings(); let bold = Style::default().add_modifier(StyleModifier::BOLD); let s = "

Header 1

"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("#", bold), Span::styled(" ", bold), Span::styled("Header", bold), Span::styled(" ", bold), Span::styled("1", bold), space_span(10, Style::default()) ])]); let s = "

Header 2

"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("#", bold), Span::styled("#", bold), Span::styled(" ", bold), Span::styled("Header", bold), Span::styled(" ", bold), Span::styled("2", bold), space_span(9, Style::default()) ])]); let s = "

Header 3

"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled(" ", bold), Span::styled("Header", bold), Span::styled(" ", bold), Span::styled("3", bold), space_span(8, Style::default()) ])]); let s = "

Header 4

"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled(" ", bold), Span::styled("Header", bold), Span::styled(" ", bold), Span::styled("4", bold), space_span(7, Style::default()) ])]); let s = "
Header 5
"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled(" ", bold), Span::styled("Header", bold), Span::styled(" ", bold), Span::styled("5", bold), space_span(6, Style::default()) ])]); let s = "
Header 6
"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled("#", bold), Span::styled(" ", bold), Span::styled("Header", bold), Span::styled(" ", bold), Span::styled("6", bold), space_span(5, Style::default()) ])]); } #[test] fn test_style() { let info = mock_room(); let settings = mock_settings(); let def = Style::default(); let bold = def.add_modifier(StyleModifier::BOLD); let italic = def.add_modifier(StyleModifier::ITALIC); let strike = def.add_modifier(StyleModifier::CROSSED_OUT); let underl = def.add_modifier(StyleModifier::UNDERLINED); let red = def.fg(Color::Rgb(0xff, 0x00, 0x00)); let s = "Bold!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Bold", bold), Span::styled("!", bold), space_span(15, def) ])]); let s = "Bold!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Bold", bold), Span::styled("!", bold), space_span(15, def) ])]); let s = "Italic!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Italic", italic), Span::styled("!", italic), space_span(13, def) ])]); let s = "Italic!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Italic", italic), Span::styled("!", italic), space_span(13, def) ])]); let s = "Strikethrough!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Strikethrough", strike), Span::styled("!", strike), space_span(6, def) ])]); let s = "Strikethrough!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Strikethrough", strike), Span::styled("!", strike), space_span(6, def) ])]); let s = "Underline!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Underline", underl), Span::styled("!", underl), space_span(10, def) ])]); let s = "Red!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Red", red), Span::styled("!", red), space_span(16, def) ])]); let s = "Red!"; let tree = parse_matrix_html(s); let text = tree.to_text(20, Style::default(), &settings, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::styled("Red", red), Span::styled("!", red), space_span(16, def) ])]); } #[test] fn test_paragraph() { let info = mock_room(); let settings = mock_settings(); let s = "

Hello world!

Content

Goodbye world!

"; let tree = parse_matrix_html(s); let text = tree.to_text(10, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 7); assert_eq!( text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "), Span::raw(" ")]) ); assert_eq!( text.lines[1], Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")]) ); assert_eq!(text.lines[2], Line::from(vec![Span::raw(" ")])); assert_eq!(text.lines[3], Line::from(vec![Span::raw("Content"), Span::raw(" ")])); assert_eq!(text.lines[4], Line::from(vec![Span::raw(" ")])); assert_eq!( text.lines[5], Line::from(vec![Span::raw("Goodbye"), Span::raw(" "), Span::raw(" ")]) ); assert_eq!( text.lines[6], Line::from(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")]) ); } #[test] fn test_blockquote() { let info = mock_room(); let settings = mock_settings(); let s = "
Hello world!
"; let tree = parse_matrix_html(s); let text = tree.to_text(10, Style::default(), &settings, &info); let style = Style::new().fg(Color::Cyan); assert_eq!(text.lines.len(), 2); assert_eq!( text.lines[0], Line::from(vec![ Span::raw(" "), Span::styled(line::THICK_VERTICAL, style), Span::raw(" "), Span::raw("Hello"), Span::raw(" "), Span::raw(" "), ]) ); assert_eq!( text.lines[1], Line::from(vec![ Span::raw(" "), Span::styled(line::THICK_VERTICAL, style), Span::raw(" "), Span::raw("world"), Span::raw("!"), Span::raw(" "), ]) ); } #[test] fn test_blockquote_adjacent() { let info = mock_room(); let settings = mock_settings(); let s = "
\n

One

\n
\n
\n

Two

\n
"; let tree = parse_matrix_html(s); let text = tree.to_text(10, Style::default(), &settings, &info); let style = Style::new().fg(Color::Cyan); let quoted = |word: &'static str, pad: &'static str| { Line::from(vec![ Span::raw(" "), Span::styled(line::THICK_VERTICAL, style), Span::raw(" "), Span::raw(word), Span::raw(pad), ]) }; assert_eq!(text.lines.len(), 3); assert_eq!(text.lines[0], quoted("One", " ")); assert_eq!(text.lines[1], Line::from(vec![Span::raw(" ".repeat(10))])); assert_eq!(text.lines[2], quoted("Two", " ")); } #[test] fn test_list_unordered() { let info = mock_room(); let settings = mock_settings(); let s = "
  • List Item 1
  • List Item 2
  • List Item 3
"; let tree = parse_matrix_html(s); let text = tree.to_text(8, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 6); assert_eq!( text.lines[0], Line::from(vec![ Span::raw("- "), Span::raw("List"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[1], Line::from(vec![ Span::raw(" "), Span::raw("Item"), Span::raw(" "), Span::raw("1") ]) ); assert_eq!( text.lines[2], Line::from(vec![ Span::raw("- "), Span::raw("List"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[3], Line::from(vec![ Span::raw(" "), Span::raw("Item"), Span::raw(" "), Span::raw("2") ]) ); assert_eq!( text.lines[4], Line::from(vec![ Span::raw("- "), Span::raw("List"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[5], Line::from(vec![ Span::raw(" "), Span::raw("Item"), Span::raw(" "), Span::raw("3") ]) ); } fn list_bullets(start: usize) -> Vec> { let info = mock_room(); let settings = mock_settings(); let s = format!("
  1. a
  2. b
"); let tree = parse_matrix_html(&s); let text = tree.to_text(40, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 2); text.lines .iter() .map(|line| line.spans.first().map(|span| span.content.to_string())) .collect() } #[test] fn test_list_ordered_start_overflow() { // Numbering that would overflow a `usize` restarts at 1. for start in [usize::MAX, usize::MAX - 1] { assert_eq!(list_bullets(start), vec![Some("1. ".to_string()), Some("2. ".to_string())]); } } #[test] fn test_list_ordered_start_near_max() { // The largest start for which the numbering still fits is left alone. let start = usize::MAX - 2; assert_eq!(list_bullets(start), vec![ Some(format!("{}. ", start)), Some(format!("{}. ", start + 1)) ]); } #[test] fn test_list_ordered() { let info = mock_room(); let settings = mock_settings(); let s = "
  1. List Item 1
  2. List Item 2
  3. List Item 3
"; let tree = parse_matrix_html(s); let text = tree.to_text(9, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 6); assert_eq!( text.lines[0], Line::from(vec![ Span::raw("1. "), Span::raw("List"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[1], Line::from(vec![ Span::raw(" "), Span::raw("Item"), Span::raw(" "), Span::raw("1") ]) ); assert_eq!( text.lines[2], Line::from(vec![ Span::raw("2. "), Span::raw("List"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[3], Line::from(vec![ Span::raw(" "), Span::raw("Item"), Span::raw(" "), Span::raw("2") ]) ); assert_eq!( text.lines[4], Line::from(vec![ Span::raw("3. "), Span::raw("List"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[5], Line::from(vec![ Span::raw(" "), Span::raw("Item"), Span::raw(" "), Span::raw("3") ]) ); } #[test] fn test_table() { let info = mock_room(); let settings = mock_settings(); let s = "\ \ \ \ \ \ \
Column 1Column 2Column 3
abc
abc
abc
"; let tree = parse_matrix_html(s); let text = tree.to_text(15, Style::default(), &settings, &info); let bold = Style::default().add_modifier(StyleModifier::BOLD); assert_eq!(text.lines.len(), 11); // Table header assert_eq!(text.lines[0].spans, vec![Span::raw("┌────┬────┬───┐")]); assert_eq!(text.lines[1].spans, vec![ Span::raw("│"), Span::styled("Colu", bold), Span::raw("│"), Span::styled("Colu", bold), Span::raw("│"), Span::styled("Col", bold), Span::raw("│") ]); assert_eq!(text.lines[2].spans, vec![ Span::raw("│"), Span::styled("mn", bold), Span::styled(" ", bold), Span::styled("1", bold), Span::raw("│"), Span::styled("mn", bold), Span::styled(" ", bold), Span::styled("2", bold), Span::raw("│"), Span::styled("umn", bold), Span::raw("│") ]); assert_eq!(text.lines[3].spans, vec![ Span::raw("│"), Span::raw(" "), Span::raw("│"), Span::raw(" "), Span::raw("│"), Span::styled("3", bold), Span::styled(" ", bold), Span::raw("│") ]); // First row assert_eq!(text.lines[4].spans, vec![Span::raw("├────┼────┼───┤")]); assert_eq!(text.lines[5].spans, vec![ Span::raw("│"), Span::raw("a"), Span::raw(" "), Span::raw("│"), Span::raw("b"), Span::raw(" "), Span::raw("│"), Span::raw("c"), Span::raw(" "), Span::raw("│") ]); // Second row assert_eq!(text.lines[6].spans, vec![Span::raw("├────┼────┼───┤")]); assert_eq!(text.lines[7].spans, vec![ Span::raw("│"), Span::raw("a"), Span::raw(" "), Span::raw("│"), Span::raw("b"), Span::raw(" "), Span::raw("│"), Span::raw("c"), Span::raw(" "), Span::raw("│") ]); // Third row assert_eq!(text.lines[8].spans, vec![Span::raw("├────┼────┼───┤")]); assert_eq!(text.lines[9].spans, vec![ Span::raw("│"), Span::raw("a"), Span::raw(" "), Span::raw("│"), Span::raw("b"), Span::raw(" "), Span::raw("│"), Span::raw("c"), Span::raw(" "), Span::raw("│") ]); // Bottom ruler assert_eq!(text.lines[10].spans, vec![Span::raw("└────┴────┴───┘")]); } #[test] fn test_table_without_cells() { let info = mock_room(); let settings = mock_settings(); for s in ["
", "
"] { let tree = parse_matrix_html(s); let text = tree.to_text(15, Style::default(), &settings, &info); assert!(text.lines.is_empty()); } let s = "
Title
"; let tree = parse_matrix_html(s); let text = tree.to_text(15, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 1); } #[test] fn test_matrix_reply_stripped() { let info = mock_room(); let settings = mock_settings(); let s = "This was replied toThis is the reply"; let tree = parse_matrix_html(s); let text = tree.to_text(10, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 2); assert_eq!( text.lines[0], Line::from(vec![ Span::raw("This"), Span::raw(" "), Span::raw("is"), Span::raw(" "), Span::raw(" ") ]) ); assert_eq!( text.lines[1], Line::from(vec![ Span::raw("the"), Span::raw(" "), Span::raw("reply"), Span::raw(" ") ]) ); } #[test] fn test_self_closing() { let info = mock_room(); let settings = mock_settings(); let s = "Hello
World
Goodbye"; let tree = parse_matrix_html(s); let text = tree.to_text(7, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 3); assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),])); assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),])); assert_eq!(text.lines[2], Line::from(vec![Span::raw("Goodbye")]),); } #[test] fn test_embedded_newline() { let info = mock_room(); let settings = mock_settings(); let s = "

Hello\nWorld

"; let tree = parse_matrix_html(s); let text = tree.to_text(15, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 1); assert_eq!( text.lines[0], Line::from(vec![ Span::raw("Hello"), Span::raw(" "), Span::raw("World"), Span::raw(" ") ]) ); } #[test] fn test_pre_tag() { let info = mock_room(); let settings = mock_settings(); let code_style = settings.theme.messages.code_block; let s = concat!( "
",
            "fn hello() -> usize {\n",
            " \t// weired\n",
            "    return 5;\n",
            "}\n",
            "
\n" ); let tree = parse_matrix_html(s); let text = tree.to_text(25, Style::default(), &settings, &info); assert_eq!(text.lines.len(), 6); assert_eq!( text.lines[0], Line::from(vec![ Span::raw(line::TOP_LEFT), Span::raw(line::HORIZONTAL.repeat(23)), Span::raw(line::TOP_RIGHT) ]) ); assert_eq!( text.lines[1], Line::from(vec![ Span::raw(line::VERTICAL), Span::styled("fn", code_style), Span::styled(" ", code_style), Span::styled("hello", code_style), Span::styled("(", code_style), Span::styled(")", code_style), Span::styled(" ", code_style), Span::styled("-", code_style), Span::styled(">", code_style), Span::styled(" ", code_style), Span::styled("usize", code_style), Span::styled(" ", code_style), Span::styled("{", code_style), Span::styled(" ", code_style), Span::raw(line::VERTICAL) ]) ); assert_eq!( text.lines[2], Line::from(vec![ Span::raw(line::VERTICAL), Span::styled(" ", code_style), Span::styled(" ", code_style), Span::styled("/", code_style), Span::styled("/", code_style), Span::styled(" ", code_style), Span::styled("weired", code_style), Span::styled(" ", code_style), Span::raw(line::VERTICAL) ]) ); assert_eq!( text.lines[3], Line::from(vec![ Span::raw(line::VERTICAL), Span::styled(" ", code_style), Span::styled("return", code_style), Span::styled(" ", code_style), Span::styled("5", code_style), Span::styled(";", code_style), Span::styled(" ", code_style), Span::raw(line::VERTICAL) ]) ); assert_eq!( text.lines[4], Line::from(vec![ Span::raw(line::VERTICAL), Span::styled("}", code_style), Span::styled(" ".repeat(22), code_style), Span::raw(line::VERTICAL) ]) ); assert_eq!( text.lines[5], Line::from(vec![ Span::raw(line::BOTTOM_LEFT), Span::raw(line::HORIZONTAL.repeat(23)), Span::raw(line::BOTTOM_RIGHT) ]) ); } #[test] fn test_emoji_shortcodes() { let info = mock_room(); let mut enabled = mock_settings(); enabled.tunables.message_shortcode_display = true; let mut disabled = mock_settings(); disabled.tunables.message_shortcode_display = false; for shortcode in ["exploding_head", "polar_bear", "canada"] { let emoji = emojis::get_by_shortcode(shortcode).unwrap().as_str(); let emoji_width = UnicodeWidthStr::width(emoji); let replacement = format!(":{shortcode}:"); let replacement_width = UnicodeWidthStr::width(replacement.as_str()); let s = format!("

{emoji}

"); let tree = parse_matrix_html(s.as_str()); // Test with emojis_shortcodes set to false let text = tree.to_text(20, Style::default(), &disabled, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::raw(emoji), space_span(20 - emoji_width, Style::default()), ]),]); // Test with emojis_shortcodes set to true let text = tree.to_text(20, Style::default(), &enabled, &info); assert_eq!(text.lines, vec![Line::from(vec![ Span::raw(replacement.as_str()), space_span(20 - replacement_width, Style::default()), ])]); } } }