//! Format note content the way Apple Notes expects to look: //! Title (first line) → optional Heading/Subheading → Body paragraphs → lists. //! //! Converts common agent/Markdown noise into clean Notes-friendly plain text. //! Paragraph style hints are also emitted for the browser layer when available. #![allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ParagraphStyle { Title, Heading, Subheading, Body, Bullet, Dashed, Numbered, Checklist, Monospace, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Paragraph { pub style: ParagraphStyle, pub text: String, /// Checklist done state (only for Checklist). pub checked: bool, } /// Public entry: Apple-style note text (first line = title). pub fn format_apple_note(title: &str, body: &str) -> String { paragraphs_to_plain(&build_paragraphs(title, body)) } /// Structured paragraphs for richer Notes styling when the web API supports it. pub fn build_paragraphs(title: &str, body: &str) -> Vec { let title = clean_title(title); let body = body.replace("\r\n", "\n").replace('\r', "\n"); let body = strip_outer_fence(&body); let mut out = Vec::new(); if !title.is_empty() { out.push(Paragraph { style: ParagraphStyle::Title, text: title.clone(), checked: false, }); } let mut in_code = false; let mut code_buf: Vec = Vec::new(); let mut para_buf: Vec = Vec::new(); let flush_para = |buf: &mut Vec, out: &mut Vec| { if buf.is_empty() { return; } let text = buf.join(" ").trim().to_string(); buf.clear(); if text.is_empty() { return; } // Skip body line that merely repeats the title if out .first() .map(|p| p.style == ParagraphStyle::Title && titles_equal(&p.text, &text)) .unwrap_or(false) && out.len() == 1 { return; } out.push(Paragraph { style: ParagraphStyle::Body, text, checked: false, }); }; for raw in body.lines() { let line = raw.trim_end(); let trimmed = line.trim(); if trimmed.starts_with("```") { if in_code { let code = code_buf.join("\n").trim_end().to_string(); code_buf.clear(); in_code = false; if !code.is_empty() { flush_para(&mut para_buf, &mut out); out.push(Paragraph { style: ParagraphStyle::Monospace, text: code, checked: false, }); } } else { flush_para(&mut para_buf, &mut out); in_code = true; } continue; } if in_code { code_buf.push(line.to_string()); continue; } if trimmed.is_empty() { flush_para(&mut para_buf, &mut out); continue; } // Horizontal rules — visual noise in Notes; skip if trimmed.chars().all(|c| c == '-' || c == '*' || c == '_') && trimmed.len() >= 3 { flush_para(&mut para_buf, &mut out); continue; } if let Some(p) = parse_special_line(trimmed) { flush_para(&mut para_buf, &mut out); if p.text.is_empty() { continue; } // Don't re-add title-looking heading if it matches note title if p.style == ParagraphStyle::Heading && out .first() .map(|t| t.style == ParagraphStyle::Title && titles_equal(&t.text, &p.text)) .unwrap_or(false) { continue; } out.push(p); continue; } para_buf.push(clean_inline(trimmed)); } if in_code { let code = code_buf.join("\n").trim_end().to_string(); if !code.is_empty() { flush_para(&mut para_buf, &mut out); out.push(Paragraph { style: ParagraphStyle::Monospace, text: code, checked: false, }); } } flush_para(&mut para_buf, &mut out); // Ensure we always have a title line for Notes if out.is_empty() { out.push(Paragraph { style: ParagraphStyle::Title, text: "Note".into(), checked: false, }); } else if out[0].style != ParagraphStyle::Title { let fallback = out[0].text.chars().take(80).collect::(); out.insert( 0, Paragraph { style: ParagraphStyle::Title, text: if fallback.is_empty() { "Note".into() } else { fallback }, checked: false, }, ); } out } pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String { let mut lines: Vec = Vec::new(); let mut prev: Option = None; for (i, p) in paragraphs.iter().enumerate() { let rendered = match p.style { ParagraphStyle::Title => p.text.clone(), ParagraphStyle::Heading | ParagraphStyle::Subheading => p.text.clone(), ParagraphStyle::Body => p.text.clone(), ParagraphStyle::Bullet => format!("• {}", p.text), ParagraphStyle::Dashed => format!("– {}", p.text), ParagraphStyle::Numbered => { // Count consecutive numbered items for display numbers let n = paragraphs[..=i] .iter() .rev() .take_while(|x| x.style == ParagraphStyle::Numbered) .count(); format!("{n}. {}", p.text) } ParagraphStyle::Checklist => { if p.checked { format!("☑ {}", p.text) } else { format!("☐ {}", p.text) } } ParagraphStyle::Monospace => p.text.clone(), }; let need_blank = match (prev, p.style) { (None, _) => false, (Some(ParagraphStyle::Title), _) => true, // Apple Notes: blank under Heading/Subheading before body or lists ( Some(ParagraphStyle::Heading | ParagraphStyle::Subheading), ParagraphStyle::Body | ParagraphStyle::Bullet | ParagraphStyle::Dashed | ParagraphStyle::Numbered | ParagraphStyle::Checklist | ParagraphStyle::Monospace, ) => true, (Some(ParagraphStyle::Body), ParagraphStyle::Body) => true, (Some(ParagraphStyle::Body), ParagraphStyle::Heading) => true, (Some(ParagraphStyle::Body), ParagraphStyle::Subheading) => true, (Some(ParagraphStyle::Monospace), _) => true, (Some(_), ParagraphStyle::Heading | ParagraphStyle::Subheading) => true, ( Some( ParagraphStyle::Bullet | ParagraphStyle::Dashed | ParagraphStyle::Numbered | ParagraphStyle::Checklist, ), ParagraphStyle::Body, ) => true, ( Some(ParagraphStyle::Body), ParagraphStyle::Bullet | ParagraphStyle::Dashed | ParagraphStyle::Numbered | ParagraphStyle::Checklist, ) => true, _ => false, }; if need_blank && lines.last().map(|s| !s.is_empty()).unwrap_or(false) { lines.push(String::new()); } if p.style == ParagraphStyle::Monospace { for (j, code_line) in rendered.lines().enumerate() { if j == 0 && need_blank && lines.last().map(|s| !s.is_empty()).unwrap_or(false) { // already added blank } lines.push(code_line.to_string()); } // trailing blank after code block lines.push(String::new()); } else { lines.push(rendered); } prev = Some(p.style); } while lines.last().map(|s| s.is_empty()).unwrap_or(false) { lines.pop(); } lines.join("\n") } fn parse_special_line(trimmed: &str) -> Option { // ATX headings if let Some(rest) = trimmed.strip_prefix("### ") { return Some(Paragraph { style: ParagraphStyle::Subheading, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("## ") { return Some(Paragraph { style: ParagraphStyle::Heading, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("# ") { return Some(Paragraph { style: ParagraphStyle::Heading, text: clean_inline(rest), checked: false, }); } // Checklist for (prefix, checked) in [("* [x] ", true), ("* [X] ", true), ("* [ ] ", false), ("- [x] ", true), ("- [X] ", true), ("- [ ] ", false), ("+ [x] ", true), ("+ [ ] ", false)] { if let Some(rest) = trimmed.strip_prefix(prefix) { return Some(Paragraph { style: ParagraphStyle::Checklist, text: clean_inline(rest), checked, }); } } // Bullets for prefix in ["* ", "- ", "+ ", "• ", "– ", "— "] { if let Some(rest) = trimmed.strip_prefix(prefix) { // avoid matching --- horizontal rules already handled? if prefix == "- " && (rest.starts_with("--") || rest.is_empty()) { break; } return Some(Paragraph { style: ParagraphStyle::Bullet, text: clean_inline(rest), checked: false, }); } } // Numbered: "1. item" or "1) item" if let Some(dot) = trimmed.find(". ") { let (num, rest) = trimmed.split_at(dot); if !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()) { return Some(Paragraph { style: ParagraphStyle::Numbered, text: clean_inline(&rest[2..]), checked: false, }); } } if let Some(paren) = trimmed.find(") ") { let (num, rest) = trimmed.split_at(paren); if !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()) { return Some(Paragraph { style: ParagraphStyle::Numbered, text: clean_inline(&rest[2..]), checked: false, }); } } None } fn clean_title(title: &str) -> String { let t = title.replace('\n', " ").replace('\r', " "); let t = clean_inline(t.trim()); // Strip leading markdown heading markers from title let t = t.trim_start_matches('#').trim().to_string(); // Prefer a concise title (Notes list truncates anyway) if t.chars().count() > 80 { let mut s: String = t.chars().take(77).collect(); s.push('…'); s } else { t } } fn clean_inline(s: &str) -> String { let mut out = s.to_string(); // **bold** / __bold__ / *italic* / _italic_ / ~~strike~~ / `code` out = strip_wrapping_markers(&out, "**"); out = strip_wrapping_markers(&out, "__"); out = strip_wrapping_markers(&out, "~~"); out = strip_wrapping_markers(&out, "`"); // single-asterisk italics (careful with lists — already handled) out = strip_wrapping_markers(&out, "*"); out = strip_wrapping_markers(&out, "_"); // [text](url) → text (url) out = rewrite_md_links(&out); // collapse whitespace let parts: Vec<_> = out.split_whitespace().collect(); parts.join(" ") } fn strip_wrapping_markers(s: &str, marker: &str) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; let mlen = marker.len(); while let Some(start) = rest.find(marker) { out.push_str(&rest[..start]); let after = &rest[start + mlen..]; if let Some(end) = after.find(marker) { out.push_str(&after[..end]); rest = &after[end + mlen..]; } else { out.push_str(marker); rest = after; } } out.push_str(rest); out } fn rewrite_md_links(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(start) = rest.find('[') { out.push_str(&rest[..start]); let after = &rest[start + 1..]; if let Some(mid) = after.find("](") { let label = &after[..mid]; let after_url = &after[mid + 2..]; if let Some(end) = after_url.find(')') { let url = &after_url[..end]; if label == url || label.is_empty() { out.push_str(url); } else { out.push_str(label); out.push(' '); out.push('('); out.push_str(url); out.push(')'); } rest = &after_url[end + 1..]; continue; } } out.push('['); rest = after; } out.push_str(rest); out } fn strip_outer_fence(body: &str) -> String { let t = body.trim(); if t.starts_with("```") && t.ends_with("```") { let mut lines: Vec<&str> = t.lines().collect(); if lines.len() >= 2 { lines.remove(0); if lines.last().map(|l| l.trim() == "```").unwrap_or(false) { lines.pop(); } return lines.join("\n"); } } body.to_string() } fn titles_equal(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } #[cfg(test)] mod tests { use super::*; #[test] fn title_and_body_spacing() { let s = format_apple_note("Grocery list", "Milk and eggs for the week."); assert_eq!(s, "Grocery list\n\nMilk and eggs for the week."); } #[test] fn markdown_headings_and_bullets() { let body = "## Details\n\n- First item\n- Second item\n\nMore text here."; let s = format_apple_note("Project", body); assert!(s.starts_with("Project\n\n")); assert!(s.contains("Details\n\n")); assert!(s.contains("• First item\n• Second item")); assert!(s.contains("\n\nMore text here.")); assert!(!s.contains("## ")); assert!(!s.contains("- First")); } #[test] fn strips_bold_and_links() { let s = format_apple_note( "Hello", "This is **bold** and a [link](https://example.com).", ); assert!(s.contains("This is bold and a link (https://example.com).")); assert!(!s.contains("**")); } #[test] fn checklist_and_numbered() { let body = "- [ ] Todo one\n- [x] Done two\n1. Alpha\n2. Beta"; let s = format_apple_note("Tasks", body); assert!(s.contains("☐ Todo one")); assert!(s.contains("☑ Done two")); assert!(s.contains("1. Alpha")); assert!(s.contains("2. Beta")); } #[test] fn does_not_duplicate_title_in_body() { let s = format_apple_note("Same", "Same\n\nActual body."); assert_eq!(s.matches("Same").count(), 1); assert!(s.contains("Actual body.")); } #[test] fn code_block_preserved() { let body = "Intro\n\n```\nlet x = 1;\n```\n\nOutro"; let s = format_apple_note("Code", body); assert!(s.contains("let x = 1;")); assert!(s.contains("Intro")); assert!(s.contains("Outro")); assert!(!s.contains("```")); } #[test] fn structured_styles() { let ps = build_paragraphs("T", "## H\n\nbody para\n\n- a"); assert_eq!(ps[0].style, ParagraphStyle::Title); assert_eq!(ps[1].style, ParagraphStyle::Heading); assert_eq!(ps[2].style, ParagraphStyle::Body); assert_eq!(ps[3].style, ParagraphStyle::Bullet); } }