diff --git a/moli-html2md/README.md b/moli-html2md/README.md index 133f4be7577..72de0a5cad9 100644 --- a/moli-html2md/README.md +++ b/moli-html2md/README.md @@ -66,17 +66,22 @@ missing trailing cells in short rows; the converter does not allocate a padded g Tables with `role="presentation"` or `role="none"` retain ordinary block expansion, in DOM order with blank lines between cells, even when structurally simple. Role -matching ignores ASCII case and surrounding HTML whitespace. The same fallback -applies to complex tables: non-unit spans, multiple `thead` rows, rows wider than +matching ignores ASCII case and surrounding HTML whitespace. Complex tables use +content-only HTML: non-unit spans, multiple `thead` rows, rows wider than an explicit header, or cells containing nested tables, lists, headings, quotes -or preformatted blocks. Inner simple tables can still produce GFM when their -containing layout table is expanded. Other roles, borders and CSS do not select -another conversion path. Complex layouts remain readable blocks instead of raw -HTML tables. +or preformatted blocks. This retains header, cell and nested-table associations +that Markdown pipe tables cannot express. Inner simple tables can still produce +GFM when an explicitly presentational containing table is expanded. Scripts, +styles and event handlers are omitted from HTML table output. Supported output includes headings, paragraphs, emphasis, strikethrough, links, -images, lists, blockquotes, hard breaks, and fenced code. Inline HTML is used when +images, lists, blockquotes, hard breaks, media source links, separated form choices, +and fenced code. Inline HTML is used when Markdown delimiters cannot express an emphasis boundary. +Superscripts and subscripts retain their HTML markers. Complete author-supplied +TeX spans retain their commands and indices. Native MathML retains mathematical +markup and presentation attributes, with alternate annotations omitted, so +fractions, roots, matrices and powers do not collapse into ambiguous plain text. Script/style/head/noscript/template subtrees are omitted. `max_depth` counts the supplied root as depth zero; nodes at or beyond the limit @@ -89,8 +94,11 @@ spaces and blank lines. Empty blocks still separate surrounding text. This is a structural content dump. It omits non-rendered serialized state blobs but retains content in collapsed panels and inactive tabs. It does not evaluate -stylesheets, layout, or JavaScript, and cannot preserve all HTML presentation (for example, arbitrary -ordered-list numbering or table spanning). DOM snapshots used by Moli's optional +stylesheets, layout, or JavaScript. Callers may supply computed block boundaries +through the optional DOM query. Moli's page exporter additionally filters current +CSS-hidden UI while retaining explicitly linked disclosure content. The converter +cannot preserve all HTML presentation (for example, arbitrary ordered-list numbering). +DOM snapshots used by Moli's optional strip/base/frame transformations remain the responsibility of the caller. ## Verification diff --git a/moli-html2md/src/anchors.rs b/moli-html2md/src/anchors.rs new file mode 100644 index 00000000000..32c790dd268 --- /dev/null +++ b/moli-html2md/src/anchors.rs @@ -0,0 +1,106 @@ +use std::collections::HashSet; + +use crate::{Dom, NodeKind}; + +pub(crate) fn referenced( + dom: &D, + root: D::NodeId, + limit: usize, +) -> HashSet { + let mut ids = HashSet::new(); + if !dom.may_have_fragment_links() { + return ids; + } + walk(dom, root, limit, |node| { + if let Some(fragment) = dom + .attribute(node, "href") + .and_then(|href| href.strip_prefix('#')) + && !fragment.is_empty() + { + ids.insert(decode_fragment(fragment)); + } + false + }); + ids +} + +pub(crate) fn contains( + dom: &D, + root: D::NodeId, + limit: usize, + ids: &HashSet, +) -> bool { + walk(dom, root, limit, |node| { + ["id", "name"] + .iter() + .any(|name| dom.attribute(node, name).is_some_and(|id| ids.contains(id))) + }) +} + +fn walk( + dom: &D, + root: D::NodeId, + limit: usize, + mut found: impl FnMut(D::NodeId) -> bool, +) -> bool { + let mut stack = vec![(Some(root), 0, false)]; + while let Some((node, depth, siblings)) = stack.pop() { + let Some(node) = node else { + continue; + }; + if siblings { + stack.push((dom.next_sibling(node), depth, true)); + } + if depth >= limit { + continue; + } + if matches!( + dom.node_kind(node), + NodeKind::Other + | NodeKind::Element("head" | "script" | "style" | "noscript" | "template") + ) { + continue; + } + if found(node) { + return true; + } + stack.push((dom.first_child(node), depth + 1, true)); + } + false +} + +pub(crate) fn decode_fragment(fragment: &str) -> String { + let bytes = fragment.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut offset = 0; + while offset < bytes.len() { + if bytes[offset] == b'%' && offset + 2 < bytes.len() { + let hex = |byte: u8| (byte as char).to_digit(16); + if let (Some(high), Some(low)) = (hex(bytes[offset + 1]), hex(bytes[offset + 2])) { + decoded.push((high * 16 + low) as u8); + offset += 3; + continue; + } + } + decoded.push(bytes[offset]); + offset += 1; + } + String::from_utf8(decoded).unwrap_or_else(|_| fragment.to_owned()) +} + +pub(crate) fn markup(id: &str) -> String { + let mut result = String::from(" result.push_str("&"), + '"' => result.push_str("""), + '<' => result.push_str("<"), + '>' => result.push_str(">"), + '\n' => result.push_str(" "), + '\r' => result.push_str(" "), + character => result.push(character), + } + } + result.push_str("\">"); + result +} diff --git a/moli-html2md/src/copy_tests.rs b/moli-html2md/src/copy_tests.rs index 9439eecea1a..123fabb65dd 100644 --- a/moli-html2md/src/copy_tests.rs +++ b/moli-html2md/src/copy_tests.rs @@ -28,7 +28,7 @@ fn nested_table_fallback_copies_text_linearly() { assert_eq!(actual.matches(&after).count(), depth); assert_eq!( support::rendered_html(&actual).matches("").count(), - 1 + depth ); // Count actual bytes copied when materializing fragments; completed // blocks move into parents without copying their text. This measures diff --git a/moli-html2md/src/dom.rs b/moli-html2md/src/dom.rs index 583e68467fb..04e82dffcc5 100644 --- a/moli-html2md/src/dom.rs +++ b/moli-html2md/src/dom.rs @@ -26,4 +26,23 @@ pub trait Dom { fn first_child(&self, node: Self::NodeId) -> Option; fn next_sibling(&self, node: Self::NodeId) -> Option; fn attribute(&self, node: Self::NodeId, name: &str) -> Option<&str>; + + /// A caller with computed CSS can retain block boundaries introduced by + /// stylesheets (for example, links rendered as separate action buttons). + /// Structural-only adapters can leave this at its default. + fn has_block_layout(&self, _node: Self::NodeId) -> bool { + false + } + + /// A caller with computed CSS can retain boundaries between independent + /// inline boxes such as tabs, badges, and compact action controls. + fn has_text_boundary(&self, _node: Self::NodeId) -> bool { + false + } + + /// Adapters that already inventory elements can skip the anchor prepass + /// when the document contains no local-fragment links. + fn may_have_fragment_links(&self) -> bool { + true + } } diff --git a/moli-html2md/src/form.rs b/moli-html2md/src/form.rs new file mode 100644 index 00000000000..418e5fc5725 --- /dev/null +++ b/moli-html2md/src/form.rs @@ -0,0 +1,43 @@ +use std::borrow::Cow; + +use crate::Dom; + +pub(crate) fn input_text<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option> { + let kind = dom.attribute(node, "type").unwrap_or("text"); + if kind.eq_ignore_ascii_case("checkbox") || kind.eq_ignore_ascii_case("radio") { + return Some(Cow::Borrowed(if dom.attribute(node, "checked").is_some() { + "☑" + } else { + "☐" + })); + } + if ["hidden", "file"] + .iter() + .any(|excluded| kind.eq_ignore_ascii_case(excluded)) + { + return None; + } + if kind.eq_ignore_ascii_case("image") { + return dom + .attribute(node, "alt") + .filter(|value| !value.is_empty()) + .map(Cow::Borrowed); + } + let value = (!kind.eq_ignore_ascii_case("password")) + .then(|| dom.attribute(node, "value")) + .flatten() + .filter(|value| !value.is_empty()) + .or_else(|| { + dom.attribute(node, "placeholder") + .filter(|value| !value.is_empty()) + }) + .or_else(|| { + dom.attribute(node, "aria-label") + .filter(|value| !value.is_empty()) + }) + .or_else(|| { + dom.attribute(node, "title") + .filter(|value| !value.is_empty()) + }); + value.map(Cow::Borrowed) +} diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs new file mode 100644 index 00000000000..6e52b285b3e --- /dev/null +++ b/moli-html2md/src/html_table.rs @@ -0,0 +1,321 @@ +use std::collections::HashSet; + +use crate::{Dom, NodeKind}; + +/// Markdown has no merged cells, nested tables, or block content inside cells. +/// Detect those structures before conversion so a table is traversed at most +/// twice, even when it contains thousands of nested tables. +pub(crate) fn needed( + dom: &D, + root: D::NodeId, + depth: usize, + limit: usize, +) -> bool { + let mut stack = vec![(dom.first_child(root), depth + 1)]; + while let Some((node, depth)) = stack.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + stack.push((dom.next_sibling(node), depth)); + if let NodeKind::Element(tag) = dom.node_kind(node) { + if matches!( + tag, + "table" + | "pre" + | "blockquote" + | "ul" + | "ol" + | "li" + | "hr" + | "h1" + | "h2" + | "h3" + | "h4" + | "h5" + | "h6" + ) { + return true; + } + if matches!(tag, "td" | "th") + && ["rowspan", "colspan"].iter().any(|attr| { + dom.attribute(node, attr) + .is_some_and(|value| value.trim().parse::() != Ok(1)) + }) + { + return true; + } + } + stack.push((dom.first_child(node), depth + 1)); + } + false +} + +pub(crate) fn has_cells( + dom: &D, + root: D::NodeId, + depth: usize, + limit: usize, +) -> bool { + let mut stack = vec![(dom.first_child(root), depth + 1)]; + while let Some((node, depth)) = stack.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + if matches!(dom.node_kind(node), NodeKind::Element("th" | "td")) { + return true; + } + stack.push((dom.next_sibling(node), depth)); + stack.push((dom.first_child(node), depth + 1)); + } + false +} + +enum Task { + Node(Id, usize), + Siblings(Option, usize), + Close(String), +} + +/// A compact HTML block is valid Markdown and preserves the original cell +/// associations. Keep content markup only; scripts, styles, event handlers +/// and unrelated presentation attributes are never copied. +pub(crate) fn render( + dom: &D, + root: D::NodeId, + depth: usize, + limit: usize, + anchor_targets: &HashSet, +) -> String { + let mut output = String::new(); + let mut emitted_anchors = HashSet::new(); + let mut tasks = vec![Task::Node(root, depth)]; + while let Some(task) = tasks.pop() { + match task { + Task::Close(tag) => { + output.push_str("'); + } + Task::Siblings(None, _) => {} + Task::Siblings(Some(node), depth) => { + tasks.push(Task::Siblings(dom.next_sibling(node), depth)); + tasks.push(Task::Node(node, depth)); + } + Task::Node(node, depth) => { + if depth >= limit { + continue; + } + let anchor = ["id", "name"].iter().find_map(|name| { + dom.attribute(node, name) + .filter(|id| anchor_targets.contains(*id)) + }); + if let (NodeKind::Element(tag), Some(id)) = (dom.node_kind(node), anchor) + && !allowed(tag) + && emitted_anchors.insert(id) + { + output.push_str(&crate::anchors::markup(id)); + } + match dom.node_kind(node) { + NodeKind::Text(text) => escape(text, &mut output), + NodeKind::Element( + "head" | "title" | "script" | "style" | "noscript" | "template", + ) + | NodeKind::Other => {} + NodeKind::Element("math") => { + output.push_str(&crate::mathml::render(dom, node, limit - depth)) + } + NodeKind::Element("input") => { + if let Some(value) = crate::form::input_text(dom, node) { + escape(&value, &mut output); + } + } + NodeKind::Element(tag) => { + if crate::visibility::nonrendered_serialized_state(dom, node) { + continue; + } + if matches!(tag, "iframe" | "video" | "audio") { + let urls = crate::media::sources(dom, node, tag, depth, limit); + if !urls.is_empty() { + output.push_str("
"); + if tag == "video" + && let Some(poster) = dom + .attribute(node, "poster") + .filter(|src| crate::media::safe_url(src, true)) + { + output.push_str("\"\""); + } + for url in urls + .into_iter() + .filter(|url| crate::media::safe_url(url, false)) + { + output.push_str(""); + escape(crate::media::label(dom, node, tag), &mut output); + output.push_str("
"); + } + output.push_str("
"); + continue; + } + } + let retained = if allowed(tag) { + Some(tag) + } else if dom.has_block_layout(node) { + Some("div") + } else { + None + }; + if dom.has_block_layout(node) + && matches!( + retained, + Some( + "a" | "span" + | "strong" + | "b" + | "em" + | "i" + | "s" + | "del" + | "sup" + | "sub" + | "code" + | "img" + | "select" + | "button" + ) + ) + { + output.push_str("
"); + tasks.push(Task::Close("div".to_owned())); + } + if let Some(tag) = retained { + output.push('<'); + output.push_str(tag); + for name in [ + "rowspan", "colspan", "scope", "headers", "id", "href", "src", + "alt", "title", "start", "reversed", "value", "label", "selected", + "multiple", "disabled", "name", + ] { + let image_source = if name == "src" && tag == "img" { + crate::media::source(dom, node) + } else { + None + }; + let value = if name == "src" && tag == "img" { + image_source.as_deref() + } else { + dom.attribute(node, name) + }; + if let Some(value) = value { + if matches!(name, "href" | "src") + && !crate::media::safe_url(value, name == "src") + { + continue; + } + output.push(' '); + output.push_str(name); + output.push_str("=\""); + escape(value, &mut output); + output.push('"'); + } + } + output.push('>'); + if !matches!(tag, "br" | "hr" | "img") { + tasks.push(Task::Close(tag.to_owned())); + } + } + if let Some((math, relative_depth)) = + crate::mathml::primary_alternative(dom, node, limit - depth) + { + output.push_str(&crate::mathml::render( + dom, + math, + limit - depth - relative_depth, + )); + } else { + tasks.push(Task::Siblings(dom.first_child(node), depth + 1)); + } + } + NodeKind::Document => { + tasks.push(Task::Siblings(dom.first_child(node), depth + 1)) + } + } + } + } + } + output +} + +fn allowed(tag: &str) -> bool { + matches!( + tag, + "table" + | "thead" + | "tbody" + | "tfoot" + | "tr" + | "td" + | "th" + | "caption" + | "select" + | "optgroup" + | "option" + | "button" + | "p" + | "div" + | "span" + | "a" + | "img" + | "br" + | "hr" + | "strong" + | "b" + | "em" + | "i" + | "s" + | "del" + | "sup" + | "sub" + | "code" + | "pre" + | "blockquote" + | "ul" + | "ol" + | "li" + | "h1" + | "h2" + | "h3" + | "h4" + | "h5" + | "h6" + | "dl" + | "dt" + | "dd" + | "details" + | "summary" + ) +} + +fn escape(text: &str, output: &mut String) { + for ch in text.chars() { + match ch { + '&' => output.push_str("&"), + '<' => output.push_str("<"), + '>' => output.push_str(">"), + '"' => output.push_str("""), + // Raw HTML blocks end at an empty Markdown line. Entities preserve + // preformatted line endings without prematurely ending the block. + '\n' => output.push_str(" "), + '\r' => output.push_str(" "), + _ => output.push(ch), + } + } +} diff --git a/moli-html2md/src/lib.rs b/moli-html2md/src/lib.rs index 2562a5125da..5be32fe2c33 100644 --- a/moli-html2md/src/lib.rs +++ b/moli-html2md/src/lib.rs @@ -1,6 +1,12 @@ +mod anchors; mod converter; mod dom; +mod form; +mod html_table; mod machine; +mod math; +mod mathml; +mod media; mod options; mod output; mod table; diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 62ff7cd9ee6..fe780200d0e 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -3,11 +3,14 @@ use crate::table::Table; use crate::visibility::nonrendered_serialized_state; use crate::writer::{Style, Writer, longest_run}; use crate::{Dom, NodeKind, Options}; +use std::collections::HashSet; enum Task<'a, Id> { Visit(Id, usize), Children(Option, usize), Boundary, + ChoiceBoundary, + RestoreSvg(bool), PopStyle, EndLink(usize), EndQuote, @@ -38,6 +41,9 @@ struct Machine<'a, D: Dom + ?Sized> { tables: Vec>, raw: String, serial: usize, + in_svg: bool, + anchor_targets: HashSet, + emitted_anchors: HashSet, } pub(crate) fn convert(dom: &D, root: D::NodeId, options: &Options) -> String { @@ -50,6 +56,9 @@ pub(crate) fn convert(dom: &D, root: D::NodeId, options: &Optio tables: Vec::new(), raw: String::new(), serial: 0, + in_svg: false, + anchor_targets: crate::anchors::referenced(dom, root, options.max_depth), + emitted_anchors: HashSet::new(), }; machine.run(); machine.take_writer().into_string() @@ -69,6 +78,8 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } Task::Children(None, _) | Task::RawChildren(None, _, _) => {} Task::Boundary => self.writer().boundary(2), + Task::ChoiceBoundary => self.writer().boundary(1), + Task::RestoreSvg(previous) => self.in_svg = previous, Task::PopStyle => self.writer().pop_style(), Task::EndLink(serial) => self.writer().end_link(serial), Task::EndQuote => { @@ -187,6 +198,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { if depth >= self.options.max_depth { return; } + if self.dom.has_block_layout(node) { + self.writer().boundary(2); + self.tasks.push(Task::Boundary); + } else if self.dom.has_text_boundary(node) { + self.writer().boundary(1); + self.tasks.push(Task::ChoiceBoundary); + } let tag = match self.dom.node_kind(node) { NodeKind::Document => { self.children(node, depth + 1); @@ -202,11 +220,67 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { if nonrendered_serialized_state(self.dom, node) { return; } - if let Some(table) = self.tables.last_mut() { - table.visit_element(tag); + let tooltip = self + .dom + .attribute(node, "data-toggle") + .is_some_and(|value| value.eq_ignore_ascii_case("tooltip")); + let tooltip_fallback = + if tooltip && !subtree_has_content(self.dom, node, self.options.max_depth - depth) { + self.dom + .attribute(node, "data-original-title") + .filter(|value| !value.trim().is_empty()) + } else { + None + }; + if tooltip && self.dom.attribute(node, "title").is_some() { + self.writer().boundary(1); + self.tasks.push(Task::ChoiceBoundary); + } + if tag == "i" + && self.dom.first_child(node).is_none() + && self.dom.attribute(node, "class").is_some_and(|class| { + class.split_ascii_whitespace().any(|token| { + let token = token.to_ascii_lowercase(); + matches!( + token.as_str(), + "check" | "fa-check" | "icon-check" | "bi-check" + ) + }) + }) + { + self.writer().text("✓"); + return; + } + if tag != "table" + && !matches!( + tag, + "head" | "script" | "style" | "noscript" | "template" | "title" + ) + { + for attribute in ["id", "name"] { + if attribute == "name" && tag != "a" { + continue; + } + if let Some(id) = self.dom.attribute(node, attribute) + && self.anchor_targets.contains(id) + && self.emitted_anchors.insert(id.to_owned()) + { + self.writer().inline_html(&crate::anchors::markup(id)); + } + } } match tag { + "math" => { + let markup = crate::mathml::render(self.dom, node, self.options.max_depth - depth); + self.writer().inline_html(&markup); + return; + } "head" | "script" | "style" | "noscript" | "template" => return, + "title" if !self.in_svg => return, + "svg" | "foreignObject" | "foreignobject" => { + self.tasks.push(Task::RestoreSvg(self.in_svg)); + self.in_svg = tag == "svg"; + } "br" => { self.writer().hard_break(); return; @@ -215,14 +289,29 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.writer().block("---".into(), 2, 2); return; } + "select" | "optgroup" | "option" | "button" | "time" => { + self.writer().boundary(1); + if matches!(tag, "optgroup" | "option") + && let Some(label) = self.dom.attribute(node, "label") + { + self.writer().text(label); + self.writer().boundary(1); + if tag == "option" { + return; + } + } + self.tasks.push(Task::ChoiceBoundary); + } "strong" | "b" => self.style(Style::Strong), "em" | "i" => self.style(Style::Emphasis), "del" | "s" | "strike" => self.style(Style::Strike), + "sup" => self.style(Style::Superscript), + "sub" => self.style(Style::Subscript), "a" => { if let Some(href) = self .dom .attribute(node, "href") - .filter(|href| !href.is_empty()) + .filter(|href| !href.is_empty() && crate::media::safe_url(href, false)) { self.serial += 1; let serial = self.serial; @@ -239,16 +328,55 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { "img" => { let alt = self.dom.attribute(node, "alt").unwrap_or_default(); let title = self.dom.attribute(node, "title"); - if let Some(src) = self - .dom - .attribute(node, "src") - .filter(|src| !src.is_empty()) - { - self.writer().image(alt, src, title); + if let Some(src) = crate::media::source(self.dom, node) { + self.writer().image(alt, &src, title); + } else { + // A failed or absent resource must not erase its textual + // alternative, especially when it is a link's only label. + self.writer().text(alt); + } + return; + } + "input" => { + if let Some(value) = crate::form::input_text(self.dom, node) { + self.writer().text(&value); } return; } + "iframe" | "video" | "audio" => { + if self.media(node, tag, depth) { + return; + } + if is_block(tag) { + self.writer().boundary(2); + self.tasks.push(Task::Boundary); + } + } "code" | "pre" => { + let remaining = self.options.max_depth - depth; + if subtree_has_link(self.dom, node, remaining) + || (!self.anchor_targets.is_empty() + && crate::anchors::contains( + self.dom, + node, + remaining, + &self.anchor_targets, + )) + { + let html = crate::html_table::render( + self.dom, + node, + depth, + self.options.max_depth, + &self.anchor_targets, + ); + if tag == "pre" { + self.writer().block(html.into(), 2, 2); + } else { + self.writer().inline_html(&html); + } + return; + } self.raw.clear(); let end = if tag == "pre" { Task::EndPre(self.language(node)) @@ -266,6 +394,28 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { return; } "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { + let remaining = self.options.max_depth - depth; + if !subtree_has_content(self.dom, node, remaining) { + self.writer().boundary(2); + return; + } + if subtree_has_nested_heading(self.dom, node, remaining) { + self.writer().boundary(2); + self.tasks.push(Task::Boundary); + self.children(node, depth + 1); + return; + } + if subtree_has_block(self.dom, node, remaining) { + let html = crate::html_table::render( + self.dom, + node, + depth, + self.options.max_depth, + &self.anchor_targets, + ); + self.writer().block(html.into(), 2, 2); + return; + } self.capture(); self.writer().heading(); self.tasks @@ -278,6 +428,32 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { "ul" | "ol" => self.start_list(node, tag == "ol"), "li" => self.start_item(), "table" => { + let presentation = self.dom.attribute(node, "role").is_some_and(|role| { + matches!( + role.trim().to_ascii_lowercase().as_str(), + "presentation" | "none" + ) + }); + if (!presentation + && crate::html_table::needed(self.dom, node, depth, self.options.max_depth)) + || (!self.anchor_targets.is_empty() + && crate::anchors::contains( + self.dom, + node, + self.options.max_depth - depth, + &self.anchor_targets, + )) + { + let html = crate::html_table::render( + self.dom, + node, + depth, + self.options.max_depth, + &self.anchor_targets, + ); + self.writer().block(html.into(), 2, 2); + return; + } if let Some(mut table) = Table::from_dom(self.dom, node, depth, self.options.max_depth) { @@ -289,23 +465,95 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } return; } + if !presentation + && crate::html_table::has_cells(self.dom, node, depth, self.options.max_depth) + { + let html = crate::html_table::render( + self.dom, + node, + depth, + self.options.max_depth, + &self.anchor_targets, + ); + self.writer().block(html.into(), 2, 2); + return; + } self.writer().boundary(2); self.tasks.push(Task::Boundary); } + _ if quote_container(tag, self.dom.attribute(node, "class")) => { + self.capture(); + self.tasks.push(Task::EndQuote); + } _ if is_block(tag) => { self.writer().boundary(2); self.tasks.push(Task::Boundary); } _ => {} } + if let Some((math, relative_depth)) = + crate::mathml::primary_alternative(self.dom, node, self.options.max_depth - depth) + { + let markup = crate::mathml::render( + self.dom, + math, + self.options.max_depth - depth - relative_depth, + ); + self.writer().inline_html(&markup); + return; + } + if let Some(value) = tooltip_fallback { + self.writer().text(value); + } else if self.dom.first_child(node).is_none() + && let Some(label) = self + .dom + .attribute(node, "aria-label") + .filter(|label| !label.trim().is_empty()) + { + self.writer().text(label); + return; + } self.children(node, depth + 1); } + fn media(&mut self, node: D::NodeId, tag: &str, depth: usize) -> bool { + let urls = crate::media::sources(self.dom, node, tag, depth, self.options.max_depth); + if urls.is_empty() { + return false; + } + self.writer().boundary(2); + if tag == "video" + && let Some(poster) = self + .dom + .attribute(node, "poster") + .filter(|src| !src.is_empty()) + { + self.writer().image("", poster, None); + self.writer().boundary(1); + } + let label = crate::media::label(self.dom, node, tag); + for href in urls { + self.serial += 1; + let serial = self.serial; + let opened = self.writer().push_style(Style::Link { + serial, + href, + title: None, + }); + self.writer().text(label); + if opened { + self.writer().end_link(serial); + } + self.writer().boundary(1); + } + self.writer().boundary(2); + true + } + fn table_cell(&mut self) { let table = self.tables.last_mut().expect("table conversion is active"); if let Some(cell) = table.next_cell() { self.capture(); - self.writer().table_cell(); self.tasks.push(Task::TableCell); self.tasks.push(Task::EndTableCell); self.children(cell.node, cell.depth + 1); @@ -387,8 +635,17 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { if nonrendered_serialized_state(self.dom, node) { return; } + if self.dom.attribute(node, "class").is_some_and(|class| { + class.split_ascii_whitespace().any(|token| { + let token = token.to_ascii_lowercase(); + token.contains("copy") && (token.contains("btn") || token.contains("button")) + }) + }) { + return; + } match self.dom.node_kind(node) { NodeKind::Text(text) => self.raw.push_str(text), + NodeKind::Element("script" | "style" | "template" | "noscript") => {} // Inline code normalizes line endings to spaces. Keep explicit // breaks without converting descendant formatting into Markdown. NodeKind::Element("br") => self.raw.push('\n'), @@ -449,6 +706,121 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } } +fn quote_container(tag: &str, class: Option<&str>) -> bool { + matches!(tag, "div" | "section" | "article" | "aside") + && class.is_some_and(|class| { + class.split_ascii_whitespace().any(|token| { + matches!( + token.to_ascii_lowercase().as_str(), + "quote" | "quoteblock" | "quote-block" | "quoted-text" + ) + }) + }) +} + +fn subtree_has_content(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = vec![(root, 0)]; + while let Some((node, depth)) = pending.pop() { + match dom.node_kind(node) { + NodeKind::Text(text) if !text.trim_matches(char::is_whitespace).is_empty() => { + return true; + } + NodeKind::Element("img") + if crate::media::source(dom, node).is_some() + || dom + .attribute(node, "alt") + .is_some_and(|alt| !alt.trim().is_empty()) => + { + return true; + } + NodeKind::Element(_) + if dom.first_child(node).is_none() + && dom + .attribute(node, "aria-label") + .is_some_and(|label| !label.trim().is_empty()) => + { + return true; + } + _ => {} + } + if depth + 1 >= limit { + continue; + } + let mut child = dom.first_child(node); + while let Some(id) = child { + pending.push((id, depth + 1)); + child = dom.next_sibling(id); + } + } + false +} + +fn subtree_has_nested_heading(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = Vec::new(); + let mut child = dom.first_child(root); + while let Some(id) = child { + pending.push((id, 1)); + child = dom.next_sibling(id); + } + while let Some((node, depth)) = pending.pop() { + if matches!( + dom.node_kind(node), + NodeKind::Element("h1" | "h2" | "h3" | "h4" | "h5" | "h6") + ) { + return true; + } + if depth + 1 >= limit { + continue; + } + let mut child = dom.first_child(node); + while let Some(id) = child { + pending.push((id, depth + 1)); + child = dom.next_sibling(id); + } + } + false +} + +fn subtree_has_link(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = vec![(dom.first_child(root), 1)]; + while let Some((node, depth)) = pending.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + pending.push((dom.next_sibling(node), depth)); + if matches!(dom.node_kind(node), NodeKind::Element("a")) + && dom + .attribute(node, "href") + .is_some_and(|href| !href.is_empty() && crate::media::safe_url(href, false)) + { + return true; + } + pending.push((dom.first_child(node), depth + 1)); + } + false +} + +fn subtree_has_block(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = vec![(dom.first_child(root), 1)]; + while let Some((node, depth)) = pending.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + pending.push((dom.next_sibling(node), depth)); + if matches!(dom.node_kind(node), NodeKind::Element(tag) if is_structural_block(tag)) { + return true; + } + pending.push((dom.first_child(node), depth + 1)); + } + false +} + fn class_language(class: Option<&str>) -> Option<&str> { class? .split_ascii_whitespace() diff --git a/moli-html2md/src/math.rs b/moli-html2md/src/math.rs new file mode 100644 index 00000000000..0358d4b2bb9 --- /dev/null +++ b/moli-html2md/src/math.rs @@ -0,0 +1,79 @@ +/// Locate a complete author-supplied TeX span before ordinary Markdown escaping. +/// Dollar boundaries follow the usual non-space/non-digit rules, so prices do +/// not consume the prose between two currency amounts. +pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { + let bytes = text.as_bytes(); + let mut index = 0; + while index < bytes.len() { + let (open, close, single_dollar) = if bytes[index] == b'$' && !escaped(bytes, index) { + if bytes.get(index + 1) == Some(&b'$') { + (2, "$$", false) + } else { + (1, "$", true) + } + } else if bytes[index] == b'\\' && !escaped(bytes, index) { + match bytes.get(index + 1) { + Some(b'(') => (2, "\\)", false), + Some(b'[') => (2, "\\]", false), + _ => { + index += 1; + continue; + } + } + } else { + index += 1; + continue; + }; + let content_start = index + open; + if single_dollar + && text[content_start..] + .chars() + .next() + .is_none_or(char::is_whitespace) + { + index = content_start; + continue; + } + let mut search = content_start; + while let Some(relative) = text[search..].find(close) { + let end = search + relative; + search = end + close.len(); + if escaped(bytes, end) { + continue; + } + if end == content_start { + break; + } + if single_dollar + && (text[..end] + .chars() + .next_back() + .is_some_and(char::is_whitespace) + || bytes.get(end + 1).is_some_and(u8::is_ascii_digit)) + { + break; + } + // A plain Markdown reader must never reinterpret source text as + // executable HTML merely because it was surrounded by dollars. + if bytes[content_start..end].windows(2).any(|pair| { + pair[0] == b'<' + && (pair[1].is_ascii_alphabetic() || matches!(pair[1], b'/' | b'!' | b'?')) + }) { + break; + } + return Some((index, search)); + } + index = search.max(content_start); + } + None +} + +fn escaped(bytes: &[u8], index: usize) -> bool { + bytes[..index] + .iter() + .rev() + .take_while(|&&ch| ch == b'\\') + .count() + % 2 + == 1 +} diff --git a/moli-html2md/src/mathml.rs b/moli-html2md/src/mathml.rs new file mode 100644 index 00000000000..d86facd9cd2 --- /dev/null +++ b/moli-html2md/src/mathml.rs @@ -0,0 +1,214 @@ +use crate::{Dom, NodeKind}; + +/// Math renderers often pair semantic MathML with an aria-hidden visual copy. +/// Recognize that relationship from markup, independently of library classes. +pub(crate) fn primary_alternative( + dom: &D, + node: D::NodeId, + limit: usize, +) -> Option<(D::NodeId, usize)> { + let mut primary = None; + let mut alternative = false; + let mut child = dom.first_child(node); + while let Some(id) = child { + child = dom.next_sibling(id); + if ignorable(dom.node_kind(id)) { + continue; + } + if dom + .attribute(id, "aria-hidden") + .is_some_and(|value| value.eq_ignore_ascii_case("true")) + { + alternative = true; + continue; + } + if primary.is_some() { + return None; + } + let mut candidate = id; + let mut found = None; + // Bound wrapper inspection per node; deeply nested ordinary prose must + // not cause repeated whole-subtree scans. + for depth in 1..limit.min(9) { + if dom.node_kind(candidate) == NodeKind::Element("math") { + found = Some((candidate, depth)); + break; + } + let mut children = dom.first_child(candidate); + let mut single = None; + while let Some(id) = children { + children = dom.next_sibling(id); + if ignorable(dom.node_kind(id)) { + continue; + } + if single.is_some() { + return None; + } + single = Some(id); + } + candidate = single?; + } + primary = Some(found?); + } + if alternative { primary } else { None } +} + +fn ignorable(kind: NodeKind<'_>) -> bool { + matches!(kind, NodeKind::Other) + || matches!(kind, NodeKind::Text(text) if text.trim().is_empty()) +} + +enum Task { + Node(Id, usize), + Sibling(Option, usize), + Close(String), +} + +/// Keep native mathematical structure instead of inventing a lossy plain-text +/// equation. Only mathematical markup and presentation attributes survive; +/// alternate encodings, HTML, scripts and event handlers cannot become active. +pub(crate) fn render(dom: &D, root: D::NodeId, max_depth: usize) -> String { + let mut output = String::new(); + let mut tasks = vec![Task::Node(root, 0)]; + while let Some(task) = tasks.pop() { + match task { + Task::Close(tag) => { + output.push_str("'); + } + Task::Sibling(Some(node), depth) => { + tasks.push(Task::Sibling(dom.next_sibling(node), depth)); + tasks.push(Task::Node(node, depth)); + } + Task::Sibling(None, _) => {} + Task::Node(node, depth) => { + if depth >= max_depth { + continue; + } + match dom.node_kind(node) { + NodeKind::Text(text) => escape(text, &mut output), + NodeKind::Element("annotation" | "annotation-xml" | "script" | "style") => {} + NodeKind::Element("semantics") => { + // Presentation is the first child; subsequent annotation + // children are alternate representations, not more terms. + let mut child = dom.first_child(node); + while let Some(id) = child { + if matches!(dom.node_kind(id), NodeKind::Element(_)) { + tasks.push(Task::Node(id, depth + 1)); + break; + } + child = dom.next_sibling(id); + } + } + NodeKind::Element(tag) => { + if allowed_tag(tag) { + output.push('<'); + output.push_str(tag); + for name in ATTRIBUTES { + if let Some(value) = dom.attribute(node, name) { + output.push(' '); + output.push_str(name); + output.push_str("=\""); + escape(value, &mut output); + output.push('"'); + } + } + output.push('>'); + tasks.push(Task::Close(tag.to_owned())); + } + tasks.push(Task::Sibling(dom.first_child(node), depth + 1)); + } + NodeKind::Document => { + tasks.push(Task::Sibling(dom.first_child(node), depth + 1)); + } + NodeKind::Other => {} + } + } + } + } + output +} + +fn allowed_tag(tag: &str) -> bool { + matches!( + tag, + "math" + | "mi" + | "mn" + | "mo" + | "mtext" + | "ms" + | "mspace" + | "mrow" + | "mfrac" + | "msqrt" + | "mroot" + | "mstyle" + | "merror" + | "mpadded" + | "mphantom" + | "mfenced" + | "menclose" + | "msub" + | "msup" + | "msubsup" + | "munder" + | "mover" + | "munderover" + | "mmultiscripts" + | "mprescripts" + | "none" + | "mtable" + | "mtr" + | "mlabeledtr" + | "mtd" + | "maligngroup" + | "malignmark" + ) +} + +const ATTRIBUTES: &[&str] = &[ + "display", + "mathvariant", + "displaystyle", + "scriptlevel", + "linethickness", + "bevelled", + "open", + "close", + "separators", + "notation", + "accent", + "accentunder", + "stretchy", + "symmetric", + "largeop", + "movablelimits", + "form", + "fence", + "separator", + "rowspan", + "columnspan", + "rowalign", + "columnalign", + "rowlines", + "columnlines", + "lquote", + "rquote", +]; + +fn escape(text: &str, output: &mut String) { + for ch in text.chars() { + match ch { + '&' => output.push_str("&"), + '<' => output.push_str("<"), + '>' => output.push_str(">"), + '"' => output.push_str("""), + // Keep an inline HTML fragment on one Markdown line, even when the + // source's pretty printing contains blank lines. + '\n' | '\r' | '\t' => output.push(' '), + _ => output.push(ch), + } + } +} diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs new file mode 100644 index 00000000000..f98d8e59d21 --- /dev/null +++ b/moli-html2md/src/media.rs @@ -0,0 +1,116 @@ +use std::borrow::Cow; + +use crate::{Dom, NodeKind}; + +/// Frozen DOMs can still carry lazy-loading placeholders. These conventional +/// attributes declare the resource the page intends to load, not the spacer. +pub(crate) fn source<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option> { + if let Some(value) = direct_source(dom, node) { + return Some(Cow::Borrowed(value)); + } + + // A responsive image may intentionally leave `src` empty. Retain the + // largest declared candidate so the image does not disappear entirely. + ["data-srcset", "srcset"].into_iter().find_map(|name| { + dom.attribute(node, name) + .and_then(largest_srcset_candidate) + .filter(|value| safe_url(value, true)) + .map(|value| Cow::Owned(value.to_owned())) + }) +} + +fn direct_source(dom: &D, node: D::NodeId) -> Option<&str> { + let usable = |value: &&str| { + !value.is_empty() + && !value.starts_with('#') + && *value != "about:blank" + && safe_url(value, true) + }; + let attr = |name| dom.attribute(node, name).map(str::trim).filter(usable); + + if let Some(value) = attr("data-original") { + return Some(value); + } + let src = attr("src"); + if let Some(value) = src.filter(|value| !is_placeholder_source(value)) { + return Some(value); + } + attr("data-src").or_else(|| attr("data-lazy-src")).or(src) +} + +fn is_placeholder_source(value: &str) -> bool { + let lower = value.to_ascii_lowercase(); + lower.starts_with("data:image/") + || [ + "placeholder", + "spacer", + "transparent", + "blank.gif", + "blank.png", + ] + .iter() + .any(|marker| lower.contains(marker)) +} + +fn largest_srcset_candidate(srcset: &str) -> Option<&str> { + srcset + .split(',') + .filter_map(|candidate| candidate.split_ascii_whitespace().next()) + .rfind(|url| !url.is_empty()) +} + +pub(crate) fn safe_url(value: &str, image: bool) -> bool { + let normalized: String = value + .trim() + .chars() + .filter(|ch| !ch.is_ascii_control()) + .collect(); + let Some((scheme, _)) = normalized.split_once(':') else { + return true; + }; + if scheme.contains(['/', '#', '?']) { + return true; + } + matches!( + scheme.to_ascii_lowercase().as_str(), + "http" | "https" | "mailto" | "tel" | "ftp" + ) || (image && normalized.to_ascii_lowercase().starts_with("data:image/")) +} + +pub(crate) fn sources<'a, D: Dom + ?Sized>( + dom: &'a D, + node: D::NodeId, + tag: &str, + depth: usize, + limit: usize, +) -> Vec<&'a str> { + let mut urls = Vec::new(); + let mut seen = std::collections::HashSet::new(); + if let Some(src) = direct_source(dom, node) { + seen.insert(src); + urls.push(src); + } + if tag != "iframe" && depth + 1 < limit { + let mut child = dom.first_child(node); + while let Some(id) = child { + child = dom.next_sibling(id); + if dom.node_kind(id) == NodeKind::Element("source") + && let Some(src) = direct_source(dom, id) + && seen.insert(src) + { + urls.push(src); + } + } + } + urls +} + +pub(crate) fn label<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId, tag: &str) -> &'a str { + dom.attribute(node, "title") + .filter(|label| !label.trim().is_empty()) + .unwrap_or(match tag { + "video" => "Video", + "audio" => "Audio", + _ => "Embedded content", + }) +} diff --git a/moli-html2md/src/table.rs b/moli-html2md/src/table.rs index f29e72208ea..6a4ee474053 100644 --- a/moli-html2md/src/table.rs +++ b/moli-html2md/src/table.rs @@ -10,7 +10,6 @@ pub(crate) struct Table { cells: std::vec::IntoIter>, content: Vec, in_cell: bool, - has_complex_content: bool, rows: Vec, separators: Vec<&'static str>, has_header: bool, @@ -37,7 +36,6 @@ impl Table { cells: Vec::new().into_iter(), content: Vec::new(), in_cell: false, - has_complex_content: false, rows: Vec::new(), separators: Vec::new(), has_header: false, @@ -166,39 +164,9 @@ impl Table { self.in_cell = false; } - pub(crate) fn visit_element(&mut self, tag: &str) { - if self.in_cell - && matches!( - tag, - "table" - | "pre" - | "blockquote" - | "ul" - | "ol" - | "li" - | "hr" - | "h1" - | "h2" - | "h3" - | "h4" - | "h5" - | "h6" - ) - { - self.has_complex_content = true; - } - } - pub(crate) fn finish(self) -> Output { - if self.has_complex_content { - let mut output = Output::default(); - for cell in self.content.into_iter().filter(|cell| !cell.is_empty()) { - if !output.is_empty() { - output.push_text("\n\n".into()); - } - output.append(cell); - } - return output; + if self.content.iter().all(Output::is_empty) { + return Output::default(); } let mut output = String::new(); if !self.has_header { diff --git a/moli-html2md/src/writer.rs b/moli-html2md/src/writer.rs index 7417fdf72c5..26a44260b9f 100644 --- a/moli-html2md/src/writer.rs +++ b/moli-html2md/src/writer.rs @@ -7,6 +7,8 @@ pub(crate) enum Style<'a> { Strong, Emphasis, Strike, + Superscript, + Subscript, Link { // Distinguish adjacent links even when their destinations match. serial: usize, @@ -38,7 +40,6 @@ pub(crate) struct Writer<'a> { markdown_code_end: Option, line_digits: Option, heading: bool, - single_line_attributes: bool, pub(crate) last_link: usize, // Block events in this output buffer, used when finalizing a list item. pub(crate) has_blocks: bool, @@ -52,25 +53,18 @@ impl<'a> Writer<'a> { pub(crate) fn child(&self) -> Self { Self { desired: self.desired.clone(), - single_line_attributes: self.single_line_attributes, ..Self::default() } } pub(crate) fn heading(&mut self) { self.heading = true; - self.single_line_attributes = true; - } - - pub(crate) fn table_cell(&mut self) { - // Literal attribute newlines must not split a Markdown table row. - self.single_line_attributes = true; } pub(crate) fn push_style(&mut self, style: Style<'a>) -> bool { // Repeated emphasis has the same visible meaning. Nested links cannot // be represented in Markdown, so retain the outer destination. - if self.desired.contains(&style) + if self.desired.contains(&style) && !matches!(style, Style::Superscript | Style::Subscript) || matches!(style, Style::Link { .. }) && self.desired.iter().any(|s| matches!(s, Style::Link { .. })) { @@ -98,6 +92,28 @@ impl<'a> Writer<'a> { pub(crate) fn text(&mut self, text: &str) { self.flush_code(); + let mut remaining = text; + while let Some((start, end)) = crate::math::next_span(remaining) { + self.plain_text(&remaining[..start]); + let math = &remaining[start..end]; + self.prepare_inline(math.chars().next().expect("nonempty math span")); + // TeX commands, indices and alignment characters carry meaning; + // CommonMark escaping changes that meaning in math-aware readers. + self.output.push_str(math); + self.line_digits = None; + remaining = &remaining[end..]; + } + self.plain_text(remaining); + } + + pub(crate) fn inline_html(&mut self, markup: &str) { + self.flush_code(); + self.prepare_inline('<'); + self.output.push_str(markup); + self.line_digits = None; + } + + fn plain_text(&mut self, text: &str) { for ch in text.chars() { if is_space(ch) { self.space = true; @@ -214,14 +230,13 @@ impl<'a> Writer<'a> { self.output.push(ch); } '&' => self.output.push_str("&"), - // Markdown image labels render soft breaks as spaces. Keep - // that meaning when a heading flattens its content. - '\n' if self.single_line_attributes => self.output.push(' '), + // Keep label line breaks from opening Markdown block syntax. + '\n' => self.output.push(' '), _ => self.output.push(ch), } } self.output.push_str("]("); - destination(&mut self.output, src, title, self.single_line_attributes); + destination(&mut self.output, src, title); self.output.push(')'); self.line_digits = None; } @@ -311,13 +326,21 @@ impl<'a> Writer<'a> { let first = if link.is_some_and(|link| index < link) { '[' } else { - next + match self.desired.get(index + 1) { + Some(Style::Strong | Style::Emphasis) => '*', + Some(Style::Strike) => '~', + Some(Style::Superscript | Style::Subscript) => '<', + Some(Style::Link { .. }) => '[', + None => next, + } }; let html = is_punctuation(first) && self.last_char().is_some_and(char::is_alphanumeric); match style { Style::Strong => self.output.push_str(if html { "" } else { "**" }), Style::Emphasis => self.output.push_str(if html { "" } else { "*" }), Style::Strike => self.output.push_str(if html { "" } else { "~~" }), + Style::Superscript => self.output.push_str(""), + Style::Subscript => self.output.push_str(""), Style::Link { serial, .. } => { self.last_link = self.last_link.max(serial); if self.output.ends_with('!') { @@ -364,9 +387,18 @@ impl<'a> Writer<'a> { Style::Strong => Some(("**", "", "")), Style::Emphasis => Some(("*", "", "")), Style::Strike => Some(("~~", "", "")), + Style::Superscript | Style::Subscript => { + self.output.push_str(if opened.style == Style::Superscript { + "" + } else { + "" + }); + closing_run = None; + None + } Style::Link { href, title, .. } => { self.output.push_str("]("); - destination(&mut self.output, href, title, self.single_line_attributes); + destination(&mut self.output, href, title); self.output.push(')'); closing_run = None; None @@ -386,8 +418,10 @@ impl<'a> Writer<'a> { } _ => self.last_char(), }; - let closing_needs_html = next.is_some_and(char::is_alphanumeric) - && preceding.is_some_and(is_punctuation); + let closing_needs_html = (opened.has_closed_child + && closing_run.is_some_and(|(previous, _)| previous == marker_byte)) + || (next.is_some_and(char::is_alphanumeric) + && preceding.is_some_and(is_punctuation)); if opened.html || closing_needs_html { if !opened.html { // Only the converter's output changes. Remaining open @@ -502,7 +536,7 @@ pub(crate) fn longest_run(text: &str, marker: char) -> usize { longest } -fn destination(output: &mut String, href: &str, title: Option<&str>, single_line: bool) { +fn destination(output: &mut String, href: &str, title: Option<&str>) { for ch in href.chars() { match ch { '\\' | '(' | ')' => { @@ -528,8 +562,8 @@ fn destination(output: &mut String, href: &str, title: Option<&str>, single_line output.push(ch); } '&' => output.push_str("&"), - // Protect title newlines from heading line flattening. - '\n' if single_line => output.push_str(" "), + // Preserve the attribute value without opening Markdown blocks. + '\n' => output.push_str(" "), _ => output.push(ch), } } diff --git a/moli-html2md/tests/conversion.rs b/moli-html2md/tests/conversion.rs index 13d0740c0f6..2238d5d5b06 100644 --- a/moli-html2md/tests/conversion.rs +++ b/moli-html2md/tests/conversion.rs @@ -1,4 +1,5 @@ use moli_html2md::{Converter, Dom, NodeKind, Options, convert}; +mod support; // A second DOM implementation, independent of NativeDom or an HTML parser. // Its stable arena IDs and borrowed strings are enough for the converter. @@ -304,7 +305,9 @@ fn table_spans_do_not_duplicate_cell_text() { let row = dom.element(table, "tr"); let cell = dom.leaf(row, "td", "end"); dom.attr(cell, "colspan", "999999999999"); - assert_eq!(convert(&dom, 0), "one\n\ntwo\n\nend"); + let result = convert(&dom, 0); + assert!(result.contains("rowspan=\"2\">one
")); + assert!(result.contains("colspan=\"999999999999\">end")); } #[test] @@ -381,7 +384,9 @@ fn converts_deep_tables_on_a_small_thread_stack() { max_depth: usize::MAX, ..Options::default() }); - assert_eq!(converter.convert(&dom, 0), "| |\n| --- |\n| deep |"); + let result = converter.convert(&dom, 0); + assert_eq!(result.matches("
two
").count(), 10_000); + assert_eq!(result.matches("deep").count(), 1); }) .expect("spawn small-stack test") .join() @@ -409,8 +414,8 @@ fn converts_nested_header_tables_on_a_small_thread_stack() { }); let actual = converter.convert(&dom, 0); assert_eq!(actual.matches("Header").count(), 1_000); - assert_eq!(actual.matches("| --- |").count(), 1); - assert!(actual.ends_with("| deep |")); + assert_eq!(actual.matches("
").count(), 1_000); + assert_eq!(actual.matches("deep").count(), 1); }) .expect("spawn small-stack test") .join() @@ -508,10 +513,15 @@ fn markdown_parser_recovers_pipes_and_preformatted_code_inside_tables() { let cell = dom.element(row, "td"); dom.leaf(cell, "pre", " |b\nnext\n"); let markdown = convert(&dom, 0); - let html = rendered_html(&markdown); - assert_eq!( - html, - "

