//! Format note content the way Apple Notes expects to look. //! //! Follows Apple Support guidance for Notes paragraph styles and lists: //! //! //! //! //! Structure: Title (first line) → Heading / Subheading sections → Body → //! lists (bulleted / dashed / numbered / checklist) → optional dividers, //! block quotes, monostyled blocks, and simple tables. //! //! 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, /// Apple Notes “Insert Divider Line” (plain-text stand-in). Divider, /// Apple Notes Block Quote style. BlockQuote, } #[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 mut table_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, }); }; let flush_table = |buf: &mut Vec, out: &mut Vec| { if buf.is_empty() { return; } let rows = std::mem::take(buf); if let Some(text) = format_md_table(&rows) { out.push(Paragraph { style: ParagraphStyle::Monospace, text, checked: false, }); } else { for row in rows { out.push(Paragraph { style: ParagraphStyle::Body, text: clean_inline(row.trim_matches('|').trim()), checked: false, }); } } }; let body_lines: Vec<&str> = body.lines().collect(); let mut i = 0; while i < body_lines.len() { let line = body_lines[i].trim_end(); let trimmed = line.trim(); if trimmed.starts_with("```") { flush_table(&mut table_buf, &mut out); 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; } i += 1; continue; } if in_code { code_buf.push(line.to_string()); i += 1; continue; } // GFM pipe tables if trimmed.starts_with('|') && trimmed.contains('|') { flush_para(&mut para_buf, &mut out); table_buf.push(trimmed.to_string()); i += 1; continue; } if !table_buf.is_empty() { flush_table(&mut table_buf, &mut out); } if trimmed.is_empty() { flush_para(&mut para_buf, &mut out); i += 1; continue; } // Apple Notes divider line (Markdown HR → Insert Divider Line stand-in) if is_divider_marker(trimmed) { flush_para(&mut para_buf, &mut out); out.push(Paragraph { style: ParagraphStyle::Divider, text: String::new(), checked: false, }); i += 1; continue; } if let Some(p) = parse_special_line(trimmed) { flush_para(&mut para_buf, &mut out); if p.style != ParagraphStyle::Divider && p.text.is_empty() { i += 1; continue; } // Don't re-add title-looking heading if it matches note title if matches!( p.style, ParagraphStyle::Heading | ParagraphStyle::Subheading ) && out .first() .map(|t| t.style == ParagraphStyle::Title && titles_equal(&t.text, &p.text)) .unwrap_or(false) { i += 1; continue; } out.push(p); i += 1; continue; } para_buf.push(clean_inline(trimmed)); i += 1; } if !table_buf.is_empty() { flush_table(&mut table_buf, &mut out); } 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); // Apple: first line of the note becomes the title 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(), // Apple list glyphs (support.apple.com/guide/notes/add-lists) ParagraphStyle::Bullet => format!("• {}", p.text), ParagraphStyle::Dashed => format!("– {}", p.text), ParagraphStyle::Numbered => { 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(), ParagraphStyle::Divider => "────────────────".into(), ParagraphStyle::BlockQuote => format!("│ {}", p.text), }; let listish = matches!( p.style, ParagraphStyle::Bullet | ParagraphStyle::Dashed | ParagraphStyle::Numbered | ParagraphStyle::Checklist ); let need_blank = match (prev, p.style) { (None, _) => false, (Some(ParagraphStyle::Title), _) => true, ( Some(ParagraphStyle::Heading | ParagraphStyle::Subheading), ParagraphStyle::Body | ParagraphStyle::Bullet | ParagraphStyle::Dashed | ParagraphStyle::Numbered | ParagraphStyle::Checklist | ParagraphStyle::Monospace | ParagraphStyle::BlockQuote | ParagraphStyle::Divider, ) => 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::Divider), _) => true, (Some(_), ParagraphStyle::Divider) => true, (Some(ParagraphStyle::BlockQuote), ParagraphStyle::BlockQuote) => false, (Some(_), ParagraphStyle::BlockQuote) => true, (Some(ParagraphStyle::BlockQuote), _) if !listish => 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, // Blank when switching list kinds (e.g. dashed → checklist) ( Some( ParagraphStyle::Bullet | ParagraphStyle::Dashed | ParagraphStyle::Numbered | ParagraphStyle::Checklist, ), _, ) if listish && prev.is_some_and(|pr| { !matches!( (pr, p.style), (ParagraphStyle::Bullet, ParagraphStyle::Bullet) | (ParagraphStyle::Dashed, ParagraphStyle::Dashed) | (ParagraphStyle::Numbered, ParagraphStyle::Numbered) | (ParagraphStyle::Checklist, 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 code_line in rendered.lines() { lines.push(code_line.to_string()); } 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 is_divider_marker(trimmed: &str) -> bool { let t = trimmed.trim(); if t.len() < 3 { return false; } t.chars().all(|c| c == '-' || c == '*' || c == '_' || c == '─') } fn parse_special_line(trimmed: &str) -> Option { // ATX headings → Apple Heading / Subheading (Title is the note’s first line) 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, }); } // Block quote if let Some(rest) = trimmed.strip_prefix("> ") { return Some(Paragraph { style: ParagraphStyle::BlockQuote, text: clean_inline(rest), checked: false, }); } if trimmed == ">" { return Some(Paragraph { style: ParagraphStyle::BlockQuote, text: String::new(), checked: false, }); } // Checklist (before plain list markers) 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, }); } } // Apple typing shortcuts (Add lists in Notes): // * + space → Bulleted List // - + space → Dashed List // 1. + space → Numbered List if let Some(rest) = trimmed.strip_prefix("* ") { return Some(Paragraph { style: ParagraphStyle::Bullet, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("• ") { return Some(Paragraph { style: ParagraphStyle::Bullet, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("- ") { return Some(Paragraph { style: ParagraphStyle::Dashed, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("+ ") { // Markdown “+” lists → bulleted (closest Apple style) return Some(Paragraph { style: ParagraphStyle::Bullet, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("– ") { return Some(Paragraph { style: ParagraphStyle::Dashed, text: clean_inline(rest), checked: false, }); } if let Some(rest) = trimmed.strip_prefix("— ") { return Some(Paragraph { style: ParagraphStyle::Dashed, 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 format_md_table(rows: &[String]) -> Option { if rows.len() < 2 { return None; } let mut cells: Vec> = Vec::new(); for (idx, row) in rows.iter().enumerate() { let parts: Vec = row .trim() .trim_matches('|') .split('|') .map(|c| clean_inline(c.trim())) .collect(); if idx == 1 && parts.iter().all(|c| is_table_separator(c)) { continue; // alignment row } if parts.is_empty() { continue; } cells.push(parts); } if cells.is_empty() { return None; } let cols = cells.iter().map(|r| r.len()).max().unwrap_or(0); if cols == 0 { return None; } let mut widths = vec![0usize; cols]; for row in &cells { for (i, cell) in row.iter().enumerate() { widths[i] = widths[i].max(cell.chars().count()); } } let mut out_lines = Vec::new(); for (ri, row) in cells.iter().enumerate() { let mut line = String::new(); for (i, w) in widths.iter().enumerate() { if i > 0 { line.push_str(" "); } let cell = row.get(i).map(|s| s.as_str()).unwrap_or(""); line.push_str(cell); let pad = w.saturating_sub(cell.chars().count()); line.push_str(&" ".repeat(pad)); } out_lines.push(line.trim_end().to_string()); if ri == 0 { // subtle header underline (not a full Apple table, but readable) let mut rule = String::new(); for (i, w) in widths.iter().enumerate() { if i > 0 { rule.push_str(" "); } rule.push_str(&"─".repeat((*w).max(1))); } out_lines.push(rule); } } Some(out_lines.join("\n")) } fn is_table_separator(cell: &str) -> bool { let t = cell.trim(); if t.is_empty() { return false; } t.chars().all(|c| c == '-' || c == ':' || c == ' ') } 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` // (Apple supports bold/italic/highlight in-app; plain TopoText cannot) out = strip_wrapping_markers(&out, "**"); out = strip_wrapping_markers(&out, "__"); out = strip_wrapping_markers(&out, "~~"); out = strip_wrapping_markers(&out, "`"); out = strip_wrapping_markers(&out, "*"); out = strip_wrapping_markers(&out, "_"); // ==highlight== → plain (Notes highlight is color-only) out = strip_wrapping_markers(&out, "=="); out = rewrite_md_links(&out); 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 apple_heading_and_dashed_list() { // Apple: hyphen + space → dashed list 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 apple_asterisk_bulleted_list() { let s = format_apple_note("Shop", "* Milk\n* Eggs"); assert!(s.contains("• Milk\n• Eggs")); } #[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 divider_and_block_quote() { let body = "Before\n\n---\n\n> A short quote\n\nAfter"; let s = format_apple_note("Quote", body); assert!(s.contains("────────────────")); assert!(s.contains("│ A short quote")); assert!(s.contains("Before")); assert!(s.contains("After")); assert!(!s.contains("---")); assert!(!s.contains("> ")); } #[test] fn markdown_table_aligned() { let body = "| Item | Qty |\n| --- | --- |\n| Apples | 3 |\n| Milk | 1 |"; let s = format_apple_note("List", body); assert!(s.contains("Item")); assert!(s.contains("Apples")); assert!(s.contains("Milk")); assert!(!s.contains("| ---")); } #[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\n- b\n> q\n\n---"); 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); assert_eq!(ps[4].style, ParagraphStyle::Dashed); assert_eq!(ps[5].style, ParagraphStyle::BlockQuote); assert_eq!(ps[6].style, ParagraphStyle::Divider); } }