diff --git a/Cargo.lock b/Cargo.lock index 857ff3e13c8..394944ae5e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1254,7 +1254,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3585,7 +3585,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4682,7 +4682,7 @@ dependencies = [ [[package]] name = "selectors" version = "0.40.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "bitflags", "cssparser", @@ -4814,7 +4814,7 @@ dependencies = [ [[package]] name = "servo_arc" version = "0.4.3" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "serde", "stable_deref_trait", @@ -5079,7 +5079,7 @@ dependencies = [ [[package]] name = "stylo" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "app_units", "arrayvec", @@ -5135,7 +5135,7 @@ dependencies = [ [[package]] name = "stylo_atoms" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "string_cache", "string_cache_codegen", @@ -5144,7 +5144,7 @@ dependencies = [ [[package]] name = "stylo_derive" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "darling", "proc-macro2", @@ -5156,7 +5156,7 @@ dependencies = [ [[package]] name = "stylo_dom" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "bitflags", "stylo_malloc_size_of", @@ -5165,7 +5165,7 @@ dependencies = [ [[package]] name = "stylo_malloc_size_of" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "app_units", "cssparser", @@ -5182,7 +5182,7 @@ dependencies = [ [[package]] name = "stylo_static_prefs" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "toml", ] @@ -5200,7 +5200,7 @@ dependencies = [ [[package]] name = "stylo_traits" version = "0.20.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "app_units", "bitflags", @@ -5293,7 +5293,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.4", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5499,7 +5499,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "to_shmem" version = "0.5.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "cssparser", "servo_arc", @@ -5512,7 +5512,7 @@ dependencies = [ [[package]] name = "to_shmem_derive" version = "0.1.0" -source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27" +source = "git+https://github.com/lexmount/stylo?rev=1032a2947ec2f7cee1027d07084203be87e17643#1032a2947ec2f7cee1027d07084203be87e17643" dependencies = [ "darling", "proc-macro2", @@ -6175,7 +6175,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 63ec86ac4fb..91f0525dc15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -107,13 +107,13 @@ curl-sys = { git = "https://github.com/lexmount/curl-rust", rev = "a0ea59f5ca1b1 cookie = { git = "https://github.com/ldm0/cookie-rs", branch = "priority" } v8 = { path = "vendor/v8-152.2.0" } deno_v8 = { path = "vendor/deno_v8-0.3.0" } -selectors = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } -servo_arc = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } -stylo = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } -stylo_atoms = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } -stylo_dom = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } -stylo_static_prefs = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } -stylo_traits = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" } +selectors = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } +servo_arc = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } +stylo = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } +stylo_atoms = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } +stylo_dom = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } +stylo_static_prefs = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } +stylo_traits = { git = "https://github.com/lexmount/stylo", rev = "1032a2947ec2f7cee1027d07084203be87e17643" } svgtypes = { git = "https://github.com/lexmount/svgtypes", branch = "feat/strict-path-numbers" } taffy = { git = "https://github.com/ldm0/taffy", rev = "645bf5a49df607a8bff34ec90c5343901d04f10e" } 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..a4d8145a758 --- /dev/null +++ b/moli-html2md/src/anchors.rs @@ -0,0 +1,178 @@ +use std::collections::HashSet; + +use crate::{Dom, NodeKind}; + +pub(crate) struct Targets { + referenced: HashSet, + ids: HashSet, +} + +impl Targets { + pub(crate) fn is_empty(&self) -> bool { + self.referenced.is_empty() + } + + pub(crate) fn contains(&self, value: &str) -> bool { + self.referenced.contains(value) + } + + pub(crate) fn targets<'a, D: Dom + ?Sized>(&self, dom: &'a D, node: D::NodeId) -> Vec<&'a str> { + let mut targets = Vec::with_capacity(2); + if let Some(id) = dom.attribute(node, "id").filter(|id| self.contains(id)) { + targets.push(id); + } + if dom.node_kind(node) == NodeKind::Element("a") + && let Some(name) = dom + .attribute(node, "name") + .filter(|name| self.contains(name) && !self.ids.contains(*name)) + && !targets.contains(&name) + { + targets.push(name); + } + targets + } +} + +pub(crate) fn referenced(dom: &D, root: D::NodeId, limit: usize) -> Targets { + let mut available = HashSet::new(); + let mut element_ids = HashSet::new(); + if !dom.may_have_fragment_links() { + return Targets { + referenced: available, + ids: element_ids, + }; + } + walk(dom, root, limit, |node| { + for attribute in ["id", "name"] { + if attribute == "name" && dom.node_kind(node) != NodeKind::Element("a") { + continue; + } + if let Some(value) = dom.attribute(node, attribute) { + available.insert(value.to_owned()); + if attribute == "id" { + element_ids.insert(value.to_owned()); + } + } + } + false + }); + let mut referenced = HashSet::new(); + walk(dom, root, limit, |node| { + if let Some(fragment) = dom + .attribute(node, "href") + .and_then(|href| href.strip_prefix('#')) + && !fragment.is_empty() + { + // HTML fragment navigation tries the literal fragment first and + // only percent-decodes it when no literal target exists. + if available.contains(fragment) { + referenced.insert(fragment.to_owned()); + } else { + let decoded = decode_fragment(fragment); + if available.contains(&decoded) { + referenced.insert(decoded); + } + } + } + false + }); + Targets { + referenced, + ids: element_ids, + } +} + +pub(crate) fn contains( + dom: &D, + root: D::NodeId, + limit: usize, + ids: &Targets, +) -> bool { + walk(dom, root, limit, |node| !ids.targets(dom, node).is_empty()) +} + +pub(crate) fn within( + dom: &D, + root: D::NodeId, + limit: usize, + ids: &Targets, +) -> Vec { + let mut found = Vec::new(); + walk(dom, root, limit, |node| { + for id in ids.targets(dom, node) { + if !found.iter().any(|existing| existing == id) { + found.push(id.to_owned()); + } + } + false + }); + found +} + +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/content.rs b/moli-html2md/src/content.rs new file mode 100644 index 00000000000..4ebce0590f9 --- /dev/null +++ b/moli-html2md/src/content.rs @@ -0,0 +1,86 @@ +use crate::{Dom, NodeKind}; + +pub(crate) fn has_readable_content( + dom: &D, + root: D::NodeId, + limit: usize, +) -> bool { + let mut pending = vec![(root, 0)]; + while let Some((node, depth)) = pending.pop() { + if matches!( + dom.node_kind(node), + NodeKind::Element("head" | "title" | "script" | "style" | "noscript" | "template") + ) { + continue; + } + 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("input") if crate::form::input_text(dom, node).is_some() => { + return true; + } + NodeKind::Element("textarea") => { + if let Some(value) = crate::form::textarea_text(dom, node) { + if !value.trim().is_empty() { + return true; + } + // A present live value is authoritative even when the user + // cleared it. Do not inspect serialized default children. + continue; + } + } + NodeKind::Element(_) if depth > 0 && fallback_text(dom, node).is_some() => 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 +} + +pub(crate) fn fallback_text(dom: &D, node: D::NodeId) -> Option { + for name in ["aria-label", "data-original-title", "title"] { + if let Some(value) = dom + .attribute(node, name) + .map(str::trim) + .filter(|value| !value.is_empty()) + { + return Some(value.to_owned()); + } + } + if matches!(dom.node_kind(node), NodeKind::Element("svg")) { + let mut child = dom.first_child(node); + while let Some(id) = child { + if dom.node_kind(id) == NodeKind::Element("title") { + let mut text = String::new(); + let mut title_child = dom.first_child(id); + while let Some(part) = title_child { + if let NodeKind::Text(value) = dom.node_kind(part) { + text.push_str(value); + } + title_child = dom.next_sibling(part); + } + if !text.trim().is_empty() { + return Some(text); + } + } + child = dom.next_sibling(id); + } + } + None +} 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..6beb52aa2fe --- /dev/null +++ b/moli-html2md/src/form.rs @@ -0,0 +1,50 @@ +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) +} + +pub(crate) fn textarea_text<'a, D: Dom + ?Sized>( + dom: &'a D, + node: D::NodeId, +) -> Option> { + dom.attribute(node, "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..1dbfec6bd8f --- /dev/null +++ b/moli-html2md/src/html_table.rs @@ -0,0 +1,328 @@ +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), + Literal(&'static str), +} + +/// 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: &crate::anchors::Targets, +) -> 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::Literal(value) => output.push_str(value), + 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; + } + if matches!(dom.node_kind(node), NodeKind::Element(_)) { + if dom.has_block_layout(node) { + output.push_str("
"); + tasks.push(Task::Close("div".to_owned())); + } else if dom.has_text_boundary(node) { + output.push(' '); + tasks.push(Task::Literal(" ")); + } + } + if let NodeKind::Element(tag) = dom.node_kind(node) + && !allowed(tag) + { + for id in anchor_targets.targets(dom, node) { + if emitted_anchors.insert(id.to_owned()) { + 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") => { + for id in crate::anchors::within(dom, node, limit - depth, anchor_targets) { + if emitted_anchors.insert(id.clone()) { + output.push_str(&crate::anchors::markup(&id)); + } + } + 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("textarea") => { + if let Some(value) = crate::form::textarea_text(dom, node) { + escape(&value, &mut output); + } else { + tasks.push(Task::Siblings(dom.first_child(node), depth + 1)); + } + } + 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 { None }; + 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) + { + for id in + crate::anchors::within(dom, node, limit - depth, anchor_targets) + { + if emitted_anchors.insert(id.clone()) { + output.push_str(&crate::anchors::markup(&id)); + } + } + output.push_str(&crate::mathml::render( + dom, + math, + limit - depth - relative_depth, + )); + } else { + if let Some(label) = crate::content::fallback_text(dom, node) + && !crate::content::has_readable_content(dom, node, limit - depth) + { + escape(&label, &mut output); + } 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" + | "textarea" + | "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..e6470ba79c6 100644 --- a/moli-html2md/src/lib.rs +++ b/moli-html2md/src/lib.rs @@ -1,6 +1,13 @@ +mod anchors; +mod content; mod converter; mod dom; +mod form; +mod html_table; mod machine; +mod math; +mod mathml; +mod media; mod options; mod output; mod table; @@ -11,6 +18,9 @@ pub use converter::{Converter, convert}; pub use dom::{Dom, NodeKind}; pub use options::Options; +#[doc(hidden)] +pub use media::{SrcsetCandidate, parse_srcset}; + #[cfg(test)] extern crate self as moli_html2md; diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 62ff7cd9ee6..9131672da17 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: crate::anchors::Targets, + 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 => { @@ -163,7 +174,8 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } fn take_writer(&mut self) -> Output { - let writer = self.writers.pop().expect("capture has an output"); + let mut writer = self.writers.pop().expect("capture has an output"); + writer.materialize_pending(); if let Some(parent) = self.writers.last_mut() { parent.last_link = parent.last_link.max(writer.last_link); } @@ -187,6 +199,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 +221,62 @@ 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 id in self.anchor_targets.targets(self.dom, node) { + if self.emitted_anchors.insert(id.to_owned()) { + self.writer().inline_html(&crate::anchors::markup(id)); + } + } } match tag { + "math" => { + self.emit_anchors_within(node, self.options.max_depth - depth); + 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 +285,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 +324,70 @@ 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; } + "textarea" => { + if let Some(value) = crate::form::textarea_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; + } + if tag == "pre" && !self.anchor_targets.is_empty() { + for id in + crate::anchors::within(self.dom, node, remaining, &self.anchor_targets) + { + if self.emitted_anchors.insert(id.clone()) { + self.writer().inline_html(&crate::anchors::markup(&id)); + } + } + } self.raw.clear(); let end = if tag == "pre" { Task::EndPre(self.language(node)) @@ -266,6 +405,24 @@ 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_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 +435,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 +472,101 @@ 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) + { + self.emit_anchors_within(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 let Some(label) = crate::content::fallback_text(self.dom, node) + && !subtree_has_content(self.dom, node, self.options.max_depth - depth) + { + self.writer().text(&label); + return; + } self.children(node, depth + 1); } + fn emit_anchors_within(&mut self, node: D::NodeId, remaining: usize) { + for id in crate::anchors::within(self.dom, node, remaining, &self.anchor_targets) { + if self.emitted_anchors.insert(id.clone()) { + self.writer().inline_html(&crate::anchors::markup(&id)); + } + } + } + + 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() && crate::media::safe_url(src, true)) + { + 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 +648,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 +719,88 @@ 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 { + crate::content::has_readable_content(dom, root, limit) +} + +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..9a35da5cbf2 --- /dev/null +++ b/moli-html2md/src/math.rs @@ -0,0 +1,154 @@ +/// 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 spans(text: &str) -> Vec<(usize, usize)> { + let mut steps = 0; + spans_counted(text, &mut steps) +} + +fn spans_counted(text: &str, steps: &mut usize) -> Vec<(usize, usize)> { + let bytes = text.as_bytes(); + let mut index = 0; + let mut backslashes = 0; + let mut dollar = None; + let mut double_dollar = None; + let mut paren = None; + let mut bracket = None; + let mut candidates = Vec::new(); + while index < bytes.len() { + *steps += 1; + if bytes[index] == b'$' && backslashes % 2 == 0 { + if bytes.get(index + 1) == Some(&b'$') { + if let Some(start) = double_dollar.take() { + accept_candidate(text, start, index + 2, 2, false, &mut candidates); + } else { + double_dollar = Some(index); + } + index += 2; + backslashes = 0; + continue; + } + if let Some(start) = dollar.take() { + accept_candidate(text, start, index + 1, 1, true, &mut candidates); + } else if text[index + 1..] + .chars() + .next() + .is_some_and(|ch| !ch.is_whitespace()) + { + dollar = Some(index); + } + index += 1; + backslashes = 0; + continue; + } + if bytes[index] == b'\\' && backslashes % 2 == 0 { + match bytes.get(index + 1) { + Some(b'(') => { + paren.get_or_insert(index); + } + Some(b'[') => { + bracket.get_or_insert(index); + } + Some(b')') => { + if let Some(start) = paren.take() { + accept_candidate(text, start, index + 2, 2, false, &mut candidates); + } + } + Some(b']') => { + if let Some(start) = bracket.take() { + accept_candidate(text, start, index + 2, 2, false, &mut candidates); + } + } + _ => {} + } + if matches!(bytes.get(index + 1), Some(b'(' | b'[' | b')' | b']')) { + index += 2; + backslashes = 0; + continue; + } + } + if bytes[index] == b'\\' { + backslashes += 1; + } else { + backslashes = 0; + } + index += 1; + } + candidates.sort_unstable_by_key(|candidate| candidate.0); + let mut end = 0; + candidates.retain(|candidate| { + let keep = candidate.0 >= end; + if keep { + end = candidate.1; + } + keep + }); + candidates +} + +fn accept_candidate( + text: &str, + start: usize, + end: usize, + delimiter: usize, + single_dollar: bool, + candidates: &mut Vec<(usize, usize)>, +) { + let content_start = start + delimiter; + let content_end = end - delimiter; + if content_start == content_end + || single_dollar + && (text[..content_end] + .chars() + .next_back() + .is_some_and(char::is_whitespace) + || text.as_bytes().get(end).is_some_and(u8::is_ascii_digit)) + { + return; + } + let content = &text[content_start..content_end]; + if content.as_bytes().windows(2).any(|pair| { + pair[0] == b'<' && (pair[1].is_ascii_alphabetic() || matches!(pair[1], b'/' | b'!' | b'?')) + }) || contains_markdown_resource(content) + { + return; + } + candidates.push((start, end)); +} + +fn contains_markdown_resource(text: &str) -> bool { + text.contains("](") || text.contains("][") || text.contains("![[") +} + +#[cfg(test)] +mod tests { + use super::spans_counted; + + #[test] + fn math_scan_work_is_linear_for_backslashes_and_unclosed_delimiters() { + for text in ["\\\\".repeat(8_192), "\\(x ".repeat(4_096)] { + let mut steps = 0; + let _ = spans_counted(&text, &mut steps); + assert!( + steps <= text.len(), + "{steps} steps for {} bytes", + text.len() + ); + } + } + + #[test] + fn mixed_unclosed_and_valid_math_is_scanned_once() { + for size in [256, 512, 1024, 2048] { + let text = r"\( $x_i$ ".repeat(size); + let mut steps = 0; + let spans = spans_counted(&text, &mut steps); + assert_eq!(spans.len(), size); + assert!( + steps <= text.len(), + "{steps} steps for {} bytes", + text.len() + ); + } + } +} 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..84f9e7fdcd0 --- /dev/null +++ b/moli-html2md/src/media.rs @@ -0,0 +1,301 @@ +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> { + // A responsive declaration determines the rendered resource even when a + // fallback `src` is present. Private lazy-load attributes remain fallback + // inputs and never override a valid standard declaration. + if let Some(value) = dom + .attribute(node, "srcset") + .and_then(|value| largest_srcset_candidate(value, true)) + { + return Some(value); + } + let src = direct_attribute(dom, node, "src", true); + if src.is_some_and(|value| !is_explicit_placeholder(value)) { + return src.map(Cow::Borrowed); + } + if let Some(value) = dom + .attribute(node, "data-srcset") + .and_then(|value| largest_srcset_candidate(value, true)) + { + return Some(value); + } + ["data-src", "data-lazy-src", "data-original"] + .into_iter() + .find_map(|name| direct_attribute(dom, node, name, true)) + .or(src) + .map(Cow::Borrowed) +} + +fn direct_source(dom: &D, node: D::NodeId, image: bool) -> Option<&str> { + let src = direct_attribute(dom, node, "src", image); + if src.is_some_and(is_explicit_placeholder) { + return direct_attribute(dom, node, "data-src", image) + .or_else(|| direct_attribute(dom, node, "data-lazy-src", image)) + .or_else(|| direct_attribute(dom, node, "data-original", image)) + .or(src); + } + src.or_else(|| direct_attribute(dom, node, "data-src", image)) + .or_else(|| direct_attribute(dom, node, "data-lazy-src", image)) + .or_else(|| direct_attribute(dom, node, "data-original", image)) +} + +fn direct_attribute<'a, D: Dom + ?Sized>( + dom: &'a D, + node: D::NodeId, + name: &str, + image: bool, +) -> Option<&'a str> { + dom.attribute(node, name).map(str::trim).filter(|value| { + !value.is_empty() + && !value.starts_with('#') + && *value != "about:blank" + && safe_url(value, image) + }) +} + +fn is_explicit_placeholder(value: &str) -> bool { + let lower = value.to_ascii_lowercase(); + let path = lower + .split(['?', '#']) + .next() + .unwrap_or(&lower) + .trim_end_matches('/'); + matches!( + path.rsplit('/').next().unwrap_or_default(), + "placeholder.gif" + | "placeholder.png" + | "spacer.gif" + | "spacer.png" + | "transparent.gif" + | "transparent.png" + | "blank.gif" + | "blank.png" + ) +} + +#[doc(hidden)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SrcsetCandidate<'a> { + pub url: &'a str, + pub descriptor: &'a str, + pub score: f64, +} + +#[doc(hidden)] +pub fn parse_srcset(srcset: &str) -> Vec> { + let bytes = srcset.as_bytes(); + let mut offset = 0; + let mut candidates = Vec::new(); + while offset < bytes.len() { + while offset < bytes.len() && (bytes[offset].is_ascii_whitespace() || bytes[offset] == b',') + { + offset += 1; + } + let url_start = offset; + while offset < bytes.len() && !bytes[offset].is_ascii_whitespace() { + offset += 1; + } + if url_start == offset { + break; + } + let mut url_end = offset; + while url_end > url_start && bytes[url_end - 1] == b',' { + url_end -= 1; + } + let url = &srcset[url_start..url_end]; + let ended_with_comma = url_end < offset; + if ended_with_comma { + if !url.is_empty() { + candidates.push(SrcsetCandidate { + url, + descriptor: "", + score: 1.0, + }); + } + continue; + } + + let descriptor_start = offset; + let mut parentheses = 0usize; + while offset < bytes.len() { + match bytes[offset] { + b'(' => parentheses += 1, + b')' => parentheses = parentheses.saturating_sub(1), + b',' if parentheses == 0 => break, + _ => {} + } + offset += 1; + } + let descriptor = srcset[descriptor_start..offset].trim(); + let score = if descriptor.is_empty() { + Some(1.0) + } else { + descriptor_score(descriptor) + }; + if let Some(score) = score + && !url.is_empty() + { + candidates.push(SrcsetCandidate { + url, + descriptor, + score, + }); + } + } + candidates +} + +fn descriptor_score(descriptor: &str) -> Option { + let mut width = None; + let mut height = None; + let mut density = None; + for token in descriptor.split_ascii_whitespace() { + if let Some(value) = token.strip_suffix('w') { + if width.is_some() { + return None; + } + width = Some(valid_positive_integer(value)?); + } else if let Some(value) = token.strip_suffix('h') { + if height.is_some() { + return None; + } + height = Some(valid_positive_integer(value)?); + } else if let Some(value) = token.strip_suffix('x') { + if density.is_some() { + return None; + } + density = Some(valid_positive_float(value)?); + } else { + return None; + } + } + match (width, height, density) { + (Some(width), _, None) => Some(width as f64), + (None, None, Some(density)) => Some(density), + _ => None, + } +} + +fn valid_positive_integer(value: &str) -> Option { + (!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())) + .then(|| value.parse::().ok()) + .flatten() + .filter(|value| *value > 0) +} + +fn valid_positive_float(value: &str) -> Option { + let bytes = value.as_bytes(); + if bytes.is_empty() || bytes[0] == b'+' { + return None; + } + let mut offset = usize::from(bytes[0] == b'-'); + if offset == bytes.len() { + return None; + } + let integer_start = offset; + while offset < bytes.len() && bytes[offset].is_ascii_digit() { + offset += 1; + } + let has_integer = offset > integer_start; + let mut has_fraction = false; + if bytes.get(offset) == Some(&b'.') { + offset += 1; + let fraction = offset; + while offset < bytes.len() && bytes[offset].is_ascii_digit() { + offset += 1; + } + if fraction == offset { + return None; + } + has_fraction = true; + } + if !has_integer && !has_fraction { + return None; + } + if matches!(bytes.get(offset), Some(b'e' | b'E')) { + offset += 1; + if matches!(bytes.get(offset), Some(b'+' | b'-')) { + offset += 1; + } + let exponent = offset; + while offset < bytes.len() && bytes[offset].is_ascii_digit() { + offset += 1; + } + if exponent == offset { + return None; + } + } + (offset == bytes.len()) + .then(|| value.parse::().ok()) + .flatten() + .filter(|value| value.is_finite() && *value >= 0.0) +} + +fn largest_srcset_candidate(srcset: &str, image: bool) -> Option> { + parse_srcset(srcset) + .into_iter() + .filter(|candidate| safe_url(candidate.url, image)) + .max_by(|left, right| left.score.total_cmp(&right.score)) + .map(|candidate| Cow::Owned(candidate.url.to_owned())) +} + +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, tag == "img") { + 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, false) + && 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..50189b29ed8 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, @@ -32,13 +34,16 @@ pub(crate) struct Writer<'a> { space: bool, preserved_spaces: String, breaks: usize, + // Text nodes separated only by transparent inline DOM wrappers still form + // one author text stream. Delay escaping until a real formatting boundary + // so TeX delimiters can span those wrappers without changing semantics. + pending_text: String, code: Option, // End of the last emitted Markdown code span in the local output. Only // actual output after this position separates it from another code span. 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,41 +57,37 @@ 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 { .. })) { return false; } + self.flush_pending_text(); self.flush_code(); self.desired.push(style); true } pub(crate) fn pop_style(&mut self) { + self.flush_pending_text(); self.flush_code(); self.desired.pop(); } pub(crate) fn end_link(&mut self, serial: usize) { + self.flush_pending_text(); self.flush_code(); if self.last_link < serial { // Empty anchors still carry a destination. Materialize the link @@ -97,7 +98,38 @@ impl<'a> Writer<'a> { } pub(crate) fn text(&mut self, text: &str) { + self.pending_text.push_str(text); + } + + fn flush_pending_text(&mut self) { + if self.pending_text.is_empty() { + return; + } + self.flush_code(); + let text = std::mem::take(&mut self.pending_text); + let mut consumed = 0; + for (start, end) in crate::math::spans(&text) { + self.plain_text(&text[consumed..start]); + let math = &text[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; + consumed = end; + } + self.plain_text(&text[consumed..]); + } + + pub(crate) fn inline_html(&mut self, markup: &str) { + self.flush_pending_text(); 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; @@ -147,6 +179,7 @@ impl<'a> Writer<'a> { } pub(crate) fn code(&mut self, text: &str) { + self.flush_pending_text(); if text.starts_with(is_space) { self.flush_code(); self.space = true; @@ -174,6 +207,7 @@ impl<'a> Writer<'a> { } pub(crate) fn code_with_edges(&mut self, text: &str, preformatted: bool) { + self.flush_pending_text(); // An empty element has no visible edge. Keep the pending code until // the next visible text or element decides whether it needs a gap. if text.is_empty() { @@ -203,6 +237,7 @@ impl<'a> Writer<'a> { } pub(crate) fn image(&mut self, alt: &str, src: &str, title: Option<&str>) { + self.flush_pending_text(); self.flush_code(); self.prepare_inline('!'); self.output.push_str("!["); @@ -214,19 +249,19 @@ 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; } pub(crate) fn boundary(&mut self, lines: usize) { + self.flush_pending_text(); self.has_blocks |= lines > 1; self.flush_code(); self.close_to(0, None); @@ -236,6 +271,7 @@ impl<'a> Writer<'a> { } pub(crate) fn hard_break(&mut self) { + self.flush_pending_text(); self.flush_code(); self.close_to(0, None); self.flush_spaces(false); @@ -263,6 +299,7 @@ impl<'a> Writer<'a> { } pub(crate) fn finish(mut self) -> Output { + self.flush_pending_text(); self.flush_code(); self.close_to(0, None); self.flush_spaces(false); @@ -272,6 +309,11 @@ impl<'a> Writer<'a> { self.prefix } + pub(crate) fn materialize_pending(&mut self) { + self.flush_pending_text(); + self.flush_code(); + } + fn is_empty(&self) -> bool { self.output.is_empty() && self.prefix.is_empty() } @@ -311,13 +353,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 +414,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 +445,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 +563,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 +589,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..02aadc4d3e7 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -1,6 +1,7 @@ mod support; -use moli_html2md::{Converter, Options}; +use moli_html2md::{Converter, Dom, NodeKind, Options, parse_srcset}; +use std::cell::Cell; use support::{Tree, rendered_html}; fn markdown(html: &str, preformatted_code: bool) -> String { @@ -12,6 +13,330 @@ 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 transparent_inline_wrappers_do_not_change_tex_or_activate_markdown_resources() { + use pulldown_cmark::{Event, Options as MarkdownOptions, Parser}; + for source in [ + r"

$x_i + \alpha$

", + r"

$x_i + \alpha$

", + ] { + let result = markdown(source, 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"], "{result}"); + } + for source in [ + "$[download](https://example.org/file)$", + "$![diagram](https://example.org/pixel)$", + ] { + let result = rendered_html(&markdown(&format!("

{source}

"), false)); + assert!(!result.contains("Model $x_i + \alpha$.

", + r"

Model $x_i + \alpha$.

", + r"
  • Model $x_i + \alpha$.
", + r"
Model $x_i + \alpha$.
", + ] { + let result = markdown(source, 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"], "{source}: {result}"); + } + let result = markdown( + r"
Equation

$x + y$

$z + 1$

", + false, + ); + assert!(result.contains(""), "{result}"); + assert!(result.contains("$x + y$\n\n$z + 1$"), "{result}"); +} + +#[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", + "Notes", + ] { + 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 embedded_media_uses_the_same_url_policy_in_all_output_paths() { + let media = ""; + for source in [ + media.to_owned(), + format!("
{media}
"), ] { - assert_eq!(markdown(html, false), "ab"); + let result = markdown(&source, false); + assert!(result.contains("/clip.mp4"), "{result}"); + assert!(!result.contains("javascript:"), "{result}"); + assert!(!result.contains("data:image"), "{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 [ @@ -445,6 +1136,122 @@ fn embedded_image_references_survive_regardless_of_pixel_content() { } } +#[test] +fn responsive_images_preserve_url_commas_and_use_declared_candidates() { + let comma_url = "https://cdn.example/c_fill,w_640,h_480/photo.jpg"; + for content in [ + format!("Photo"), + format!("Photo"), + format!( + "
Photo
" + ), + ] { + let result = markdown(&content, false); + assert!(result.contains(comma_url), "{result}"); + } + let result = markdown( + "Photo", + false, + ); + assert!(result.contains("/current.jpg"), "{result}"); + assert!(!result.contains("/old.jpg"), "{result}"); + let result = markdown( + "Photo", + false, + ); + assert!(result.contains("/large.jpg"), "{result}"); + for source in [ + "Photo", + "Photo", + ] { + let result = markdown(source, false); + assert!(!result.contains("/old.jpg"), "{result}"); + } + let defaults = markdown( + "PhotoSafe", + false, + ); + assert!(defaults.contains("![Photo](/large.jpg)"), "{defaults}"); + assert!(defaults.contains("![Safe](/safe.jpg)"), "{defaults}"); +} + +#[test] +fn fragment_targets_keep_all_aliases_and_delegated_math_descendants() { + let result = markdown( + "ModernLegacyEquationTargetx", + false, + ); + for id in ["modern", "legacy", "eq"] { + assert!(result.contains(&format!("")), "{result}"); + } +} + +struct CountingDom<'a> { + tree: &'a Tree, + calls: Cell, +} + +impl Dom for CountingDom<'_> { + type NodeId = usize; + + fn node_kind(&self, node: usize) -> NodeKind<'_> { + self.calls.set(self.calls.get() + 1); + self.tree.node_kind(node) + } + fn first_child(&self, node: usize) -> Option { + self.calls.set(self.calls.get() + 1); + self.tree.first_child(node) + } + fn next_sibling(&self, node: usize) -> Option { + self.calls.set(self.calls.get() + 1); + self.tree.next_sibling(node) + } + fn attribute(&self, node: usize, name: &str) -> Option<&str> { + self.calls.set(self.calls.get() + 1); + self.tree.attribute(node, name) + } +} + +#[test] +fn transparent_depth_keeps_dom_queries_linear() { + let measure = |depth: usize| { + let html = format!( + "{}content{}", + "".repeat(depth), + "".repeat(depth) + ); + let tree = Tree::parse(&html); + let dom = CountingDom { + tree: &tree, + calls: Cell::new(0), + }; + let result = Converter::default().convert(&dom, tree.root); + assert_eq!(result, "content"); + dom.calls.get() + }; + let shallow = measure(64); + let deep = measure(128); + assert!( + deep < shallow * 3, + "query growth was not linear: {shallow} -> {deep}" + ); +} + +#[test] +fn readable_fallbacks_survive_all_table_representations() { + for wrapper in [ + "

{}

", + "
{}
", + "
{}
", + ] { + let content = " Chart title"; + let result = markdown(&wrapper.replace("{}", content), false); + for expected in ["Download report", "Open panel", "Chart title"] { + assert!(result.contains(expected), "missing {expected}: {result}"); + } + } +} + #[test] fn list_paragraphs_and_code_blocks_require_blank_lines_between_items() { for (html, expected) in [ @@ -488,3 +1295,97 @@ fn fallback_block_elements_separate_neighboring_words() { ); } } + +#[test] +fn live_textarea_value_replaces_or_clears_serialized_default_in_all_paths() { + for wrapper in [ + "
{}
", + "
{}
", + ] { + let current = markdown( + &wrapper.replace( + "{}", + "", + ), + false, + ); + assert!(current.contains("Current user text"), "{current}"); + assert!(!current.contains("Old default"), "{current}"); + + let cleared = markdown( + &wrapper.replace("{}", ""), + false, + ); + assert!(!cleared.contains("Old default"), "{cleared}"); + } +} + +#[test] +fn html_table_math_delegation_preserves_referenced_descendant_targets() { + let result = markdown( + "Term
x
", + false, + ); + assert!(result.contains(""), "{result}"); + assert!(result.contains(""), "{result}"); + + let alternative = markdown( + "Term
x
", + false, + ); + assert!( + alternative.contains(""), + "{alternative}" + ); + assert!(alternative.contains(""), "{alternative}"); +} + +#[test] +fn srcset_rejects_invalid_numbers_and_commas_inside_parentheses() { + let result = markdown( + "DensityParentheses", + false, + ); + assert!(result.contains("![Density](/safe.jpg)"), "{result}"); + assert!( + result.contains("![Parentheses](/safe-parentheses.jpg)"), + "{result}" + ); + assert!(!result.contains("phantom.jpg"), "{result}"); +} + +#[test] +fn srcset_density_uses_the_html_floating_point_grammar() { + let result = markdown( + "FractionExponentZeroNegative zeroInvalid plusInvalid trailing dotNegative", + false, + ); + for expected in [ + "![Fraction](/fraction.jpg)", + "![Exponent](/exponent.jpg)", + "![Zero](/zero.jpg)", + "![Negative zero](/negative-zero.jpg)", + ] { + assert!(result.contains(expected), "missing {expected}: {result}"); + } + for rejected in ["invalid-plus.jpg", "invalid-dot.jpg", "negative.jpg"] { + assert!(!result.contains(rejected), "accepted {rejected}: {result}"); + } +} + +#[test] +fn srcset_recovers_only_the_future_compatible_width_height_pair() { + let paired = parse_srcset("/photo.jpg 640w 480h"); + assert_eq!(paired.len(), 1); + assert_eq!(paired[0].url, "/photo.jpg"); + assert_eq!(paired[0].score, 640.0); + + for invalid in [ + "/height-only.jpg 480h", + "/duplicate-width.jpg 640w 800w", + "/duplicate-height.jpg 640w 480h 720h", + "/density-height.jpg 2x 480h", + ] { + assert!(parse_srcset(invalid).is_empty(), "accepted {invalid}"); + } +} 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/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs index fe2aec5152c..30bcaf93c34 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs @@ -1517,6 +1517,15 @@ impl JsContextHost { .retained_stylesheet_query_snapshot_for_document(document) } + pub(crate) fn elements_with_bounded_final_opacity( + &self, + document: DomHandle, + elements: impl IntoIterator, + ) -> std::collections::HashSet { + self.style_engine + .elements_with_bounded_final_opacity(self.dom_host(), document, elements) + } + #[cfg(test)] pub(crate) fn computed_style_cache_generation_for_document_for_test( &self, diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index 7baab27cf72..e997b7be906 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -167,6 +167,7 @@ pub(crate) use shadow_dom::{ }; pub(crate) use styles::{ ComputedStyleRead, StyleMode, active_css_animation_transform_value, + computed_style_own_visibility_values_for_document_snapshot, computed_style_properties_for_inspector_handle, computed_style_property_values_for_document_snapshot, css_animation_start_applies, cssom_style_entry_requires_structured_parser, diff --git a/moli-renderer-v8/src/native_bridge/element/styles.rs b/moli-renderer-v8/src/native_bridge/element/styles.rs index 85d4b007051..77243464ec6 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles.rs @@ -619,6 +619,26 @@ pub(crate) fn computed_style_property_values_for_document_snapshot( .collect() } +pub(crate) fn computed_style_own_visibility_values_for_document_snapshot( + host: &JsContextHost, + handles: impl IntoIterator, +) -> Vec { + let mut observation = StyleObservation::new(host); + handles + .into_iter() + .map(|handle| { + let Some(DocumentSnapshotStyleComputation::Available(_)) = + style_computation_context_for_document_snapshot(host, handle) + else { + return false; + }; + observation + .read(handle) + .computed_style_has_own_visibility_value() + }) + .collect() +} + pub(crate) fn computed_style_properties_for_inspector_handle( host: &JsContextHost, handle: DomHandle, diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs index 28594b70957..e44d758b898 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs @@ -220,6 +220,14 @@ impl<'a> ComputedStyleRead<'a> { Some(self.stylo_style.as_ref()?.rendered_style_facts()) } + pub(in crate::native_bridge::element) fn computed_style_has_own_visibility_value( + &self, + ) -> bool { + self.stylo_style + .as_ref() + .is_some_and(StyloComputedStyleSnapshot::has_own_visibility_value) + } + pub(crate) fn computed_values(&self) -> Option> { self.stylo_style .as_ref() diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index ee2f639de6a..8322693f038 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -2,18 +2,165 @@ 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, HashSet}; 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, final_opacity_elements) = 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(), "baseline-shift".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(), + "text-shadow".to_owned(), + ], + ); + let own_visibility_values = self + .vm() + .computed_style_own_visibility_values_for_document_snapshot(nodes.iter().copied()); + let own_visibility: HashMap<_, _> = + nodes.iter().copied().zip(own_visibility_values).collect(); + let animation_candidates = nodes + .iter() + .copied() + .zip(values.iter()) + .filter(|(_, values)| values.get(2).is_some_and(|value| value == "0")) + .map(|(node, _)| node); + let final_opacity_elements = self + .vm() + .elements_with_bounded_final_opacity_for_document_snapshot(animation_candidates); + let styles = nodes + .into_iter() + .zip(values) + .map(|(node, mut values)| { + let text_shadow = 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(text_shadow); + values.push(background_images.get(&node).cloned().unwrap_or_default()); + values.push( + own_visibility + .get(&node) + .copied() + .unwrap_or_default() + .to_string(), + ); + (node, values) + }) + .collect::>(); + (styles, final_opacity_elements) + } else { + (Vec::new(), HashSet::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(), + final_opacity_elements, + ); } let mut dom = self.vm().document_runtime.dom_host().dom().clone(); @@ -33,7 +180,12 @@ 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(), + final_opacity_elements, + ), } } @@ -181,14 +333,25 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String { + render_markdown_document_with_styles(dom, Vec::new(), None, HashSet::new()) +} + +fn render_markdown_document_with_styles( + dom: &NativeDom, + styles: Vec<(NativeNodeId, Vec)>, + base_url: Option<&url::Url>, + final_opacity_elements: HashSet, +) -> String { let root = dom.body_node_id().unwrap_or(dom.document_node_id()); + let visible = visibility::MarkdownDom::new(dom, styles, base_url, final_opacity_elements); 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 +556,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..efbd79caeec --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -0,0 +1,596 @@ +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>, + unchecked_controls: HashSet, + fragment_links: bool, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum VisibilityMode { + Normal, + RootVeil, + DisclosureVeil, + Hidden, +} + +impl<'a> MarkdownDom<'a> { + pub(super) fn new( + dom: &'a NativeDom, + styles: impl IntoIterator)>, + base_url: Option<&Url>, + final_opacity_elements: HashSet, + ) -> 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(); + let mut non_solid_backgrounds = HashSet::new(); + if styles + .iter() + .any(|(_, values)| values.get(11).is_some_and(|value| !value.is_empty())) + { + for (node, values) in &styles { + let own_color = values.get(11).and_then(|value| css_color(value)); + let own = own_color.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 own_image = values + .get(13) + .is_some_and(|image| !image.is_empty() && image != "none"); + let inherited_image = own.is_none() + && dom + .parent_node(*node) + .is_some_and(|parent| non_solid_backgrounds.contains(&parent)); + let translucent = own_color.is_some_and(|color| color.3 > 0.0 && color.3 <= 0.99); + if own_image || inherited_image || translucent { + non_solid_backgrounds.insert(*node); + } + } + } + let mut disclosures = HashSet::new(); + let mut excerpts = HashSet::new(); + let targets: HashMap<_, _> = styles + .iter() + .filter_map(|(node, _)| Dom::attribute(dom, *node, "id").map(|id| (id, *node))) + .collect(); + let hidden_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(controlled) = Dom::attribute(dom, *node, "aria-controls") + { + disclosures.extend( + controlled + .split_ascii_whitespace() + .filter(|id| target_is_disclosure(dom, &targets, 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) = hidden_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 disclosure_roots: HashSet<_> = disclosures + .iter() + .filter_map(|id| targets.get(id).copied()) + .collect(); + let hidden_nodes: HashSet<_> = styles + .iter() + .filter_map(|(node, values)| { + (values.first().is_some_and(|value| value == "none") + || values + .get(1) + .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse"))) + .then_some(*node) + }) + .collect(); + let mut disclosure_paths = HashSet::new(); + for &target in &disclosure_roots { + let mut chain = Vec::new(); + let mut current = dom.parent_node(target); + while let Some(node) = current { + chain.push(node); + current = dom.parent_node(node); + } + if let Some(last_hidden) = chain.iter().rposition(|node| hidden_nodes.contains(node)) { + disclosure_paths.extend(chain.into_iter().take(last_hidden + 1)); + } + } + 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(); + let mut unchecked_controls = HashSet::new(); + let mut visibility_modes = HashMap::new(); + for (node, values) in styles { + let role = Dom::attribute(dom, node, "role").unwrap_or_default(); + if matches!( + Dom::node_kind(dom, node), + NodeKind::Element("input" | "textarea") + ) && let Some(element) = dom.node(node).and_then(|node| node.as_element()) + { + resolved_urls + .entry(node) + .or_insert_with(HashMap::new) + .insert("value".to_owned(), element.input_value()); + if matches!(Dom::node_kind(dom, node), NodeKind::Element("input")) + && element.checked() + { + resolved_urls + .entry(node) + .or_insert_with(HashMap::new) + .insert("checked".to_owned(), String::new()); + } else if matches!(Dom::node_kind(dom, node), NodeKind::Element("input")) { + unchecked_controls.insert(node); + } + } + // 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_root = disclosure_roots.contains(&node) + || 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 disclosure_path = disclosure_paths.contains(&node); + let parent_is_disclosure_path = dom + .parent_node(node) + .is_some_and(|parent| disclosure_paths.contains(&parent)); + if disclosure_path { + invisible.insert(node); + } + // 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 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) + && !non_solid_backgrounds.contains(&node) + && values + .get(12) + .is_none_or(|shadow| shadow.is_empty() || shadow == "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 parent_visibility = dom + .parent_node(node) + .and_then(|parent| visibility_modes.get(&parent).copied()) + .unwrap_or(VisibilityMode::Normal); + let computed_visibility = values.get(1).map(String::as_str).unwrap_or("visible"); + let visibility_mode = if document_root + && document_visibility_is_hidden + && matches!(computed_visibility, "hidden" | "collapse") + { + VisibilityMode::RootVeil + } else if disclosure_root && matches!(computed_visibility, "hidden" | "collapse") { + VisibilityMode::DisclosureVeil + } else if computed_visibility == "visible" { + VisibilityMode::Normal + } else if matches!(computed_visibility, "hidden" | "collapse") { + match parent_visibility { + VisibilityMode::RootVeil + if values.get(14).is_none_or(|value| value != "true") => + { + VisibilityMode::RootVeil + } + VisibilityMode::DisclosureVeil + if values.get(14).is_none_or(|value| value != "true") => + { + VisibilityMode::DisclosureVeil + } + _ => VisibilityMode::Hidden, + } + } else { + parent_visibility + }; + visibility_modes.insert(node, visibility_mode); + if ((values.first().is_some_and(|value| value == "none") + || values + .get(2) + .is_some_and(|value| value.parse::() == Ok(0.0)) + && !lazy_media + && !final_opacity_elements.contains(&node) + && !document_root) + && !disclosure_root + && !disclosure_path) + || uninitialized_template + || tracking_pixel + || (zero_contrast_leaf && !disclosure_root && !disclosure_path) + || (parent_is_disclosure_path && !disclosure_root && !disclosure_path) + || dom + .parent_node(node) + .is_some_and(|parent| suppressed.contains(&parent)) + && !disclosure_root + && !disclosure_path + { + 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 vertical_align = values.get(7).map(String::as_str).unwrap_or_default(); + if vertical_align == "super" { + superscripts.insert(node); + } else if vertical_align == "sub" { + 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 visibility_mode == VisibilityMode::Hidden && !disclosure_root && !disclosure_path { + invisible.insert(node); + } + } + Self { + dom, + suppressed, + invisible, + blocks, + inline_boundaries, + superscripts, + subscripts, + resolved_urls, + unchecked_controls, + 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 target_is_disclosure( + dom: &D, + targets: &HashMap<&str, D::NodeId>, + id: &str, +) -> bool { + targets.get(id).is_some_and(|target| { + !Dom::attribute(dom, *target, "role").is_some_and(|role| { + ["dialog", "alertdialog", "menu"] + .iter() + .any(|excluded| role.eq_ignore_ascii_case(excluded)) + }) + }) +} + +fn px(value: &str) -> Option { + value.strip_suffix("px")?.trim().parse().ok() +} + +fn resolve_srcset(base_url: &Url, value: &str) -> Option { + let resolved: Vec<_> = moli_html2md::parse_srcset(value) + .into_iter() + .filter_map(|candidate| { + let url = base_url.join(candidate.url).ok()?; + Some(if candidate.descriptor.is_empty() { + url.to_string() + } else { + format!("{url} {}", candidate.descriptor) + }) + }) + .collect(); + (!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> { + if name == "checked" && self.unchecked_controls.contains(&node) { + return None; + } + 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..59e21f4ecca --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -0,0 +1,409 @@ +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 hidden text

+ +

Animated revealed text

+ +

Overridden animation text

+ +

Animated rotation text

+

Zero-duration reveal text

+

Repeating reveal text

+

Reverse reveal text

+
ActiveReviewed
+

Mass 2.4 × 10−17 J; mn

+

Account settings

+ + 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 313131", "Parser trap", "Accessible helper", "Faded text", "Animated revealed 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", "Animated hidden text", "Overridden animation text", "Animated rotation text", "Zero-duration reveal text", "Repeating reveal text", "Reverse reveal text", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { + assert!(!output.contains(omitted), "leaked {omitted}: {output}"); + } + assert!(output.contains("Account settings"), "{output}"); + assert!(!output.contains("settings"), "{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
Independent hidden text
'; + "#).unwrap(); + let root_visibility = page.render_page_dump(options(false)); + assert!(root_visibility.contains("Font loading veil"), "{root_visibility}"); + assert!(!root_visibility.contains("Independent hidden text"), "{root_visibility}"); + 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.head.innerHTML = ``; + 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 = ` + +
Hidden unrelated sibling
Expandable history
Nested hidden template
Nested dialog template
+ + + `; + "##).unwrap(); + let expanded = page.render_page_dump(options(false)); + assert!(expanded.contains("Expandable history"), "{expanded}"); + assert!(expanded.contains("Visibility disclosure"), "{expanded}"); + assert!(!expanded.contains("Hidden unrelated sibling"), "{expanded}"); + assert!(!expanded.contains("Nested hidden template"), "{expanded}"); + assert!(!expanded.contains("Nested dialog template"), "{expanded}"); + assert!(!expanded.contains("Hidden template"), "{expanded}"); + page.vm_mut().eval(r##" + document.body.innerHTML = ` + + `; + "##).unwrap(); + let nested_visibility = page.render_page_dump(options(false)); + assert!(nested_visibility.contains("Full disclosure body"), "{nested_visibility}"); + assert!(!nested_visibility.contains("Nested hidden duplicate"), "{nested_visibility}"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = ` + + +

Account settings

`; + "#).unwrap(); + let cascaded_visibility = page.render_page_dump(options(false)); + assert!(cascaded_visibility.contains("Styled disclosure"), "{cascaded_visibility}"); + assert!(!cascaded_visibility.contains("Stylesheet hidden duplicate"), "{cascaded_visibility}"); + assert!(cascaded_visibility.contains("Account settings"), "{cascaded_visibility}"); + assert!(!cascaded_visibility.contains("settings"), "{cascaded_visibility}"); + page.vm_mut().eval(r#" + document.body.style.visibility = 'hidden'; + document.body.innerHTML = '
Root veil text
Root stylesheet hidden duplicate
'; + "#).unwrap(); + let cascaded_root_visibility = page.render_page_dump(options(false)); + assert!(cascaded_root_visibility.contains("Root veil text"), "{cascaded_root_visibility}"); + assert!(!cascaded_root_visibility.contains("Root stylesheet hidden duplicate"), "{cascaded_root_visibility}"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = ` +
+

Independent variable hidden content

+

Hidden fallback content

+

Invalid variable inherits the veil

+

Variable fallback inherits the veil

+

Origin revert inherits the veil

+

Layer revert inherits the veil

+
`; + "#).unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('variable-hidden')).visibility").unwrap(), "hidden"); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('fallback-hidden')).visibility").unwrap(), "hidden"); + let inherited_visibility = page.render_page_dump(options(false)); + for text in ["Invalid variable inherits the veil", "Variable fallback inherits the veil", "Origin revert inherits the veil", "Layer revert inherits the veil"] { + assert!(inherited_visibility.contains(text), "missing {text}: {inherited_visibility}"); + } + for text in ["Independent variable hidden content", "Hidden fallback content"] { + assert!(!inherited_visibility.contains(text), "leaked {text}: {inherited_visibility}"); + } + page.vm_mut().eval(r#" + document.body.style.visibility = ''; + document.head.innerHTML = ''; + document.body.innerHTML = '

Count 992

'; + "#).unwrap(); + let inactive_keyframes = page.render_page_dump(options(false)); + assert!(inactive_keyframes.contains("Count 2"), "{inactive_keyframes}"); + assert!(!inactive_keyframes.contains("Count 992"), "{inactive_keyframes}"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + "#).unwrap(); + let active_keyframes = page.render_page_dump(options(false)); + assert!(active_keyframes.contains("Count 992"), "{active_keyframes}"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = '

Scoped count 992

'; + document.getElementById('shadow-host').attachShadow({mode:'open'}).innerHTML = ''; + "#).unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('scoped-count')).opacity").unwrap(), "0"); + let scoped_keyframes = page.render_page_dump(options(false)); + assert!(scoped_keyframes.contains("Scoped count 2"), "{scoped_keyframes}"); + assert!(!scoped_keyframes.contains("Scoped count 992"), "{scoped_keyframes}"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = '

Layered count 992

Repeated count 992

'; + "#).unwrap(); + for id in ["layered-count", "repeated-count"] { + assert_eq!(page.vm_mut().eval(&format!("getComputedStyle(document.getElementById('{id}')).opacity")).unwrap(), "0"); + } + let keyframe_priority = page.render_page_dump(options(false)); + assert!(keyframe_priority.contains("Layered count 2"), "{keyframe_priority}"); + assert!(keyframe_priority.contains("Repeated count 2"), "{keyframe_priority}"); + assert!(!keyframe_priority.contains("Layered count 992"), "{keyframe_priority}"); + assert!(!keyframe_priority.contains("Repeated count 992"), "{keyframe_priority}"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = ` +

Leading none kept

+

Middle none kept

+

Trailing none kept

+

Wrong slot hidden992

+

Escaped name kept

+

Reveal then conceal hidden992

+

Conceal then reveal kept

+

Reveal then transform kept

+

Reveal then middle kept

+

Middle then reveal kept

+

Middle alone hidden992

+

Reveal then no fill kept

+

No fill then reveal kept

+

Reveal then backwards kept

+

Reveal then paused hidden992

+

Reveal then infinite hidden992

`; + "#).unwrap(); + for strip_css in [false, true] { + let animation_lists = page.render_page_dump(options(strip_css)); + for text in [ + "Leading none kept", + "Middle none kept", + "Trailing none kept", + "Escaped name kept", + "Conceal then reveal kept", + "Reveal then transform kept", + "Reveal then middle kept", + "Middle then reveal kept", + "Reveal then no fill kept", + "No fill then reveal kept", + "Reveal then backwards kept", + ] { + assert!(animation_lists.contains(text), "missing {text}: {animation_lists}"); + } + for text in [ + "Wrong slot hidden99", + "Reveal then conceal hidden99", + "Middle alone hidden99", + "Reveal then paused hidden99", + "Reveal then infinite hidden99", + ] { + assert!(!animation_lists.contains(text), "leaked {text}: {animation_lists}"); + } + assert!(animation_lists.contains("Wrong slot 2"), "{animation_lists}"); + assert!(animation_lists.contains("Reveal then conceal 2"), "{animation_lists}"); + assert!(animation_lists.contains("Middle alone 2"), "{animation_lists}"); + assert!(animation_lists.contains("Reveal then paused 2"), "{animation_lists}"); + assert!(animation_lists.contains("Reveal then infinite 2"), "{animation_lists}"); + } + page.vm_mut().eval(r#" + const unrelatedRules = Array.from({length:128}, (_, index) => `@keyframes unused${index}{to{opacity:1}}`).join(''); + const unrelatedNodes = Array.from({length:128}, (_, index) => `hidden${index}`).join(''); + document.head.innerHTML = ``; + document.body.innerHTML = `

Scale ${unrelatedNodes}kept

`; + "#).unwrap(); + crate::style_engine::reset_final_opacity_animation_query_count_for_test(); + let scaled_keyframes = page.render_page_dump(options(false)); + assert!(scaled_keyframes.contains("Scale kept"), "{scaled_keyframes}"); + assert_eq!(crate::style_engine::final_opacity_animation_query_count_for_test(), 1); + page.vm_mut().eval(r##" + document.body.innerHTML = ` + + + + + + + + + + + + + + - + + + + + +
Actual next disclosure
+ + + + `; + "##).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("Hidden read-only state"), "{related}"); + assert!(!related.contains("Hidden commented state"), "{related}"); + assert!(!related.contains("Query-selected history"), "{related}"); + assert!(!related.contains("Function-revealed records"), "{related}"); + assert!(!related.contains("Paired expandable results"), "{related}"); + assert!(!related.contains("Hidden analytics metadata"), "{related}"); + assert!(!related.contains("Unreachable hidden state"), "{related}"); + assert!(!related.contains("Hidden anchor metadata"), "{related}"); + assert!(!related.contains("Actual next disclosure"), "{related}"); + assert!(!related.contains("Function-read hidden state"), "{related}"); + assert!(!related.contains("Unrelated mutation hidden state"), "{related}"); + page.vm_mut().eval("document.querySelector('.hovl a').click()").unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('results')).display").unwrap(), "inline"); + let shown_pair = page.render_page_dump(options(false)); + assert!(shown_pair.contains("Paired expandable results"), "{shown_pair}"); + page.vm_mut().eval("document.querySelectorAll('.hovl a')[1].click()").unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('results')).display").unwrap(), "none"); + assert!(!page.render_page_dump(options(false)).contains("Paired expandable results")); + page.vm_mut().eval("document.querySelector('button[onclick*=records]').click()").unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('records')).display").unwrap(), "block"); + assert!(page.render_page_dump(options(false)).contains("Function-revealed records")); + page.vm_mut().eval(r#" + document.body.innerHTML = ` +

Visible gradient text

+

Visible inherited gradient text

+
Photo
`; + "#).unwrap(); + let painted = page.render_page_dump(options(false)); + assert!(painted.contains("Visible gradient text"), "{painted}"); + assert!(painted.contains("Visible inherited gradient text"), "{painted}"); + assert!(painted.contains("![Photo](https://example.test/photo.png)"), "{painted}"); + page.vm_mut().eval(r##" + document.body.innerHTML = ` +

Visible on grey

+

Visible shadow

+

Hidden on opaque child

+

A detailed review... Read more

`; + "##).unwrap(); + let composite = page.render_page_dump(options(false)); + assert!(composite.contains("Visible on grey"), "{composite}"); + assert!(composite.contains("Visible shadow"), "{composite}"); + assert!(!composite.contains("Hidden on opaque child"), "{composite}"); + assert!(composite.contains("full conclusion"), "{composite}"); + assert!(!composite.contains("A detailed review..."), "{composite}"); + page.vm_mut().eval(r#" + document.body.innerHTML = ''; + document.getElementById('field').value = 'Edited'; + document.getElementById('check').checked = true; + document.getElementById('notes').value = 'Edited notes'; + "#).unwrap(); + let controls = page.render_page_dump(options(false)); + assert!(controls.contains("Edited"), "{controls}"); + assert!(controls.contains("☑"), "{controls}"); + assert!(controls.contains("Edited notes"), "{controls}"); + assert!(!controls.contains("Initial"), "{controls}"); + assert!(!controls.contains("Original notes"), "{controls}"); + page.vm_mut().eval(r#" + document.body.innerHTML = '
'; + document.getElementById('notes').value = ''; + "#).unwrap(); + let cleared = page.render_page_dump(options(false)); + assert!(!cleared.contains("Old default"), "{cleared}"); + page.vm_mut().eval(r#" + document.body.innerHTML = ` + Responsive + Comma URL + Lazy responsive + Invalid density + Parentheses`; + "#).unwrap(); + let responsive = page.render_page_dump(options(false)); + assert!(responsive.contains("![Responsive](https://example.test/large.png)"), "{responsive}"); + assert!(responsive.contains("![Comma URL](https://cdn.example/c_fill,w_640/photo.jpg)"), "{responsive}"); + assert!(responsive.contains("![Lazy responsive](https://example.test/lazy-large.png)"), "{responsive}"); + assert!(responsive.contains("![Invalid density](https://example.test/safe.jpg)"), "{responsive}"); + assert!(responsive.contains("![Parentheses](https://example.test/safe-parentheses.jpg)"), "{responsive}"); + assert!(!responsive.contains("phantom.jpg"), "{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 8dac9e8b879..f75e5bee1b8 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/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs index 8e584f55331..723f175f74b 100644 --- a/moli-renderer-v8/src/script_vm/layout.rs +++ b/moli-renderer-v8/src/script_vm/layout.rs @@ -70,6 +70,15 @@ impl ScriptVm { read(host.dom_host(), &mut input) } + pub(crate) fn elements_with_bounded_final_opacity_for_document_snapshot( + &self, + elements: impl IntoIterator, + ) -> std::collections::HashSet { + let host = self._context_host.borrow(); + let document = host.document_handle(); + host.elements_with_bounded_final_opacity(document, elements) + } + pub(crate) fn sync_live_document_style_sources(&mut self) { let document = self.document_runtime.document_handle(); self._context_host @@ -89,6 +98,16 @@ impl ScriptVm { ) } + pub(crate) fn computed_style_own_visibility_values_for_document_snapshot( + &self, + handles: impl IntoIterator, + ) -> Vec { + crate::native_bridge::element::computed_style_own_visibility_values_for_document_snapshot( + &self._context_host.borrow(), + handles, + ) + } + pub(crate) fn publish_layout(&mut self) -> anyhow::Result<()> { let viewport = { let host = self._context_host.borrow(); diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index be22111f4a9..761e1a66801 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -1,9 +1,12 @@ use std::collections::HashSet; +#[cfg(test)] +use std::sync::atomic::{AtomicUsize, Ordering}; use dom::ElementState as StyloElementState; use style::{ Atom, animation::DocumentAnimationSet, + computed_value_flags::ComputedValueFlags, context::{ QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext, StyleContext, StyleSystemOptions, ThreadLocalStyleContext, @@ -11,7 +14,7 @@ use style::{ data::ElementStyles, dom::{TElement, TNode}, properties::{ - ComputedValues, PropertyId, + ComputedValues, LonghandId, PropertyDeclarationId, PropertyId, longhands::{ text_wrap_mode::computed_value::T as StyloTextWrapMode, visibility::computed_value::T as ComputedVisibility, @@ -20,15 +23,19 @@ use style::{ parse_style_attribute, }, selector_parser::{PseudoElement, SnapshotMap}, + servo::animation::{FinalKeyframeOpacity, final_keyframe_opacity}, servo_arc::Arc as ServoArc, shared_lock::StylesheetGuards, + style_resolver::{PseudoElementResolution, StyleResolverForElement}, stylesheets::{CssRuleType, UrlExtraData}, stylist::RuleInclusion, thread_state::{self, ThreadState}, traversal::resolve_style, traversal_flags::TraversalFlags, values::{ - AtomIdent, resolved, + AtomIdent, + computed::{AnimationDirection, AnimationFillMode, AnimationPlayState}, + resolved, specified::{ box_::{ContentVisibility, Display, DisplayInside, DisplayOutside}, text::TextTransformCase, @@ -43,6 +50,19 @@ use crate::{ use moli_selector::StyloElement; +#[cfg(test)] +static FINAL_OPACITY_ANIMATION_QUERY_COUNT: AtomicUsize = AtomicUsize::new(0); + +#[cfg(test)] +pub(crate) fn reset_final_opacity_animation_query_count_for_test() { + FINAL_OPACITY_ANIMATION_QUERY_COUNT.store(0, Ordering::Relaxed); +} + +#[cfg(test)] +pub(crate) fn final_opacity_animation_query_count_for_test() -> usize { + FINAL_OPACITY_ANIMATION_QUERY_COUNT.load(Ordering::Relaxed) +} + use super::{ FullStyleWorldSnapshot, MoliStyleEngine, PreparedStyleWorldUpdate, StyleViewport, StyleWorldUpdate, StyleWorldUpdatePlan, @@ -284,6 +304,14 @@ impl StyloComputedStyleSnapshot { serialize_raw_computed_property(&self.primary, property_id) } + /// Whether Stylo's completed cascade established `visibility` on this + /// element instead of inheriting it from the parent. + pub(crate) fn has_own_visibility_value(&self) -> bool { + self.primary + .flags + .contains(ComputedValueFlags::HAS_OWN_VISIBILITY) + } + pub(crate) fn resolved_property_value(&self, property: &str) -> Option { if property.starts_with("--") { return serialize_computed_custom_property(&self.primary, property); @@ -327,6 +355,120 @@ pub(super) fn retained_current_element_state( })? } +pub(super) fn retained_elements_with_bounded_final_opacity( + engine: &MoliStyleEngine, + host: &DomHost, + document: DomHandle, + elements: impl IntoIterator, +) -> HashSet { + let elements: Vec<_> = elements.into_iter().collect(); + if elements.is_empty() { + return Default::default(); + } + let Some(world) = engine.document_worlds.active_world(document) else { + return Default::default(); + }; + engine.dom_adapter.with_bound_host(host, |dom_adapter| { + install_shadow_cascade_data_for_resolution(&world, dom_adapter); + let shared_lock = dom_adapter.shared_lock().clone(); + let guard = shared_lock.read(); + let guards = StylesheetGuards::same(&guard); + let snapshot_map = SnapshotMap::new(); + let empty_painters = EmptyRegisteredSpeculativePainters; + world.document_state.with_retained_style_system(|retained| { + let shared = SharedStyleContext { + stylist: &retained.stylist, + visited_styles_enabled: false, + options: StyleSystemOptions::default(), + guards, + current_time_for_animations: 0.0, + traversal_flags: TraversalFlags::empty(), + snapshot_map: &snapshot_map, + animations: DocumentAnimationSet::default(), + registered_speculative_painters: &empty_painters, + }; + let _layout_thread_state = StyloLayoutThreadStateGuard::enter(); + let mut thread_local = ThreadLocalStyleContext::new(); + let mut context = StyleContext { + shared: &shared, + thread_local: &mut thread_local, + }; + elements + .into_iter() + .filter_map(|handle| { + let element = dom_adapter.element(host, handle)?; + let base_style = element.borrow_data()?.styles.primary().clone(); + let ui = base_style.get_ui(); + let opacity_property = PropertyDeclarationId::Longhand(LonghandId::Opacity); + let mut final_opacity = None; + let mut final_opacity_is_known = true; + for (index, name) in ui.animation_name_iter().enumerate() { + let Some(name) = name.as_atom() else { + continue; + }; + #[cfg(test)] + FINAL_OPACITY_ANIMATION_QUERY_COUNT.fetch_add(1, Ordering::Relaxed); + let Some(animation) = retained.stylist.lookup_keyframes(name, element) + else { + continue; + }; + if !animation.properties_changed.contains(opacity_property) { + continue; + } + let has_bounded_final_state = ui.animation_duration_mod(index).seconds() + > 0.0 + && ui.animation_delay_mod(index).seconds() <= 0.0 + && ui.animation_iteration_count_mod(index).0 == 1.0 + && ui.animation_direction_mod(index) == AnimationDirection::Normal + && ui.animation_play_state_mod(index) == AnimationPlayState::Running; + if has_bounded_final_state + && matches!( + ui.animation_fill_mode_mod(index), + AnimationFillMode::None | AnimationFillMode::Backwards + ) + { + continue; + } + if !has_bounded_final_state + || !matches!( + ui.animation_fill_mode_mod(index), + AnimationFillMode::Forwards | AnimationFillMode::Both + ) + { + final_opacity_is_known = false; + continue; + } + let mut resolver = StyleResolverForElement::new( + element, + &mut context, + RuleInclusion::All, + PseudoElementResolution::IfApplicable, + ); + match final_keyframe_opacity( + element, + animation, + &shared, + &base_style, + &mut resolver, + ) { + FinalKeyframeOpacity::NoEffect | FinalKeyframeOpacity::Underlying => {} + FinalKeyframeOpacity::Replace(opacity) => { + final_opacity = Some(opacity); + final_opacity_is_known = true; + } + FinalKeyframeOpacity::Unknown => { + final_opacity_is_known = false; + } + } + } + (final_opacity_is_known && final_opacity.is_some_and(|value| value > 0.0)) + .then_some(handle) + }) + .collect() + }) + }) +} + pub(super) fn computed_style_property_value( engine: &MoliStyleEngine, host: &DomHost, diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs index 36ac463d0a8..67834c6ce4e 100644 --- a/moli-renderer-v8/src/style_engine/mod.rs +++ b/moli-renderer-v8/src/style_engine/mod.rs @@ -1,7 +1,11 @@ #[cfg(test)] use std::sync::Arc as StdArc; use std::sync::Once; -use std::{cell::RefCell, collections::HashMap, rc::Rc}; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + rc::Rc, +}; use crate::{document_runtime::DomHandle, dom::native::DomHost}; use dom::ElementState as StyloElementState; @@ -31,6 +35,11 @@ mod cache; mod cause; mod cleanup; mod computed; +#[cfg(test)] +pub(crate) use computed::{ + final_opacity_animation_query_count_for_test, + reset_final_opacity_animation_query_count_for_test, +}; mod document_world; mod drain; mod eligibility; @@ -323,6 +332,15 @@ impl MoliStyleEngine { }) } + pub(crate) fn elements_with_bounded_final_opacity( + &self, + host: &DomHost, + document: DomHandle, + elements: impl IntoIterator, + ) -> HashSet { + computed::retained_elements_with_bounded_final_opacity(self, host, document, elements) + } + #[cfg(debug_assertions)] pub(crate) fn computed_style_observation_input_epochs( &self, diff --git a/moli-renderer-v8/src/style_engine/mutation_effect.rs b/moli-renderer-v8/src/style_engine/mutation_effect.rs index 2e58900c9fa..b1ba354c77c 100644 --- a/moli-renderer-v8/src/style_engine/mutation_effect.rs +++ b/moli-renderer-v8/src/style_engine/mutation_effect.rs @@ -225,7 +225,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" | "hidden" => Self::ComputedStyle, + "style" | "class" | "id" | "hidden" | "color" => Self::ComputedStyle, "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 3c922835332..753f8a1ba87 100644 --- a/moli-selector/src/stylo/presentation.rs +++ b/moli-selector/src/stylo/presentation.rs @@ -165,7 +165,7 @@ impl QueryElement<'_> { if element.local_name() == "object" { append_html_object_dimension_declarations(element, &mut block); } - append_html_table_presentation_declarations(*self, &mut block); + append_html_presentation_declarations(*self, &mut block); } if !block.is_empty() { @@ -206,7 +206,7 @@ fn append_html_direction_declaration(element: &Element, block: &mut PropertyDecl } } -fn append_html_table_presentation_declarations( +fn append_html_presentation_declarations( element: QueryElement<'_>, block: &mut PropertyDeclarationBlock, ) { @@ -214,6 +214,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<()> {