Code

\n

a|b

\n
  <a>|b\nnext\n
\n", - "{markdown}" + let html = support::rendered_html(&markdown); + assert!(html.contains("a|b"), "{html}"); + assert_eq!(html.matches("
"), "{html}"); + assert!( + html.contains(""), + "{html}" + ); + assert_eq!(html.matches(">Group<").count(), 1); +} + +#[test] +fn nested_tables_stay_with_their_column_labels() { + let source = "
").count(), 2); + let parsed = support::Tree::parse(&html); + assert!( + parsed + .nodes + .iter() + .any(|node| node.text.as_deref() == Some(" |b\nnext\n")), + "{html}" ); } diff --git a/moli-html2md/tests/inline_boundaries.rs b/moli-html2md/tests/inline_boundaries.rs index 51fe74785ac..fc45b31df12 100644 --- a/moli-html2md/tests/inline_boundaries.rs +++ b/moli-html2md/tests/inline_boundaries.rs @@ -20,7 +20,6 @@ fn inline_code_breaks_separate_words_without_formatting_markers() { for html in [ "git
status
", "git
status
", - "
git
status
", ] { for preformatted_code in [false, true] { let result = markdown_with( diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index f5e12486a8b..88bb7e28e2f 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -12,6 +12,278 @@ fn markdown(html: &str, preformatted_code: bool) -> String { .convert(&dom, dom.root) } +#[test] +fn scientific_indices_keep_their_meaning_in_markdown() { + let result = markdown( + "

