From 934d501e7edcc869525f478e33e8ede110d4024c Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Thu, 24 Sep 2026 23:08:26 +0800 Subject: [PATCH 01/21] fix(fetch): preserve rendered document content --- moli-html2md/README.md | 26 +- moli-html2md/src/anchors.rs | 107 ++++ moli-html2md/src/copy_tests.rs | 2 +- moli-html2md/src/dom.rs | 19 + moli-html2md/src/form.rs | 43 ++ moli-html2md/src/html_table.rs | 307 +++++++++++ moli-html2md/src/lib.rs | 6 + moli-html2md/src/machine.rs | 354 ++++++++++++- moli-html2md/src/math.rs | 79 +++ moli-html2md/src/mathml.rs | 214 ++++++++ moli-html2md/src/media.rs | 114 ++++ moli-html2md/src/table.rs | 36 +- moli-html2md/src/writer.rs | 74 ++- moli-html2md/tests/conversion.rs | 28 +- moli-html2md/tests/inline_boundaries.rs | 1 - moli-html2md/tests/regressions.rs | 500 +++++++++++++++++- moli-html2md/tests/tables.rs | 130 +++-- moli-html2md/tests/tracking.rs | 38 +- moli-html2md/tests/turndown/README.md | 18 +- moli-html2md/tests/turndown/expectations.json | 4 + moli-renderer-v8/src/runtime/page_dump.rs | 135 ++++- .../src/runtime/page_dump/visibility.rs | 441 +++++++++++++++ .../runtime/page_vm/tests/markdown_dump.rs | 101 ++++ .../src/runtime/page_vm/tests/mod.rs | 1 + 24 files changed, 2595 insertions(+), 183 deletions(-) create mode 100644 moli-html2md/src/anchors.rs create mode 100644 moli-html2md/src/form.rs create mode 100644 moli-html2md/src/html_table.rs create mode 100644 moli-html2md/src/math.rs create mode 100644 moli-html2md/src/mathml.rs create mode 100644 moli-html2md/src/media.rs create mode 100644 moli-renderer-v8/src/runtime/page_dump/visibility.rs create mode 100644 moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs 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..f4191d09c07 --- /dev/null +++ b/moli-html2md/src/anchors.rs @@ -0,0 +1,107 @@ +use std::collections::HashSet; + +use crate::{Dom, NodeKind}; + +pub(crate) fn referenced( + dom: &D, + root: D::NodeId, + limit: usize, +) -> HashSet { + let mut ids = HashSet::new(); + if !dom.may_have_fragment_links() { + return ids; + } + walk(dom, root, limit, |node| { + if let Some(fragment) = dom + .attribute(node, "href") + .and_then(|href| href.strip_prefix('#')) + && !fragment.is_empty() + { + ids.insert(normalize(fragment)); + } + false + }); + ids +} + +pub(crate) fn contains( + dom: &D, + root: D::NodeId, + limit: usize, + ids: &HashSet, +) -> bool { + walk(dom, root, limit, |node| { + ["id", "name"].iter().any(|name| { + dom.attribute(node, name) + .is_some_and(|id| ids.contains(&normalize(id))) + }) + }) +} + +fn walk( + dom: &D, + root: D::NodeId, + limit: usize, + mut found: impl FnMut(D::NodeId) -> bool, +) -> bool { + let mut stack = vec![(Some(root), 0, false)]; + while let Some((node, depth, siblings)) = stack.pop() { + let Some(node) = node else { + continue; + }; + if siblings { + stack.push((dom.next_sibling(node), depth, true)); + } + if depth >= limit { + continue; + } + if matches!( + dom.node_kind(node), + NodeKind::Other + | NodeKind::Element("head" | "script" | "style" | "noscript" | "template") + ) { + continue; + } + if found(node) { + return true; + } + stack.push((dom.first_child(node), depth + 1, true)); + } + false +} + +pub(crate) fn normalize(fragment: &str) -> String { + let bytes = fragment.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut offset = 0; + while offset < bytes.len() { + if bytes[offset] == b'%' && offset + 2 < bytes.len() { + let hex = |byte: u8| (byte as char).to_digit(16); + if let (Some(high), Some(low)) = (hex(bytes[offset + 1]), hex(bytes[offset + 2])) { + decoded.push((high * 16 + low) as u8); + offset += 3; + continue; + } + } + decoded.push(bytes[offset]); + offset += 1; + } + String::from_utf8(decoded).unwrap_or_else(|_| fragment.to_owned()) +} + +pub(crate) fn markup(id: &str) -> String { + let mut result = String::from(" result.push_str("&"), + '"' => result.push_str("""), + '<' => result.push_str("<"), + '>' => result.push_str(">"), + '\n' => result.push_str(" "), + '\r' => result.push_str(" "), + character => result.push(character), + } + } + result.push_str("\">"); + result +} diff --git a/moli-html2md/src/copy_tests.rs b/moli-html2md/src/copy_tests.rs index 9439eecea1a..123fabb65dd 100644 --- a/moli-html2md/src/copy_tests.rs +++ b/moli-html2md/src/copy_tests.rs @@ -28,7 +28,7 @@ fn nested_table_fallback_copies_text_linearly() { assert_eq!(actual.matches(&after).count(), depth); assert_eq!( support::rendered_html(&actual).matches("").count(), - 1 + depth ); // Count actual bytes copied when materializing fragments; completed // blocks move into parents without copying their text. This measures diff --git a/moli-html2md/src/dom.rs b/moli-html2md/src/dom.rs index 583e68467fb..04e82dffcc5 100644 --- a/moli-html2md/src/dom.rs +++ b/moli-html2md/src/dom.rs @@ -26,4 +26,23 @@ pub trait Dom { fn first_child(&self, node: Self::NodeId) -> Option; fn next_sibling(&self, node: Self::NodeId) -> Option; fn attribute(&self, node: Self::NodeId, name: &str) -> Option<&str>; + + /// A caller with computed CSS can retain block boundaries introduced by + /// stylesheets (for example, links rendered as separate action buttons). + /// Structural-only adapters can leave this at its default. + fn has_block_layout(&self, _node: Self::NodeId) -> bool { + false + } + + /// A caller with computed CSS can retain boundaries between independent + /// inline boxes such as tabs, badges, and compact action controls. + fn has_text_boundary(&self, _node: Self::NodeId) -> bool { + false + } + + /// Adapters that already inventory elements can skip the anchor prepass + /// when the document contains no local-fragment links. + fn may_have_fragment_links(&self) -> bool { + true + } } diff --git a/moli-html2md/src/form.rs b/moli-html2md/src/form.rs new file mode 100644 index 00000000000..418e5fc5725 --- /dev/null +++ b/moli-html2md/src/form.rs @@ -0,0 +1,43 @@ +use std::borrow::Cow; + +use crate::Dom; + +pub(crate) fn input_text<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option> { + let kind = dom.attribute(node, "type").unwrap_or("text"); + if kind.eq_ignore_ascii_case("checkbox") || kind.eq_ignore_ascii_case("radio") { + return Some(Cow::Borrowed(if dom.attribute(node, "checked").is_some() { + "☑" + } else { + "☐" + })); + } + if ["hidden", "file"] + .iter() + .any(|excluded| kind.eq_ignore_ascii_case(excluded)) + { + return None; + } + if kind.eq_ignore_ascii_case("image") { + return dom + .attribute(node, "alt") + .filter(|value| !value.is_empty()) + .map(Cow::Borrowed); + } + let value = (!kind.eq_ignore_ascii_case("password")) + .then(|| dom.attribute(node, "value")) + .flatten() + .filter(|value| !value.is_empty()) + .or_else(|| { + dom.attribute(node, "placeholder") + .filter(|value| !value.is_empty()) + }) + .or_else(|| { + dom.attribute(node, "aria-label") + .filter(|value| !value.is_empty()) + }) + .or_else(|| { + dom.attribute(node, "title") + .filter(|value| !value.is_empty()) + }); + value.map(Cow::Borrowed) +} diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs new file mode 100644 index 00000000000..3ccd0105a73 --- /dev/null +++ b/moli-html2md/src/html_table.rs @@ -0,0 +1,307 @@ +use crate::{Dom, NodeKind}; + +/// Markdown has no merged cells, nested tables, or block content inside cells. +/// Detect those structures before conversion so a table is traversed at most +/// twice, even when it contains thousands of nested tables. +pub(crate) fn needed( + dom: &D, + root: D::NodeId, + depth: usize, + limit: usize, +) -> bool { + let mut stack = vec![(dom.first_child(root), depth + 1)]; + while let Some((node, depth)) = stack.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + stack.push((dom.next_sibling(node), depth)); + if let NodeKind::Element(tag) = dom.node_kind(node) { + if matches!( + tag, + "table" + | "pre" + | "blockquote" + | "ul" + | "ol" + | "li" + | "hr" + | "h1" + | "h2" + | "h3" + | "h4" + | "h5" + | "h6" + ) { + return true; + } + if matches!(tag, "td" | "th") + && ["rowspan", "colspan"].iter().any(|attr| { + dom.attribute(node, attr) + .is_some_and(|value| value.trim().parse::() != Ok(1)) + }) + { + return true; + } + } + stack.push((dom.first_child(node), depth + 1)); + } + false +} + +pub(crate) fn has_cells( + dom: &D, + root: D::NodeId, + depth: usize, + limit: usize, +) -> bool { + let mut stack = vec![(dom.first_child(root), depth + 1)]; + while let Some((node, depth)) = stack.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + if matches!(dom.node_kind(node), NodeKind::Element("th" | "td")) { + return true; + } + stack.push((dom.next_sibling(node), depth)); + stack.push((dom.first_child(node), depth + 1)); + } + false +} + +enum Task { + Node(Id, usize), + Siblings(Option, usize), + Close(String), +} + +/// A compact HTML block is valid Markdown and preserves the original cell +/// associations. Keep content markup only; scripts, styles, event handlers +/// and unrelated presentation attributes are never copied. +pub(crate) fn render( + dom: &D, + root: D::NodeId, + depth: usize, + limit: usize, +) -> String { + let mut output = String::new(); + let mut tasks = vec![Task::Node(root, depth)]; + while let Some(task) = tasks.pop() { + match task { + Task::Close(tag) => { + output.push_str("'); + } + Task::Siblings(None, _) => {} + Task::Siblings(Some(node), depth) => { + tasks.push(Task::Siblings(dom.next_sibling(node), depth)); + tasks.push(Task::Node(node, depth)); + } + Task::Node(node, depth) => { + if depth >= limit { + continue; + } + match dom.node_kind(node) { + NodeKind::Text(text) => escape(text, &mut output), + NodeKind::Element( + "head" | "title" | "script" | "style" | "noscript" | "template", + ) + | NodeKind::Other => {} + NodeKind::Element("math") => { + output.push_str(&crate::mathml::render(dom, node, limit - depth)) + } + NodeKind::Element("input") => { + if let Some(value) = crate::form::input_text(dom, node) { + escape(&value, &mut output); + } + } + NodeKind::Element(tag) => { + if crate::visibility::nonrendered_serialized_state(dom, node) { + continue; + } + if matches!(tag, "iframe" | "video" | "audio") { + let urls = crate::media::sources(dom, node, tag, depth, limit); + if !urls.is_empty() { + output.push_str("
"); + if tag == "video" + && let Some(poster) = dom + .attribute(node, "poster") + .filter(|src| crate::media::safe_url(src, true)) + { + output.push_str("\"\""); + } + for url in urls + .into_iter() + .filter(|url| crate::media::safe_url(url, false)) + { + output.push_str(""); + escape(crate::media::label(dom, node, tag), &mut output); + output.push_str("
"); + } + output.push_str("
"); + continue; + } + } + let retained = if allowed(tag) { + Some(tag) + } else if dom.has_block_layout(node) { + Some("div") + } else { + None + }; + if dom.has_block_layout(node) + && matches!( + retained, + Some( + "a" | "span" + | "strong" + | "b" + | "em" + | "i" + | "s" + | "del" + | "sup" + | "sub" + | "code" + | "img" + | "select" + | "button" + ) + ) + { + output.push_str("
"); + tasks.push(Task::Close("div".to_owned())); + } + if let Some(tag) = retained { + output.push('<'); + output.push_str(tag); + for name in [ + "rowspan", "colspan", "scope", "headers", "id", "href", "src", + "alt", "title", "start", "reversed", "value", "label", "selected", + "multiple", "disabled", "name", + ] { + let image_source = if name == "src" && tag == "img" { + crate::media::source(dom, node) + } else { + None + }; + let value = if name == "src" && tag == "img" { + image_source.as_deref() + } else { + dom.attribute(node, name) + }; + if let Some(value) = value { + if matches!(name, "href" | "src") + && !crate::media::safe_url(value, name == "src") + { + continue; + } + output.push(' '); + output.push_str(name); + output.push_str("=\""); + escape(value, &mut output); + output.push('"'); + } + } + output.push('>'); + if !matches!(tag, "br" | "hr" | "img") { + tasks.push(Task::Close(tag.to_owned())); + } + } + if let Some((math, relative_depth)) = + crate::mathml::primary_alternative(dom, node, limit - depth) + { + output.push_str(&crate::mathml::render( + dom, + math, + limit - depth - relative_depth, + )); + } else { + tasks.push(Task::Siblings(dom.first_child(node), depth + 1)); + } + } + NodeKind::Document => { + tasks.push(Task::Siblings(dom.first_child(node), depth + 1)) + } + } + } + } + } + output +} + +fn allowed(tag: &str) -> bool { + matches!( + tag, + "table" + | "thead" + | "tbody" + | "tfoot" + | "tr" + | "td" + | "th" + | "caption" + | "select" + | "optgroup" + | "option" + | "button" + | "p" + | "div" + | "span" + | "a" + | "img" + | "br" + | "hr" + | "strong" + | "b" + | "em" + | "i" + | "s" + | "del" + | "sup" + | "sub" + | "code" + | "pre" + | "blockquote" + | "ul" + | "ol" + | "li" + | "h1" + | "h2" + | "h3" + | "h4" + | "h5" + | "h6" + | "dl" + | "dt" + | "dd" + | "details" + | "summary" + ) +} + +fn escape(text: &str, output: &mut String) { + for ch in text.chars() { + match ch { + '&' => output.push_str("&"), + '<' => output.push_str("<"), + '>' => output.push_str(">"), + '"' => output.push_str("""), + // Raw HTML blocks end at an empty Markdown line. Entities preserve + // preformatted line endings without prematurely ending the block. + '\n' => output.push_str(" "), + '\r' => output.push_str(" "), + _ => output.push(ch), + } + } +} diff --git a/moli-html2md/src/lib.rs b/moli-html2md/src/lib.rs index 2562a5125da..5be32fe2c33 100644 --- a/moli-html2md/src/lib.rs +++ b/moli-html2md/src/lib.rs @@ -1,6 +1,12 @@ +mod anchors; mod converter; mod dom; +mod form; +mod html_table; mod machine; +mod math; +mod mathml; +mod media; mod options; mod output; mod table; diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 62ff7cd9ee6..9786f1c4b72 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -3,11 +3,14 @@ use crate::table::Table; use crate::visibility::nonrendered_serialized_state; use crate::writer::{Style, Writer, longest_run}; use crate::{Dom, NodeKind, Options}; +use std::collections::HashSet; enum Task<'a, Id> { Visit(Id, usize), Children(Option, usize), Boundary, + ChoiceBoundary, + RestoreSvg(bool), PopStyle, EndLink(usize), EndQuote, @@ -38,6 +41,9 @@ struct Machine<'a, D: Dom + ?Sized> { tables: Vec>, raw: String, serial: usize, + in_svg: bool, + anchor_targets: HashSet, + emitted_anchors: HashSet, } pub(crate) fn convert(dom: &D, root: D::NodeId, options: &Options) -> String { @@ -50,6 +56,9 @@ pub(crate) fn convert(dom: &D, root: D::NodeId, options: &Optio tables: Vec::new(), raw: String::new(), serial: 0, + in_svg: false, + anchor_targets: crate::anchors::referenced(dom, root, options.max_depth), + emitted_anchors: HashSet::new(), }; machine.run(); machine.take_writer().into_string() @@ -69,6 +78,8 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } Task::Children(None, _) | Task::RawChildren(None, _, _) => {} Task::Boundary => self.writer().boundary(2), + Task::ChoiceBoundary => self.writer().boundary(1), + Task::RestoreSvg(previous) => self.in_svg = previous, Task::PopStyle => self.writer().pop_style(), Task::EndLink(serial) => self.writer().end_link(serial), Task::EndQuote => { @@ -187,6 +198,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { if depth >= self.options.max_depth { return; } + if self.dom.has_block_layout(node) { + self.writer().boundary(2); + self.tasks.push(Task::Boundary); + } else if self.dom.has_text_boundary(node) { + self.writer().boundary(1); + self.tasks.push(Task::ChoiceBoundary); + } let tag = match self.dom.node_kind(node) { NodeKind::Document => { self.children(node, depth + 1); @@ -202,11 +220,70 @@ 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")); + if tooltip + && let Some(value) = self + .dom + .attribute(node, "data-original-title") + .filter(|value| !value.trim().is_empty()) + { + self.writer().text(value); + return; + } + if tooltip { + self.writer().boundary(1); + self.tasks.push(Task::ChoiceBoundary); + } + if tag == "i" + && self.dom.first_child(node).is_none() + && self.dom.attribute(node, "class").is_some_and(|class| { + class.split_ascii_whitespace().any(|token| { + let token = token.to_ascii_lowercase(); + matches!( + token.as_str(), + "check" | "fa-check" | "icon-check" | "bi-check" + ) + }) + }) + { + self.writer().text("✓"); + return; + } + if tag != "table" + && !matches!( + tag, + "head" | "script" | "style" | "noscript" | "template" | "title" + ) + { + for attribute in ["id", "name"] { + if attribute == "name" && tag != "a" { + continue; + } + if let Some(id) = self.dom.attribute(node, attribute) + && self.anchor_targets.contains(&crate::anchors::normalize(id)) + { + let id = crate::anchors::normalize(id); + if self.emitted_anchors.insert(id.clone()) { + self.writer().inline_html(&crate::anchors::markup(&id)); + } + } + } } match tag { + "math" => { + let markup = crate::mathml::render(self.dom, node, self.options.max_depth - depth); + self.writer().inline_html(&markup); + return; + } "head" | "script" | "style" | "noscript" | "template" => return, + "title" if !self.in_svg => return, + "svg" | "foreignObject" | "foreignobject" => { + self.tasks.push(Task::RestoreSvg(self.in_svg)); + self.in_svg = tag == "svg"; + } "br" => { self.writer().hard_break(); return; @@ -215,14 +292,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 +331,41 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { "img" => { let alt = self.dom.attribute(node, "alt").unwrap_or_default(); let title = self.dom.attribute(node, "title"); - if let Some(src) = self - .dom - .attribute(node, "src") - .filter(|src| !src.is_empty()) - { - self.writer().image(alt, src, title); + if let Some(src) = crate::media::source(self.dom, node) { + self.writer().image(alt, &src, title); + } else { + // A failed or absent resource must not erase its textual + // alternative, especially when it is a link's only label. + self.writer().text(alt); + } + return; + } + "input" => { + if let Some(value) = crate::form::input_text(self.dom, node) { + self.writer().text(&value); } return; } + "iframe" | "video" | "audio" => { + if self.media(node, tag, depth) { + return; + } + if is_block(tag) { + self.writer().boundary(2); + self.tasks.push(Task::Boundary); + } + } "code" | "pre" => { + if subtree_has_link(self.dom, node, self.options.max_depth - depth) { + let html = + crate::html_table::render(self.dom, node, depth, self.options.max_depth); + if tag == "pre" { + self.writer().block(html.into(), 2, 2); + } else { + self.writer().inline_html(&html); + } + return; + } self.raw.clear(); let end = if tag == "pre" { Task::EndPre(self.language(node)) @@ -266,6 +383,23 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { return; } "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { + let remaining = self.options.max_depth - depth; + if !subtree_has_content(self.dom, node, remaining) { + self.writer().boundary(2); + return; + } + if subtree_has_nested_heading(self.dom, node, remaining) { + self.writer().boundary(2); + self.tasks.push(Task::Boundary); + self.children(node, depth + 1); + return; + } + if subtree_has_block(self.dom, node, remaining) { + let html = + crate::html_table::render(self.dom, node, depth, self.options.max_depth); + self.writer().block(html.into(), 2, 2); + return; + } self.capture(); self.writer().heading(); self.tasks @@ -275,9 +409,34 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.capture(); self.tasks.push(Task::EndQuote); } + _ if quote_container(self.dom.attribute(node, "class")) => { + self.capture(); + self.tasks.push(Task::EndQuote); + } "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.writer().block(html.into(), 2, 2); + return; + } if let Some(mut table) = Table::from_dom(self.dom, node, depth, self.options.max_depth) { @@ -289,6 +448,14 @@ 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.writer().block(html.into(), 2, 2); + return; + } self.writer().boundary(2); self.tasks.push(Task::Boundary); } @@ -298,14 +465,67 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } _ => {} } + if let Some((math, relative_depth)) = + crate::mathml::primary_alternative(self.dom, node, self.options.max_depth - depth) + { + let markup = crate::mathml::render( + self.dom, + math, + self.options.max_depth - depth - relative_depth, + ); + self.writer().inline_html(&markup); + return; + } + if self.dom.first_child(node).is_none() + && let Some(label) = self + .dom + .attribute(node, "aria-label") + .filter(|label| !label.trim().is_empty()) + { + self.writer().text(label); + return; + } self.children(node, depth + 1); } + fn media(&mut self, node: D::NodeId, tag: &str, depth: usize) -> bool { + let urls = crate::media::sources(self.dom, node, tag, depth, self.options.max_depth); + if urls.is_empty() { + return false; + } + self.writer().boundary(2); + if tag == "video" + && let Some(poster) = self + .dom + .attribute(node, "poster") + .filter(|src| !src.is_empty()) + { + self.writer().image("", poster, None); + self.writer().boundary(1); + } + let label = crate::media::label(self.dom, node, tag); + for href in urls { + self.serial += 1; + let serial = self.serial; + let opened = self.writer().push_style(Style::Link { + serial, + href, + title: None, + }); + self.writer().text(label); + if opened { + self.writer().end_link(serial); + } + self.writer().boundary(1); + } + self.writer().boundary(2); + true + } + fn table_cell(&mut self) { let table = self.tables.last_mut().expect("table conversion is active"); if let Some(cell) = table.next_cell() { self.capture(); - self.writer().table_cell(); self.tasks.push(Task::TableCell); self.tasks.push(Task::EndTableCell); self.children(cell.node, cell.depth + 1); @@ -387,8 +607,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 +678,111 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } } +fn quote_container(class: Option<&str>) -> bool { + class.is_some_and(|class| { + class.split_ascii_whitespace().any(|token| { + matches!( + token.to_ascii_lowercase().as_str(), + "quote" | "quoteblock" | "quote-block" | "quoted-text" + ) + }) + }) +} + +fn subtree_has_content(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = vec![(root, 0)]; + while let Some((node, depth)) = pending.pop() { + match dom.node_kind(node) { + NodeKind::Text(text) if !text.trim_matches(char::is_whitespace).is_empty() => { + return true; + } + NodeKind::Element("img") + if dom + .attribute(node, "alt") + .is_some_and(|alt| !alt.trim().is_empty()) => + { + return true; + } + _ => {} + } + if depth + 1 >= limit { + continue; + } + let mut child = dom.first_child(node); + while let Some(id) = child { + pending.push((id, depth + 1)); + child = dom.next_sibling(id); + } + } + false +} + +fn subtree_has_nested_heading(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = Vec::new(); + let mut child = dom.first_child(root); + while let Some(id) = child { + pending.push((id, 1)); + child = dom.next_sibling(id); + } + while let Some((node, depth)) = pending.pop() { + if matches!( + dom.node_kind(node), + NodeKind::Element("h1" | "h2" | "h3" | "h4" | "h5" | "h6") + ) { + return true; + } + if depth + 1 >= limit { + continue; + } + let mut child = dom.first_child(node); + while let Some(id) = child { + pending.push((id, depth + 1)); + child = dom.next_sibling(id); + } + } + false +} + +fn subtree_has_link(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = vec![(dom.first_child(root), 1)]; + while let Some((node, depth)) = pending.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + pending.push((dom.next_sibling(node), depth)); + if matches!(dom.node_kind(node), NodeKind::Element("a")) + && dom + .attribute(node, "href") + .is_some_and(|href| !href.is_empty() && crate::media::safe_url(href, false)) + { + return true; + } + pending.push((dom.first_child(node), depth + 1)); + } + false +} + +fn subtree_has_block(dom: &D, root: D::NodeId, limit: usize) -> bool { + let mut pending = vec![(dom.first_child(root), 1)]; + while let Some((node, depth)) = pending.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + continue; + } + pending.push((dom.next_sibling(node), depth)); + if matches!(dom.node_kind(node), NodeKind::Element(tag) if is_structural_block(tag)) { + return true; + } + pending.push((dom.first_child(node), depth + 1)); + } + false +} + fn class_language(class: Option<&str>) -> Option<&str> { class? .split_ascii_whitespace() diff --git a/moli-html2md/src/math.rs b/moli-html2md/src/math.rs new file mode 100644 index 00000000000..0358d4b2bb9 --- /dev/null +++ b/moli-html2md/src/math.rs @@ -0,0 +1,79 @@ +/// Locate a complete author-supplied TeX span before ordinary Markdown escaping. +/// Dollar boundaries follow the usual non-space/non-digit rules, so prices do +/// not consume the prose between two currency amounts. +pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { + let bytes = text.as_bytes(); + let mut index = 0; + while index < bytes.len() { + let (open, close, single_dollar) = if bytes[index] == b'$' && !escaped(bytes, index) { + if bytes.get(index + 1) == Some(&b'$') { + (2, "$$", false) + } else { + (1, "$", true) + } + } else if bytes[index] == b'\\' && !escaped(bytes, index) { + match bytes.get(index + 1) { + Some(b'(') => (2, "\\)", false), + Some(b'[') => (2, "\\]", false), + _ => { + index += 1; + continue; + } + } + } else { + index += 1; + continue; + }; + let content_start = index + open; + if single_dollar + && text[content_start..] + .chars() + .next() + .is_none_or(char::is_whitespace) + { + index = content_start; + continue; + } + let mut search = content_start; + while let Some(relative) = text[search..].find(close) { + let end = search + relative; + search = end + close.len(); + if escaped(bytes, end) { + continue; + } + if end == content_start { + break; + } + if single_dollar + && (text[..end] + .chars() + .next_back() + .is_some_and(char::is_whitespace) + || bytes.get(end + 1).is_some_and(u8::is_ascii_digit)) + { + break; + } + // A plain Markdown reader must never reinterpret source text as + // executable HTML merely because it was surrounded by dollars. + if bytes[content_start..end].windows(2).any(|pair| { + pair[0] == b'<' + && (pair[1].is_ascii_alphabetic() || matches!(pair[1], b'/' | b'!' | b'?')) + }) { + break; + } + return Some((index, search)); + } + index = search.max(content_start); + } + None +} + +fn escaped(bytes: &[u8], index: usize) -> bool { + bytes[..index] + .iter() + .rev() + .take_while(|&&ch| ch == b'\\') + .count() + % 2 + == 1 +} diff --git a/moli-html2md/src/mathml.rs b/moli-html2md/src/mathml.rs new file mode 100644 index 00000000000..d86facd9cd2 --- /dev/null +++ b/moli-html2md/src/mathml.rs @@ -0,0 +1,214 @@ +use crate::{Dom, NodeKind}; + +/// Math renderers often pair semantic MathML with an aria-hidden visual copy. +/// Recognize that relationship from markup, independently of library classes. +pub(crate) fn primary_alternative( + dom: &D, + node: D::NodeId, + limit: usize, +) -> Option<(D::NodeId, usize)> { + let mut primary = None; + let mut alternative = false; + let mut child = dom.first_child(node); + while let Some(id) = child { + child = dom.next_sibling(id); + if ignorable(dom.node_kind(id)) { + continue; + } + if dom + .attribute(id, "aria-hidden") + .is_some_and(|value| value.eq_ignore_ascii_case("true")) + { + alternative = true; + continue; + } + if primary.is_some() { + return None; + } + let mut candidate = id; + let mut found = None; + // Bound wrapper inspection per node; deeply nested ordinary prose must + // not cause repeated whole-subtree scans. + for depth in 1..limit.min(9) { + if dom.node_kind(candidate) == NodeKind::Element("math") { + found = Some((candidate, depth)); + break; + } + let mut children = dom.first_child(candidate); + let mut single = None; + while let Some(id) = children { + children = dom.next_sibling(id); + if ignorable(dom.node_kind(id)) { + continue; + } + if single.is_some() { + return None; + } + single = Some(id); + } + candidate = single?; + } + primary = Some(found?); + } + if alternative { primary } else { None } +} + +fn ignorable(kind: NodeKind<'_>) -> bool { + matches!(kind, NodeKind::Other) + || matches!(kind, NodeKind::Text(text) if text.trim().is_empty()) +} + +enum Task { + Node(Id, usize), + Sibling(Option, usize), + Close(String), +} + +/// Keep native mathematical structure instead of inventing a lossy plain-text +/// equation. Only mathematical markup and presentation attributes survive; +/// alternate encodings, HTML, scripts and event handlers cannot become active. +pub(crate) fn render(dom: &D, root: D::NodeId, max_depth: usize) -> String { + let mut output = String::new(); + let mut tasks = vec![Task::Node(root, 0)]; + while let Some(task) = tasks.pop() { + match task { + Task::Close(tag) => { + output.push_str("'); + } + Task::Sibling(Some(node), depth) => { + tasks.push(Task::Sibling(dom.next_sibling(node), depth)); + tasks.push(Task::Node(node, depth)); + } + Task::Sibling(None, _) => {} + Task::Node(node, depth) => { + if depth >= max_depth { + continue; + } + match dom.node_kind(node) { + NodeKind::Text(text) => escape(text, &mut output), + NodeKind::Element("annotation" | "annotation-xml" | "script" | "style") => {} + NodeKind::Element("semantics") => { + // Presentation is the first child; subsequent annotation + // children are alternate representations, not more terms. + let mut child = dom.first_child(node); + while let Some(id) = child { + if matches!(dom.node_kind(id), NodeKind::Element(_)) { + tasks.push(Task::Node(id, depth + 1)); + break; + } + child = dom.next_sibling(id); + } + } + NodeKind::Element(tag) => { + if allowed_tag(tag) { + output.push('<'); + output.push_str(tag); + for name in ATTRIBUTES { + if let Some(value) = dom.attribute(node, name) { + output.push(' '); + output.push_str(name); + output.push_str("=\""); + escape(value, &mut output); + output.push('"'); + } + } + output.push('>'); + tasks.push(Task::Close(tag.to_owned())); + } + tasks.push(Task::Sibling(dom.first_child(node), depth + 1)); + } + NodeKind::Document => { + tasks.push(Task::Sibling(dom.first_child(node), depth + 1)); + } + NodeKind::Other => {} + } + } + } + } + output +} + +fn allowed_tag(tag: &str) -> bool { + matches!( + tag, + "math" + | "mi" + | "mn" + | "mo" + | "mtext" + | "ms" + | "mspace" + | "mrow" + | "mfrac" + | "msqrt" + | "mroot" + | "mstyle" + | "merror" + | "mpadded" + | "mphantom" + | "mfenced" + | "menclose" + | "msub" + | "msup" + | "msubsup" + | "munder" + | "mover" + | "munderover" + | "mmultiscripts" + | "mprescripts" + | "none" + | "mtable" + | "mtr" + | "mlabeledtr" + | "mtd" + | "maligngroup" + | "malignmark" + ) +} + +const ATTRIBUTES: &[&str] = &[ + "display", + "mathvariant", + "displaystyle", + "scriptlevel", + "linethickness", + "bevelled", + "open", + "close", + "separators", + "notation", + "accent", + "accentunder", + "stretchy", + "symmetric", + "largeop", + "movablelimits", + "form", + "fence", + "separator", + "rowspan", + "columnspan", + "rowalign", + "columnalign", + "rowlines", + "columnlines", + "lquote", + "rquote", +]; + +fn escape(text: &str, output: &mut String) { + for ch in text.chars() { + match ch { + '&' => output.push_str("&"), + '<' => output.push_str("<"), + '>' => output.push_str(">"), + '"' => output.push_str("""), + // Keep an inline HTML fragment on one Markdown line, even when the + // source's pretty printing contains blank lines. + '\n' | '\r' | '\t' => output.push(' '), + _ => output.push(ch), + } + } +} diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs new file mode 100644 index 00000000000..714589a071c --- /dev/null +++ b/moli-html2md/src/media.rs @@ -0,0 +1,114 @@ +use std::borrow::Cow; + +use crate::{Dom, NodeKind}; + +/// Frozen DOMs can still carry lazy-loading placeholders. These conventional +/// attributes declare the resource the page intends to load, not the spacer. +pub(crate) fn source<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option> { + if let Some(value) = direct_source(dom, node) { + return Some(Cow::Borrowed(value)); + } + + // A responsive image may intentionally leave `src` empty. Retain the + // largest declared candidate so the image does not disappear entirely. + dom.attribute(node, "srcset") + .and_then(largest_srcset_candidate) + .filter(|value| safe_url(value, true)) + .map(|value| Cow::Owned(value.to_owned())) +} + +fn direct_source(dom: &D, node: D::NodeId) -> Option<&str> { + let usable = |value: &&str| { + !value.is_empty() + && !value.starts_with('#') + && *value != "about:blank" + && safe_url(value, true) + }; + let attr = |name| dom.attribute(node, name).map(str::trim).filter(usable); + + if let Some(value) = attr("data-original") { + return Some(value); + } + let src = attr("src"); + if let Some(value) = src.filter(|value| !is_placeholder_source(value)) { + return Some(value); + } + attr("data-src").or_else(|| attr("data-lazy-src")).or(src) +} + +fn is_placeholder_source(value: &str) -> bool { + let lower = value.to_ascii_lowercase(); + lower.starts_with("data:image/") + || [ + "placeholder", + "spacer", + "transparent", + "blank.gif", + "blank.png", + ] + .iter() + .any(|marker| lower.contains(marker)) +} + +fn largest_srcset_candidate(srcset: &str) -> Option<&str> { + srcset + .split(',') + .filter_map(|candidate| candidate.split_ascii_whitespace().next()) + .rfind(|url| !url.is_empty()) +} + +pub(crate) fn safe_url(value: &str, image: bool) -> bool { + let normalized: String = value + .trim() + .chars() + .filter(|ch| !ch.is_ascii_control()) + .collect(); + let Some((scheme, _)) = normalized.split_once(':') else { + return true; + }; + if scheme.contains(['/', '#', '?']) { + return true; + } + matches!( + scheme.to_ascii_lowercase().as_str(), + "http" | "https" | "mailto" | "tel" | "ftp" + ) || (image && normalized.to_ascii_lowercase().starts_with("data:image/")) +} + +pub(crate) fn sources<'a, D: Dom + ?Sized>( + dom: &'a D, + node: D::NodeId, + tag: &str, + depth: usize, + limit: usize, +) -> Vec<&'a str> { + let mut urls = Vec::new(); + let mut seen = std::collections::HashSet::new(); + if let Some(src) = direct_source(dom, node) { + seen.insert(src); + urls.push(src); + } + if tag != "iframe" && depth + 1 < limit { + let mut child = dom.first_child(node); + while let Some(id) = child { + child = dom.next_sibling(id); + if dom.node_kind(id) == NodeKind::Element("source") + && let Some(src) = direct_source(dom, id) + && seen.insert(src) + { + urls.push(src); + } + } + } + urls +} + +pub(crate) fn label<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId, tag: &str) -> &'a str { + dom.attribute(node, "title") + .filter(|label| !label.trim().is_empty()) + .unwrap_or(match tag { + "video" => "Video", + "audio" => "Audio", + _ => "Embedded content", + }) +} diff --git a/moli-html2md/src/table.rs b/moli-html2md/src/table.rs index f29e72208ea..6a4ee474053 100644 --- a/moli-html2md/src/table.rs +++ b/moli-html2md/src/table.rs @@ -10,7 +10,6 @@ pub(crate) struct Table { cells: std::vec::IntoIter>, content: Vec, in_cell: bool, - has_complex_content: bool, rows: Vec, separators: Vec<&'static str>, has_header: bool, @@ -37,7 +36,6 @@ impl Table { cells: Vec::new().into_iter(), content: Vec::new(), in_cell: false, - has_complex_content: false, rows: Vec::new(), separators: Vec::new(), has_header: false, @@ -166,39 +164,9 @@ impl Table { self.in_cell = false; } - pub(crate) fn visit_element(&mut self, tag: &str) { - if self.in_cell - && matches!( - tag, - "table" - | "pre" - | "blockquote" - | "ul" - | "ol" - | "li" - | "hr" - | "h1" - | "h2" - | "h3" - | "h4" - | "h5" - | "h6" - ) - { - self.has_complex_content = true; - } - } - pub(crate) fn finish(self) -> Output { - if self.has_complex_content { - let mut output = Output::default(); - for cell in self.content.into_iter().filter(|cell| !cell.is_empty()) { - if !output.is_empty() { - output.push_text("\n\n".into()); - } - output.append(cell); - } - return output; + if self.content.iter().all(Output::is_empty) { + return Output::default(); } let mut output = String::new(); if !self.has_header { diff --git a/moli-html2md/src/writer.rs b/moli-html2md/src/writer.rs index 7417fdf72c5..26a44260b9f 100644 --- a/moli-html2md/src/writer.rs +++ b/moli-html2md/src/writer.rs @@ -7,6 +7,8 @@ pub(crate) enum Style<'a> { Strong, Emphasis, Strike, + Superscript, + Subscript, Link { // Distinguish adjacent links even when their destinations match. serial: usize, @@ -38,7 +40,6 @@ pub(crate) struct Writer<'a> { markdown_code_end: Option, line_digits: Option, heading: bool, - single_line_attributes: bool, pub(crate) last_link: usize, // Block events in this output buffer, used when finalizing a list item. pub(crate) has_blocks: bool, @@ -52,25 +53,18 @@ impl<'a> Writer<'a> { pub(crate) fn child(&self) -> Self { Self { desired: self.desired.clone(), - single_line_attributes: self.single_line_attributes, ..Self::default() } } pub(crate) fn heading(&mut self) { self.heading = true; - self.single_line_attributes = true; - } - - pub(crate) fn table_cell(&mut self) { - // Literal attribute newlines must not split a Markdown table row. - self.single_line_attributes = true; } pub(crate) fn push_style(&mut self, style: Style<'a>) -> bool { // Repeated emphasis has the same visible meaning. Nested links cannot // be represented in Markdown, so retain the outer destination. - if self.desired.contains(&style) + if self.desired.contains(&style) && !matches!(style, Style::Superscript | Style::Subscript) || matches!(style, Style::Link { .. }) && self.desired.iter().any(|s| matches!(s, Style::Link { .. })) { @@ -98,6 +92,28 @@ impl<'a> Writer<'a> { pub(crate) fn text(&mut self, text: &str) { self.flush_code(); + let mut remaining = text; + while let Some((start, end)) = crate::math::next_span(remaining) { + self.plain_text(&remaining[..start]); + let math = &remaining[start..end]; + self.prepare_inline(math.chars().next().expect("nonempty math span")); + // TeX commands, indices and alignment characters carry meaning; + // CommonMark escaping changes that meaning in math-aware readers. + self.output.push_str(math); + self.line_digits = None; + remaining = &remaining[end..]; + } + self.plain_text(remaining); + } + + pub(crate) fn inline_html(&mut self, markup: &str) { + self.flush_code(); + self.prepare_inline('<'); + self.output.push_str(markup); + self.line_digits = None; + } + + fn plain_text(&mut self, text: &str) { for ch in text.chars() { if is_space(ch) { self.space = true; @@ -214,14 +230,13 @@ impl<'a> Writer<'a> { self.output.push(ch); } '&' => self.output.push_str("&"), - // Markdown image labels render soft breaks as spaces. Keep - // that meaning when a heading flattens its content. - '\n' if self.single_line_attributes => self.output.push(' '), + // Keep label line breaks from opening Markdown block syntax. + '\n' => self.output.push(' '), _ => self.output.push(ch), } } self.output.push_str("]("); - destination(&mut self.output, src, title, self.single_line_attributes); + destination(&mut self.output, src, title); self.output.push(')'); self.line_digits = None; } @@ -311,13 +326,21 @@ impl<'a> Writer<'a> { let first = if link.is_some_and(|link| index < link) { '[' } else { - next + match self.desired.get(index + 1) { + Some(Style::Strong | Style::Emphasis) => '*', + Some(Style::Strike) => '~', + Some(Style::Superscript | Style::Subscript) => '<', + Some(Style::Link { .. }) => '[', + None => next, + } }; let html = is_punctuation(first) && self.last_char().is_some_and(char::is_alphanumeric); match style { Style::Strong => self.output.push_str(if html { "" } else { "**" }), Style::Emphasis => self.output.push_str(if html { "" } else { "*" }), Style::Strike => self.output.push_str(if html { "" } else { "~~" }), + Style::Superscript => self.output.push_str(""), + Style::Subscript => self.output.push_str(""), Style::Link { serial, .. } => { self.last_link = self.last_link.max(serial); if self.output.ends_with('!') { @@ -364,9 +387,18 @@ impl<'a> Writer<'a> { Style::Strong => Some(("**", "", "")), Style::Emphasis => Some(("*", "", "")), Style::Strike => Some(("~~", "", "")), + Style::Superscript | Style::Subscript => { + self.output.push_str(if opened.style == Style::Superscript { + "" + } else { + "" + }); + closing_run = None; + None + } Style::Link { href, title, .. } => { self.output.push_str("]("); - destination(&mut self.output, href, title, self.single_line_attributes); + destination(&mut self.output, href, title); self.output.push(')'); closing_run = None; None @@ -386,8 +418,10 @@ impl<'a> Writer<'a> { } _ => self.last_char(), }; - let closing_needs_html = next.is_some_and(char::is_alphanumeric) - && preceding.is_some_and(is_punctuation); + let closing_needs_html = (opened.has_closed_child + && closing_run.is_some_and(|(previous, _)| previous == marker_byte)) + || (next.is_some_and(char::is_alphanumeric) + && preceding.is_some_and(is_punctuation)); if opened.html || closing_needs_html { if !opened.html { // Only the converter's output changes. Remaining open @@ -502,7 +536,7 @@ pub(crate) fn longest_run(text: &str, marker: char) -> usize { longest } -fn destination(output: &mut String, href: &str, title: Option<&str>, single_line: bool) { +fn destination(output: &mut String, href: &str, title: Option<&str>) { for ch in href.chars() { match ch { '\\' | '(' | ')' => { @@ -528,8 +562,8 @@ fn destination(output: &mut String, href: &str, title: Option<&str>, single_line output.push(ch); } '&' => output.push_str("&"), - // Protect title newlines from heading line flattening. - '\n' if single_line => output.push_str(" "), + // Preserve the attribute value without opening Markdown blocks. + '\n' => output.push_str(" "), _ => output.push(ch), } } diff --git a/moli-html2md/tests/conversion.rs b/moli-html2md/tests/conversion.rs index 13d0740c0f6..2238d5d5b06 100644 --- a/moli-html2md/tests/conversion.rs +++ b/moli-html2md/tests/conversion.rs @@ -1,4 +1,5 @@ use moli_html2md::{Converter, Dom, NodeKind, Options, convert}; +mod support; // A second DOM implementation, independent of NativeDom or an HTML parser. // Its stable arena IDs and borrowed strings are enough for the converter. @@ -304,7 +305,9 @@ fn table_spans_do_not_duplicate_cell_text() { let row = dom.element(table, "tr"); let cell = dom.leaf(row, "td", "end"); dom.attr(cell, "colspan", "999999999999"); - assert_eq!(convert(&dom, 0), "one\n\ntwo\n\nend"); + let result = convert(&dom, 0); + assert!(result.contains("rowspan=\"2\">one
")); + assert!(result.contains("colspan=\"999999999999\">end")); } #[test] @@ -381,7 +384,9 @@ fn converts_deep_tables_on_a_small_thread_stack() { max_depth: usize::MAX, ..Options::default() }); - assert_eq!(converter.convert(&dom, 0), "| |\n| --- |\n| deep |"); + let result = converter.convert(&dom, 0); + assert_eq!(result.matches("
two
").count(), 10_000); + assert_eq!(result.matches("deep").count(), 1); }) .expect("spawn small-stack test") .join() @@ -409,8 +414,8 @@ fn converts_nested_header_tables_on_a_small_thread_stack() { }); let actual = converter.convert(&dom, 0); assert_eq!(actual.matches("Header").count(), 1_000); - assert_eq!(actual.matches("| --- |").count(), 1); - assert!(actual.ends_with("| deep |")); + assert_eq!(actual.matches("
").count(), 1_000); + assert_eq!(actual.matches("deep").count(), 1); }) .expect("spawn small-stack test") .join() @@ -508,10 +513,15 @@ fn markdown_parser_recovers_pipes_and_preformatted_code_inside_tables() { let cell = dom.element(row, "td"); dom.leaf(cell, "pre", " |b\nnext\n"); let markdown = convert(&dom, 0); - let html = rendered_html(&markdown); - assert_eq!( - html, - "

