//! The note body as the editor edits it: the Loro text, its [`BlockIndex`] and the //! primitive edits. //! //! The index follows the body's text events, applied right after each commit or //! import ([`Model::commit`], [`Model::import`]), so it is current between edits. Every //! primitive commits, and records its inverse for [`super::history::History`]: //! positions are held by Loro cursors ([`Anchor`]), and anchors on text a delete removes //! move to the copy its undo restores. //! //! Offsets in the public API are UTF-16 from the start of the body (the DOM's unit); //! Loro positions are Unicode scalars and stay internal. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::rc::{Rc, Weak}; use std::sync::{Arc, Mutex}; use loro::cursor::{Cursor, PosType, Side}; use loro::{ContainerTrait, LoroDoc, LoroText, LoroValue, TextDelta}; use note_model::blocks::{BlockIndex, Info, Splice}; use note_model::flat::{self, Attrs, FlatBlock, Kind, SEP}; use note_model::write::Inline; use super::marks::Marks; /// Origin of the editor's own commits. pub const LOCAL: &str = "local"; /// Every mark key the editor writes, inline first. pub const KEYS: [&str; 10] = [ "strong", "em", "code", "link", flat::KEY_IMAGE, flat::KEY_KIND, flat::KEY_LANG, flat::KEY_WRAP, flat::KEY_JOIN, flat::KEY_START, ]; /// The keys of inline content (marks and images). pub const INLINE: [&str; 5] = ["strong", "em", "code", "link", flat::KEY_IMAGE]; fn key(k: &str) -> Option<&'static str> { KEYS.iter().find(|s| **s == k).copied() } /// One block: UTF-16 and Unicode offsets of its first content unit and its separator. #[derive(Clone, Debug, PartialEq)] pub struct Blk { pub index: usize, pub start: usize, pub sep: usize, pub startu: usize, pub sepu: usize, pub attrs: Attrs, } impl Blk { fn new(info: Info, attrs: &Attrs) -> Blk { Blk { index: info.index, start: info.start16, sep: info.sep16(), startu: info.startu, sepu: info.sepu(), attrs: attrs.clone() } } /// Start of the next block. pub fn end(&self) -> usize { self.sep + 1 } pub fn len(&self) -> usize { self.sep - self.start } pub fn is_empty(&self) -> bool { self.sep == self.start } pub fn kind(&self) -> Kind { self.attrs.kind } pub fn depth(&self) -> usize { self.attrs.wrap.len() } /// Whether a caret at `off` is inside (content start through the separator). pub fn holds(&self, off: usize) -> bool { self.start <= off && off <= self.sep } } /// A position that follows edits, local and remote. pub type Anchor = Rc>; /// A mark change over a Unicode range: `value` None unsets `key`. #[derive(Clone, Debug, PartialEq)] pub struct Seg { pub from: usize, pub to: usize, pub key: &'static str, pub value: Option, } /// What undoes one primitive. pub enum Inverse { /// Undoes an insert: deletes `first` through `last`. Remove { first: Anchor, last: Anchor }, /// Undoes a delete: inserts `delta` at `at`, and moves each anchor of `revive` /// (those that were on the deleted text) to its offset in the copy. Restore { at: Anchor, delta: Vec, revive: Vec<(Weak>, usize)> }, /// Undoes a restyle: segments relative to `at`. Restyle { at: Anchor, segs: Vec }, } #[derive(Default)] struct Rec { ops: Vec, /// End (Unicode) of the last insert while it is the last op: typing extends it. typing: Option, anchors: Vec>>, /// Ids of chars known deleted. A deleted char never comes back, and resolving an /// anchor on one replays history (seconds on a huge note), so it happens once. dead: HashSet, } pub struct Model { pub doc: LoroDoc, pub text: LoroText, pending: Arc>>>, index: RefCell, splices: RefCell>, rec: RefCell, origin: Cell<&'static str>, _sub: loro::Subscription, } fn plain_len(s: &str) -> (usize, usize) { note_model::flat::str_lens(s) } impl Model { pub fn new(doc: LoroDoc) -> Model { let text = flat::body(&doc); let pending: Arc>>> = Arc::default(); let queue = pending.clone(); let sub = doc.subscribe( &text.id(), Arc::new(move |e| { let mut q = queue.lock().unwrap(); for d in e.events { if let loro::event::Diff::Text(delta) = d.diff { q.push(delta); } } }), ); let index = BlockIndex::read(&text); Model { doc, text, pending, index: RefCell::new(index), splices: RefCell::default(), rec: RefCell::default(), origin: Cell::new(LOCAL), _sub: sub, } } /// Applies queued text events to the index. pub fn sync(&self) { let deltas = std::mem::take(&mut *self.pending.lock().unwrap()); for d in deltas { let sp = self.index.borrow_mut().apply(&d, &self.text); self.splices.borrow_mut().extend(sp); } } pub fn commit(&self) { self.doc.set_next_commit_origin(self.origin.get()); self.doc.commit(); self.sync(); } /// Commits with `origin` instead of [`LOCAL`]. pub fn commit_as(&self, origin: &'static str) { self.origin.set(origin); self.commit(); self.origin.set(LOCAL); } pub fn import(&self, bytes: &[u8]) -> loro::LoroResult<()> { self.commit(); let r = self.doc.import(bytes).map(|_| ()); self.sync(); r } /// Block changes since the last call, for the view. pub fn take_splices(&self) -> Vec { self.sync(); std::mem::take(&mut *self.splices.borrow_mut()) } /// Rebuilds the index from the text (after a checkout or a wholesale change). pub fn reindex(&self) { self.pending.lock().unwrap().clear(); let n = self.index.borrow().len(); *self.index.borrow_mut() = BlockIndex::read(&self.text); let m = self.index.borrow().len(); self.splices.borrow_mut().push(Splice { at: 0, removed: n, inserted: m, edit: None }); } // ----------------------------------------------------------------------- // Lookups // ----------------------------------------------------------------------- /// Runs `f` on the index. Don't edit inside `f`. pub fn with(&self, f: impl FnOnce(&BlockIndex) -> R) -> R { f(&self.index.borrow()) } pub fn len(&self) -> usize { self.index.borrow().len() } pub fn is_empty(&self) -> bool { self.index.borrow().is_empty() } /// Whether the body ends without a separator (see [`BlockIndex::open`]). pub fn open(&self) -> bool { self.index.borrow().open } /// UTF-16 length of the body. pub fn total(&self) -> usize { self.index.borrow().total16() } pub fn block(&self, i: usize) -> Option { let ix = self.index.borrow(); ix.get(i).map(|info| Blk::new(info, ix.attrs(&info))) } /// The block holding `off` (a separator belongs to its block; past the end, the /// last). An empty body (before the note loads) reads as one empty paragraph. pub fn at(&self, off: usize) -> Blk { let ix = self.index.borrow(); match ix.find16(off) { Some(info) => Blk::new(info, ix.attrs(&info)), None => Blk { index: 0, start: 0, sep: 0, startu: 0, sepu: 0, attrs: Attrs::default() }, } } pub fn last(&self) -> Blk { self.at(self.total()) } /// Blocks `lo..hi`. pub fn blocks(&self, lo: usize, hi: usize) -> Vec { let ix = self.index.borrow(); ix.iter_from(lo).take(hi.saturating_sub(lo)).map(|i| Blk::new(i, ix.attrs(&i))).collect() } /// Calls `f` on blocks from `i` on (`back`: from `i - 1` down) until it returns false. pub fn scan(&self, i: usize, back: bool, mut f: impl FnMut(&Info, &Attrs) -> bool) { let ix = self.index.borrow(); if back { for info in ix.iter_back(i) { if !f(&info, ix.attrs(&info)) { return; } } } else { for info in ix.iter_from(i) { if !f(&info, ix.attrs(&info)) { return; } } } } pub fn to_u(&self, off: usize) -> usize { if off == 0 { return 0; } self.text.convert_pos(off, PosType::Utf16, PosType::Unicode).unwrap_or_else(|| self.text.len_unicode()) } pub fn to16(&self, u: usize) -> usize { if u == 0 { return 0; } self.text.convert_pos(u, PosType::Unicode, PosType::Utf16).unwrap_or_else(|| self.text.len_utf16()) } /// Rich runs of `from..to` (UTF-16). pub fn slice(&self, from: usize, to: usize) -> Vec { if from >= to { return Vec::new(); } self.text.slice_delta(from, to, PosType::Utf16).unwrap_or_default() } /// Plain text of `from..to` (UTF-16). pub fn plain(&self, from: usize, to: usize) -> String { if from >= to { return String::new(); } let (a, b) = (self.to_u(from), self.to_u(to)); self.text.slice(a, b).unwrap_or_default() } /// The content of block `b` (inline runs; code as one text run). pub fn read_block(&self, b: &Blk) -> FlatBlock { let mut delta = self.slice(b.start, b.end()); if self.open() && b.index + 1 == self.len() { delta.push(TextDelta::Insert { insert: SEP.to_string(), attributes: None }); } let mut v = flat::read_delta(delta); let mut fb = v.pop().unwrap_or_default(); fb.attrs = b.attrs.clone(); if fb.attrs.kind == Kind::Code { let text = fb.plain(); fb.inl = if text.is_empty() { Vec::new() } else { vec![note_model::write::Inline::Text(text, Default::default())] }; } fb } // ----------------------------------------------------------------------- // Anchors // ----------------------------------------------------------------------- fn anchor_u(&self, u: usize) -> Anchor { let c = self.text.get_cursor(u, Side::Left).expect("body is attached"); let a = Rc::new(RefCell::new(c)); let mut rec = self.rec.borrow_mut(); if rec.anchors.len() > 64 && rec.anchors.len().is_power_of_two() { rec.anchors.retain(|w| w.strong_count() > 0); } rec.anchors.push(Rc::downgrade(&a)); a } /// An anchor at UTF-16 offset `off`. pub fn anchor(&self, off: usize) -> Anchor { self.anchor_u(self.to_u(off)) } /// Unicode position of an anchor, and whether its char is still there. fn resolve_u(&self, a: &Anchor) -> (usize, bool) { match self.doc.get_cursor_pos(&a.borrow()) { Ok(r) => (r.current.pos.min(self.text.len_unicode()), r.update.is_none()), Err(_) => (0, false), } } /// A plain cursor at `off`, for the presence wire format. pub fn cursor(&self, off: usize) -> Option { self.text.get_cursor(self.to_u(off), Side::Left) } /// The offset of a cursor, if it is on the body. pub fn cursor_pos(&self, c: &Cursor) -> Option { if c.container != self.text.id() { return None; } let r = self.doc.get_cursor_pos(c).ok()?; Some(self.to16(r.current.pos.min(self.text.len_unicode()))) } /// UTF-16 offset of an anchor. pub fn resolve(&self, a: &Anchor) -> usize { self.to16(self.resolve_u(a).0) } // ----------------------------------------------------------------------- // Primitives // ----------------------------------------------------------------------- fn push(&self, op: Inverse) { let mut rec = self.rec.borrow_mut(); rec.typing = None; rec.ops.push(op); } /// The inverses recorded since the last call, oldest first. pub fn take_ops(&self) -> Vec { let mut rec = self.rec.borrow_mut(); rec.typing = None; std::mem::take(&mut rec.ops) } /// Inserts plain text carrying exactly `marks`; separators in `s` become line /// breaks. Returns the end offset. pub fn insert(&self, at: usize, s: &str, marks: &Marks) -> usize { if s.is_empty() { return at; } let s = s.replace(SEP, "\n"); let inl = [Inline::Text(s, marks.into())]; self.insert_inline(at, &inl) } /// Inserts inline content (text runs, breaks, images) inside a block. Returns the /// end offset. pub fn insert_inline(&self, at: usize, inl: &[Inline]) -> usize { let u = self.to_u(at); let fb = FlatBlock { inl: inl.to_vec(), ..Default::default() }; let built = flat::build(std::slice::from_ref(&fb)); let mut s = built.text; s.pop(); if s.is_empty() { return at; } let (n, n16) = plain_len(&s); self.text.insert(u, &s).expect("insert"); // Every unit of `s` gets exactly its run's marks, nothing the neighbours lend. let mut want: Vec<(usize, Vec<(&'static str, Option)>)> = Vec::new(); let mut pos = 0; let mut cut = |to: usize, vals: Vec<(&'static str, Option)>, want: &mut Vec<_>| { if to > pos { want.push((to - pos, vals)); pos = to; } }; let none = || INLINE.iter().map(|k| (*k, None)).collect::>(); let mut marks: Vec<(std::ops::Range, Option<¬e_model::marks::Marks>, Option<&LoroValue>)> = Vec::new(); for (r, m) in &built.inline { marks.push((r.clone(), Some(m), None)); } for (p, v) in &built.images { marks.push((*p..*p + 1, None, Some(v))); } marks.sort_by_key(|m| m.0.start); for (r, m, img) in marks { cut(r.start, none(), &mut want); let mut vals = none(); if let Some(m) = m { let m: Marks = m.into(); for v in vals.iter_mut() { v.1 = m.value_of(v.0); } } if let Some(img) = img { vals[4].1 = Some(img.clone()); } cut(r.end, vals, &mut want); } cut(n, none(), &mut want); self.force(u, &want); let typing = self.rec.borrow().typing; let extended = typing == Some(u) && { let rec = self.rec.borrow(); match rec.ops.last() { Some(Inverse::Remove { last, .. }) => { *last.borrow_mut() = self.text.get_cursor(u + n - 1, Side::Left).expect("cursor"); true } _ => false, } }; if !extended { let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1)); self.push(Inverse::Remove { first, last }); } self.rec.borrow_mut().typing = Some(u + n); self.commit(); at + n16 } /// Inserts whole blocks at `at` (a block start, or inside content to split there). /// Returns the end offset. pub fn insert_blocks(&self, at: usize, blocks: &[FlatBlock]) -> usize { let u = self.to_u(at); let n = self.write_u(u, blocks); self.commit(); if n == 0 { at } else { self.to16(u + n) } } fn write_u(&self, u: usize, blocks: &[FlatBlock]) -> usize { let n = flat::write(&self.text, u, blocks, true).expect("write blocks"); if n > 0 { let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1)); self.push(Inverse::Remove { first, last }); } n } /// Deletes `from..to` (UTF-16). pub fn delete(&self, from: usize, to: usize) { if from < to { self.delete_u(self.to_u(from), self.to_u(to)); self.commit(); } } fn delete_u(&self, a: usize, b: usize) { if a >= b { return; } let delta = self.text.slice_delta(a, b, PosType::Unicode).expect("slice"); let revive = self.anchors_in(a, b); self.text.delete(a, b - a).expect("delete"); let at = self.anchor_u(a); self.push(Inverse::Restore { at, delta, revive }); } /// Anchors on the chars `a..b` with their offsets. A short range compares char ids /// (no anchor is resolved); a long one resolves every anchor. fn anchors_in(&self, a: usize, b: usize) -> Vec<(Weak>, usize)> { let live: Vec<(Weak>, Anchor)> = self.rec.borrow().anchors.iter().filter_map(|w| w.upgrade().map(|x| (w.clone(), x))).collect(); if live.is_empty() { return Vec::new(); } let found: Vec<(Weak>, usize, Option)> = if b - a <= 64 { let ids: HashMap = (a..b).filter_map(|p| self.text.get_cursor(p, Side::Left).and_then(|c| c.id).map(|id| (id, p - a))).collect(); live.into_iter().filter_map(|(w, x)| x.borrow().id.and_then(|id| ids.get(&id).map(|off| (w.clone(), *off, Some(id))))).collect() } else { let mut gone = Vec::new(); let found = live .into_iter() .filter_map(|(w, x)| { let id = x.borrow().id; if id.is_some_and(|id| self.rec.borrow().dead.contains(&id)) { return None; } let (p, alive) = self.resolve_u(&x); if !alive { gone.extend(id); } (alive && (a..b).contains(&p)).then(|| (w, p - a, id)) }) .collect(); self.rec.borrow_mut().dead.extend(gone); found }; // These chars are about to be deleted. self.rec.borrow_mut().dead.extend(found.iter().filter_map(|f| f.2)); found.into_iter().map(|(w, off, _)| (w, off)).collect() } /// Replaces single chars (UTF-16 offsets of BMP chars): `Some(attrs)` puts a /// separator with those attributes there, `None` a line break. One commit. pub fn swap_chars(&self, mut at: Vec<(usize, Option)>) { at.sort_by_key(|x| std::cmp::Reverse(x.0)); let us: Vec = at.iter().map(|x| self.to_u(x.0)).collect(); for ((_, attrs), u) in at.into_iter().zip(us) { self.delete_u(u, u + 1); match attrs { Some(a) => { self.write_u(u, &[FlatBlock { attrs: a, ..Default::default() }]); } None => { self.text.insert(u, "\n").expect("insert"); self.force(u, &[(1, KEYS.iter().map(|k| (*k, None)).collect())]); let (first, last) = (self.anchor_u(u), self.anchor_u(u)); self.push(Inverse::Remove { first, last }); } } } self.commit(); } /// Applies mark changes (Unicode ranges), recording what they replace. pub fn restyle(&self, segs: Vec) { let segs = merge_segs(segs); let Some(lo) = segs.iter().map(|s| s.from).min() else { return }; let hi = segs.iter().map(|s| s.to).max().unwrap(); let runs = Runs::new(self.text.slice_delta(lo, hi, PosType::Unicode).unwrap_or_default(), lo); let mut inverse = Vec::new(); let mut apply = Vec::new(); for s in segs { let mut changed = false; runs.each(s.from, s.to, |a, b, attrs| { let old = attrs.get(s.key).filter(|v| !v.is_null()).cloned(); if old != s.value { changed = true; } inverse.push(Seg { from: a - lo, to: b - lo, key: s.key, value: old }); }); if changed { apply.push(s); } } if apply.is_empty() { return; } self.apply_raw(&apply); let at = self.anchor_u(lo); self.push(Inverse::Restyle { at, segs: merge_segs(inverse) }); self.commit(); } /// Sets the attributes of blocks `lo..`, one entry per block (None: unchanged). /// Equal values on consecutive blocks become one mark. pub fn set_attrs(&self, lo: usize, new: &[Option]) { if new.iter().all(Option::is_none) { return; } let cur = self.blocks(lo, lo + new.len()); let mut segs = Vec::new(); for (k, key) in flat::BLOCK_KEYS.iter().enumerate() { let key = self::key(key).unwrap(); let mut i = 0; while i < cur.len() { let Some(want) = &new[i] else { i += 1; continue; }; let v = want.values()[k].clone(); let mut j = i + 1; let mut differs = cur[i].attrs.values()[k] != v; while j < cur.len() && new[j].as_ref().is_some_and(|w| w.values()[k] == v) { differs |= cur[j].attrs.values()[k] != v; j += 1; } if differs { segs.push(Seg { from: cur[i].sepu, to: cur[j - 1].sepu + 1, key, value: v }); } i = j; } } self.restyle(segs); } /// Makes the runs from `u` carry exactly the given values (unrecorded). fn force(&self, u: usize, want: &[(usize, Vec<(&'static str, Option)>)]) { let total: usize = want.iter().map(|w| w.0).sum(); if total == 0 { return; } let runs = Runs::new(self.text.slice_delta(u, u + total, PosType::Unicode).unwrap_or_default(), u); let mut segs = Vec::new(); let mut pos = u; for (len, vals) in want { runs.each(pos, pos + len, |a, b, attrs| { for (k, v) in vals { let have = attrs.get(*k).filter(|x| !x.is_null()); if have != v.as_ref() { segs.push(Seg { from: a, to: b, key: k, value: v.clone() }); } } }); pos += len; } self.apply_raw(&merge_segs(segs)); } fn apply_raw(&self, segs: &[Seg]) { for s in segs { match &s.value { Some(v) => self.text.mark(s.from..s.to, s.key, v.clone()).expect("mark"), None => self.text.unmark(s.from..s.to, s.key).expect("unmark"), } } } /// Inserts rich runs at Unicode `u` exactly as they were. fn restore(&self, u: usize, delta: &[TextDelta]) { let mut s = String::new(); let mut want: Vec<(usize, Vec<(&'static str, Option)>)> = Vec::new(); for d in delta { let TextDelta::Insert { insert, attributes } = d else { continue }; s.push_str(insert); let vals = KEYS.iter().map(|k| (*k, attributes.as_ref().and_then(|a| a.get(*k)).filter(|v| !v.is_null()).cloned())).collect(); want.push((insert.chars().count(), vals)); } if s.is_empty() { return; } let n = s.chars().count(); self.text.insert(u, &s).expect("insert"); // One insert carries one set of inherited marks: read it off the first char // instead of slicing the whole range. let first = self.text.slice_delta(u, u + 1, PosType::Unicode).unwrap_or_default(); let have = |k: &str| match first.first() { Some(TextDelta::Insert { attributes: Some(a), .. }) => a.get(k).filter(|x| !x.is_null()), _ => None, }; let mut segs = Vec::new(); let mut pos = u; for (len, vals) in &want { for (k, v) in vals { if have(k) != v.as_ref() { segs.push(Seg { from: pos, to: pos + len, key: k, value: v.clone() }); } } pos += len; } self.apply_raw(&merge_segs(segs)); let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1)); self.push(Inverse::Remove { first, last }); } /// Applies an inverse, recording its own inverse (undo records redo). pub fn apply(&self, op: &Inverse) { match op { Inverse::Remove { first, last } => { let (a, _) = self.resolve_u(first); let (b, alive) = self.resolve_u(last); let b = if alive { b + 1 } else { b }; self.delete_u(a, b.min(self.text.len_unicode())); self.commit(); } Inverse::Restore { at, delta, revive } => { let (u, _) = self.resolve_u(at); self.restore(u, delta); for (w, off) in revive { if let Some(a) = w.upgrade() { *a.borrow_mut() = self.text.get_cursor(u + off, Side::Left).expect("cursor"); } } self.commit(); } Inverse::Restyle { at, segs } => { let (base, _) = self.resolve_u(at); let len = self.text.len_unicode(); let segs = segs .iter() .map(|s| Seg { from: (base + s.from).min(len), to: (base + s.to).min(len), key: s.key, value: s.value.clone() }) .filter(|s| s.from < s.to) .collect(); self.restyle(segs); } } } /// Asserts the index matches a fresh read of the body. #[cfg(test)] pub fn check(&self) { self.sync(); self.index.borrow().check(&self.text); } /// Ends the body with a separator when concurrent edits left content after the /// last one (unrecorded, origin `sys:init`). pub fn close_body(&self) { let len = self.text.len_unicode(); if len == 0 || self.open() { self.text.insert(len, flat::SEP_STR).expect("insert"); self.force(len, &[(1, KEYS.iter().map(|k| (*k, None)).collect())]); self.commit_as("sys:init"); } } } /// Merges touching segments of one key and value. fn merge_segs(mut segs: Vec) -> Vec { segs.sort_by(|a, b| a.key.cmp(b.key).then(a.from.cmp(&b.from))); let mut out: Vec = Vec::with_capacity(segs.len()); for s in segs { if let Some(l) = out.last_mut() && l.key == s.key && l.value == s.value && l.to >= s.from { l.to = l.to.max(s.to); continue; } out.push(s); } out } /// Rich runs with their absolute Unicode starts. struct Runs { starts: Vec, attrs: Vec>, end: usize, } impl Runs { fn new(delta: Vec, at: usize) -> Runs { let mut r = Runs { starts: Vec::new(), attrs: Vec::new(), end: at }; for d in delta { let TextDelta::Insert { insert, attributes } = d else { continue }; r.starts.push(r.end); r.end += insert.chars().count(); let mut m = HashMap::new(); for (k, v) in attributes.into_iter().flatten() { if let Some(k) = key(&k) { m.insert(k, v); } } r.attrs.push(m); } r } /// Calls `f(from, to, attrs)` for each run piece within `from..to`. fn each(&self, from: usize, to: usize, mut f: impl FnMut(usize, usize, &HashMap<&'static str, LoroValue>)) { let mut i = self.starts.partition_point(|&s| s <= from).saturating_sub(1); while i < self.starts.len() && self.starts[i] < to { let end = self.starts.get(i + 1).copied().unwrap_or(self.end); let (a, b) = (self.starts[i].max(from), end.min(to)); if a < b { f(a, b, &self.attrs[i]); } i += 1; } } }