Water H2O; area x2; note1.

", + false, + ); + assert!(result.contains("H2O"), "{result}"); + assert!(result.contains("x2"), "{result}"); + let html = rendered_html(&result); + assert!(html.contains("1"), "{html}"); +} + +#[test] +fn tex_math_keeps_commands_indices_and_matrix_separators() { + let source = r"

Model $x_i^2 + \alpha$ and $$\begin{matrix} a & b \\ c & d \end{matrix}$$.

"; + let result = markdown(source, false); + assert!(result.contains(r"$x_i^2 + \alpha$"), "{result}"); + assert!( + result.contains(r"$$\begin{matrix} a & b \\ c & d \end{matrix}$$"), + "{result}" + ); +} + +#[test] +fn math_recognition_does_not_reinterpret_prices_or_literal_code() { + let result = markdown( + r"

Pay $5 for a_b and $10 for c_d; $x_i$; $unfinished_name

", + false, + ); + assert!(result.contains(r"$5 for a\_b and $10 for c\_d"), "{result}"); + assert!(result.contains("`$x_i$`"), "{result}"); + assert!(result.contains(r"$unfinished\_name"), "{result}"); + let result = markdown(r"

括号 \(x_i + \alpha\);方括号 \[y_1=2\]。

", false); + assert!(result.contains(r"\(x_i + \alpha\)"), "{result}"); + assert!(result.contains(r"\[y_1=2\]"), "{result}"); +} + +#[test] +fn dollar_wrapped_literal_html_remains_inert_without_a_math_extension() { + let result = markdown(r"

