//! Compact builders and a dump format for core tests. //! Dump: `p(ab) h2(x) ul(li(p(a)))`, `|` for a hard break, `{s:x}` strong, `{e:x}` em, //! `{c:x}` code, `{l=href:x}` link, `hr`. use loro::LoroDoc; use note_model::flat; use note_model::marks::Marks; use note_model::write::{Block, Inline}; use super::model::{Blk, Model}; use super::pos::{Pos, Selection}; pub fn t(s: &str) -> Inline { Inline::Text(s.into(), Marks::default()) } pub fn strong(s: &str) -> Inline { Inline::Text(s.into(), Marks { strong: true, ..Marks::default() }) } pub fn br() -> Inline { Inline::HardBreak } pub fn p(s: &str) -> Block { Block::Paragraph(if s.is_empty() { Vec::new() } else { vec![t(s)] }) } pub fn pi(v: Vec) -> Block { Block::Paragraph(v) } pub fn h(n: i64, s: &str) -> Block { Block::Heading(n, vec![t(s)]) } pub fn hr() -> Block { Block::Rule } pub fn quote(v: Vec) -> Block { Block::Quote(v) } pub fn ul(items: Vec>) -> Block { Block::List { ordered: false, start: 1, items } } pub fn build(blocks: Vec) -> Model { let doc = LoroDoc::new(); super::marks::configure(&doc); let text = flat::body(&doc); if blocks.is_empty() { flat::init(&doc).unwrap(); } else { flat::write(&text, 0, &flat::flatten(&blocks), false).unwrap(); } doc.commit(); Model::new(doc) } pub fn dump(m: &Model) -> String { m.check(); flat::doc_blocks(&m.doc).iter().map(block).collect::>().join(" ") } fn block(b: &Block) -> String { match b { Block::Paragraph(v) => format!("p({})", inline(v)), Block::Heading(n, v) => format!("h{n}({})", inline(v)), Block::Code { text, .. } => format!("code({text})"), Block::Rule => "hr".into(), Block::Quote(v) => format!("quote({})", v.iter().map(block).collect::>().join(" ")), Block::List { ordered, items, .. } => format!( "{}({})", if *ordered { "ol" } else { "ul" }, items.iter().map(|i| format!("li({})", i.iter().map(block).collect::>().join(" "))).collect::>().join(" ") ), } } fn inline(v: &[Inline]) -> String { let mut s = String::new(); for i in v { match i { Inline::Text(t, m) => { let mut x = t.clone(); if m.code { x = format!("{{c:{x}}}"); } if m.strong { x = format!("{{s:{x}}}"); } if m.em { x = format!("{{e:{x}}}"); } if let Some((href, _)) = &m.link { x = format!("{{l={href}:{x}}}"); } s.push_str(&x); } Inline::HardBreak => s.push('|'), Inline::Image { .. } => s.push_str("[img]"), } } s } /// The n-th text block. pub fn tb(m: &Model, n: usize) -> Blk { let all = m.blocks(0, m.len()); all.into_iter().filter(|b| b.kind().is_text()).nth(n).expect("text block") } pub fn at(m: &Model, n: usize, off: usize) -> Selection { Selection::caret(tb(m, n).start + off) } pub fn pos(m: &Model, n: usize, off: usize) -> Pos { tb(m, n).start + off }