Code

\n

a|b

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

Water H2O; area x2; note1.

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

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

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

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

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

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

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

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

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

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

Rate dQdt=x2+y.

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

xy2 + abi

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

News

Actual story

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

Article

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

website

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

Watch the interview:

End.

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

Concept title
Resource Information

Long explanation.

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

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

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

Open panelPosterEmail

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

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

after

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

Heading

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

![first

\n

heading](/x)

\n"); let desired_html = "

\"first

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

[link](/ \"first

\n

heading\")

\n" - ); let desired_html = "

link

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

xbc**

\n" - ); let desired_html = "

xbc

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

before*x*

\n" - ); let desired_html = "

beforex

\n"; - assert_ne!( + assert_eq!( actual_html, desired_html, "review the resolved mixed-marker gap" ); diff --git a/moli-html2md/tests/turndown/README.md b/moli-html2md/tests/turndown/README.md index 703252d8d2e..086e7c4689b 100644 --- a/moli-html2md/tests/turndown/README.md +++ b/moli-html2md/tests/turndown/README.md @@ -25,28 +25,30 @@ accepts equivalent delimiter choices and list indentation while detecting lost text, incorrect links, changed paragraph/list structure, and visible delimiters. There are also exact Markdown assertions in the original and regression suites. -`expectations.json` documents 12 deliberate differences with exact Moli outputs. +`expectations.json` documents 13 deliberate differences with exact Moli outputs. These preserve bare pre blocks and avoid upstream losses of literal characters, emphasis, whitespace, and list boundaries. They remain active assertions; no case is skipped. A reference change that makes a difference obsolete also fails the test. Separate converter tests cover GFM tables and strikethrough as Moli extensions. Explicit table headers follow Turndown's GFM plugin; simple headerless -tables receive empty headings. Complex tables retain the core's block expansion -rather than the plugin's raw HTML fallback. +tables receive empty headings. Complex tables retain content-only HTML so merged +cells and nested tables keep their associations. Explicitly presentational tables +still expand into blocks. ## Findings tracked outside the reference corpus -The 12 exceptions above describe this corpus, not every design difference or +The 13 exceptions above describe this corpus, not every design difference or every correctness issue. [tracking.rs](../tracking.rs) records these open review findings with active assertions of both Markdown and rendered HTML: | Tests | Status | Current behavior and comparison | | --- | --- | --- | | `track_nested_list_spacing_through_a_transparent_wrapper`, `track_nested_list_spacing_before_a_trailing_empty_element` | Open compatibility decision | Moli keeps the outer list tight when an `ins` wraps the nested list or an empty `span` follows it. Turndown makes it loose. Both preserve the list items. | -| `track_multiline_image_alt_becoming_a_heading` | Open bug, also present in Turndown | An image alt containing `first\n# heading` breaks the image into text and a heading. The desired HTML retains the image and its full label. | -| `track_multiline_link_title_becoming_a_heading` | Open bug, also present in Turndown | A link title containing `first\n# heading` breaks the link into text and a heading. The desired HTML retains the link and its multiline title. | -| `track_multiple_nested_spans_at_the_end_of_a_paragraph` | Open bug, also present in Turndown | `xbc` produces ambiguous star delimiters at paragraph end, losing the second strong span and exposing literal stars. | -| `track_mixed_emphasis_markers_at_an_intraword_opening` | Open bug in Moli's emphasis/strikethrough extension | `beforex` loses outer emphasis because its opener precedes generated punctuation. | + +Multiline image labels and link titles, nested sibling emphasis at paragraph +ends, and intraword mixed emphasis now have semantic regressions in +[tracking.rs](../tracking.rs). Attribute line breaks cannot introduce Markdown +blocks, and ambiguous emphasis boundaries retain their styles through inline HTML. These tests are not ignored or expected to panic. A change to a recorded output requires review; when fixing a bug, replace the current-output assertion with a diff --git a/moli-html2md/tests/turndown/expectations.json b/moli-html2md/tests/turndown/expectations.json index 9a9593aad97..cc813ee462f 100644 --- a/moli-html2md/tests/turndown/expectations.json +++ b/moli-html2md/tests/turndown/expectations.json @@ -43,6 +43,10 @@ "markdown": "before` `after", "reason": "Explicit preformatted-code mode preserves the spaces inside code. Turndown removes a whitespace-only code element entirely." }, + "extra_missing_image_src": { + "markdown": "beforemissingafter", + "reason": "An unavailable image retains its existing text alternative. Dropping alt also removes the only accessible label from image-only navigation links; Turndown loses that text." + }, "extra_split_list_marker": { "markdown": "12\\. text", "reason": "Escape list markers across text-node boundaries. Turndown escapes nodes individually and accidentally creates an ordered list." diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index ee2f639de6a..550a07bde03 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -2,18 +2,135 @@ 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 = 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 mut background_nodes = HashSet::new(); + for node in &nodes { + if matches!(Dom::node_kind(dom, *node), NodeKind::Element("font")) + && Dom::attribute(dom, *node, "color").is_some() + { + let mut current = Some(*node); + while let Some(id) = current { + background_nodes.insert(id); + current = dom.parent_node(id); + } + } + } + let background_nodes: Vec<_> = background_nodes.into_iter().collect(); + 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( + background_nodes.iter().copied(), + &["background-color".to_owned()], + ); + let backgrounds: HashMap<_, _> = background_nodes + .into_iter() + .zip(background_values) + .filter_map(|(node, values)| values.into_iter().next().map(|value| (node, value))) + .collect(); + let span_values = self + .vm() + .computed_style_property_values_for_document_snapshot( + span_nodes.iter().copied(), + &["bottom".to_owned(), "vertical-align".to_owned()], + ); + let spans: HashMap<_, _> = span_nodes.into_iter().zip(span_values).collect(); + let image_values = self + .vm() + .computed_style_property_values_for_document_snapshot( + image_nodes.iter().copied(), + &["width".to_owned(), "height".to_owned()], + ); + let images: HashMap<_, _> = image_nodes.into_iter().zip(image_values).collect(); + let values = self + .vm() + .computed_style_property_values_for_document_snapshot( + nodes.iter().copied(), + &[ + "display".to_owned(), + "visibility".to_owned(), + "opacity".to_owned(), + "position".to_owned(), + "left".to_owned(), + "top".to_owned(), + ], + ); + nodes + .into_iter() + .zip(values) + .map(|(node, mut values)| { + // 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(String::new()); + values.push(backgrounds.get(&node).cloned().unwrap_or_default()); + (node, values) + }) + .collect::>() + } else { + Vec::new() + }; if options.format == RendererPageDumpFormat::Markdown && !options.with_base && !options.with_frames && options.strip == RendererPageDumpStripOptions::default() { - return render_markdown_document(self.vm().document_runtime.dom_host().dom()); + return render_markdown_document_with_styles( + self.vm().document_runtime.dom_host().dom(), + styles, + markdown_base_url.as_ref(), + ); } let mut dom = self.vm().document_runtime.dom_host().dom().clone(); @@ -33,7 +150,9 @@ impl PageVm { match options.format { RendererPageDumpFormat::Html => dom.serialize_document(), - RendererPageDumpFormat::Markdown => render_markdown_document(&dom), + RendererPageDumpFormat::Markdown => { + render_markdown_document_with_styles(&dom, styles, markdown_base_url.as_ref()) + } } } @@ -181,14 +300,24 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String { + render_markdown_document_with_styles(dom, Vec::new(), None) +} + +fn render_markdown_document_with_styles( + dom: &NativeDom, + styles: Vec<(NativeNodeId, Vec)>, + base_url: Option<&url::Url>, +) -> String { let root = dom.body_node_id().unwrap_or(dom.document_node_id()); + let visible = visibility::MarkdownDom::new(dom, styles, base_url); moli_html2md::Converter::new(moli_html2md::Options { max_depth: MAX_DOM_OUTPUT_TREE_DEPTH, default_code_language: Some("text".to_owned()), ..Default::default() }) - .convert(dom, root) + .convert(&visible, root) } #[cfg(test)] 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..930c225f061 --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -0,0 +1,441 @@ +use std::collections::{HashMap, HashSet}; + +use moli_html2md::{Dom, NodeKind}; +use url::Url; + +use crate::dom::native::{NativeDom, NativeNodeId}; + +/// Read the current page's computed visibility without mutating the live DOM. +/// Explicit disclosure content remains useful in a document dump, even while +/// its tab or section is closed. Other non-rendered UI is not document text. +pub(super) struct MarkdownDom<'a> { + dom: &'a NativeDom, + suppressed: HashSet, + invisible: HashSet, + blocks: HashSet, + inline_boundaries: HashSet, + superscripts: HashSet, + subscripts: HashSet, + resolved_urls: HashMap>, + fragment_links: bool, +} + +impl<'a> MarkdownDom<'a> { + pub(super) fn new( + dom: &'a NativeDom, + styles: impl IntoIterator)>, + base_url: Option<&Url>, + ) -> Self { + let styles: Vec<_> = styles.into_iter().collect(); + let fragment_links = styles.iter().any(|(node, _)| { + Dom::attribute(dom, *node, "href").is_some_and(|href| href.starts_with('#')) + }); + // `styles` follows the document's preorder, so every element's parent + // has already been seen. Cache the painted ancestor background once; + // walking ancestors for every node is quadratic on deeply nested pages. + let mut effective_backgrounds = HashMap::new(); + if styles + .iter() + .any(|(_, values)| values.get(11).is_some_and(|value| !value.is_empty())) + { + for (node, values) in &styles { + let own = values + .get(11) + .and_then(|value| css_color(value)) + .filter(|color| color.3 > 0.99); + let inherited = dom + .parent_node(*node) + .and_then(|parent| effective_backgrounds.get(&parent).copied()); + effective_backgrounds + .insert(*node, own.or(inherited).unwrap_or((255, 255, 255, 1.0))); + } + } + let mut disclosures = HashSet::new(); + let mut excerpts = HashSet::new(); + let targets: HashMap<_, _> = styles + .iter() + .filter_map(|(node, values)| { + (values.first().is_some_and(|value| value == "none")) + .then(|| Dom::attribute(dom, *node, "id").map(|id| (id, *node))) + .flatten() + }) + .collect(); + for (node, _) in &styles { + if Dom::attribute(dom, *node, "aria-expanded").is_some() + || Dom::attribute(dom, *node, "role") + .is_some_and(|role| role.eq_ignore_ascii_case("tab")) + { + if let Some(targets) = Dom::attribute(dom, *node, "aria-controls") { + disclosures.extend(targets.split_ascii_whitespace()); + } + } + // Some pages pair a shortened paragraph with an explicitly linked + // hidden full-text copy. Keep the complete copy once; an unrelated + // dialog or a matching paragraph elsewhere is not such a pair. + for attribute in ["href", "data-src", "data-target"] { + let Some(id) = + Dom::attribute(dom, *node, attribute).and_then(|value| value.strip_prefix('#')) + else { + continue; + }; + let Some(&target) = targets.get(id) else { + continue; + }; + if Dom::attribute(dom, target, "role").is_some_and(|role| { + ["dialog", "alertdialog", "menu"] + .iter() + .any(|excluded| role.eq_ignore_ascii_case(excluded)) + }) { + continue; + } + let mut ancestor = dom.parent_node(*node); + while let Some(paragraph) = ancestor { + if matches!(Dom::node_kind(dom, paragraph), NodeKind::Element("p")) { + if let Some(container) = dom.parent_node(paragraph) { + if within(dom, target, container) && !within(dom, target, paragraph) { + let short = text(dom, paragraph, Some(*node)); + let prefix = short + .strip_suffix("...") + .or_else(|| short.strip_suffix('…')); + if let Some(prefix) = prefix + .map(str::trim_end) + .filter(|prefix| !prefix.is_empty()) + { + let full = text(dom, target, None); + if full.len() > prefix.len() && full.starts_with(prefix) { + disclosures.insert(id); + excerpts.insert(paragraph); + } + } + } + } + break; + } + ancestor = dom.parent_node(paragraph); + } + } + } + let mut suppressed = excerpts; + let mut invisible = HashSet::new(); + let mut blocks = HashSet::new(); + let mut inline_boundaries = HashSet::new(); + let mut superscripts = HashSet::new(); + let mut subscripts = HashSet::new(); + let mut resolved_urls = HashMap::new(); + for (node, values) in styles { + let role = Dom::attribute(dom, node, "role").unwrap_or_default(); + // Lazy media often stays transparent until a scroll/load event. + // Its declared resource still belongs to the document, unlike + // transparent numeric placeholders or hidden UI text. + let lazy_media = matches!( + Dom::node_kind(dom, node), + NodeKind::Element("img" | "iframe" | "video" | "audio") + ) && ["data-original", "data-src", "data-lazy-src"].iter().any( + |attribute| { + Dom::attribute(dom, node, attribute) + .is_some_and(|value| !value.trim().is_empty()) + }, + ); + let disclosure = role.eq_ignore_ascii_case("tabpanel") + || Dom::attribute(dom, node, "hidden") == Some("until-found") + || (!matches!(role, "dialog" | "alertdialog" | "menu") + && Dom::attribute(dom, node, "id").is_some_and(|id| disclosures.contains(id))); + let aria_hidden = Dom::attribute(dom, node, "aria-hidden") + .is_some_and(|value| value.eq_ignore_ascii_case("true")); + // Angular/Vue remove cloak attributes only after the bound view + // is ready. If one remains at dump time, its template text is not + // reader content even when a missing stylesheet fails to hide it. + let uninitialized_template = ["ng-cloak", "data-ng-cloak", "x-ng-cloak", "v-cloak"] + .iter() + .any(|name| Dom::attribute(dom, node, name).is_some()); + let far_offscreen = values + .get(3) + .is_some_and(|position| matches!(position.as_str(), "absolute" | "fixed")) + && values + .get(4) + .and_then(|value| px(value)) + .is_some_and(|left| left <= -1000.0) + && values + .get(5) + .and_then(|value| px(value)) + .is_some_and(|top| top <= -1000.0); + let tracking_pixel = matches!(Dom::node_kind(dom, node), NodeKind::Element("img")) + && Dom::attribute(dom, node, "alt").is_none_or(|alt| alt.trim().is_empty()) + && values + .get(8) + .and_then(|value| px(value)) + .is_some_and(|width| width <= 1.5) + && values + .get(9) + .and_then(|value| px(value)) + .is_some_and(|height| height <= 1.5); + let foreground = match Dom::node_kind(dom, node) { + NodeKind::Element("font") => Dom::attribute(dom, node, "color") + .and_then(css_color) + .or_else(|| values.get(10).and_then(|value| css_color(value))), + _ => values.get(10).and_then(|value| css_color(value)), + }; + let zero_contrast_leaf = !has_element_child(dom, node) + && 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) + }); + if ((values.first().is_some_and(|value| value == "none") + || values + .get(2) + .is_some_and(|value| value.parse::() == Ok(0.0)) + && !lazy_media) + && !disclosure) + || aria_hidden + || uninitialized_template + || far_offscreen + || tracking_pixel + || zero_contrast_leaf + || dom + .parent_node(node) + .is_some_and(|parent| suppressed.contains(&parent)) + { + suppressed.insert(node); + } + if values.first().is_some_and(|value| { + matches!( + value.as_str(), + "block" | "flow-root" | "flex" | "grid" | "list-item" | "table" + ) + }) { + blocks.insert(node); + } else if values.first().is_some_and(|value| { + matches!( + value.as_str(), + "inline-block" | "inline-flex" | "inline-grid" | "inline-table" + ) + }) { + inline_boundaries.insert(node); + } + if matches!(Dom::node_kind(dom, node), NodeKind::Element("span")) { + let relative = values.get(3).is_some_and(|position| position == "relative"); + let vertical_align = values.get(7).map(String::as_str).unwrap_or_default(); + if vertical_align == "super" + || (relative + && values + .get(5) + .and_then(|value| px(value)) + .is_some_and(|top| top < -1.0)) + { + superscripts.insert(node); + } else if vertical_align == "sub" + || (relative + && values + .get(6) + .and_then(|value| px(value)) + .is_some_and(|bottom| bottom < -1.0)) + { + subscripts.insert(node); + } + } + if let Some(base_url) = base_url { + let names: &[&str] = match Dom::node_kind(dom, node) { + NodeKind::Element("a") => &["href"], + NodeKind::Element("img") => { + &["src", "data-original", "data-src", "data-lazy-src"] + } + 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; + }; + if let Ok(url) = base_url.join(value) { + resolved_urls + .entry(node) + .or_insert_with(HashMap::new) + .insert(name.to_owned(), url.to_string()); + } + } + } + if values + .get(1) + .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) + && !disclosure + { + invisible.insert(node); + } + } + Self { + dom, + suppressed, + invisible, + blocks, + inline_boundaries, + superscripts, + subscripts, + resolved_urls, + fragment_links, + } + } + + fn next_retained(&self, mut node: Option) -> Option { + while let Some(id) = node { + if !self.suppressed.contains(&id) { + return Some(id); + } + node = self.dom.next_sibling(id); + } + None + } +} + +fn px(value: &str) -> Option { + value.strip_suffix("px")?.trim().parse().ok() +} + +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 within(dom: &NativeDom, mut node: NativeNodeId, ancestor: NativeNodeId) -> bool { + loop { + if node == ancestor { + return true; + } + let Some(parent) = dom.parent_node(node) else { + return false; + }; + node = parent; + } +} + +fn text(dom: &NativeDom, root: NativeNodeId, skip: Option) -> String { + let mut pending = vec![root]; + let mut result = String::new(); + while let Some(node) = pending.pop() { + if Some(node) == skip { + continue; + } + match Dom::node_kind(dom, node) { + NodeKind::Text(value) => result.push_str(value), + NodeKind::Element("script" | "style" | "template") => continue, + _ => {} + } + let mut children = Vec::new(); + let mut child = dom.first_child(node); + while let Some(id) = child { + children.push(id); + child = dom.next_sibling(id); + } + pending.extend(children.into_iter().rev()); + } + result.split_whitespace().collect::>().join(" ") +} + +impl Dom for MarkdownDom<'_> { + type NodeId = NativeNodeId; + + fn node_kind(&self, node: Self::NodeId) -> NodeKind<'_> { + if self.suppressed.contains(&node) { + return NodeKind::Other; + } + let kind = Dom::node_kind(self.dom, node); + if self.invisible.contains(&node) { + // Visibility can be overridden by a descendant. Keep traversing + // without emitting this element's own image, link or formatting. + return NodeKind::Document; + } + if matches!(kind, NodeKind::Text(_)) + && self + .dom + .parent_node(node) + .is_some_and(|parent| self.invisible.contains(&parent)) + { + return NodeKind::Other; + } + if self.superscripts.contains(&node) { + return NodeKind::Element("sup"); + } + if self.subscripts.contains(&node) { + return NodeKind::Element("sub"); + } + kind + } + + fn first_child(&self, node: Self::NodeId) -> Option { + self.next_retained(self.dom.first_child(node)) + } + + fn next_sibling(&self, node: Self::NodeId) -> Option { + self.next_retained(self.dom.next_sibling(node)) + } + + fn attribute(&self, node: Self::NodeId, name: &str) -> Option<&str> { + self.resolved_urls + .get(&node) + .and_then(|attributes| attributes.get(name)) + .map(String::as_str) + .or_else(|| Dom::attribute(self.dom, node, name)) + } + + fn has_block_layout(&self, node: Self::NodeId) -> bool { + self.blocks.contains(&node) + } + + fn has_text_boundary(&self, node: Self::NodeId) -> bool { + self.inline_boundaries.contains(&node) + } + + fn may_have_fragment_links(&self) -> bool { + self.fragment_links + } +} diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs new file mode 100644 index 00000000000..68edce14678 --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -0,0 +1,101 @@ +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

+

White on black stays visible

+

Faded text

+
ActiveReviewed
+

Mass 2.4 × 10−17 J; mn

+ + Upload complete + Article photo + + +

Panel content

+ +
Disclosure content
+
DetailsClosed details content
+ + `; + "#).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", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Visible value 8", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + assert!(output.contains(kept), "missing {kept}: {output}"); + } + assert!(output.contains("10−17"), "{output}"); + assert!(output.contains("mn"), "{output}"); + assert!(output.contains("Active\nReviewed"), "{output}"); + assert!(!output.contains("tracking.gif"), "{output}"); + assert!(output.contains("Upload complete"), "{output}"); + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "product.name", "Vue template", "hidden suffix"] { + assert!(!output.contains(omitted), "leaked {omitted}: {output}"); + } + } + page.vm_mut().eval("document.getElementById('waiting').className = ''").unwrap(); + assert!(page.render_page_dump(options(false)).contains("Translation pending")); + assert_eq!(page.vm_mut().eval("document.querySelector('style').textContent.includes('.off')").unwrap(), "true"); + page.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = 'AcceptReject'; + "#).unwrap(); + let actions = page.render_page_dump(options(false)); + assert!(actions.contains("[Accept](https://example.test/accept)\n\n[Reject](https://example.test/reject)"), "{actions}"); + page.vm_mut().eval(r##" + document.body.innerHTML = ` +

A detailed review starts... Read more

+
+

A different excerpt... Read more

+
+

Complete short review.

Complete short review.
+

Complete short review.

+

Privacy policy... Read more

+
`; + "##).unwrap(); + for strip_css in [false, true] { + let output = page.render_page_dump(options(strip_css)); + assert_eq!(output.matches("A detailed review starts").count(), 1, "{output}"); + assert!(output.contains("retains the final conclusion."), "{output}"); + assert!(!output.contains("A detailed review starts..."), "{output}"); + assert!(output.contains("A different excerpt..."), "{output}"); + assert!(!output.contains("Unrelated hidden template"), "{output}"); + assert_eq!(output.matches("Complete short review.").count(), 2, "{output}"); + assert!(output.contains("Privacy policy..."), "{output}"); + assert!(!output.contains("cookie settings"), "{output}"); + } + page.vm_mut().eval("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; From 92a76a7486541ae034a25aeb15c3a4d4be3abde6 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Thu, 24 Sep 2026 23:32:02 +0800 Subject: [PATCH 02/21] fix(renderer): retain content behind loading veils --- moli-renderer-v8/src/runtime/page_dump.rs | 3 +++ .../src/runtime/page_dump/visibility.rs | 17 ++++++++++++++++- .../src/runtime/page_vm/tests/markdown_dump.rs | 15 ++++++++++++++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 550a07bde03..772a0f70701 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -82,12 +82,14 @@ impl PageVm { "position".to_owned(), "left".to_owned(), "top".to_owned(), + "animation-name".to_owned(), ], ); nodes .into_iter() .zip(values) .map(|(node, mut values)| { + let animation_name = values.pop().unwrap_or_default(); // Preserve the visibility adapter's stable field layout. let span = spans.get(&node); values.push( @@ -115,6 +117,7 @@ impl PageVm { ); values.push(String::new()); values.push(backgrounds.get(&node).cloned().unwrap_or_default()); + values.push(animation_name); (node, values) }) .collect::>() diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 930c225f061..2a35bcec22d 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -27,6 +27,14 @@ impl<'a> MarkdownDom<'a> { base_url: Option<&Url>, ) -> Self { let styles: Vec<_> = styles.into_iter().collect(); + let document_element = dom.document_element_node_id(); + let body = dom.body_node_id(); + let document_visibility_is_hidden = styles.iter().any(|(node, values)| { + (Some(*node) == document_element || Some(*node) == body) + && values + .get(1) + .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) + }); let fragment_links = styles.iter().any(|(node, _)| { Dom::attribute(dom, *node, "href").is_some_and(|href| href.starts_with('#')) }); @@ -184,11 +192,17 @@ impl<'a> MarkdownDom<'a> { && (foreground.0, foreground.1, foreground.2) == (background.0, background.1, background.2) }); + let document_root = Some(node) == document_element || Some(node) == body; + let animated = values + .get(12) + .is_some_and(|name| !name.is_empty() && name != "none"); if ((values.first().is_some_and(|value| value == "none") || values .get(2) .is_some_and(|value| value.parse::() == Ok(0.0)) - && !lazy_media) + && !lazy_media + && !animated + && !document_root) && !disclosure) || aria_hidden || uninitialized_template @@ -268,6 +282,7 @@ impl<'a> MarkdownDom<'a> { .get(1) .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) && !disclosure + && !document_visibility_is_hidden { invisible.insert(node); } 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 index 68edce14678..d3e2e4cf1c1 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -36,6 +36,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

Visible value hidden suffix 8

White on black stays visible

Faded text

+

Animated article text

ActiveReviewed

Mass 2.4 × 10−17 J; mn

@@ -52,7 +53,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { "#).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", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Visible value 8", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + for kept in ["Visible body", "Restored child", "Panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value 8", "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}"); @@ -67,6 +68,18 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { page.vm_mut().eval("document.getElementById('waiting').className = ''").unwrap(); assert!(page.render_page_dump(options(false)).contains("Translation pending")); assert_eq!(page.vm_mut().eval("document.querySelector('style').textContent.includes('.off')").unwrap(), "true"); + page.vm_mut().eval(r#" + document.documentElement.style.opacity = '0'; + document.body.innerHTML = '
Whole-page loading veil
'; + "#).unwrap(); + assert!(page.render_page_dump(options(false)).contains("Whole-page loading veil")); + page.vm_mut().eval(r#" + document.documentElement.style.opacity = ''; + document.body.style.visibility = 'hidden'; + document.body.innerHTML = '
Font loading veil
'; + "#).unwrap(); + assert!(page.render_page_dump(options(false)).contains("Font loading veil")); + page.vm_mut().eval("document.body.style.visibility = ''").unwrap(); page.vm_mut().eval(r#" document.head.innerHTML = ''; document.body.innerHTML = 'AcceptReject'; From eabea478446b4505fe6ac30b1362d2e24f399833 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Fri, 25 Sep 2026 00:20:12 +0800 Subject: [PATCH 03/21] test(fetch): align markdown regressions with preserved semantics --- moli-renderer-v8/src/runtime/page_dump.rs | 36 +++++++++++--- .../src/runtime/page_dump/visibility.rs | 40 ++++++++-------- moli/tests/fetch_cli/markdown.rs | 48 +++++++++++++++++-- 3 files changed, 95 insertions(+), 29 deletions(-) diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 772a0f70701..c23ddf37297 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -525,10 +525,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 index 2a35bcec22d..b110094b1b0 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -69,13 +69,12 @@ impl<'a> MarkdownDom<'a> { }) .collect(); for (node, _) in &styles { - if Dom::attribute(dom, *node, "aria-expanded").is_some() + if (Dom::attribute(dom, *node, "aria-expanded").is_some() || Dom::attribute(dom, *node, "role") - .is_some_and(|role| role.eq_ignore_ascii_case("tab")) + .is_some_and(|role| role.eq_ignore_ascii_case("tab"))) + && let Some(targets) = Dom::attribute(dom, *node, "aria-controls") { - if let Some(targets) = Dom::attribute(dom, *node, "aria-controls") { - disclosures.extend(targets.split_ascii_whitespace()); - } + disclosures.extend(targets.split_ascii_whitespace()); } // Some pages pair a shortened paragraph with an explicitly linked // hidden full-text copy. Keep the complete copy once; an unrelated @@ -99,21 +98,22 @@ impl<'a> MarkdownDom<'a> { 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) { - if 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); - } + 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); } } } 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<()> { From be2ff8d11f7e65578a326b2f80babedafaaa5245 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Sat, 26 Sep 2026 22:51:09 +0800 Subject: [PATCH 04/21] fix(fetch): preserve interactive document semantics --- moli-html2md/src/anchors.rs | 11 ++- moli-html2md/src/machine.rs | 58 +++++++----- moli-html2md/src/media.rs | 3 +- moli-html2md/tests/regressions.rs | 61 ++++++++++++- moli-renderer-v8/src/runtime/page_dump.rs | 26 ++---- .../src/runtime/page_dump/visibility.rs | 90 +++++++++++++++---- .../runtime/page_vm/tests/markdown_dump.rs | 23 ++++- 7 files changed, 205 insertions(+), 67 deletions(-) diff --git a/moli-html2md/src/anchors.rs b/moli-html2md/src/anchors.rs index f4191d09c07..32c790dd268 100644 --- a/moli-html2md/src/anchors.rs +++ b/moli-html2md/src/anchors.rs @@ -17,7 +17,7 @@ pub(crate) fn referenced( .and_then(|href| href.strip_prefix('#')) && !fragment.is_empty() { - ids.insert(normalize(fragment)); + ids.insert(decode_fragment(fragment)); } false }); @@ -31,10 +31,9 @@ pub(crate) fn contains( ids: &HashSet, ) -> bool { walk(dom, root, limit, |node| { - ["id", "name"].iter().any(|name| { - dom.attribute(node, name) - .is_some_and(|id| ids.contains(&normalize(id))) - }) + ["id", "name"] + .iter() + .any(|name| dom.attribute(node, name).is_some_and(|id| ids.contains(id))) }) } @@ -70,7 +69,7 @@ fn walk( false } -pub(crate) fn normalize(fragment: &str) -> String { +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; diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 9786f1c4b72..8d161a9c06c 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -225,6 +225,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { .attribute(node, "data-toggle") .is_some_and(|value| value.eq_ignore_ascii_case("tooltip")); if tooltip + && !subtree_has_content(self.dom, node, self.options.max_depth - depth) && let Some(value) = self .dom .attribute(node, "data-original-title") @@ -233,7 +234,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.writer().text(value); return; } - if tooltip { + if tooltip && self.dom.attribute(node, "title").is_some() { self.writer().boundary(1); self.tasks.push(Task::ChoiceBoundary); } @@ -263,11 +264,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { continue; } if let Some(id) = self.dom.attribute(node, attribute) - && self.anchor_targets.contains(&crate::anchors::normalize(id)) + && self.anchor_targets.contains(id) { - let id = crate::anchors::normalize(id); - if self.emitted_anchors.insert(id.clone()) { - self.writer().inline_html(&crate::anchors::markup(&id)); + if self.emitted_anchors.insert(id.to_owned()) { + self.writer().inline_html(&crate::anchors::markup(id)); } } } @@ -356,7 +356,16 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } } "code" | "pre" => { - if subtree_has_link(self.dom, node, self.options.max_depth - depth) { + 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); if tag == "pre" { @@ -409,10 +418,6 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.capture(); self.tasks.push(Task::EndQuote); } - _ if quote_container(self.dom.attribute(node, "class")) => { - self.capture(); - self.tasks.push(Task::EndQuote); - } "ul" | "ol" => self.start_list(node, tag == "ol"), "li" => self.start_item(), "table" => { @@ -459,6 +464,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { 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); @@ -678,15 +687,16 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } } -fn quote_container(class: Option<&str>) -> bool { - 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 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 { @@ -696,10 +706,14 @@ fn subtree_has_content(dom: &D, root: D::NodeId, limit: usize) NodeKind::Text(text) if !text.trim_matches(char::is_whitespace).is_empty() => { return true; } - NodeKind::Element("img") - if dom - .attribute(node, "alt") - .is_some_and(|alt| !alt.trim().is_empty()) => + NodeKind::Element("img") if crate::media::source(dom, node).is_some() => { + return true; + } + NodeKind::Element(_) + if dom.first_child(node).is_none() + && dom + .attribute(node, "aria-label") + .is_some_and(|label| !label.trim().is_empty()) => { return true; } diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index 714589a071c..e2fe378c186 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -11,7 +11,8 @@ pub(crate) fn source<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option // A responsive image may intentionally leave `src` empty. Retain the // largest declared candidate so the image does not disappear entirely. - dom.attribute(node, "srcset") + dom.attribute(node, "data-srcset") + .or_else(|| dom.attribute(node, "srcset")) .and_then(largest_srcset_candidate) .filter(|value| safe_url(value, true)) .map(|value| Cow::Owned(value.to_owned())) diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index fcc1b697efd..11e8d435826 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -651,7 +651,7 @@ fn fragment_links_keep_explicit_targets_without_copying_unreferenced_ids() { #[test] fn percent_encoded_named_anchor_matches_its_fragment_link() { let result = markdown( - "Run

Run the program

", + "Run

Run the program

", false, ); assert!(result.contains("[Run](#Run%20the%20program)"), "{result}"); @@ -661,6 +661,14 @@ fn percent_encoded_named_anchor_matches_its_fragment_link() { ); } +#[test] +fn fragment_decoding_does_not_rewrite_dom_ids() { + let result = markdown("Go

Target

", false); + assert!(result.contains("[Go](#x%2520y)"), "{result}"); + assert!(result.contains(""), "{result}"); + assert!(result.contains("Target"), "{result}"); +} + #[test] fn table_fragment_targets_preserve_rows_cells_and_legacy_named_anchors() { let source = "RowCellLegacy
ValueOther
"; @@ -778,13 +786,38 @@ fn conventional_quote_container_retains_quote_semantics() { assert!(result.contains("Current reply."), "{result}"); } +#[test] +fn quote_classes_do_not_replace_list_or_table_semantics() { + let list = markdown( + "
  • First
  • Second
", + false, + ); + assert_eq!(list, "- First\n- Second"); + let table = rendered_html(&markdown( + "
Name
Ada
", + false, + )); + assert!(table.contains(""), "{table}"); + assert!(table.contains(""), "{table}"); +} + #[test] fn tooltip_trigger_retains_its_reader_facing_detail() { let result = markdown( "

Paid Orientation Details

", false, ); - assert_eq!(result, "Paid Orientation $100/day"); + assert_eq!(result, "Paid Orientation Details"); + let link = markdown( + "Download", + false, + ); + assert_eq!(link, "[Download](/download)"); + let fallback = markdown( + "", + false, + ); + assert_eq!(fallback, "$100/day"); let metadata = markdown( "January 24, 20183 mins read", false, @@ -792,6 +825,17 @@ fn tooltip_trigger_retains_its_reader_facing_detail() { assert_eq!(metadata, "January 24, 2018\n3 mins read"); } +#[test] +fn resource_only_headings_are_not_dropped() { + let result = markdown( + "

Article

", + false, + ); + assert!(result.contains("# [![](/logo.svg)](/home)"), "{result}"); + assert!(result.contains("## Accessible title"), "{result}"); + assert!(result.contains("Article"), "{result}"); +} + #[test] fn invalid_nested_and_empty_headings_do_not_emit_literal_markers() { let result = markdown( @@ -821,6 +865,19 @@ fn preformatted_navigation_retains_link_targets() { assert!(result.contains("Scores stay aligned"), "{result}"); } +#[test] +fn preformatted_code_preserves_externally_referenced_targets() { + let result = markdown( + "Line 1
let x = 1;\nlet y = 2;
", + false, + ); + assert!(result.contains("[Line 1](#L1)"), "{result}"); + assert!( + result.contains("let x = 1;"), + "{result}" + ); +} + #[test] fn inline_code_retains_term_link_targets() { let result = markdown( diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index c23ddf37297..4142625f02d 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -4,7 +4,7 @@ use crate::runtime::page_surface::{ }; use moli_html2md::{Dom, NodeKind}; use moli_page_types::MAX_DOM_OUTPUT_TREE_DEPTH; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use super::page_vm::PageVm; @@ -23,19 +23,6 @@ impl PageVm { dom.node(*node) .is_some_and(|node| node.as_element().is_some()) }); - let mut background_nodes = HashSet::new(); - for node in &nodes { - if matches!(Dom::node_kind(dom, *node), NodeKind::Element("font")) - && Dom::attribute(dom, *node, "color").is_some() - { - let mut current = Some(*node); - while let Some(id) = current { - background_nodes.insert(id); - current = dom.parent_node(id); - } - } - } - let background_nodes: Vec<_> = background_nodes.into_iter().collect(); let span_nodes: Vec<_> = nodes .iter() .copied() @@ -49,11 +36,12 @@ impl PageVm { let background_values = self .vm() .computed_style_property_values_for_document_snapshot( - background_nodes.iter().copied(), + nodes.iter().copied(), &["background-color".to_owned()], ); - let backgrounds: HashMap<_, _> = background_nodes - .into_iter() + let backgrounds: HashMap<_, _> = nodes + .iter() + .copied() .zip(background_values) .filter_map(|(node, values)| values.into_iter().next().map(|value| (node, value))) .collect(); @@ -82,6 +70,7 @@ impl PageVm { "position".to_owned(), "left".to_owned(), "top".to_owned(), + "color".to_owned(), "animation-name".to_owned(), ], ); @@ -90,6 +79,7 @@ impl PageVm { .zip(values) .map(|(node, mut values)| { let animation_name = values.pop().unwrap_or_default(); + let foreground = values.pop().unwrap_or_default(); // Preserve the visibility adapter's stable field layout. let span = spans.get(&node); values.push( @@ -115,7 +105,7 @@ impl PageVm { .cloned() .unwrap_or_default(), ); - values.push(String::new()); + values.push(foreground); values.push(backgrounds.get(&node).cloned().unwrap_or_default()); values.push(animation_name); (node, values) diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index b110094b1b0..d8decfe7b47 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -76,6 +76,19 @@ impl<'a> MarkdownDom<'a> { { disclosures.extend(targets.split_ascii_whitespace()); } + for attribute_name in dom.get_attribute_names(*node).unwrap_or_default() { + if !attribute_name.starts_with("on") { + continue; + } + let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else { + continue; + }; + for literal in quoted_literals(handler) { + if let Some((&id, _)) = targets.get_key_value(literal) { + disclosures.insert(id); + } + } + } // Some pages pair a shortened paragraph with an explicitly linked // hidden full-text copy. Keep the complete copy once; an unrelated // dialog or a matching paragraph elsewhere is not such a pair. @@ -138,12 +151,12 @@ impl<'a> MarkdownDom<'a> { let lazy_media = matches!( Dom::node_kind(dom, node), NodeKind::Element("img" | "iframe" | "video" | "audio") - ) && ["data-original", "data-src", "data-lazy-src"].iter().any( - |attribute| { + ) && ["data-original", "data-src", "data-lazy-src", "data-srcset"] + .iter() + .any(|attribute| { Dom::attribute(dom, node, attribute) .is_some_and(|value| !value.trim().is_empty()) - }, - ); + }); let disclosure = role.eq_ignore_ascii_case("tabpanel") || Dom::attribute(dom, node, "hidden") == Some("until-found") || (!matches!(role, "dialog" | "alertdialog" | "menu") @@ -177,12 +190,7 @@ impl<'a> MarkdownDom<'a> { .get(9) .and_then(|value| px(value)) .is_some_and(|height| height <= 1.5); - let foreground = match Dom::node_kind(dom, node) { - NodeKind::Element("font") => Dom::attribute(dom, node, "color") - .and_then(css_color) - .or_else(|| values.get(10).and_then(|value| css_color(value))), - _ => values.get(10).and_then(|value| css_color(value)), - }; + let foreground = values.get(10).and_then(|value| css_color(value)); let zero_contrast_leaf = !has_element_child(dom, node) && foreground .filter(|color| color.3 > 0.99) @@ -204,7 +212,7 @@ impl<'a> MarkdownDom<'a> { && !animated && !document_root) && !disclosure) - || aria_hidden + || (aria_hidden && !disclosure) || uninitialized_template || far_offscreen || tracking_pixel @@ -254,9 +262,14 @@ impl<'a> MarkdownDom<'a> { 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"] - } + 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"] } @@ -270,11 +283,16 @@ impl<'a> MarkdownDom<'a> { else { continue; }; - if let Ok(url) = base_url.join(value) { + 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.to_string()); + .insert(name.to_owned(), url); } } } @@ -311,10 +329,50 @@ impl<'a> MarkdownDom<'a> { } } +fn quoted_literals(value: &str) -> Vec<&str> { + let mut result = Vec::new(); + let mut quote = None; + let mut start = 0; + let mut escaped = false; + for (index, character) in value.char_indices() { + if let Some(delimiter) = quote { + if escaped { + escaped = false; + } else if character == '\\' { + escaped = true; + } else if character == delimiter { + result.push(&value[start..index]); + quote = None; + } + } else if matches!(character, '\'' | '"') { + quote = Some(character); + start = index + character.len_utf8(); + } + } + result +} + fn px(value: &str) -> Option { value.strip_suffix("px")?.trim().parse().ok() } +fn resolve_srcset(base_url: &Url, value: &str) -> Option { + let mut resolved = Vec::new(); + for candidate in value.split(',') { + let candidate = candidate.trim(); + if candidate.is_empty() { + continue; + } + let split = candidate + .find(char::is_whitespace) + .unwrap_or(candidate.len()); + let (source, descriptor) = candidate.split_at(split); + let url = base_url.join(source).ok()?; + resolved.push(format!("{}{descriptor}", url)); + } + (!resolved.is_empty()).then(|| resolved.join(", ")) +} + fn css_color(value: &str) -> Option<(u8, u8, u8, f32)> { let value = value.trim().to_ascii_lowercase(); match value.as_str() { 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 index d3e2e4cf1c1..48257e1f487 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -34,6 +34,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {
Buy {{product.name}} for {{product.price | currency}}
Vue template {{message}}

Visible value hidden suffix 8

+

CSS override VISIBLE

White on black stays visible

Faded text

Animated article text

@@ -45,6 +46,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

Panel content

+
Disclosure content
DetailsClosed details content
@@ -53,7 +55,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { "#).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", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value 8", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + for kept in ["Visible body", "Restored child", "Panel content", "ARIA panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value hidden suffix 8", "CSS override 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}"); @@ -61,7 +63,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { assert!(output.contains("Active\nReviewed"), "{output}"); assert!(!output.contains("tracking.gif"), "{output}"); assert!(output.contains("Upload complete"), "{output}"); - for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "product.name", "Vue template", "hidden suffix"] { + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "product.name", "Vue template"] { assert!(!output.contains(omitted), "leaked {omitted}: {output}"); } } @@ -108,6 +110,23 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { assert!(output.contains("Privacy policy..."), "{output}"); assert!(!output.contains("cookie settings"), "{output}"); } + page.vm_mut().eval(r##" + document.body.innerHTML = ` + + + + `; + "##).unwrap(); + let expanded = page.render_page_dump(options(false)); + assert!(expanded.contains("Expandable history"), "{expanded}"); + assert!(!expanded.contains("Hidden template"), "{expanded}"); + page.vm_mut().eval(r#" + document.body.innerHTML = ` + Responsive + Lazy responsive`; + "#).unwrap(); + let responsive = page.render_page_dump(options(false)); + assert!(responsive.contains("![Responsive](https://example.test/large.png)"), "{responsive}"); + assert!(responsive.contains("![Lazy responsive](https://example.test/lazy-large.png)"), "{responsive}"); page.vm_mut().eval("document.documentElement.style.display = 'none'").unwrap(); assert!(page.render_page_dump(options(false)).is_empty()); }).await; From 35178baaaa17fa5bda1ce302111ec001840e4253 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Mon, 28 Sep 2026 11:48:37 +0800 Subject: [PATCH 05/21] fix(fetch): close content audit regressions --- moli-html2md/src/html_table.rs | 14 ++++ moli-html2md/src/machine.rs | 70 +++++++++++------ moli-html2md/src/media.rs | 11 +-- moli-html2md/tests/regressions.rs | 40 ++++++++++ moli-renderer-v8/src/runtime/page_dump.rs | 13 ++++ .../src/runtime/page_dump/visibility.rs | 77 +++++++++++++++++-- .../runtime/page_vm/tests/markdown_dump.rs | 37 +++++++-- .../src/style_engine/mutation_effect.rs | 2 +- moli-selector/src/stylo/presentation.rs | 9 ++- 9 files changed, 229 insertions(+), 44 deletions(-) diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs index 3ccd0105a73..6e52b285b3e 100644 --- a/moli-html2md/src/html_table.rs +++ b/moli-html2md/src/html_table.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use crate::{Dom, NodeKind}; /// Markdown has no merged cells, nested tables, or block content inside cells. @@ -88,8 +90,10 @@ pub(crate) fn render( root: D::NodeId, depth: usize, limit: usize, + anchor_targets: &HashSet, ) -> String { let mut output = String::new(); + let mut emitted_anchors = HashSet::new(); let mut tasks = vec![Task::Node(root, depth)]; while let Some(task) = tasks.pop() { match task { @@ -107,6 +111,16 @@ pub(crate) fn render( if depth >= limit { continue; } + let anchor = ["id", "name"].iter().find_map(|name| { + dom.attribute(node, name) + .filter(|id| anchor_targets.contains(*id)) + }); + if let (NodeKind::Element(tag), Some(id)) = (dom.node_kind(node), anchor) + && !allowed(tag) + && emitted_anchors.insert(id) + { + output.push_str(&crate::anchors::markup(id)); + } match dom.node_kind(node) { NodeKind::Text(text) => escape(text, &mut output), NodeKind::Element( diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 8d161a9c06c..fe780200d0e 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -224,16 +224,14 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { .dom .attribute(node, "data-toggle") .is_some_and(|value| value.eq_ignore_ascii_case("tooltip")); - if tooltip - && !subtree_has_content(self.dom, node, self.options.max_depth - depth) - && let Some(value) = self - .dom - .attribute(node, "data-original-title") - .filter(|value| !value.trim().is_empty()) - { - self.writer().text(value); - return; - } + 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); @@ -265,10 +263,9 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } if let Some(id) = self.dom.attribute(node, attribute) && self.anchor_targets.contains(id) + && self.emitted_anchors.insert(id.to_owned()) { - if self.emitted_anchors.insert(id.to_owned()) { - self.writer().inline_html(&crate::anchors::markup(id)); - } + self.writer().inline_html(&crate::anchors::markup(id)); } } } @@ -366,8 +363,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { &self.anchor_targets, )) { - let html = - crate::html_table::render(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, + ); if tag == "pre" { self.writer().block(html.into(), 2, 2); } else { @@ -404,8 +406,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { return; } if subtree_has_block(self.dom, node, remaining) { - let html = - crate::html_table::render(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; } @@ -437,8 +444,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { &self.anchor_targets, )) { - let html = - crate::html_table::render(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; } @@ -456,8 +468,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { 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); + 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; } @@ -485,7 +502,9 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.writer().inline_html(&markup); return; } - if self.dom.first_child(node).is_none() + if let Some(value) = tooltip_fallback { + self.writer().text(value); + } else if self.dom.first_child(node).is_none() && let Some(label) = self .dom .attribute(node, "aria-label") @@ -706,7 +725,12 @@ fn subtree_has_content(dom: &D, root: D::NodeId, limit: usize) 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() => { + 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(_) diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index e2fe378c186..f98d8e59d21 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -11,11 +11,12 @@ pub(crate) fn source<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option // A responsive image may intentionally leave `src` empty. Retain the // largest declared candidate so the image does not disappear entirely. - dom.attribute(node, "data-srcset") - .or_else(|| dom.attribute(node, "srcset")) - .and_then(largest_srcset_candidate) - .filter(|value| safe_url(value, true)) - .map(|value| Cow::Owned(value.to_owned())) + ["data-srcset", "srcset"].into_iter().find_map(|name| { + dom.attribute(node, name) + .and_then(largest_srcset_candidate) + .filter(|value| safe_url(value, true)) + .map(|value| Cow::Owned(value.to_owned())) + }) } fn direct_source(dom: &D, node: D::NodeId) -> Option<&str> { diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index 11e8d435826..88bb7e28e2f 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -818,6 +818,11 @@ fn tooltip_trigger_retains_its_reader_facing_detail() { false, ); assert_eq!(fallback, "$100/day"); + let fallback_link = markdown( + "", + false, + ); + assert_eq!(fallback_link, "[Download](/download)"); let metadata = markdown( "January 24, 20183 mins read", false, @@ -834,6 +839,41 @@ fn resource_only_headings_are_not_dropped() { assert!(result.contains("# [![](/logo.svg)](/home)"), "{result}"); assert!(result.contains("## Accessible title"), "{result}"); assert!(result.contains("Article"), "{result}"); + let alternative = markdown( + "

Product manual

Safe title

", + false, + ); + assert!(alternative.contains("# Product manual"), "{alternative}"); + assert!(alternative.contains("## Safe title"), "{alternative}"); +} + +#[test] +fn responsive_image_falls_back_from_unusable_lazy_candidates() { + for lazy in ["", "javascript:bad() 1x"] { + let result = markdown( + &format!( + "Chart" + ), + false, + ); + assert_eq!(result, "![Chart](/chart.png)"); + } +} + +#[test] +fn html_fallback_preserves_referenced_targets_for_special_nodes() { + let code = markdown( + "Line 1
let x = 1;
", + false, + ); + assert!(code.contains(""), "{code}"); + let table = markdown( + "EmailEquationVideo
Ada
x
", + false, + ); + for id in ["email", "eq1", "video1"] { + assert!(table.contains(&format!("")), "{table}"); + } } #[test] diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 4142625f02d..35f45839294 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -45,6 +45,18 @@ impl PageVm { .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( @@ -108,6 +120,7 @@ impl PageVm { values.push(foreground); values.push(backgrounds.get(&node).cloned().unwrap_or_default()); values.push(animation_name); + values.push(background_images.get(&node).cloned().unwrap_or_default()); (node, values) }) .collect::>() diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index d8decfe7b47..5c9c20d4e3e 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -83,8 +83,8 @@ impl<'a> MarkdownDom<'a> { let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else { continue; }; - for literal in quoted_literals(handler) { - if let Some((&id, _)) = targets.get_key_value(literal) { + for target in inline_disclosure_targets(handler) { + if let Some((&id, _)) = targets.get_key_value(target) { disclosures.insert(id); } } @@ -192,6 +192,10 @@ impl<'a> MarkdownDom<'a> { .is_some_and(|height| height <= 1.5); let foreground = values.get(10).and_then(|value| css_color(value)); let zero_contrast_leaf = !has_element_child(dom, node) + && has_text_child(dom, node) + && values + .get(13) + .is_none_or(|image| image.is_empty() || image == "none") && foreground .filter(|color| color.3 > 0.99) .zip(effective_backgrounds.get(&node).copied()) @@ -329,25 +333,71 @@ impl<'a> MarkdownDom<'a> { } } -fn quoted_literals(value: &str) -> Vec<&str> { +fn inline_disclosure_targets(value: &str) -> Vec<&str> { + let mut result = Vec::new(); + for (marker, fragment) in [ + ("document.getElementById", false), + ("document.querySelector", true), + ] { + for offset in code_marker_offsets(value, marker) { + let remaining = &value[offset + marker.len()..]; + let Some(argument) = remaining + .trim_start() + .strip_prefix('(') + .map(str::trim_start) + else { + continue; + }; + let Some(quote) = argument + .chars() + .next() + .filter(|quote| matches!(quote, '\'' | '"')) + else { + continue; + }; + let literal = &argument[quote.len_utf8()..]; + let Some(end) = literal.find(quote) else { + continue; + }; + let literal = &literal[..end]; + if let Some(target) = literal + .strip_prefix('#') + .or_else(|| (!fragment).then_some(literal)) + && !target.is_empty() + { + result.push(target); + } + } + } + result +} + +fn code_marker_offsets(value: &str, marker: &str) -> Vec { let mut result = Vec::new(); + let mut offset = 0; let mut quote = None; - let mut start = 0; let mut escaped = false; - for (index, character) in value.char_indices() { + while offset < value.len() { + let character = value[offset..] + .chars() + .next() + .expect("offset remains on a character boundary"); if let Some(delimiter) = quote { if escaped { escaped = false; } else if character == '\\' { escaped = true; } else if character == delimiter { - result.push(&value[start..index]); quote = None; } - } else if matches!(character, '\'' | '"') { + } else if matches!(character, '\'' | '"' | '`') { quote = Some(character); - start = index + character.len_utf8(); + } else if value[offset..].starts_with(marker) { + result.push(offset); + offset += marker.len(); + continue; } + offset += character.len_utf8(); } result } @@ -419,6 +469,17 @@ fn has_element_child(dom: &NativeDom, node: NativeNodeId) -> bool { 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 { 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 index 48257e1f487..0e08c5df909 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -21,7 +21,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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.head.innerHTML = ''; document.body.innerHTML = `

Article

Visible body

Translation pending
@@ -33,8 +33,9 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {
Transparent parent Transparent child
Buy {{product.name}} for {{product.price | currency}}
Vue template {{message}}
-

Visible value hidden suffix 8

-

CSS override VISIBLE

+

Visible value hidden suffix 8

+

CSS override VISIBLE

+

Stylesheet override ALSO VISIBLE

White on black stays visible

Faded text

Animated article text

@@ -53,9 +54,14 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { `; "#).unwrap(); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('legacy-hidden')).color").unwrap(), "rgb(255, 255, 255)"); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('css-override')).color").unwrap(), "rgb(0, 0, 0)"); + assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('external-override')).color").unwrap(), "rgb(0, 0, 0)"); + assert_eq!(page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','black'); getComputedStyle(document.getElementById('legacy-hidden')).color").unwrap(), "rgb(0, 0, 0)"); + page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','white')").unwrap(); for strip_css in [false, true] { let output = page.render_page_dump(options(strip_css)); - for kept in ["Visible body", "Restored child", "Panel content", "ARIA panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value hidden suffix 8", "CSS override VISIBLE", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + for kept in ["Visible body", "Restored child", "Panel content", "ARIA panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value 8", "CSS override VISIBLE", "Stylesheet override ALSO VISIBLE", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { assert!(output.contains(kept), "missing {kept}: {output}"); } assert!(output.contains("10−17"), "{output}"); @@ -63,7 +69,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { assert!(output.contains("Active\nReviewed"), "{output}"); assert!(!output.contains("tracking.gif"), "{output}"); assert!(output.contains("Upload complete"), "{output}"); - for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "product.name", "Vue template"] { + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { assert!(!output.contains(omitted), "leaked {omitted}: {output}"); } } @@ -119,6 +125,27 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { let expanded = page.render_page_dump(options(false)); assert!(expanded.contains("Expandable history"), "{expanded}"); assert!(!expanded.contains("Hidden template"), "{expanded}"); + page.vm_mut().eval(r##" + document.body.innerHTML = ` + + + + + + `; + "##).unwrap(); + let related = page.render_page_dump(options(false)); + assert!(!related.contains("Hidden telemetry state"), "{related}"); + assert!(!related.contains("Hidden diagnostic state"), "{related}"); + assert!(related.contains("Query-selected history"), "{related}"); + page.vm_mut().eval(r#" + document.body.innerHTML = ` +

Visible gradient text

+
Photo
`; + "#).unwrap(); + let painted = page.render_page_dump(options(false)); + assert!(painted.contains("Visible gradient text"), "{painted}"); + assert!(painted.contains("![Photo](https://example.test/photo.png)"), "{painted}"); page.vm_mut().eval(r#" document.body.innerHTML = ` Responsive 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. From 7450ce0d035f121a22bf86071f879b13dbe1e26c Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:34:05 +0800 Subject: [PATCH 06/21] fix(html2md): keep preformatted blocks as markdown code --- moli-html2md/src/anchors.rs | 24 +++++++++++++++++++++++ moli-html2md/src/machine.rs | 32 ++++++++++++++++++------------- moli-html2md/tests/regressions.rs | 17 ++++++++-------- 3 files changed, 52 insertions(+), 21 deletions(-) diff --git a/moli-html2md/src/anchors.rs b/moli-html2md/src/anchors.rs index 32c790dd268..ac97016687f 100644 --- a/moli-html2md/src/anchors.rs +++ b/moli-html2md/src/anchors.rs @@ -37,6 +37,30 @@ pub(crate) fn contains( }) } +pub(crate) fn within( + dom: &D, + root: D::NodeId, + limit: usize, + ids: &HashSet, +) -> Vec { + let mut found = Vec::new(); + walk(dom, root, limit, |node| { + for attribute in ["id", "name"] { + if attribute == "name" && dom.node_kind(node) != NodeKind::Element("a") { + continue; + } + if let Some(id) = dom.attribute(node, attribute) + && ids.contains(id) + && !found.iter().any(|existing| existing == id) + { + found.push(id.to_owned()); + } + } + false + }); + found +} + fn walk( dom: &D, root: D::NodeId, diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index fe780200d0e..914a0bccb7a 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -354,14 +354,15 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } "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, - )) + if tag == "code" + && (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, @@ -370,13 +371,18 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.options.max_depth, &self.anchor_targets, ); - if tag == "pre" { - self.writer().block(html.into(), 2, 2); - } else { - self.writer().inline_html(&html); - } + 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)) diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index 88bb7e28e2f..e74808454ef 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -867,6 +867,8 @@ fn html_fallback_preserves_referenced_targets_for_special_nodes() { false, ); assert!(code.contains(""), "{code}"); + assert!(code.contains("```\nlet x = 1;\n```"), "{code}"); + assert!(!code.contains("
"), "{code}");
     let table = markdown(
         "EmailEquationVideo
x
", false, @@ -888,18 +890,15 @@ fn invalid_nested_and_empty_headings_do_not_emit_literal_markers() { } #[test] -fn preformatted_navigation_retains_link_targets() { +fn preformatted_navigation_retains_literal_content_as_markdown_code() { let result = markdown( "
ALL GAMES: HOME GAMES : AWAY GAMES\nScores stay aligned
", false, ); - assert!(result.contains("
"), "{result}");
+    assert!(result.starts_with("```\n"), "{result}");
+    assert!(!result.contains("
"), "{result}");
     assert!(
-        result.contains("HOME GAMES"),
-        "{result}"
-    );
-    assert!(
-        result.contains("AWAY GAMES"),
+        result.contains("ALL GAMES: HOME GAMES : AWAY GAMES"),
         "{result}"
     );
     assert!(result.contains("Scores stay aligned"), "{result}");
@@ -912,10 +911,12 @@ fn preformatted_code_preserves_externally_referenced_targets() {
         false,
     );
     assert!(result.contains("[Line 1](#L1)"), "{result}");
+    assert!(result.contains(""), "{result}");
     assert!(
-        result.contains("let x = 1;"),
+        result.contains("```\nlet x = 1;\nlet y = 2;\n```"),
         "{result}"
     );
+    assert!(!result.contains("
"), "{result}");
 }
 
 #[test]

From 9ab29d38cad078fdce3f80e8c417840e4c79e5ca Mon Sep 17 00:00:00 2001
From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com>
Date: Mon, 28 Sep 2026 14:00:06 +0800
Subject: [PATCH 07/21] fix(html2md): expose table code as markdown

---
 moli-html2md/src/html_table.rs    | 23 +++++++++++++++++++++++
 moli-html2md/src/machine.rs       | 24 ++++++++++++++++++++++++
 moli-html2md/tests/conversion.rs  |  3 ++-
 moli-html2md/tests/regressions.rs | 23 +++++++++++++++++++----
 moli-html2md/tests/tables.rs      | 16 ++++++++--------
 5 files changed, 76 insertions(+), 13 deletions(-)

diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs
index 6e52b285b3e..a398219be2d 100644
--- a/moli-html2md/src/html_table.rs
+++ b/moli-html2md/src/html_table.rs
@@ -76,6 +76,29 @@ pub(crate) fn has_cells(
     false
 }
 
+pub(crate) fn has_preformatted(
+    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("pre")) {
+            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),
diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs
index 914a0bccb7a..ea372d59050 100644
--- a/moli-html2md/src/machine.rs
+++ b/moli-html2md/src/machine.rs
@@ -440,6 +440,30 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
                         "presentation" | "none"
                     )
                 });
+                // A raw HTML table keeps cell associations, but Markdown code
+                // extractors cannot see a 
 nested inside that block. No
+                // Markdown table syntax can contain a fenced block either, so
+                // keep the visible cells in source order and let the ordinary
+                // block visitor emit the preformatted content as a fence.
+                if crate::html_table::has_preformatted(
+                    self.dom,
+                    node,
+                    depth,
+                    self.options.max_depth,
+                ) {
+                    for attribute in ["id", "name"] {
+                        if let Some(id) = self.dom.attribute(node, attribute)
+                            && self.anchor_targets.contains(id)
+                            && self.emitted_anchors.insert(id.to_owned())
+                        {
+                            self.writer().inline_html(&crate::anchors::markup(id));
+                        }
+                    }
+                    self.writer().boundary(2);
+                    self.tasks.push(Task::Boundary);
+                    self.children(node, depth + 1);
+                    return;
+                }
                 if (!presentation
                     && crate::html_table::needed(self.dom, node, depth, self.options.max_depth))
                     || (!self.anchor_targets.is_empty()
diff --git a/moli-html2md/tests/conversion.rs b/moli-html2md/tests/conversion.rs
index 2238d5d5b06..bae5caa458c 100644
--- a/moli-html2md/tests/conversion.rs
+++ b/moli-html2md/tests/conversion.rs
@@ -515,7 +515,8 @@ fn markdown_parser_recovers_pipes_and_preformatted_code_inside_tables() {
     let markdown = convert(&dom, 0);
     let html = support::rendered_html(&markdown);
     assert!(html.contains("a|b"), "{html}");
-    assert_eq!(html.matches("").count(), 2);
+    assert_eq!(html.matches("").count(), 0);
+    assert!(markdown.contains("```\n  |b\nnext\n```"), "{markdown}");
     let parsed = support::Tree::parse(&html);
     assert!(
         parsed
diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs
index e74808454ef..05aa8c48aad 100644
--- a/moli-html2md/tests/regressions.rs
+++ b/moli-html2md/tests/regressions.rs
@@ -223,10 +223,7 @@ fn complex_tables_keep_media_choices_and_literal_content_inert() {
     let source = "
<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("Day\nNight"), "{html}"); assert!( html.contains("<script>literal</script>"), "{html}" @@ -919,6 +916,24 @@ fn preformatted_code_preserves_externally_referenced_targets() { assert!(!result.contains("
"), "{result}");
 }
 
+#[test]
+fn preformatted_code_inside_complex_tables_remains_markdown_code() {
+    let result = markdown(
+        "Source
Code
let x = 1;\nlet y = 2;
Explanation
", + false, + ); + assert!(result.contains("[Source](#line-1)"), "{result}"); + assert!(result.contains(""), "{result}"); + assert!( + result.contains("```\nlet x = 1;\nlet y = 2;\n```"), + "{result}" + ); + assert!(result.contains("Code"), "{result}"); + assert!(result.contains("Explanation"), "{result}"); + assert!(!result.contains(" quote"), "{output}"); + assert!(output.contains("- item"), "{output}"); + assert!(output.ends_with("end"), "{output}"); + assert!(!output.contains(" code\nnext\n
", "
  • item
", "

Title

", "
quote
", From 1486f8c4256ad427da27dab3cf6d7b083e7dbe55 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:01:44 +0800 Subject: [PATCH 08/21] fix(content): preserve semantic pre and visibility relationships --- moli-html2md/src/anchors.rs | 27 +++++- moli-html2md/src/html_table.rs | 23 ----- moli-html2md/src/machine.rs | 47 +++------ moli-html2md/tests/conversion.rs | 3 +- moli-html2md/tests/regressions.rs | 50 +++++----- moli-html2md/tests/tables.rs | 16 ++-- .../src/runtime/page_dump/visibility.rs | 96 +++---------------- .../runtime/page_vm/tests/markdown_dump.rs | 12 ++- 8 files changed, 89 insertions(+), 185 deletions(-) diff --git a/moli-html2md/src/anchors.rs b/moli-html2md/src/anchors.rs index ac97016687f..d49abbf687c 100644 --- a/moli-html2md/src/anchors.rs +++ b/moli-html2md/src/anchors.rs @@ -7,17 +7,38 @@ pub(crate) fn referenced( root: D::NodeId, limit: usize, ) -> HashSet { - let mut ids = HashSet::new(); + let mut targets = HashSet::new(); if !dom.may_have_fragment_links() { - return ids; + return targets; } + 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) { + targets.insert(value.to_owned()); + } + } + false + }); + let mut ids = HashSet::new(); walk(dom, root, limit, |node| { if let Some(fragment) = dom .attribute(node, "href") .and_then(|href| href.strip_prefix('#')) && !fragment.is_empty() { - ids.insert(decode_fragment(fragment)); + // HTML fragment navigation tries the literal fragment first and + // only percent-decodes it when no literal target exists. + if targets.contains(fragment) { + ids.insert(fragment.to_owned()); + } else { + let decoded = decode_fragment(fragment); + if targets.contains(&decoded) { + ids.insert(decoded); + } + } } false }); diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs index a398219be2d..6e52b285b3e 100644 --- a/moli-html2md/src/html_table.rs +++ b/moli-html2md/src/html_table.rs @@ -76,29 +76,6 @@ pub(crate) fn has_cells( false } -pub(crate) fn has_preformatted( - 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("pre")) { - 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), diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index ea372d59050..56d691594a4 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -354,15 +354,14 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } "code" | "pre" => { let remaining = self.options.max_depth - depth; - if tag == "code" - && (subtree_has_link(self.dom, node, remaining) - || (!self.anchor_targets.is_empty() - && crate::anchors::contains( - self.dom, - node, - remaining, - &self.anchor_targets, - ))) + 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, @@ -371,7 +370,11 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { self.options.max_depth, &self.anchor_targets, ); - self.writer().inline_html(&html); + 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() { @@ -440,30 +443,6 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { "presentation" | "none" ) }); - // A raw HTML table keeps cell associations, but Markdown code - // extractors cannot see a
 nested inside that block. No
-                // Markdown table syntax can contain a fenced block either, so
-                // keep the visible cells in source order and let the ordinary
-                // block visitor emit the preformatted content as a fence.
-                if crate::html_table::has_preformatted(
-                    self.dom,
-                    node,
-                    depth,
-                    self.options.max_depth,
-                ) {
-                    for attribute in ["id", "name"] {
-                        if let Some(id) = self.dom.attribute(node, attribute)
-                            && self.anchor_targets.contains(id)
-                            && self.emitted_anchors.insert(id.to_owned())
-                        {
-                            self.writer().inline_html(&crate::anchors::markup(id));
-                        }
-                    }
-                    self.writer().boundary(2);
-                    self.tasks.push(Task::Boundary);
-                    self.children(node, depth + 1);
-                    return;
-                }
                 if (!presentation
                     && crate::html_table::needed(self.dom, node, depth, self.options.max_depth))
                     || (!self.anchor_targets.is_empty()
diff --git a/moli-html2md/tests/conversion.rs b/moli-html2md/tests/conversion.rs
index bae5caa458c..2238d5d5b06 100644
--- a/moli-html2md/tests/conversion.rs
+++ b/moli-html2md/tests/conversion.rs
@@ -515,8 +515,7 @@ fn markdown_parser_recovers_pipes_and_preformatted_code_inside_tables() {
     let markdown = convert(&dom, 0);
     let html = support::rendered_html(&markdown);
     assert!(html.contains("a|b"), "{html}");
-    assert_eq!(html.matches("").count(), 0);
-    assert!(markdown.contains("```\n  |b\nnext\n```"), "{markdown}");
+    assert_eq!(html.matches("").count(), 2);
     let parsed = support::Tree::parse(&html);
     assert!(
         parsed
diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs
index 05aa8c48aad..6c8ca421492 100644
--- a/moli-html2md/tests/regressions.rs
+++ b/moli-html2md/tests/regressions.rs
@@ -223,7 +223,10 @@ fn complex_tables_keep_media_choices_and_literal_content_inert() {
     let source = "
<script>literal</script>\n\nline
Bad link
"; let html = rendered_html(&markdown(source, false)); assert!(html.contains("href=\"/lecture\">Lecture
"), "{html}"); - assert!(html.contains("Day\nNight"), "{html}"); + assert!( + html.contains(""), + "{html}" + ); assert!( html.contains("<script>literal</script>"), "{html}" @@ -666,6 +669,16 @@ fn fragment_decoding_does_not_rewrite_dom_ids() { assert!(result.contains("Target"), "{result}"); } +#[test] +fn literal_fragment_target_wins_before_percent_decoding() { + let result = markdown( + "Go

Original target

Different target

", + false, + ); + assert!(result.contains(""), "{result}"); + assert!(!result.contains(""), "{result}"); +} + #[test] fn table_fragment_targets_preserve_rows_cells_and_legacy_named_anchors() { let source = "RowCellLegacy
ValueOther
"; @@ -864,8 +877,6 @@ fn html_fallback_preserves_referenced_targets_for_special_nodes() { false, ); assert!(code.contains(""), "{code}"); - assert!(code.contains("```\nlet x = 1;\n```"), "{code}"); - assert!(!code.contains("
"), "{code}");
     let table = markdown(
         "EmailEquationVideo
x
", false, @@ -887,15 +898,18 @@ fn invalid_nested_and_empty_headings_do_not_emit_literal_markers() { } #[test] -fn preformatted_navigation_retains_literal_content_as_markdown_code() { +fn preformatted_navigation_retains_link_targets() { let result = markdown( "
ALL GAMES: HOME GAMES : AWAY GAMES\nScores stay aligned
", false, ); - assert!(result.starts_with("```\n"), "{result}"); - assert!(!result.contains("
"), "{result}");
+    assert!(result.contains("
"), "{result}");
     assert!(
-        result.contains("ALL GAMES: HOME GAMES : AWAY GAMES"),
+        result.contains("HOME GAMES"),
+        "{result}"
+    );
+    assert!(
+        result.contains("AWAY GAMES"),
         "{result}"
     );
     assert!(result.contains("Scores stay aligned"), "{result}");
@@ -908,30 +922,10 @@ fn preformatted_code_preserves_externally_referenced_targets() {
         false,
     );
     assert!(result.contains("[Line 1](#L1)"), "{result}");
-    assert!(result.contains(""), "{result}");
-    assert!(
-        result.contains("```\nlet x = 1;\nlet y = 2;\n```"),
-        "{result}"
-    );
-    assert!(!result.contains("
"), "{result}");
-}
-
-#[test]
-fn preformatted_code_inside_complex_tables_remains_markdown_code() {
-    let result = markdown(
-        "Source
Code
let x = 1;\nlet y = 2;
Explanation
", - false, - ); - assert!(result.contains("[Source](#line-1)"), "{result}"); - assert!(result.contains(""), "{result}"); assert!( - result.contains("```\nlet x = 1;\nlet y = 2;\n```"), + result.contains("let x = 1;"), "{result}" ); - assert!(result.contains("Code"), "{result}"); - assert!(result.contains("Explanation"), "{result}"); - assert!(!result.contains(" quote"), "{output}"); - assert!(output.contains("- item"), "{output}"); - assert!(output.ends_with("end"), "{output}"); - assert!(!output.contains(" code\nnext\n
", "
  • item
", "

Title

", "
quote
", diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 5c9c20d4e3e..56090c2b7a6 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -42,6 +42,7 @@ impl<'a> MarkdownDom<'a> { // 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())) @@ -56,6 +57,15 @@ impl<'a> MarkdownDom<'a> { .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 = dom + .parent_node(*node) + .is_some_and(|parent| non_solid_backgrounds.contains(&parent)); + if own_image || inherited_image { + non_solid_backgrounds.insert(*node); + } } } let mut disclosures = HashSet::new(); @@ -76,19 +86,6 @@ impl<'a> MarkdownDom<'a> { { disclosures.extend(targets.split_ascii_whitespace()); } - for attribute_name in dom.get_attribute_names(*node).unwrap_or_default() { - if !attribute_name.starts_with("on") { - continue; - } - let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else { - continue; - }; - for target in inline_disclosure_targets(handler) { - if let Some((&id, _)) = targets.get_key_value(target) { - disclosures.insert(id); - } - } - } // Some pages pair a shortened paragraph with an explicitly linked // hidden full-text copy. Keep the complete copy once; an unrelated // dialog or a matching paragraph elsewhere is not such a pair. @@ -193,9 +190,7 @@ impl<'a> MarkdownDom<'a> { let foreground = values.get(10).and_then(|value| css_color(value)); let zero_contrast_leaf = !has_element_child(dom, node) && has_text_child(dom, node) - && values - .get(13) - .is_none_or(|image| image.is_empty() || image == "none") + && !non_solid_backgrounds.contains(&node) && foreground .filter(|color| color.3 > 0.99) .zip(effective_backgrounds.get(&node).copied()) @@ -333,75 +328,6 @@ impl<'a> MarkdownDom<'a> { } } -fn inline_disclosure_targets(value: &str) -> Vec<&str> { - let mut result = Vec::new(); - for (marker, fragment) in [ - ("document.getElementById", false), - ("document.querySelector", true), - ] { - for offset in code_marker_offsets(value, marker) { - let remaining = &value[offset + marker.len()..]; - let Some(argument) = remaining - .trim_start() - .strip_prefix('(') - .map(str::trim_start) - else { - continue; - }; - let Some(quote) = argument - .chars() - .next() - .filter(|quote| matches!(quote, '\'' | '"')) - else { - continue; - }; - let literal = &argument[quote.len_utf8()..]; - let Some(end) = literal.find(quote) else { - continue; - }; - let literal = &literal[..end]; - if let Some(target) = literal - .strip_prefix('#') - .or_else(|| (!fragment).then_some(literal)) - && !target.is_empty() - { - result.push(target); - } - } - } - result -} - -fn code_marker_offsets(value: &str, marker: &str) -> Vec { - let mut result = Vec::new(); - let mut offset = 0; - let mut quote = None; - let mut escaped = false; - while offset < value.len() { - let character = value[offset..] - .chars() - .next() - .expect("offset remains on a character boundary"); - if let Some(delimiter) = quote { - if escaped { - escaped = false; - } else if character == '\\' { - escaped = true; - } else if character == delimiter { - quote = None; - } - } else if matches!(character, '\'' | '"' | '`') { - quote = Some(character); - } else if value[offset..].starts_with(marker) { - result.push(offset); - offset += marker.len(); - continue; - } - offset += character.len_utf8(); - } - result -} - fn px(value: &str) -> Option { value.strip_suffix("px")?.trim().parse().ok() } 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 index 0e08c5df909..f147146b975 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -118,7 +118,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { } page.vm_mut().eval(r##" document.body.innerHTML = ` - + + `; "##).unwrap(); @@ -131,20 +131,28 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { + + + + `; "##).unwrap(); let related = page.render_page_dump(options(false)); assert!(!related.contains("Hidden telemetry state"), "{related}"); assert!(!related.contains("Hidden diagnostic state"), "{related}"); - assert!(related.contains("Query-selected history"), "{related}"); + assert!(!related.contains("Hidden read-only state"), "{related}"); + assert!(!related.contains("Hidden commented state"), "{related}"); + assert!(!related.contains("Query-selected history"), "{related}"); 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 = ` From 3303fadb1aa1ccface86b7919b2063fdc79b7f2e Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:26:29 +0800 Subject: [PATCH 09/21] fix(content): preserve rendered semantics across fallbacks --- moli-html2md/src/anchors.rs | 89 +++++++---- moli-html2md/src/content.rs | 99 ++++++++++++ moli-html2md/src/html_table.rs | 57 +++---- moli-html2md/src/lib.rs | 1 + moli-html2md/src/machine.rs | 104 +++++++------ moli-html2md/src/math.rs | 23 +-- moli-html2md/src/media.rs | 131 ++++++++++++---- moli-html2md/tests/regressions.rs | 85 ++++++++++ moli-renderer-v8/src/runtime/page_dump.rs | 6 +- .../src/runtime/page_dump/visibility.rs | 147 ++++++++++++------ .../runtime/page_vm/tests/markdown_dump.rs | 40 ++++- 11 files changed, 566 insertions(+), 216 deletions(-) create mode 100644 moli-html2md/src/content.rs diff --git a/moli-html2md/src/anchors.rs b/moli-html2md/src/anchors.rs index d49abbf687c..58312d22d22 100644 --- a/moli-html2md/src/anchors.rs +++ b/moli-html2md/src/anchors.rs @@ -2,14 +2,45 @@ use std::collections::HashSet; use crate::{Dom, NodeKind}; -pub(crate) fn referenced( - dom: &D, - root: D::NodeId, - limit: usize, -) -> HashSet { - let mut targets = HashSet::new(); +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 target<'a, D: Dom + ?Sized>( + &self, + dom: &'a D, + node: D::NodeId, + ) -> Option<&'a str> { + if let Some(id) = dom.attribute(node, "id").filter(|id| self.contains(id)) { + return Some(id); + } + if dom.node_kind(node) == NodeKind::Element("a") { + return dom + .attribute(node, "name") + .filter(|name| self.contains(name) && !self.ids.contains(*name)); + } + None + } +} + +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; + return Targets { + referenced: available, + ids: element_ids, + }; } walk(dom, root, limit, |node| { for attribute in ["id", "name"] { @@ -17,12 +48,15 @@ pub(crate) fn referenced( continue; } if let Some(value) = dom.attribute(node, attribute) { - targets.insert(value.to_owned()); + available.insert(value.to_owned()); + if attribute == "id" { + element_ids.insert(value.to_owned()); + } } } false }); - let mut ids = HashSet::new(); + let mut referenced = HashSet::new(); walk(dom, root, limit, |node| { if let Some(fragment) = dom .attribute(node, "href") @@ -31,51 +65,44 @@ pub(crate) fn referenced( { // HTML fragment navigation tries the literal fragment first and // only percent-decodes it when no literal target exists. - if targets.contains(fragment) { - ids.insert(fragment.to_owned()); + if available.contains(fragment) { + referenced.insert(fragment.to_owned()); } else { let decoded = decode_fragment(fragment); - if targets.contains(&decoded) { - ids.insert(decoded); + if available.contains(&decoded) { + referenced.insert(decoded); } } } false }); - ids + Targets { + referenced, + ids: element_ids, + } } pub(crate) fn contains( dom: &D, root: D::NodeId, limit: usize, - ids: &HashSet, + ids: &Targets, ) -> bool { - walk(dom, root, limit, |node| { - ["id", "name"] - .iter() - .any(|name| dom.attribute(node, name).is_some_and(|id| ids.contains(id))) - }) + walk(dom, root, limit, |node| ids.target(dom, node).is_some()) } pub(crate) fn within( dom: &D, root: D::NodeId, limit: usize, - ids: &HashSet, + ids: &Targets, ) -> Vec { let mut found = Vec::new(); walk(dom, root, limit, |node| { - for attribute in ["id", "name"] { - if attribute == "name" && dom.node_kind(node) != NodeKind::Element("a") { - continue; - } - if let Some(id) = dom.attribute(node, attribute) - && ids.contains(id) - && !found.iter().any(|existing| existing == id) - { - found.push(id.to_owned()); - } + if let Some(id) = ids.target(dom, node) + && !found.iter().any(|existing| existing == id) + { + found.push(id.to_owned()); } false }); diff --git a/moli-html2md/src/content.rs b/moli-html2md/src/content.rs new file mode 100644 index 00000000000..d81079c4758 --- /dev/null +++ b/moli-html2md/src/content.rs @@ -0,0 +1,99 @@ +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; + } + _ => {} + } + 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_within( + dom: &D, + root: D::NodeId, + limit: usize, +) -> Option { + let mut pending = vec![(root, 0)]; + while let Some((node, depth)) = pending.pop() { + if let Some(text) = fallback_text(dom, node) { + return Some(text); + } + if depth + 1 >= limit { + 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().map(|id| (id, depth + 1))); + } + None +} + +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/html_table.rs b/moli-html2md/src/html_table.rs index 6e52b285b3e..5e856eb1b90 100644 --- a/moli-html2md/src/html_table.rs +++ b/moli-html2md/src/html_table.rs @@ -80,6 +80,7 @@ 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 @@ -90,13 +91,14 @@ pub(crate) fn render( root: D::NodeId, depth: usize, limit: usize, - anchor_targets: &HashSet, + 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("( if depth >= limit { continue; } - let anchor = ["id", "name"].iter().find_map(|name| { - dom.attribute(node, name) - .filter(|id| anchor_targets.contains(*id)) - }); + 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(" ")); + } + } + let anchor = anchor_targets.target(dom, node); if let (NodeKind::Element(tag), Some(id)) = (dom.node_kind(node), anchor) && !allowed(tag) && emitted_anchors.insert(id) @@ -166,36 +174,7 @@ pub(crate) fn render( continue; } } - let retained = if allowed(tag) { - Some(tag) - } else if dom.has_block_layout(node) { - Some("div") - } else { - None - }; - if dom.has_block_layout(node) - && matches!( - retained, - Some( - "a" | "span" - | "strong" - | "b" - | "em" - | "i" - | "s" - | "del" - | "sup" - | "sub" - | "code" - | "img" - | "select" - | "button" - ) - ) - { - output.push_str("
"); - tasks.push(Task::Close("div".to_owned())); - } + let retained = if allowed(tag) { Some(tag) } else { None }; if let Some(tag) = retained { output.push('<'); output.push_str(tag); @@ -241,7 +220,13 @@ pub(crate) fn render( limit - depth - relative_depth, )); } else { - tasks.push(Task::Siblings(dom.first_child(node), depth + 1)); + if !crate::content::has_readable_content(dom, node, limit - depth) + && let Some(label) = crate::content::fallback_text(dom, node) + { + escape(&label, &mut output); + } else { + tasks.push(Task::Siblings(dom.first_child(node), depth + 1)); + } } } NodeKind::Document => { diff --git a/moli-html2md/src/lib.rs b/moli-html2md/src/lib.rs index 5be32fe2c33..fb21db22823 100644 --- a/moli-html2md/src/lib.rs +++ b/moli-html2md/src/lib.rs @@ -1,4 +1,5 @@ mod anchors; +mod content; mod converter; mod dom; mod form; diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 56d691594a4..6dcb75dac57 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -42,7 +42,7 @@ struct Machine<'a, D: Dom + ?Sized> { raw: String, serial: usize, in_svg: bool, - anchor_targets: HashSet, + anchor_targets: crate::anchors::Targets, emitted_anchors: HashSet, } @@ -220,6 +220,13 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { if nonrendered_serialized_state(self.dom, node) { return; } + if matches!(tag, "p" | "div") + && let Some(text) = + transparent_math_text(self.dom, node, self.options.max_depth.saturating_sub(depth)) + { + self.writer().text(&text); + return; + } let tooltip = self .dom .attribute(node, "data-toggle") @@ -257,16 +264,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { "head" | "script" | "style" | "noscript" | "template" | "title" ) { - for attribute in ["id", "name"] { - if attribute == "name" && tag != "a" { - continue; - } - if let Some(id) = self.dom.attribute(node, attribute) - && self.anchor_targets.contains(id) - && self.emitted_anchors.insert(id.to_owned()) - { - self.writer().inline_html(&crate::anchors::markup(id)); - } + if let Some(id) = self.anchor_targets.target(self.dom, node) + && self.emitted_anchors.insert(id.to_owned()) + { + self.writer().inline_html(&crate::anchors::markup(id)); } } match tag { @@ -405,7 +406,18 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { let remaining = self.options.max_depth - depth; if !subtree_has_content(self.dom, node, remaining) { - self.writer().boundary(2); + if let Some(label) = + crate::content::fallback_text_within(self.dom, node, remaining) + { + let heading = format!( + "{} {}", + "#".repeat((tag.as_bytes()[1] - b'0') as usize), + label + ); + self.writer().block(heading.into(), 2, 2); + } else { + self.writer().boundary(2); + } return; } if subtree_has_nested_heading(self.dom, node, remaining) { @@ -513,13 +525,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } if let Some(value) = tooltip_fallback { self.writer().text(value); - } else if self.dom.first_child(node).is_none() - && let Some(label) = self - .dom - .attribute(node, "aria-label") - .filter(|label| !label.trim().is_empty()) + } else if !subtree_has_content(self.dom, node, self.options.max_depth - depth) + && let Some(label) = crate::content::fallback_text(self.dom, node) { - self.writer().text(label); + self.writer().text(&label); return; } self.children(node, depth + 1); @@ -535,7 +544,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { && let Some(poster) = self .dom .attribute(node, "poster") - .filter(|src| !src.is_empty()) + .filter(|src| !src.is_empty() && crate::media::safe_url(src, true)) { self.writer().image("", poster, None); self.writer().boundary(1); @@ -728,40 +737,41 @@ fn quote_container(tag: &str, class: Option<&str>) -> bool { } fn subtree_has_content(dom: &D, root: D::NodeId, limit: usize) -> bool { - let mut pending = vec![(root, 0)]; + crate::content::has_readable_content(dom, root, limit) +} + +fn transparent_math_text( + dom: &D, + root: D::NodeId, + limit: usize, +) -> Option { + let mut pending = vec![(dom.first_child(root), 1)]; + let mut text = String::new(); + let mut crossed_wrapper = false; while let Some((node, depth)) = pending.pop() { + let Some(node) = node else { + continue; + }; + if depth >= limit { + return None; + } + pending.push((dom.next_sibling(node), depth)); match dom.node_kind(node) { - NodeKind::Text(text) if !text.trim_matches(char::is_whitespace).is_empty() => { - return true; - } - NodeKind::Element("img") - if crate::media::source(dom, node).is_some() - || dom - .attribute(node, "alt") - .is_some_and(|alt| !alt.trim().is_empty()) => - { - return true; - } - NodeKind::Element(_) - if dom.first_child(node).is_none() - && dom - .attribute(node, "aria-label") - .is_some_and(|label| !label.trim().is_empty()) => + NodeKind::Text(value) => text.push_str(value), + NodeKind::Other => crossed_wrapper = true, + NodeKind::Element("span") + if !dom.has_block_layout(node) && !dom.has_text_boundary(node) => { - return true; + crossed_wrapper = true; + pending.push((dom.first_child(node), depth + 1)); } - _ => {} - } - 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); + _ => return None, } } - false + if !crossed_wrapper { + return None; + } + (crate::math::next_span(&text) == Some((0, text.len()))).then_some(text) } fn subtree_has_nested_heading(dom: &D, root: D::NodeId, limit: usize) -> bool { diff --git a/moli-html2md/src/math.rs b/moli-html2md/src/math.rs index 0358d4b2bb9..f571ca15b01 100644 --- a/moli-html2md/src/math.rs +++ b/moli-html2md/src/math.rs @@ -11,14 +11,14 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { } else { (1, "$", true) } - } else if bytes[index] == b'\\' && !escaped(bytes, index) { - match bytes.get(index + 1) { - Some(b'(') => (2, "\\)", false), - Some(b'[') => (2, "\\]", false), - _ => { - index += 1; - continue; - } + } else if bytes[index] == b'\\' + && matches!(bytes.get(index + 1), Some(b'(' | b'[')) + && !escaped(bytes, index) + { + if bytes[index + 1] == b'(' { + (2, "\\)", false) + } else { + (2, "\\]", false) } } else { index += 1; @@ -58,7 +58,8 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { if bytes[content_start..end].windows(2).any(|pair| { pair[0] == b'<' && (pair[1].is_ascii_alphabetic() || matches!(pair[1], b'/' | b'!' | b'?')) - }) { + }) || contains_markdown_resource(&text[content_start..end]) + { break; } return Some((index, search)); @@ -68,6 +69,10 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { None } +fn contains_markdown_resource(text: &str) -> bool { + text.contains("](") || text.contains("][") || text.contains("![[") +} + fn escaped(bytes: &[u8], index: usize) -> bool { bytes[..index] .iter() diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index f98d8e59d21..050dbfdc198 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -5,58 +5,123 @@ use crate::{Dom, NodeKind}; /// Frozen DOMs can still carry lazy-loading placeholders. These conventional /// attributes declare the resource the page intends to load, not the spacer. pub(crate) fn source<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Option> { - if let Some(value) = direct_source(dom, node) { - return Some(Cow::Borrowed(value)); - } - - // A responsive image may intentionally leave `src` empty. Retain the - // largest declared candidate so the image does not disappear entirely. - ["data-srcset", "srcset"].into_iter().find_map(|name| { + // 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) = ["srcset", "data-srcset"].into_iter().find_map(|name| { dom.attribute(node, name) .and_then(largest_srcset_candidate) .filter(|value| safe_url(value, true)) .map(|value| Cow::Owned(value.to_owned())) - }) + }) { + return Some(value); + } + direct_source(dom, node, true).map(Cow::Borrowed) } -fn direct_source(dom: &D, node: D::NodeId) -> Option<&str> { +fn direct_source(dom: &D, node: D::NodeId, image: bool) -> Option<&str> { let usable = |value: &&str| { !value.is_empty() && !value.starts_with('#') && *value != "about:blank" - && safe_url(value, true) + && safe_url(value, image) }; let attr = |name| dom.attribute(node, name).map(str::trim).filter(usable); - if let Some(value) = attr("data-original") { - return Some(value); - } let src = attr("src"); - if let Some(value) = src.filter(|value| !is_placeholder_source(value)) { - return Some(value); + if src.is_some_and(is_explicit_placeholder) { + return attr("data-src") + .or_else(|| attr("data-lazy-src")) + .or_else(|| attr("data-original")) + .or(src); } - attr("data-src").or_else(|| attr("data-lazy-src")).or(src) + src.or_else(|| attr("data-src")) + .or_else(|| attr("data-lazy-src")) + .or_else(|| attr("data-original")) } -fn is_placeholder_source(value: &str) -> bool { +fn is_explicit_placeholder(value: &str) -> bool { let lower = value.to_ascii_lowercase(); - lower.starts_with("data:image/") - || [ - "placeholder", - "spacer", - "transparent", - "blank.gif", - "blank.png", - ] - .iter() - .any(|marker| lower.contains(marker)) + if lower.starts_with("data:image/") { + return true; + } + 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" + ) } fn largest_srcset_candidate(srcset: &str) -> Option<&str> { - srcset - .split(',') - .filter_map(|candidate| candidate.split_ascii_whitespace().next()) - .rfind(|url| !url.is_empty()) + let bytes = srcset.as_bytes(); + let mut offset = 0; + let mut best: Option<(&str, f64)> = None; + 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 descriptor_start = offset; + while offset < bytes.len() && bytes[offset] != b',' { + offset += 1; + } + let descriptors = srcset[descriptor_start..offset].split_ascii_whitespace(); + let mut score = 1.0; + let mut valid = true; + let mut seen = false; + for descriptor in descriptors { + if seen { + valid = false; + break; + } + seen = true; + score = if let Some(value) = descriptor.strip_suffix('w') { + value + .parse::() + .ok() + .filter(|value| *value > 0) + .map(f64::from) + } else if let Some(value) = descriptor.strip_suffix('x') { + value + .parse::() + .ok() + .filter(|value| value.is_finite() && *value > 0.0) + } else { + None + } + .unwrap_or_else(|| { + valid = false; + 0.0 + }); + } + if valid && !url.is_empty() && best.is_none_or(|(_, current)| score >= current) { + best = Some((url, score)); + } + } + best.map(|(url, _)| url) } pub(crate) fn safe_url(value: &str, image: bool) -> bool { @@ -86,7 +151,7 @@ pub(crate) fn sources<'a, D: Dom + ?Sized>( ) -> Vec<&'a str> { let mut urls = Vec::new(); let mut seen = std::collections::HashSet::new(); - if let Some(src) = direct_source(dom, node) { + if let Some(src) = direct_source(dom, node, tag == "img") { seen.insert(src); urls.push(src); } @@ -95,7 +160,7 @@ pub(crate) fn sources<'a, D: Dom + ?Sized>( 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) + && let Some(src) = direct_source(dom, id, false) && seen.insert(src) { urls.push(src); diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index 6c8ca421492..101623238cd 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -70,6 +70,32 @@ fn tex_payload_is_usable_by_a_markdown_math_reader() { 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(""), "{result}"); } +#[test] +fn fragment_targets_prefer_ids_and_only_accept_legacy_anchor_names() { + let result = rendered_html(&markdown( + "Go

Legacy

ID target

", + false, + )); + assert_eq!(result.matches("id=\"target\"").count(), 1, "{result}"); + assert!(result.find("ID target").unwrap() > result.find("id=\"target\"").unwrap()); + assert!(!result.contains("Legacy"), "{result}"); + + let result = rendered_html(&markdown( + "Go
WrongRight
", + false, + )); + assert!(!result.contains("id=\"target\">Wrong"), "{result}"); + assert!(result.contains("name=\"target\""), "{result}"); +} + #[test] fn table_fragment_targets_preserve_rows_cells_and_legacy_named_anchors() { let source = "RowCellLegacy
ValueOther
"; @@ -1036,6 +1080,47 @@ 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}"); +} + +#[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 [ diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 35f45839294..f22ab5d5462 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -83,14 +83,14 @@ impl PageVm { "left".to_owned(), "top".to_owned(), "color".to_owned(), - "animation-name".to_owned(), + "text-shadow".to_owned(), ], ); nodes .into_iter() .zip(values) .map(|(node, mut values)| { - let animation_name = values.pop().unwrap_or_default(); + 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); @@ -119,7 +119,7 @@ impl PageVm { ); values.push(foreground); values.push(backgrounds.get(&node).cloned().unwrap_or_default()); - values.push(animation_name); + values.push(text_shadow); values.push(background_images.get(&node).cloned().unwrap_or_default()); (node, values) }) diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 56090c2b7a6..fde37ba7cdb 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -17,6 +17,7 @@ pub(super) struct MarkdownDom<'a> { superscripts: HashSet, subscripts: HashSet, resolved_urls: HashMap>, + unchecked_controls: HashSet, fragment_links: bool, } @@ -29,12 +30,6 @@ impl<'a> MarkdownDom<'a> { 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('#')) }); @@ -48,10 +43,8 @@ impl<'a> MarkdownDom<'a> { .any(|(_, values)| values.get(11).is_some_and(|value| !value.is_empty())) { for (node, values) in &styles { - let own = values - .get(11) - .and_then(|value| css_color(value)) - .filter(|color| color.3 > 0.99); + let 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()); @@ -60,10 +53,12 @@ impl<'a> MarkdownDom<'a> { let own_image = values .get(13) .is_some_and(|image| !image.is_empty() && image != "none"); - let inherited_image = dom - .parent_node(*node) - .is_some_and(|parent| non_solid_backgrounds.contains(&parent)); - if own_image || inherited_image { + 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); } } @@ -82,9 +77,13 @@ impl<'a> MarkdownDom<'a> { if (Dom::attribute(dom, *node, "aria-expanded").is_some() || Dom::attribute(dom, *node, "role") .is_some_and(|role| role.eq_ignore_ascii_case("tab"))) - && let Some(targets) = Dom::attribute(dom, *node, "aria-controls") + && let Some(controlled) = Dom::attribute(dom, *node, "aria-controls") { - disclosures.extend(targets.split_ascii_whitespace()); + 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 @@ -133,6 +132,18 @@ impl<'a> MarkdownDom<'a> { } } } + let disclosure_roots: HashSet<_> = disclosures + .iter() + .filter_map(|id| targets.get(id).copied()) + .collect(); + let mut disclosure_paths = HashSet::new(); + for &target in &disclosure_roots { + let mut current = Some(target); + while let Some(node) = current { + disclosure_paths.insert(node); + current = dom.parent_node(node); + } + } let mut suppressed = excerpts; let mut invisible = HashSet::new(); let mut blocks = HashSet::new(); @@ -140,8 +151,26 @@ impl<'a> MarkdownDom<'a> { let mut superscripts = HashSet::new(); let mut subscripts = HashSet::new(); let mut resolved_urls = HashMap::new(); + let mut unchecked_controls = HashSet::new(); + let mut disclosure_regions = HashSet::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")) + && 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 element.checked() { + resolved_urls + .entry(node) + .or_insert_with(HashMap::new) + .insert("checked".to_owned(), String::new()); + } else { + 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. @@ -154,29 +183,24 @@ impl<'a> MarkdownDom<'a> { Dom::attribute(dom, node, attribute) .is_some_and(|value| !value.trim().is_empty()) }); - let disclosure = role.eq_ignore_ascii_case("tabpanel") + let disclosure_root = role.eq_ignore_ascii_case("tabpanel") || Dom::attribute(dom, node, "hidden") == Some("until-found") || (!matches!(role, "dialog" | "alertdialog" | "menu") && Dom::attribute(dom, node, "id").is_some_and(|id| disclosures.contains(id))); - let aria_hidden = Dom::attribute(dom, node, "aria-hidden") - .is_some_and(|value| value.eq_ignore_ascii_case("true")); + let disclosure = disclosure_root + || dom + .parent_node(node) + .is_some_and(|parent| disclosure_regions.contains(&parent)); + if disclosure { + disclosure_regions.insert(node); + } + let preserves_disclosure = disclosure || disclosure_paths.contains(&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 far_offscreen = values - .get(3) - .is_some_and(|position| matches!(position.as_str(), "absolute" | "fixed")) - && values - .get(4) - .and_then(|value| px(value)) - .is_some_and(|left| left <= -1000.0) - && values - .get(5) - .and_then(|value| px(value)) - .is_some_and(|top| top <= -1000.0); let tracking_pixel = matches!(Dom::node_kind(dom, node), NodeKind::Element("img")) && Dom::attribute(dom, node, "alt").is_none_or(|alt| alt.trim().is_empty()) && values @@ -191,6 +215,9 @@ impl<'a> MarkdownDom<'a> { 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()) @@ -200,25 +227,20 @@ impl<'a> MarkdownDom<'a> { == (background.0, background.1, background.2) }); let document_root = Some(node) == document_element || Some(node) == body; - let animated = values - .get(12) - .is_some_and(|name| !name.is_empty() && name != "none"); if ((values.first().is_some_and(|value| value == "none") || values .get(2) .is_some_and(|value| value.parse::() == Ok(0.0)) && !lazy_media - && !animated && !document_root) - && !disclosure) - || (aria_hidden && !disclosure) + && !preserves_disclosure) || uninitialized_template - || far_offscreen || tracking_pixel - || zero_contrast_leaf + || (zero_contrast_leaf && !preserves_disclosure) || dom .parent_node(node) .is_some_and(|parent| suppressed.contains(&parent)) + && !preserves_disclosure { suppressed.insert(node); } @@ -298,8 +320,7 @@ impl<'a> MarkdownDom<'a> { if values .get(1) .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) - && !disclosure - && !document_visibility_is_hidden + && !preserves_disclosure { invisible.insert(node); } @@ -313,6 +334,7 @@ impl<'a> MarkdownDom<'a> { superscripts, subscripts, resolved_urls, + unchecked_controls, fragment_links, } } @@ -328,23 +350,45 @@ impl<'a> MarkdownDom<'a> { } } +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 mut resolved = Vec::new(); - for candidate in value.split(',') { - let candidate = candidate.trim(); - if candidate.is_empty() { - continue; - } - let split = candidate + let mut remaining = value.trim(); + while !remaining.is_empty() { + let split = remaining .find(char::is_whitespace) - .unwrap_or(candidate.len()); - let (source, descriptor) = candidate.split_at(split); - let url = base_url.join(source).ok()?; - resolved.push(format!("{}{descriptor}", url)); + .unwrap_or(remaining.len()); + let source = &remaining[..split]; + remaining = remaining[split..].trim_start(); + let (descriptor, rest) = if let Some(end) = remaining.find(',') { + (remaining[..end].trim(), remaining[end + 1..].trim_start()) + } else { + (remaining.trim(), "") + }; + let url = base_url.join(source.trim_end_matches(',')).ok()?; + resolved.push(if descriptor.is_empty() { + url.to_string() + } else { + format!("{url} {descriptor}") + }); + remaining = rest; } (!resolved.is_empty()).then(|| resolved.join(", ")) } @@ -480,6 +524,9 @@ impl Dom for MarkdownDom<'_> { } 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)) 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 index f147146b975..f9ce09834fc 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -20,7 +20,7 @@ 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#" + page.vm_mut().eval(r##" document.head.innerHTML = ''; document.body.innerHTML = `

Article

Visible body

@@ -38,7 +38,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

Stylesheet override ALSO VISIBLE

White on black stays visible

Faded text

-

Animated article text

+

Animated hidden text

ActiveReviewed

Mass 2.4 × 10−17 J; mn

@@ -53,7 +53,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {
DetailsClosed details content
`; - "#).unwrap(); + "##).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)"); @@ -61,7 +61,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','white')").unwrap(); for strip_css in [false, true] { let output = page.render_page_dump(options(strip_css)); - for kept in ["Visible body", "Restored child", "Panel content", "ARIA panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value 8", "CSS override VISIBLE", "Stylesheet override ALSO VISIBLE", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + 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", "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}"); @@ -69,7 +69,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { assert!(output.contains("Active\nReviewed"), "{output}"); assert!(!output.contains("tracking.gif"), "{output}"); assert!(output.contains("Upload complete"), "{output}"); - for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Animated hidden text", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { assert!(!output.contains(omitted), "leaked {omitted}: {output}"); } } @@ -84,9 +84,11 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { page.vm_mut().eval(r#" document.documentElement.style.opacity = ''; document.body.style.visibility = 'hidden'; - document.body.innerHTML = '
Font loading veil
'; + document.body.innerHTML = '
Font loading veil
Independent hidden text
'; "#).unwrap(); - assert!(page.render_page_dump(options(false)).contains("Font loading veil")); + 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 = ''; @@ -154,13 +156,37 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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; + "#).unwrap(); + let controls = page.render_page_dump(options(false)); + assert!(controls.contains("Edited"), "{controls}"); + assert!(controls.contains("☑"), "{controls}"); + assert!(!controls.contains("Initial"), "{controls}"); page.vm_mut().eval(r#" document.body.innerHTML = ` Responsive + Comma URL Lazy responsive`; "#).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}"); page.vm_mut().eval("document.documentElement.style.display = 'none'").unwrap(); assert!(page.render_page_dump(options(false)).is_empty()); From 766f24740cd95acd2508a164dd69ec08eb733967 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:44:37 +0800 Subject: [PATCH 10/21] fix(content): preserve completed loading transitions --- moli-html2md/src/machine.rs | 8 ++-- moli-renderer-v8/src/runtime/page_dump.rs | 9 ++++ .../src/runtime/page_dump/visibility.rs | 46 +++++++++++++++++++ .../runtime/page_vm/tests/markdown_dump.rs | 4 +- 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 6dcb75dac57..58292dab4c4 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -263,12 +263,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { tag, "head" | "script" | "style" | "noscript" | "template" | "title" ) + && let Some(id) = self.anchor_targets.target(self.dom, node) + && self.emitted_anchors.insert(id.to_owned()) { - if let Some(id) = self.anchor_targets.target(self.dom, node) - && self.emitted_anchors.insert(id.to_owned()) - { - self.writer().inline_html(&crate::anchors::markup(id)); - } + self.writer().inline_html(&crate::anchors::markup(id)); } match tag { "math" => { diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index f22ab5d5462..20fd6e99d25 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -84,12 +84,18 @@ impl PageVm { "top".to_owned(), "color".to_owned(), "text-shadow".to_owned(), + "animation-name".to_owned(), + "animation-duration".to_owned(), + "animation-fill-mode".to_owned(), ], ); nodes .into_iter() .zip(values) .map(|(node, mut values)| { + let animation_fill_mode = values.pop().unwrap_or_default(); + let animation_duration = values.pop().unwrap_or_default(); + let animation_name = values.pop().unwrap_or_default(); let text_shadow = values.pop().unwrap_or_default(); let foreground = values.pop().unwrap_or_default(); // Preserve the visibility adapter's stable field layout. @@ -121,6 +127,9 @@ impl PageVm { 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(animation_name); + values.push(animation_duration); + values.push(animation_fill_mode); (node, values) }) .collect::>() diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index fde37ba7cdb..a377d2637d2 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -30,6 +30,12 @@ impl<'a> MarkdownDom<'a> { 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('#')) }); @@ -153,6 +159,7 @@ impl<'a> MarkdownDom<'a> { let mut resolved_urls = HashMap::new(); let mut unchecked_controls = HashSet::new(); let mut disclosure_regions = HashSet::new(); + let mut visibility_restored_regions = HashSet::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")) @@ -227,11 +234,19 @@ impl<'a> MarkdownDom<'a> { == (background.0, background.1, background.2) }); let document_root = Some(node) == document_element || Some(node) == body; + let visibility_restored = document_visibility_is_hidden + && !document_root + && values.get(1).is_some_and(|value| value == "visible"); + if visibility_restored { + visibility_restored_regions.insert(node); + } + let opacity_revealed_by_animation = animation_reveals_content(&values); if ((values.first().is_some_and(|value| value == "none") || values .get(2) .is_some_and(|value| value.parse::() == Ok(0.0)) && !lazy_media + && !opacity_revealed_by_animation && !document_root) && !preserves_disclosure) || uninitialized_template @@ -321,6 +336,10 @@ impl<'a> MarkdownDom<'a> { .get(1) .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) && !preserves_disclosure + && (!document_visibility_is_hidden + || dom + .parent_node(node) + .is_some_and(|parent| visibility_restored_regions.contains(&parent))) { invisible.insert(node); } @@ -350,6 +369,33 @@ impl<'a> MarkdownDom<'a> { } } +fn animation_reveals_content(values: &[String]) -> bool { + let named = values.get(14).is_some_and(|names| { + names + .split(',') + .any(|name| !matches!(name.trim(), "" | "none")) + }); + let has_duration = values.get(15).is_some_and(|durations| { + durations.split(',').any(|duration| { + let duration = duration.trim(); + duration + .strip_suffix("ms") + .and_then(|value| value.trim().parse::().ok()) + .is_some_and(|value| value > 0.0) + || duration + .strip_suffix('s') + .and_then(|value| value.trim().parse::().ok()) + .is_some_and(|value| value > 0.0) + }) + }); + let retains_final_frame = values.get(16).is_some_and(|modes| { + modes + .split(',') + .any(|mode| matches!(mode.trim(), "forwards" | "both")) + }); + named && has_duration && retains_final_frame +} + fn target_is_disclosure( dom: &D, targets: &HashMap<&str, D::NodeId>, 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 index f9ce09834fc..24123fc9737 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -39,6 +39,8 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

White on black stays visible

Faded text

Animated hidden text

+ +

Animated revealed text

ActiveReviewed

Mass 2.4 × 10−17 J; mn

@@ -61,7 +63,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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", "Visible value 8", "CSS override VISIBLE", "Stylesheet override ALSO VISIBLE", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + 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}"); From f1a90552b67adb496df921c6edbf405f2f3cbdbe Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:48:42 +0800 Subject: [PATCH 11/21] fix(content): preserve semantic streams and disclosure boundaries --- moli-html2md/src/anchors.rs | 30 ++-- moli-html2md/src/content.rs | 25 +-- moli-html2md/src/html_table.rs | 14 +- moli-html2md/src/machine.rs | 81 +++------ moli-html2md/src/math.rs | 155 ++++++++++++------ moli-html2md/src/media.rs | 87 ++++++---- moli-html2md/src/writer.rs | 29 +++- moli-html2md/tests/regressions.rs | 118 ++++++++++++- moli-renderer-v8/src/runtime/page_dump.rs | 9 - .../src/runtime/page_dump/visibility.rs | 127 +++++++------- .../runtime/page_vm/tests/markdown_dump.rs | 13 +- 11 files changed, 427 insertions(+), 261 deletions(-) diff --git a/moli-html2md/src/anchors.rs b/moli-html2md/src/anchors.rs index 58312d22d22..a4d8145a758 100644 --- a/moli-html2md/src/anchors.rs +++ b/moli-html2md/src/anchors.rs @@ -16,20 +16,20 @@ impl Targets { self.referenced.contains(value) } - pub(crate) fn target<'a, D: Dom + ?Sized>( - &self, - dom: &'a D, - node: D::NodeId, - ) -> Option<&'a str> { + 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)) { - return Some(id); + targets.push(id); } - if dom.node_kind(node) == NodeKind::Element("a") { - return dom + if dom.node_kind(node) == NodeKind::Element("a") + && let Some(name) = dom .attribute(node, "name") - .filter(|name| self.contains(name) && !self.ids.contains(*name)); + .filter(|name| self.contains(name) && !self.ids.contains(*name)) + && !targets.contains(&name) + { + targets.push(name); } - None + targets } } @@ -88,7 +88,7 @@ pub(crate) fn contains( limit: usize, ids: &Targets, ) -> bool { - walk(dom, root, limit, |node| ids.target(dom, node).is_some()) + walk(dom, root, limit, |node| !ids.targets(dom, node).is_empty()) } pub(crate) fn within( @@ -99,10 +99,10 @@ pub(crate) fn within( ) -> Vec { let mut found = Vec::new(); walk(dom, root, limit, |node| { - if let Some(id) = ids.target(dom, node) - && !found.iter().any(|existing| existing == id) - { - found.push(id.to_owned()); + for id in ids.targets(dom, node) { + if !found.iter().any(|existing| existing == id) { + found.push(id.to_owned()); + } } false }); diff --git a/moli-html2md/src/content.rs b/moli-html2md/src/content.rs index d81079c4758..e26ae6dcd6e 100644 --- a/moli-html2md/src/content.rs +++ b/moli-html2md/src/content.rs @@ -28,6 +28,7 @@ pub(crate) fn has_readable_content( NodeKind::Element("input") if crate::form::input_text(dom, node).is_some() => { return true; } + NodeKind::Element(_) if depth > 0 && fallback_text(dom, node).is_some() => return true, _ => {} } if depth + 1 >= limit { @@ -42,30 +43,6 @@ pub(crate) fn has_readable_content( false } -pub(crate) fn fallback_text_within( - dom: &D, - root: D::NodeId, - limit: usize, -) -> Option { - let mut pending = vec![(root, 0)]; - while let Some((node, depth)) = pending.pop() { - if let Some(text) = fallback_text(dom, node) { - return Some(text); - } - if depth + 1 >= limit { - 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().map(|id| (id, depth + 1))); - } - None -} - 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 diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs index 5e856eb1b90..dbcc9ecb1bb 100644 --- a/moli-html2md/src/html_table.rs +++ b/moli-html2md/src/html_table.rs @@ -122,12 +122,14 @@ pub(crate) fn render( tasks.push(Task::Literal(" ")); } } - let anchor = anchor_targets.target(dom, node); - if let (NodeKind::Element(tag), Some(id)) = (dom.node_kind(node), anchor) + if let NodeKind::Element(tag) = dom.node_kind(node) && !allowed(tag) - && emitted_anchors.insert(id) { - output.push_str(&crate::anchors::markup(id)); + for id in anchor_targets.targets(dom, node) { + if emitted_anchors.insert(id) { + output.push_str(&crate::anchors::markup(id)); + } + } } match dom.node_kind(node) { NodeKind::Text(text) => escape(text, &mut output), @@ -220,8 +222,8 @@ pub(crate) fn render( limit - depth - relative_depth, )); } else { - if !crate::content::has_readable_content(dom, node, limit - depth) - && let Some(label) = crate::content::fallback_text(dom, node) + if let Some(label) = crate::content::fallback_text(dom, node) + && !crate::content::has_readable_content(dom, node, limit - depth) { escape(&label, &mut output); } else { diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index 58292dab4c4..d1873b819ca 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -174,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); } @@ -220,13 +221,6 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { if nonrendered_serialized_state(self.dom, node) { return; } - if matches!(tag, "p" | "div") - && let Some(text) = - transparent_math_text(self.dom, node, self.options.max_depth.saturating_sub(depth)) - { - self.writer().text(&text); - return; - } let tooltip = self .dom .attribute(node, "data-toggle") @@ -263,13 +257,16 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { tag, "head" | "script" | "style" | "noscript" | "template" | "title" ) - && let Some(id) = self.anchor_targets.target(self.dom, node) - && self.emitted_anchors.insert(id.to_owned()) { - self.writer().inline_html(&crate::anchors::markup(id)); + 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; @@ -403,21 +400,6 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { let remaining = self.options.max_depth - depth; - if !subtree_has_content(self.dom, node, remaining) { - if let Some(label) = - crate::content::fallback_text_within(self.dom, node, remaining) - { - let heading = format!( - "{} {}", - "#".repeat((tag.as_bytes()[1] - b'0') as usize), - label - ); - self.writer().block(heading.into(), 2, 2); - } else { - self.writer().boundary(2); - } - return; - } if subtree_has_nested_heading(self.dom, node, remaining) { self.writer().boundary(2); self.tasks.push(Task::Boundary); @@ -513,6 +495,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { 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, @@ -523,8 +506,8 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } if let Some(value) = tooltip_fallback { self.writer().text(value); - } else if !subtree_has_content(self.dom, node, self.options.max_depth - depth) - && let Some(label) = crate::content::fallback_text(self.dom, node) + } 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; @@ -532,6 +515,14 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { 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() { @@ -738,40 +729,6 @@ fn subtree_has_content(dom: &D, root: D::NodeId, limit: usize) crate::content::has_readable_content(dom, root, limit) } -fn transparent_math_text( - dom: &D, - root: D::NodeId, - limit: usize, -) -> Option { - let mut pending = vec![(dom.first_child(root), 1)]; - let mut text = String::new(); - let mut crossed_wrapper = false; - while let Some((node, depth)) = pending.pop() { - let Some(node) = node else { - continue; - }; - if depth >= limit { - return None; - } - pending.push((dom.next_sibling(node), depth)); - match dom.node_kind(node) { - NodeKind::Text(value) => text.push_str(value), - NodeKind::Other => crossed_wrapper = true, - NodeKind::Element("span") - if !dom.has_block_layout(node) && !dom.has_text_boundary(node) => - { - crossed_wrapper = true; - pending.push((dom.first_child(node), depth + 1)); - } - _ => return None, - } - } - if !crossed_wrapper { - return None; - } - (crate::math::next_span(&text) == Some((0, text.len()))).then_some(text) -} - 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); diff --git a/moli-html2md/src/math.rs b/moli-html2md/src/math.rs index f571ca15b01..668a29a26c5 100644 --- a/moli-html2md/src/math.rs +++ b/moli-html2md/src/math.rs @@ -4,69 +4,120 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { let bytes = text.as_bytes(); let mut index = 0; + let mut dollar = None; + let mut double_dollar = None; + let mut paren = None; + let mut bracket = None; + let mut candidate = None; while index < bytes.len() { - let (open, close, single_dollar) = if bytes[index] == b'$' && !escaped(bytes, index) { + if bytes[index] == b'$' && !escaped(bytes, index) { if bytes.get(index + 1) == Some(&b'$') { - (2, "$$", false) - } else { - (1, "$", true) - } - } else if bytes[index] == b'\\' - && matches!(bytes.get(index + 1), Some(b'(' | b'[')) - && !escaped(bytes, index) - { - if bytes[index + 1] == b'(' { - (2, "\\)", false) - } else { - (2, "\\]", false) + if let Some(start) = double_dollar.take() { + accept_candidate(text, start, index + 2, 2, false, &mut candidate); + } else { + double_dollar = Some(index); + } + index += 2; + if let Some(ready) = + ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) + { + return Some(ready); + } + continue; } - } else { - index += 1; - continue; - }; - let content_start = index + open; - if single_dollar - && text[content_start..] + if let Some(start) = dollar.take() { + accept_candidate(text, start, index + 1, 1, true, &mut candidate); + } else if text[index + 1..] .chars() .next() - .is_none_or(char::is_whitespace) - { - index = content_start; - continue; - } - let mut search = content_start; - while let Some(relative) = text[search..].find(close) { - let end = search + relative; - search = end + close.len(); - if escaped(bytes, end) { - continue; - } - if end == content_start { - break; - } - if single_dollar - && (text[..end] - .chars() - .next_back() - .is_some_and(char::is_whitespace) - || bytes.get(end + 1).is_some_and(u8::is_ascii_digit)) + .is_some_and(|ch| !ch.is_whitespace()) { - break; + dollar = Some(index); } - // A plain Markdown reader must never reinterpret source text as - // executable HTML merely because it was surrounded by dollars. - if bytes[content_start..end].windows(2).any(|pair| { - pair[0] == b'<' - && (pair[1].is_ascii_alphabetic() || matches!(pair[1], b'/' | b'!' | b'?')) - }) || contains_markdown_resource(&text[content_start..end]) + index += 1; + if let Some(ready) = ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) { - break; + return Some(ready); } - return Some((index, search)); + continue; } - index = search.max(content_start); + if bytes[index] == b'\\' && !escaped(bytes, index) { + 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 candidate); + } + } + Some(b']') => { + if let Some(start) = bracket.take() { + accept_candidate(text, start, index + 2, 2, false, &mut candidate); + } + } + _ => {} + } + if matches!(bytes.get(index + 1), Some(b'(' | b'[' | b')' | b']')) { + index += 2; + if let Some(ready) = + ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) + { + return Some(ready); + } + continue; + } + } + index += 1; + } + candidate +} + +fn ready_candidate( + candidate: Option<(usize, usize)>, + openers: [Option; 4], +) -> Option<(usize, usize)> { + let candidate = candidate?; + openers + .into_iter() + .flatten() + .all(|start| start >= candidate.0) + .then_some(candidate) +} + +fn accept_candidate( + text: &str, + start: usize, + end: usize, + delimiter: usize, + single_dollar: bool, + candidate: &mut Option<(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; + } + if candidate.is_none_or(|(current, _)| start < current) { + *candidate = Some((start, end)); } - None } fn contains_markdown_resource(text: &str) -> bool { diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index 050dbfdc198..d9b523f656b 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -8,43 +8,58 @@ 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) = ["srcset", "data-srcset"].into_iter().find_map(|name| { - dom.attribute(node, name) - .and_then(largest_srcset_candidate) - .filter(|value| safe_url(value, true)) - .map(|value| Cow::Owned(value.to_owned())) - }) { + if let Some(value) = dom + .attribute(node, "srcset") + .and_then(|value| largest_srcset_candidate(value, true)) + { return Some(value); } - direct_source(dom, node, true).map(Cow::Borrowed) + 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 usable = |value: &&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) - }; - let attr = |name| dom.attribute(node, name).map(str::trim).filter(usable); - - let src = attr("src"); - if src.is_some_and(is_explicit_placeholder) { - return attr("data-src") - .or_else(|| attr("data-lazy-src")) - .or_else(|| attr("data-original")) - .or(src); - } - src.or_else(|| attr("data-src")) - .or_else(|| attr("data-lazy-src")) - .or_else(|| attr("data-original")) + }) } fn is_explicit_placeholder(value: &str) -> bool { let lower = value.to_ascii_lowercase(); - if lower.starts_with("data:image/") { - return true; - } let path = lower .split(['?', '#']) .next() @@ -63,7 +78,7 @@ fn is_explicit_placeholder(value: &str) -> bool { ) } -fn largest_srcset_candidate(srcset: &str) -> Option<&str> { +fn largest_srcset_candidate(srcset: &str, image: bool) -> Option> { let bytes = srcset.as_bytes(); let mut offset = 0; let mut best: Option<(&str, f64)> = None; @@ -84,11 +99,19 @@ fn largest_srcset_candidate(srcset: &str) -> Option<&str> { url_end -= 1; } let url = &srcset[url_start..url_end]; + let ended_with_comma = url_end < offset; let descriptor_start = offset; - while offset < bytes.len() && bytes[offset] != b',' { - offset += 1; + if !ended_with_comma { + while offset < bytes.len() && bytes[offset] != b',' { + offset += 1; + } } - let descriptors = srcset[descriptor_start..offset].split_ascii_whitespace(); + let descriptors = if ended_with_comma { + "" + } else { + &srcset[descriptor_start..offset] + } + .split_ascii_whitespace(); let mut score = 1.0; let mut valid = true; let mut seen = false; @@ -117,11 +140,15 @@ fn largest_srcset_candidate(srcset: &str) -> Option<&str> { 0.0 }); } - if valid && !url.is_empty() && best.is_none_or(|(_, current)| score >= current) { + if valid + && !url.is_empty() + && safe_url(url, image) + && best.is_none_or(|(_, current)| score >= current) + { best = Some((url, score)); } } - best.map(|(url, _)| url) + best.map(|(url, _)| Cow::Owned(url.to_owned())) } pub(crate) fn safe_url(value: &str, image: bool) -> bool { diff --git a/moli-html2md/src/writer.rs b/moli-html2md/src/writer.rs index 26a44260b9f..be11930fc4a 100644 --- a/moli-html2md/src/writer.rs +++ b/moli-html2md/src/writer.rs @@ -34,6 +34,10 @@ 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. @@ -70,17 +74,20 @@ impl<'a> Writer<'a> { { 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 @@ -91,8 +98,16 @@ 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 mut remaining = text; + let text = std::mem::take(&mut self.pending_text); + let mut remaining = text.as_str(); while let Some((start, end)) = crate::math::next_span(remaining) { self.plain_text(&remaining[..start]); let math = &remaining[start..end]; @@ -107,6 +122,7 @@ impl<'a> Writer<'a> { } pub(crate) fn inline_html(&mut self, markup: &str) { + self.flush_pending_text(); self.flush_code(); self.prepare_inline('<'); self.output.push_str(markup); @@ -163,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; @@ -190,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() { @@ -219,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("!["); @@ -242,6 +261,7 @@ impl<'a> Writer<'a> { } 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); @@ -251,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); @@ -278,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); @@ -287,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() } diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index 101623238cd..e485a2d74fc 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}; +use std::cell::Cell; use support::{Tree, rendered_html}; fn markdown(html: &str, preformatted_code: bool) -> String { @@ -96,6 +97,32 @@ fn transparent_inline_wrappers_do_not_change_tex_or_activate_markdown_resources( } } +#[test] +fn math_streams_across_transparent_wrappers_in_every_inline_container() { + use pulldown_cmark::{Event, Options as MarkdownOptions, Parser}; + for source in [ + r"

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.

"; @@ -901,6 +928,20 @@ fn resource_only_headings_are_not_dropped() { assert!(alternative.contains("## Safe title"), "{alternative}"); } +#[test] +fn fallback_labels_preserve_all_children_and_remain_literal_text() { + let result = markdown( + "

", + false, + ); + assert!(result.contains("Save"), "{result}"); + assert!(result.contains("Delete"), "{result}"); + assert!(result.contains("# [One](/one)[Two](/two)"), "{result}"); + let rendered = rendered_html(&result); + assert!(!rendered.contains("href=\"/unintended\""), "{rendered}"); + assert!(rendered.contains("[Open](/unintended)"), "{rendered}"); +} + #[test] fn responsive_image_falls_back_from_unusable_lazy_candidates() { for lazy in ["", "javascript:bad() 1x"] { @@ -1104,6 +1145,81 @@ fn responsive_images_preserve_url_commas_and_use_declared_candidates() { 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] diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 20fd6e99d25..f22ab5d5462 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -84,18 +84,12 @@ impl PageVm { "top".to_owned(), "color".to_owned(), "text-shadow".to_owned(), - "animation-name".to_owned(), - "animation-duration".to_owned(), - "animation-fill-mode".to_owned(), ], ); nodes .into_iter() .zip(values) .map(|(node, mut values)| { - let animation_fill_mode = values.pop().unwrap_or_default(); - let animation_duration = values.pop().unwrap_or_default(); - let animation_name = values.pop().unwrap_or_default(); let text_shadow = values.pop().unwrap_or_default(); let foreground = values.pop().unwrap_or_default(); // Preserve the visibility adapter's stable field layout. @@ -127,9 +121,6 @@ impl PageVm { 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(animation_name); - values.push(animation_duration); - values.push(animation_fill_mode); (node, values) }) .collect::>() diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index a377d2637d2..41e67f752d7 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -72,9 +72,15 @@ impl<'a> MarkdownDom<'a> { 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")) + values + .first() + .is_some_and(|value| value == "none") .then(|| Dom::attribute(dom, *node, "id").map(|id| (id, *node))) .flatten() }) @@ -100,7 +106,7 @@ impl<'a> MarkdownDom<'a> { else { continue; }; - let Some(&target) = targets.get(id) else { + let Some(&target) = hidden_targets.get(id) else { continue; }; if Dom::attribute(dom, target, "role").is_some_and(|role| { @@ -142,13 +148,27 @@ impl<'a> MarkdownDom<'a> { .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 current = Some(target); + let mut chain = Vec::new(); + let mut current = dom.parent_node(target); while let Some(node) = current { - disclosure_paths.insert(node); + 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(); @@ -158,7 +178,6 @@ impl<'a> MarkdownDom<'a> { let mut subscripts = HashSet::new(); let mut resolved_urls = HashMap::new(); let mut unchecked_controls = HashSet::new(); - let mut disclosure_regions = HashSet::new(); let mut visibility_restored_regions = HashSet::new(); for (node, values) in styles { let role = Dom::attribute(dom, node, "role").unwrap_or_default(); @@ -190,18 +209,18 @@ impl<'a> MarkdownDom<'a> { Dom::attribute(dom, node, attribute) .is_some_and(|value| !value.trim().is_empty()) }); - let disclosure_root = role.eq_ignore_ascii_case("tabpanel") + 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 = disclosure_root - || dom - .parent_node(node) - .is_some_and(|parent| disclosure_regions.contains(&parent)); - if disclosure { - disclosure_regions.insert(node); + 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); } - let preserves_disclosure = disclosure || disclosure_paths.contains(&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. @@ -240,22 +259,23 @@ impl<'a> MarkdownDom<'a> { if visibility_restored { visibility_restored_regions.insert(node); } - let opacity_revealed_by_animation = animation_reveals_content(&values); if ((values.first().is_some_and(|value| value == "none") || values .get(2) .is_some_and(|value| value.parse::() == Ok(0.0)) && !lazy_media - && !opacity_revealed_by_animation && !document_root) - && !preserves_disclosure) + && !disclosure_root + && !disclosure_path) || uninitialized_template || tracking_pixel - || (zero_contrast_leaf && !preserves_disclosure) + || (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)) - && !preserves_disclosure + && !disclosure_root + && !disclosure_path { suppressed.insert(node); } @@ -335,7 +355,8 @@ impl<'a> MarkdownDom<'a> { if values .get(1) .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) - && !preserves_disclosure + && !disclosure_root + && !disclosure_path && (!document_visibility_is_hidden || dom .parent_node(node) @@ -369,33 +390,6 @@ impl<'a> MarkdownDom<'a> { } } -fn animation_reveals_content(values: &[String]) -> bool { - let named = values.get(14).is_some_and(|names| { - names - .split(',') - .any(|name| !matches!(name.trim(), "" | "none")) - }); - let has_duration = values.get(15).is_some_and(|durations| { - durations.split(',').any(|duration| { - let duration = duration.trim(); - duration - .strip_suffix("ms") - .and_then(|value| value.trim().parse::().ok()) - .is_some_and(|value| value > 0.0) - || duration - .strip_suffix('s') - .and_then(|value| value.trim().parse::().ok()) - .is_some_and(|value| value > 0.0) - }) - }); - let retains_final_frame = values.get(16).is_some_and(|modes| { - modes - .split(',') - .any(|mode| matches!(mode.trim(), "forwards" | "both")) - }); - named && has_duration && retains_final_frame -} - fn target_is_disclosure( dom: &D, targets: &HashMap<&str, D::NodeId>, @@ -416,25 +410,42 @@ fn px(value: &str) -> Option { fn resolve_srcset(base_url: &Url, value: &str) -> Option { let mut resolved = Vec::new(); - let mut remaining = value.trim(); - while !remaining.is_empty() { - let split = remaining - .find(char::is_whitespace) - .unwrap_or(remaining.len()); - let source = &remaining[..split]; - remaining = remaining[split..].trim_start(); - let (descriptor, rest) = if let Some(end) = remaining.find(',') { - (remaining[..end].trim(), remaining[end + 1..].trim_start()) + let bytes = value.as_bytes(); + let mut offset = 0; + while offset < bytes.len() { + while offset < bytes.len() && (bytes[offset].is_ascii_whitespace() || bytes[offset] == b',') + { + offset += 1; + } + let start = offset; + while offset < bytes.len() && !bytes[offset].is_ascii_whitespace() { + offset += 1; + } + if start == offset { + break; + } + let mut end = offset; + while end > start && bytes[end - 1] == b',' { + end -= 1; + } + let ended_with_comma = end < offset; + let descriptor_start = offset; + if !ended_with_comma { + while offset < bytes.len() && bytes[offset] != b',' { + offset += 1; + } + } + let descriptor = if ended_with_comma { + "" } else { - (remaining.trim(), "") + value[descriptor_start..offset].trim() }; - let url = base_url.join(source.trim_end_matches(',')).ok()?; + let url = base_url.join(&value[start..end]).ok()?; resolved.push(if descriptor.is_empty() { url.to_string() } else { format!("{url} {descriptor}") }); - remaining = rest; } (!resolved.is_empty()).then(|| resolved.join(", ")) } 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 index 24123fc9737..15500cf3836 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -41,6 +41,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

Animated hidden text

Animated revealed text

+

Animated rotation text

ActiveReviewed

Mass 2.4 × 10−17 J; mn

@@ -63,7 +64,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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)"] { + 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", "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}"); @@ -71,7 +72,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Animated hidden text", "Animated revealed text", "Animated rotation text", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { assert!(!output.contains(omitted), "leaked {omitted}: {output}"); } } @@ -123,11 +124,17 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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 = ` From d69da759fce12e4089d22fb08351c0910b8c5f32 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:41:28 +0800 Subject: [PATCH 12/21] fix(content): preserve proven interactive disclosures --- moli-html2md/src/form.rs | 9 + moli-html2md/src/html_table.rs | 8 + moli-html2md/src/machine.rs | 6 + moli-html2md/src/math.rs | 43 ++- moli-html2md/tests/regressions.rs | 17 +- .../src/runtime/page_dump/visibility.rs | 363 +++++++++++++++++- .../runtime/page_vm/tests/markdown_dump.rs | 26 +- 7 files changed, 454 insertions(+), 18 deletions(-) diff --git a/moli-html2md/src/form.rs b/moli-html2md/src/form.rs index 418e5fc5725..857b56d0d76 100644 --- a/moli-html2md/src/form.rs +++ b/moli-html2md/src/form.rs @@ -41,3 +41,12 @@ pub(crate) fn input_text<'a, D: Dom + ?Sized>(dom: &'a D, node: D::NodeId) -> Op }); value.map(Cow::Borrowed) } + +pub(crate) fn textarea_text<'a, D: Dom + ?Sized>( + dom: &'a D, + node: D::NodeId, +) -> Option> { + dom.attribute(node, "value") + .filter(|value| !value.is_empty()) + .map(Cow::Borrowed) +} diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs index dbcc9ecb1bb..f08f59ec3b1 100644 --- a/moli-html2md/src/html_table.rs +++ b/moli-html2md/src/html_table.rs @@ -145,6 +145,13 @@ pub(crate) fn render( 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; @@ -256,6 +263,7 @@ fn allowed(tag: &str) -> bool { | "optgroup" | "option" | "button" + | "textarea" | "p" | "div" | "span" diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs index d1873b819ca..9131672da17 100644 --- a/moli-html2md/src/machine.rs +++ b/moli-html2md/src/machine.rs @@ -339,6 +339,12 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> { } 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; diff --git a/moli-html2md/src/math.rs b/moli-html2md/src/math.rs index 668a29a26c5..c6bd6ad137b 100644 --- a/moli-html2md/src/math.rs +++ b/moli-html2md/src/math.rs @@ -2,15 +2,22 @@ /// Dollar boundaries follow the usual non-space/non-digit rules, so prices do /// not consume the prose between two currency amounts. pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { + let mut steps = 0; + next_span_counted(text, &mut steps) +} + +fn next_span_counted(text: &str, steps: &mut usize) -> Option<(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 candidate = None; while index < bytes.len() { - if bytes[index] == b'$' && !escaped(bytes, index) { + *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 candidate); @@ -18,6 +25,7 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { double_dollar = Some(index); } index += 2; + backslashes = 0; if let Some(ready) = ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) { @@ -35,13 +43,14 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { dollar = Some(index); } index += 1; + backslashes = 0; if let Some(ready) = ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) { return Some(ready); } continue; } - if bytes[index] == b'\\' && !escaped(bytes, index) { + if bytes[index] == b'\\' && backslashes % 2 == 0 { match bytes.get(index + 1) { Some(b'(') => { paren.get_or_insert(index); @@ -63,6 +72,7 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { } if matches!(bytes.get(index + 1), Some(b'(' | b'[' | b')' | b']')) { index += 2; + backslashes = 0; if let Some(ready) = ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) { @@ -71,6 +81,11 @@ pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { continue; } } + if bytes[index] == b'\\' { + backslashes += 1; + } else { + backslashes = 0; + } index += 1; } candidate @@ -124,12 +139,20 @@ fn contains_markdown_resource(text: &str) -> bool { text.contains("](") || text.contains("][") || text.contains("![[") } -fn escaped(bytes: &[u8], index: usize) -> bool { - bytes[..index] - .iter() - .rev() - .take_while(|&&ch| ch == b'\\') - .count() - % 2 - == 1 +#[cfg(test)] +mod tests { + use super::next_span_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 _ = next_span_counted(&text, &mut steps); + assert!( + steps <= text.len(), + "{steps} steps for {} bytes", + text.len() + ); + } + } } diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index e485a2d74fc..7de3d571df0 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -1064,7 +1064,7 @@ fn block_content_inside_heading_keeps_its_own_boundary() { #[test] fn form_values_preserve_current_readable_state_without_secrets() { - let source = "
PeriodMonSun
Morning

"; + let source = "
PeriodMonSun
Morning

"; let result = rendered_html(&markdown(source, false)); for value in [ "Morning", @@ -1075,6 +1075,7 @@ fn form_values_preserve_current_readable_state_without_secrets() { "Search", "Map button", "Password", + "Notes", ] { assert!(result.contains(value), "missing {value}: {result}"); } @@ -1096,6 +1097,20 @@ fn unsafe_resource_urls_keep_labels_without_emitting_active_links() { 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}
"), + ] { + 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
"; diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 41e67f752d7..881b951d853 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -85,6 +85,7 @@ impl<'a> MarkdownDom<'a> { .flatten() }) .collect(); + let visible_handler_functions = visible_handler_functions(dom); for (node, _) in &styles { if (Dom::attribute(dom, *node, "aria-expanded").is_some() || Dom::attribute(dom, *node, "role") @@ -97,6 +98,19 @@ impl<'a> MarkdownDom<'a> { .filter(|id| target_is_disclosure(dom, &targets, id)), ); } + for attribute_name in dom.get_attribute_names(*node).unwrap_or_default() { + if !attribute_name.starts_with("on") { + continue; + } + let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else { + continue; + }; + for target in inline_disclosure_targets(handler, &visible_handler_functions) { + if target_is_disclosure(dom, &targets, target) { + disclosures.insert(target); + } + } + } // 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. @@ -181,19 +195,23 @@ impl<'a> MarkdownDom<'a> { let mut visibility_restored_regions = HashSet::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")) - && let Some(element) = dom.node(node).and_then(|node| node.as_element()) + 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 element.checked() { + 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 { + } else if matches!(Dom::node_kind(dom, node), NodeKind::Element("input")) { unchecked_controls.insert(node); } } @@ -404,6 +422,343 @@ fn target_is_disclosure( }) } +fn inline_disclosure_targets<'a>( + value: &'a str, + visible_functions: &HashSet, +) -> Vec<&'a str> { + let mut result = Vec::new(); + for (marker, fragment) in [ + ("document.getElementById", false), + ("document.querySelector", true), + ] { + for offset in code_marker_offsets(value, marker) { + let remaining = &value[offset + marker.len()..]; + let Some((literal, end)) = quoted_call_argument(remaining) else { + continue; + }; + let Some(target) = literal + .strip_prefix('#') + .or_else(|| (!fragment).then_some(literal)) + .filter(|target| !target.is_empty()) + else { + continue; + }; + let direct_mutation = sets_display_visible(&remaining[end..], None); + let named_mutation = enclosing_function_name(&value[..offset]) + .is_some_and(|name| visible_functions.contains(name)); + if direct_mutation || named_mutation { + result.push(target); + } + } + } + result +} + +fn visible_handler_functions(dom: &NativeDom) -> HashSet { + let mut result = HashSet::new(); + let mut pending = vec![dom.document_node_id()]; + while let Some(node) = pending.pop() { + if !matches!(Dom::node_kind(dom, node), NodeKind::Element("script")) { + pending.extend(dom.child_ids(node)); + continue; + } + let source = descendant_text(dom, node); + for offset in code_marker_offsets(&source, "function") { + let signature = &source[offset + "function".len()..]; + let Some((name, parameter, body)) = function_parts(signature) else { + continue; + }; + if function_sets_parameter_visible(body, parameter) { + result.insert(name.to_owned()); + } + } + } + result +} + +fn function_parts(source: &str) -> Option<(&str, &str, &str)> { + let source = source.trim_start(); + let name_end = source.find(|character: char| !is_identifier(character))?; + let name = &source[..name_end]; + if name.is_empty() { + return None; + } + let parameters = source[name_end..].trim_start().strip_prefix('(')?; + let close = parameters.find(')')?; + let parameter = parameters[..close].trim(); + if parameter.is_empty() || parameter.contains(',') || !parameter.chars().all(is_identifier) { + return None; + } + let rest = parameters[close + 1..].trim_start(); + let body_start = rest.find('{')?; + let body_end = matching_delimiter(rest, body_start, '{', '}')?; + Some((name, parameter, &rest[body_start + 1..body_end])) +} + +fn function_sets_parameter_visible(body: &str, parameter: &str) -> bool { + for offset in code_marker_offsets(body, ".style.display") { + let owner = body[..offset] + .trim_end() + .rsplit_once(|character: char| !is_identifier(character)) + .map_or(body[..offset].trim_end(), |(_, owner)| owner); + if owner.is_empty() + || !sets_display_visible(&body[offset + ".style.display".len()..], Some("")) + { + continue; + } + if owner == parameter || alias_depends_on_parameter(&body[..offset], owner, parameter) { + return true; + } + } + false +} + +fn alias_depends_on_parameter(prefix: &str, owner: &str, parameter: &str) -> bool { + let Some(offset) = code_marker_offsets(prefix, owner) + .into_iter() + .rev() + .find(|offset| { + let before = prefix[..*offset].chars().next_back(); + let after = prefix[*offset + owner.len()..].chars().next(); + before.is_none_or(|character| !is_identifier(character)) + && after.is_none_or(|character| !is_identifier(character)) + && prefix[*offset + owner.len()..] + .trim_start() + .starts_with('=') + }) + else { + return false; + }; + let assignment = prefix[offset + owner.len()..].trim_start(); + let Some(right) = assignment.strip_prefix('=') else { + return false; + }; + let right = right.split_once(';').map_or(right, |(right, _)| right); + contains_identifier(right, parameter) +} + +fn contains_identifier(value: &str, identifier: &str) -> bool { + code_marker_offsets(value, identifier) + .into_iter() + .any(|offset| { + let before = value[..offset].chars().next_back(); + let after = value[offset + identifier.len()..].chars().next(); + before.is_none_or(|character| !is_identifier(character)) + && after.is_none_or(|character| !is_identifier(character)) + }) +} + +fn enclosing_function_name(value: &str) -> Option<&str> { + let value = value.trim_end(); + let value = value.strip_suffix('(')?.trim_end(); + let start = value + .rfind(|character: char| !is_identifier(character)) + .map_or(0, |offset| offset + 1); + let name = &value[start..]; + (!name.is_empty()).then_some(name) +} + +fn quoted_call_argument(value: &str) -> Option<(&str, usize)> { + let leading = value.len() - value.trim_start().len(); + let value = value.trim_start().strip_prefix('(')?; + let after_open = value.len() - value.trim_start().len(); + let value = value.trim_start(); + let quote = value + .chars() + .next() + .filter(|quote| matches!(quote, '\'' | '"'))?; + let literal = &value[quote.len_utf8()..]; + let end = literal.find(quote)?; + let after_literal = literal[end + quote.len_utf8()..].trim_start(); + if !after_literal.starts_with(')') { + return None; + } + let consumed = leading + + 1 + + after_open + + quote.len_utf8() + + end + + quote.len_utf8() + + (literal[end + quote.len_utf8()..].len() - after_literal.len()) + + 1; + Some((&literal[..end], consumed)) +} + +fn sets_display_visible(value: &str, display_already_consumed: Option<&str>) -> bool { + let value = if display_already_consumed.is_some() { + value + } else { + let Some(value) = value.trim_start().strip_prefix(".style.display") else { + return false; + }; + value + }; + let Some(value) = value.trim_start().strip_prefix('=') else { + return false; + }; + let value = value.trim_start(); + let Some(quote) = value + .chars() + .next() + .filter(|quote| matches!(quote, '\'' | '"')) + else { + return false; + }; + let literal = &value[quote.len_utf8()..]; + let Some(end) = literal.find(quote) else { + return false; + }; + matches!( + literal[..end].trim(), + "" | "block" + | "inline" + | "inline-block" + | "flex" + | "inline-flex" + | "grid" + | "inline-grid" + | "list-item" + | "table" + | "table-row" + | "table-cell" + ) +} + +fn code_marker_offsets(value: &str, marker: &str) -> Vec { + let mut result = Vec::new(); + let mut offset = 0; + let mut quote = None; + let mut escaped = false; + let mut line_comment = false; + let mut block_comment = false; + while offset < value.len() { + let tail = &value[offset..]; + if line_comment { + if tail.starts_with('\n') { + line_comment = false; + } + } else if block_comment { + if tail.starts_with("*/") { + block_comment = false; + offset += 2; + continue; + } + } else if let Some(delimiter) = quote { + let character = tail.chars().next().expect("offset is within value"); + if escaped { + escaped = false; + } else if character == '\\' { + escaped = true; + } else if character == delimiter { + quote = None; + } + } else if tail.starts_with("//") { + line_comment = true; + offset += 2; + continue; + } else if tail.starts_with("/*") { + block_comment = true; + offset += 2; + continue; + } else { + let character = tail.chars().next().expect("offset is within value"); + if matches!(character, '\'' | '"' | '`') { + quote = Some(character); + } else if tail.starts_with(marker) { + result.push(offset); + offset += marker.len(); + continue; + } + } + offset += tail + .chars() + .next() + .expect("offset is within value") + .len_utf8(); + } + result +} + +fn matching_delimiter(value: &str, start: usize, open: char, close: char) -> Option { + let mut depth = 0; + let mut quote = None; + let mut escaped = false; + let mut line_comment = false; + let mut block_comment = false; + let mut offset = start; + while offset < value.len() { + let tail = &value[offset..]; + if line_comment { + if tail.starts_with('\n') { + line_comment = false; + } + } else if block_comment { + if tail.starts_with("*/") { + block_comment = false; + offset += 2; + continue; + } + } else if let Some(delimiter) = quote { + let character = tail.chars().next().expect("offset is within value"); + if escaped { + escaped = false; + } else if character == '\\' { + escaped = true; + } else if character == delimiter { + quote = None; + } + } else if tail.starts_with("//") { + line_comment = true; + offset += 2; + continue; + } else if tail.starts_with("/*") { + block_comment = true; + offset += 2; + continue; + } else { + let character = tail.chars().next().expect("offset is within value"); + if matches!(character, '\'' | '"' | '`') { + quote = Some(character); + } else if character == open { + depth += 1; + } else if character == close { + depth -= 1; + if depth == 0 { + return Some(offset); + } + } + } + offset += tail + .chars() + .next() + .expect("offset is within value") + .len_utf8(); + } + None +} + +fn is_identifier(character: char) -> bool { + character == '_' || character == '$' || character.is_ascii_alphanumeric() +} + +fn descendant_text(dom: &NativeDom, root: NativeNodeId) -> String { + let mut pending = vec![root]; + let mut result = String::new(); + while let Some(node) = pending.pop() { + if let NodeKind::Text(value) = Dom::node_kind(dom, node) { + result.push_str(value); + } + 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 +} + fn px(value: &str) -> Option { value.strip_suffix("px")?.trim().parse().ok() } 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 index 15500cf3836..4de83bb0a27 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -100,6 +100,14 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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

@@ -147,14 +155,23 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { - `; + + + + + + + `; "##).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("Query-selected history"), "{related}"); + assert!(related.contains("Function-revealed records"), "{related}"); + assert!(!related.contains("Function-read hidden state"), "{related}"); + assert!(!related.contains("Unrelated mutation hidden state"), "{related}"); page.vm_mut().eval(r#" document.body.innerHTML = `

Visible gradient text

@@ -179,14 +196,17 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { assert!(composite.contains("full conclusion"), "{composite}"); assert!(!composite.contains("A detailed review..."), "{composite}"); page.vm_mut().eval(r#" - document.body.innerHTML = ''; + 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 = ` Responsive From 0ac34b9c476e883bd51bc248121d18c87c3a4227 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 15:13:13 +0800 Subject: [PATCH 13/21] fix(renderer): retain bounded fade-in content --- moli-renderer-v8/src/runtime/page_dump.rs | 53 +++++-- .../src/runtime/page_dump/visibility.rs | 140 ++++++++++++++++++ .../runtime/page_vm/tests/markdown_dump.rs | 12 +- moli-renderer-v8/src/script_vm/layout.rs | 20 +++ 4 files changed, 211 insertions(+), 14 deletions(-) diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index f22ab5d5462..50b056badf4 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -4,7 +4,7 @@ use crate::runtime::page_surface::{ }; use moli_html2md::{Dom, NodeKind}; use moli_page_types::MAX_DOM_OUTPUT_TREE_DEPTH; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use super::page_vm::PageVm; @@ -15,7 +15,9 @@ impl PageVm { let markdown_base_url = (options.format == RendererPageDumpFormat::Markdown) .then(|| self.vm().document_runtime.dom_host().document_base_url()) .flatten(); - let styles = if options.format == RendererPageDumpFormat::Markdown { + let (styles, final_opacity_animations) = 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); @@ -84,12 +86,26 @@ impl PageVm { "top".to_owned(), "color".to_owned(), "text-shadow".to_owned(), + "animation-name".to_owned(), + "animation-duration".to_owned(), + "animation-fill-mode".to_owned(), + "animation-delay".to_owned(), + "animation-iteration-count".to_owned(), + "animation-direction".to_owned(), + "animation-play-state".to_owned(), ], ); - nodes + let styles = nodes .into_iter() .zip(values) .map(|(node, mut values)| { + let animation_play_state = values.pop().unwrap_or_default(); + let animation_direction = values.pop().unwrap_or_default(); + let animation_iteration_count = values.pop().unwrap_or_default(); + let animation_delay = values.pop().unwrap_or_default(); + let animation_fill_mode = values.pop().unwrap_or_default(); + let animation_duration = values.pop().unwrap_or_default(); + let animation_name = values.pop().unwrap_or_default(); let text_shadow = values.pop().unwrap_or_default(); let foreground = values.pop().unwrap_or_default(); // Preserve the visibility adapter's stable field layout. @@ -121,11 +137,23 @@ impl PageVm { 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(animation_name); + values.push(animation_duration); + values.push(animation_fill_mode); + values.push(animation_delay); + values.push(animation_iteration_count); + values.push(animation_direction); + values.push(animation_play_state); (node, values) }) - .collect::>() + .collect::>(); + let stylesheet_texts = self.vm().active_stylesheet_texts_for_document_snapshot(); + let final_opacity_animations = visibility::final_opacity_animation_names( + stylesheet_texts.iter().map(String::as_str), + ); + (styles, final_opacity_animations) } else { - Vec::new() + (Vec::new(), HashSet::new()) }; if options.format == RendererPageDumpFormat::Markdown && !options.with_base @@ -136,6 +164,7 @@ impl PageVm { self.vm().document_runtime.dom_host().dom(), styles, markdown_base_url.as_ref(), + final_opacity_animations, ); } let mut dom = self.vm().document_runtime.dom_host().dom().clone(); @@ -156,9 +185,12 @@ impl PageVm { match options.format { RendererPageDumpFormat::Html => dom.serialize_document(), - RendererPageDumpFormat::Markdown => { - render_markdown_document_with_styles(&dom, styles, markdown_base_url.as_ref()) - } + RendererPageDumpFormat::Markdown => render_markdown_document_with_styles( + &dom, + styles, + markdown_base_url.as_ref(), + final_opacity_animations, + ), } } @@ -308,16 +340,17 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String { - render_markdown_document_with_styles(dom, Vec::new(), None) + 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_animations: HashSet, ) -> String { let root = dom.body_node_id().unwrap_or(dom.document_node_id()); - let visible = visibility::MarkdownDom::new(dom, styles, base_url); + let visible = visibility::MarkdownDom::new(dom, styles, base_url, final_opacity_animations); moli_html2md::Converter::new(moli_html2md::Options { max_depth: MAX_DOM_OUTPUT_TREE_DEPTH, default_code_language: Some("text".to_owned()), diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 881b951d853..0aaa6e1b007 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -26,6 +26,7 @@ impl<'a> MarkdownDom<'a> { dom: &'a NativeDom, styles: impl IntoIterator)>, base_url: Option<&Url>, + final_opacity_animations: HashSet, ) -> Self { let styles: Vec<_> = styles.into_iter().collect(); let document_element = dom.document_element_node_id(); @@ -277,11 +278,14 @@ impl<'a> MarkdownDom<'a> { if visibility_restored { visibility_restored_regions.insert(node); } + let has_bounded_final_opacity = + has_bounded_final_opacity(&values, &final_opacity_animations); if ((values.first().is_some_and(|value| value == "none") || values .get(2) .is_some_and(|value| value.parse::() == Ok(0.0)) && !lazy_media + && !has_bounded_final_opacity && !document_root) && !disclosure_root && !disclosure_path) @@ -408,6 +412,142 @@ impl<'a> MarkdownDom<'a> { } } +fn has_bounded_final_opacity( + values: &[String], + final_opacity_animations: &HashSet, +) -> bool { + let names: Vec<_> = values + .get(14) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + let durations: Vec<_> = values + .get(15) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + let fill_modes: Vec<_> = values + .get(16) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + let delays: Vec<_> = values + .get(17) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + let iteration_counts: Vec<_> = values + .get(18) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + let directions: Vec<_> = values + .get(19) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + let play_states: Vec<_> = values + .get(20) + .map(|value| value.split(',').map(str::trim).collect()) + .unwrap_or_default(); + names.iter().enumerate().any(|(index, name)| { + final_opacity_animations.contains(*name) + && !durations.is_empty() + && animation_duration_is_positive(durations[index % durations.len()]) + && !fill_modes.is_empty() + && matches!(fill_modes[index % fill_modes.len()], "forwards" | "both") + && !delays.is_empty() + && animation_time_seconds(delays[index % delays.len()]) + .is_some_and(|delay| delay <= 0.0) + && !iteration_counts.is_empty() + && iteration_counts[index % iteration_counts.len()].parse::() == Ok(1.0) + && !directions.is_empty() + && directions[index % directions.len()] == "normal" + && !play_states.is_empty() + && play_states[index % play_states.len()] == "running" + }) +} + +fn animation_duration_is_positive(duration: &str) -> bool { + animation_time_seconds(duration).is_some_and(|duration| duration > 0.0) +} + +fn animation_time_seconds(value: &str) -> Option { + value + .strip_suffix("ms") + .and_then(|value| value.trim().parse::().ok()) + .map(|value| value / 1000.0) + .or_else(|| { + value + .strip_suffix('s') + .and_then(|value| value.trim().parse::().ok()) + }) +} + +/// Return only animations whose declared final keyframe paints a nonzero +/// opacity. The caller still requires a finite, forward, running animation +/// before using that final authored state for the static document snapshot. +pub(super) fn final_opacity_animation_names<'a>( + stylesheets: impl IntoIterator, +) -> HashSet { + let mut result = HashSet::new(); + for source in stylesheets { + let folded = source.to_ascii_lowercase(); + for offset in code_marker_offsets(&folded, "@keyframes") { + let Some(relative_open) = source[offset..].find('{') else { + continue; + }; + let open = offset + relative_open; + let Some(close) = matching_delimiter(source, open, '{', '}') else { + continue; + }; + let Some(rule) = + moli_css_parse::parse_keyframes_rule_view_with_stylo(&source[offset..=close]) + else { + continue; + }; + let Some(canonical_open) = rule.css_text.find('{') else { + continue; + }; + let Some(canonical_close) = + matching_delimiter(&rule.css_text, canonical_open, '{', '}') + else { + continue; + }; + if final_keyframe_reveals(&rule.css_text[canonical_open + 1..canonical_close]) { + result.insert(rule.name); + } + } + } + result +} + +fn final_keyframe_reveals(body: &str) -> bool { + let mut offset = 0; + while let Some(relative_open) = body[offset..].find('{') { + let open = offset + relative_open; + let selector = body[offset..open].trim(); + let Some(close) = matching_delimiter(body, open, '{', '}') else { + return false; + }; + let is_final = selector + .split(',') + .map(str::trim) + .any(|value| matches!(value, "to" | "100%" | "100.0%")); + if is_final { + for declaration in body[open + 1..close].split(';') { + let Some((name, value)) = declaration.split_once(':') else { + continue; + }; + if name.trim().eq_ignore_ascii_case("opacity") + && value + .trim() + .parse::() + .is_ok_and(|opacity| opacity > 0.0) + { + return true; + } + } + } + offset = close + 1; + } + false +} + fn target_is_disclosure( dom: &D, targets: &HashMap<&str, D::NodeId>, 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 index 4de83bb0a27..cc5635b09ab 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -39,9 +39,13 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

White on black stays visible

Faded text

Animated hidden text

- -

Animated revealed text

+ +

Animated revealed text

+

Animated rotation text

+

Zero-duration reveal text

+

Repeating reveal text

+

Reverse reveal text

ActiveReviewed

Mass 2.4 × 10−17 J; mn

@@ -64,7 +68,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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", "Visible value 8", "CSS override VISIBLE", "Stylesheet override ALSO VISIBLE", "White on black stays visible", "![Article photo](https://example.test/article.jpg)"] { + 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}"); @@ -72,7 +76,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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", "Animated revealed text", "Animated rotation text", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { + for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Animated hidden 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}"); } } diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs index 8e584f55331..28794119684 100644 --- a/moli-renderer-v8/src/script_vm/layout.rs +++ b/moli-renderer-v8/src/script_vm/layout.rs @@ -70,6 +70,26 @@ impl ScriptVm { read(host.dom_host(), &mut input) } + pub(crate) fn active_stylesheet_texts_for_document_snapshot(&self) -> Vec { + let host = self._context_host.borrow(); + let document = host.document_handle(); + host.retained_stylesheet_query_snapshot_for_document(document) + .map(|snapshot| { + snapshot + .document_stylesheet_sources + .iter() + .chain( + snapshot + .shadow_stylesheet_sources + .iter() + .flat_map(|(_, sources)| sources.iter()), + ) + .map(|source| source.serialized_css_text().to_string()) + .collect() + }) + .unwrap_or_default() + } + pub(crate) fn sync_live_document_style_sources(&mut self) { let document = self.document_runtime.document_handle(); self._context_host From 3be2093ca5aac47146dea490e7fd6d10c0da7620 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 18:24:13 +0800 Subject: [PATCH 14/21] fix(content): close semantic boundary regressions --- moli-html2md/src/content.rs | 10 + moli-html2md/src/form.rs | 4 +- moli-html2md/src/html_table.rs | 14 +- moli-html2md/src/lib.rs | 3 + moli-html2md/src/math.rs | 78 ++-- moli-html2md/src/media.rs | 151 +++++-- moli-html2md/src/writer.rs | 12 +- moli-html2md/tests/regressions.rs | 58 +++ moli-renderer-v8/src/runtime/page_dump.rs | 5 + .../src/runtime/page_dump/visibility.rs | 390 ++++-------------- .../runtime/page_vm/tests/markdown_dump.rs | 42 +- 11 files changed, 365 insertions(+), 402 deletions(-) diff --git a/moli-html2md/src/content.rs b/moli-html2md/src/content.rs index e26ae6dcd6e..4ebce0590f9 100644 --- a/moli-html2md/src/content.rs +++ b/moli-html2md/src/content.rs @@ -28,6 +28,16 @@ pub(crate) fn has_readable_content( 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, _ => {} } diff --git a/moli-html2md/src/form.rs b/moli-html2md/src/form.rs index 857b56d0d76..6beb52aa2fe 100644 --- a/moli-html2md/src/form.rs +++ b/moli-html2md/src/form.rs @@ -46,7 +46,5 @@ pub(crate) fn textarea_text<'a, D: Dom + ?Sized>( dom: &'a D, node: D::NodeId, ) -> Option> { - dom.attribute(node, "value") - .filter(|value| !value.is_empty()) - .map(Cow::Borrowed) + dom.attribute(node, "value").map(Cow::Borrowed) } diff --git a/moli-html2md/src/html_table.rs b/moli-html2md/src/html_table.rs index f08f59ec3b1..1dbfec6bd8f 100644 --- a/moli-html2md/src/html_table.rs +++ b/moli-html2md/src/html_table.rs @@ -126,7 +126,7 @@ pub(crate) fn render( && !allowed(tag) { for id in anchor_targets.targets(dom, node) { - if emitted_anchors.insert(id) { + if emitted_anchors.insert(id.to_owned()) { output.push_str(&crate::anchors::markup(id)); } } @@ -138,6 +138,11 @@ pub(crate) fn render( ) | 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") => { @@ -223,6 +228,13 @@ pub(crate) fn render( 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, diff --git a/moli-html2md/src/lib.rs b/moli-html2md/src/lib.rs index fb21db22823..e6470ba79c6 100644 --- a/moli-html2md/src/lib.rs +++ b/moli-html2md/src/lib.rs @@ -18,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/math.rs b/moli-html2md/src/math.rs index c6bd6ad137b..9a35da5cbf2 100644 --- a/moli-html2md/src/math.rs +++ b/moli-html2md/src/math.rs @@ -1,12 +1,12 @@ /// Locate a complete author-supplied TeX span before ordinary Markdown escaping. /// Dollar boundaries follow the usual non-space/non-digit rules, so prices do /// not consume the prose between two currency amounts. -pub(crate) fn next_span(text: &str) -> Option<(usize, usize)> { +pub(crate) fn spans(text: &str) -> Vec<(usize, usize)> { let mut steps = 0; - next_span_counted(text, &mut steps) + spans_counted(text, &mut steps) } -fn next_span_counted(text: &str, steps: &mut usize) -> Option<(usize, usize)> { +fn spans_counted(text: &str, steps: &mut usize) -> Vec<(usize, usize)> { let bytes = text.as_bytes(); let mut index = 0; let mut backslashes = 0; @@ -14,27 +14,22 @@ fn next_span_counted(text: &str, steps: &mut usize) -> Option<(usize, usize)> { let mut double_dollar = None; let mut paren = None; let mut bracket = None; - let mut candidate = 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 candidate); + accept_candidate(text, start, index + 2, 2, false, &mut candidates); } else { double_dollar = Some(index); } index += 2; backslashes = 0; - if let Some(ready) = - ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) - { - return Some(ready); - } continue; } if let Some(start) = dollar.take() { - accept_candidate(text, start, index + 1, 1, true, &mut candidate); + accept_candidate(text, start, index + 1, 1, true, &mut candidates); } else if text[index + 1..] .chars() .next() @@ -44,10 +39,6 @@ fn next_span_counted(text: &str, steps: &mut usize) -> Option<(usize, usize)> { } index += 1; backslashes = 0; - if let Some(ready) = ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) - { - return Some(ready); - } continue; } if bytes[index] == b'\\' && backslashes % 2 == 0 { @@ -60,12 +51,12 @@ fn next_span_counted(text: &str, steps: &mut usize) -> Option<(usize, usize)> { } Some(b')') => { if let Some(start) = paren.take() { - accept_candidate(text, start, index + 2, 2, false, &mut candidate); + 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 candidate); + accept_candidate(text, start, index + 2, 2, false, &mut candidates); } } _ => {} @@ -73,11 +64,6 @@ fn next_span_counted(text: &str, steps: &mut usize) -> Option<(usize, usize)> { if matches!(bytes.get(index + 1), Some(b'(' | b'[' | b')' | b']')) { index += 2; backslashes = 0; - if let Some(ready) = - ready_candidate(candidate, [dollar, double_dollar, paren, bracket]) - { - return Some(ready); - } continue; } } @@ -88,19 +74,16 @@ fn next_span_counted(text: &str, steps: &mut usize) -> Option<(usize, usize)> { } index += 1; } - candidate -} - -fn ready_candidate( - candidate: Option<(usize, usize)>, - openers: [Option; 4], -) -> Option<(usize, usize)> { - let candidate = candidate?; - openers - .into_iter() - .flatten() - .all(|start| start >= candidate.0) - .then_some(candidate) + 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( @@ -109,7 +92,7 @@ fn accept_candidate( end: usize, delimiter: usize, single_dollar: bool, - candidate: &mut Option<(usize, usize)>, + candidates: &mut Vec<(usize, usize)>, ) { let content_start = start + delimiter; let content_end = end - delimiter; @@ -130,9 +113,7 @@ fn accept_candidate( { return; } - if candidate.is_none_or(|(current, _)| start < current) { - *candidate = Some((start, end)); - } + candidates.push((start, end)); } fn contains_markdown_resource(text: &str) -> bool { @@ -141,13 +122,28 @@ fn contains_markdown_resource(text: &str) -> bool { #[cfg(test)] mod tests { - use super::next_span_counted; + 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 _ = next_span_counted(&text, &mut steps); + 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", diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index d9b523f656b..2d646c2430c 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -78,10 +78,19 @@ fn is_explicit_placeholder(value: &str) -> bool { ) } -fn largest_srcset_candidate(srcset: &str, image: bool) -> Option> { +#[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 best: Option<(&str, f64)> = None; + let mut candidates = Vec::new(); while offset < bytes.len() { while offset < bytes.len() && (bytes[offset].is_ascii_whitespace() || bytes[offset] == b',') { @@ -100,55 +109,111 @@ fn largest_srcset_candidate(srcset: &str, image: bool) -> Option> { } let url = &srcset[url_start..url_end]; let ended_with_comma = url_end < offset; - let descriptor_start = offset; - if !ended_with_comma { - while offset < bytes.len() && bytes[offset] != b',' { - offset += 1; + if ended_with_comma { + if !url.is_empty() { + candidates.push(SrcsetCandidate { + url, + descriptor: "", + score: 1.0, + }); } + continue; } - let descriptors = if ended_with_comma { - "" - } else { - &srcset[descriptor_start..offset] - } - .split_ascii_whitespace(); - let mut score = 1.0; - let mut valid = true; - let mut seen = false; - for descriptor in descriptors { - if seen { - valid = false; - break; - } - seen = true; - score = if let Some(value) = descriptor.strip_suffix('w') { - value - .parse::() - .ok() - .filter(|value| *value > 0) - .map(f64::from) - } else if let Some(value) = descriptor.strip_suffix('x') { - value - .parse::() - .ok() - .filter(|value| value.is_finite() && *value > 0.0) - } else { - None + + 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, + _ => {} } - .unwrap_or_else(|| { - valid = false; - 0.0 - }); + offset += 1; } - if valid + let descriptor = srcset[descriptor_start..offset].trim(); + let score = if descriptor.is_empty() { + Some(1.0) + } else if !descriptor.bytes().any(|byte| byte.is_ascii_whitespace()) { + descriptor_score(descriptor) + } else { + None + }; + if let Some(score) = score && !url.is_empty() - && safe_url(url, image) - && best.is_none_or(|(_, current)| score >= current) { - best = Some((url, score)); + candidates.push(SrcsetCandidate { + url, + descriptor, + score, + }); + } + } + candidates +} + +fn descriptor_score(descriptor: &str) -> Option { + if let Some(value) = descriptor.strip_suffix('w') { + return valid_positive_integer(value).map(|value| value as f64); + } + let value = descriptor.strip_suffix('x')?; + valid_positive_float(value) +} + +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() || matches!(bytes[0], b'+' | b'-') { + return None; + } + let mut offset = 0; + while offset < bytes.len() && bytes[offset].is_ascii_digit() { + offset += 1; + } + if offset == 0 { + return None; + } + 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; } } - best.map(|(url, _)| Cow::Owned(url.to_owned())) + 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 { diff --git a/moli-html2md/src/writer.rs b/moli-html2md/src/writer.rs index be11930fc4a..50189b29ed8 100644 --- a/moli-html2md/src/writer.rs +++ b/moli-html2md/src/writer.rs @@ -107,18 +107,18 @@ impl<'a> Writer<'a> { } self.flush_code(); let text = std::mem::take(&mut self.pending_text); - let mut remaining = text.as_str(); - while let Some((start, end)) = crate::math::next_span(remaining) { - self.plain_text(&remaining[..start]); - let math = &remaining[start..end]; + 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; - remaining = &remaining[end..]; + consumed = end; } - self.plain_text(remaining); + self.plain_text(&text[consumed..]); } pub(crate) fn inline_html(&mut self, markup: &str) { diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index 7de3d571df0..6eb3eab6a91 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -1295,3 +1295,61 @@ 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}"); +} diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 50b056badf4..fd11527f223 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -144,6 +144,11 @@ impl PageVm { values.push(animation_iteration_count); values.push(animation_direction); values.push(animation_play_state); + values.push( + Dom::attribute(dom, node, "style") + .unwrap_or_default() + .to_owned(), + ); (node, values) }) .collect::>(); diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 0aaa6e1b007..4ca1a2f001e 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -21,6 +21,14 @@ pub(super) struct MarkdownDom<'a> { 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, @@ -86,7 +94,6 @@ impl<'a> MarkdownDom<'a> { .flatten() }) .collect(); - let visible_handler_functions = visible_handler_functions(dom); for (node, _) in &styles { if (Dom::attribute(dom, *node, "aria-expanded").is_some() || Dom::attribute(dom, *node, "role") @@ -99,19 +106,6 @@ impl<'a> MarkdownDom<'a> { .filter(|id| target_is_disclosure(dom, &targets, id)), ); } - for attribute_name in dom.get_attribute_names(*node).unwrap_or_default() { - if !attribute_name.starts_with("on") { - continue; - } - let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else { - continue; - }; - for target in inline_disclosure_targets(handler, &visible_handler_functions) { - if target_is_disclosure(dom, &targets, target) { - disclosures.insert(target); - } - } - } // 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. @@ -193,7 +187,7 @@ impl<'a> MarkdownDom<'a> { let mut subscripts = HashSet::new(); let mut resolved_urls = HashMap::new(); let mut unchecked_controls = HashSet::new(); - let mut visibility_restored_regions = 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!( @@ -272,12 +266,38 @@ impl<'a> MarkdownDom<'a> { == (background.0, background.1, background.2) }); let document_root = Some(node) == document_element || Some(node) == body; - let visibility_restored = document_visibility_is_hidden - && !document_root - && values.get(1).is_some_and(|value| value == "visible"); - if visibility_restored { - visibility_restored_regions.insert(node); - } + 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 !explicit_visibility_hidden(values.get(21).map(String::as_str)) => + { + VisibilityMode::RootVeil + } + VisibilityMode::DisclosureVeil + if !explicit_visibility_hidden(values.get(21).map(String::as_str)) => + { + VisibilityMode::DisclosureVeil + } + _ => VisibilityMode::Hidden, + } + } else { + parent_visibility + }; + visibility_modes.insert(node, visibility_mode); let has_bounded_final_opacity = has_bounded_final_opacity(&values, &final_opacity_animations); if ((values.first().is_some_and(|value| value == "none") @@ -317,23 +337,12 @@ impl<'a> MarkdownDom<'a> { inline_boundaries.insert(node); } if matches!(Dom::node_kind(dom, node), NodeKind::Element("span")) { - let relative = values.get(3).is_some_and(|position| position == "relative"); let vertical_align = values.get(7).map(String::as_str).unwrap_or_default(); - if vertical_align == "super" - || (relative - && values - .get(5) - .and_then(|value| px(value)) - .is_some_and(|top| top < -1.0)) - { + let authored_vertical_align = + explicit_vertical_align(values.get(21).map(String::as_str)); + if vertical_align == "super" || authored_vertical_align == Some("super") { superscripts.insert(node); - } else if vertical_align == "sub" - || (relative - && values - .get(6) - .and_then(|value| px(value)) - .is_some_and(|bottom| bottom < -1.0)) - { + } else if vertical_align == "sub" || authored_vertical_align == Some("sub") { subscripts.insert(node); } } @@ -374,16 +383,7 @@ impl<'a> MarkdownDom<'a> { } } } - if values - .get(1) - .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse")) - && !disclosure_root - && !disclosure_path - && (!document_visibility_is_hidden - || dom - .parent_node(node) - .is_some_and(|parent| visibility_restored_regions.contains(&parent))) - { + if visibility_mode == VisibilityMode::Hidden && !disclosure_root && !disclosure_path { invisible.insert(node); } } @@ -508,8 +508,11 @@ pub(super) fn final_opacity_animation_names<'a>( else { continue; }; + let name = rule.name; if final_keyframe_reveals(&rule.css_text[canonical_open + 1..canonical_close]) { - result.insert(rule.name); + result.insert(name); + } else { + result.remove(&name); } } } @@ -562,208 +565,38 @@ fn target_is_disclosure( }) } -fn inline_disclosure_targets<'a>( - value: &'a str, - visible_functions: &HashSet, -) -> Vec<&'a str> { - let mut result = Vec::new(); - for (marker, fragment) in [ - ("document.getElementById", false), - ("document.querySelector", true), - ] { - for offset in code_marker_offsets(value, marker) { - let remaining = &value[offset + marker.len()..]; - let Some((literal, end)) = quoted_call_argument(remaining) else { - continue; - }; - let Some(target) = literal - .strip_prefix('#') - .or_else(|| (!fragment).then_some(literal)) - .filter(|target| !target.is_empty()) - else { - continue; - }; - let direct_mutation = sets_display_visible(&remaining[end..], None); - let named_mutation = enclosing_function_name(&value[..offset]) - .is_some_and(|name| visible_functions.contains(name)); - if direct_mutation || named_mutation { - result.push(target); - } - } - } - result -} - -fn visible_handler_functions(dom: &NativeDom) -> HashSet { - let mut result = HashSet::new(); - let mut pending = vec![dom.document_node_id()]; - while let Some(node) = pending.pop() { - if !matches!(Dom::node_kind(dom, node), NodeKind::Element("script")) { - pending.extend(dom.child_ids(node)); - continue; - } - let source = descendant_text(dom, node); - for offset in code_marker_offsets(&source, "function") { - let signature = &source[offset + "function".len()..]; - let Some((name, parameter, body)) = function_parts(signature) else { - continue; - }; - if function_sets_parameter_visible(body, parameter) { - result.insert(name.to_owned()); - } - } - } - result -} - -fn function_parts(source: &str) -> Option<(&str, &str, &str)> { - let source = source.trim_start(); - let name_end = source.find(|character: char| !is_identifier(character))?; - let name = &source[..name_end]; - if name.is_empty() { - return None; - } - let parameters = source[name_end..].trim_start().strip_prefix('(')?; - let close = parameters.find(')')?; - let parameter = parameters[..close].trim(); - if parameter.is_empty() || parameter.contains(',') || !parameter.chars().all(is_identifier) { - return None; - } - let rest = parameters[close + 1..].trim_start(); - let body_start = rest.find('{')?; - let body_end = matching_delimiter(rest, body_start, '{', '}')?; - Some((name, parameter, &rest[body_start + 1..body_end])) -} - -fn function_sets_parameter_visible(body: &str, parameter: &str) -> bool { - for offset in code_marker_offsets(body, ".style.display") { - let owner = body[..offset] - .trim_end() - .rsplit_once(|character: char| !is_identifier(character)) - .map_or(body[..offset].trim_end(), |(_, owner)| owner); - if owner.is_empty() - || !sets_display_visible(&body[offset + ".style.display".len()..], Some("")) - { - continue; - } - if owner == parameter || alias_depends_on_parameter(&body[..offset], owner, parameter) { - return true; - } - } - false -} - -fn alias_depends_on_parameter(prefix: &str, owner: &str, parameter: &str) -> bool { - let Some(offset) = code_marker_offsets(prefix, owner) - .into_iter() - .rev() - .find(|offset| { - let before = prefix[..*offset].chars().next_back(); - let after = prefix[*offset + owner.len()..].chars().next(); - before.is_none_or(|character| !is_identifier(character)) - && after.is_none_or(|character| !is_identifier(character)) - && prefix[*offset + owner.len()..] - .trim_start() - .starts_with('=') +fn explicit_visibility_hidden(style: Option<&str>) -> bool { + style.is_some_and(|style| { + style.split(';').any(|declaration| { + declaration.split_once(':').is_some_and(|(name, value)| { + name.trim().eq_ignore_ascii_case("visibility") + && matches!( + value + .split('!') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase() + .as_str(), + "hidden" | "collapse" + ) + }) }) - else { - return false; - }; - let assignment = prefix[offset + owner.len()..].trim_start(); - let Some(right) = assignment.strip_prefix('=') else { - return false; - }; - let right = right.split_once(';').map_or(right, |(right, _)| right); - contains_identifier(right, parameter) + }) } -fn contains_identifier(value: &str, identifier: &str) -> bool { - code_marker_offsets(value, identifier) - .into_iter() - .any(|offset| { - let before = value[..offset].chars().next_back(); - let after = value[offset + identifier.len()..].chars().next(); - before.is_none_or(|character| !is_identifier(character)) - && after.is_none_or(|character| !is_identifier(character)) +fn explicit_vertical_align(style: Option<&str>) -> Option<&str> { + style? + .split(';') + .filter_map(|declaration| declaration.split_once(':')) + .rev() + .find_map(|(name, value)| { + name.trim() + .eq_ignore_ascii_case("vertical-align") + .then(|| value.trim()) }) } -fn enclosing_function_name(value: &str) -> Option<&str> { - let value = value.trim_end(); - let value = value.strip_suffix('(')?.trim_end(); - let start = value - .rfind(|character: char| !is_identifier(character)) - .map_or(0, |offset| offset + 1); - let name = &value[start..]; - (!name.is_empty()).then_some(name) -} - -fn quoted_call_argument(value: &str) -> Option<(&str, usize)> { - let leading = value.len() - value.trim_start().len(); - let value = value.trim_start().strip_prefix('(')?; - let after_open = value.len() - value.trim_start().len(); - let value = value.trim_start(); - let quote = value - .chars() - .next() - .filter(|quote| matches!(quote, '\'' | '"'))?; - let literal = &value[quote.len_utf8()..]; - let end = literal.find(quote)?; - let after_literal = literal[end + quote.len_utf8()..].trim_start(); - if !after_literal.starts_with(')') { - return None; - } - let consumed = leading - + 1 - + after_open - + quote.len_utf8() - + end - + quote.len_utf8() - + (literal[end + quote.len_utf8()..].len() - after_literal.len()) - + 1; - Some((&literal[..end], consumed)) -} - -fn sets_display_visible(value: &str, display_already_consumed: Option<&str>) -> bool { - let value = if display_already_consumed.is_some() { - value - } else { - let Some(value) = value.trim_start().strip_prefix(".style.display") else { - return false; - }; - value - }; - let Some(value) = value.trim_start().strip_prefix('=') else { - return false; - }; - let value = value.trim_start(); - let Some(quote) = value - .chars() - .next() - .filter(|quote| matches!(quote, '\'' | '"')) - else { - return false; - }; - let literal = &value[quote.len_utf8()..]; - let Some(end) = literal.find(quote) else { - return false; - }; - matches!( - literal[..end].trim(), - "" | "block" - | "inline" - | "inline-block" - | "flex" - | "inline-flex" - | "grid" - | "inline-grid" - | "list-item" - | "table" - | "table-row" - | "table-cell" - ) -} - fn code_marker_offsets(value: &str, marker: &str) -> Vec { let mut result = Vec::new(); let mut offset = 0; @@ -877,71 +710,22 @@ fn matching_delimiter(value: &str, start: usize, open: char, close: char) -> Opt None } -fn is_identifier(character: char) -> bool { - character == '_' || character == '$' || character.is_ascii_alphanumeric() -} - -fn descendant_text(dom: &NativeDom, root: NativeNodeId) -> String { - let mut pending = vec![root]; - let mut result = String::new(); - while let Some(node) = pending.pop() { - if let NodeKind::Text(value) = Dom::node_kind(dom, node) { - result.push_str(value); - } - 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 -} - fn px(value: &str) -> Option { value.strip_suffix("px")?.trim().parse().ok() } fn resolve_srcset(base_url: &Url, value: &str) -> Option { - let mut resolved = Vec::new(); - let bytes = value.as_bytes(); - let mut offset = 0; - while offset < bytes.len() { - while offset < bytes.len() && (bytes[offset].is_ascii_whitespace() || bytes[offset] == b',') - { - offset += 1; - } - let start = offset; - while offset < bytes.len() && !bytes[offset].is_ascii_whitespace() { - offset += 1; - } - if start == offset { - break; - } - let mut end = offset; - while end > start && bytes[end - 1] == b',' { - end -= 1; - } - let ended_with_comma = end < offset; - let descriptor_start = offset; - if !ended_with_comma { - while offset < bytes.len() && bytes[offset] != b',' { - offset += 1; - } - } - let descriptor = if ended_with_comma { - "" - } else { - value[descriptor_start..offset].trim() - }; - let url = base_url.join(&value[start..end]).ok()?; - resolved.push(if descriptor.is_empty() { - url.to_string() - } else { - format!("{url} {descriptor}") - }); - } + 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(", ")) } 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 index cc5635b09ab..0221122f8a8 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -41,13 +41,16 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

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

+

Mass 2.4 × 10−17 J; mn

+

Account settings

Upload complete Article photo @@ -76,9 +79,11 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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", "Animated rotation text", "Zero-duration reveal text", "Repeating reveal text", "Reverse reveal text", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] { + 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")); @@ -148,6 +153,14 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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.body.innerHTML = ` @@ -162,6 +175,11 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { + + + + +
Actual next disclosure
@@ -172,8 +190,11 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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("Query-selected history"), "{related}"); + assert!(!related.contains("Function-revealed records"), "{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(r#" @@ -211,16 +232,27 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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`; + 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; From 7b35185f7baddd4ba2958b9b7ff6860bb33d0f59 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 20:19:20 +0800 Subject: [PATCH 15/21] fix(content): honor effective style and disclosure facts --- moli-html2md/src/media.rs | 19 +++-- moli-html2md/tests/regressions.rs | 19 +++++ .../context_host/host_environment.rs | 12 +++ moli-renderer-v8/src/native_bridge/element.rs | 1 + .../src/native_bridge/element/styles.rs | 22 ++++++ .../element/styles/declaration/values.rs | 10 +++ moli-renderer-v8/src/runtime/page_dump.rs | 20 ++++- .../src/runtime/page_dump/visibility.rs | 79 +++++++++++-------- .../runtime/page_vm/tests/markdown_dump.rs | 34 ++++++++ moli-renderer-v8/src/script_vm/layout.rs | 30 ++++--- moli-renderer-v8/src/style_engine/computed.rs | 51 +++++++++++- moli-renderer-v8/src/style_engine/mod.rs | 38 +++++++++ .../src/style_engine/stylesheet.rs | 19 +++++ 13 files changed, 293 insertions(+), 61 deletions(-) diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index 2d646c2430c..75911cb60e0 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -169,16 +169,19 @@ fn valid_positive_integer(value: &str) -> Option { fn valid_positive_float(value: &str) -> Option { let bytes = value.as_bytes(); - if bytes.is_empty() || matches!(bytes[0], b'+' | b'-') { + if bytes.is_empty() || bytes[0] == b'+' { return None; } - let mut offset = 0; + 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; } - if offset == 0 { - return None; - } + let has_integer = offset > integer_start; + let mut has_fraction = false; if bytes.get(offset) == Some(&b'.') { offset += 1; let fraction = offset; @@ -188,6 +191,10 @@ fn valid_positive_float(value: &str) -> Option { 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; @@ -205,7 +212,7 @@ fn valid_positive_float(value: &str) -> Option { (offset == bytes.len()) .then(|| value.parse::().ok()) .flatten() - .filter(|value| value.is_finite() && *value > 0.0) + .filter(|value| value.is_finite() && *value >= 0.0) } fn largest_srcset_candidate(srcset: &str, image: bool) -> Option> { diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index 6eb3eab6a91..feffcc50971 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -1353,3 +1353,22 @@ fn srcset_rejects_invalid_numbers_and_commas_inside_parentheses() { ); 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}"); + } +} 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..d408d7eae5f 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,18 @@ impl JsContextHost { .retained_stylesheet_query_snapshot_for_document(document) } + pub(crate) fn style_engine_author_shared_lock(&self) -> style::shared_lock::SharedRwLock { + self.style_engine.author_shared_lock() + } + + pub(crate) fn effective_keyframe_rule_texts_for_document( + &self, + document: DomHandle, + ) -> Vec { + self.style_engine + .effective_keyframe_rule_texts_for_document(document) + } + #[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..17a008f1eb2 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_inherited_property_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..c040c1c4a7e 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles.rs @@ -619,6 +619,28 @@ pub(crate) fn computed_style_property_values_for_document_snapshot( .collect() } +pub(crate) fn computed_style_own_inherited_property_values_for_document_snapshot( + host: &JsContextHost, + handles: impl IntoIterator, + property: &str, +) -> Vec { + let mut observation = StyleObservation::new(host); + let shared_lock = host.style_engine_author_shared_lock(); + 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_inherited_longhand_value(property, &shared_lock) + }) + .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..d0dff7c0d8e 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,16 @@ impl<'a> ComputedStyleRead<'a> { Some(self.stylo_style.as_ref()?.rendered_style_facts()) } + pub(in crate::native_bridge::element) fn computed_style_has_own_inherited_longhand_value( + &self, + property: &str, + shared_lock: &style::shared_lock::SharedRwLock, + ) -> bool { + self.stylo_style + .as_ref() + .is_some_and(|style| style.has_own_inherited_longhand_value(property, shared_lock)) + } + 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 fd11527f223..21d1447d5f6 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -63,7 +63,7 @@ impl PageVm { .vm() .computed_style_property_values_for_document_snapshot( span_nodes.iter().copied(), - &["bottom".to_owned(), "vertical-align".to_owned()], + &["bottom".to_owned(), "baseline-shift".to_owned()], ); let spans: HashMap<_, _> = span_nodes.into_iter().zip(span_values).collect(); let image_values = self @@ -95,6 +95,14 @@ impl PageVm { "animation-play-state".to_owned(), ], ); + let own_visibility_values = self + .vm() + .computed_style_own_inherited_property_values_for_document_snapshot( + nodes.iter().copied(), + "visibility", + ); + let own_visibility: HashMap<_, _> = + nodes.iter().copied().zip(own_visibility_values).collect(); let styles = nodes .into_iter() .zip(values) @@ -145,14 +153,18 @@ impl PageVm { values.push(animation_direction); values.push(animation_play_state); values.push( - Dom::attribute(dom, node, "style") + own_visibility + .get(&node) + .copied() .unwrap_or_default() - .to_owned(), + .to_string(), ); (node, values) }) .collect::>(); - let stylesheet_texts = self.vm().active_stylesheet_texts_for_document_snapshot(); + let stylesheet_texts = self + .vm() + .effective_keyframe_rule_texts_for_document_snapshot(); let final_opacity_animations = visibility::final_opacity_animation_names( stylesheet_texts.iter().map(String::as_str), ); diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 4ca1a2f001e..41a2c184f54 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -94,6 +94,11 @@ impl<'a> MarkdownDom<'a> { .flatten() }) .collect(); + for (&id, &target) in &hidden_targets { + if paired_adjacent_disclosure(dom, target, id) { + disclosures.insert(id); + } + } for (node, _) in &styles { if (Dom::attribute(dom, *node, "aria-expanded").is_some() || Dom::attribute(dom, *node, "role") @@ -283,12 +288,12 @@ impl<'a> MarkdownDom<'a> { } else if matches!(computed_visibility, "hidden" | "collapse") { match parent_visibility { VisibilityMode::RootVeil - if !explicit_visibility_hidden(values.get(21).map(String::as_str)) => + if values.get(21).is_none_or(|value| value != "true") => { VisibilityMode::RootVeil } VisibilityMode::DisclosureVeil - if !explicit_visibility_hidden(values.get(21).map(String::as_str)) => + if values.get(21).is_none_or(|value| value != "true") => { VisibilityMode::DisclosureVeil } @@ -338,11 +343,9 @@ impl<'a> MarkdownDom<'a> { } if matches!(Dom::node_kind(dom, node), NodeKind::Element("span")) { let vertical_align = values.get(7).map(String::as_str).unwrap_or_default(); - let authored_vertical_align = - explicit_vertical_align(values.get(21).map(String::as_str)); - if vertical_align == "super" || authored_vertical_align == Some("super") { + if vertical_align == "super" { superscripts.insert(node); - } else if vertical_align == "sub" || authored_vertical_align == Some("sub") { + } else if vertical_align == "sub" { subscripts.insert(node); } } @@ -565,36 +568,44 @@ fn target_is_disclosure( }) } -fn explicit_visibility_hidden(style: Option<&str>) -> bool { - style.is_some_and(|style| { - style.split(';').any(|declaration| { - declaration.split_once(':').is_some_and(|(name, value)| { - name.trim().eq_ignore_ascii_case("visibility") - && matches!( - value - .split('!') - .next() - .unwrap_or_default() - .trim() - .to_ascii_lowercase() - .as_str(), - "hidden" | "collapse" - ) - }) - }) - }) +fn paired_adjacent_disclosure(dom: &NativeDom, target: NativeNodeId, id: &str) -> bool { + let mut sibling = dom.previous_sibling(target); + while sibling.is_some_and(|node| { + matches!(Dom::node_kind(dom, node), NodeKind::Text(value) if value.trim().is_empty()) + || matches!(Dom::node_kind(dom, node), NodeKind::Other) + }) { + sibling = sibling.and_then(|node| dom.previous_sibling(node)); + } + let Some(control_region) = sibling else { + return false; + }; + if !matches!(Dom::node_kind(dom, control_region), NodeKind::Element(_)) { + return false; + } + + let mut show = false; + let mut hide = false; + let mut pending = vec![control_region]; + while let Some(node) = pending.pop() { + if matches!(Dom::node_kind(dom, node), NodeKind::Element("a" | "button")) + && Dom::attribute(dom, node, "onclick") + .is_some_and(|handler| handler_references_id(handler, id)) + { + match text(dom, node, None).trim().to_ascii_lowercase().as_str() { + "+" | "show" | "expand" | "more" => show = true, + "-" | "hide" | "collapse" | "less" => hide = true, + _ => {} + } + } + pending.extend(dom.child_ids(node)); + } + show && hide } -fn explicit_vertical_align(style: Option<&str>) -> Option<&str> { - style? - .split(';') - .filter_map(|declaration| declaration.split_once(':')) - .rev() - .find_map(|(name, value)| { - name.trim() - .eq_ignore_ascii_case("vertical-align") - .then(|| value.trim()) - }) +fn handler_references_id(handler: &str, id: &str) -> bool { + [format!("'{id}'"), format!("\"{id}\"")] + .iter() + .any(|quoted| handler.contains(quoted)) } fn code_marker_offsets(value: &str, marker: &str) -> Vec { 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 index 0221122f8a8..e0d13f15b64 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -161,6 +161,38 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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.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.body.innerHTML = ` @@ -175,6 +207,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { + + - @@ -192,6 +225,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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("Unreachable hidden state"), "{related}"); assert!(!related.contains("Hidden anchor metadata"), "{related}"); assert!(!related.contains("Actual next disclosure"), "{related}"); diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs index 28794119684..ba9b6bd5800 100644 --- a/moli-renderer-v8/src/script_vm/layout.rs +++ b/moli-renderer-v8/src/script_vm/layout.rs @@ -70,24 +70,10 @@ impl ScriptVm { read(host.dom_host(), &mut input) } - pub(crate) fn active_stylesheet_texts_for_document_snapshot(&self) -> Vec { + pub(crate) fn effective_keyframe_rule_texts_for_document_snapshot(&self) -> Vec { let host = self._context_host.borrow(); let document = host.document_handle(); - host.retained_stylesheet_query_snapshot_for_document(document) - .map(|snapshot| { - snapshot - .document_stylesheet_sources - .iter() - .chain( - snapshot - .shadow_stylesheet_sources - .iter() - .flat_map(|(_, sources)| sources.iter()), - ) - .map(|source| source.serialized_css_text().to_string()) - .collect() - }) - .unwrap_or_default() + host.effective_keyframe_rule_texts_for_document(document) } pub(crate) fn sync_live_document_style_sources(&mut self) { @@ -109,6 +95,18 @@ impl ScriptVm { ) } + pub(crate) fn computed_style_own_inherited_property_values_for_document_snapshot( + &self, + handles: impl IntoIterator, + property: &str, + ) -> Vec { + crate::native_bridge::element::computed_style_own_inherited_property_values_for_document_snapshot( + &self._context_host.borrow(), + handles, + property, + ) + } + 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..70394f8ed4a 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -11,7 +11,7 @@ use style::{ data::ElementStyles, dom::{TElement, TNode}, properties::{ - ComputedValues, PropertyId, + CSSWideKeyword, ComputedValues, PropertyDeclarationId, PropertyId, longhands::{ text_wrap_mode::computed_value::T as StyloTextWrapMode, visibility::computed_value::T as ComputedVisibility, @@ -284,6 +284,55 @@ impl StyloComputedStyleSnapshot { serialize_raw_computed_property(&self.primary, property_id) } + /// Whether this element's cascade supplies a value for an inherited + /// longhand instead of taking the value from its parent. + /// + /// Computed values alone cannot distinguish `visibility:hidden` declared + /// on an element from the same value inherited from an ancestor. Consumers + /// that selectively expose an otherwise hidden subtree need that source + /// distinction, but should not parse inline style or stylesheet text a + /// second time. + pub(crate) fn has_own_inherited_longhand_value( + &self, + property: &str, + shared_lock: &style::shared_lock::SharedRwLock, + ) -> bool { + let Ok(property_id) = PropertyId::parse_enabled_for_all_content(property) else { + return false; + }; + let Some(longhand) = property_id.longhand_id() else { + return false; + }; + let guard = shared_lock.read(); + let guards = StylesheetGuards::same(&guard); + for node in self.primary.rules().self_and_ancestors() { + let Some(source) = node.style_source() else { + continue; + }; + for (declaration, importance) in source + .read(node.cascade_level().guard(&guards)) + .declaration_importance_iter() + .rev() + { + if importance.important() != node.importance().important() + || declaration.id() != PropertyDeclarationId::Longhand(longhand) + { + continue; + } + match declaration.get_css_wide_keyword() { + Some(CSSWideKeyword::Inherit | CSSWideKeyword::Unset) => return false, + Some( + CSSWideKeyword::Revert + | CSSWideKeyword::RevertLayer + | CSSWideKeyword::RevertRule, + ) => continue, + _ => return true, + } + } + } + false + } + pub(crate) fn resolved_property_value(&self, property: &str) -> Option { if property.starts_with("--") { return serialize_computed_custom_property(&self.primary, property); diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs index 36ac463d0a8..c3287994cb1 100644 --- a/moli-renderer-v8/src/style_engine/mod.rs +++ b/moli-renderer-v8/src/style_engine/mod.rs @@ -323,6 +323,44 @@ impl MoliStyleEngine { }) } + pub(crate) fn effective_keyframe_rule_texts_for_document( + &self, + document: DomHandle, + ) -> Vec { + let Some(world) = self.document_worlds.active_world(document) else { + return Vec::new(); + }; + world + .document_state + .try_with_retained_style_system(|retained| { + let device = retained.stylist.device(); + let mut result = Vec::new(); + let document_custom_media = retained + .stylist + .cascade_data() + .borrow_for_origin(style::stylesheets::Origin::Author) + .custom_media_map(); + for entry in retained.document_stylesheets.entries() { + result.extend(stylesheet::native_effective_keyframe_rule_texts( + entry.stylesheet(), + device, + document_custom_media, + )); + } + for scope in &retained.shadow_scopes { + for entry in scope.active_stylesheets().entries() { + result.extend(stylesheet::native_effective_keyframe_rule_texts( + entry.stylesheet(), + device, + scope.author_styles().data.custom_media_map(), + )); + } + } + result + }) + .unwrap_or_default() + } + #[cfg(debug_assertions)] pub(crate) fn computed_style_observation_input_epochs( &self, diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rs index 016a4d00618..aa2d2ef2e11 100644 --- a/moli-renderer-v8/src/style_engine/stylesheet.rs +++ b/moli-renderer-v8/src/style_engine/stylesheet.rs @@ -218,6 +218,25 @@ pub(super) fn native_effective_font_face_rule_addresses( native_effective_font_face_rule_addresses_with_guard(stylesheet, device, custom_media, &guard) } +pub(super) fn native_effective_keyframe_rule_texts( + stylesheet: &DocumentStyleSheet, + device: &Device, + custom_media: &CustomMediaMap, +) -> Vec { + let guard = stylesheet.0.shared_lock.read(); + if !stylesheet.enabled() || !stylesheet.is_effective_for_device(device, custom_media, &guard) { + return Vec::new(); + } + stylesheet + .contents(&guard) + .effective_rules(device, custom_media, &guard) + .filter_map(|rule| match rule { + CssRule::Keyframes(rule) => Some(rule.read_with(&guard).to_css_string(&guard)), + _ => None, + }) + .collect() +} + fn native_effective_font_face_rule_addresses_with_guard( stylesheet: &DocumentStyleSheet, device: &Device, From f93a23a2c9d2ffb3fbc760e3e80a8e53f55645ca Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:24:17 +0800 Subject: [PATCH 16/21] fix(content): trust scoped state over handler shape --- moli-html2md/src/media.rs | 35 ++++++++++--- moli-html2md/tests/regressions.rs | 19 ++++++- .../context_host/host_environment.rs | 18 +++++-- moli-renderer-v8/src/runtime/page_dump.rs | 40 ++++++++++---- .../src/runtime/page_dump/visibility.rs | 52 ++----------------- .../runtime/page_vm/tests/markdown_dump.rs | 41 +++++++++++++-- moli-renderer-v8/src/script_vm/layout.rs | 10 +++- moli-renderer-v8/src/style_engine/computed.rs | 27 +++++++--- moli-renderer-v8/src/style_engine/mod.rs | 36 ++++++++++--- 9 files changed, 189 insertions(+), 89 deletions(-) diff --git a/moli-html2md/src/media.rs b/moli-html2md/src/media.rs index 75911cb60e0..84f9e7fdcd0 100644 --- a/moli-html2md/src/media.rs +++ b/moli-html2md/src/media.rs @@ -134,10 +134,8 @@ pub fn parse_srcset(srcset: &str) -> Vec> { let descriptor = srcset[descriptor_start..offset].trim(); let score = if descriptor.is_empty() { Some(1.0) - } else if !descriptor.bytes().any(|byte| byte.is_ascii_whitespace()) { - descriptor_score(descriptor) } else { - None + descriptor_score(descriptor) }; if let Some(score) = score && !url.is_empty() @@ -153,11 +151,34 @@ pub fn parse_srcset(srcset: &str) -> Vec> { } fn descriptor_score(descriptor: &str) -> Option { - if let Some(value) = descriptor.strip_suffix('w') { - return valid_positive_integer(value).map(|value| value as f64); + 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, } - let value = descriptor.strip_suffix('x')?; - valid_positive_float(value) } fn valid_positive_integer(value: &str) -> Option { diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs index feffcc50971..02aadc4d3e7 100644 --- a/moli-html2md/tests/regressions.rs +++ b/moli-html2md/tests/regressions.rs @@ -1,6 +1,6 @@ mod support; -use moli_html2md::{Converter, Dom, NodeKind, Options}; +use moli_html2md::{Converter, Dom, NodeKind, Options, parse_srcset}; use std::cell::Cell; use support::{Tree, rendered_html}; @@ -1372,3 +1372,20 @@ fn srcset_density_uses_the_html_floating_point_grammar() { 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-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs index d408d7eae5f..e1c7e92d1a4 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 @@ -1521,12 +1521,22 @@ impl JsContextHost { self.style_engine.author_shared_lock() } - pub(crate) fn effective_keyframe_rule_texts_for_document( + pub(crate) fn effective_keyframe_rule_texts_for_elements( &self, document: DomHandle, - ) -> Vec { - self.style_engine - .effective_keyframe_rule_texts_for_document(document) + elements: impl IntoIterator, + ) -> ( + Vec>, + std::collections::HashMap, Vec>, + ) { + let tree_scopes: Vec<_> = elements + .into_iter() + .map(|element| self.dom_host().containing_shadow_root(element)) + .collect(); + let rules = self + .style_engine + .effective_keyframe_rule_texts_for_tree_scopes(document, tree_scopes.iter().copied()); + (tree_scopes, rules) } #[cfg(test)] diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 21d1447d5f6..16845bf53b2 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -103,6 +103,34 @@ impl PageVm { ); let own_visibility: HashMap<_, _> = nodes.iter().copied().zip(own_visibility_values).collect(); + let (keyframe_scopes, keyframe_rules) = self + .vm() + .effective_keyframe_rule_texts_for_element_snapshots(nodes.iter().copied()); + let final_opacity_by_scope: HashMap<_, _> = keyframe_rules + .into_iter() + .map(|(scope, stylesheet_texts)| { + ( + scope, + visibility::final_opacity_animation_names( + stylesheet_texts.iter().map(String::as_str), + ), + ) + }) + .collect(); + let final_opacity_animations: HashMap<_, _> = nodes + .iter() + .copied() + .zip(keyframe_scopes) + .map(|(node, scope)| { + ( + node, + final_opacity_by_scope + .get(&scope) + .cloned() + .unwrap_or_default(), + ) + }) + .collect(); let styles = nodes .into_iter() .zip(values) @@ -162,15 +190,9 @@ impl PageVm { (node, values) }) .collect::>(); - let stylesheet_texts = self - .vm() - .effective_keyframe_rule_texts_for_document_snapshot(); - let final_opacity_animations = visibility::final_opacity_animation_names( - stylesheet_texts.iter().map(String::as_str), - ); (styles, final_opacity_animations) } else { - (Vec::new(), HashSet::new()) + (Vec::new(), HashMap::new()) }; if options.format == RendererPageDumpFormat::Markdown && !options.with_base @@ -357,14 +379,14 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String { - render_markdown_document_with_styles(dom, Vec::new(), None, HashSet::new()) + render_markdown_document_with_styles(dom, Vec::new(), None, HashMap::new()) } fn render_markdown_document_with_styles( dom: &NativeDom, styles: Vec<(NativeNodeId, Vec)>, base_url: Option<&url::Url>, - final_opacity_animations: HashSet, + final_opacity_animations: HashMap>, ) -> String { let root = dom.body_node_id().unwrap_or(dom.document_node_id()); let visible = visibility::MarkdownDom::new(dom, styles, base_url, final_opacity_animations); diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index 41a2c184f54..c0dadc9f56e 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -34,7 +34,7 @@ impl<'a> MarkdownDom<'a> { dom: &'a NativeDom, styles: impl IntoIterator)>, base_url: Option<&Url>, - final_opacity_animations: HashSet, + final_opacity_animations: HashMap>, ) -> Self { let styles: Vec<_> = styles.into_iter().collect(); let document_element = dom.document_element_node_id(); @@ -94,11 +94,6 @@ impl<'a> MarkdownDom<'a> { .flatten() }) .collect(); - for (&id, &target) in &hidden_targets { - if paired_adjacent_disclosure(dom, target, id) { - disclosures.insert(id); - } - } for (node, _) in &styles { if (Dom::attribute(dom, *node, "aria-expanded").is_some() || Dom::attribute(dom, *node, "role") @@ -303,8 +298,9 @@ impl<'a> MarkdownDom<'a> { parent_visibility }; visibility_modes.insert(node, visibility_mode); - let has_bounded_final_opacity = - has_bounded_final_opacity(&values, &final_opacity_animations); + let has_bounded_final_opacity = final_opacity_animations + .get(&node) + .is_some_and(|names| has_bounded_final_opacity(&values, names)); if ((values.first().is_some_and(|value| value == "none") || values .get(2) @@ -568,46 +564,6 @@ fn target_is_disclosure( }) } -fn paired_adjacent_disclosure(dom: &NativeDom, target: NativeNodeId, id: &str) -> bool { - let mut sibling = dom.previous_sibling(target); - while sibling.is_some_and(|node| { - matches!(Dom::node_kind(dom, node), NodeKind::Text(value) if value.trim().is_empty()) - || matches!(Dom::node_kind(dom, node), NodeKind::Other) - }) { - sibling = sibling.and_then(|node| dom.previous_sibling(node)); - } - let Some(control_region) = sibling else { - return false; - }; - if !matches!(Dom::node_kind(dom, control_region), NodeKind::Element(_)) { - return false; - } - - let mut show = false; - let mut hide = false; - let mut pending = vec![control_region]; - while let Some(node) = pending.pop() { - if matches!(Dom::node_kind(dom, node), NodeKind::Element("a" | "button")) - && Dom::attribute(dom, node, "onclick") - .is_some_and(|handler| handler_references_id(handler, id)) - { - match text(dom, node, None).trim().to_ascii_lowercase().as_str() { - "+" | "show" | "expand" | "more" => show = true, - "-" | "hide" | "collapse" | "less" => hide = true, - _ => {} - } - } - pending.extend(dom.child_ids(node)); - } - show && hide -} - -fn handler_references_id(handler: &str, id: &str) -> bool { - [format!("'{id}'"), format!("\"{id}\"")] - .iter() - .any(|quoted| handler.contains(quoted)) -} - fn code_marker_offsets(value: &str, marker: &str) -> Vec { let mut result = Vec::new(); let mut offset = 0; 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 index e0d13f15b64..32283a9bb47 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -180,6 +180,20 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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 = ` +
+

Invalid variable inherits the veil

+

Variable fallback inherits the veil

+

Origin revert inherits the veil

+

Layer revert inherits the veil

+
`; + "#).unwrap(); + 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}"); + } page.vm_mut().eval(r#" document.body.style.visibility = ''; document.head.innerHTML = ''; @@ -193,6 +207,15 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { "#).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.body.innerHTML = ` @@ -205,9 +228,10 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { - + - + - + + - + @@ -225,12 +249,23 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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("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

diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs index ba9b6bd5800..da883c5c4af 100644 --- a/moli-renderer-v8/src/script_vm/layout.rs +++ b/moli-renderer-v8/src/script_vm/layout.rs @@ -70,10 +70,16 @@ impl ScriptVm { read(host.dom_host(), &mut input) } - pub(crate) fn effective_keyframe_rule_texts_for_document_snapshot(&self) -> Vec { + pub(crate) fn effective_keyframe_rule_texts_for_element_snapshots( + &self, + elements: impl IntoIterator, + ) -> ( + Vec>, + std::collections::HashMap, Vec>, + ) { let host = self._context_host.borrow(); let document = host.document_handle(); - host.effective_keyframe_rule_texts_for_document(document) + host.effective_keyframe_rule_texts_for_elements(document, elements) } pub(crate) fn sync_live_document_style_sources(&mut self) { diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index 70394f8ed4a..c44c2f1f37c 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -4,6 +4,7 @@ use dom::ElementState as StyloElementState; use style::{ Atom, animation::DocumentAnimationSet, + applicable_declarations::{CascadePriority, RevertKind}, context::{ QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext, StyleContext, StyleSystemOptions, ThreadLocalStyleContext, @@ -11,7 +12,7 @@ use style::{ data::ElementStyles, dom::{TElement, TNode}, properties::{ - CSSWideKeyword, ComputedValues, PropertyDeclarationId, PropertyId, + CSSWideKeyword, ComputedValues, PropertyDeclaration, PropertyDeclarationId, PropertyId, longhands::{ text_wrap_mode::computed_value::T as StyloTextWrapMode, visibility::computed_value::T as ComputedVisibility, @@ -305,7 +306,14 @@ impl StyloComputedStyleSnapshot { }; let guard = shared_lock.read(); let guards = StylesheetGuards::same(&guard); + let mut reverted: Option<(CascadePriority, RevertKind)> = None; for node in self.primary.rules().self_and_ancestors() { + let priority = node.cascade_priority(); + if reverted.is_some_and(|(reverted_priority, kind)| { + !reverted_priority.allows_when_reverted(&priority, kind) + }) { + continue; + } let Some(source) = node.style_source() else { continue; }; @@ -321,13 +329,18 @@ impl StyloComputedStyleSnapshot { } match declaration.get_css_wide_keyword() { Some(CSSWideKeyword::Inherit | CSSWideKeyword::Unset) => return false, - Some( - CSSWideKeyword::Revert - | CSSWideKeyword::RevertLayer - | CSSWideKeyword::RevertRule, - ) => continue, - _ => return true, + Some(keyword) if keyword.revert_kind().is_some() => { + reverted = Some((priority, keyword.revert_kind().unwrap())); + continue; + } + _ => {} } + // Variable substitution happens inside Stylo's cascade. A raw + // `WithVariables` declaration cannot establish an independent + // hidden boundary here: it may be invalid at computed-value + // time or resolve to `inherit`. Treat it conservatively as + // inherited instead of recreating the substitution engine. + return !matches!(declaration, PropertyDeclaration::WithVariables(_)); } } false diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs index c3287994cb1..fa4191c0f72 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; @@ -323,40 +327,56 @@ impl MoliStyleEngine { }) } - pub(crate) fn effective_keyframe_rule_texts_for_document( + pub(crate) fn effective_keyframe_rule_texts_for_tree_scopes( &self, document: DomHandle, - ) -> Vec { + tree_scopes: impl IntoIterator>, + ) -> HashMap, Vec> { let Some(world) = self.document_worlds.active_world(document) else { - return Vec::new(); + return HashMap::new(); }; world .document_state .try_with_retained_style_system(|retained| { let device = retained.stylist.device(); - let mut result = Vec::new(); + let mut document_rules = Vec::new(); let document_custom_media = retained .stylist .cascade_data() .borrow_for_origin(style::stylesheets::Origin::Author) .custom_media_map(); for entry in retained.document_stylesheets.entries() { - result.extend(stylesheet::native_effective_keyframe_rule_texts( + document_rules.extend(stylesheet::native_effective_keyframe_rule_texts( entry.stylesheet(), device, document_custom_media, )); } + let mut shadow_rules = HashMap::new(); for scope in &retained.shadow_scopes { + let rules = shadow_rules.entry(scope.root()).or_insert_with(Vec::new); for entry in scope.active_stylesheets().entries() { - result.extend(stylesheet::native_effective_keyframe_rule_texts( + rules.extend(stylesheet::native_effective_keyframe_rule_texts( entry.stylesheet(), device, scope.author_styles().data.custom_media_map(), )); } } - result + tree_scopes + .into_iter() + .collect::>() + .into_iter() + .map(|tree_scope| { + let mut rules = document_rules.clone(); + if let Some(tree_scope) = tree_scope + && let Some(scoped_rules) = shadow_rules.get(&tree_scope) + { + rules.extend(scoped_rules.iter().cloned()); + } + (tree_scope, rules) + }) + .collect() }) .unwrap_or_default() } From c5efa39b42d5ee7579dc803e6ae9dd68c5411344 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:19:54 +0800 Subject: [PATCH 17/21] fix(content): consume resolved style semantics --- .../context_host/host_environment.rs | 23 +- moli-renderer-v8/src/native_bridge/element.rs | 2 +- .../src/native_bridge/element/styles.rs | 6 +- .../element/styles/declaration/values.rs | 6 +- moli-renderer-v8/src/runtime/page_dump.rs | 40 +--- .../src/runtime/page_dump/visibility.rs | 210 ++---------------- .../runtime/page_vm/tests/markdown_dump.rs | 29 +++ moli-renderer-v8/src/script_vm/layout.rs | 17 +- moli-renderer-v8/src/style_engine/computed.rs | 162 +++++++++----- moli-renderer-v8/src/style_engine/mod.rs | 60 +---- .../src/style_engine/stylesheet.rs | 19 -- 11 files changed, 185 insertions(+), 389 deletions(-) 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 e1c7e92d1a4..d8ff52167d4 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,26 +1517,13 @@ impl JsContextHost { .retained_stylesheet_query_snapshot_for_document(document) } - pub(crate) fn style_engine_author_shared_lock(&self) -> style::shared_lock::SharedRwLock { - self.style_engine.author_shared_lock() - } - - pub(crate) fn effective_keyframe_rule_texts_for_elements( + pub(crate) fn final_opacity_animation_names_for_elements( &self, document: DomHandle, - elements: impl IntoIterator, - ) -> ( - Vec>, - std::collections::HashMap, Vec>, - ) { - let tree_scopes: Vec<_> = elements - .into_iter() - .map(|element| self.dom_host().containing_shadow_root(element)) - .collect(); - let rules = self - .style_engine - .effective_keyframe_rule_texts_for_tree_scopes(document, tree_scopes.iter().copied()); - (tree_scopes, rules) + elements: impl IntoIterator)>, + ) -> std::collections::HashMap> { + self.style_engine + .final_opacity_animation_names_for_elements(self.dom_host(), document, elements) } #[cfg(test)] diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index 17a008f1eb2..e997b7be906 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -167,7 +167,7 @@ pub(crate) use shadow_dom::{ }; pub(crate) use styles::{ ComputedStyleRead, StyleMode, active_css_animation_transform_value, - computed_style_own_inherited_property_values_for_document_snapshot, + 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 c040c1c4a7e..77243464ec6 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles.rs @@ -619,13 +619,11 @@ pub(crate) fn computed_style_property_values_for_document_snapshot( .collect() } -pub(crate) fn computed_style_own_inherited_property_values_for_document_snapshot( +pub(crate) fn computed_style_own_visibility_values_for_document_snapshot( host: &JsContextHost, handles: impl IntoIterator, - property: &str, ) -> Vec { let mut observation = StyleObservation::new(host); - let shared_lock = host.style_engine_author_shared_lock(); handles .into_iter() .map(|handle| { @@ -636,7 +634,7 @@ pub(crate) fn computed_style_own_inherited_property_values_for_document_snapshot }; observation .read(handle) - .computed_style_has_own_inherited_longhand_value(property, &shared_lock) + .computed_style_has_own_visibility_value() }) .collect() } 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 d0dff7c0d8e..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,14 +220,12 @@ impl<'a> ComputedStyleRead<'a> { Some(self.stylo_style.as_ref()?.rendered_style_facts()) } - pub(in crate::native_bridge::element) fn computed_style_has_own_inherited_longhand_value( + pub(in crate::native_bridge::element) fn computed_style_has_own_visibility_value( &self, - property: &str, - shared_lock: &style::shared_lock::SharedRwLock, ) -> bool { self.stylo_style .as_ref() - .is_some_and(|style| style.has_own_inherited_longhand_value(property, shared_lock)) + .is_some_and(StyloComputedStyleSnapshot::has_own_visibility_value) } pub(crate) fn computed_values(&self) -> Option> { diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 16845bf53b2..7c0e6e9c9ae 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -97,40 +97,20 @@ impl PageVm { ); let own_visibility_values = self .vm() - .computed_style_own_inherited_property_values_for_document_snapshot( - nodes.iter().copied(), - "visibility", - ); + .computed_style_own_visibility_values_for_document_snapshot(nodes.iter().copied()); let own_visibility: HashMap<_, _> = nodes.iter().copied().zip(own_visibility_values).collect(); - let (keyframe_scopes, keyframe_rules) = self - .vm() - .effective_keyframe_rule_texts_for_element_snapshots(nodes.iter().copied()); - let final_opacity_by_scope: HashMap<_, _> = keyframe_rules - .into_iter() - .map(|(scope, stylesheet_texts)| { - ( - scope, - visibility::final_opacity_animation_names( - stylesheet_texts.iter().map(String::as_str), - ), - ) - }) - .collect(); - let final_opacity_animations: HashMap<_, _> = nodes + let animation_candidates = nodes .iter() .copied() - .zip(keyframe_scopes) - .map(|(node, scope)| { - ( - node, - final_opacity_by_scope - .get(&scope) - .cloned() - .unwrap_or_default(), - ) - }) - .collect(); + .zip(values.iter()) + .filter(|(_, values)| values.get(2).is_some_and(|value| value == "0")) + .map(|(node, values)| { + (node, visibility::computed_property_animation_names(values)) + }); + let final_opacity_animations = self + .vm() + .final_opacity_animation_names_for_element_snapshots(animation_candidates); let styles = nodes .into_iter() .zip(values) diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index c0dadc9f56e..e29e0fff442 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -415,10 +415,7 @@ fn has_bounded_final_opacity( values: &[String], final_opacity_animations: &HashSet, ) -> bool { - let names: Vec<_> = values - .get(14) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); + let names = parse_animation_names(values.get(14)); let durations: Vec<_> = values .get(15) .map(|value| value.split(',').map(str::trim).collect()) @@ -444,7 +441,7 @@ fn has_bounded_final_opacity( .map(|value| value.split(',').map(str::trim).collect()) .unwrap_or_default(); names.iter().enumerate().any(|(index, name)| { - final_opacity_animations.contains(*name) + final_opacity_animations.contains(name) && !durations.is_empty() && animation_duration_is_positive(durations[index % durations.len()]) && !fill_modes.is_empty() @@ -461,6 +458,23 @@ fn has_bounded_final_opacity( }) } +pub(super) fn computed_property_animation_names(values: &[String]) -> Vec { + parse_animation_names(values.get(8)) +} + +fn parse_animation_names(value: Option<&String>) -> Vec { + value + .map(|value| { + value + .split(',') + .map(str::trim) + .filter(|name| !name.is_empty() && *name != "none") + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() +} + fn animation_duration_is_positive(duration: &str) -> bool { animation_time_seconds(duration).is_some_and(|duration| duration > 0.0) } @@ -477,79 +491,6 @@ fn animation_time_seconds(value: &str) -> Option { }) } -/// Return only animations whose declared final keyframe paints a nonzero -/// opacity. The caller still requires a finite, forward, running animation -/// before using that final authored state for the static document snapshot. -pub(super) fn final_opacity_animation_names<'a>( - stylesheets: impl IntoIterator, -) -> HashSet { - let mut result = HashSet::new(); - for source in stylesheets { - let folded = source.to_ascii_lowercase(); - for offset in code_marker_offsets(&folded, "@keyframes") { - let Some(relative_open) = source[offset..].find('{') else { - continue; - }; - let open = offset + relative_open; - let Some(close) = matching_delimiter(source, open, '{', '}') else { - continue; - }; - let Some(rule) = - moli_css_parse::parse_keyframes_rule_view_with_stylo(&source[offset..=close]) - else { - continue; - }; - let Some(canonical_open) = rule.css_text.find('{') else { - continue; - }; - let Some(canonical_close) = - matching_delimiter(&rule.css_text, canonical_open, '{', '}') - else { - continue; - }; - let name = rule.name; - if final_keyframe_reveals(&rule.css_text[canonical_open + 1..canonical_close]) { - result.insert(name); - } else { - result.remove(&name); - } - } - } - result -} - -fn final_keyframe_reveals(body: &str) -> bool { - let mut offset = 0; - while let Some(relative_open) = body[offset..].find('{') { - let open = offset + relative_open; - let selector = body[offset..open].trim(); - let Some(close) = matching_delimiter(body, open, '{', '}') else { - return false; - }; - let is_final = selector - .split(',') - .map(str::trim) - .any(|value| matches!(value, "to" | "100%" | "100.0%")); - if is_final { - for declaration in body[open + 1..close].split(';') { - let Some((name, value)) = declaration.split_once(':') else { - continue; - }; - if name.trim().eq_ignore_ascii_case("opacity") - && value - .trim() - .parse::() - .is_ok_and(|opacity| opacity > 0.0) - { - return true; - } - } - } - offset = close + 1; - } - false -} - fn target_is_disclosure( dom: &D, targets: &HashMap<&str, D::NodeId>, @@ -564,119 +505,6 @@ fn target_is_disclosure( }) } -fn code_marker_offsets(value: &str, marker: &str) -> Vec { - let mut result = Vec::new(); - let mut offset = 0; - let mut quote = None; - let mut escaped = false; - let mut line_comment = false; - let mut block_comment = false; - while offset < value.len() { - let tail = &value[offset..]; - if line_comment { - if tail.starts_with('\n') { - line_comment = false; - } - } else if block_comment { - if tail.starts_with("*/") { - block_comment = false; - offset += 2; - continue; - } - } else if let Some(delimiter) = quote { - let character = tail.chars().next().expect("offset is within value"); - if escaped { - escaped = false; - } else if character == '\\' { - escaped = true; - } else if character == delimiter { - quote = None; - } - } else if tail.starts_with("//") { - line_comment = true; - offset += 2; - continue; - } else if tail.starts_with("/*") { - block_comment = true; - offset += 2; - continue; - } else { - let character = tail.chars().next().expect("offset is within value"); - if matches!(character, '\'' | '"' | '`') { - quote = Some(character); - } else if tail.starts_with(marker) { - result.push(offset); - offset += marker.len(); - continue; - } - } - offset += tail - .chars() - .next() - .expect("offset is within value") - .len_utf8(); - } - result -} - -fn matching_delimiter(value: &str, start: usize, open: char, close: char) -> Option { - let mut depth = 0; - let mut quote = None; - let mut escaped = false; - let mut line_comment = false; - let mut block_comment = false; - let mut offset = start; - while offset < value.len() { - let tail = &value[offset..]; - if line_comment { - if tail.starts_with('\n') { - line_comment = false; - } - } else if block_comment { - if tail.starts_with("*/") { - block_comment = false; - offset += 2; - continue; - } - } else if let Some(delimiter) = quote { - let character = tail.chars().next().expect("offset is within value"); - if escaped { - escaped = false; - } else if character == '\\' { - escaped = true; - } else if character == delimiter { - quote = None; - } - } else if tail.starts_with("//") { - line_comment = true; - offset += 2; - continue; - } else if tail.starts_with("/*") { - block_comment = true; - offset += 2; - continue; - } else { - let character = tail.chars().next().expect("offset is within value"); - if matches!(character, '\'' | '"' | '`') { - quote = Some(character); - } else if character == open { - depth += 1; - } else if character == close { - depth -= 1; - if depth == 0 { - return Some(offset); - } - } - } - offset += tail - .chars() - .next() - .expect("offset is within value") - .len_utf8(); - } - None -} - fn px(value: &str) -> Option { value.strip_suffix("px")?.trim().parse().ok() } 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 index 32283a9bb47..6cda0534b00 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -184,16 +184,23 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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 = ''; @@ -216,6 +223,28 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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#" + 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 = ` diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs index da883c5c4af..d7fac84a484 100644 --- a/moli-renderer-v8/src/script_vm/layout.rs +++ b/moli-renderer-v8/src/script_vm/layout.rs @@ -70,16 +70,13 @@ impl ScriptVm { read(host.dom_host(), &mut input) } - pub(crate) fn effective_keyframe_rule_texts_for_element_snapshots( + pub(crate) fn final_opacity_animation_names_for_element_snapshots( &self, - elements: impl IntoIterator, - ) -> ( - Vec>, - std::collections::HashMap, Vec>, - ) { + elements: impl IntoIterator)>, + ) -> std::collections::HashMap> { let host = self._context_host.borrow(); let document = host.document_handle(); - host.effective_keyframe_rule_texts_for_elements(document, elements) + host.final_opacity_animation_names_for_elements(document, elements) } pub(crate) fn sync_live_document_style_sources(&mut self) { @@ -101,15 +98,13 @@ impl ScriptVm { ) } - pub(crate) fn computed_style_own_inherited_property_values_for_document_snapshot( + pub(crate) fn computed_style_own_visibility_values_for_document_snapshot( &self, handles: impl IntoIterator, - property: &str, ) -> Vec { - crate::native_bridge::element::computed_style_own_inherited_property_values_for_document_snapshot( + crate::native_bridge::element::computed_style_own_visibility_values_for_document_snapshot( &self._context_host.borrow(), handles, - property, ) } diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index c44c2f1f37c..fe7ffa3ab90 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -1,10 +1,12 @@ use std::collections::HashSet; +#[cfg(test)] +use std::sync::atomic::{AtomicUsize, Ordering}; use dom::ElementState as StyloElementState; use style::{ Atom, animation::DocumentAnimationSet, - applicable_declarations::{CascadePriority, RevertKind}, + computed_value_flags::ComputedValueFlags, context::{ QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext, StyleContext, StyleSystemOptions, ThreadLocalStyleContext, @@ -12,7 +14,7 @@ use style::{ data::ElementStyles, dom::{TElement, TNode}, properties::{ - CSSWideKeyword, ComputedValues, PropertyDeclaration, PropertyDeclarationId, PropertyId, + ComputedValues, PropertyId, longhands::{ text_wrap_mode::computed_value::T as StyloTextWrapMode, visibility::computed_value::T as ComputedVisibility, @@ -21,8 +23,10 @@ use style::{ parse_style_attribute, }, selector_parser::{PseudoElement, SnapshotMap}, + servo::animation::final_keyframe_opacity, servo_arc::Arc as ServoArc, shared_lock::StylesheetGuards, + style_resolver::{PseudoElementResolution, StyleResolverForElement}, stylesheets::{CssRuleType, UrlExtraData}, stylist::RuleInclusion, thread_state::{self, ThreadState}, @@ -44,6 +48,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, @@ -285,65 +302,12 @@ impl StyloComputedStyleSnapshot { serialize_raw_computed_property(&self.primary, property_id) } - /// Whether this element's cascade supplies a value for an inherited - /// longhand instead of taking the value from its parent. - /// - /// Computed values alone cannot distinguish `visibility:hidden` declared - /// on an element from the same value inherited from an ancestor. Consumers - /// that selectively expose an otherwise hidden subtree need that source - /// distinction, but should not parse inline style or stylesheet text a - /// second time. - pub(crate) fn has_own_inherited_longhand_value( - &self, - property: &str, - shared_lock: &style::shared_lock::SharedRwLock, - ) -> bool { - let Ok(property_id) = PropertyId::parse_enabled_for_all_content(property) else { - return false; - }; - let Some(longhand) = property_id.longhand_id() else { - return false; - }; - let guard = shared_lock.read(); - let guards = StylesheetGuards::same(&guard); - let mut reverted: Option<(CascadePriority, RevertKind)> = None; - for node in self.primary.rules().self_and_ancestors() { - let priority = node.cascade_priority(); - if reverted.is_some_and(|(reverted_priority, kind)| { - !reverted_priority.allows_when_reverted(&priority, kind) - }) { - continue; - } - let Some(source) = node.style_source() else { - continue; - }; - for (declaration, importance) in source - .read(node.cascade_level().guard(&guards)) - .declaration_importance_iter() - .rev() - { - if importance.important() != node.importance().important() - || declaration.id() != PropertyDeclarationId::Longhand(longhand) - { - continue; - } - match declaration.get_css_wide_keyword() { - Some(CSSWideKeyword::Inherit | CSSWideKeyword::Unset) => return false, - Some(keyword) if keyword.revert_kind().is_some() => { - reverted = Some((priority, keyword.revert_kind().unwrap())); - continue; - } - _ => {} - } - // Variable substitution happens inside Stylo's cascade. A raw - // `WithVariables` declaration cannot establish an independent - // hidden boundary here: it may be invalid at computed-value - // time or resolve to `inherit`. Treat it conservatively as - // inherited instead of recreating the substitution engine. - return !matches!(declaration, PropertyDeclaration::WithVariables(_)); - } - } - false + /// 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 { @@ -389,6 +353,82 @@ pub(super) fn retained_current_element_state( })? } +pub(super) fn retained_final_opacity_animation_names( + engine: &MoliStyleEngine, + host: &DomHost, + document: DomHandle, + elements: impl IntoIterator)>, +) -> std::collections::HashMap> { + 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, names)| { + let element = dom_adapter.element(host, handle)?; + let base_style = element.borrow_data()?.styles.primary().clone(); + let revealing = names + .into_iter() + .filter(|name| { + #[cfg(test)] + FINAL_OPACITY_ANIMATION_QUERY_COUNT.fetch_add(1, Ordering::Relaxed); + let atom = Atom::from(name.as_str()); + let Some(animation) = retained.stylist.lookup_keyframes(&atom, element) + else { + return false; + }; + let mut resolver = StyleResolverForElement::new( + element, + &mut context, + RuleInclusion::All, + PseudoElementResolution::IfApplicable, + ); + let opacity = final_keyframe_opacity( + element, + animation, + &shared, + &base_style, + &mut resolver, + ); + opacity.is_some_and(|opacity| opacity > 0.0) + }) + .collect::>(); + (!revealing.is_empty()).then_some((handle, revealing)) + }) + .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 fa4191c0f72..dc2b0b7437a 100644 --- a/moli-renderer-v8/src/style_engine/mod.rs +++ b/moli-renderer-v8/src/style_engine/mod.rs @@ -35,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; @@ -327,58 +332,13 @@ impl MoliStyleEngine { }) } - pub(crate) fn effective_keyframe_rule_texts_for_tree_scopes( + pub(crate) fn final_opacity_animation_names_for_elements( &self, + host: &DomHost, document: DomHandle, - tree_scopes: impl IntoIterator>, - ) -> HashMap, Vec> { - let Some(world) = self.document_worlds.active_world(document) else { - return HashMap::new(); - }; - world - .document_state - .try_with_retained_style_system(|retained| { - let device = retained.stylist.device(); - let mut document_rules = Vec::new(); - let document_custom_media = retained - .stylist - .cascade_data() - .borrow_for_origin(style::stylesheets::Origin::Author) - .custom_media_map(); - for entry in retained.document_stylesheets.entries() { - document_rules.extend(stylesheet::native_effective_keyframe_rule_texts( - entry.stylesheet(), - device, - document_custom_media, - )); - } - let mut shadow_rules = HashMap::new(); - for scope in &retained.shadow_scopes { - let rules = shadow_rules.entry(scope.root()).or_insert_with(Vec::new); - for entry in scope.active_stylesheets().entries() { - rules.extend(stylesheet::native_effective_keyframe_rule_texts( - entry.stylesheet(), - device, - scope.author_styles().data.custom_media_map(), - )); - } - } - tree_scopes - .into_iter() - .collect::>() - .into_iter() - .map(|tree_scope| { - let mut rules = document_rules.clone(); - if let Some(tree_scope) = tree_scope - && let Some(scoped_rules) = shadow_rules.get(&tree_scope) - { - rules.extend(scoped_rules.iter().cloned()); - } - (tree_scope, rules) - }) - .collect() - }) - .unwrap_or_default() + elements: impl IntoIterator)>, + ) -> HashMap> { + computed::retained_final_opacity_animation_names(self, host, document, elements) } #[cfg(debug_assertions)] diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rs index aa2d2ef2e11..016a4d00618 100644 --- a/moli-renderer-v8/src/style_engine/stylesheet.rs +++ b/moli-renderer-v8/src/style_engine/stylesheet.rs @@ -218,25 +218,6 @@ pub(super) fn native_effective_font_face_rule_addresses( native_effective_font_face_rule_addresses_with_guard(stylesheet, device, custom_media, &guard) } -pub(super) fn native_effective_keyframe_rule_texts( - stylesheet: &DocumentStyleSheet, - device: &Device, - custom_media: &CustomMediaMap, -) -> Vec { - let guard = stylesheet.0.shared_lock.read(); - if !stylesheet.enabled() || !stylesheet.is_effective_for_device(device, custom_media, &guard) { - return Vec::new(); - } - stylesheet - .contents(&guard) - .effective_rules(device, custom_media, &guard) - .filter_map(|rule| match rule { - CssRule::Keyframes(rule) => Some(rule.read_with(&guard).to_css_string(&guard)), - _ => None, - }) - .collect() -} - fn native_effective_font_face_rule_addresses_with_guard( stylesheet: &DocumentStyleSheet, device: &Device, From 8c01910670e38a99b9193e3eafd8f0de02e083fc Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:23:01 +0800 Subject: [PATCH 18/21] chore(deps): retain regenerated lock resolution --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 857ff3e13c8..82d01309898 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]] @@ -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]] @@ -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]] From c078c4ac6d10441cf1fdf12da2258b7ee11060d7 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Wed, 30 Sep 2026 11:01:23 +0800 Subject: [PATCH 19/21] fix(content): preserve animation list semantics --- .../context_host/host_environment.rs | 8 +- moli-renderer-v8/src/runtime/page_dump.rs | 46 +++------- .../src/runtime/page_dump/visibility.rs | 91 +----------------- .../runtime/page_vm/tests/markdown_dump.rs | 30 ++++++ moli-renderer-v8/src/script_vm/layout.rs | 8 +- moli-renderer-v8/src/style_engine/computed.rs | 92 ++++++++++++------- moli-renderer-v8/src/style_engine/mod.rs | 8 +- 7 files changed, 116 insertions(+), 167 deletions(-) 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 d8ff52167d4..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,13 +1517,13 @@ impl JsContextHost { .retained_stylesheet_query_snapshot_for_document(document) } - pub(crate) fn final_opacity_animation_names_for_elements( + pub(crate) fn elements_with_bounded_final_opacity( &self, document: DomHandle, - elements: impl IntoIterator)>, - ) -> std::collections::HashMap> { + elements: impl IntoIterator, + ) -> std::collections::HashSet { self.style_engine - .final_opacity_animation_names_for_elements(self.dom_host(), document, elements) + .elements_with_bounded_final_opacity(self.dom_host(), document, elements) } #[cfg(test)] diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs index 7c0e6e9c9ae..8322693f038 100644 --- a/moli-renderer-v8/src/runtime/page_dump.rs +++ b/moli-renderer-v8/src/runtime/page_dump.rs @@ -15,8 +15,7 @@ impl PageVm { let markdown_base_url = (options.format == RendererPageDumpFormat::Markdown) .then(|| self.vm().document_runtime.dom_host().document_base_url()) .flatten(); - let (styles, final_opacity_animations) = if options.format - == RendererPageDumpFormat::Markdown + let (styles, final_opacity_elements) = if options.format == RendererPageDumpFormat::Markdown { let dom = self.vm().document_runtime.dom_host().dom(); let mut nodes = Vec::new(); @@ -86,13 +85,6 @@ impl PageVm { "top".to_owned(), "color".to_owned(), "text-shadow".to_owned(), - "animation-name".to_owned(), - "animation-duration".to_owned(), - "animation-fill-mode".to_owned(), - "animation-delay".to_owned(), - "animation-iteration-count".to_owned(), - "animation-direction".to_owned(), - "animation-play-state".to_owned(), ], ); let own_visibility_values = self @@ -105,23 +97,14 @@ impl PageVm { .copied() .zip(values.iter()) .filter(|(_, values)| values.get(2).is_some_and(|value| value == "0")) - .map(|(node, values)| { - (node, visibility::computed_property_animation_names(values)) - }); - let final_opacity_animations = self + .map(|(node, _)| node); + let final_opacity_elements = self .vm() - .final_opacity_animation_names_for_element_snapshots(animation_candidates); + .elements_with_bounded_final_opacity_for_document_snapshot(animation_candidates); let styles = nodes .into_iter() .zip(values) .map(|(node, mut values)| { - let animation_play_state = values.pop().unwrap_or_default(); - let animation_direction = values.pop().unwrap_or_default(); - let animation_iteration_count = values.pop().unwrap_or_default(); - let animation_delay = values.pop().unwrap_or_default(); - let animation_fill_mode = values.pop().unwrap_or_default(); - let animation_duration = values.pop().unwrap_or_default(); - let animation_name = values.pop().unwrap_or_default(); let text_shadow = values.pop().unwrap_or_default(); let foreground = values.pop().unwrap_or_default(); // Preserve the visibility adapter's stable field layout. @@ -153,13 +136,6 @@ impl PageVm { 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(animation_name); - values.push(animation_duration); - values.push(animation_fill_mode); - values.push(animation_delay); - values.push(animation_iteration_count); - values.push(animation_direction); - values.push(animation_play_state); values.push( own_visibility .get(&node) @@ -170,9 +146,9 @@ impl PageVm { (node, values) }) .collect::>(); - (styles, final_opacity_animations) + (styles, final_opacity_elements) } else { - (Vec::new(), HashMap::new()) + (Vec::new(), HashSet::new()) }; if options.format == RendererPageDumpFormat::Markdown && !options.with_base @@ -183,7 +159,7 @@ impl PageVm { self.vm().document_runtime.dom_host().dom(), styles, markdown_base_url.as_ref(), - final_opacity_animations, + final_opacity_elements, ); } let mut dom = self.vm().document_runtime.dom_host().dom().clone(); @@ -208,7 +184,7 @@ impl PageVm { &dom, styles, markdown_base_url.as_ref(), - final_opacity_animations, + final_opacity_elements, ), } } @@ -359,17 +335,17 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String { - render_markdown_document_with_styles(dom, Vec::new(), None, HashMap::new()) + 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_animations: HashMap>, + 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_animations); + 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()), diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs index e29e0fff442..efbd79caeec 100644 --- a/moli-renderer-v8/src/runtime/page_dump/visibility.rs +++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs @@ -34,7 +34,7 @@ impl<'a> MarkdownDom<'a> { dom: &'a NativeDom, styles: impl IntoIterator)>, base_url: Option<&Url>, - final_opacity_animations: HashMap>, + final_opacity_elements: HashSet, ) -> Self { let styles: Vec<_> = styles.into_iter().collect(); let document_element = dom.document_element_node_id(); @@ -283,12 +283,12 @@ impl<'a> MarkdownDom<'a> { } else if matches!(computed_visibility, "hidden" | "collapse") { match parent_visibility { VisibilityMode::RootVeil - if values.get(21).is_none_or(|value| value != "true") => + if values.get(14).is_none_or(|value| value != "true") => { VisibilityMode::RootVeil } VisibilityMode::DisclosureVeil - if values.get(21).is_none_or(|value| value != "true") => + if values.get(14).is_none_or(|value| value != "true") => { VisibilityMode::DisclosureVeil } @@ -298,15 +298,12 @@ impl<'a> MarkdownDom<'a> { parent_visibility }; visibility_modes.insert(node, visibility_mode); - let has_bounded_final_opacity = final_opacity_animations - .get(&node) - .is_some_and(|names| has_bounded_final_opacity(&values, names)); if ((values.first().is_some_and(|value| value == "none") || values .get(2) .is_some_and(|value| value.parse::() == Ok(0.0)) && !lazy_media - && !has_bounded_final_opacity + && !final_opacity_elements.contains(&node) && !document_root) && !disclosure_root && !disclosure_path) @@ -411,86 +408,6 @@ impl<'a> MarkdownDom<'a> { } } -fn has_bounded_final_opacity( - values: &[String], - final_opacity_animations: &HashSet, -) -> bool { - let names = parse_animation_names(values.get(14)); - let durations: Vec<_> = values - .get(15) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); - let fill_modes: Vec<_> = values - .get(16) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); - let delays: Vec<_> = values - .get(17) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); - let iteration_counts: Vec<_> = values - .get(18) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); - let directions: Vec<_> = values - .get(19) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); - let play_states: Vec<_> = values - .get(20) - .map(|value| value.split(',').map(str::trim).collect()) - .unwrap_or_default(); - names.iter().enumerate().any(|(index, name)| { - final_opacity_animations.contains(name) - && !durations.is_empty() - && animation_duration_is_positive(durations[index % durations.len()]) - && !fill_modes.is_empty() - && matches!(fill_modes[index % fill_modes.len()], "forwards" | "both") - && !delays.is_empty() - && animation_time_seconds(delays[index % delays.len()]) - .is_some_and(|delay| delay <= 0.0) - && !iteration_counts.is_empty() - && iteration_counts[index % iteration_counts.len()].parse::() == Ok(1.0) - && !directions.is_empty() - && directions[index % directions.len()] == "normal" - && !play_states.is_empty() - && play_states[index % play_states.len()] == "running" - }) -} - -pub(super) fn computed_property_animation_names(values: &[String]) -> Vec { - parse_animation_names(values.get(8)) -} - -fn parse_animation_names(value: Option<&String>) -> Vec { - value - .map(|value| { - value - .split(',') - .map(str::trim) - .filter(|name| !name.is_empty() && *name != "none") - .map(str::to_owned) - .collect() - }) - .unwrap_or_default() -} - -fn animation_duration_is_positive(duration: &str) -> bool { - animation_time_seconds(duration).is_some_and(|duration| duration > 0.0) -} - -fn animation_time_seconds(value: &str) -> Option { - value - .strip_suffix("ms") - .and_then(|value| value.trim().parse::().ok()) - .map(|value| value / 1000.0) - .or_else(|| { - value - .strip_suffix('s') - .and_then(|value| value.trim().parse::().ok()) - }) -} - fn target_is_disclosure( dom: &D, targets: &HashMap<&str, D::NodeId>, 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 index 6cda0534b00..3c643a3bb21 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -235,6 +235,36 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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

`; + "#).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", + ] { + assert!(animation_lists.contains(text), "missing {text}: {animation_lists}"); + } + for text in ["Wrong slot hidden99", "Reveal then conceal 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}"); + } 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(''); diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs index d7fac84a484..723f175f74b 100644 --- a/moli-renderer-v8/src/script_vm/layout.rs +++ b/moli-renderer-v8/src/script_vm/layout.rs @@ -70,13 +70,13 @@ impl ScriptVm { read(host.dom_host(), &mut input) } - pub(crate) fn final_opacity_animation_names_for_element_snapshots( + pub(crate) fn elements_with_bounded_final_opacity_for_document_snapshot( &self, - elements: impl IntoIterator)>, - ) -> std::collections::HashMap> { + elements: impl IntoIterator, + ) -> std::collections::HashSet { let host = self._context_host.borrow(); let document = host.document_handle(); - host.final_opacity_animation_names_for_elements(document, elements) + host.elements_with_bounded_final_opacity(document, elements) } pub(crate) fn sync_live_document_style_sources(&mut self) { diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index fe7ffa3ab90..894cf6cc99a 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -14,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, @@ -33,7 +33,9 @@ use style::{ traversal::resolve_style, traversal_flags::TraversalFlags, values::{ - AtomIdent, resolved, + AtomIdent, + computed::{AnimationDirection, AnimationFillMode, AnimationPlayState}, + resolved, specified::{ box_::{ContentVisibility, Display, DisplayInside, DisplayOutside}, text::TextTransformCase, @@ -353,12 +355,12 @@ pub(super) fn retained_current_element_state( })? } -pub(super) fn retained_final_opacity_animation_names( +pub(super) fn retained_elements_with_bounded_final_opacity( engine: &MoliStyleEngine, host: &DomHost, document: DomHandle, - elements: impl IntoIterator)>, -) -> std::collections::HashMap> { + elements: impl IntoIterator, +) -> HashSet { let elements: Vec<_> = elements.into_iter().collect(); if elements.is_empty() { return Default::default(); @@ -393,36 +395,60 @@ pub(super) fn retained_final_opacity_animation_names( }; elements .into_iter() - .filter_map(|(handle, names)| { + .filter_map(|handle| { let element = dom_adapter.element(host, handle)?; let base_style = element.borrow_data()?.styles.primary().clone(); - let revealing = names - .into_iter() - .filter(|name| { - #[cfg(test)] - FINAL_OPACITY_ANIMATION_QUERY_COUNT.fetch_add(1, Ordering::Relaxed); - let atom = Atom::from(name.as_str()); - let Some(animation) = retained.stylist.lookup_keyframes(&atom, element) - else { - return false; - }; - let mut resolver = StyleResolverForElement::new( - element, - &mut context, - RuleInclusion::All, - PseudoElementResolution::IfApplicable, - ); - let opacity = final_keyframe_opacity( - element, - animation, - &shared, - &base_style, - &mut resolver, - ); - opacity.is_some_and(|opacity| opacity > 0.0) - }) - .collect::>(); - (!revealing.is_empty()).then_some((handle, revealing)) + 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 bounded = ui.animation_duration_mod(index).seconds() > 0.0 + && matches!( + ui.animation_fill_mode_mod(index), + AnimationFillMode::Forwards | AnimationFillMode::Both + ) + && 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 !bounded { + final_opacity_is_known = false; + continue; + } + let mut resolver = StyleResolverForElement::new( + element, + &mut context, + RuleInclusion::All, + PseudoElementResolution::IfApplicable, + ); + if let Some(opacity) = final_keyframe_opacity( + element, + animation, + &shared, + &base_style, + &mut resolver, + ) { + final_opacity = Some(opacity); + final_opacity_is_known = true; + } else { + final_opacity_is_known = false; + } + } + (final_opacity_is_known && final_opacity.is_some_and(|value| value > 0.0)) + .then_some(handle) }) .collect() }) diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs index dc2b0b7437a..67834c6ce4e 100644 --- a/moli-renderer-v8/src/style_engine/mod.rs +++ b/moli-renderer-v8/src/style_engine/mod.rs @@ -332,13 +332,13 @@ impl MoliStyleEngine { }) } - pub(crate) fn final_opacity_animation_names_for_elements( + pub(crate) fn elements_with_bounded_final_opacity( &self, host: &DomHost, document: DomHandle, - elements: impl IntoIterator)>, - ) -> HashMap> { - computed::retained_final_opacity_animation_names(self, host, document, elements) + elements: impl IntoIterator, + ) -> HashSet { + computed::retained_elements_with_bounded_final_opacity(self, host, document, elements) } #[cfg(debug_assertions)] From ee104dfdef2183f60b0898667b024718943388dd Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Wed, 30 Sep 2026 11:28:30 +0800 Subject: [PATCH 20/21] fix(content): compose final animation effects --- .../runtime/page_vm/tests/markdown_dump.rs | 28 ++++++++++++-- moli-renderer-v8/src/style_engine/computed.rs | 38 +++++++++++++------ 2 files changed, 51 insertions(+), 15 deletions(-) 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 index 3c643a3bb21..59e21f4ecca 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs @@ -236,7 +236,7 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { 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.head.innerHTML = ''; document.body.innerHTML = `

Leading none kept

Middle none kept

@@ -245,7 +245,15 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {

Escaped name kept

Reveal then conceal hidden992

Conceal then reveal kept

-

Reveal then transform 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)); @@ -256,14 +264,28 @@ async fn markdown_uses_live_visibility_and_preserves_disclosure_content() { "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"] { + 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(''); diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index 894cf6cc99a..761e1a66801 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -23,7 +23,7 @@ use style::{ parse_style_attribute, }, selector_parser::{PseudoElement, SnapshotMap}, - servo::animation::final_keyframe_opacity, + servo::animation::{FinalKeyframeOpacity, final_keyframe_opacity}, servo_arc::Arc as ServoArc, shared_lock::StylesheetGuards, style_resolver::{PseudoElementResolution, StyleResolverForElement}, @@ -415,16 +415,26 @@ pub(super) fn retained_elements_with_bounded_final_opacity( if !animation.properties_changed.contains(opacity_property) { continue; } - let bounded = ui.animation_duration_mod(index).seconds() > 0.0 - && matches!( - ui.animation_fill_mode_mod(index), - AnimationFillMode::Forwards | AnimationFillMode::Both - ) + 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 !bounded { + 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; } @@ -434,17 +444,21 @@ pub(super) fn retained_elements_with_bounded_final_opacity( RuleInclusion::All, PseudoElementResolution::IfApplicable, ); - if let Some(opacity) = final_keyframe_opacity( + match final_keyframe_opacity( element, animation, &shared, &base_style, &mut resolver, ) { - final_opacity = Some(opacity); - final_opacity_is_known = true; - } else { - final_opacity_is_known = false; + 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)) From 4f556a687c93fe0c10c445ed0f3350f87209f227 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:14:06 +0800 Subject: [PATCH 21/21] chore(deps): restore content style support --- Cargo.lock | 22 +++++++++++----------- Cargo.toml | 14 +++++++------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 82d01309898..394944ae5e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", @@ -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", 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" }