$<img src=x onerror=alert(1)>_i$

", false); + let html = rendered_html(&result); + assert!(!html.contains("$x_i + \alpha$

", false); + let payloads: Vec<_> = Parser::new_ext(&result, MarkdownOptions::ENABLE_MATH) + .filter_map(|event| match event { + Event::InlineMath(text) => Some(text.into_string()), + _ => None, + }) + .collect(); + assert_eq!(payloads, [r"x_i + \alpha"]); +} + +#[test] +fn mathematical_structures_survive_markdown_rendering() { + let source = "

Rate dQdt=x2+y.

"; + let result = markdown(source, false); + let html = rendered_html(&result); + for structure in [ + "dQdt", + "x2", + "y", + ] { + assert!(html.contains(structure), "{html}"); + } +} + +#[test] +fn nested_powers_retain_each_level() { + let result = markdown( + "

xy2 + abi

", + false, + ); + assert!(result.contains("xy2"), "{result}"); + assert!(result.contains("abi"), "{result}"); +} + +#[test] +fn body_metadata_does_not_become_article_text() { + let result = markdown( + "

News

Actual story

Untitled templatePublisher
", + false, + ); + assert!(result.contains("Actual story")); + assert!(result.contains("Publisher")); + assert!(!result.contains("Untitled template"), "{result}"); + let graphic = markdown( + "Chart descriptionRevenueTemplate metadata", + false, + ); + assert!(graphic.contains("Chart description"), "{graphic}"); + assert!(graphic.contains("Revenue"), "{graphic}"); + assert!(!graphic.contains("Template metadata"), "{graphic}"); +} + +#[test] +fn empty_layout_tables_do_not_invent_data() { + let result = markdown( + "

