Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,17 @@ impl PageScriptHost {
document,
&scripting,
policy,
(with_frames && !self.child_browsing_context_document_handles.is_empty())
.then_some(self as &dyn HtmlEmbeddedDocumentProvider),
self.embedded_documents_for_export(with_frames),
max_bytes,
)
}

/// The live child Documents an export may inline, if requested and present.
pub(crate) fn embedded_documents_for_export(
&self,
with_frames: bool,
) -> Option<&dyn HtmlEmbeddedDocumentProvider> {
(with_frames && !self.child_browsing_context_document_handles.is_empty())
.then_some(self as &dyn HtmlEmbeddedDocumentProvider)
}
}
15 changes: 9 additions & 6 deletions moli-renderer-v8/src/runtime/markdown_dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ impl PageVm {
pub(crate) fn render_markdown(&self, options: RendererMarkdownOptions) -> String {
let strip = options.strip;
let host = self.vm().document_runtime.dom_host();
let dom = live_dom::LiveDom::new(host);
if dom.has_shadow_roots() {
self.render_markdown_source(&dom, strip)
} else {
self.render_markdown_source(host.dom(), strip)
}
self.vm()
.with_embedded_documents_for_export(options.with_frames, |frames| {
let dom = live_dom::LiveDom::new(host, frames);
if dom.is_projected() {
self.render_markdown_source(&dom, strip)
} else {
self.render_markdown_source(host.dom(), strip)
}
})
}

fn render_markdown_source(
Expand Down
86 changes: 80 additions & 6 deletions moli-renderer-v8/src/runtime/markdown_dump/live_dom.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
};

use moli_html2md::{Dom, NodeKind};
use url::Url;

use crate::dom::native::{DomHost, NativeDom, NativeNodeId};
use crate::dom::native::{DomHost, HtmlEmbeddedDocumentProvider, NativeDom, NativeNodeId, Node};

/// Additional page facts needed by the Markdown presentation adapter.
pub(super) trait MarkdownSource: Dom<NodeId = NativeNodeId> {
fn native(&self) -> &NativeDom;
fn parent_node(&self, node: NativeNodeId) -> Option<NativeNodeId>;
/// Base URL of the embedded Document containing `node`, if inlined.
fn frame_base_url(&self, _node: NativeNodeId) -> Option<&Url> {
None
}
}

/// A read-only adapter over the live page. Query caches store node IDs;
Expand All @@ -16,19 +25,28 @@ pub(super) struct LiveDom<'a> {
host: &'a DomHost,
has_shadow_roots: bool,
projection: RefCell<ProjectionCache>,
/// Live embedded Documents, borrowed exactly as the HTML writer does.
frames: Option<&'a dyn HtmlEmbeddedDocumentProvider>,
sole_frame_owner: Option<NativeNodeId>,
}

