forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksJavaScript3.6 MiBe100df4Tahinli1 month ago1 commit

export.rs669 lines, 21.4 KiBHistoryRawDownload
1//! Markdown export from a loro-prosemirror shaped LoroDoc.
2//!
3//! Layout (see loro-prosemirror `createLoroMap` / `createLoroText`): the root
4//! is `doc.get_map("doc")`. Every non-text node is a LoroMap with `nodeName`,
5//! `attributes` (LoroMap) and `children` (LoroList). Children are either node
6//! maps or a LoroText whose rich-text deltas carry the marks as attributes.
7
8use loro::{Container, LoroDoc, LoroMap, LoroText, LoroValue, TextDelta, ValueOrContainer};
9
10mod html;
11pub use html::{html_page, to_html};
12
13/// Maps a note id to its current title, for wiki-style links in `to_markdown_with`.
14pub type Resolve<'a> = &'a dyn Fn(&str) -> Option<String>;
15
16/// Rendering options. `wiki` is set by `to_markdown_with`: note links then render as
17/// `[[Title]]`, and ids the resolver cannot name stay ordinary markdown links.
18#[derive(Clone, Copy)]
19struct Ctx<'a> {
20 wiki: Option<Resolve<'a>>,
21}
22
23/// Full note as CommonMark/GFM. Note links stay ordinary markdown links, which is
24/// what the search text wants.
25pub fn to_markdown(doc: &LoroDoc) -> String {
26 render_doc(doc, Ctx { wiki: None })
27}
28
29/// Full note as markdown with note links written as `[[Title]]` (or `[[Title|text]]`
30/// when the link text differs). Links by title use the stored title; links by id use
31/// `resolve`, and an id it cannot name stays an ordinary link.
32pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String {
33 render_doc(doc, Ctx { wiki: Some(resolve) })
34}
35
36fn render_doc(doc: &LoroDoc, cx: Ctx<'_>) -> String {
37 let root = doc.get_map("doc");
38 let body = render_children(&root, false, cx);
39 if body.is_empty() {
40 String::new()
41 } else {
42 format!("{body}\n")
43 }
44}
45
46/// A link to another note: by id (`/notes/<id>`) or by title (`/notes/by-title/<title>`).
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum LinkTarget {
49 Id(String),
50 Title(String),
51}
52
53/// Every note the doc links to, each target once, in document order. Hrefs that are
54/// not note links are ignored.
55pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> {
56 let mut out = Vec::new();
57 collect_links(&doc.get_map("doc"), &mut out);
58 out
59}
60
61fn collect_links(node: &LoroMap, out: &mut Vec<LinkTarget>) {
62 for child in children(node) {
63 match child {
64 Child::Text(text) => {
65 for delta in text.to_delta() {
66 let TextDelta::Insert {
67 attributes: Some(attrs),
68 ..
69 } = delta
70 else {
71 continue;
72 };
73 let Some(href) = attrs
74 .get("link")
75 .and_then(|link| link.get_by_key("href"))
76 .and_then(value_str)
77 else {
78 continue;
79 };
80 if let Some(target) = link_target(&href) {
81 if !out.contains(&target) {
82 out.push(target);
83 }
84 }
85 }
86 }
87 Child::Node(m) => collect_links(&m, out),
88 }
89 }
90}
91
92fn link_target(href: &str) -> Option<LinkTarget> {
93 let rest = href.strip_prefix("/notes/")?;
94 if let Some(encoded) = rest.strip_prefix("by-title/") {
95 let title = percent_decode(encoded);
96 return (!title.trim().is_empty()).then_some(LinkTarget::Title(title));
97 }
98 let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']);
99 is_id.then(|| LinkTarget::Id(rest.to_owned()))
100}
101
102/// The note a link mark points at, as a title, when the link is a note link the
103/// resolver can name. Links by title need no resolver.
104fn wiki_target(href: &str, cx: Ctx<'_>) -> Option<String> {
105 let resolve = cx.wiki?;
106 match link_target(href)? {
107 LinkTarget::Title(title) => Some(title),
108 LinkTarget::Id(id) => resolve(&id),
109 }
110}
111
112/// `[[target]]`, or `[[target|text]]` when the link text differs. None when the title or
113/// the text holds wiki syntax (`[ ] | #` or a line break), so the link stays a markdown link.
114fn wiki_link(target: &str, text: &str) -> Option<String> {
115 let reserved = |s: &str| s.contains(['[', ']', '|', '#', '\n']);
116 if target.trim().is_empty() || reserved(target) || reserved(text) {
117 return None;
118 }
119 if text == target {
120 Some(format!("[[{target}]]"))
121 } else {
122 Some(format!("[[{target}|{text}]]"))
123 }
124}
125
126/// Percent-encodes everything except RFC 3986 unreserved characters.
127pub fn percent_encode(s: &str) -> String {
128 let mut out = String::with_capacity(s.len());
129 for b in s.bytes() {
130 match b {
131 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
132 out.push(b as char)
133 }
134 _ => out.push_str(&format!("%{b:02X}")),
135 }
136 }
137 out
138}
139
140/// Decodes `%XX` escapes. Malformed escapes are kept as they are.
141pub fn percent_decode(s: &str) -> String {
142 let bytes = s.as_bytes();
143 let mut out = Vec::with_capacity(bytes.len());
144 let mut i = 0;
145 while i < bytes.len() {
146 if bytes[i] == b'%' && i + 2 < bytes.len() {
147 let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
148 if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
149 out.push(v);
150 i += 3;
151 continue;
152 }
153 }
154 out.push(bytes[i]);
155 i += 1;
156 }
157 String::from_utf8_lossy(&out).into_owned()
158}
159
160/// Plain text of the first non-empty block, trimmed, max 80 chars. "Untitled" if empty.
161pub fn title(doc: &LoroDoc) -> String {
162 let root = doc.get_map("doc");
163 let raw = first_text(&root).unwrap_or_default();
164 let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
165 let truncated: String = collapsed.chars().take(80).collect();
166 let trimmed = truncated.trim_end();
167 if trimmed.is_empty() {
168 "Untitled".to_string()
169 } else {
170 trimmed.to_string()
171 }
172}
173
174// ---------------------------------------------------------------------------
175// Tree access helpers
176// ---------------------------------------------------------------------------
177
178pub(super) enum Child {
179 Text(LoroText),
180 Node(LoroMap),
181}
182
183pub(super) fn children(node: &LoroMap) -> Vec<Child> {
184 let mut out = Vec::new();
185 let Some(ValueOrContainer::Container(Container::List(list))) = node.get("children") else {
186 return out;
187 };
188 for i in 0..list.len() {
189 match list.get(i) {
190 Some(ValueOrContainer::Container(Container::Text(t))) => out.push(Child::Text(t)),
191 Some(ValueOrContainer::Container(Container::Map(m))) => out.push(Child::Node(m)),
192 _ => {}
193 }
194 }
195 out
196}
197
198pub(super) fn node_name(node: &LoroMap) -> String {
199 match node.get("nodeName") {
200 Some(ValueOrContainer::Value(v)) => value_str(&v).unwrap_or_default(),
201 _ => String::new(),
202 }
203}
204
205pub(super) fn attr(node: &LoroMap, key: &str) -> Option<LoroValue> {
206 match node.get("attributes") {
207 Some(ValueOrContainer::Container(Container::Map(attrs))) => match attrs.get(key) {
208 Some(ValueOrContainer::Value(v)) => Some(v),
209 _ => None,
210 },
211 _ => None,
212 }
213}
214
215pub(super) fn attr_str(node: &LoroMap, key: &str) -> Option<String> {
216 attr(node, key).and_then(|v| value_str(&v))
217}
218
219pub(super) fn attr_num(node: &LoroMap, key: &str) -> Option<i64> {
220 match attr(node, key)? {
221 LoroValue::I64(i) => Some(i),
222 LoroValue::Double(d) => Some(d as i64),
223 _ => None,
224 }
225}
226
227pub(super) fn value_str(v: &LoroValue) -> Option<String> {
228 v.as_string().map(|s| s.as_str().to_owned())
229}
230
231pub(super) fn plain_text(text: &LoroText) -> String {
232 text.to_delta()
233 .into_iter()
234 .filter_map(|d| match d {
235 TextDelta::Insert { insert, .. } => Some(insert),
236 _ => None,
237 })
238 .collect()
239}
240
241pub(super) fn plain_node_text(node: &LoroMap) -> String {
242 children(node)
243 .into_iter()
244 .map(|c| match c {
245 Child::Text(t) => plain_text(&t),
246 Child::Node(m) => plain_node_text(&m),
247 })
248 .collect()
249}
250
251/// First non-blank text of the tree, in document order.
252fn first_text(node: &LoroMap) -> Option<String> {
253 for child in children(node) {
254 let found = match child {
255 Child::Text(t) => Some(plain_text(&t)),
256 Child::Node(m) => first_text(&m),
257 };
258 if let Some(s) = found {
259 if !s.trim().is_empty() {
260 return Some(s);
261 }
262 }
263 }
264 None
265}
266
267// ---------------------------------------------------------------------------
268// Block rendering
269// ---------------------------------------------------------------------------
270
271/// Renders the children of `node` as blocks separated by blank lines.
272/// With `tight`, a nested list directly follows its sibling with a single
273/// newline instead of a blank line (used inside list items).
274fn render_children(node: &LoroMap, tight: bool, cx: Ctx<'_>) -> String {
275 let mut blocks: Vec<(String, bool)> = Vec::new();
276 for child in children(node) {
277 match child {
278 Child::Text(t) => {
279 let s = paragraph_text(inline_text(&t, cx));
280 if !s.is_empty() {
281 blocks.push((s, false));
282 }
283 }
284 Child::Node(m) => {
285 let is_list = matches!(node_name(&m).as_str(), "bullet_list" | "ordered_list");
286 if let Some(s) = render_block(&m, cx) {
287 blocks.push((s, is_list));
288 }
289 }
290 }
291 }
292
293 let mut out = String::new();
294 for (i, (block, is_list)) in blocks.iter().enumerate() {
295 if i > 0 {
296 out.push_str(if tight && *is_list { "\n" } else { "\n\n" });
297 }
298 out.push_str(block);
299 }
300 out
301}
302
303fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> {
304 let name = node_name(node);
305 let out = match name.as_str() {
306 "paragraph" => paragraph_text(inline_children(node, cx)),
307 "heading" => {
308 let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6) as usize;
309 let text = inline_children(node, cx).replace('\n', " ");
310 let text = text.trim();
311 if text.is_empty() {
312 String::new()
313 } else {
314 format!("{} {}", "#".repeat(level), text)
315 }
316 }
317 "blockquote" => render_children(node, false, cx)
318 .lines()
319 .map(|l| {
320 if l.is_empty() {
321 ">".to_string()
322 } else {
323 format!("> {l}")
324 }
325 })
326 .collect::<Vec<_>>()
327 .join("\n"),
328 "code_block" => code_block(node),
329 "horizontal_rule" => "---".to_string(),
330 "bullet_list" => render_list(node, false, cx),
331 "ordered_list" => render_list(node, true, cx),
332 "list_item" => render_children(node, true, cx),
333 "image" => paragraph_text(image_md(node)),
334 "hard_break" => String::new(),
335 // doc and unknown containers: render their children.
336 _ => render_children(node, false, cx),
337 };
338
339 if out.trim().is_empty() {
340 None
341 } else {
342 Some(out.trim_end().to_string())
343 }
344}
345
346fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String {
347 let start = if ordered {
348 attr_num(node, "order").unwrap_or(1)
349 } else {
350 1
351 };
352 let mut items = Vec::new();
353 let mut index: i64 = 0;
354 for child in children(node) {
355 let Child::Node(item) = child else {
356 continue;
357 };
358 let marker = if ordered {
359 format!("{}. ", start + index)
360 } else {
361 "- ".to_string()
362 };
363 index += 1;
364
365 let body = render_children(&item, true, cx);
366 if body.is_empty() {
367 items.push(marker.trim_end().to_string());
368 continue;
369 }
370 let pad = " ".repeat(marker.len());
371 let mut lines = body.lines();
372 let mut text = format!("{marker}{}", lines.next().unwrap_or(""));
373 for line in lines {
374 text.push('\n');
375 if !line.is_empty() {
376 text.push_str(&pad);
377 text.push_str(line);
378 }
379 }
380 items.push(text);
381 }
382 items.join("\n")
383}
384
385fn code_block(node: &LoroMap) -> String {
386 let mut content = String::new();
387 for child in children(node) {
388 match child {
389 Child::Text(t) => content.push_str(&plain_text(&t)),
390 Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'),
391 Child::Node(m) => content.push_str(&plain_node_text(&m)),
392 }
393 }
394 let content = content.trim_end_matches('\n');
395 let fence = "`".repeat((longest_backtick_run(content) + 1).max(3));
396 let lang = attr_str(node, "language").unwrap_or_default();
397 if content.is_empty() {
398 format!("{fence}{lang}\n{fence}")
399 } else {
400 format!("{fence}{lang}\n{content}\n{fence}")
401 }
402}
403
404fn longest_backtick_run(s: &str) -> usize {
405 let mut best = 0;
406 let mut cur = 0;
407 for c in s.chars() {
408 if c == '`' {
409 cur += 1;
410 best = best.max(cur);
411 } else {
412 cur = 0;
413 }
414 }
415 best
416}
417
418/// Trims the inline output and protects the start of each line from being
419/// read as block syntax (heading, list, blockquote, ordered list marker).
420fn paragraph_text(inline: String) -> String {
421 inline
422 .trim()
423 .split('\n')
424 .map(escape_line_start)
425 .collect::<Vec<_>>()
426 .join("\n")
427}
428
429fn escape_line_start(line: &str) -> String {
430 let mut chars = line.chars();
431 match chars.next() {
432 Some('>') => format!("\\>{}", chars.as_str()),
433 Some('-') | Some('+') => {
434 let next = line.chars().nth(1);
435 if next.is_none() || next == Some(' ') || next == Some('-') {
436 format!("\\{line}")
437 } else {
438 line.to_string()
439 }
440 }
441 Some('#') => {
442 let hashes = line.chars().take_while(|&c| c == '#').count();
443 let after = line.chars().nth(hashes);
444 if (1..=6).contains(&hashes) && (after.is_none() || after == Some(' ')) {
445 format!("\\{line}")
446 } else {
447 line.to_string()
448 }
449 }
450 Some(c) if c.is_ascii_digit() => {
451 let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
452 let rest = &line[digits..];
453 if rest.starts_with('.') || rest.starts_with(')') {
454 format!("{}\\{}", &line[..digits], rest)
455 } else {
456 line.to_string()
457 }
458 }
459 _ => line.to_string(),
460 }
461}
462
463// ---------------------------------------------------------------------------
464// Inline rendering
465// ---------------------------------------------------------------------------
466
467/// Concatenated inline content of a node: text runs and inline child nodes.
468fn inline_children(node: &LoroMap, cx: Ctx<'_>) -> String {
469 let mut out = String::new();
470 for child in children(node) {
471 match child {
472 Child::Text(t) => out.push_str(&inline_text(&t, cx)),
473 Child::Node(m) => out.push_str(&inline_node(&m, cx)),
474 }
475 }
476 out
477}
478
479fn inline_node(node: &LoroMap, cx: Ctx<'_>) -> String {
480 match node_name(node).as_str() {
481 "hard_break" => "\\\n".to_string(),
482 "image" => image_md(node),
483 _ => inline_children(node, cx),
484 }
485}
486
487#[derive(PartialEq, Clone, Default)]
488struct Marks {
489 strong: bool,
490 em: bool,
491 code: bool,
492 link: Option<(String, Option<String>)>,
493}
494
495/// Renders a LoroText as markdown, merging adjacent runs with identical marks
496/// so that e.g. two bold runs become one `**...**` span.
497fn inline_text(text: &LoroText, cx: Ctx<'_>) -> String {
498 let mut runs: Vec<(String, Marks)> = Vec::new();
499 for delta in text.to_delta() {
500 let TextDelta::Insert { insert, attributes } = delta else {
501 continue;
502 };
503 let attrs = attributes.unwrap_or_default();
504 let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null));
505 let link = attrs.get("link").map(|v| {
506 let href = v.get_by_key("href").and_then(value_str).unwrap_or_default();
507 let title = v
508 .get_by_key("title")
509 .and_then(value_str)
510 .filter(|t| !t.is_empty());
511 (href, title)
512 });
513 let marks = Marks {
514 strong: on("strong"),
515 em: on("em"),
516 code: on("code"),
517 link,
518 };
519 match runs.last_mut() {
520 Some((s, m)) if *m == marks => s.push_str(&insert),
521 _ => runs.push((insert, marks)),
522 }
523 }
524 // Consecutive runs under the same link render as one link, so a partly bold link
525 // stays a single link.
526 let mut out = String::new();
527 let mut i = 0;
528 while i < runs.len() {
529 let mut j = i + 1;
530 if runs[i].1.link.is_some() {
531 while j < runs.len() && runs[j].1.link == runs[i].1.link {
532 j += 1;
533 }
534 }
535 out.push_str(&render_group(&runs[i..j], cx));
536 i = j;
537 }
538 out
539}
540
541/// One run without a link, or every run of one link.
542fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String {
543 let Some((href, title)) = group[0].1.link.clone() else {
544 return render_marks(&group[0].0, &group[0].1);
545 };
546 let text: String = group.iter().map(|(s, _)| s.as_str()).collect();
547 let core = text.trim();
548 if core.is_empty() || href.is_empty() {
549 return group.iter().map(|(s, m)| render_marks(s, m)).collect();
550 }
551 let lead = &text[..text.len() - text.trim_start().len()];
552 let trail = &text[lead.len() + core.len()..];
553
554 if let Some(target) = wiki_target(&href, cx) {
555 // Marks that cover the whole link go around `[[...]]`, which can't hold any.
556 let first = &group[0].1;
557 let uniform = !first.code
558 && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em);
559 if uniform {
560 if let Some(mut link) = wiki_link(&target, core) {
561 if first.em {
562 link = format!("*{link}*");
563 }
564 if first.strong {
565 link = format!("**{link}**");
566 }
567 return format!("{lead}{link}{trail}");
568 }
569 }
570 // Mixed marks: a markdown link to the note's file, which Obsidian also follows.
571 let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect();
572 let file = percent_encode(&format!("{target}.md"));
573 return format!("{lead}[{}]({file}){trail}", inner.trim());
574 }
575
576 let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect();
577 format!(
578 "{lead}[{}]({}){trail}",
579 inner.trim(),
580 link_dest(&href, title.as_deref())
581 )
582}
583
584/// A run's text with its emphasis and code marks; links are handled by `render_group`.
585fn render_marks(s: &str, m: &Marks) -> String {
586 let core = s.trim();
587 if core.is_empty() {
588 return s.to_string();
589 }
590 // Keep surrounding whitespace outside the emphasis markers.
591 let lead_len = s.len() - s.trim_start().len();
592 let lead = &s[..lead_len];
593 let trail = &s[lead_len + core.len()..];
594
595 let mut out = if m.code {
596 code_span(core)
597 } else {
598 escape_text(core)
599 };
600 if m.em {
601 out = format!("*{out}*");
602 }
603 if m.strong {
604 out = format!("**{out}**");
605 }
606 format!("{lead}{out}{trail}")
607}
608
609/// Escapes markdown-significant characters in plain text. Underscores inside
610/// a word (snake_case) are left alone.
611fn escape_text(s: &str) -> String {
612 let chars: Vec<char> = s.chars().collect();
613 let mut out = String::with_capacity(s.len());
614 for (i, &c) in chars.iter().enumerate() {
615 let escape = match c {
616 '\\' | '`' | '*' | '[' | ']' | '<' | '~' => true,
617 '_' => {
618 let prev = i.checked_sub(1).map(|p| chars[p]);
619 let next = chars.get(i + 1).copied();
620 !(prev.is_some_and(char::is_alphanumeric) && next.is_some_and(char::is_alphanumeric))
621 }
622 _ => false,
623 };
624 if escape {
625 out.push('\\');
626 }
627 out.push(c);
628 }
629 out
630}
631
632fn code_span(s: &str) -> String {
633 let fence = "`".repeat(longest_backtick_run(s) + 1);
634 let pad = if s.starts_with('`') || s.ends_with('`') {
635 " "
636 } else {
637 ""
638 };
639 format!("{fence}{pad}{s}{pad}{fence}")
640}
641
642fn link_dest(href: &str, title: Option<&str>) -> String {
643 let dest = if href.chars().any(|c| c.is_whitespace() || c == '(' || c == ')') {
644 format!("<{}>", href.replace('<', "\\<").replace('>', "\\>"))
645 } else {
646 href.to_string()
647 };
648 match title.filter(|t| !t.is_empty()) {
649 Some(t) => format!(
650 "{dest} \"{}\"",
651 t.replace('\\', "\\\\").replace('"', "\\\"")
652 ),
653 None => dest,
654 }
655}
656
657fn image_md(node: &LoroMap) -> String {
658 let alt = attr_str(node, "alt").unwrap_or_default();
659 let src = attr_str(node, "src").unwrap_or_default();
660 if src.is_empty() {
661 return escape_text(&alt);
662 }
663 let alt = alt
664 .replace('\\', "\\\\")
665 .replace('[', "\\[")
666 .replace(']', "\\]");
667 let title = attr_str(node, "title").filter(|t| !t.is_empty());
668 format!("![{alt}]({})", link_dest(&src, title.as_deref()))
669}