automerge 0.10.0

A JSON-like data structure (a CRDT) that can be modified concurrently by different users, and merged again automatically
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use smol_str::SmolStr;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::fmt::Display;
use std::sync::Arc;

use crate::op_set2::{MarkData, Op, OpType};
use crate::types::{Clock, ObjType, OpId, SmallHashMap};
use crate::value::ScalarValue;

/// Marks let you store out-of-bound information about sequences.
///
/// The motivating use-case is rich text editing, see <https://www.inkandswitch.com/peritext/>.
/// Each position in the sequence can be affected by only one Mark of the same "name".
/// If multiple collaborators have set marks with the same name but different values
/// in overlapping ranges, automerge will chose a consistent (but arbitrary) value
/// when reading marks from the doc.
#[derive(Debug, Clone, PartialEq)]
pub struct Mark {
    pub start: usize,
    pub end: usize,
    pub name: SmolStr,
    pub value: ScalarValue,
}

#[derive(Debug, Clone, PartialEq)]
pub struct OldMark<'a> {
    pub start: usize,
    pub end: usize,
    pub(crate) data: Cow<'a, OldMarkData>,
}

impl Mark {
    pub(crate) fn old_data(&self) -> OldMarkData {
        OldMarkData {
            name: SmolStr::from(self.name.as_str()),
            value: self.value.clone(),
        }
    }

    pub(crate) fn len(&self) -> usize {
        self.end - self.start
    }

    pub(crate) fn into_mark_set(self) -> Arc<MarkSet> {
        let mut m = MarkSet::default();
        m.insert(self.name, self.value);
        Arc::new(m)
    }
}

#[derive(Debug, PartialEq, Clone)]
struct MarkAccItem {
    index: usize,
    len: usize,
    value: ScalarValue,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub(crate) struct MarkAccumulator {
    marks: BTreeMap<SmolStr, Vec<MarkAccItem>>,
}

impl MarkAccumulator {
    pub(crate) fn into_iter(self) -> impl Iterator<Item = Mark> {
        self.marks.into_iter().flat_map(|(name, items)| {
            items.into_iter().map(move |i| {
                Mark::new(name.to_string(), i.value.clone(), i.index, i.index + i.len)
            })
        })
    }

    pub(crate) fn into_iter_no_unmark(self) -> impl Iterator<Item = Mark> {
        self.marks.into_iter().flat_map(|(name, items)| {
            items
                .into_iter()
                .filter(|i| !i.value.is_null())
                .map(move |i| {
                    Mark::new(name.to_string(), i.value.clone(), i.index, i.index + i.len)
                })
        })
    }

    pub(crate) fn add(&mut self, index: usize, len: usize, other: &MarkSet) {
        for (name, value) in other.marks.iter() {
            let entry = self.marks.entry(name.clone()).or_default();
            if let Some(last) = entry.last_mut() {
                if &last.value == value && last.index + last.len == index {
                    last.len += len;
                    continue;
                }
            }
            entry.push(MarkAccItem {
                index,
                len,
                value: value.clone(),
            })
        }
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct MarkSet {
    marks: BTreeMap<SmolStr, ScalarValue>,
}

use std::collections::btree_map;

#[derive(Debug, Clone, Default)]
pub struct MarkSetIter<'a> {
    set: Option<btree_map::Iter<'a, SmolStr, ScalarValue>>,
}

impl<'a> MarkSetIter<'a> {
    fn new(set: &'a MarkSet) -> Self {
        Self {
            set: Some(set.marks.iter()),
        }
    }
}

impl<'a> Iterator for MarkSetIter<'a> {
    type Item = (&'a str, &'a ScalarValue);

    fn next(&mut self) -> Option<Self::Item> {
        self.set
            .as_mut()?
            .next()
            .map(|(name, value)| (name.as_str(), value))
    }
}

impl MarkSet {
    pub fn iter(&self) -> MarkSetIter<'_> {
        MarkSetIter::new(self)
    }

    pub fn num_marks(&self) -> usize {
        self.marks.len()
    }

    fn inner(&self) -> &BTreeMap<SmolStr, ScalarValue> {
        &self.marks
    }

    pub fn len(&self) -> usize {
        self.marks.len()
    }

    pub(crate) fn insert(&mut self, name: SmolStr, value: ScalarValue) {
        self.marks.insert(name, value);
    }

    fn remove(&mut self, name: &SmolStr) {
        self.marks.remove(name);
    }

    pub fn is_empty(&self) -> bool {
        self.inner().is_empty()
    }