impl<'a> LiveDom<'a> {
pub(super) fn new(host: &'a DomHost) -> Self {
pub(super) fn new(
host: &'a DomHost,
frames: Option<&'a dyn HtmlEmbeddedDocumentProvider>,
) -> Self {
Self {
host,
has_shadow_roots: !host.snapshot_connected_shadow_root_bindings().is_empty(),
projection: RefCell::new(ProjectionCache::default()),
frames,
sole_frame_owner: frames.and_then(|frames| frames.sole_owner()),
}
}

pub(super) fn has_shadow_roots(&self) -> bool {
self.has_shadow_roots
/// Whether the export must follow projected edges rather than native ones.
pub(super) fn is_projected(&self) -> bool {
self.has_shadow_roots || self.frames.is_some()
}
}

Expand All @@ -39,6 +57,9 @@ impl<'a> LiveDom<'a> {
struct ProjectionCache {
parents: HashMap<NativeNodeId, Option<NativeNodeId>>,
slot_children: HashMap<NativeNodeId, Option<Rc<[NativeNodeId]>>>,
/// Inlined frame content root -> its owner element.
frame_owners: HashMap<NativeNodeId, NativeNodeId>,
frame_documents: HashSet<NativeNodeId>,
}

impl LiveDom<'_> {
Expand All @@ -60,6 +81,32 @@ impl LiveDom<'_> {
cache.slot_children.insert(slot, children.clone());
children
}

/// The body (or root element) of the live Document embedded by `owner`.
/// A Document is inlined under at most one owner.
fn frame_root(&self, owner: NativeNodeId) -> Option<NativeNodeId> {
let frames = self.frames?;
if self.sole_frame_owner.is_some_and(|sole| sole != owner) {
return None;
}
let document = frames.embedded_document(owner)?.document;
let dom = self.host.dom();
let element_child = |parent, tag| {
dom.find_child(parent, |child| {
dom.node(child)
.and_then(Node::as_element)
.is_some_and(|element| element.is_html_element(tag))
})
};
let html = element_child(document, "html")?;
let root = element_child(html, "body").unwrap_or(html);
let mut cache = self.projection.borrow_mut();
if *cache.frame_owners.entry(root).or_insert(owner) != owner {
return None;
}
cache.frame_documents.insert(document);
Some(root)
}
}

struct ProjectedChildren {
Expand Down Expand Up @@ -110,7 +157,24 @@ impl MarkdownSource for LiveDom<'_> {
self.host.dom()
}

fn frame_base_url(&self, node: NativeNodeId) -> Option<&Url> {
self.frames?;
let document = self.host.node(node).and_then(Node::owner_document)?;
if !self.projection.borrow().frame_documents.contains(&document) {
return None;
}
self.host
.node(document)
.and_then(Node::as_document)
.map(|document| document.base_url())
}

fn parent_node(&self, node: NativeNodeId) -> Option<NativeNodeId> {
if self.frames.is_some()
&& let Some(&owner) = self.projection.borrow().frame_owners.get(&node)
{
return Some(owner);
}
let native_parent = self.host.dom().parent_node(node)?;
if !self.has_shadow_roots {
return Some(native_parent);
Expand Down Expand Up @@ -160,6 +224,10 @@ impl Dom for LiveDom<'_> {
type NodeId = NativeNodeId;

fn node_kind(&self, node: Self::NodeId) -> NodeKind<'_> {
// An inlined frame owner is a plain container for its Document.
if self.frame_root(node).is_some() {
return NodeKind::Element("div");
}
Dom::node_kind(self.host.dom(), node)
}

Expand All @@ -176,6 +244,12 @@ impl Dom for LiveDom<'_> {

fn children(&self, node: Self::NodeId) -> impl Iterator<Item = Self::NodeId> {
let dom = self.host.dom();
if let Some(root) = self.frame_root(node) {
return ChildNodes::Projected(ProjectedChildren {
nodes: Rc::from([root]),
next: 0,
});
}
if self.has_shadow_roots
&& let Some(element) = dom.node(node).and_then(|node| node.as_element())
{
Expand Down Expand Up @@ -203,7 +277,7 @@ mod tests {
use crate::dom_presentation::{flat_children, flat_parent};

fn assert_projection(host: &DomHost) {
let view = LiveDom::new(host);
let view = LiveDom::new(host, None);
let root = host.document_handle();
let mut known_nodes = Vec::new();
let mut stack = vec![root];
Expand Down
2 changes: 1 addition & 1 deletion moli-renderer-v8/src/runtime/markdown_dump/visibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ impl<'a, D: MarkdownSource> MarkdownDom<'a, D> {
subscripts.insert(node);
}
}
if let Some(base_url) = base_url {
if let Some(base_url) = dom.frame_base_url(node).or(base_url) {
let tag = match Dom::node_kind(dom, node) {
NodeKind::Element(tag) => tag,
_ => "",
Expand Down
1 change: 1 addition & 0 deletions moli-renderer-v8/src/runtime/page_surface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6186,6 +6186,7 @@ pub struct RendererHtmlSerializeOptions {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RendererMarkdownOptions {
pub strip: RendererContentStripOptions,
pub with_frames: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ fn options(strip_css: bool) -> RendererMarkdownOptions {
css: strip_css,
..Default::default()
},
..Default::default()
}
}

Expand Down
12 changes: 12 additions & 0 deletions moli-renderer-v8/src/script_vm/child_frame_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,18 @@ impl ScriptVm {
)
}

/// Runs `f` with the live child Documents an export may inline.
pub(crate) fn with_embedded_documents_for_export<R>(
&self,
with_frames: bool,
f: impl FnOnce(Option<&dyn crate::dom::native::HtmlEmbeddedDocumentProvider>) -> R,
) -> R {
f(self
._context_host
.borrow()
.embedded_documents_for_export(with_frames))
}

pub(crate) fn take_pending_location_navigation_with_seed(
&mut self,
) -> Option<crate::native_bridge::PendingLocationNavigation> {
Expand Down
7 changes: 6 additions & 1 deletion moli/src/fetch_dump/dom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,14 @@ fn html_serialize_options(
}
}

pub(super) async fn render_markdown(page: &mut Page, strip: StripOptions) -> Result<String> {
pub(super) async fn render_markdown(
page: &mut Page,
strip: StripOptions,
with_frames: bool,
) -> Result<String> {
page.render_markdown_async(RendererMarkdownOptions {
strip: renderer_strip_options(strip),
with_frames,
})
.await
}
Expand Down
2 changes: 1 addition & 1 deletion moli/src/fetch_dump/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ async fn render_page_dump_with_trace_config_async(
.await
}
DumpFormat::Html => dom::render_html(page, strip, with_base, with_frames).await,
DumpFormat::Markdown => dom::render_markdown(page, strip).await,
DumpFormat::Markdown => dom::render_markdown(page, strip, with_frames).await,
DumpFormat::Screenshot | DumpFormat::ScreenshotFull | DumpFormat::Pdf => {
bail!("binary dump formats are only supported by the fetch CLI output path")
}
Expand Down
11 changes: 11 additions & 0 deletions moli/tests/fetch_cli/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,14 @@ fn http_markdown_dump_resolves_resource_urls() -> Result<()> {
assert_eq!(String::from_utf8(output.stdout)?, expected);
Ok(())
}

#[test]
fn markdown_with_frames_inlines_child_documents_with_their_own_base_url() -> Result<()> {
let html = "<h1>Root</h1><p>Before frame</p><iframe srcdoc=\"<base href='https://child.example/dir/'><p>CHILD TEXT <a href='page.html'>child link</a></p><iframe srcdoc='<p>INNER</p>'></iframe>\"></iframe><p>After frame</p>";
assert_markdown_dump(
html,
"# Root\n\nBefore frame\n\nCHILD TEXT [child link](https://child.example/dir/page.html)\n\nINNER\n\nAfter frame",
&["--with-frames"],
)?;
assert_markdown_dump(html, "# Root\n\nBefore frame\n\nAfter frame", &[])
}
Loading