| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use loro::{LoroDoc, LoroMap, LoroText, LoroValue, TextDelta}; |
| 6 | |
| 7 | use super::{Child, attr_num, attr_str, children, node_name, plain_node_text, plain_text, value_str}; |
| 8 | |
| 9 | |
| 10 | pub fn to_html(doc: &LoroDoc) -> String { |
| 11 | let root = doc.get_map("doc"); |
| 12 | render_children(&root) |
| 13 | } |
| 14 | |
| 15 | |
| 16 | |
| 17 | pub fn html_page(title: &str, body: &str, lang: &str, print: bool) -> String { |
| 18 | let script = if print { |
| 19 | "<script>addEventListener('load',()=>print())</script>" |
| 20 | } else { |
| 21 | "" |
| 22 | }; |
| 23 | format!( |
| 24 | "<!DOCTYPE html>\n<html lang=\"{lang}\">\n<head>\n<meta charset=\"utf-8\">\n\ |
| 25 | <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\ |
| 26 | <title>{title}</title>\n<style>{STYLE}</style>\n</head>\n<body>\n\ |
| 27 | <main class=\"note\">\n{body}\n</main>\n{script}\n</body>\n</html>\n", |
| 28 | lang = esc(lang), |
| 29 | title = esc(title), |
| 30 | ) |
| 31 | } |
| 32 | |
| 33 | const STYLE: &str = "\ |
| 34 | body{margin:0;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;\ |
| 35 | font-size:16px;line-height:1.6;color:#1c1c1e;background:#fff}\ |
| 36 | .note{max-width:42rem;margin:2.5rem auto;padding:0 1.25rem}\ |
| 37 | h1,h2,h3,h4,h5,h6{line-height:1.25;margin:1.6em 0 .5em}\ |
| 38 | p,ul,ol,blockquote,pre,table{margin:0 0 1em}\ |
| 39 | ul,ol{padding-left:1.5em}\ |
| 40 | blockquote{margin-left:0;padding-left:1em;border-left:3px solid #d0d0d5;color:#555}\ |
| 41 | code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em;\ |
| 42 | background:#f2f2f4;padding:.1em .3em;border-radius:4px}\ |
| 43 | pre{background:#f2f2f4;padding:.75em 1em;border-radius:6px;overflow-x:auto;white-space:pre}\ |
| 44 | pre code{background:none;padding:0;font-size:.875em}\ |
| 45 | img{max-width:100%;height:auto}\ |
| 46 | hr{border:0;border-top:1px solid #d0d0d5;margin:2em 0}\ |
| 47 | a{color:#0a58ca}\ |
| 48 | table{border-collapse:collapse;max-width:100%}\ |
| 49 | th,td{border:1px solid #d0d0d5;padding:.4em .6em;text-align:left}\ |
| 50 | @page{margin:2cm}\ |
| 51 | @media print{body{color:#000}.note{max-width:none;margin:0;padding:0}\ |
| 52 | a{color:inherit}pre,blockquote,img{break-inside:avoid}pre{background:#f2f2f2}code{background:#f2f2f2}}"; |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | fn esc(s: &str) -> String { |
| 59 | let mut out = String::with_capacity(s.len()); |
| 60 | for c in s.chars() { |
| 61 | match c { |
| 62 | '&' => out.push_str("&"), |
| 63 | '<' => out.push_str("<"), |
| 64 | '>' => out.push_str(">"), |
| 65 | '"' => out.push_str("""), |
| 66 | '\'' => out.push_str("'"), |
| 67 | _ => out.push(c), |
| 68 | } |
| 69 | } |
| 70 | out |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | fn safe_href(href: &str) -> Option<&str> { |
| 76 | let h = href.trim(); |
| 77 | if h.is_empty() { |
| 78 | return None; |
| 79 | } |
| 80 | let lower = h.to_ascii_lowercase(); |
| 81 | if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:") { |
| 82 | return Some(h); |
| 83 | } |
| 84 | |
| 85 | match h.find(':') { |
| 86 | Some(i) if !h[..i].contains(['/', '?', '#']) => None, |
| 87 | _ => Some(h), |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | |
| 92 | fn safe_src(src: &str) -> Option<&str> { |
| 93 | let lower = src.trim().to_ascii_lowercase(); |
| 94 | if lower.starts_with("data:image/png") |
| 95 | || lower.starts_with("data:image/jpeg") |
| 96 | || lower.starts_with("data:image/gif") |
| 97 | || lower.starts_with("data:image/webp") |
| 98 | { |
| 99 | return Some(src.trim()); |
| 100 | } |
| 101 | safe_href(src) |
| 102 | } |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | fn render_children(node: &LoroMap) -> String { |
| 110 | let mut out = String::new(); |
| 111 | for child in children(node) { |
| 112 | match child { |
| 113 | Child::Text(t) => { |
| 114 | let inner = inline_text(&t); |
| 115 | if !inner.trim().is_empty() { |
| 116 | out.push_str(&format!("<p>{}</p>\n", inner.trim())); |
| 117 | } |
| 118 | } |
| 119 | Child::Node(m) => { |
| 120 | if let Some(html) = render_block(&m) { |
| 121 | out.push_str(&html); |
| 122 | out.push('\n'); |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | out |
| 128 | } |
| 129 | |
| 130 | fn render_block(node: &LoroMap) -> Option<String> { |
| 131 | let html = match node_name(node).as_str() { |
| 132 | "paragraph" => { |
| 133 | let inner = inline_children(node); |
| 134 | if inner.trim().is_empty() { |
| 135 | return None; |
| 136 | } |
| 137 | format!("<p>{}</p>", inner.trim()) |
| 138 | } |
| 139 | "heading" => { |
| 140 | let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6); |
| 141 | let inner = inline_children(node).replace('\n', " "); |
| 142 | let inner = inner.trim(); |
| 143 | if inner.is_empty() { |
| 144 | return None; |
| 145 | } |
| 146 | format!("<h{level}>{inner}</h{level}>") |
| 147 | } |
| 148 | "blockquote" => { |
| 149 | let inner = render_children(node); |
| 150 | if inner.trim().is_empty() { |
| 151 | return None; |
| 152 | } |
| 153 | format!("<blockquote>\n{inner}</blockquote>") |
| 154 | } |
| 155 | "code_block" => code_block(node), |
| 156 | "horizontal_rule" => "<hr>".to_string(), |
| 157 | "bullet_list" => render_list(node, false)?, |
| 158 | "ordered_list" => render_list(node, true)?, |
| 159 | "image" => { |
| 160 | let inner = image_html(node); |
| 161 | format!("<p>{inner}</p>") |
| 162 | } |
| 163 | "hard_break" => return None, |
| 164 | |
| 165 | _ => render_children(node), |
| 166 | }; |
| 167 | if html.trim().is_empty() { |
| 168 | None |
| 169 | } else { |
| 170 | Some(html) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | fn render_list(node: &LoroMap, ordered: bool) -> Option<String> { |
| 175 | let mut items = String::new(); |
| 176 | for child in children(node) { |
| 177 | let Child::Node(item) = child else { |
| 178 | continue; |
| 179 | }; |
| 180 | items.push_str(&format!("<li>{}</li>\n", render_children(&item).trim_end())); |
| 181 | } |
| 182 | if items.is_empty() { |
| 183 | return None; |
| 184 | } |
| 185 | if ordered { |
| 186 | let start = attr_num(node, "order").unwrap_or(1); |
| 187 | let start_attr = if start == 1 { |
| 188 | String::new() |
| 189 | } else { |
| 190 | format!(" start=\"{start}\"") |
| 191 | }; |
| 192 | Some(format!("<ol{start_attr}>\n{items}</ol>")) |
| 193 | } else { |
| 194 | Some(format!("<ul>\n{items}</ul>")) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | fn code_block(node: &LoroMap) -> String { |
| 199 | let mut content = String::new(); |
| 200 | for child in children(node) { |
| 201 | match child { |
| 202 | Child::Text(t) => content.push_str(&plain_text(&t)), |
| 203 | Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'), |
| 204 | Child::Node(m) => content.push_str(&plain_node_text(&m)), |
| 205 | } |
| 206 | } |
| 207 | let content = content.trim_end_matches('\n'); |
| 208 | let lang = attr_str(node, "language").unwrap_or_default(); |
| 209 | let class = if lang.trim().is_empty() { |
| 210 | String::new() |
| 211 | } else { |
| 212 | format!(" class=\"language-{}\"", esc(lang.trim())) |
| 213 | }; |
| 214 | format!("<pre><code{class}>{}</code></pre>", esc(content)) |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | fn inline_children(node: &LoroMap) -> String { |
| 223 | let mut out = String::new(); |
| 224 | for child in children(node) { |
| 225 | match child { |
| 226 | Child::Text(t) => out.push_str(&inline_text(&t)), |
| 227 | Child::Node(m) => out.push_str(&inline_node(&m)), |
| 228 | } |
| 229 | } |
| 230 | out |
| 231 | } |
| 232 | |
| 233 | fn inline_node(node: &LoroMap) -> String { |
| 234 | match node_name(node).as_str() { |
| 235 | "hard_break" => "<br>".to_string(), |
| 236 | "image" => image_html(node), |
| 237 | _ => inline_children(node), |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | fn image_html(node: &LoroMap) -> String { |
| 242 | let alt = attr_str(node, "alt").unwrap_or_default(); |
| 243 | let src = attr_str(node, "src").unwrap_or_default(); |
| 244 | let Some(src) = safe_src(&src) else { |
| 245 | return esc(&alt); |
| 246 | }; |
| 247 | let title = attr_str(node, "title") |
| 248 | .filter(|t| !t.is_empty()) |
| 249 | .map(|t| format!(" title=\"{}\"", esc(&t))) |
| 250 | .unwrap_or_default(); |
| 251 | format!("<img src=\"{}\" alt=\"{}\"{title}>", esc(src), esc(&alt)) |
| 252 | } |
| 253 | |
| 254 | #[derive(PartialEq, Clone, Default)] |
| 255 | struct Marks { |
| 256 | strong: bool, |
| 257 | em: bool, |
| 258 | code: bool, |
| 259 | link: Option<(String, Option<String>)>, |
| 260 | } |
| 261 | |
| 262 | |
| 263 | fn inline_text(text: &LoroText) -> String { |
| 264 | let mut runs: Vec<(String, Marks)> = Vec::new(); |
| 265 | for delta in text.to_delta() { |
| 266 | let TextDelta::Insert { insert, attributes } = delta else { |
| 267 | continue; |
| 268 | }; |
| 269 | let attrs = attributes.unwrap_or_default(); |
| 270 | let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null)); |
| 271 | let link = attrs.get("link").map(|v| { |
| 272 | let href = v.get_by_key("href").and_then(value_str).unwrap_or_default(); |
| 273 | let title = v |
| 274 | .get_by_key("title") |
| 275 | .and_then(value_str) |
| 276 | .filter(|t| !t.is_empty()); |
| 277 | (href, title) |
| 278 | }); |
| 279 | let marks = Marks { |
| 280 | strong: on("strong"), |
| 281 | em: on("em"), |
| 282 | code: on("code"), |
| 283 | link, |
| 284 | }; |
| 285 | match runs.last_mut() { |
| 286 | Some((s, m)) if *m == marks => s.push_str(&insert), |
| 287 | _ => runs.push((insert, marks)), |
| 288 | } |
| 289 | } |
| 290 | runs.iter().map(|(s, m)| render_run(s, m)).collect() |
| 291 | } |
| 292 | |
| 293 | fn render_run(s: &str, m: &Marks) -> String { |
| 294 | let core = s.trim(); |
| 295 | if core.is_empty() { |
| 296 | return esc(s); |
| 297 | } |
| 298 | |
| 299 | let lead_len = s.len() - s.trim_start().len(); |
| 300 | let lead = &s[..lead_len]; |
| 301 | let trail = &s[lead_len + core.len()..]; |
| 302 | |
| 303 | let mut out = if m.code { |
| 304 | format!("<code>{}</code>", esc(core)) |
| 305 | } else { |
| 306 | esc(core) |
| 307 | }; |
| 308 | if m.em { |
| 309 | out = format!("<em>{out}</em>"); |
| 310 | } |
| 311 | if m.strong { |
| 312 | out = format!("<strong>{out}</strong>"); |
| 313 | } |
| 314 | if let Some((href, title)) = &m.link { |
| 315 | if let Some(href) = safe_href(href) { |
| 316 | let title = title |
| 317 | .as_deref() |
| 318 | .map(|t| format!(" title=\"{}\"", esc(t))) |
| 319 | .unwrap_or_default(); |
| 320 | out = format!("<a href=\"{}\"{title}>{out}</a>", esc(href)); |
| 321 | } |
| 322 | } |
| 323 | format!("{}{out}{}", esc(lead), esc(trail)) |
| 324 | } |