taino-edit-core 0.4.0

Framework-agnostic document model, transforms, state, history and commands for the taino-edit WYSIWYG editor.
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! [`Step`] — an atomic, invertible, mappable document change — and the
//! v0.1 concrete steps. Steps are the unit of change history and the
//! designed-in extension point for future OT/CRDT integration.

use std::fmt;

use serde_json::{json, Value};

use crate::error::DocError;
use crate::fragment::Fragment;
use crate::map::{Mapping, StepMap};
use crate::mark::Mark;
use crate::node::Node;
use crate::schema::Schema;
use crate::slice::Slice;

/// A step failed to apply to the given document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StepError(pub String);

impl fmt::Display for StepError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "step failed: {}", self.0)
    }
}
impl std::error::Error for StepError {}

/// An atomic document change.
///
/// Every step can be **applied**, **inverted** (given the document it was
/// applied to) and **mapped** through a [`Mapping`] so concurrent or
/// rebased changes compose. `to_json` plus
/// [`step_from_json`] give lossless persistence. A future `map_against`
/// for CRDT/OT can be added without reshaping this trait (DESIGN_NOTES §6).
pub trait Step: fmt::Debug + Send + Sync {
    /// Apply the step, returning the new document or why it failed.
    fn apply(&self, doc: &Node, schema: &Schema) -> Result<Node, StepError>;

    /// How this step remaps positions.
    fn get_map(&self) -> StepMap;

    /// The step that undoes this one, given the document it applied to.
    fn invert(&self, doc: &Node) -> Result<Box<dyn Step>, StepError>;

    /// This step rebased through `mapping`, or `None` if it is entirely
    /// mapped away (its whole range was deleted).
    fn map(&self, mapping: &Mapping) -> Option<Box<dyn Step>>;

    /// Serialize to JSON (tagged with `stepType`).
    fn to_json(&self) -> Value;

    /// Clone into a new boxed step (steps are stored in undo history).
    fn clone_box(&self) -> Box<dyn Step>;
}

impl Clone for Box<dyn Step> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

fn slice_to_json(slice: &Slice) -> Value {
    if slice.is_empty() {
        return json!({});
    }
    let content: Vec<Value> = slice.content().iter().map(Node::to_json).collect();
    json!({
        "content": content,
        "openStart": slice.open_start(),
        "openEnd": slice.open_end(),
    })
}

fn slice_from_json(schema: &Schema, v: &Value) -> Result<Slice, DocError> {
    let obj = v
        .as_object()
        .ok_or_else(|| DocError::MalformedJson("slice must be an object".into()))?;
    let content = match obj.get("content") {
        None => return Ok(Slice::empty()),
        Some(Value::Array(a)) => a
            .iter()
            .map(|n| schema.node_from_json(n))
            .collect::<Result<Vec<_>, _>>()?,
        Some(_) => {
            return Err(DocError::MalformedJson(
                "slice.content must be an array".into(),
            ))
        }
    };
    let open_start = obj.get("openStart").and_then(Value::as_u64).unwrap_or(0) as usize;
    let open_end = obj.get("openEnd").and_then(Value::as_u64).unwrap_or(0) as usize;
    Ok(Slice::new(
        Fragment::from_nodes(content),
        open_start,
        open_end,
    ))
}

/// Replace the range `from..to` with `slice`.
#[derive(Debug, Clone)]
pub struct ReplaceStep {
    from: usize,
    to: usize,
    slice: Slice,
}

impl ReplaceStep {
    /// A step replacing `from..to` with `slice`.
    pub fn new(from: usize, to: usize, slice: Slice) -> Self {
        ReplaceStep { from, to, slice }
    }
}

impl Step for ReplaceStep {
    fn apply(&self, doc: &Node, schema: &Schema) -> Result<Node, StepError> {
        doc.replace(self.from, self.to, &self.slice, schema)
            .map_err(|e| StepError(e.to_string()))
    }

    fn get_map(&self) -> StepMap {
        StepMap::new(vec![self.from, self.to - self.from, self.slice.size()])
    }

    fn invert(&self, doc: &Node) -> Result<Box<dyn Step>, StepError> {
        let removed = doc
            .slice(self.from, self.to)
            .map_err(|e| StepError(e.to_string()))?;
        Ok(Box::new(ReplaceStep {
            from: self.from,
            to: self.from + self.slice.size(),
            slice: removed,
        }))
    }

    fn map(&self, mapping: &Mapping) -> Option<Box<dyn Step>> {
        let from = mapping.map_result(self.from, 1);
        let to = mapping.map_result(self.to, -1);
        if from.deleted_across() && to.deleted_across() {
            return None;
        }
        Some(Box::new(ReplaceStep {
            from: from.pos,
            to: from.pos.max(to.pos),
            slice: self.slice.clone(),
        }))
    }