Article

Video unavailable
MetricValue
Rate
", + false, + ); + assert!(result.contains("Video unavailable"), "{result}"); + assert!(!result.contains("| |\n| --- |\n| |"), "{result}"); + assert!(result.contains("| Rate | |"), "{result}"); +} + +#[test] +fn form_choices_keep_option_and_group_boundaries() { + let result = markdown( + "", + false, + ); + assert!(result.contains("All posts\n"), "{result}"); + assert!(result.contains("Recent\n1 day\n1 week"), "{result}"); + assert!(!result.contains("Internal long label"), "{result}"); + assert_eq!(markdown("

website

", false), "website"); +} + +#[test] +fn embedded_media_retains_usable_sources() { + let result = markdown( + "

Watch the interview:

End.

", + false, + ); + for link in [ + "[Interview](https://video.example/embed/42)", + "(/movie.webm)", + "(/movie.mp4)", + "[Episode](/episode.ogg)", + "(/cover.jpg)", + ] { + assert!(result.contains(link), "{result}"); + } + assert_eq!(result.matches("(/movie.mp4)").count(), 1, "{result}"); + assert!(result.ends_with("End."), "{result}"); +} + +#[test] +fn responsive_image_without_src_retains_largest_candidate() { + assert_eq!( + markdown( + "Course cover", + false, + ), + "![Course cover](//cdn.example/cover-500.jpg)" + ); +} + +#[test] +fn concrete_loaded_image_wins_over_an_unexpanded_lazy_template() { + let result = markdown( + "Basin", + false, + ); + assert_eq!(result, "![Basin](https://cdn.example/basin_300x.jpg)"); +} + +#[test] +fn lazy_media_uses_declared_resources_instead_of_spacers() { + let source = "OneTwo"; + let result = markdown(source, false); + for target in [ + "(/photo-one.jpg)", + "(/photo-two.jpg)", + "(//video.example/lecture)", + "(/ordinary.jpg)", + ] { + assert!(result.contains(target), "{result}"); + } + assert!(!result.contains("placeholder"), "{result}"); + let table = markdown( + "
Photo
", + false, + ); + assert!(table.contains("src=\"/actual.jpg\""), "{table}"); + assert!(!table.contains("spacer.gif"), "{table}"); +} + +#[test] +fn merged_cells_keep_calendar_and_group_associations() { + let source = "
MonTueWed
1
GroupA
B
"; + let result = markdown(source, false); + let html = rendered_html(&result); + assert!(html.contains("
1GroupA
TodayMonth
Alice20
Bob100
"; + let html = rendered_html(&markdown(source, false)); + assert!(html.contains("TodayMonth"), "{html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); +} + +#[test] +fn complex_tables_keep_media_choices_and_literal_content_inert() { + let source = "
Alice20Bob100
<script>literal</script>\n\nline
Bad link
"; + let html = rendered_html(&markdown(source, false)); + assert!(html.contains("href=\"/lecture\">Lecture
"), "{html}"); + assert!( + html.contains(""), + "{html}" + ); + assert!( + html.contains("<script>literal</script>"), + "{html}" + ); + assert!(!html.contains("onclick"), "{html}"); + assert!(!html.contains("", + false, + ); + assert!(result.contains("run();"), "{result}"); + assert!(!result.contains("Copy code"), "{result}"); + assert!(!result.contains("advert"), "{result}"); +} + +#[test] +fn block_content_inside_heading_keeps_its_own_boundary() { + let result = markdown( + "

Concept title
Resource Information

Long explanation.

", + false, + ); + assert!(result.contains("

Concept titleResource Information"), + "{result}" + ); + assert!(!result.starts_with("# Concept title Resource"), "{result}"); +} + +#[test] +fn form_values_preserve_current_readable_state_without_secrets() { + let source = "
PeriodMonSun
Morning

"; + let result = rendered_html(&markdown(source, false)); + for value in [ + "Morning", + "☑", + "☐", + "Search term", + "Your Email", + "Search", + "Map button", + "Password", + ] { + assert!(result.contains(value), "missing {value}: {result}"); + } + for secret in ["secret", "token", "private.pdf"] { + assert!(!result.contains(secret), "leaked {secret}: {result}"); + } +} + +#[test] +fn unsafe_resource_urls_keep_labels_without_emitting_active_links() { + let source = "

Open panelPosterEmail

"; + let result = markdown(source, false); + assert!(result.contains("Open panel"), "{result}"); + assert!(result.contains("Poster"), "{result}"); + assert!( + result.contains("[Email](mailto:a@example.test)"), + "{result}" + ); + assert!(!result.contains("javascript:"), "{result}"); +} + +#[test] +fn complex_table_preserves_checkbox_state() { + let source = "
Status
"; + let result = rendered_html(&markdown(source, false)); + assert!(result.contains("rowspan=\"2\""), "{result}"); + assert!(result.contains("☑"), "{result}"); + assert!(result.contains("☐"), "{result}"); +} + #[test] fn embedded_image_references_survive_regardless_of_pixel_content() { for src in [ diff --git a/moli-html2md/tests/tables.rs b/moli-html2md/tests/tables.rs index e19c8ee15e6..7fc939604db 100644 --- a/moli-html2md/tests/tables.rs +++ b/moli-html2md/tests/tables.rs @@ -11,43 +11,81 @@ fn markdown(html: &str) -> String { result } +// Compare browser-parsed cell nesting, spans and text, independently of the +// serializer's spelling, indentation or Markdown representation. +fn table_signature(html: &str) -> Vec { + let tree = Tree::parse(html); + let mut result = Vec::new(); + let mut stack = vec![(tree.root, false)]; + while let Some((id, close)) = stack.pop() { + let node = &tree.nodes[id]; + let table_tag = node.tag.as_deref().filter(|tag| { + matches!( + *tag, + "table" | "thead" | "tbody" | "tfoot" | "tr" | "td" | "th" | "caption" + ) + }); + if close { + if let Some(tag) = table_tag { + result.push(format!("/{tag}")); + } + continue; + } + if let Some(tag) = table_tag { + result.push(tag.to_owned()); + for (key, value) in &node.attrs { + if matches!(key.as_str(), "rowspan" | "colspan" | "scope" | "headers") { + result.push(format!("{key}={value}")); + } + } + } + if let Some(text) = &node.text { + let text = text.split_whitespace().collect::>().join(" "); + if !text.is_empty() { + result.push(text); + } + } + stack.push((id, true)); + let mut children = Vec::new(); + let mut child = node.first; + while let Some(id) = child { + children.push(id); + child = tree.nodes[id].next; + } + stack.extend(children.into_iter().rev().map(|id| (id, false))); + } + result +} + +fn assert_preserves_table(source: &str) { + assert_eq!( + table_signature(&rendered_html(&markdown(source))), + table_signature(source) + ); +} + #[test] fn hacker_news_layout_tables_preserve_story_and_metadata_order() { let result = markdown(include_str!("fixtures/hacker-news-layout.html")); - assert_eq!( - result, - include_str!("fixtures/hacker-news-layout.md").trim_end() - ); + assert_preserves_table(include_str!("fixtures/hacker-news-layout.html")); let html = rendered_html(&result); - // The simple navigation row becomes a table; nested/spanning story layout - // still expands into blocks in the original content order. - assert_eq!(html.matches("").count(), 1); + assert_eq!(html.matches("")); assert_eq!(html.matches("before

\n
\n\n
KeyValue
a|bc|d
\n

after

\n" - ); + assert_preserves_table(html); + assert!(rendered_html(&markdown(html)).contains("c|d")); } #[test] fn wrapping_a_table_preserves_its_content() { let data = "
onetwo
threefour
"; - assert_eq!( - markdown(&format!("
{data}
")), - markdown(data) - ); + assert_preserves_table(&format!("
{data}
")); assert_eq!( markdown(data), "| | |\n| --- | --- |\n| one | two |\n| three | four |" @@ -118,9 +156,12 @@ fn other_table_roles_do_not_change_conversion() { #[test] fn table_cells_preserve_block_syntax_and_code_whitespace() { let html = "
intro

Heading

  a\n  b\n
quote
  • item
end
"; - assert_eq!( - markdown(html), - "intro\n\n## Heading\n\n```\n a\n b\n```\n\n> quote\n\n- item\n\nend" + assert_preserves_table(html); + let tree = Tree::parse(&rendered_html(&markdown(html))); + assert!( + tree.nodes + .iter() + .any(|node| node.text.as_deref() == Some(" a\n b\n")) ); } @@ -277,7 +318,7 @@ fn literal_pipes_survive_in_text_code_links_and_image_attributes() { } #[test] -fn unrepresentable_tables_expand_without_losing_or_duplicating_content() { +fn complex_tables_keep_cell_associations_without_duplicate_content() { for row in [ "onetwo", "onetwo", @@ -285,15 +326,8 @@ fn unrepresentable_tables_expand_without_losing_or_duplicating_content() { "onetwo", "onetwoextra", ] { - let actual = markdown(&format!( - "{row}
AB
" - )); - let extra = if row.contains("extra") { - "\n\nextra" - } else { - "" - }; - assert_eq!(actual, format!("A\n\nB\n\none\n\ntwo{extra}")); + let source = format!("{row}
AB
"); + assert_preserves_table(&source); } for content in [ "
  code\nnext\n
", @@ -303,14 +337,10 @@ fn unrepresentable_tables_expand_without_losing_or_duplicating_content() { "
nested
", ] { for cell in ["th", "td"] { - let actual = markdown(&format!( + let source = format!( "<{cell}>A<{cell}>B
one{content}
" - )); - assert_eq!( - actual, - format!("A\n\nB\n\none\n\n{}", markdown(content)), - "{cell}: {content}" ); + assert_preserves_table(&source); } } } @@ -349,12 +379,9 @@ fn table_blocks_preserve_surrounding_inline_styles() { } #[test] -fn multiple_heading_rows_fall_back_to_blocks() { - assert_eq!( - markdown( - "
AB
onetwo
threefour
" - ), - "A\n\nB\n\none\n\ntwo\n\nthree\n\nfour" +fn multiple_heading_rows_keep_their_hierarchy() { + assert_preserves_table( + "
AB
onetwo
threefour
", ); } @@ -439,15 +466,16 @@ fn nested_tables_obey_the_conversion_depth_limit() { let dom = Tree::parse( "
visible
too deep
", ); - for (max_depth, expected) in [(6, "| |\n| --- |\n| visible |"), (7, "visible")] { + for max_depth in [6, 7] { let converter = Converter::new(Options { max_depth, ..Options::default() }); - assert_eq!(converter.convert(&dom, dom.root), expected); + let result = converter.convert(&dom, dom.root); + assert!(result.contains("visible")); + assert!(!result.contains("too deep")); } - assert_eq!( - convert(&dom, dom.root), - "visible\n\n| |\n| --- |\n| too deep |" + assert_preserves_table( + "
visible
too deep
", ); } diff --git a/moli-html2md/tests/tracking.rs b/moli-html2md/tests/tracking.rs index 903e9ca15e3..06ed887f1a1 100644 --- a/moli-html2md/tests/tracking.rs +++ b/moli-html2md/tests/tracking.rs @@ -1,7 +1,4 @@ -//! Open review findings, separate from regressions asserting desired behavior. -//! These tests run normally and fail if the recorded behavior changes. When a -//! gap is fixed, replace its current-output assertion with the desired result -//! and update turndown/README.md; do not refresh the snapshot automatically. +//! Review findings: explicit compatibility choices and semantic regressions. mod support; @@ -46,67 +43,50 @@ fn track_nested_list_spacing_before_a_trailing_empty_element() { } #[test] -fn track_multiline_image_alt_becoming_a_heading() { +fn multiline_image_alt_preserves_the_image() { let result = markdown("first\n# heading"); // Turndown emits the same Markdown. Matching it does not preserve the image. - assert_eq!(result, "![first\n# heading](/x)"); let actual_html = rendered_html(&result); - assert_eq!(actual_html, "

