").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
\na|b
\n <a>|b\nnext\n
\n",
- "{markdown}"
+ let html = support::rendered_html(&markdown);
+ assert!(html.contains("a|b"), "{html}");
+ assert_eq!(html.matches("").count(), 2);
+ let parsed = support::Tree::parse(&html);
+ assert!(
+ parsed
+ .nodes
+ .iter()
+ .any(|node| node.text.as_deref() == Some(" |b\nnext\n")),
+ "{html}"
);
}
diff --git a/moli-html2md/tests/inline_boundaries.rs b/moli-html2md/tests/inline_boundaries.rs
index 51fe74785ac..fc45b31df12 100644
--- a/moli-html2md/tests/inline_boundaries.rs
+++ b/moli-html2md/tests/inline_boundaries.rs
@@ -20,7 +20,6 @@ fn inline_code_breaks_separate_words_without_formatting_markers() {
for html in [
"git status",
"git status",
- "git status",
] {
for preformatted_code in [false, true] {
let result = markdown_with(
diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs
index f5e12486a8b..88bb7e28e2f 100644
--- a/moli-html2md/tests/regressions.rs
+++ b/moli-html2md/tests/regressions.rs
@@ -12,6 +12,278 @@ fn markdown(html: &str, preformatted_code: bool) -> String {
.convert(&dom, dom.root)
}
+#[test]
+fn scientific_indices_keep_their_meaning_in_markdown() {
+ let result = markdown(
+ "Water H2O; area x2; note1. ",
+ false,
+ );
+ assert!(result.contains("H2O"), "{result}");
+ assert!(result.contains("x2"), "{result}");
+ let html = rendered_html(&result);
+ assert!(html.contains("1"), "{html}");
+}
+
+#[test]
+fn tex_math_keeps_commands_indices_and_matrix_separators() {
+ let source = r"Model $x_i^2 + \alpha$ and $$\begin{matrix} a & b \\ c & d \end{matrix}$$. ";
+ let result = markdown(source, false);
+ assert!(result.contains(r"$x_i^2 + \alpha$"), "{result}");
+ assert!(
+ result.contains(r"$$\begin{matrix} a & b \\ c & d \end{matrix}$$"),
+ "{result}"
+ );
+}
+
+#[test]
+fn math_recognition_does_not_reinterpret_prices_or_literal_code() {
+ let result = markdown(
+ r"Pay $5 for a_b and $10 for c_d; $x_i$; $unfinished_name ",
+ false,
+ );
+ assert!(result.contains(r"$5 for a\_b and $10 for c\_d"), "{result}");
+ assert!(result.contains("`$x_i$`"), "{result}");
+ assert!(result.contains(r"$unfinished\_name"), "{result}");
+ let result = markdown(r"括号 \(x_i + \alpha\);方括号 \[y_1=2\]。 ", false);
+ assert!(result.contains(r"\(x_i + \alpha\)"), "{result}");
+ assert!(result.contains(r"\[y_1=2\]"), "{result}");
+}
+
+#[test]
+fn dollar_wrapped_literal_html_remains_inert_without_a_math_extension() {
+ let result = markdown(r"$<img src=x onerror=alert(1)>_i$ ", false);
+ let html = rendered_html(&result);
+ assert!(!html.contains(" $x_i + \alpha$", false);
+ let payloads: Vec<_> = Parser::new_ext(&result, MarkdownOptions::ENABLE_MATH)
+ .filter_map(|event| match event {
+ Event::InlineMath(text) => Some(text.into_string()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(payloads, [r"x_i + \alpha"]);
+}
+
+#[test]
+fn mathematical_structures_survive_markdown_rendering() {
+ let source = "Rate . ";
+ 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(
+ "NewsActual story ",
+ false,
+ );
+ assert!(result.contains("Actual story"));
+ assert!(result.contains("Publisher"));
+ assert!(!result.contains("Untitled template"), "{result}");
+ let graphic = markdown(
+ "Template 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 ",
+ 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(
+ " ",
+ false,
+ ),
+ ""
+ );
+}
+
+#[test]
+fn concrete_loaded_image_wins_over_an_unexpanded_lazy_template() {
+ let result = markdown(
+ " ",
+ false,
+ );
+ assert_eq!(result, "");
+}
+
+#[test]
+fn lazy_media_uses_declared_resources_instead_of_spacers() {
+ let source = "  ";
+ 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(
+ "",
+ 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 = "";
+ let result = markdown(source, false);
+ let html = rendered_html(&result);
+ assert!(html.contains(" | | 1 | "), "{html}");
+ assert!(
+ html.contains("Group | A | "),
+ "{html}"
+ );
+ assert_eq!(html.matches(">Group<").count(), 1);
+}
+
+#[test]
+fn nested_tables_stay_with_their_column_labels() {
+ let source = "";
+ let html = rendered_html(&markdown(source, false));
+ assert!(html.contains("Today | Month | "), "{html}");
+ assert!(html.contains(""), "{html}");
+ assert!(html.contains("| Alice | 20 | "), "{html}");
+ assert!(html.contains("Bob | 100 | "), "{html}");
+}
+
+#[test]
+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("<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 titleResource 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 = "";
+ 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 panel Email ";
+ 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 = "";
+ 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\nafter \n"
- );
+ assert_preserves_table(html);
+ assert!(rendered_html(&markdown(html)).contains("c|d"));
}
#[test]
fn wrapping_a_table_preserves_its_content() {
let data =
"";
- assert_eq!(
- markdown(&format!("")),
- markdown(data)
- );
+ assert_preserves_table(&format!(""));
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 | 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 [
"| one | two | ",
"| one | two | ",
@@ -285,15 +326,8 @@ fn unrepresentable_tables_expand_without_losing_or_duplicating_content() {
"| one | two | ",
"| one | two | extra | ",
] {
- let actual = markdown(&format!(
- ""
- ));
- let extra = if row.contains("extra") {
- "\n\nextra"
- } else {
- ""
- };
- assert_eq!(actual, format!("A\n\nB\n\none\n\ntwo{extra}"));
+ let source = format!("");
+ assert_preserves_table(&source);
}
for content in [
" code\nnext\n ",
@@ -303,14 +337,10 @@ fn unrepresentable_tables_expand_without_losing_or_duplicating_content() {
"",
] {
for cell in ["th", "td"] {
- let actual = markdown(&format!(
+ let source = format!(
"<{cell}>A{cell}><{cell}>B{cell}> | 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(
- ""
- ),
- "A\n\nB\n\none\n\ntwo\n\nthree\n\nfour"
+fn multiple_heading_rows_keep_their_hierarchy() {
+ assert_preserves_table(
+ "",
);
}
@@ -439,15 +466,16 @@ fn nested_tables_obey_the_conversion_depth_limit() {
let dom = Tree::parse(
"",
);
- 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(
+ "",
);
}
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(" ");
// Turndown emits the same Markdown. Matching it does not preserve the image.
- assert_eq!(result, "");
let actual_html = rendered_html(&result);
- assert_eq!(actual_html, "\n");
let desired_html = " \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 \nheading\")\n"
- );
let desired_html = "link \n";
- assert_ne!(
+ assert_eq!(
actual_html, desired_html,
"review the resolved link-title gap"
);
}
#[test]
-fn track_multiple_nested_spans_at_the_end_of_a_paragraph() {
+fn multiple_nested_spans_keep_their_styles_at_paragraph_end() {
// This predates the closing-edge fix: with no following character there
// is no punctuation fallback, but sibling delimiters can still mispair.
let result = markdown("xbc");
- assert_eq!(result, "***x**b**c***");
let actual_html = rendered_html(&result);
- assert_eq!(
- actual_html,
- "xbc** \n"
- );
let desired_html = "xbc \n";
- assert_ne!(
+ assert_eq!(
actual_html, desired_html,
"review the resolved sibling-span gap"
);
}
#[test]
-fn track_mixed_emphasis_markers_at_an_intraword_opening() {
+fn mixed_emphasis_markers_preserve_intraword_styles() {
// The opening check sees the text 'x', although the nested styles emit
// punctuation first. This is separate from closing a same-marker run.
let result = markdown("beforex");
- assert_eq!(result, "before*~~**x**~~*");
let actual_html = rendered_html(&result);
- assert_eq!(
- actual_html,
- "before*x* \n"
- );
let desired_html = "beforex \n";
- assert_ne!(
+ assert_eq!(
actual_html, desired_html,
"review the resolved mixed-marker gap"
);
diff --git a/moli-html2md/tests/turndown/README.md b/moli-html2md/tests/turndown/README.md
index 703252d8d2e..086e7c4689b 100644
--- a/moli-html2md/tests/turndown/README.md
+++ b/moli-html2md/tests/turndown/README.md
@@ -25,28 +25,30 @@ accepts equivalent delimiter choices and list indentation while detecting lost
text, incorrect links, changed paragraph/list structure, and visible delimiters.
There are also exact Markdown assertions in the original and regression suites.
-`expectations.json` documents 12 deliberate differences with exact Moli outputs.
+`expectations.json` documents 13 deliberate differences with exact Moli outputs.
These preserve bare pre blocks and avoid upstream losses of literal characters,
emphasis, whitespace, and list boundaries. They remain active assertions; no
case is skipped. A reference change that makes a difference obsolete also fails
the test. Separate converter tests cover GFM tables and strikethrough as Moli
extensions. Explicit table headers follow Turndown's GFM plugin; simple headerless
-tables receive empty headings. Complex tables retain the core's block expansion
-rather than the plugin's raw HTML fallback.
+tables receive empty headings. Complex tables retain content-only HTML so merged
+cells and nested tables keep their associations. Explicitly presentational tables
+still expand into blocks.
## Findings tracked outside the reference corpus
-The 12 exceptions above describe this corpus, not every design difference or
+The 13 exceptions above describe this corpus, not every design difference or
every correctness issue. [tracking.rs](../tracking.rs) records these open review
findings with active assertions of both Markdown and rendered HTML:
| Tests | Status | Current behavior and comparison |
| --- | --- | --- |
| `track_nested_list_spacing_through_a_transparent_wrapper`, `track_nested_list_spacing_before_a_trailing_empty_element` | Open compatibility decision | Moli keeps the outer list tight when an `ins` wraps the nested list or an empty `span` follows it. Turndown makes it loose. Both preserve the list items. |
-| `track_multiline_image_alt_becoming_a_heading` | Open bug, also present in Turndown | An image alt containing `first\n# heading` breaks the image into text and a heading. The desired HTML retains the image and its full label. |
-| `track_multiline_link_title_becoming_a_heading` | Open bug, also present in Turndown | A link title containing `first\n# heading` breaks the link into text and a heading. The desired HTML retains the link and its multiline title. |
-| `track_multiple_nested_spans_at_the_end_of_a_paragraph` | Open bug, also present in Turndown | `xbc` produces ambiguous star delimiters at paragraph end, losing the second strong span and exposing literal stars. |
-| `track_mixed_emphasis_markers_at_an_intraword_opening` | Open bug in Moli's emphasis/strikethrough extension | `beforex` loses outer emphasis because its opener precedes generated punctuation. |
+
+Multiline image labels and link titles, nested sibling emphasis at paragraph
+ends, and intraword mixed emphasis now have semantic regressions in
+[tracking.rs](../tracking.rs). Attribute line breaks cannot introduce Markdown
+blocks, and ambiguous emphasis boundaries retain their styles through inline HTML.
These tests are not ignored or expected to panic. A change to a recorded output
requires review; when fixing a bug, replace the current-output assertion with a
diff --git a/moli-html2md/tests/turndown/expectations.json b/moli-html2md/tests/turndown/expectations.json
index 9a9593aad97..cc813ee462f 100644
--- a/moli-html2md/tests/turndown/expectations.json
+++ b/moli-html2md/tests/turndown/expectations.json
@@ -43,6 +43,10 @@
"markdown": "before` `after",
"reason": "Explicit preformatted-code mode preserves the spaces inside code. Turndown removes a whitespace-only code element entirely."
},
+ "extra_missing_image_src": {
+ "markdown": "beforemissingafter",
+ "reason": "An unavailable image retains its existing text alternative. Dropping alt also removes the only accessible label from image-only navigation links; Turndown loses that text."
+ },
"extra_split_list_marker": {
"markdown": "12\\. text",
"reason": "Escape list markers across text-node boundaries. Turndown escapes nodes individually and accidentally creates an ordered list."
diff --git a/moli-renderer-v8/src/runtime/page_dump.rs b/moli-renderer-v8/src/runtime/page_dump.rs
index ee2f639de6a..35f45839294 100644
--- a/moli-renderer-v8/src/runtime/page_dump.rs
+++ b/moli-renderer-v8/src/runtime/page_dump.rs
@@ -2,18 +2,141 @@ use crate::dom::native::{NativeDom, NativeNodeId};
use crate::runtime::page_surface::{
RendererPageDumpFormat, RendererPageDumpOptions, RendererPageDumpStripOptions,
};
+use moli_html2md::{Dom, NodeKind};
use moli_page_types::MAX_DOM_OUTPUT_TREE_DEPTH;
+use std::collections::HashMap;
use super::page_vm::PageVm;
+mod visibility;
+
impl PageVm {
pub(crate) fn render_page_dump(&mut self, options: RendererPageDumpOptions) -> String {
+ let markdown_base_url = (options.format == RendererPageDumpFormat::Markdown)
+ .then(|| self.vm().document_runtime.dom_host().document_base_url())
+ .flatten();
+ let styles = if options.format == RendererPageDumpFormat::Markdown {
+ let dom = self.vm().document_runtime.dom_host().dom();
+ let mut nodes = Vec::new();
+ collect_node_ids(dom, dom.document_node_id(), &mut nodes);
+ nodes.retain(|node| {
+ dom.node(*node)
+ .is_some_and(|node| node.as_element().is_some())
+ });
+ let span_nodes: Vec<_> = nodes
+ .iter()
+ .copied()
+ .filter(|node| matches!(Dom::node_kind(dom, *node), NodeKind::Element("span")))
+ .collect();
+ let image_nodes: Vec<_> = nodes
+ .iter()
+ .copied()
+ .filter(|node| matches!(Dom::node_kind(dom, *node), NodeKind::Element("img")))
+ .collect();
+ let background_values = self
+ .vm()
+ .computed_style_property_values_for_document_snapshot(
+ nodes.iter().copied(),
+ &["background-color".to_owned()],
+ );
+ let backgrounds: HashMap<_, _> = nodes
+ .iter()
+ .copied()
+ .zip(background_values)
+ .filter_map(|(node, values)| values.into_iter().next().map(|value| (node, value)))
+ .collect();
+ let background_image_values = self
+ .vm()
+ .computed_style_property_values_for_document_snapshot(
+ nodes.iter().copied(),
+ &["background-image".to_owned()],
+ );
+ let background_images: HashMap<_, _> = nodes
+ .iter()
+ .copied()
+ .zip(background_image_values)
+ .filter_map(|(node, values)| values.into_iter().next().map(|value| (node, value)))
+ .collect();
+ let span_values = self
+ .vm()
+ .computed_style_property_values_for_document_snapshot(
+ span_nodes.iter().copied(),
+ &["bottom".to_owned(), "vertical-align".to_owned()],
+ );
+ let spans: HashMap<_, _> = span_nodes.into_iter().zip(span_values).collect();
+ let image_values = self
+ .vm()
+ .computed_style_property_values_for_document_snapshot(
+ image_nodes.iter().copied(),
+ &["width".to_owned(), "height".to_owned()],
+ );
+ let images: HashMap<_, _> = image_nodes.into_iter().zip(image_values).collect();
+ let values = self
+ .vm()
+ .computed_style_property_values_for_document_snapshot(
+ nodes.iter().copied(),
+ &[
+ "display".to_owned(),
+ "visibility".to_owned(),
+ "opacity".to_owned(),
+ "position".to_owned(),
+ "left".to_owned(),
+ "top".to_owned(),
+ "color".to_owned(),
+ "animation-name".to_owned(),
+ ],
+ );
+ nodes
+ .into_iter()
+ .zip(values)
+ .map(|(node, mut values)| {
+ let animation_name = values.pop().unwrap_or_default();
+ let foreground = values.pop().unwrap_or_default();
+ // Preserve the visibility adapter's stable field layout.
+ let span = spans.get(&node);
+ values.push(
+ span.and_then(|values| values.first())
+ .cloned()
+ .unwrap_or_default(),
+ );
+ values.push(
+ span.and_then(|values| values.get(1))
+ .cloned()
+ .unwrap_or_default(),
+ );
+ let image = images.get(&node);
+ values.push(
+ image
+ .and_then(|values| values.first())
+ .cloned()
+ .unwrap_or_default(),
+ );
+ values.push(
+ image
+ .and_then(|values| values.get(1))
+ .cloned()
+ .unwrap_or_default(),
+ );
+ values.push(foreground);
+ values.push(backgrounds.get(&node).cloned().unwrap_or_default());
+ values.push(animation_name);
+ values.push(background_images.get(&node).cloned().unwrap_or_default());
+ (node, values)
+ })
+ .collect::>()
+ } else {
+ Vec::new()
+ };
if options.format == RendererPageDumpFormat::Markdown
&& !options.with_base
&& !options.with_frames
&& options.strip == RendererPageDumpStripOptions::default()
{
- return render_markdown_document(self.vm().document_runtime.dom_host().dom());
+ return render_markdown_document_with_styles(
+ self.vm().document_runtime.dom_host().dom(),
+ styles,
+ markdown_base_url.as_ref(),
+ );
}
let mut dom = self.vm().document_runtime.dom_host().dom().clone();
@@ -33,7 +156,9 @@ impl PageVm {
match options.format {
RendererPageDumpFormat::Html => dom.serialize_document(),
- RendererPageDumpFormat::Markdown => render_markdown_document(&dom),
+ RendererPageDumpFormat::Markdown => {
+ render_markdown_document_with_styles(&dom, styles, markdown_base_url.as_ref())
+ }
}
}
@@ -181,14 +306,24 @@ fn collect_node_ids(dom: &NativeDom, node_id: NativeNodeId, out: &mut Vec String {
+ render_markdown_document_with_styles(dom, Vec::new(), None)
+}
+
+fn render_markdown_document_with_styles(
+ dom: &NativeDom,
+ styles: Vec<(NativeNodeId, Vec)>,
+ base_url: Option<&url::Url>,
+) -> String {
let root = dom.body_node_id().unwrap_or(dom.document_node_id());
+ let visible = visibility::MarkdownDom::new(dom, styles, base_url);
moli_html2md::Converter::new(moli_html2md::Options {
max_depth: MAX_DOM_OUTPUT_TREE_DEPTH,
default_code_language: Some("text".to_owned()),
..Default::default()
})
- .convert(dom, root)
+ .convert(&visible, root)
}
#[cfg(test)]
@@ -393,10 +528,31 @@ mod tests {
include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.html").to_owned(),
);
let before = dom.serialize_document();
- assert_eq!(
- render_markdown_document(&dom),
- include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.md").trim_end()
+ let markdown = render_markdown_document(&dom);
+ for content in [
+ "First story",
+ "42 points by",
+ "8 comments",
+ "Second story",
+ "7 points by",
+ "discuss",
+ "More",
+ ] {
+ assert!(markdown.contains(content), "missing {content}: {markdown}");
+ }
+ let positions = [
+ "First story",
+ "42 points by",
+ "Second story",
+ "7 points by",
+ "More",
+ ]
+ .map(|content| markdown.find(content).expect("checked above"));
+ assert!(
+ positions.windows(2).all(|pair| pair[0] < pair[1]),
+ "{markdown}"
);
+ assert!(markdown.contains("link",
- "[link](/a \"one\ntwo\")",
+ "[link](/a \"one
two\")",
),
(
" ",
- "",
+ "",
),
(
"",
"## [link](/a \"one
two\")",
),
- ("a b c", "abc"),
+ (
+ "a b c",
+ "alabelblabelc",
+ ),
] {
assert_eq!(markdown_from_html(html), expected, "{html}");
}
diff --git a/moli-renderer-v8/src/runtime/page_dump/visibility.rs b/moli-renderer-v8/src/runtime/page_dump/visibility.rs
new file mode 100644
index 00000000000..5c9c20d4e3e
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_dump/visibility.rs
@@ -0,0 +1,575 @@
+use std::collections::{HashMap, HashSet};
+
+use moli_html2md::{Dom, NodeKind};
+use url::Url;
+
+use crate::dom::native::{NativeDom, NativeNodeId};
+
+/// Read the current page's computed visibility without mutating the live DOM.
+/// Explicit disclosure content remains useful in a document dump, even while
+/// its tab or section is closed. Other non-rendered UI is not document text.
+pub(super) struct MarkdownDom<'a> {
+ dom: &'a NativeDom,
+ suppressed: HashSet,
+ invisible: HashSet,
+ blocks: HashSet,
+ inline_boundaries: HashSet,
+ superscripts: HashSet,
+ subscripts: HashSet,
+ resolved_urls: HashMap>,
+ fragment_links: bool,
+}
+
+impl<'a> MarkdownDom<'a> {
+ pub(super) fn new(
+ dom: &'a NativeDom,
+ styles: impl IntoIterator- )>,
+ base_url: Option<&Url>,
+ ) -> Self {
+ let styles: Vec<_> = styles.into_iter().collect();
+ let document_element = dom.document_element_node_id();
+ let body = dom.body_node_id();
+ let document_visibility_is_hidden = styles.iter().any(|(node, values)| {
+ (Some(*node) == document_element || Some(*node) == body)
+ && values
+ .get(1)
+ .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse"))
+ });
+ let fragment_links = styles.iter().any(|(node, _)| {
+ Dom::attribute(dom, *node, "href").is_some_and(|href| href.starts_with('#'))
+ });
+ // `styles` follows the document's preorder, so every element's parent
+ // has already been seen. Cache the painted ancestor background once;
+ // walking ancestors for every node is quadratic on deeply nested pages.
+ let mut effective_backgrounds = HashMap::new();
+ if styles
+ .iter()
+ .any(|(_, values)| values.get(11).is_some_and(|value| !value.is_empty()))
+ {
+ for (node, values) in &styles {
+ let own = values
+ .get(11)
+ .and_then(|value| css_color(value))
+ .filter(|color| color.3 > 0.99);
+ let inherited = dom
+ .parent_node(*node)
+ .and_then(|parent| effective_backgrounds.get(&parent).copied());
+ effective_backgrounds
+ .insert(*node, own.or(inherited).unwrap_or((255, 255, 255, 1.0)));
+ }
+ }
+ let mut disclosures = HashSet::new();
+ let mut excerpts = HashSet::new();
+ let targets: HashMap<_, _> = styles
+ .iter()
+ .filter_map(|(node, values)| {
+ (values.first().is_some_and(|value| value == "none"))
+ .then(|| Dom::attribute(dom, *node, "id").map(|id| (id, *node)))
+ .flatten()
+ })
+ .collect();
+ for (node, _) in &styles {
+ if (Dom::attribute(dom, *node, "aria-expanded").is_some()
+ || Dom::attribute(dom, *node, "role")
+ .is_some_and(|role| role.eq_ignore_ascii_case("tab")))
+ && let Some(targets) = Dom::attribute(dom, *node, "aria-controls")
+ {
+ disclosures.extend(targets.split_ascii_whitespace());
+ }
+ for attribute_name in dom.get_attribute_names(*node).unwrap_or_default() {
+ if !attribute_name.starts_with("on") {
+ continue;
+ }
+ let Some(handler) = Dom::attribute(dom, *node, &attribute_name) else {
+ continue;
+ };
+ for target in inline_disclosure_targets(handler) {
+ if let Some((&id, _)) = targets.get_key_value(target) {
+ disclosures.insert(id);
+ }
+ }
+ }
+ // Some pages pair a shortened paragraph with an explicitly linked
+ // hidden full-text copy. Keep the complete copy once; an unrelated
+ // dialog or a matching paragraph elsewhere is not such a pair.
+ for attribute in ["href", "data-src", "data-target"] {
+ let Some(id) =
+ Dom::attribute(dom, *node, attribute).and_then(|value| value.strip_prefix('#'))
+ else {
+ continue;
+ };
+ let Some(&target) = targets.get(id) else {
+ continue;
+ };
+ if Dom::attribute(dom, target, "role").is_some_and(|role| {
+ ["dialog", "alertdialog", "menu"]
+ .iter()
+ .any(|excluded| role.eq_ignore_ascii_case(excluded))
+ }) {
+ continue;
+ }
+ let mut ancestor = dom.parent_node(*node);
+ while let Some(paragraph) = ancestor {
+ if matches!(Dom::node_kind(dom, paragraph), NodeKind::Element("p")) {
+ if let Some(container) = dom.parent_node(paragraph)
+ && within(dom, target, container)
+ && !within(dom, target, paragraph)
+ {
+ let short = text(dom, paragraph, Some(*node));
+ let prefix = short
+ .strip_suffix("...")
+ .or_else(|| short.strip_suffix('…'));
+ if let Some(prefix) = prefix
+ .map(str::trim_end)
+ .filter(|prefix| !prefix.is_empty())
+ {
+ let full = text(dom, target, None);
+ if full.len() > prefix.len() && full.starts_with(prefix) {
+ disclosures.insert(id);
+ excerpts.insert(paragraph);
+ }
+ }
+ }
+ break;
+ }
+ ancestor = dom.parent_node(paragraph);
+ }
+ }
+ }
+ let mut suppressed = excerpts;
+ let mut invisible = HashSet::new();
+ let mut blocks = HashSet::new();
+ let mut inline_boundaries = HashSet::new();
+ let mut superscripts = HashSet::new();
+ let mut subscripts = HashSet::new();
+ let mut resolved_urls = HashMap::new();
+ for (node, values) in styles {
+ let role = Dom::attribute(dom, node, "role").unwrap_or_default();
+ // Lazy media often stays transparent until a scroll/load event.
+ // Its declared resource still belongs to the document, unlike
+ // transparent numeric placeholders or hidden UI text.
+ let lazy_media = matches!(
+ Dom::node_kind(dom, node),
+ NodeKind::Element("img" | "iframe" | "video" | "audio")
+ ) && ["data-original", "data-src", "data-lazy-src", "data-srcset"]
+ .iter()
+ .any(|attribute| {
+ Dom::attribute(dom, node, attribute)
+ .is_some_and(|value| !value.trim().is_empty())
+ });
+ let disclosure = role.eq_ignore_ascii_case("tabpanel")
+ || Dom::attribute(dom, node, "hidden") == Some("until-found")
+ || (!matches!(role, "dialog" | "alertdialog" | "menu")
+ && Dom::attribute(dom, node, "id").is_some_and(|id| disclosures.contains(id)));
+ let aria_hidden = Dom::attribute(dom, node, "aria-hidden")
+ .is_some_and(|value| value.eq_ignore_ascii_case("true"));
+ // Angular/Vue remove cloak attributes only after the bound view
+ // is ready. If one remains at dump time, its template text is not
+ // reader content even when a missing stylesheet fails to hide it.
+ let uninitialized_template = ["ng-cloak", "data-ng-cloak", "x-ng-cloak", "v-cloak"]
+ .iter()
+ .any(|name| Dom::attribute(dom, node, name).is_some());
+ let far_offscreen = values
+ .get(3)
+ .is_some_and(|position| matches!(position.as_str(), "absolute" | "fixed"))
+ && values
+ .get(4)
+ .and_then(|value| px(value))
+ .is_some_and(|left| left <= -1000.0)
+ && values
+ .get(5)
+ .and_then(|value| px(value))
+ .is_some_and(|top| top <= -1000.0);
+ let tracking_pixel = matches!(Dom::node_kind(dom, node), NodeKind::Element("img"))
+ && Dom::attribute(dom, node, "alt").is_none_or(|alt| alt.trim().is_empty())
+ && values
+ .get(8)
+ .and_then(|value| px(value))
+ .is_some_and(|width| width <= 1.5)
+ && values
+ .get(9)
+ .and_then(|value| px(value))
+ .is_some_and(|height| height <= 1.5);
+ let foreground = values.get(10).and_then(|value| css_color(value));
+ let zero_contrast_leaf = !has_element_child(dom, node)
+ && has_text_child(dom, node)
+ && values
+ .get(13)
+ .is_none_or(|image| image.is_empty() || image == "none")
+ && foreground
+ .filter(|color| color.3 > 0.99)
+ .zip(effective_backgrounds.get(&node).copied())
+ .is_some_and(|(foreground, background)| {
+ background.3 > 0.99
+ && (foreground.0, foreground.1, foreground.2)
+ == (background.0, background.1, background.2)
+ });
+ let document_root = Some(node) == document_element || Some(node) == body;
+ let animated = values
+ .get(12)
+ .is_some_and(|name| !name.is_empty() && name != "none");
+ if ((values.first().is_some_and(|value| value == "none")
+ || values
+ .get(2)
+ .is_some_and(|value| value.parse::() == Ok(0.0))
+ && !lazy_media
+ && !animated
+ && !document_root)
+ && !disclosure)
+ || (aria_hidden && !disclosure)
+ || uninitialized_template
+ || far_offscreen
+ || tracking_pixel
+ || zero_contrast_leaf
+ || dom
+ .parent_node(node)
+ .is_some_and(|parent| suppressed.contains(&parent))
+ {
+ suppressed.insert(node);
+ }
+ if values.first().is_some_and(|value| {
+ matches!(
+ value.as_str(),
+ "block" | "flow-root" | "flex" | "grid" | "list-item" | "table"
+ )
+ }) {
+ blocks.insert(node);
+ } else if values.first().is_some_and(|value| {
+ matches!(
+ value.as_str(),
+ "inline-block" | "inline-flex" | "inline-grid" | "inline-table"
+ )
+ }) {
+ inline_boundaries.insert(node);
+ }
+ if matches!(Dom::node_kind(dom, node), NodeKind::Element("span")) {
+ let relative = values.get(3).is_some_and(|position| position == "relative");
+ let vertical_align = values.get(7).map(String::as_str).unwrap_or_default();
+ if vertical_align == "super"
+ || (relative
+ && values
+ .get(5)
+ .and_then(|value| px(value))
+ .is_some_and(|top| top < -1.0))
+ {
+ superscripts.insert(node);
+ } else if vertical_align == "sub"
+ || (relative
+ && values
+ .get(6)
+ .and_then(|value| px(value))
+ .is_some_and(|bottom| bottom < -1.0))
+ {
+ subscripts.insert(node);
+ }
+ }
+ if let Some(base_url) = base_url {
+ let names: &[&str] = match Dom::node_kind(dom, node) {
+ NodeKind::Element("a") => &["href"],
+ NodeKind::Element("img") => &[
+ "src",
+ "data-original",
+ "data-src",
+ "data-lazy-src",
+ "srcset",
+ "data-srcset",
+ ],
+ NodeKind::Element("iframe" | "audio" | "source") => {
+ &["src", "data-src", "data-lazy-src"]
+ }
+ NodeKind::Element("video") => &["src", "poster", "data-src", "data-lazy-src"],
+ _ => &[],
+ };
+ for &name in names {
+ let Some(value) = Dom::attribute(dom, node, name)
+ .map(str::trim)
+ .filter(|value| !value.is_empty() && !value.starts_with('#'))
+ else {
+ continue;
+ };
+ let resolved = if matches!(name, "srcset" | "data-srcset") {
+ resolve_srcset(base_url, value)
+ } else {
+ base_url.join(value).ok().map(|url| url.to_string())
+ };
+ if let Some(url) = resolved {
+ resolved_urls
+ .entry(node)
+ .or_insert_with(HashMap::new)
+ .insert(name.to_owned(), url);
+ }
+ }
+ }
+ if values
+ .get(1)
+ .is_some_and(|value| matches!(value.as_str(), "hidden" | "collapse"))
+ && !disclosure
+ && !document_visibility_is_hidden
+ {
+ invisible.insert(node);
+ }
+ }
+ Self {
+ dom,
+ suppressed,
+ invisible,
+ blocks,
+ inline_boundaries,
+ superscripts,
+ subscripts,
+ resolved_urls,
+ fragment_links,
+ }
+ }
+
+ fn next_retained(&self, mut node: Option) -> Option {
+ while let Some(id) = node {
+ if !self.suppressed.contains(&id) {
+ return Some(id);
+ }
+ node = self.dom.next_sibling(id);
+ }
+ None
+ }
+}
+
+fn inline_disclosure_targets(value: &str) -> Vec<&str> {
+ let mut result = Vec::new();
+ for (marker, fragment) in [
+ ("document.getElementById", false),
+ ("document.querySelector", true),
+ ] {
+ for offset in code_marker_offsets(value, marker) {
+ let remaining = &value[offset + marker.len()..];
+ let Some(argument) = remaining
+ .trim_start()
+ .strip_prefix('(')
+ .map(str::trim_start)
+ else {
+ continue;
+ };
+ let Some(quote) = argument
+ .chars()
+ .next()
+ .filter(|quote| matches!(quote, '\'' | '"'))
+ else {
+ continue;
+ };
+ let literal = &argument[quote.len_utf8()..];
+ let Some(end) = literal.find(quote) else {
+ continue;
+ };
+ let literal = &literal[..end];
+ if let Some(target) = literal
+ .strip_prefix('#')
+ .or_else(|| (!fragment).then_some(literal))
+ && !target.is_empty()
+ {
+ result.push(target);
+ }
+ }
+ }
+ result
+}
+
+fn code_marker_offsets(value: &str, marker: &str) -> Vec {
+ let mut result = Vec::new();
+ let mut offset = 0;
+ let mut quote = None;
+ let mut escaped = false;
+ while offset < value.len() {
+ let character = value[offset..]
+ .chars()
+ .next()
+ .expect("offset remains on a character boundary");
+ if let Some(delimiter) = quote {
+ if escaped {
+ escaped = false;
+ } else if character == '\\' {
+ escaped = true;
+ } else if character == delimiter {
+ quote = None;
+ }
+ } else if matches!(character, '\'' | '"' | '`') {
+ quote = Some(character);
+ } else if value[offset..].starts_with(marker) {
+ result.push(offset);
+ offset += marker.len();
+ continue;
+ }
+ offset += character.len_utf8();
+ }
+ result
+}
+
+fn px(value: &str) -> Option {
+ value.strip_suffix("px")?.trim().parse().ok()
+}
+
+fn resolve_srcset(base_url: &Url, value: &str) -> Option {
+ let mut resolved = Vec::new();
+ for candidate in value.split(',') {
+ let candidate = candidate.trim();
+ if candidate.is_empty() {
+ continue;
+ }
+ let split = candidate
+ .find(char::is_whitespace)
+ .unwrap_or(candidate.len());
+ let (source, descriptor) = candidate.split_at(split);
+ let url = base_url.join(source).ok()?;
+ resolved.push(format!("{}{descriptor}", url));
+ }
+ (!resolved.is_empty()).then(|| resolved.join(", "))
+}
+
+fn css_color(value: &str) -> Option<(u8, u8, u8, f32)> {
+ let value = value.trim().to_ascii_lowercase();
+ match value.as_str() {
+ "transparent" => return Some((0, 0, 0, 0.0)),
+ "white" => return Some((255, 255, 255, 1.0)),
+ "black" => return Some((0, 0, 0, 1.0)),
+ _ => {}
+ }
+ let (body, alpha) = match (
+ value
+ .strip_prefix("rgba(")
+ .and_then(|body| body.strip_suffix(')')),
+ value
+ .strip_prefix("rgb(")
+ .and_then(|body| body.strip_suffix(')')),
+ ) {
+ (Some(body), _) => (body, true),
+ (_, Some(body)) => (body, false),
+ _ => return None,
+ };
+ let mut parts = body.split(',').map(str::trim);
+ let red = parts.next()?.parse().ok()?;
+ let green = parts.next()?.parse().ok()?;
+ let blue = parts.next()?.parse().ok()?;
+ let opacity = if alpha {
+ parts.next()?.parse().ok()?
+ } else {
+ 1.0
+ };
+ parts
+ .next()
+ .is_none()
+ .then_some((red, green, blue, opacity))
+}
+
+fn has_element_child(dom: &NativeDom, node: NativeNodeId) -> bool {
+ let mut child = dom.first_child(node);
+ while let Some(id) = child {
+ if matches!(Dom::node_kind(dom, id), NodeKind::Element(_)) {
+ return true;
+ }
+ child = dom.next_sibling(id);
+ }
+ false
+}
+
+fn has_text_child(dom: &NativeDom, node: NativeNodeId) -> bool {
+ let mut child = dom.first_child(node);
+ while let Some(id) = child {
+ if matches!(Dom::node_kind(dom, id), NodeKind::Text(text) if !text.trim().is_empty()) {
+ return true;
+ }
+ child = dom.next_sibling(id);
+ }
+ false
+}
+
+fn within(dom: &NativeDom, mut node: NativeNodeId, ancestor: NativeNodeId) -> bool {
+ loop {
+ if node == ancestor {
+ return true;
+ }
+ let Some(parent) = dom.parent_node(node) else {
+ return false;
+ };
+ node = parent;
+ }
+}
+
+fn text(dom: &NativeDom, root: NativeNodeId, skip: Option) -> String {
+ let mut pending = vec![root];
+ let mut result = String::new();
+ while let Some(node) = pending.pop() {
+ if Some(node) == skip {
+ continue;
+ }
+ match Dom::node_kind(dom, node) {
+ NodeKind::Text(value) => result.push_str(value),
+ NodeKind::Element("script" | "style" | "template") => continue,
+ _ => {}
+ }
+ let mut children = Vec::new();
+ let mut child = dom.first_child(node);
+ while let Some(id) = child {
+ children.push(id);
+ child = dom.next_sibling(id);
+ }
+ pending.extend(children.into_iter().rev());
+ }
+ result.split_whitespace().collect::>().join(" ")
+}
+
+impl Dom for MarkdownDom<'_> {
+ type NodeId = NativeNodeId;
+
+ fn node_kind(&self, node: Self::NodeId) -> NodeKind<'_> {
+ if self.suppressed.contains(&node) {
+ return NodeKind::Other;
+ }
+ let kind = Dom::node_kind(self.dom, node);
+ if self.invisible.contains(&node) {
+ // Visibility can be overridden by a descendant. Keep traversing
+ // without emitting this element's own image, link or formatting.
+ return NodeKind::Document;
+ }
+ if matches!(kind, NodeKind::Text(_))
+ && self
+ .dom
+ .parent_node(node)
+ .is_some_and(|parent| self.invisible.contains(&parent))
+ {
+ return NodeKind::Other;
+ }
+ if self.superscripts.contains(&node) {
+ return NodeKind::Element("sup");
+ }
+ if self.subscripts.contains(&node) {
+ return NodeKind::Element("sub");
+ }
+ kind
+ }
+
+ fn first_child(&self, node: Self::NodeId) -> Option {
+ self.next_retained(self.dom.first_child(node))
+ }
+
+ fn next_sibling(&self, node: Self::NodeId) -> Option {
+ self.next_retained(self.dom.next_sibling(node))
+ }
+
+ fn attribute(&self, node: Self::NodeId, name: &str) -> Option<&str> {
+ self.resolved_urls
+ .get(&node)
+ .and_then(|attributes| attributes.get(name))
+ .map(String::as_str)
+ .or_else(|| Dom::attribute(self.dom, node, name))
+ }
+
+ fn has_block_layout(&self, node: Self::NodeId) -> bool {
+ self.blocks.contains(&node)
+ }
+
+ fn has_text_boundary(&self, node: Self::NodeId) -> bool {
+ self.inline_boundaries.contains(&node)
+ }
+
+ fn may_have_fragment_links(&self) -> bool {
+ self.fragment_links
+ }
+}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs
new file mode 100644
index 00000000000..0e08c5df909
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/markdown_dump.rs
@@ -0,0 +1,160 @@
+use super::*;
+use crate::runtime::page_surface::{
+ RendererPageDumpFormat, RendererPageDumpOptions, RendererPageDumpStripOptions,
+};
+
+fn options(strip_css: bool) -> RendererPageDumpOptions {
+ RendererPageDumpOptions {
+ format: RendererPageDumpFormat::Markdown,
+ strip: RendererPageDumpStripOptions {
+ css: strip_css,
+ ..Default::default()
+ },
+ with_base: false,
+ with_frames: false,
+ }
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn markdown_uses_live_visibility_and_preserves_disclosure_content() {
+ run_page_vm_async_test(async move {
+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let mut page = test_page_vm_with_loader_and_document_url(&loader, Vec::new(), Url::parse("https://example.test/content").unwrap());
+ page.vm_mut().eval(r#"
+ document.head.innerHTML = '';
+ document.body.innerHTML = `
+
ArticleVisible body
+ Translation pending
+ Share metadata
+ Followers 92
+ Score 313131
+ Parser trap
+ Accessible helper
+ Transparent parent Transparent child
+ Buy {{product.name}} for {{product.price | currency}}
+ Vue template {{message}}
+ Visible value hidden suffix 8
+ CSS override VISIBLE
+ Stylesheet override ALSO VISIBLE
+ White on black stays visible
+ Faded text
+ Animated article text
+ ActiveReviewed
+ Mass 2.4 × 10−17 J; mn
+
+
+
+ Hidden ancestor Inherited hiddenRestored child
+
+
+
+
+
+ DetailsClosed details content
+
+ Cookie template `;
+ "#).unwrap();
+ assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('legacy-hidden')).color").unwrap(), "rgb(255, 255, 255)");
+ assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('css-override')).color").unwrap(), "rgb(0, 0, 0)");
+ assert_eq!(page.vm_mut().eval("getComputedStyle(document.getElementById('external-override')).color").unwrap(), "rgb(0, 0, 0)");
+ assert_eq!(page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','black'); getComputedStyle(document.getElementById('legacy-hidden')).color").unwrap(), "rgb(0, 0, 0)");
+ page.vm_mut().eval("document.getElementById('legacy-hidden').setAttribute('color','white')").unwrap();
+ for strip_css in [false, true] {
+ let output = page.render_page_dump(options(strip_css));
+ for kept in ["Visible body", "Restored child", "Panel content", "ARIA panel content", "Disclosure content", "Closed details content", "Followers 2", "Score 31", "Accessible helper", "Faded text", "Animated article text", "Visible value 8", "CSS override VISIBLE", "Stylesheet override ALSO VISIBLE", "White on black stays visible", ""] {
+ assert!(output.contains(kept), "missing {kept}: {output}");
+ }
+ assert!(output.contains("10−17"), "{output}");
+ assert!(output.contains("mn"), "{output}");
+ assert!(output.contains("Active\nReviewed"), "{output}");
+ assert!(!output.contains("tracking.gif"), "{output}");
+ assert!(output.contains("Upload complete"), "{output}");
+ for omitted in ["Translation pending", "Share metadata", "Hidden ancestor", "Inherited hidden", "Cookie template", "Followers 92", "Score 3131", "Parser trap", "Transparent parent", "Transparent child", "hidden suffix", "product.name", "Vue template"] {
+ assert!(!output.contains(omitted), "leaked {omitted}: {output}");
+ }
+ }
+ page.vm_mut().eval("document.getElementById('waiting').className = ''").unwrap();
+ assert!(page.render_page_dump(options(false)).contains("Translation pending"));
+ assert_eq!(page.vm_mut().eval("document.querySelector('style').textContent.includes('.off')").unwrap(), "true");
+ page.vm_mut().eval(r#"
+ document.documentElement.style.opacity = '0';
+ document.body.innerHTML = 'Whole-page loading veil';
+ "#).unwrap();
+ assert!(page.render_page_dump(options(false)).contains("Whole-page loading veil"));
+ page.vm_mut().eval(r#"
+ document.documentElement.style.opacity = '';
+ document.body.style.visibility = 'hidden';
+ document.body.innerHTML = 'Font loading veil';
+ "#).unwrap();
+ assert!(page.render_page_dump(options(false)).contains("Font loading veil"));
+ page.vm_mut().eval("document.body.style.visibility = ''").unwrap();
+ page.vm_mut().eval(r#"
+ document.head.innerHTML = '';
+ document.body.innerHTML = 'AcceptReject';
+ "#).unwrap();
+ let actions = page.render_page_dump(options(false));
+ assert!(actions.contains("[Accept](https://example.test/accept)\n\n[Reject](https://example.test/reject)"), "{actions}");
+ page.vm_mut().eval(r##"
+ document.body.innerHTML = `
+ A detailed review starts... Read more
+ A detailed review starts here and retains the final conclusion.
+ A different excerpt... Read more
+ Unrelated hidden template
+ Complete short review. Complete short review.
+ Complete short review.
+ Privacy policy... Read more
+ Privacy policy with cookie settings `;
+ "##).unwrap();
+ for strip_css in [false, true] {
+ let output = page.render_page_dump(options(strip_css));
+ assert_eq!(output.matches("A detailed review starts").count(), 1, "{output}");
+ assert!(output.contains("retains the final conclusion."), "{output}");
+ assert!(!output.contains("A detailed review starts..."), "{output}");
+ assert!(output.contains("A different excerpt..."), "{output}");
+ assert!(!output.contains("Unrelated hidden template"), "{output}");
+ assert_eq!(output.matches("Complete short review.").count(), 2, "{output}");
+ assert!(output.contains("Privacy policy..."), "{output}");
+ assert!(!output.contains("cookie settings"), "{output}");
+ }
+ page.vm_mut().eval(r##"
+ document.body.innerHTML = `
+ +
+
+ `;
+ "##).unwrap();
+ let expanded = page.render_page_dump(options(false));
+ assert!(expanded.contains("Expandable history"), "{expanded}");
+ assert!(!expanded.contains("Hidden template"), "{expanded}");
+ page.vm_mut().eval(r##"
+ document.body.innerHTML = `
+
+
+
+
+
+ `;
+ "##).unwrap();
+ let related = page.render_page_dump(options(false));
+ assert!(!related.contains("Hidden telemetry state"), "{related}");
+ assert!(!related.contains("Hidden diagnostic state"), "{related}");
+ assert!(related.contains("Query-selected history"), "{related}");
+ page.vm_mut().eval(r#"
+ document.body.innerHTML = `
+ Visible gradient text
+ `;
+ "#).unwrap();
+ let painted = page.render_page_dump(options(false));
+ assert!(painted.contains("Visible gradient text"), "{painted}");
+ assert!(painted.contains(""), "{painted}");
+ page.vm_mut().eval(r#"
+ document.body.innerHTML = `
+
+ `;
+ "#).unwrap();
+ let responsive = page.render_page_dump(options(false));
+ assert!(responsive.contains(""), "{responsive}");
+ assert!(responsive.contains(""), "{responsive}");
+ page.vm_mut().eval("document.documentElement.style.display = 'none'").unwrap();
+ assert!(page.render_page_dump(options(false)).is_empty());
+ }).await;
+}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index 0298a7d021d..12d8f524520 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -146,6 +146,7 @@ mod main_parser_module_completion;
mod main_parser_owned_module_completion;
mod main_runtime_module_completion;
mod main_runtime_script_completion;
+mod markdown_dump;
mod media_element_event;
mod message_port_delivery;
mod misc_platform_api;
diff --git a/moli-renderer-v8/src/style_engine/mutation_effect.rs b/moli-renderer-v8/src/style_engine/mutation_effect.rs
index ea25c3be900..92868c6b20f 100644
--- a/moli-renderer-v8/src/style_engine/mutation_effect.rs
+++ b/moli-renderer-v8/src/style_engine/mutation_effect.rs
@@ -212,7 +212,7 @@ impl StyleAttributeImpact {
pub(crate) fn for_attribute_name(name: &str) -> Self {
let name = name.to_ascii_lowercase();
match name.as_str() {
- "style" | "class" | "id" => Self::ComputedStyle,
+ "style" | "class" | "id" | "color" => Self::ComputedStyle,
"hidden" | "width" | "height" | "cols" | "rows" | "size" | "value" | "border"
| "slot" | "align" => Self::LayoutMetric,
"cellpadding" => Self::DescendantComputedStyle,
diff --git a/moli-selector/src/stylo/presentation.rs b/moli-selector/src/stylo/presentation.rs
index d91a15a86c7..2e6ea755676 100644
--- a/moli-selector/src/stylo/presentation.rs
+++ b/moli-selector/src/stylo/presentation.rs
@@ -161,7 +161,7 @@ impl QueryElement<'_> {
);
}
} else if element.namespace() == HTML_NAMESPACE {
- append_html_table_presentation_declarations(*self, &mut block);
+ append_html_presentation_declarations(*self, &mut block);
} else {
return;
}
@@ -176,7 +176,7 @@ impl QueryElement<'_> {
}
}
-fn append_html_table_presentation_declarations(
+fn append_html_presentation_declarations(
element: QueryElement<'_>,
block: &mut PropertyDeclarationBlock,
) {
@@ -184,6 +184,11 @@ fn append_html_table_presentation_declarations(
let local_name = native.local_name();
let is_cell = matches!(local_name, "td" | "th");
let is_column = matches!(local_name, "col" | "colgroup");
+ if local_name == "font"
+ && let Some(color) = native.attribute("color").and_then(parse_html_legacy_color)
+ {
+ append_parsed_presentation_declaration(element, "color", &color, block);
+ }
// Table dimensions are presentation hints, including column-group widths.
// Keep them in the cascade so author CSS can override them and the table
// algorithm receives the same constraints as an authored CSS length.
diff --git a/moli/tests/fetch_cli/markdown.rs b/moli/tests/fetch_cli/markdown.rs
index 36711ea604c..917047c302d 100644
--- a/moli/tests/fetch_cli/markdown.rs
+++ b/moli/tests/fetch_cli/markdown.rs
@@ -3,10 +3,52 @@ use base64::{Engine as _, engine::general_purpose::STANDARD};
use std::process::Command;
const HTML: &str = include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.html");
-const MARKDOWN: &str = include_str!("../../../moli-html2md/tests/fixtures/hacker-news-layout.md");
-
fn assert_layout_table_dump(args: &[&str]) -> Result<()> {
- assert_markdown_dump(HTML, MARKDOWN, args)
+ let url = format!("data:text/html;base64,{}", STANDARD.encode(HTML));
+ let output = Command::new(env!("CARGO_BIN_EXE_moli"))
+ .args([
+ "fetch",
+ "--dump",
+ "markdown",
+ "--wait-until",
+ "load",
+ "--timeout",
+ "10000",
+ ])
+ .args(args)
+ .arg(url)
+ .output()?;
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let markdown = String::from_utf8(output.stdout)?;
+ for content in [
+ "First story",
+ "42 points by",
+ "8 comments",
+ "Second story",
+ "7 points by",
+ "discuss",
+ "More",
+ ] {
+ assert!(markdown.contains(content), "missing {content}: {markdown}");
+ }
+ let positions = [
+ "First story",
+ "42 points by",
+ "Second story",
+ "7 points by",
+ "More",
+ ]
+ .map(|content| markdown.find(content).expect("checked above"));
+ assert!(
+ positions.windows(2).all(|pair| pair[0] < pair[1]),
+ "{markdown}"
+ );
+ assert!(markdown.contains(" |