    fn to_json(&self) -> Value {
        json!({
            "stepType": "replace",
            "from": self.from,
            "to": self.to,
            "slice": slice_to_json(&self.slice),
        })
    }

    fn clone_box(&self) -> Box<dyn Step> {
        Box::new(self.clone())
    }
}

fn map_inline(frag: &Fragment, f: &dyn Fn(&Node) -> Node) -> Fragment {
    let mut out = Vec::new();
    for child in frag.iter() {
        let mut c = child.clone();
        if c.content().child_count() > 0 {
            c = c.copy_content(map_inline(c.content(), f));
        }
        if c.is_inline() {
            c = f(&c);
        }
        out.push(c);
    }
    Fragment::from_nodes(out)
}

/// Add `mark` to every inline node in `from..to`.
#[derive(Debug, Clone)]
pub struct AddMarkStep {
    from: usize,
    to: usize,
    mark: Mark,
}

impl AddMarkStep {
    /// A step adding `mark` across `from..to`.
    pub fn new(from: usize, to: usize, mark: Mark) -> Self {
        AddMarkStep { from, to, mark }
    }
}

impl Step for AddMarkStep {
    fn apply(&self, doc: &Node, schema: &Schema) -> Result<Node, StepError> {
        let old = doc
            .slice(self.from, self.to)
            .map_err(|e| StepError(e.to_string()))?;
        let mark = self.mark.clone();
        let content = map_inline(old.content(), &|n| n.with_marks(mark.add_to_set(n.marks())));
        let slice = Slice::new(content, old.open_start(), old.open_end());
        doc.replace(self.from, self.to, &slice, schema)
            .map_err(|e| StepError(e.to_string()))
    }

    fn get_map(&self) -> StepMap {
        StepMap::identity()
    }

    fn invert(&self, _doc: &Node) -> Result<Box<dyn Step>, StepError> {
        Ok(Box::new(RemoveMarkStep {
            from: self.from,
            to: self.to,
            mark: self.mark.clone(),
        }))
    }

    fn map(&self, mapping: &Mapping) -> Option<Box<dyn Step>> {
        let from = mapping.map_result(self.from, 1);
        let to = mapping.map_result(self.to, -1);
        if (from.deleted() && to.deleted()) || from.pos >= to.pos {
            return None;
        }
        Some(Box::new(AddMarkStep {
            from: from.pos,
            to: from.pos.max(to.pos),
            mark: self.mark.clone(),
        }))
    }

    fn to_json(&self) -> Value {
        json!({
            "stepType": "addMark",
            "mark": self.mark.to_json(),
            "from": self.from,
            "to": self.to,
        })
    }

    fn clone_box(&self) -> Box<dyn Step> {
        Box::new(self.clone())
    }
}

/// Remove `mark` from every inline node in `from..to`.
#[derive(Debug, Clone)]
pub struct RemoveMarkStep {
    from: usize,
    to: usize,
    mark: Mark,
}

impl RemoveMarkStep {
    /// A step removing `mark` across `from..to`.
    pub fn new(from: usize, to: usize, mark: Mark) -> Self {
        RemoveMarkStep { from, to, mark }
    }
}

impl Step for RemoveMarkStep {
    fn apply(&self, doc: &Node, schema: &Schema) -> Result<Node, StepError> {
        let old = doc
            .slice(self.from, self.to)
            .map_err(|e| StepError(e.to_string()))?;
        let mark = self.mark.clone();
        let content = map_inline(old.content(), &|n| {
            n.with_marks(mark.remove_from_set(n.marks()))
        });
        let slice = Slice::new(content, old.open_start(), old.open_end());
        doc.replace(self.from, self.to, &slice, schema)
            .map_err(|e| StepError(e.to_string()))
    }

    fn get_map(&self) -> StepMap {
        StepMap::identity()
    }

    fn invert(&self, _doc: &Node) -> Result<Box<dyn Step>, StepError> {
        Ok(Box::new(AddMarkStep {
            from: self.from,
            to: self.to,
            mark: self.mark.clone(),
        }))
    }

    fn map(&self, mapping: &Mapping) -> Option<Box<dyn Step>> {
        let from = mapping.map_result(self.from, 1);
        let to = mapping.map_result(self.to, -1);
        if (from.deleted() && to.deleted()) || from.pos >= to.pos {
            return None;
        }
        Some(Box::new(RemoveMarkStep {
            from: from.pos,
            to: from.pos.max(to.pos),
            mark: self.mark.clone(),
        }))
    }

    fn to_json(&self) -> Value {
        json!({
            "stepType": "removeMark",
            "mark": self.mark.to_json(),
            "from": self.from,
            "to": self.to,
        })
    }

