//! The note layout: one LoroText, `doc.get_text("body")`. //! //! Every block is its content followed by [`SEP`], so a body always ends with one; a //! fresh note is a single `SEP` (one empty paragraph). Inside a block `'\n'` is a hard //! break, or a newline in code. An image is [`OBJ`] under an `image` mark. Inline marks //! (`strong`, `em`, `code`, `link`) may span separators (one mark over a styled run of //! blocks); readers ignore them there. //! //! Block attributes are marks read from the separator only, all with expand None: //! - `b`: `"h1"`..`"h6"`, `"code"` or `"hr"`; absent for a paragraph. //! - `lang`: the language of a code block. //! - `wrap`: the containers around the block, outermost first, one char per level: //! `q` blockquote, `u` bullet list, `o` ordered list. //! - `join`: how many levels the block shares with the previous one, when that is not //! the default (see [`default_join`]). //! - `start`: the number of an ordered list the block opens, when not 1. //! //! Marks of equal value on consecutive separators are one mark over the whole run, so //! a long list is a single `wrap` mark. Content chars inside that range carry the mark //! too, which readers ignore. use std::collections::HashMap; use loro::{LoroDoc, LoroResult, LoroText, LoroValue, TextDelta}; use crate::marks::Marks; use crate::tree::value_str; use crate::write::{Block, Inline, apply_marks}; pub const BODY: &str = "body"; /// Ends every block. pub const SEP: char = '\u{2029}'; pub const SEP_STR: &str = "\u{2029}"; /// An image's place in the text; its attributes are the `image` mark. pub const OBJ: char = '\u{FFFC}'; pub const KEY_KIND: &str = "b"; pub const KEY_LANG: &str = "lang"; pub const KEY_WRAP: &str = "wrap"; pub const KEY_JOIN: &str = "join"; pub const KEY_START: &str = "start"; pub const KEY_IMAGE: &str = "image"; /// Every key that lives on separators. pub const BLOCK_KEYS: [&str; 5] = [KEY_KIND, KEY_LANG, KEY_WRAP, KEY_JOIN, KEY_START]; pub fn body(doc: &LoroDoc) -> LoroText { doc.get_text(BODY) } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)] pub enum Kind { #[default] Para, Heading(u8), Code, Rule, } impl Kind { pub fn from_value(v: Option<&LoroValue>) -> Kind { let Some(s) = v.and_then(|v| v.as_string()) else { return Kind::Para }; match s.as_str() { "code" => Kind::Code, "hr" => Kind::Rule, h if h.len() == 2 && h.starts_with('h') => match h.as_bytes()[1] { n @ b'1'..=b'6' => Kind::Heading(n - b'0'), _ => Kind::Para, }, _ => Kind::Para, } } pub fn value(self) -> Option { let s = match self { Kind::Para => return None, Kind::Heading(n) => ["h1", "h2", "h3", "h4", "h5", "h6"][n.clamp(1, 6) as usize - 1], Kind::Code => "code", Kind::Rule => "hr", }; Some(s.into()) } /// Whether the block holds editable inline content. pub fn is_text(self) -> bool { self != Kind::Rule } } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Wrap { Quote, Bullet, Ordered, } impl Wrap { pub fn is_list(self) -> bool { self != Wrap::Quote } fn char(self) -> char { match self { Wrap::Quote => 'q', Wrap::Bullet => 'u', Wrap::Ordered => 'o', } } fn from_char(c: char) -> Option { match c { 'q' => Some(Wrap::Quote), 'u' => Some(Wrap::Bullet), 'o' => Some(Wrap::Ordered), _ => None, } } } pub fn wrap_from_value(v: Option<&LoroValue>) -> Vec { v.and_then(|v| v.as_string()).map(|s| s.chars().filter_map(Wrap::from_char).collect()).unwrap_or_default() } pub fn wrap_value(wrap: &[Wrap]) -> Option { (!wrap.is_empty()).then(|| wrap.iter().map(|w| w.char()).collect::().into()) } /// The attributes of a block, from its separator. #[derive(Clone, PartialEq, Eq, Hash, Debug, Default)] pub struct Attrs { pub kind: Kind, pub lang: Option, pub wrap: Vec, pub join: Option, pub start: Option, } impl Attrs { pub fn from_map(attrs: Option<&HashMap>) -> Attrs { let mut out = Attrs::default(); for (k, v) in attrs.into_iter().flatten() { out.set(k, v); } out } /// Applies one key of a separator's marks; null or a foreign key clears or does /// nothing. Returns whether `key` is a block key. pub fn set(&mut self, key: &str, v: &LoroValue) -> bool { let num = |v: &LoroValue| match v { LoroValue::I64(i) => Some(*i), LoroValue::Double(d) => Some(*d as i64), _ => None, }; match key { KEY_KIND => self.kind = Kind::from_value(Some(v)), KEY_LANG => self.lang = value_str(v).filter(|l| !l.is_empty()), KEY_WRAP => self.wrap = wrap_from_value(Some(v)), KEY_JOIN => self.join = num(v).map(|j| j.max(0) as usize), KEY_START => self.start = num(v), _ => return false, } true } /// The value of each of [`BLOCK_KEYS`], None when unset. pub fn values(&self) -> [Option; 5] { [ self.kind.value(), self.lang.as_deref().map(LoroValue::from), wrap_value(&self.wrap), self.join.map(|j| LoroValue::from(j as i64)), self.start.filter(|&s| s != 1).map(LoroValue::from), ] } } /// One block of the body: its attributes and content. Code content is one text run. #[derive(Clone, PartialEq, Debug, Default)] pub struct FlatBlock { pub attrs: Attrs, pub inl: Vec, /// UTF-16 length including the separator. pub len16: usize, /// Unicode scalars including the separator (Loro's text positions). pub lenu: usize, } impl FlatBlock { pub fn plain(&self) -> String { let mut s = String::new(); for i in &self.inl { match i { Inline::Text(t, _) => s.push_str(t), Inline::HardBreak => s.push('\n'), Inline::Image { .. } => {} } } s } } /// How many levels a block shares with the previous one when its `join` is unset: /// within the common wrap prefix, everything above the deepest list, so the block is /// the next item of that list. Without a list in common, the whole common prefix. pub fn default_join(prev: &[Wrap], cur: &[Wrap]) -> usize { let common = prev.iter().zip(cur).take_while(|(a, b)| a == b).count(); match cur[..common].iter().rposition(|w| w.is_list()) { Some(d) => d, None => common, } } // --------------------------------------------------------------------------- // Reading // --------------------------------------------------------------------------- /// Unicode scalars and UTF-16 units of `s`. ASCII, nearly all text, counts as bytes. pub fn str_lens(s: &str) -> (usize, usize) { // Lead bytes count chars, 4-byte leads count surrogate pairs; ASCII chunks are skipped. let (mut unicode, mut wide) = (0, 0); for c in s.as_bytes().chunks(4096) { if c.is_ascii() { unicode += c.len(); continue; } for &b in c { unicode += ((b as i8) >= -0x40) as usize; wide += (b >= 0xF0) as usize; } } (unicode, unicode + wide) } /// Every block of the body. pub fn read(text: &LoroText) -> Vec { read_delta(text.to_delta()) } pub fn read_doc(doc: &LoroDoc) -> Vec { read(&body(doc)) } /// Blocks from rich-text delta runs, split at separators. Content after the last /// separator, which concurrent edits can leave, is a last paragraph. pub fn read_delta(delta: Vec) -> Vec { let mut out = Vec::new(); let mut cur = FlatBlock::default(); // The current block's text in runs of equal marks, split into inlines once its // separator gives its kind: a code block stays one text however many lines it has. let mut runs: Vec<(String, Marks, Option)> = Vec::new(); for d in delta { let TextDelta::Insert { insert, attributes } = d else { continue }; let attrs = attributes.as_ref(); let marks = attrs.map(Marks::from_attrs).unwrap_or_default(); let image = attrs.and_then(|a| a.get(KEY_IMAGE)).filter(|v| !matches!(v, LoroValue::Null)); for (i, piece) in insert.split(SEP).enumerate() { if i > 0 { cur.attrs = Attrs::from_map(attrs); cur.len16 += 1; cur.lenu += 1; finish_block(&mut cur, &mut runs); out.push(std::mem::take(&mut cur)); } if piece.is_empty() { continue; } let (u, u16) = str_lens(piece); cur.len16 += u16; cur.lenu += u; match runs.last_mut() { Some((t, m, img)) if *m == marks && img.as_ref() == image => t.push_str(piece), _ => runs.push((piece.to_owned(), marks.clone(), image.cloned())), } } } if !runs.is_empty() { finish_block(&mut cur, &mut runs); out.push(cur); } out } /// Turns the text `runs` of a block into its inlines. A code block's is its plain text. fn finish_block(b: &mut FlatBlock, runs: &mut Vec<(String, Marks, Option)>) { if b.attrs.kind == Kind::Code { let mut text = String::new(); for (t, _, image) in runs.drain(..) { match image { Some(_) => text.extend(t.chars().filter(|&c| c != OBJ)), None if text.is_empty() => text = t, None => text.push_str(&t), } } if !text.is_empty() { b.inl.push(Inline::Text(text, Marks::default())); } return; } for (t, marks, image) in runs.drain(..) { push_piece(b, &t, &marks, image.as_ref()); } } fn push_piece(b: &mut FlatBlock, piece: &str, marks: &Marks, image: Option<&LoroValue>) { let text = |s: &str, b: &mut FlatBlock| { if s.is_empty() { return; } match b.inl.last_mut() { Some(Inline::Text(t, m)) if m == marks => t.push_str(s), _ => b.inl.push(Inline::Text(s.to_owned(), marks.clone())), } }; let mut rest = piece; loop { let stop = rest.find(|c| c == '\n' || (c == OBJ && image.is_some())); let Some(at) = stop else { text(rest, b); return; }; text(&rest[..at], b); let c = rest[at..].chars().next().unwrap(); if c == '\n' { b.inl.push(Inline::HardBreak); } else if let Some(v) = image { let get = |k: &str| v.get_by_key(k).and_then(value_str); b.inl.push(Inline::Image { src: get("src").unwrap_or_default(), alt: get("alt").unwrap_or_default(), title: get("title").filter(|t| !t.is_empty()), }); } rest = &rest[at + c.len_utf8()..]; } } /// Rebuilds the block tree from flat blocks. pub fn nest(blocks: &[FlatBlock]) -> Vec { // The open containers, outermost first: their wrap and the blocks so far. A list // collects items; `Open::items` holds them, the last one open. struct Open { wrap: Wrap, start: i64, items: Vec>, } fn close(open: Open) -> Block { match open.wrap { Wrap::Quote => Block::Quote(open.items.into_iter().next().unwrap_or_default()), w => Block::List { ordered: w == Wrap::Ordered, start: open.start, items: open.items }, } } fn target<'a>(root: &'a mut Vec, stack: &'a mut [Open]) -> &'a mut Vec { match stack.last_mut() { Some(o) => o.items.last_mut().unwrap(), None => root, } } fn pop(root: &mut Vec, stack: &mut Vec) { let o = stack.pop().unwrap(); let b = close(o); target(root, stack).push(b); } let mut root = Vec::new(); let mut stack: Vec = Vec::new(); for b in blocks { let wrap = &b.attrs.wrap; let prev: Vec = stack.iter().map(|o| o.wrap).collect(); let common = prev.iter().zip(wrap).take_while(|(a, c)| a == c).count(); let keep = b.attrs.join.unwrap_or_else(|| default_join(&prev, wrap)).min(common); // Levels below `keep` stay; at `keep`, a list in common gets a new item. let new_item = keep < common && wrap[keep].is_list(); let stay = if new_item { keep + 1 } else { keep }; while stack.len() > stay { pop(&mut root, &mut stack); } if new_item { stack[keep].items.push(Vec::new()); } let deepest_new_ordered = (stack.len()..wrap.len()).rev().find(|&i| wrap[i] == Wrap::Ordered); for (i, &w) in wrap.iter().enumerate().skip(stack.len()) { let start = if Some(i) == deepest_new_ordered { b.attrs.start.unwrap_or(1) } else { 1 }; stack.push(Open { wrap: w, start, items: vec![Vec::new()] }); } target(&mut root, &mut stack).push(leaf(b)); } while !stack.is_empty() { pop(&mut root, &mut stack); } root } fn leaf(b: &FlatBlock) -> Block { match b.attrs.kind { Kind::Para => Block::Paragraph(b.inl.clone()), Kind::Heading(n) => Block::Heading(n as i64, b.inl.clone()), Kind::Code => Block::Code { lang: b.attrs.lang.clone(), text: b.plain() }, Kind::Rule => Block::Rule, } } /// The note's block tree. pub fn doc_blocks(doc: &LoroDoc) -> Vec { nest(&read_doc(doc)) } // --------------------------------------------------------------------------- // Writing // --------------------------------------------------------------------------- /// Flattens a block tree. Every container gets at least one block, so an empty quote /// or list item survives as an empty paragraph. pub fn flatten(blocks: &[Block]) -> Vec { // Each level of the path: wrap, container instance, item index. type Level = (Wrap, usize, usize); struct Cx { out: Vec, prev: Vec, next_id: usize, /// The ordered list a block opens, set until its first leaf. start: Option, } fn walk(cx: &mut Cx, path: &mut Vec, blocks: &[Block]) { if blocks.is_empty() { emit(cx, path, Kind::Para, None, Vec::new()); } for b in blocks { match b { Block::Paragraph(inl) => emit(cx, path, Kind::Para, None, inl.clone()), Block::Heading(n, inl) => emit(cx, path, Kind::Heading((*n).clamp(1, 6) as u8), None, inl.clone()), Block::Code { lang, text } => { let inl = if text.is_empty() { Vec::new() } else { vec![Inline::Text(text.clone(), Marks::default())] }; emit(cx, path, Kind::Code, lang.clone().filter(|l| !l.is_empty()), inl) } Block::Rule => emit(cx, path, Kind::Rule, None, Vec::new()), Block::Quote(inner) => { cx.next_id += 1; path.push((Wrap::Quote, cx.next_id, 0)); walk(cx, path, inner); path.pop(); } Block::List { ordered, start, items } => { if items.is_empty() { continue; } cx.next_id += 1; let w = if *ordered { Wrap::Ordered } else { Wrap::Bullet }; if *ordered && *start != 1 { cx.start = Some(*start); } for (i, item) in items.iter().enumerate() { path.push((w, cx.next_id, i)); walk(cx, path, item); path.pop(); } } } } } fn emit(cx: &mut Cx, path: &[Level], kind: Kind, lang: Option, inl: Vec) { // Levels in the same container and item as the previous block. At the next level // `nest` starts a new item when both are lists of one kind, else new containers. let same = cx.prev.iter().zip(path).take_while(|(a, b)| a == b).count(); let wrap: Vec = path.iter().map(|l| l.0).collect(); let prev: Vec = cx.prev.iter().map(|l| l.0).collect(); let attrs = Attrs { kind, lang, join: (same != default_join(&prev, &wrap)).then_some(same), start: cx.start.take(), wrap, }; cx.out.push(FlatBlock { attrs, inl, len16: 0, lenu: 0 }); cx.prev = path.to_vec(); } let mut cx = Cx { out: Vec::new(), prev: Vec::new(), next_id: 0, start: None }; walk(&mut cx, &mut Vec::new(), blocks); cx.out } /// The text of `blocks` and its marks, as [`write`] inserts them. Positions are /// Unicode scalars from the start of the text. pub struct Built { pub text: String, /// Inline mark runs: range and marks. pub inline: Vec<(std::ops::Range, Marks)>, pub images: Vec<(usize, LoroValue)>, /// The separator position and attributes of each block. pub seps: Vec<(usize, [Option; 5])>, } pub fn build(blocks: &[FlatBlock]) -> Built { let mut b = Built { text: String::new(), inline: Vec::new(), images: Vec::new(), seps: Vec::with_capacity(blocks.len()) }; let mut pos = 0usize; let push = |b: &mut Built, s: &str, pos: &mut usize| { for c in s.chars() { b.text.push(if c == SEP { '\n' } else { c }); } let n = s.chars().count(); *pos += n; n }; for block in blocks { for i in &block.inl { match i { Inline::Text(s, m) => { let start = pos; let n = push(&mut b, s, &mut pos); if n > 0 && *m != Marks::default() && block.attrs.kind != Kind::Code { b.inline.push((start..pos, m.clone())); } } Inline::HardBreak => { push(&mut b, "\n", &mut pos); } Inline::Image { src, alt, title } => { let mut map: HashMap = HashMap::new(); map.insert("src".into(), src.as_str().into()); map.insert("alt".into(), alt.as_str().into()); if let Some(t) = title { map.insert("title".into(), t.as_str().into()); } b.images.push((pos, map.into())); b.text.push(OBJ); pos += 1; } } } b.seps.push((pos, block.attrs.values())); b.text.push(SEP); pos += 1; } b } /// Inserts `blocks` at Unicode position `at` and returns the inserted length. With /// `clean`, marks the surrounding text would lend the new text are cleared first. pub fn write(text: &LoroText, at: usize, blocks: &[FlatBlock], clean: bool) -> LoroResult { let built = build(blocks); if built.text.is_empty() { return Ok(0); } text.insert(at, &built.text)?; let end = at + built.seps.last().map_or(0, |s| s.0 + 1); if clean { for key in BLOCK_KEYS.iter().chain(&["strong", "em", "code", "link", KEY_IMAGE]) { text.unmark(at..end, key)?; } } for (range, marks) in &built.inline { apply_marks(text, at + range.start..at + range.end, marks)?; } for (pos, v) in &built.images { text.mark(at + pos..at + pos + 1, KEY_IMAGE, v.clone())?; } mark_seps(text, at, &built.seps)?; Ok(end - at) } /// Marks block attributes on separators, one mark per run of equal values. pub fn mark_seps(text: &LoroText, at: usize, seps: &[(usize, [Option; 5])]) -> LoroResult<()> { for (k, key) in BLOCK_KEYS.iter().enumerate() { let mut i = 0; while i < seps.len() { let Some(v) = &seps[i].1[k] else { i += 1; continue; }; let mut j = i + 1; while j < seps.len() && seps[j].1[k].as_ref() == Some(v) { j += 1; } text.mark(at + seps[i].0..at + seps[j - 1].0 + 1, key, v.clone())?; i = j; } } Ok(()) } /// A new doc's body: one empty paragraph. pub fn init(doc: &LoroDoc) -> LoroResult<()> { let text = body(doc); if text.len_unicode() == 0 { text.insert(0, SEP_STR)?; } Ok(()) } // --------------------------------------------------------------------------- // Queries // --------------------------------------------------------------------------- /// Plain text of the first non-blank block. Reads the head of the body first, so a /// huge note costs no more than its start. pub fn first_text(doc: &LoroDoc) -> String { let text = body(doc); let len = text.len_unicode(); let mut head = 4096usize; loop { let n = head.min(len); let delta = text.slice_delta(0, n, loro::cursor::PosType::Unicode).unwrap_or_default(); let mut blocks = read_delta(delta); // The last block may be cut off unless the whole body was read. if n < len { blocks.pop(); } if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) { return b.plain(); } if n == len { return String::new(); } head *= 16; } } #[cfg(test)] mod tests { use super::*; fn p(s: &str) -> Block { Block::Paragraph(vec![Inline::Text(s.into(), Marks::default())]) } fn ul(items: Vec>) -> Block { Block::List { ordered: false, start: 1, items } } #[test] fn round_trip() { let bold = Marks { strong: true, ..Marks::default() }; let tree = vec![ Block::Heading(2, vec![Inline::Text("Title".into(), Marks::default())]), Block::Paragraph(vec![ Inline::Text("a ".into(), Marks::default()), Inline::Text("bold".into(), bold), Inline::HardBreak, Inline::Image { src: "x.png".into(), alt: "x".into(), title: None }, ]), ul(vec![vec![p("one"), ul(vec![vec![p("nested")], vec![p("nested 2")]])], vec![p("two"), p("two b")], vec![p("three")]]), Block::List { ordered: true, start: 3, items: vec![vec![p("c")], vec![Block::Quote(vec![p("q1"), p("q2")])], vec![Block::Quote(vec![p("q3")])]] }, Block::Quote(vec![p("quoted"), ul(vec![vec![p("in quote")]])]), Block::Code { lang: Some("rust".into()), text: "fn main() {\n}\n".into() }, Block::Rule, Block::Paragraph(Vec::new()), ]; let doc = LoroDoc::new(); doc.config_text_style(crate::schema::text_style_config()); write(&body(&doc), 0, &flatten(&tree), false).unwrap(); doc.commit(); let copy = LoroDoc::new(); copy.import(&doc.export(loro::ExportMode::Snapshot).unwrap()).unwrap(); assert_eq!(doc_blocks(©), tree); assert_eq!(first_text(©), "Title"); } }