//! HTML export. Walks the same loro-prosemirror tree as the markdown export in
//! the parent module and emits an HTML body fragment, plus a standalone page
//! wrapper for download and print.
use loro::{LoroDoc, LoroMap, LoroText, LoroValue, TextDelta};
use super::{Child, attr_num, attr_str, children, node_name, plain_node_text, plain_text, value_str};
/// Note body as an HTML fragment (no surrounding document).
pub fn to_html(doc: &LoroDoc) -> String {
let root = doc.get_map("doc");
render_children(&root)
}
/// Standalone HTML document around `body`. With `print`, the page opens the
/// browser's print dialog on load (Save as PDF).
pub fn html_page(title: &str, body: &str, lang: &str, print: bool) -> String {
let script = if print {
""
} else {
""
};
format!(
"\n\n
\n\n\
\n\
{title}\n\n\n\n\
\n{body}\n\n{script}\n\n\n",
lang = esc(lang),
title = esc(title),
)
}
const STYLE: &str = "\
body{margin:0;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;\
font-size:16px;line-height:1.6;color:#1c1c1e;background:#fff}\
.note{max-width:42rem;margin:2.5rem auto;padding:0 1.25rem}\
h1,h2,h3,h4,h5,h6{line-height:1.25;margin:1.6em 0 .5em}\
p,ul,ol,blockquote,pre,table{margin:0 0 1em}\
ul,ol{padding-left:1.5em}\
blockquote{margin-left:0;padding-left:1em;border-left:3px solid #d0d0d5;color:#555}\
code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em;\
background:#f2f2f4;padding:.1em .3em;border-radius:4px}\
pre{background:#f2f2f4;padding:.75em 1em;border-radius:6px;overflow-x:auto;white-space:pre}\
pre code{background:none;padding:0;font-size:.875em}\
img{max-width:100%;height:auto}\
hr{border:0;border-top:1px solid #d0d0d5;margin:2em 0}\
a{color:#0a58ca}\
table{border-collapse:collapse;max-width:100%}\
th,td{border:1px solid #d0d0d5;padding:.4em .6em;text-align:left}\
@page{margin:2cm}\
@media print{body{color:#000}.note{max-width:none;margin:0;padding:0}\
a{color:inherit}pre,blockquote,img{break-inside:avoid}pre{background:#f2f2f2}code{background:#f2f2f2}}";
// ---------------------------------------------------------------------------
// Escaping and link safety
// ---------------------------------------------------------------------------
fn esc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(c),
}
}
out
}
/// Accepts http(s), mailto and scheme-less (relative) URLs. Anything else,
/// including javascript: and data:, is rejected.
fn safe_href(href: &str) -> Option<&str> {
let h = href.trim();
if h.is_empty() {
return None;
}
let lower = h.to_ascii_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:") {
return Some(h);
}
// A colon before any path, query or fragment delimiter starts a scheme.
match h.find(':') {
Some(i) if !h[..i].contains(['/', '?', '#']) => None,
_ => Some(h),
}
}
/// Image sources: the link rules, plus inline raster data URIs.
fn safe_src(src: &str) -> Option<&str> {
let lower = src.trim().to_ascii_lowercase();
if lower.starts_with("data:image/png")
|| lower.starts_with("data:image/jpeg")
|| lower.starts_with("data:image/gif")
|| lower.starts_with("data:image/webp")
{
return Some(src.trim());
}
safe_href(src)
}
// ---------------------------------------------------------------------------
// Block rendering
// ---------------------------------------------------------------------------
/// Renders the children of `node` as blocks, in order.
fn render_children(node: &LoroMap) -> String {
let mut out = String::new();
for child in children(node) {
match child {
Child::Text(t) => {
let inner = inline_text(&t);
if !inner.trim().is_empty() {
out.push_str(&format!("{}
\n", inner.trim()));
}
}
Child::Node(m) => {
if let Some(html) = render_block(&m) {
out.push_str(&html);
out.push('\n');
}
}
}
}
out
}
fn render_block(node: &LoroMap) -> Option {
let html = match node_name(node).as_str() {
"paragraph" => {
let inner = inline_children(node);
if inner.trim().is_empty() {
return None;
}
format!("{}
", inner.trim())
}
"heading" => {
let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6);
let inner = inline_children(node).replace('\n', " ");
let inner = inner.trim();
if inner.is_empty() {
return None;
}
format!("{inner}")
}
"blockquote" => {
let inner = render_children(node);
if inner.trim().is_empty() {
return None;
}
format!("\n{inner}
")
}
"code_block" => code_block(node),
"horizontal_rule" => "
".to_string(),
"bullet_list" => render_list(node, false)?,
"ordered_list" => render_list(node, true)?,
"image" => {
let inner = image_html(node);
format!("{inner}
")
}
"hard_break" => return None,
// doc and unknown containers: render their children.
_ => render_children(node),
};
if html.trim().is_empty() {
None
} else {
Some(html)
}
}
fn render_list(node: &LoroMap, ordered: bool) -> Option {
let mut items = String::new();
for child in children(node) {
let Child::Node(item) = child else {
continue;
};
items.push_str(&format!("{}\n", render_children(&item).trim_end()));
}
if items.is_empty() {
return None;
}
if ordered {
let start = attr_num(node, "order").unwrap_or(1);
let start_attr = if start == 1 {
String::new()
} else {
format!(" start=\"{start}\"")
};
Some(format!("\n{items}
"))
} else {
Some(format!(""))
}
}
fn code_block(node: &LoroMap) -> String {
let mut content = String::new();
for child in children(node) {
match child {
Child::Text(t) => content.push_str(&plain_text(&t)),
Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'),
Child::Node(m) => content.push_str(&plain_node_text(&m)),
}
}
let content = content.trim_end_matches('\n');
let lang = attr_str(node, "language").unwrap_or_default();
let class = if lang.trim().is_empty() {
String::new()
} else {
format!(" class=\"language-{}\"", esc(lang.trim()))
};
format!("{}
", esc(content))
}
// ---------------------------------------------------------------------------
// Inline rendering
// ---------------------------------------------------------------------------
/// Concatenated inline content of a node: text runs and inline child nodes.
fn inline_children(node: &LoroMap) -> String {
let mut out = String::new();
for child in children(node) {
match child {
Child::Text(t) => out.push_str(&inline_text(&t)),
Child::Node(m) => out.push_str(&inline_node(&m)),
}
}
out
}
fn inline_node(node: &LoroMap) -> String {
match node_name(node).as_str() {
"hard_break" => "
".to_string(),
"image" => image_html(node),
_ => inline_children(node),
}
}
fn image_html(node: &LoroMap) -> String {
let alt = attr_str(node, "alt").unwrap_or_default();
let src = attr_str(node, "src").unwrap_or_default();
let Some(src) = safe_src(&src) else {
return esc(&alt);
};
let title = attr_str(node, "title")
.filter(|t| !t.is_empty())
.map(|t| format!(" title=\"{}\"", esc(&t)))
.unwrap_or_default();
format!("
", esc(src), esc(&alt))
}
#[derive(PartialEq, Clone, Default)]
struct Marks {
strong: bool,
em: bool,
code: bool,
link: Option<(String, Option)>,
}
/// Renders a LoroText as HTML, merging adjacent runs with identical marks.
fn inline_text(text: &LoroText) -> String {
let mut runs: Vec<(String, Marks)> = Vec::new();
for delta in text.to_delta() {
let TextDelta::Insert { insert, attributes } = delta else {
continue;
};
let attrs = attributes.unwrap_or_default();
let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null));
let link = attrs.get("link").map(|v| {
let href = v.get_by_key("href").and_then(value_str).unwrap_or_default();
let title = v
.get_by_key("title")
.and_then(value_str)
.filter(|t| !t.is_empty());
(href, title)
});
let marks = Marks {
strong: on("strong"),
em: on("em"),
code: on("code"),
link,
};
match runs.last_mut() {
Some((s, m)) if *m == marks => s.push_str(&insert),
_ => runs.push((insert, marks)),
}
}
runs.iter().map(|(s, m)| render_run(s, m)).collect()
}
fn render_run(s: &str, m: &Marks) -> String {
let core = s.trim();
if core.is_empty() {
return esc(s);
}
// Keep surrounding whitespace outside the tags.
let lead_len = s.len() - s.trim_start().len();
let lead = &s[..lead_len];
let trail = &s[lead_len + core.len()..];
let mut out = if m.code {
format!("{}", esc(core))
} else {
esc(core)
};
if m.em {
out = format!("{out}");
}
if m.strong {
out = format!("{out}");
}
if let Some((href, title)) = &m.link {
if let Some(href) = safe_href(href) {
let title = title
.as_deref()
.map(|t| format!(" title=\"{}\"", esc(t)))
.unwrap_or_default();
out = format!("{out}", esc(href));
}
}
format!("{}{out}{}", esc(lead), esc(trail))
}