    fn clone_box(&self) -> Box<dyn Step> {
        Box::new(self.clone())
    }
}

fn rebuild_at(node: &Node, pos: usize, f: &dyn Fn(&Node) -> Node) -> Option<Node> {
    let (index, offset) = node.content().find_index(pos);
    let child = node.content().children().get(index)?;
    if offset == pos {
        let new_child = f(child);
        return Some(node.copy_content(node.content().replace_child(index, new_child)));
    }
    let inner = rebuild_at(child, pos - offset - 1, f)?;
    Some(node.copy_content(node.content().replace_child(index, inner)))
}

/// Set a single attribute on the node that begins at `pos`.
#[derive(Debug, Clone)]
pub struct AttrStep {
    pos: usize,
    attr: String,
    value: Value,
}

impl AttrStep {
    /// A step setting `attr` to `value` on the node at `pos`.
    pub fn new(pos: usize, attr: &str, value: Value) -> Self {
        AttrStep {
            pos,
            attr: attr.to_string(),
            value,
        }
    }
}

impl Step for AttrStep {
    fn apply(&self, doc: &Node, _schema: &Schema) -> Result<Node, StepError> {
        let attr = self.attr.clone();
        let value = self.value.clone();
        rebuild_at(doc, self.pos, &|n| {
            let mut attrs = n.attrs().clone();
            attrs.insert(attr.clone(), value.clone());
            n.with_attrs(attrs)
        })
        .ok_or_else(|| StepError("no node at the attribute step's position".into()))
    }

    fn get_map(&self) -> StepMap {
        StepMap::identity()
    }

    fn invert(&self, doc: &Node) -> Result<Box<dyn Step>, StepError> {
        let node = doc
            .node_at(self.pos)
            .ok_or_else(|| StepError("no node at the attribute step's position".into()))?;
        let old = node.attrs().get(&self.attr).cloned().unwrap_or(Value::Null);
        Ok(Box::new(AttrStep {
            pos: self.pos,
            attr: self.attr.clone(),
            value: old,
        }))
    }

    fn map(&self, mapping: &Mapping) -> Option<Box<dyn Step>> {
        let r = mapping.map_result(self.pos, 1);
        if r.deleted_after() {
            None
        } else {
            Some(Box::new(AttrStep {
                pos: r.pos,
                attr: self.attr.clone(),
                value: self.value.clone(),
            }))
        }
    }

    fn to_json(&self) -> Value {
        json!({
            "stepType": "attr",
            "pos": self.pos,
            "attr": self.attr,
            "value": self.value,
        })
    }

    fn clone_box(&self) -> Box<dyn Step> {
        Box::new(self.clone())
    }
}

/// Replace `from..to` but keep the content in `gap_from..gap_to`, splicing
/// it into `slice` at offset `insert`. This is how nodes are wrapped
/// (e.g. paragraph → blockquote/list item) or unwrapped.
#[derive(Debug, Clone)]
pub struct ReplaceAroundStep {
    from: usize,
    to: usize,
    gap_from: usize,
    gap_to: usize,
    slice: Slice,
    insert: usize,
}

impl ReplaceAroundStep {
    /// Construct a replace-around step.
    pub fn new(
        from: usize,
        to: usize,
        gap_from: usize,
        gap_to: usize,
        slice: Slice,
        insert: usize,
    ) -> Self {
        ReplaceAroundStep {
            from,
            to,
            gap_from,
            gap_to,
            slice,
            insert,
        }
    }
}

impl Step for ReplaceAroundStep {
    fn apply(&self, doc: &Node, schema: &Schema) -> Result<Node, StepError> {
        let gap = doc
            .slice(self.gap_from, self.gap_to)
            .map_err(|e| StepError(e.to_string()))?;
        if gap.open_start() > 0 || gap.open_end() > 0 {
            return Err(StepError("structure gap can't be inserted".into()));
        }
        let inserted = self
            .slice
            .insert_at(self.insert, gap.content().clone())
            .ok_or_else(|| StepError("content does not fit in gap".into()))?;
        doc.replace(self.from, self.to, &inserted, schema)
            .map_err(|e| StepError(e.to_string()))
    }

    fn get_map(&self) -> StepMap {
        StepMap::new(vec![
            self.from,
            self.gap_from - self.from,
            self.insert,
            self.gap_to,
            self.to - self.gap_to,
            self.slice.size().saturating_sub(self.insert),
        ])
    }

