Skip to content
Closed
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
26 changes: 17 additions & 9 deletions moli-html2md/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
106 changes: 106 additions & 0 deletions moli-html2md/src/anchors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use std::collections::HashSet;

use crate::{Dom, NodeKind};

pub(crate) fn referenced<D: Dom + ?Sized>(
dom: &D,
root: D::NodeId,
limit: usize,
) -> HashSet<String> {
let mut ids = HashSet::new();
if !dom.may_have_fragment_links() {
return ids;
}
walk(dom, root, limit, |node| {
if let Some(fragment) = dom
.attribute(node, "href")
.and_then(|href| href.strip_prefix('#'))
&& !fragment.is_empty()
{
ids.insert(decode_fragment(fragment));
}
false
});
ids
}

pub(crate) fn contains<D: Dom + ?Sized>(
dom: &D,
root: D::NodeId,
limit: usize,
ids: &HashSet<String>,
) -> bool {
walk(dom, root, limit, |node| {
["id", "name"]
.iter()
.any(|name| dom.attribute(node, name).is_some_and(|id| ids.contains(id)))
})
}

fn walk<D: Dom + ?Sized>(
dom: &D,
root: D::NodeId,
limit: usize,
mut found: impl FnMut(D::NodeId) -> bool,
) -> bool {
let mut stack = vec![(Some(root), 0, false)];
while let Some((node, depth, siblings)) = stack.pop() {
let Some(node) = node else {
continue;
};
if siblings {
stack.push((dom.next_sibling(node), depth, true));
}
if depth >= limit {
continue;
}
if matches!(
dom.node_kind(node),
NodeKind::Other
| NodeKind::Element("head" | "script" | "style" | "noscript" | "template")
) {
continue;
}
if found(node) {
return true;
}
stack.push((dom.first_child(node), depth + 1, true));
}
false
}

pub(crate) fn decode_fragment(fragment: &str) -> String {
let bytes = fragment.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut offset = 0;
while offset < bytes.len() {
if bytes[offset] == b'%' && offset + 2 < bytes.len() {
let hex = |byte: u8| (byte as char).to_digit(16);
if let (Some(high), Some(low)) = (hex(bytes[offset + 1]), hex(bytes[offset + 2])) {
decoded.push((high * 16 + low) as u8);
offset += 3;
continue;
}
}
decoded.push(bytes[offset]);
offset += 1;
}
String::from_utf8(decoded).unwrap_or_else(|_| fragment.to_owned())
}

pub(crate) fn markup(id: &str) -> String {
let mut result = String::from("<a id=\"");
for character in id.chars() {
match character {
'&' => result.push_str("&amp;"),
'"' => result.push_str("&quot;"),
'<' => result.push_str("&lt;"),
'>' => result.push_str("&gt;"),
'\n' => result.push_str("&#10;"),
'\r' => result.push_str("&#13;"),
character => result.push(character),
}
}
result.push_str("\"></a>");
result
}
2 changes: 1 addition & 1 deletion moli-html2md/src/copy_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("<table>").count(),
1
depth
);
// Count actual bytes copied when materializing fragments; completed
// blocks move into parents without copying their text. This measures
Expand Down
19 changes: 19 additions & 0 deletions moli-html2md/src/dom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,23 @@ pub trait Dom {
fn first_child(&self, node: Self::NodeId) -> Option<Self::NodeId>;
fn next_sibling(&self, node: Self::NodeId) -> Option<Self::NodeId>;
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
}
}
43 changes: 43 additions & 0 deletions moli-html2md/src/form.rs
Original file line number Diff line number Diff line change
@@ -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<Cow<'a, str>> {
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)
}
Loading