![first

\n

heading](/x)

\n"); let desired_html = "

\"first

\n"; - assert_ne!( + assert_eq!( actual_html, desired_html, "review the resolved image-alt gap" ); } #[test] -fn track_multiline_link_title_becoming_a_heading() { +fn multiline_link_title_preserves_the_link() { let result = markdown("
link"); // Turndown has this loss too; the link and its title must survive rendering. - assert_eq!(result, "[link](/ \"first\n# heading\")"); let actual_html = rendered_html(&result); - assert_eq!( - actual_html, - "

[link](/ \"first

\n

heading\")

\n" - ); let desired_html = "

link

\n"; - assert_ne!( + assert_eq!( actual_html, desired_html, "review the resolved link-title gap" ); } #[test] -fn track_multiple_nested_spans_at_the_end_of_a_paragraph() { +fn multiple_nested_spans_keep_their_styles_at_paragraph_end() { // This predates the closing-edge fix: with no following character there // is no punctuation fallback, but sibling delimiters can still mispair. let result = markdown("xbc"); - assert_eq!(result, "***x**b**c***"); let actual_html = rendered_html(&result); - assert_eq!( - actual_html, - "

xbc**

\n" - ); let desired_html = "

xbc

\n"; - assert_ne!( + assert_eq!( actual_html, desired_html, "review the resolved sibling-span gap" ); } #[test] -fn track_mixed_emphasis_markers_at_an_intraword_opening() { +fn mixed_emphasis_markers_preserve_intraword_styles() { // The opening check sees the text 'x', although the nested styles emit // punctuation first. This is separate from closing a same-marker run. let result = markdown("beforex"); - assert_eq!(result, "before*~~**x**~~*"); let actual_html = rendered_html(&result); - assert_eq!( - actual_html, - "

before*x*

\n" - ); let desired_html = "

beforex

\n"; - assert_ne!( + assert_eq!( actual_html, desired_html, "review the resolved mixed-marker gap" ); diff --git a/moli-html2md/tests/turndown/README.md b/moli-html2md/tests/turndown/README.md index 703252d8d2e..086e7c4689b 100644 --- a/moli-html2md/tests/turndown/README.md +++ b/moli-html2md/tests/turndown/README.md @@ -25,28 +25,30 @@ accepts equivalent delimiter choices and list indentation while detecting lost text, incorrect links, changed paragraph/list structure, and visible delimiters. There are also exact Markdown assertions in the original and regression suites. -`expectations.json` documents 12 deliberate differences with exact Moli outputs. +`expectations.json` documents 13 deliberate differences with exact Moli outputs. These preserve bare pre blocks and avoid upstream losses of literal characters, emphasis, whitespace, and list boundaries. They remain active assertions; no case is skipped. A reference change that makes a difference obsolete also fails the test. Separate converter tests cover GFM tables and strikethrough as Moli extensions. Explicit table headers follow Turndown's GFM plugin; simple headerless -tables receive empty headings. Complex tables retain the core's block expansion -rather than the plugin's raw HTML fallback. +tables receive empty headings. Complex tables retain content-only HTML so merged +cells and nested tables keep their associations. Explicitly presentational tables +still expand into blocks. ## Findings tracked outside the reference corpus -The 12 exceptions above describe this corpus, not every design difference or +The 13 exceptions above describe this corpus, not every design difference or every correctness issue. [tracking.rs](../tracking.rs) records these open review findings with active assertions of both Markdown and rendered HTML: | Tests | Status | Current behavior and comparison | | --- | --- | --- | | `track_nested_list_spacing_through_a_transparent_wrapper`, `track_nested_list_spacing_before_a_trailing_empty_element` | Open compatibility decision | Moli keeps the outer list tight when an `ins` wraps the nested list or an empty `span` follows it. Turndown makes it loose. Both preserve the list items. | -| `track_multiline_image_alt_becoming_a_heading` | Open bug, also present in Turndown | An image alt containing `first\n# heading` breaks the image into text and a heading. The desired HTML retains the image and its full label. | -| `track_multiline_link_title_becoming_a_heading` | Open bug, also present in Turndown | A link title containing `first\n# heading` breaks the link into text and a heading. The desired HTML retains the link and its multiline title. | -| `track_multiple_nested_spans_at_the_end_of_a_paragraph` | Open bug, also present in Turndown | `xbc` produces ambiguous star delimiters at paragraph end, losing the second strong span and exposing literal stars. | -| `track_mixed_emphasis_markers_at_an_intraword_opening` | Open bug in Moli's emphasis/strikethrough extension | `beforex` loses outer emphasis because its opener precedes generated punctuation. | + +Multiline image labels and link titles, nested sibling emphasis at paragraph +ends, and intraword mixed emphasis now have semantic regressions in +[tracking.rs](../tracking.rs). Attribute line breaks cannot introduce Markdown +blocks, and ambiguous emphasis boundaries retain their styles through inline HTML. These tests are not ignored or expected to panic. A change to a recorded output requires review; when fixing a bug, replace the current-output assertion with a diff --git a/moli-html2md/tests/turndown/expectations.json b/moli-html2md/tests/turndown/expectations.json index 9a9593aad97..cc813ee462f 100644 --- a/moli-html2md/tests/turndown/expectations.json +++ b/moli-html2md/tests/turndown/expectations.json @@ -43,6 +43,10 @@ "markdown": "before` `after", "reason": "Explicit preformatted-code mode preserves the spaces inside code. Turndown removes a whitespace-only code element entirely." }, + "extra_missing_image_src": { + "markdown": "beforemissingafter", + "reason": "An unavailable image retains its existing text alternative. Dropping alt also removes the only accessible label from image-only navigation links; Turndown loses that text." + }, "extra_split_list_marker": { "markdown": "12\\. text", "reason": "Escape list markers across text-node boundaries. Turndown escapes nodes individually and accidentally creates an ordered list." diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index ee2f639de6a..35f45839294 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -2,18 +2,141 @@ use crate::dom::native::{NativeDom, NativeNodeId}; use crate::runtime::page_surface::{ RendererPageDumpFormat, RendererPageDumpOptions, RendererPageDumpStripOptions, }; +use moli_html2md::{Dom, NodeKind}; use moli_page_types::MAX_DOM_OUTPUT_TREE_DEPTH; +use std::collections::HashMap; use super::page_vm::PageVm; +mod visibility; + impl PageVm { pub(crate) fn render_page_dump(&mut self, options: RendererPageDumpOptions) -> String { + let markdown_base_url = (options.format == RendererPageDumpFormat::Markdown) + .then(|| self.vm().document_runtime.dom_host().document_base_url()) + .flatten(); + let styles = if options.format == RendererPageDumpFormat::Markdown { + let dom = self.vm().document_runtime.dom_host().dom(); + let mut nodes = Vec::new(); + collect_node_ids(dom, dom.document_node_id(), &mut nodes); + nodes.retain(|node| { + dom.node(*node) + .is_some_and(|node| node.as_element().is_some()) + }); + let span_nodes: Vec<_> = nodes + .iter() + .copied() + .filter(|node| matches!(Dom::node_kind(dom, *node), NodeKind::Element("span"))) + .collect(); + let image_nodes: Vec<_> = nodes + .iter() + .copied() + .filter(|node| matches!(Dom::node_kind(dom, *node), NodeKind::Element("img"))) + .collect(); + let background_values = self + .vm() + .computed_style_property_values_for_document_snapshot( + nodes.iter().copied(), + &["background-color".to_owned()], + ); + let backgrounds: HashMap<_, _> = nodes + .iter() + .copied() + .zip(background_values) + .filter_map(|(node, values)| values.into_iter().next().map(|value| (node, value))) + .collect(); + let background_image_values = self + .vm() + .computed_style_property_values_for_document_snapshot( + nodes.iter().copied(), + &["background-image".to_owned()], + ); + let background_images: HashMap<_, _> = nodes + .iter() + .copied() + .zip(background_image_values) + .filter_map(|(node, values)| values.into_iter().next().map(|value| (node, value))) + .collect(); + let span_values = self + .vm() + .computed_style_property_values_for_document_snapshot( + span_nodes.iter().copied(), + &["bottom".to_owned(), "vertical-align".to_owned()], + ); + let spans: HashMap<_, _> = span_nodes.into_iter().zip(span_values).collect(); + let image_values = self + .vm() + .computed_style_property_values_for_document_snapshot( + image_nodes.iter().copied(), + &["width".to_owned(), "height".to_owned()], + ); + let images: HashMap<_, _> = image_nodes.into_iter().zip(image_values).collect(); + let values = self + .vm() + .computed_style_property_values_for_document_snapshot( + nodes.iter().copied(), + &[ + "display".to_owned(), + "visibility".to_owned(), + "opacity".to_owned(), + "position".to_owned(), + "left".to_owned(), + "top".to_owned(), + "color".to_owned(), + "animation-name".to_owned(), + ], + ); + nodes + .into_iter() + .zip(values) + .map(|(node, mut values)| { + let animation_name = values.pop().unwrap_or_default(); + let foreground = values.pop().unwrap_or_default(); + // Preserve the visibility adapter's stable field layout. + let span = spans.get(&node); + values.push( + span.and_then(|values| values.first()) + .cloned() + .unwrap_or_default(), + ); + values.push( + span.and_then(|values| values.get(1)) + .cloned() + .unwrap_or_default(), + ); + let image = images.get(&node); + values.push( + image + .and_then(|values| values.first()) + .cloned() + .unwrap_or_default(), + ); + values.push( + image + .and_then(|values| values.get(1)) + .cloned() + .unwrap_or_default(), + ); + values.push(foreground); + values.push(backgrounds.get(&node).cloned().unwrap_or_default()); + values.push(animation_name); + values.push(background_images.get(&node).cloned().unwrap_or_default()); + (node, values) + }) + .collect::>() + } else { + Vec::new() + }; if options.format == RendererPageDumpFormat::Markdown && !options.with_base && !options.with_frames && options.strip == RendererPageDumpStripOptions::default() { - return render_markdown_document(self.vm().document_runtime.dom_host().dom()); + return render_markdown_document_with_styles( + self.vm().document_runtime.dom_host().dom(), + styles, + markdown_base_url.as_ref(), + ); } let mut dom = self.vm().document_runtime.dom_host().dom().clone(); @@ -33,7 +156,9 @@ impl PageVm { match options.format { RendererPageDumpFormat::Html => dom.serialize_document(), - RendererPageDumpFormat::Markdown => render_markdown_document(&dom), + RendererPageDumpFormat::Markdown => { + render_markdown_document_with_styles(&dom, styles, markdown_base_url.as_ref()) + } } } @@ -181,14 +306,24 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String { + render_markdown_document_with_styles(dom, Vec::new(), None) +} + +fn render_markdown_document_with_styles( + dom: &NativeDom, + styles: Vec<(NativeNodeId, Vec)>, + base_url: Option<&url::Url>, +) -> String { let root = dom.body_node_id().unwrap_or(dom.document_node_id()); + let visible = visibility::MarkdownDom::new(dom, styles, base_url); moli_html2md::Converter::new(moli_html2md::Options { max_depth: MAX_DOM_OUTPUT_TREE_DEPTH, default_code_language: Some("text".to_owned()), ..Default::default() }) - .convert(dom, root) + .convert(&visible, root) } #[cfg(test)] @@ -393,10 +528,31 @@ mod tests { include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.html").to_owned(), ); let before = dom.serialize_document(); - assert_eq!( - render_markdown_document(&dom), - include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.md").trim_end() + let markdown = render_markdown_document(&dom); + for content in [ + "First story", + "42 points by", + "8 comments", + "Second story", + "7 points by", + "discuss", + "More", + ] { + assert!(markdown.contains(content), "missing {content}: {markdown}"); + } + let positions = [ + "First story", + "42 points by", + "Second story", + "7 points by", + "More", + ] + .map(|content| markdown.find(content).expect("checked above")); + assert!( + positions.windows(2).all(|pair| pair[0] < pair[1]), + "{markdown}" ); + assert!(markdown.contains("link", - "[link](/a \"one\ntwo\")", + "[link](/a \"one two\")", ), ( "one\n  two", - "![one\ntwo](/i \"one\ntwo\")", + "![one two](/i \"one two\")", ), ( "

link

", "## [link](/a \"one two\")", ), - ("alabelblabelc", "abc"), + ( + "alabelblabelc", + "alabelblabelc", + ), ] { assert_eq!(markdown_from_html(html), expected, "{html}"); } diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs new file mode 100644 index 00000000000..5c9c20d4e3e --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -0,0 +1,575 @@ +use std::collections::{HashMap, HashSet}; + +use moli_html2md::{Dom, NodeKind}; +use url::Url; + +use crate::dom::native::{NativeDom, NativeNodeId}; + +/// Read the current page's computed visibility without mutating the live DOM. +/// Explicit disclosure content remains useful in a document dump, even while +/// its tab or section is closed. Other non-rendered UI is not document text. +pub(super) struct MarkdownDom<'a> { + dom: &'a NativeDom, + suppressed: HashSet, + invisible: HashSet, + blocks: HashSet, + inline_boundaries: HashSet, + superscripts: HashSet, + subscripts: HashSet, + resolved_urls: HashMap>, + fragment_links: bool, +} + +impl<'a> MarkdownDom<'a> { + pub(super) fn new( + dom: &'a NativeDom, + styles: impl IntoIterator)>, + base_url: Option<&Url>, + ) -> Self { + let styles: Vec<_> = styles.into_iter().collect(); + let document_element = dom.document_element_node_id(); + let body = dom.body_node_id(); + let document_visibility_is_hidden = styles.iter().any(|(node, values)| { + (Some(*node) == document_element || Some(*node) == body) + && values + .get(1) + .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) + }); + let fragment_links = styles.iter().any(|(node, _)| { + Dom::attribute(dom, *node, "href").is_some_and(|href| href.starts_with('#')) + }); + // `styles` follows the document's preorder, so every element's parent + // has already been seen. Cache the painted ancestor background once; + // walking ancestors for every node is quadratic on deeply nested pages. + let mut effective_backgrounds = HashMap::new(); + if styles + .iter() + .any(|(_, values)| values.get(11).is_some_and(|value| !value.is_empty())) + { + for (node, values) in &styles { + let own = values + .get(11) + .and_then(|value| css_color(value)) + .filter(|color| color.3 > 0.99); + let inherited = dom + .parent_node(*node) + .and_then(|parent| effective_backgrounds.get(&parent).copied()); + effective_backgrounds + .insert(*node, own.or(inherited).unwrap_or((255, 255, 255, 1.0))); + } + } + let mut disclosures = HashSet::new(); + let mut excerpts = HashSet::new(); + let targets: HashMap<_, _> = styles + .iter() + .filter_map(|(node, values)| { + (values.first().is_some_and(|value| value == "none")) + .then(|| Dom::attribute(dom, *node, "id").map(|id| (id, *node))) + .flatten() + }) + .collect(); + for (node, _) in &styles { + if (Dom::attribute(dom, *node, "aria-expanded").is_some() + || Dom::attribute(dom, *node, "role") + .is_some_and(|role| role.eq_ignore_ascii_case("tab"))) + && let Some(targets) = Dom::attribute(dom, *node, "aria-controls") + { + disclosures.extend(targets.split_ascii_whitespace()); + } + for attribute_name in dom.get_attribute_names(*node).unwrap_or_default() { + if !attribute_name.starts_with("on") { + continue; + } + let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else { + continue; + }; + for target in inline_disclosure_targets(handler) { + if let Some((&id, _)) = targets.get_key_value(target) { + disclosures.insert(id); + } + } + } + // Some pages pair a shortened paragraph with an explicitly linked + // hidden full-text copy. Keep the complete copy once; an unrelated + // dialog or a matching paragraph elsewhere is not such a pair. + for attribute in ["href", "data-src", "data-target"] { + let Some(id) = + Dom::attribute(dom, *node, attribute).and_then(|value| value.strip_prefix('#')) + else { + continue; + }; + let Some(&target) = targets.get(id) else { + continue; + }; + if Dom::attribute(dom, target, "role").is_some_and(|role| { + ["dialog", "alertdialog", "menu"] + .iter() + .any(|excluded| role.eq_ignore_ascii_case(excluded)) + }) { + continue; + } + let mut ancestor = dom.parent_node(*node); + while let Some(paragraph) = ancestor { + if matches!(Dom::node_kind(dom, paragraph), NodeKind::Element("p")) { + if let Some(container) = dom.parent_node(paragraph) + && within(dom, target, container) + && !within(dom, target, paragraph) + { + let short = text(dom, paragraph, Some(*node)); + let prefix = short + .strip_suffix("...") + .or_else(|| short.strip_suffix('…')); + if let Some(prefix) = prefix + .map(str::trim_end) + .filter(|prefix| !prefix.is_empty()) + { + let full = text(dom, target, None); + if full.len() > prefix.len() && full.starts_with(prefix) { + disclosures.insert(id); + excerpts.insert(paragraph); + } + } + } + break; + } + ancestor = dom.parent_node(paragraph); + } + } + } + let mut suppressed = excerpts; + let mut invisible = HashSet::new(); + let mut blocks = HashSet::new(); + let mut inline_boundaries = HashSet::new(); + let mut superscripts = HashSet::new(); + let mut subscripts = HashSet::new(); + let mut resolved_urls = HashMap::new(); + for (node, values) in styles { + let role = Dom::attribute(dom, node, "role").unwrap_or_default(); + // Lazy media often stays transparent until a scroll/load event. + // Its declared resource still belongs to the document, unlike + // transparent numeric placeholders or hidden UI text. + let lazy_media = matches!( + Dom::node_kind(dom, node), + NodeKind::Element("img" | "iframe" | "video" | "audio") + ) && ["data-original", "data-src", "data-lazy-src", "data-srcset"] + .iter() + .any(|attribute| { + Dom::attribute(dom, node, attribute) + .is_some_and(|value| !value.trim().is_empty()) + }); + let disclosure = role.eq_ignore_ascii_case("tabpanel") + || Dom::attribute(dom, node, "hidden") == Some("until-found") + || (!matches!(role, "dialog" | "alertdialog" | "menu") + && Dom::attribute(dom, node, "id").is_some_and(|id| disclosures.contains(id))); + let aria_hidden = Dom::attribute(dom, node, "aria-hidden") + .is_some_and(|value| value.eq_ignore_ascii_case("true")); + // Angular/Vue remove cloak attributes only after the bound view + // is ready. If one remains at dump time, its template text is not + // reader content even when a missing stylesheet fails to hide it. + let uninitialized_template = ["ng-cloak", "data-ng-cloak", "x-ng-cloak", "v-cloak"] + .iter() + .any(|name| Dom::attribute(dom, node, name).is_some()); + let far_offscreen = values + .get(3) + .is_some_and(|position| matches!(position.as_str(), "absolute" | "fixed")) + && values + .get(4) + .and_then(|value| px(value)) + .is_some_and(|left| left <= -1000.0) + && values + .get(5) + .and_then(|value| px(value)) + .is_some_and(|top| top <= -1000.0); + let tracking_pixel = matches!(Dom::node_kind(dom, node), NodeKind::Element("img")) + && Dom::attribute(dom, node, "alt").is_none_or(|alt| alt.trim().is_empty()) + && values + .get(8) + .and_then(|value| px(value)) + .is_some_and(|width| width <= 1.5) + && values + .get(9) + .and_then(|value| px(value)) + .is_some_and(|height| height <= 1.5); + let foreground = values.get(10).and_then(|value| css_color(value)); + let zero_contrast_leaf = !has_element_child(dom, node) + && has_text_child(dom, node) + && values + .get(13) + .is_none_or(|image| image.is_empty() || image == "none") + && foreground + .filter(|color| color.3 > 0.99) + .zip(effective_backgrounds.get(&node).copied()) + .is_some_and(|(foreground, background)| { + background.3 > 0.99 + && (foreground.0, foreground.1, foreground.2) + == (background.0, background.1, background.2) + }); + let document_root = Some(node) == document_element || Some(node) == body; + let animated = values + .get(12) + .is_some_and(|name| !name.is_empty() && name != "none"); + if ((values.first().is_some_and(|value| value == "none") + || values + .get(2) + .is_some_and(|value| value.parse::() == Ok(0.0)) + && !lazy_media + && !animated + && !document_root) + && !disclosure) + || (aria_hidden && !disclosure) + || uninitialized_template + || far_offscreen + || tracking_pixel + || zero_contrast_leaf + || dom + .parent_node(node) + .is_some_and(|parent| suppressed.contains(&parent)) + { + suppressed.insert(node); + } + if values.first().is_some_and(|value| { + matches!( + value.as_str(), + "block" | "flow-root" | "flex" | "grid" | "list-item" | "table" + ) + }) { + blocks.insert(node); + } else if values.first().is_some_and(|value| { + matches!( + value.as_str(), + "inline-block" | "inline-flex" | "inline-grid" | "inline-table" + ) + }) { + inline_boundaries.insert(node); + } + if matches!(Dom::node_kind(dom, node), NodeKind::Element("span")) { + let relative = values.get(3).is_some_and(|position| position == "relative"); + let vertical_align = values.get(7).map(String::as_str).unwrap_or_default(); + if vertical_align == "super" + || (relative + && values + .get(5) + .and_then(|value| px(value)) + .is_some_and(|top| top < -1.0)) + { + superscripts.insert(node); + } else if vertical_align == "sub" + || (relative + && values + .get(6) + .and_then(|value| px(value)) + .is_some_and(|bottom| bottom < -1.0)) + { + subscripts.insert(node); + } + } + if let Some(base_url) = base_url { + let names: &[&str] = match Dom::node_kind(dom, node) { + NodeKind::Element("a") => &["href"], + NodeKind::Element("img") => &[ + "src", + "data-original", + "data-src", + "data-lazy-src", + "srcset", + "data-srcset", + ], + NodeKind::Element("iframe" | "audio" | "source") => { + &["src", "data-src", "data-lazy-src"] + } + NodeKind::Element("video") => &["src", "poster", "data-src", "data-lazy-src"], + _ => &[], + }; + for &name in names { + let Some(value) = Dom::attribute(dom, node, name) + .map(str::trim) + .filter(|value| !value.is_empty() && !value.starts_with('#')) + else { + continue; + }; + let resolved = if matches!(name, "srcset" | "data-srcset") { + resolve_srcset(base_url, value) + } else { + base_url.join(value).ok().map(|url| url.to_string()) + }; + if let Some(url) = resolved { + resolved_urls + .entry(node) + .or_insert_with(HashMap::new) + .insert(name.to_owned(), url); + } + } + } + if values + .get(1) + .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) + && !disclosure + && !document_visibility_is_hidden + { + invisible.insert(node); + } + } + Self { + dom, + suppressed, + invisible, + blocks, + inline_boundaries, + superscripts, + subscripts, + resolved_urls, + fragment_links, + } + } + + fn next_retained(&self, mut node: Option) -> Option { + while let Some(id) = node { + if !self.suppressed.contains(&id) { + return Some(id); + } + node = self.dom.next_sibling(id); + } + None + } +} + +fn inline_disclosure_targets(value: &str) -> Vec<&str> { + let mut result = Vec::new(); + for (marker, fragment) in [ + ("document.getElementById", false), + ("document.querySelector", true), + ] { + for offset in code_marker_offsets(value, marker) { + let remaining = &value[offset + marker.len()..]; + let Some(argument) = remaining + .trim_start() + .strip_prefix('(') + .map(str::trim_start) + else { + continue; + }; + let Some(quote) = argument + .chars() + .next() + .filter(|quote| matches!(quote, '\'' | '"')) + else { + continue; + }; + let literal = &argument[quote.len_utf8()..]; + let Some(end) = literal.find(quote) else { + continue; + }; + let literal = &literal[..end]; + if let Some(target) = literal + .strip_prefix('#') + .or_else(|| (!fragment).then_some(literal)) + && !target.is_empty() + { + result.push(target); + } + } + } + result +} + +fn code_marker_offsets(value: &str, marker: &str) -> Vec { + let mut result = Vec::new(); + let mut offset = 0; + let mut quote = None; + let mut escaped = false; + while offset < value.len() { + let character = value[offset..] + .chars() + .next() + .expect("offset remains on a character boundary"); + if let Some(delimiter) = quote { + if escaped { + escaped = false; + } else if character == '\\' { + escaped = true; + } else if character == delimiter { + quote = None; + } + } else if matches!(character, '\'' | '"' | '`') { + quote = Some(character); + } else if value[offset..].starts_with(marker) { + result.push(offset); + offset += marker.len(); + continue; + } + offset += character.len_utf8(); + } + result +} + +fn px(value: &str) -> Option { + value.strip_suffix("px")?.trim().parse().ok() +} + +fn resolve_srcset(base_url: &Url, value: &str) -> Option { + let mut resolved = Vec::new(); + for candidate in value.split(',') { + let candidate = candidate.trim(); + if candidate.is_empty() { + continue; + } + let split = candidate + .find(char::is_whitespace) + .unwrap_or(candidate.len()); + let (source, descriptor) = candidate.split_at(split); + let url = base_url.join(source).ok()?; + resolved.push(format!("{}{descriptor}", url)); + } + (!resolved.is_empty()).then(|| resolved.join(", ")) +} + +fn css_color(value: &str) -> Option<(u8, u8, u8, f32)> { + let value = value.trim().to_ascii_lowercase(); + match value.as_str() { + "transparent" => return Some((0, 0, 0, 0.0)), + "white" => return Some((255, 255, 255, 1.0)), + "black" => return Some((0, 0, 0, 1.0)), + _ => {} + } + let (body, alpha) = match ( + value + .strip_prefix("rgba(") + .and_then(|body| body.strip_suffix(')')), + value + .strip_prefix("rgb(") + .and_then(|body| body.strip_suffix(')')), + ) { + (Some(body), _) => (body, true), + (_, Some(body)) => (body, false), + _ => return None, + }; + let mut parts = body.split(',').map(str::trim); + let red = parts.next()?.parse().ok()?; + let green = parts.next()?.parse().ok()?; + let blue = parts.next()?.parse().ok()?; + let opacity = if alpha { + parts.next()?.parse().ok()? + } else { + 1.0 + }; + parts + .next() + .is_none() + .then_some((red, green, blue, opacity)) +} + +fn has_element_child(dom: &NativeDom, node: NativeNodeId) -> bool { + let mut child = dom.first_child(node); + while let Some(id) = child { + if matches!(Dom::node_kind(dom, id), NodeKind::Element(_)) { + return true; + } + child = dom.next_sibling(id); + } + false +} + +fn has_text_child(dom: &NativeDom, node: NativeNodeId) -> bool { + let mut child = dom.first_child(node); + while let Some(id) = child { + if matches!(Dom::node_kind(dom, id), NodeKind::Text(text) if !text.trim().is_empty()) { + return true; + } + child = dom.next_sibling(id); + } + false +} + +fn within(dom: &NativeDom, mut node: NativeNodeId, ancestor: NativeNodeId) -> bool { + loop { + if node == ancestor { + return true; + } + let Some(parent) = dom.parent_node(node) else { + return false; + }; + node = parent; + } +} + +fn text(dom: &NativeDom, root: NativeNodeId, skip: Option) -> String { + let mut pending = vec![root]; + let mut result = String::new(); + while let Some(node) = pending.pop() { + if Some(node) == skip { + continue; + } + match Dom::node_kind(dom, node) { + NodeKind::Text(value) => result.push_str(value), + NodeKind::Element("script" | "style" | "template") => continue, + _ => {} + } + let mut children = Vec::new(); + let mut child = dom.first_child(node); + while let Some(id) = child { + children.push(id); + child = dom.next_sibling(id); + } + pending.extend(children.into_iter().rev()); + } + result.split_whitespace().collect::>().join(" ") +} + +impl Dom for MarkdownDom<'_> { + type NodeId = NativeNodeId; + + fn node_kind(&self, node: Self::NodeId) -> NodeKind<'_> { + if self.suppressed.contains(&node) { + return NodeKind::Other; + } + let kind = Dom::node_kind(self.dom, node); + if self.invisible.contains(&node) { + // Visibility can be overridden by a descendant. Keep traversing + // without emitting this element's own image, link or formatting. + return NodeKind::Document; + } + if matches!(kind, NodeKind::Text(_)) + && self + .dom + .parent_node(node) + .is_some_and(|parent| self.invisible.contains(&parent)) + { + return NodeKind::Other; + } + if self.superscripts.contains(&node) { + return NodeKind::Element("sup"); + } + if self.subscripts.contains(&node) { + return NodeKind::Element("sub"); + } + kind + } + + fn first_child(&self, node: Self::NodeId) -> Option { + self.next_retained(self.dom.first_child(node)) + } + + fn next_sibling(&self, node: Self::NodeId) -> Option { + self.next_retained(self.dom.next_sibling(node)) + } + + fn attribute(&self, node: Self::NodeId, name: &str) -> Option<&str> { + self.resolved_urls + .get(&node) + .and_then(|attributes| attributes.get(name)) + .map(String::as_str) + .or_else(|| Dom::attribute(self.dom, node, name)) + } + + fn has_block_layout(&self, node: Self::NodeId) -> bool { + self.blocks.contains(&node) + } + + fn has_text_boundary(&self, node: Self::NodeId) -> bool { + self.inline_boundaries.contains(&node) + } + + fn may_have_fragment_links(&self) -> bool { + self.fragment_links + } +} diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs new file mode 100644 index 00000000000..0e08c5df909 --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -0,0 +1,160 @@ +use super::*; +use crate::runtime::page_surface::{ + RendererPageDumpFormat, RendererPageDumpOptions, RendererPageDumpStripOptions, +}; + +fn options(strip_css: bool) -> RendererPageDumpOptions { + RendererPageDumpOptions { + format: RendererPageDumpFormat::Markdown, + strip: RendererPageDumpStripOptions { + css: strip_css, + ..Default::default() + }, + with_base: false, + with_frames: false, + } +} + +#[tokio::test(flavor = "current_thread")] +async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader"); + let mut page = test_page_vm_with_loader_and_document_url(&loader, Vec::new(), Url::parse("https://example.test/content").unwrap()); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = ` +

Article

Visible body

+
Translation pending
+ +

Followers 92

+

Score 31

+
Parser trap
+ Accessible helper +
Transparent parent Transparent child
+
Buy {{product.name}} for {{product.price | currency}}
+
Vue template {{message}}
+

Visible value hidden suffix 8

+

CSS override VISIBLE

+

Stylesheet override ALSO VISIBLE

+

White on black stays visible

+

Faded text

+

Animated article text

+
ActiveReviewed
+

Mass 2.4 × 10−17 J; mn

+ + Upload complete + Article photo + + +

Panel content

+ + +
Disclosure content
+
DetailsClosed details content
+ + `; + "#).unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('legacy-hidden')).color").unwrap(), "rgb(255, 255, 255)"); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('css-override')).color").unwrap(), "rgb(0, 0, 0)"); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('external-override')).color").unwrap(), "rgb(0, 0, 0)"); + assert_eq!(page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','black'); getComputedStyle(document.getElementById('legacy-hidden')).color").unwrap(), "rgb(0, 0, 0)"); + page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','white')").unwrap(); + for strip_css in [false, true] { + let output = page.render_page_dump(options(strip_css)); + for kept in ["Visible body", "Restored child", "Panel content", "ARIA panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value 8", "CSS override VISIBLE", "Stylesheet override ALSO VISIBLE", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + assert!(output.contains(kept), "missing {kept}: {output}"); + } + assert!(output.contains("10−17"), "{output}"); + assert!(output.contains("mn"), "{output}"); + assert!(output.contains("Active\nReviewed"), "{output}"); + assert!(!output.contains("tracking.gif"), "{output}"); + assert!(output.contains("Upload complete"), "{output}"); + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { + assert!(!output.contains(omitted), "leaked {omitted}: {output}"); + } + } + page.vm_mut().eval("document.getElementById('waiting').className = ''").unwrap(); + assert!(page.render_page_dump(options(false)).contains("Translation pending")); + assert_eq!(page.vm_mut().eval("document.querySelector('style').textContent.includes('.off')").unwrap(), "true"); + page.vm_mut().eval(r#" + document.documentElement.style.opacity = '0'; + document.body.innerHTML = '
Whole-page loading veil
'; + "#).unwrap(); + assert!(page.render_page_dump(options(false)).contains("Whole-page loading veil")); + page.vm_mut().eval(r#" + document.documentElement.style.opacity = ''; + document.body.style.visibility = 'hidden'; + document.body.innerHTML = '
Font loading veil
'; + "#).unwrap(); + assert!(page.render_page_dump(options(false)).contains("Font loading veil")); + page.vm_mut().eval("document.body.style.visibility = ''").unwrap(); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = 'AcceptReject'; + "#).unwrap(); + let actions = page.render_page_dump(options(false)); + assert!(actions.contains("[Accept](https://example.test/accept)\n\n[Reject](https://example.test/reject)"), "{actions}"); + page.vm_mut().eval(r##" + document.body.innerHTML = ` +

A detailed review starts... Read more

+
+

A different excerpt... Read more

+
+

Complete short review.

Complete short review.
+

Complete short review.

+

Privacy policy... Read more

+
`; + "##).unwrap(); + for strip_css in [false, true] { + let output = page.render_page_dump(options(strip_css)); + assert_eq!(output.matches("A detailed review starts").count(), 1, "{output}"); + assert!(output.contains("retains the final conclusion."), "{output}"); + assert!(!output.contains("A detailed review starts..."), "{output}"); + assert!(output.contains("A different excerpt..."), "{output}"); + assert!(!output.contains("Unrelated hidden template"), "{output}"); + assert_eq!(output.matches("Complete short review.").count(), 2, "{output}"); + assert!(output.contains("Privacy policy..."), "{output}"); + assert!(!output.contains("cookie settings"), "{output}"); + } + page.vm_mut().eval(r##" + document.body.innerHTML = ` + + + + `; + "##).unwrap(); + let expanded = page.render_page_dump(options(false)); + assert!(expanded.contains("Expandable history"), "{expanded}"); + assert!(!expanded.contains("Hidden template"), "{expanded}"); + page.vm_mut().eval(r##" + document.body.innerHTML = ` + + + + + + `; + "##).unwrap(); + let related = page.render_page_dump(options(false)); + assert!(!related.contains("Hidden telemetry state"), "{related}"); + assert!(!related.contains("Hidden diagnostic state"), "{related}"); + assert!(related.contains("Query-selected history"), "{related}"); + page.vm_mut().eval(r#" + document.body.innerHTML = ` +

Visible gradient text

+
Photo
`; + "#).unwrap(); + let painted = page.render_page_dump(options(false)); + assert!(painted.contains("Visible gradient text"), "{painted}"); + assert!(painted.contains("![Photo](https://example.test/photo.png)"), "{painted}"); + page.vm_mut().eval(r#" + document.body.innerHTML = ` + Responsive + Lazy responsive`; + "#).unwrap(); + let responsive = page.render_page_dump(options(false)); + assert!(responsive.contains("![Responsive](https://example.test/large.png)"), "{responsive}"); + assert!(responsive.contains("![Lazy responsive](https://example.test/lazy-large.png)"), "{responsive}"); + page.vm_mut().eval("document.documentElement.style.display = 'none'").unwrap(); + assert!(page.render_page_dump(options(false)).is_empty()); + }).await; +} diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs index 0298a7d021d..12d8f524520 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs @@ -146,6 +146,7 @@ mod main_parser_module_completion; mod main_parser_owned_module_completion; mod main_runtime_module_completion; mod main_runtime_script_completion; +mod markdown_dump; mod media_element_event; mod message_port_delivery; mod misc_platform_api; diff --git a/moli-renderer-v8/src/style_engine/mutation_effect.rs b/moli-renderer-v8/src/style_engine/mutation_effect.rs index ea25c3be900..92868c6b20f 100644 --- a/moli-renderer-v8/src/style_engine/mutation_effect.rs +++ b/moli-renderer-v8/src/style_engine/mutation_effect.rs @@ -212,7 +212,7 @@ impl StyleAttributeImpact { pub(crate) fn for_attribute_name(name: &str) -> Self { let name = name.to_ascii_lowercase(); match name.as_str() { - "style" | "class" | "id" => Self::ComputedStyle, + "style" | "class" | "id" | "color" => Self::ComputedStyle, "hidden" | "width" | "height" | "cols" | "rows" | "size" | "value" | "border" | "slot" | "align" => Self::LayoutMetric, "cellpadding" => Self::DescendantComputedStyle, diff --git a/moli-selector/src/stylo/presentation.rs b/moli-selector/src/stylo/presentation.rs index d91a15a86c7..2e6ea755676 100644 --- a/moli-selector/src/stylo/presentation.rs +++ b/moli-selector/src/stylo/presentation.rs @@ -161,7 +161,7 @@ impl QueryElement<'_> { ); } } else if element.namespace() == HTML_NAMESPACE { - append_html_table_presentation_declarations(*self, &mut block); + append_html_presentation_declarations(*self, &mut block); } else { return; } @@ -176,7 +176,7 @@ impl QueryElement<'_> { } } -fn append_html_table_presentation_declarations( +fn append_html_presentation_declarations( element: QueryElement<'_>, block: &mut PropertyDeclarationBlock, ) { @@ -184,6 +184,11 @@ fn append_html_table_presentation_declarations( let local_name = native.local_name(); let is_cell = matches!(local_name, "td" | "th"); let is_column = matches!(local_name, "col" | "colgroup"); + if local_name == "font" + && let Some(color) = native.attribute("color").and_then(parse_html_legacy_color) + { + append_parsed_presentation_declaration(element, "color", &color, block); + } // Table dimensions are presentation hints, including column-group widths. // Keep them in the cascade so author CSS can override them and the table // algorithm receives the same constraints as an authored CSS length. diff --git a/moli/tests/fetch_cli/markdown.rs b/moli/tests/fetch_cli/markdown.rs index 36711ea604c..917047c302d 100644 --- a/moli/tests/fetch_cli/markdown.rs +++ b/moli/tests/fetch_cli/markdown.rs @@ -3,10 +3,52 @@ use base64::{Engine as _, engine::general_purpose::STANDARD}; use std::process::Command; const HTML: &str = include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.html"); -const MARKDOWN: &str = include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.md"); - fn assert_layout_table_dump(args: &[&str]) -> Result<()> { - assert_markdown_dump(HTML, MARKDOWN, args) + let url = format!("data:text/html;base64,{}", STANDARD.encode(HTML)); + let output = Command::new(env!("CARGO_BIN_EXE_moli")) + .args([ + "fetch", + "--dump", + "markdown", + "--wait-until", + "load", + "--timeout", + "10000", + ]) + .args(args) + .arg(url) + .output()?; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let markdown = String::from_utf8(output.stdout)?; + for content in [ + "First story", + "42 points by", + "8 comments", + "Second story", + "7 points by", + "discuss", + "More", + ] { + assert!(markdown.contains(content), "missing {content}: {markdown}"); + } + let positions = [ + "First story", + "42 points by", + "Second story", + "7 points by", + "More", + ] + .map(|content| markdown.find(content).expect("checked above")); + assert!( + positions.windows(2).all(|pair| pair[0] < pair[1]), + "{markdown}" + ); + assert!(markdown.contains(" Result<()> {