    fn invert(&self, doc: &Node) -> Result<Box<dyn Step>, StepError> {
        let gap = self.gap_to - self.gap_from;
        let removed = doc
            .slice(self.from, self.to)
            .map_err(|e| StepError(e.to_string()))?
            .remove_between(self.gap_from - self.from, self.gap_to - self.from)
            .ok_or_else(|| StepError("cannot invert replace-around".into()))?;
        Ok(Box::new(ReplaceAroundStep {
            from: self.from,
            to: self.from + self.slice.size() + gap,
            gap_from: self.from + self.insert,
            gap_to: self.from + self.insert + gap,
            slice: removed,
            insert: self.gap_from - self.from,
        }))
    }

    fn map(&self, mapping: &Mapping) -> Option<Box<dyn Step>> {
        let from = mapping.map_result(self.from, 1);
        let to = mapping.map_result(self.to, -1);
        let gap_from = if self.from == self.gap_from {
            from.pos
        } else {
            mapping.map(self.gap_from, -1)
        };
        let gap_to = if self.to == self.gap_to {
            to.pos
        } else {
            mapping.map(self.gap_to, 1)
        };
        if (from.deleted_across() && to.deleted_across()) || gap_from < from.pos || gap_to > to.pos
        {
            return None;
        }
        Some(Box::new(ReplaceAroundStep {
            from: from.pos,
            to: to.pos,
            gap_from,
            gap_to,
            slice: self.slice.clone(),
            insert: self.insert,
        }))
    }

    fn to_json(&self) -> Value {
        json!({
            "stepType": "replaceAround",
            "from": self.from,
            "to": self.to,
            "gapFrom": self.gap_from,
            "gapTo": self.gap_to,
            "insert": self.insert,
            "slice": slice_to_json(&self.slice),
        })
    }

    fn clone_box(&self) -> Box<dyn Step> {
        Box::new(self.clone())
    }
}

/// Reconstruct a step from its JSON form (produced by [`Step::to_json`]).
pub fn step_from_json(schema: &Schema, v: &Value) -> Result<Box<dyn Step>, DocError> {
    let obj = v
        .as_object()
        .ok_or_else(|| DocError::MalformedJson("step must be an object".into()))?;
    let kind = obj
        .get("stepType")
        .and_then(Value::as_str)
        .ok_or_else(|| DocError::MalformedJson("step missing `stepType`".into()))?;
    match kind {
        "replace" => {
            let from = obj
                .get("from")
                .and_then(Value::as_u64)
                .ok_or_else(|| DocError::MalformedJson("replace step missing `from`".into()))?
                as usize;
            let to = obj
                .get("to")
                .and_then(Value::as_u64)
                .ok_or_else(|| DocError::MalformedJson("replace step missing `to`".into()))?
                as usize;
            let slice = match obj.get("slice") {
                Some(s) => slice_from_json(schema, s)?,
                None => Slice::empty(),
            };
            Ok(Box::new(ReplaceStep::new(from, to, slice)))
        }
        "addMark" | "removeMark" => {
            let from = obj
                .get("from")
                .and_then(Value::as_u64)
                .ok_or_else(|| DocError::MalformedJson("mark step missing `from`".into()))?
                as usize;
            let to = obj
                .get("to")
                .and_then(Value::as_u64)
                .ok_or_else(|| DocError::MalformedJson("mark step missing `to`".into()))?
                as usize;
            let mark = schema.mark_from_json(
                obj.get("mark")
                    .ok_or_else(|| DocError::MalformedJson("mark step missing `mark`".into()))?,
            )?;
            Ok(if kind == "addMark" {
                Box::new(AddMarkStep::new(from, to, mark))
            } else {
                Box::new(RemoveMarkStep::new(from, to, mark))
            })
        }
        "replaceAround" => {
            let g = |k: &str| {
                obj.get(k)
                    .and_then(Value::as_u64)
                    .map(|n| n as usize)
                    .ok_or_else(|| {
                        DocError::MalformedJson(format!("replaceAround step missing `{k}`"))
                    })
            };
            let slice = match obj.get("slice") {
                Some(s) => slice_from_json(schema, s)?,
                None => Slice::empty(),
            };
            Ok(Box::new(ReplaceAroundStep::new(
                g("from")?,
                g("to")?,
                g("gapFrom")?,
                g("gapTo")?,
                slice,
                g("insert")?,
            )))
        }
        "attr" => {
            let pos = obj
                .get("pos")
                .and_then(Value::as_u64)
                .ok_or_else(|| DocError::MalformedJson("attr step missing `pos`".into()))?
                as usize;
            let attr = obj
                .get("attr")
                .and_then(Value::as_str)
                .ok_or_else(|| DocError::MalformedJson("attr step missing `attr`".into()))?;
            let value = obj.get("value").cloned().unwrap_or(Value::Null);
            Ok(Box::new(AttrStep::new(pos, attr, value)))
        }
        other => Err(DocError::MalformedJson(format!(
            "unknown stepType `{other}`"
        ))),
    }
}