    pub(crate) fn from_query_state(q: &RichTextQueryState<'_>) -> Option<Arc<Self>> {
        let mut marks = MarkStateMachine::default();
        for (id, mark_data) in q.iter() {
            marks.mark_begin(*id, mark_data.clone());
        }
        marks.current().cloned()
    }

    /// Return this MarkSet without any marks which have a value of Null, i.e.
    /// marks which have been removed.
    pub(crate) fn without_unmarks(self) -> Self {
        // FIXME - do I need this clone?
        let mut marks = self.marks.clone();
        marks.retain(|_, value| !matches!(value, ScalarValue::Null));
        MarkSet { marks }
    }

    // Returns a wrapper for comparing two MarkSets while ignoring marks that have been deleted.
    //
    // Marksets track which marks have been deleted by storing them with a value of `ScalarValue::Null`.
    // When we want to compare the marks in two MarkSets, we often want to ignore these deleted marks so
    // that we can focus on whether the user visible state has changed.
    //
    // ## Example
    //
    // ```rust
    // let markset1 = MarkSet::from_iter(vec![
    //     ("bold".to_string(), ScalarValue::String("true".to_string())),
    //     ("italic".to_string(), ScalarValue::Null),
    // ]);
    // let markset2 = MarkSet::from_iter(vec![
    //     ("bold".to_string(), ScalarValue::String("true".to_string())),
    //     ("underlined".to_string(), ScalarValue::Null),
    // ]);
    // assert_eq!(markset1.non_deleted_marks(), markset2.non_deleted_marks());
    // ```
    pub fn non_deleted_marks(&self) -> NonDeletedMarks<'_> {
        NonDeletedMarks(self)
    }
}

impl std::iter::FromIterator<(String, ScalarValue)> for MarkSet {
    fn from_iter<I: IntoIterator<Item = (String, ScalarValue)>>(iter: I) -> Self {
        let mut marks = BTreeMap::new();
        for (name, value) in iter {
            marks.insert(name.into(), value);
        }
        MarkSet { marks }
    }
}

impl Mark {
    pub fn new<V: Into<ScalarValue>>(name: String, value: V, start: usize, end: usize) -> Mark {
        Mark {
            name: SmolStr::from(&name),
            value: value.into(),
            start,
            end,
        }
    }

    pub fn name(&self) -> &str {
        &self.name //.as_str()
    }

