forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

model.rs800 lines, 28.1 KiBHistoryRawDownload
1//! The note body as the editor edits it: the Loro text, its [`BlockIndex`] and the
2//! primitive edits.
3//!
4//! The index follows the body's text events, applied right after each commit or
5//! import ([`Model::commit`], [`Model::import`]), so it is current between edits. Every
6//! primitive commits, and records its inverse for [`super::history::History`]:
7//! positions are held by Loro cursors ([`Anchor`]), and anchors on text a delete removes
8//! move to the copy its undo restores.
9//!
10//! Offsets in the public API are UTF-16 from the start of the body (the DOM's unit);
11//! Loro positions are Unicode scalars and stay internal.
12
13use std::cell::{Cell, RefCell};
14use std::collections::{HashMap, HashSet};
15use std::rc::{Rc, Weak};
16use std::sync::{Arc, Mutex};
17
18use loro::cursor::{Cursor, PosType, Side};
19use loro::{ContainerTrait, LoroDoc, LoroText, LoroValue, TextDelta};
20use note_model::blocks::{BlockIndex, Info, Splice};
21use note_model::flat::{self, Attrs, FlatBlock, Kind, SEP};
22use note_model::write::Inline;
23
24use super::marks::Marks;
25
26/// Origin of the editor's own commits.
27pub const LOCAL: &str = "local";
28
29/// Every mark key the editor writes, inline first.
30pub const KEYS: [&str; 10] = [
31 "strong",
32 "em",
33 "code",
34 "link",
35 flat::KEY_IMAGE,
36 flat::KEY_KIND,
37 flat::KEY_LANG,
38 flat::KEY_WRAP,
39 flat::KEY_JOIN,
40 flat::KEY_START,
41];
42/// The keys of inline content (marks and images).
43pub const INLINE: [&str; 5] = ["strong", "em", "code", "link", flat::KEY_IMAGE];
44
45fn key(k: &str) -> Option<&'static str> {
46 KEYS.iter().find(|s| **s == k).copied()
47}
48
49/// One block: UTF-16 and Unicode offsets of its first content unit and its separator.
50#[derive(Clone, Debug, PartialEq)]
51pub struct Blk {
52 pub index: usize,
53 pub start: usize,
54 pub sep: usize,
55 pub startu: usize,
56 pub sepu: usize,
57 pub attrs: Attrs,
58}
59
60impl Blk {
61 fn new(info: Info, attrs: &Attrs) -> Blk {
62 Blk { index: info.index, start: info.start16, sep: info.sep16(), startu: info.startu, sepu: info.sepu(), attrs: attrs.clone() }
63 }
64 /// Start of the next block.
65 pub fn end(&self) -> usize {
66 self.sep + 1
67 }
68 pub fn len(&self) -> usize {
69 self.sep - self.start
70 }
71 pub fn is_empty(&self) -> bool {
72 self.sep == self.start
73 }
74 pub fn kind(&self) -> Kind {
75 self.attrs.kind
76 }
77 pub fn depth(&self) -> usize {
78 self.attrs.wrap.len()
79 }
80 /// Whether a caret at `off` is inside (content start through the separator).
81 pub fn holds(&self, off: usize) -> bool {
82 self.start <= off && off <= self.sep
83 }
84}
85
86/// A position that follows edits, local and remote.
87pub type Anchor = Rc<RefCell<Cursor>>;
88
89/// A mark change over a Unicode range: `value` None unsets `key`.
90#[derive(Clone, Debug, PartialEq)]
91pub struct Seg {
92 pub from: usize,
93 pub to: usize,
94 pub key: &'static str,
95 pub value: Option<LoroValue>,
96}
97
98/// What undoes one primitive.
99pub enum Inverse {
100 /// Undoes an insert: deletes `first` through `last`.
101 Remove { first: Anchor, last: Anchor },
102 /// Undoes a delete: inserts `delta` at `at`, and moves each anchor of `revive`
103 /// (those that were on the deleted text) to its offset in the copy.
104 Restore { at: Anchor, delta: Vec<TextDelta>, revive: Vec<(Weak<RefCell<Cursor>>, usize)> },
105 /// Undoes a restyle: segments relative to `at`.
106 Restyle { at: Anchor, segs: Vec<Seg> },
107}
108
109#[derive(Default)]
110struct Rec {
111 ops: Vec<Inverse>,
112 /// End (Unicode) of the last insert while it is the last op: typing extends it.
113 typing: Option<usize>,
114 anchors: Vec<Weak<RefCell<Cursor>>>,
115 /// Ids of chars known deleted. A deleted char never comes back, and resolving an
116 /// anchor on one replays history (seconds on a huge note), so it happens once.
117 dead: HashSet<loro::ID>,
118}
119
120pub struct Model {
121 pub doc: LoroDoc,
122 pub text: LoroText,
123 pending: Arc<Mutex<Vec<Vec<TextDelta>>>>,
124 index: RefCell<BlockIndex>,
125 splices: RefCell<Vec<Splice>>,
126 rec: RefCell<Rec>,
127 origin: Cell<&'static str>,
128 _sub: loro::Subscription,
129}
130
131fn plain_len(s: &str) -> (usize, usize) {
132 note_model::flat::str_lens(s)
133}
134
135impl Model {
136 pub fn new(doc: LoroDoc) -> Model {
137 let text = flat::body(&doc);
138 let pending: Arc<Mutex<Vec<Vec<TextDelta>>>> = Arc::default();
139 let queue = pending.clone();
140 let sub = doc.subscribe(
141 &text.id(),
142 Arc::new(move |e| {
143 let mut q = queue.lock().unwrap();
144 for d in e.events {
145 if let loro::event::Diff::Text(delta) = d.diff {
146 q.push(delta);
147 }
148 }
149 }),
150 );
151 let index = BlockIndex::read(&text);
152 Model {
153 doc,
154 text,
155 pending,
156 index: RefCell::new(index),
157 splices: RefCell::default(),
158 rec: RefCell::default(),
159 origin: Cell::new(LOCAL),
160 _sub: sub,
161 }
162 }
163
164 /// Applies queued text events to the index.
165 pub fn sync(&self) {
166 let deltas = std::mem::take(&mut *self.pending.lock().unwrap());
167 for d in deltas {
168 let sp = self.index.borrow_mut().apply(&d, &self.text);
169 self.splices.borrow_mut().extend(sp);
170 }
171 }
172
173 pub fn commit(&self) {
174 self.doc.set_next_commit_origin(self.origin.get());
175 self.doc.commit();
176 self.sync();
177 }
178
179 /// Commits with `origin` instead of [`LOCAL`].
180 pub fn commit_as(&self, origin: &'static str) {
181 self.origin.set(origin);
182 self.commit();
183 self.origin.set(LOCAL);
184 }
185
186 pub fn import(&self, bytes: &[u8]) -> loro::LoroResult<()> {
187 self.commit();
188 let r = self.doc.import(bytes).map(|_| ());
189 self.sync();
190 r
191 }
192
193 /// Block changes since the last call, for the view.
194 pub fn take_splices(&self) -> Vec<Splice> {
195 self.sync();
196 std::mem::take(&mut *self.splices.borrow_mut())
197 }
198
199 /// Rebuilds the index from the text (after a checkout or a wholesale change).
200 pub fn reindex(&self) {
201 self.pending.lock().unwrap().clear();
202 let n = self.index.borrow().len();
203 *self.index.borrow_mut() = BlockIndex::read(&self.text);
204 let m = self.index.borrow().len();
205 self.splices.borrow_mut().push(Splice { at: 0, removed: n, inserted: m, edit: None });
206 }
207
208 // -----------------------------------------------------------------------
209 // Lookups
210 // -----------------------------------------------------------------------
211
212 /// Runs `f` on the index. Don't edit inside `f`.
213 pub fn with<R>(&self, f: impl FnOnce(&BlockIndex) -> R) -> R {
214 f(&self.index.borrow())
215 }
216
217 pub fn len(&self) -> usize {
218 self.index.borrow().len()
219 }
220
221 pub fn is_empty(&self) -> bool {
222 self.index.borrow().is_empty()
223 }
224
225 /// Whether the body ends without a separator (see [`BlockIndex::open`]).
226 pub fn open(&self) -> bool {
227 self.index.borrow().open
228 }
229
230 /// UTF-16 length of the body.
231 pub fn total(&self) -> usize {
232 self.index.borrow().total16()
233 }
234
235 pub fn block(&self, i: usize) -> Option<Blk> {
236 let ix = self.index.borrow();
237 ix.get(i).map(|info| Blk::new(info, ix.attrs(&info)))
238 }
239
240 /// The block holding `off` (a separator belongs to its block; past the end, the
241 /// last). An empty body (before the note loads) reads as one empty paragraph.
242 pub fn at(&self, off: usize) -> Blk {
243 let ix = self.index.borrow();
244 match ix.find16(off) {
245 Some(info) => Blk::new(info, ix.attrs(&info)),
246 None => Blk { index: 0, start: 0, sep: 0, startu: 0, sepu: 0, attrs: Attrs::default() },
247 }
248 }
249
250 pub fn last(&self) -> Blk {
251 self.at(self.total())
252 }
253
254 /// Blocks `lo..hi`.
255 pub fn blocks(&self, lo: usize, hi: usize) -> Vec<Blk> {
256 let ix = self.index.borrow();
257 ix.iter_from(lo).take(hi.saturating_sub(lo)).map(|i| Blk::new(i, ix.attrs(&i))).collect()
258 }
259
260 /// Calls `f` on blocks from `i` on (`back`: from `i - 1` down) until it returns false.
261 pub fn scan(&self, i: usize, back: bool, mut f: impl FnMut(&Info, &Attrs) -> bool) {
262 let ix = self.index.borrow();
263 if back {
264 for info in ix.iter_back(i) {
265 if !f(&info, ix.attrs(&info)) {
266 return;
267 }
268 }
269 } else {
270 for info in ix.iter_from(i) {
271 if !f(&info, ix.attrs(&info)) {
272 return;
273 }
274 }
275 }
276 }
277
278 pub fn to_u(&self, off: usize) -> usize {
279 if off == 0 {
280 return 0;
281 }
282 self.text.convert_pos(off, PosType::Utf16, PosType::Unicode).unwrap_or_else(|| self.text.len_unicode())
283 }
284
285 pub fn to16(&self, u: usize) -> usize {
286 if u == 0 {
287 return 0;
288 }
289 self.text.convert_pos(u, PosType::Unicode, PosType::Utf16).unwrap_or_else(|| self.text.len_utf16())
290 }
291
292 /// Rich runs of `from..to` (UTF-16).
293 pub fn slice(&self, from: usize, to: usize) -> Vec<TextDelta> {
294 if from >= to {
295 return Vec::new();
296 }
297 self.text.slice_delta(from, to, PosType::Utf16).unwrap_or_default()
298 }
299
300 /// Plain text of `from..to` (UTF-16).
301 pub fn plain(&self, from: usize, to: usize) -> String {
302 if from >= to {
303 return String::new();
304 }
305 let (a, b) = (self.to_u(from), self.to_u(to));
306 self.text.slice(a, b).unwrap_or_default()
307 }
308
309 /// The content of block `b` (inline runs; code as one text run).
310 pub fn read_block(&self, b: &Blk) -> FlatBlock {
311 let mut delta = self.slice(b.start, b.end());
312 if self.open() && b.index + 1 == self.len() {
313 delta.push(TextDelta::Insert { insert: SEP.to_string(), attributes: None });
314 }
315 let mut v = flat::read_delta(delta);
316 let mut fb = v.pop().unwrap_or_default();
317 fb.attrs = b.attrs.clone();
318 if fb.attrs.kind == Kind::Code {
319 let text = fb.plain();
320 fb.inl = if text.is_empty() { Vec::new() } else { vec![note_model::write::Inline::Text(text, Default::default())] };
321 }
322 fb
323 }
324
325 // -----------------------------------------------------------------------
326 // Anchors
327 // -----------------------------------------------------------------------
328
329 fn anchor_u(&self, u: usize) -> Anchor {
330 let c = self.text.get_cursor(u, Side::Left).expect("body is attached");
331 let a = Rc::new(RefCell::new(c));
332 let mut rec = self.rec.borrow_mut();
333 if rec.anchors.len() > 64 && rec.anchors.len().is_power_of_two() {
334 rec.anchors.retain(|w| w.strong_count() > 0);
335 }
336 rec.anchors.push(Rc::downgrade(&a));
337 a
338 }
339
340 /// An anchor at UTF-16 offset `off`.
341 pub fn anchor(&self, off: usize) -> Anchor {
342 self.anchor_u(self.to_u(off))
343 }
344
345 /// Unicode position of an anchor, and whether its char is still there.
346 fn resolve_u(&self, a: &Anchor) -> (usize, bool) {
347 match self.doc.get_cursor_pos(&a.borrow()) {
348 Ok(r) => (r.current.pos.min(self.text.len_unicode()), r.update.is_none()),
349 Err(_) => (0, false),
350 }
351 }
352
353 /// A plain cursor at `off`, for the presence wire format.
354 pub fn cursor(&self, off: usize) -> Option<Cursor> {
355 self.text.get_cursor(self.to_u(off), Side::Left)
356 }
357
358 /// The offset of a cursor, if it is on the body.
359 pub fn cursor_pos(&self, c: &Cursor) -> Option<usize> {
360 if c.container != self.text.id() {
361 return None;
362 }
363 let r = self.doc.get_cursor_pos(c).ok()?;
364 Some(self.to16(r.current.pos.min(self.text.len_unicode())))
365 }
366
367 /// UTF-16 offset of an anchor.
368 pub fn resolve(&self, a: &Anchor) -> usize {
369 self.to16(self.resolve_u(a).0)
370 }
371
372 // -----------------------------------------------------------------------
373 // Primitives
374 // -----------------------------------------------------------------------
375
376 fn push(&self, op: Inverse) {
377 let mut rec = self.rec.borrow_mut();
378 rec.typing = None;
379 rec.ops.push(op);
380 }
381
382 /// The inverses recorded since the last call, oldest first.
383 pub fn take_ops(&self) -> Vec<Inverse> {
384 let mut rec = self.rec.borrow_mut();
385 rec.typing = None;
386 std::mem::take(&mut rec.ops)
387 }
388
389 /// Inserts plain text carrying exactly `marks`; separators in `s` become line
390 /// breaks. Returns the end offset.
391 pub fn insert(&self, at: usize, s: &str, marks: &Marks) -> usize {
392 if s.is_empty() {
393 return at;
394 }
395 let s = s.replace(SEP, "\n");
396 let inl = [Inline::Text(s, marks.into())];
397 self.insert_inline(at, &inl)
398 }
399
400 /// Inserts inline content (text runs, breaks, images) inside a block. Returns the
401 /// end offset.
402 pub fn insert_inline(&self, at: usize, inl: &[Inline]) -> usize {
403 let u = self.to_u(at);
404 let fb = FlatBlock { inl: inl.to_vec(), ..Default::default() };
405 let built = flat::build(std::slice::from_ref(&fb));
406 let mut s = built.text;
407 s.pop();
408 if s.is_empty() {
409 return at;
410 }
411 let (n, n16) = plain_len(&s);
412 self.text.insert(u, &s).expect("insert");
413 // Every unit of `s` gets exactly its run's marks, nothing the neighbours lend.
414 let mut want: Vec<(usize, Vec<(&'static str, Option<LoroValue>)>)> = Vec::new();
415 let mut pos = 0;
416 let mut cut = |to: usize, vals: Vec<(&'static str, Option<LoroValue>)>, want: &mut Vec<_>| {
417 if to > pos {
418 want.push((to - pos, vals));
419 pos = to;
420 }
421 };
422 let none = || INLINE.iter().map(|k| (*k, None)).collect::<Vec<_>>();
423 let mut marks: Vec<(std::ops::Range<usize>, Option<&note_model::marks::Marks>, Option<&LoroValue>)> = Vec::new();
424 for (r, m) in &built.inline {
425 marks.push((r.clone(), Some(m), None));
426 }
427 for (p, v) in &built.images {
428 marks.push((*p..*p + 1, None, Some(v)));
429 }
430 marks.sort_by_key(|m| m.0.start);
431 for (r, m, img) in marks {
432 cut(r.start, none(), &mut want);
433 let mut vals = none();
434 if let Some(m) = m {
435 let m: Marks = m.into();
436 for v in vals.iter_mut() {
437 v.1 = m.value_of(v.0);
438 }
439 }
440 if let Some(img) = img {
441 vals[4].1 = Some(img.clone());
442 }
443 cut(r.end, vals, &mut want);
444 }
445 cut(n, none(), &mut want);
446 self.force(u, &want);
447 let typing = self.rec.borrow().typing;
448 let extended = typing == Some(u) && {
449 let rec = self.rec.borrow();
450 match rec.ops.last() {
451 Some(Inverse::Remove { last, .. }) => {
452 *last.borrow_mut() = self.text.get_cursor(u + n - 1, Side::Left).expect("cursor");
453 true
454 }
455 _ => false,
456 }
457 };
458 if !extended {
459 let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1));
460 self.push(Inverse::Remove { first, last });
461 }
462 self.rec.borrow_mut().typing = Some(u + n);
463 self.commit();
464 at + n16
465 }
466
467 /// Inserts whole blocks at `at` (a block start, or inside content to split there).
468 /// Returns the end offset.
469 pub fn insert_blocks(&self, at: usize, blocks: &[FlatBlock]) -> usize {
470 let u = self.to_u(at);
471 let n = self.write_u(u, blocks);
472 self.commit();
473 if n == 0 { at } else { self.to16(u + n) }
474 }
475
476 fn write_u(&self, u: usize, blocks: &[FlatBlock]) -> usize {
477 let n = flat::write(&self.text, u, blocks, true).expect("write blocks");
478 if n > 0 {
479 let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1));
480 self.push(Inverse::Remove { first, last });
481 }
482 n
483 }
484
485 /// Deletes `from..to` (UTF-16).
486 pub fn delete(&self, from: usize, to: usize) {
487 if from < to {
488 self.delete_u(self.to_u(from), self.to_u(to));
489 self.commit();
490 }
491 }
492
493 fn delete_u(&self, a: usize, b: usize) {
494 if a >= b {
495 return;
496 }
497 let delta = self.text.slice_delta(a, b, PosType::Unicode).expect("slice");
498 let revive = self.anchors_in(a, b);
499 self.text.delete(a, b - a).expect("delete");
500 let at = self.anchor_u(a);
501 self.push(Inverse::Restore { at, delta, revive });
502 }
503
504 /// Anchors on the chars `a..b` with their offsets. A short range compares char ids
505 /// (no anchor is resolved); a long one resolves every anchor.
506 fn anchors_in(&self, a: usize, b: usize) -> Vec<(Weak<RefCell<Cursor>>, usize)> {
507 let live: Vec<(Weak<RefCell<Cursor>>, Anchor)> =
508 self.rec.borrow().anchors.iter().filter_map(|w| w.upgrade().map(|x| (w.clone(), x))).collect();
509 if live.is_empty() {
510 return Vec::new();
511 }
512 let found: Vec<(Weak<RefCell<Cursor>>, usize, Option<loro::ID>)> = if b - a <= 64 {
513 let ids: HashMap<loro::ID, usize> =
514 (a..b).filter_map(|p| self.text.get_cursor(p, Side::Left).and_then(|c| c.id).map(|id| (id, p - a))).collect();
515 live.into_iter().filter_map(|(w, x)| x.borrow().id.and_then(|id| ids.get(&id).map(|off| (w.clone(), *off, Some(id))))).collect()
516 } else {
517 let mut gone = Vec::new();
518 let found = live
519 .into_iter()
520 .filter_map(|(w, x)| {
521 let id = x.borrow().id;
522 if id.is_some_and(|id| self.rec.borrow().dead.contains(&id)) {
523 return None;
524 }
525 let (p, alive) = self.resolve_u(&x);
526 if !alive {
527 gone.extend(id);
528 }
529 (alive && (a..b).contains(&p)).then(|| (w, p - a, id))
530 })
531 .collect();
532 self.rec.borrow_mut().dead.extend(gone);
533 found
534 };
535 // These chars are about to be deleted.
536 self.rec.borrow_mut().dead.extend(found.iter().filter_map(|f| f.2));
537 found.into_iter().map(|(w, off, _)| (w, off)).collect()
538 }
539
540 /// Replaces single chars (UTF-16 offsets of BMP chars): `Some(attrs)` puts a
541 /// separator with those attributes there, `None` a line break. One commit.
542 pub fn swap_chars(&self, mut at: Vec<(usize, Option<Attrs>)>) {
543 at.sort_by_key(|x| std::cmp::Reverse(x.0));
544 let us: Vec<usize> = at.iter().map(|x| self.to_u(x.0)).collect();
545 for ((_, attrs), u) in at.into_iter().zip(us) {
546 self.delete_u(u, u + 1);
547 match attrs {
548 Some(a) => {
549 self.write_u(u, &[FlatBlock { attrs: a, ..Default::default() }]);
550 }
551 None => {
552 self.text.insert(u, "\n").expect("insert");
553 self.force(u, &[(1, KEYS.iter().map(|k| (*k, None)).collect())]);
554 let (first, last) = (self.anchor_u(u), self.anchor_u(u));
555 self.push(Inverse::Remove { first, last });
556 }
557 }
558 }
559 self.commit();
560 }
561
562 /// Applies mark changes (Unicode ranges), recording what they replace.
563 pub fn restyle(&self, segs: Vec<Seg>) {
564 let segs = merge_segs(segs);
565 let Some(lo) = segs.iter().map(|s| s.from).min() else { return };
566 let hi = segs.iter().map(|s| s.to).max().unwrap();
567 let runs = Runs::new(self.text.slice_delta(lo, hi, PosType::Unicode).unwrap_or_default(), lo);
568 let mut inverse = Vec::new();
569 let mut apply = Vec::new();
570 for s in segs {
571 let mut changed = false;
572 runs.each(s.from, s.to, |a, b, attrs| {
573 let old = attrs.get(s.key).filter(|v| !v.is_null()).cloned();
574 if old != s.value {
575 changed = true;
576 }
577 inverse.push(Seg { from: a - lo, to: b - lo, key: s.key, value: old });
578 });
579 if changed {
580 apply.push(s);
581 }
582 }
583 if apply.is_empty() {
584 return;
585 }
586 self.apply_raw(&apply);
587 let at = self.anchor_u(lo);
588 self.push(Inverse::Restyle { at, segs: merge_segs(inverse) });
589 self.commit();
590 }
591
592 /// Sets the attributes of blocks `lo..`, one entry per block (None: unchanged).
593 /// Equal values on consecutive blocks become one mark.
594 pub fn set_attrs(&self, lo: usize, new: &[Option<Attrs>]) {
595 if new.iter().all(Option::is_none) {
596 return;
597 }
598 let cur = self.blocks(lo, lo + new.len());
599 let mut segs = Vec::new();
600 for (k, key) in flat::BLOCK_KEYS.iter().enumerate() {
601 let key = self::key(key).unwrap();
602 let mut i = 0;
603 while i < cur.len() {
604 let Some(want) = &new[i] else {
605 i += 1;
606 continue;
607 };
608 let v = want.values()[k].clone();
609 let mut j = i + 1;
610 let mut differs = cur[i].attrs.values()[k] != v;
611 while j < cur.len() && new[j].as_ref().is_some_and(|w| w.values()[k] == v) {
612 differs |= cur[j].attrs.values()[k] != v;
613 j += 1;
614 }
615 if differs {
616 segs.push(Seg { from: cur[i].sepu, to: cur[j - 1].sepu + 1, key, value: v });
617 }
618 i = j;
619 }
620 }
621 self.restyle(segs);
622 }
623
624 /// Makes the runs from `u` carry exactly the given values (unrecorded).
625 fn force(&self, u: usize, want: &[(usize, Vec<(&'static str, Option<LoroValue>)>)]) {
626 let total: usize = want.iter().map(|w| w.0).sum();
627 if total == 0 {
628 return;
629 }
630 let runs = Runs::new(self.text.slice_delta(u, u + total, PosType::Unicode).unwrap_or_default(), u);
631 let mut segs = Vec::new();
632 let mut pos = u;
633 for (len, vals) in want {
634 runs.each(pos, pos + len, |a, b, attrs| {
635 for (k, v) in vals {
636 let have = attrs.get(*k).filter(|x| !x.is_null());
637 if have != v.as_ref() {
638 segs.push(Seg { from: a, to: b, key: k, value: v.clone() });
639 }
640 }
641 });
642 pos += len;
643 }
644 self.apply_raw(&merge_segs(segs));
645 }
646
647 fn apply_raw(&self, segs: &[Seg]) {
648 for s in segs {
649 match &s.value {
650 Some(v) => self.text.mark(s.from..s.to, s.key, v.clone()).expect("mark"),
651 None => self.text.unmark(s.from..s.to, s.key).expect("unmark"),
652 }
653 }
654 }
655
656 /// Inserts rich runs at Unicode `u` exactly as they were.
657 fn restore(&self, u: usize, delta: &[TextDelta]) {
658 let mut s = String::new();
659 let mut want: Vec<(usize, Vec<(&'static str, Option<LoroValue>)>)> = Vec::new();
660 for d in delta {
661 let TextDelta::Insert { insert, attributes } = d else { continue };
662 s.push_str(insert);
663 let vals = KEYS.iter().map(|k| (*k, attributes.as_ref().and_then(|a| a.get(*k)).filter(|v| !v.is_null()).cloned())).collect();
664 want.push((insert.chars().count(), vals));
665 }
666 if s.is_empty() {
667 return;
668 }
669 let n = s.chars().count();
670 self.text.insert(u, &s).expect("insert");
671 // One insert carries one set of inherited marks: read it off the first char
672 // instead of slicing the whole range.
673 let first = self.text.slice_delta(u, u + 1, PosType::Unicode).unwrap_or_default();
674 let have = |k: &str| match first.first() {
675 Some(TextDelta::Insert { attributes: Some(a), .. }) => a.get(k).filter(|x| !x.is_null()),
676 _ => None,
677 };
678 let mut segs = Vec::new();
679 let mut pos = u;
680 for (len, vals) in &want {
681 for (k, v) in vals {
682 if have(k) != v.as_ref() {
683 segs.push(Seg { from: pos, to: pos + len, key: k, value: v.clone() });
684 }
685 }
686 pos += len;
687 }
688 self.apply_raw(&merge_segs(segs));
689 let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1));
690 self.push(Inverse::Remove { first, last });
691 }
692
693 /// Applies an inverse, recording its own inverse (undo records redo).
694 pub fn apply(&self, op: &Inverse) {
695 match op {
696 Inverse::Remove { first, last } => {
697 let (a, _) = self.resolve_u(first);
698 let (b, alive) = self.resolve_u(last);
699 let b = if alive { b + 1 } else { b };
700 self.delete_u(a, b.min(self.text.len_unicode()));
701 self.commit();
702 }
703 Inverse::Restore { at, delta, revive } => {
704 let (u, _) = self.resolve_u(at);
705 self.restore(u, delta);
706 for (w, off) in revive {
707 if let Some(a) = w.upgrade() {
708 *a.borrow_mut() = self.text.get_cursor(u + off, Side::Left).expect("cursor");
709 }
710 }
711 self.commit();
712 }
713 Inverse::Restyle { at, segs } => {
714 let (base, _) = self.resolve_u(at);
715 let len = self.text.len_unicode();
716 let segs = segs
717 .iter()
718 .map(|s| Seg { from: (base + s.from).min(len), to: (base + s.to).min(len), key: s.key, value: s.value.clone() })
719 .filter(|s| s.from < s.to)
720 .collect();
721 self.restyle(segs);
722 }
723 }
724 }
725
726 /// Asserts the index matches a fresh read of the body.
727 #[cfg(test)]
728 pub fn check(&self) {
729 self.sync();
730 self.index.borrow().check(&self.text);
731 }
732
733 /// Ends the body with a separator when concurrent edits left content after the
734 /// last one (unrecorded, origin `sys:init`).
735 pub fn close_body(&self) {
736 let len = self.text.len_unicode();
737 if len == 0 || self.open() {
738 self.text.insert(len, flat::SEP_STR).expect("insert");
739 self.force(len, &[(1, KEYS.iter().map(|k| (*k, None)).collect())]);
740 self.commit_as("sys:init");
741 }
742 }
743}
744
745/// Merges touching segments of one key and value.
746fn merge_segs(mut segs: Vec<Seg>) -> Vec<Seg> {
747 segs.sort_by(|a, b| a.key.cmp(b.key).then(a.from.cmp(&b.from)));
748 let mut out: Vec<Seg> = Vec::with_capacity(segs.len());
749 for s in segs {
750 if let Some(l) = out.last_mut()
751 && l.key == s.key
752 && l.value == s.value
753 && l.to >= s.from
754 {
755 l.to = l.to.max(s.to);
756 continue;
757 }
758 out.push(s);
759 }
760 out
761}
762
763/// Rich runs with their absolute Unicode starts.
764struct Runs {
765 starts: Vec<usize>,
766 attrs: Vec<HashMap<&'static str, LoroValue>>,
767 end: usize,
768}
769
770impl Runs {
771 fn new(delta: Vec<TextDelta>, at: usize) -> Runs {
772 let mut r = Runs { starts: Vec::new(), attrs: Vec::new(), end: at };
773 for d in delta {
774 let TextDelta::Insert { insert, attributes } = d else { continue };
775 r.starts.push(r.end);
776 r.end += insert.chars().count();
777 let mut m = HashMap::new();
778 for (k, v) in attributes.into_iter().flatten() {
779 if let Some(k) = key(&k) {
780 m.insert(k, v);
781 }
782 }
783 r.attrs.push(m);
784 }
785 r
786 }
787
788 /// Calls `f(from, to, attrs)` for each run piece within `from..to`.
789 fn each(&self, from: usize, to: usize, mut f: impl FnMut(usize, usize, &HashMap<&'static str, LoroValue>)) {
790 let mut i = self.starts.partition_point(|&s| s <= from).saturating_sub(1);
791 while i < self.starts.len() && self.starts[i] < to {
792 let end = self.starts.get(i + 1).copied().unwrap_or(self.end);
793 let (a, b) = (self.starts[i].max(from), end.min(to));
794 if a < b {
795 f(a, b, &self.attrs[i]);
796 }
797 i += 1;
798 }
799 }
800}