    pub fn value(&self) -> &ScalarValue {
        &self.value
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub(crate) struct MarkStateMachine<'a> {
    // would this make more sense as a BTree<OpId, MarkData<'a>>?
    state: Vec<(OpId, MarkData<'a>)>,
    current: Arc<MarkSet>,
}

impl<'a> MarkStateMachine<'a> {
    pub(crate) fn current(&self) -> Option<&Arc<MarkSet>> {
        if self.current.is_empty() {
            None
        } else {
            Some(&self.current)
        }
    }

    pub(crate) fn process(&mut self, opid: OpId, action: OpType<'a>) -> bool {
        match action {
            OpType::MarkBegin(_, data) => self.mark_begin(opid, data),
            OpType::MarkEnd(_) => self.mark_end(opid),
            _ => false,
        }
    }

    pub(crate) fn mark_begin(&mut self, id: OpId, mark: MarkData<'a>) -> bool {
        let mut result = false;

        let index = match self.find(id).err() {
            Some(index) => index,
            None => return false,
        };

        if Self::mark_above(&self.state, index, mark.clone()).is_none() {
            if let Some(below) = Self::mark_below(&mut self.state, index, mark.clone()) {
                if below.value != mark.value {
                    Arc::make_mut(&mut self.current)
                        .insert(SmolStr::from(mark.name.as_ref()), mark.value.to_owned());
                    result = true
                }
            } else {
                // nothing above or below
                Arc::make_mut(&mut self.current)
                    .insert(SmolStr::from(mark.name.as_ref()), mark.value.to_owned());
                result = true
            }
        }

        self.state.insert(index, (id, mark));

        result
    }

    pub(crate) fn mark_end(&mut self, id: OpId) -> bool {
        let mut result = false;
        let index = match self.find(id.prev()).ok() {
            Some(index) => index,
            None => return false,
        };

        let mark = self.state.remove(index).1;

        if Self::mark_above(&self.state, index, mark.clone()).is_none() {
            match Self::mark_below(&mut self.state, index, mark.clone()) {
                Some(below) if below.value == mark.value => {}
                Some(below) => {
                    Arc::make_mut(&mut self.current)
                        .insert(SmolStr::from(below.name), below.value.into());
                    result = true;
                }
                None => {
                    Arc::make_mut(&mut self.current).remove(&SmolStr::from(mark.name.as_ref()));
                    result = true;
                }
            }
        }

        result
    }

    fn find(&self, target: OpId) -> Result<usize, usize> {
        self.state.binary_search_by(|probe| probe.0.cmp(&target))
    }

    fn mark_above(
        state: &[(OpId, MarkData<'a>)],
        index: usize,
        mark: MarkData<'a>,
    ) -> Option<MarkData<'a>> {
        Some(
            state[index..]
                .iter()
                .find(|(_, m)| m.name == mark.name)?
                .1
                .clone(),
        )
    }

    fn mark_below(
        state: &mut [(OpId, MarkData<'a>)],
        index: usize,
        mark: MarkData<'a>,
    ) -> Option<MarkData<'a>> {
        Some(
            state[0..index]
                .iter_mut()
                .filter(|(_, m)| m.name == mark.name)
                .next_back()?
                .1
                .clone(),
        )
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct OldMarkData {
    pub name: SmolStr,
    pub value: ScalarValue,
}

impl Display for MarkData<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "name={} value={}", self.name, self.value)
    }
}

/// ExpandMark allows you to decide whether new text inserted at the start/end of your
/// mark should also inherit the mark.
/// See <https://www.inkandswitch.com/peritext/> for details and
/// suggestions of which value to use for which operations when building a rich text editor.
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum ExpandMark {
    Before,
    After,
    Both,
    None,
}

impl Default for ExpandMark {
    fn default() -> Self {
        Self::After
    }
}

impl ExpandMark {
    pub fn from(before: bool, after: bool) -> Self {
        match (before, after) {
            (true, true) => Self::Both,
            (false, true) => Self::After,
            (true, false) => Self::Before,
            (false, false) => Self::None,
        }
    }
    pub fn before(&self) -> bool {
        matches!(self, Self::Before | Self::Both)
    }
    pub fn after(&self) -> bool {
        matches!(self, Self::After | Self::Both)
    }
}

#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct RichTextQueryState<'a> {
    pub(crate) map: SmallHashMap<OpId, MarkData<'a>>,
    pub(crate) block: Option<OpId>,
}

impl<'a> RichTextQueryState<'a> {
    pub(crate) fn process(&mut self, op: Op<'a>, clock: Option<&Clock>) {
        if !(clock.map(|c| c.covers(&op.id)).unwrap_or(true)) {
            // if the op is not visible in the current clock
            // we can ignore it
            return;
        }
        match op.action() {
            OpType::MarkBegin(_, data) => {
                self.map.insert(op.id, data);
            }
            OpType::MarkEnd(_) => {
                self.map.remove(&op.id.prev());
            }
            OpType::Make(ObjType::Map) => {
                self.block = Some(op.id);
            }
            _ => {}
        }
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = (&OpId, &MarkData<'a>)> {
        self.map.iter()
    }
}

// Useful for comparing MarkSets while ignoring marks that have been deleted (i.e. have a value of Null).
//
// Returned by [`MarkSet::non_deleted_marks()`]
#[derive(Debug)]
pub struct NonDeletedMarks<'a>(&'a MarkSet);

impl PartialEq for NonDeletedMarks<'_> {
    fn eq(&self, other: &Self) -> bool {
        let us_in_them = self.0.marks.iter().all(|(name, value)| {
            matches!(value, ScalarValue::Null) || other.0.marks.get(name) == Some(value)
        });
        let them_in_us = other.0.marks.iter().all(|(name, value)| {
            matches!(value, ScalarValue::Null) || self.0.marks.get(name) == Some(value)
        });
        us_in_them && them_in_us
    }
}

impl NonDeletedMarks<'_> {
    pub fn len(&self) -> usize {
        self.0
            .marks
            .iter()
            .filter(|(_, v)| !matches!(v, ScalarValue::Null))
            .count()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Configure the expand flag used when creating marks in [`update_spans`](crate::transaction::Transactable::update_spans)
#[derive(Default, Debug, Clone)]
pub struct UpdateSpansConfig {
    /// The expand flag to use when the mark does not have a flag set in Self::per_mark_expands.
    pub default_expand: ExpandMark,
    /// A map of mark names to the expand flag to use for that mark
    pub per_mark_expands: HashMap<String, ExpandMark>,
}

impl UpdateSpansConfig {
    pub fn with_default_expand(mut self, expand: ExpandMark) -> Self {
        self.default_expand = expand;
        self
    }

    pub fn with_mark_expand<S: AsRef<str>>(mut self, mark_name: S, expand: ExpandMark) -> Self {
        self.per_mark_expands
            .insert(mark_name.as_ref().to_string(), expand);
        self
    }
}