tiptap-rusty-parser 0.6.2

Fast schema-agnostic parser and manipulator for Tiptap/ProseMirror JSONContent documents
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
//! Core data model: [`Node`] and [`Mark`].
//!
//! Mirrors Tiptap's `JSONContent` interface. Schema-agnostic: any node/mark
//! `type` is accepted and unknown JSON fields are preserved in `extra` for
//! faithful roundtrip.

use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{SerializeMap, Serializer};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::fmt;
use std::marker::PhantomData;

/// A single Tiptap/ProseMirror node.
///
/// All structural fields are optional to faithfully distinguish "missing" from
/// "empty" on roundtrip. Unknown top-level keys land in [`Node::extra`].
///
/// `attrs` and `extra` are boxed so the common attr-less, extra-less node stays
/// small (one pointer each); `extra: None` and `Some(empty)` compare equal and
/// serialize identically.
///
/// Serde: serialized as a JSON object with keys in the order `type`, `attrs`,
/// `content`, `marks`, `text` (each only when `Some`), then `extra` in its own
/// order. On deserialize, a `null` known field reads as `None`, a repeated
/// known field is a `duplicate field` error, and a repeated unknown key keeps
/// its first position with the last value.
#[derive(Debug, Clone, Default)]
pub struct Node {
    /// Node type, e.g. `"doc"`, `"paragraph"`, `"text"`.
    pub node_type: Option<String>,

    /// Node attributes.
    pub attrs: Option<Box<Map<String, Value>>>,

    /// Child nodes.
    pub content: Option<Vec<Node>>,

    /// Marks applied to this node (typically text nodes).
    pub marks: Option<Vec<Mark>>,

    /// Text payload (text nodes only).
    pub text: Option<String>,

    /// Any unknown/extra top-level fields, preserved verbatim (`None` = none).
    pub extra: Option<Box<Map<String, Value>>>,
}

/// A mark applied to a node (e.g. `bold`, `italic`, `link`).
///
/// Serde: `type` (required, string), then `attrs` (when `Some`), then `extra`;
/// same `null`/duplicate rules as [`Node`].
#[derive(Debug, Clone)]
pub struct Mark {
    /// Mark type, e.g. `"bold"`.
    pub mark_type: String,

    /// Mark attributes (e.g. `href` for a link).
    pub attrs: Option<Box<Map<String, Value>>>,

    /// Any unknown/extra fields, preserved verbatim (`None` = none).
    pub extra: Option<Box<Map<String, Value>>>,
}

impl Mark {
    /// Create a mark of `mark_type` with no attrs.
    ///
    /// ```
    /// use tiptap_rusty_parser::Mark;
    /// let m = Mark::new("bold");
    /// assert_eq!(m.mark_type, "bold");
    /// ```
    #[inline]
    pub fn new(mark_type: impl Into<String>) -> Self {
        Mark {
            mark_type: mark_type.into(),
            attrs: None,
            extra: None,
        }
    }

    /// Builder: set one attr.
    #[inline]
    pub fn attr(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.attrs
            .get_or_insert_with(Default::default)
            .insert(key.into(), value.into());
        self
    }

    /// Attrs map, if any.
    #[inline]
    pub fn attrs(&self) -> Option<&Map<String, Value>> {
        self.attrs.as_deref()
    }

    /// Mutable attrs map, creating it if absent.
    #[inline]
    pub fn attrs_mut(&mut self) -> &mut Map<String, Value> {
        self.attrs.get_or_insert_with(Default::default)
    }

    /// Unknown/extra fields, if any (may be `Some(empty)`).
    #[inline]
    pub fn extra(&self) -> Option<&Map<String, Value>> {
        self.extra.as_deref()
    }

    /// Mutable extra map, creating it if absent.
    #[inline]
    pub fn extra_mut(&mut self) -> &mut Map<String, Value> {
        self.extra.get_or_insert_with(Default::default)
    }
}

impl Node {
    /// Attrs map, if any.
    #[inline]
    pub fn attrs(&self) -> Option<&Map<String, Value>> {
        self.attrs.as_deref()
    }

    /// Unknown/extra fields, if any (may be `Some(empty)`).
    #[inline]
    pub fn extra(&self) -> Option<&Map<String, Value>> {
        self.extra.as_deref()
    }

    /// Mutable extra map, creating it if absent.
    #[inline]
    pub fn extra_mut(&mut self) -> &mut Map<String, Value> {
        self.extra.get_or_insert_with(Default::default)
    }

    /// Extra field `key`.
    #[inline]
    pub fn extra_field(&self, key: &str) -> Option<&Value> {
        self.extra.as_ref()?.get(key)
    }

    /// Remove extra field `key`, dropping the map once empty.
    pub fn remove_extra(&mut self, key: &str) -> Option<Value> {
        let m = self.extra.as_mut()?;
        let prev = m.remove(key);
        if m.is_empty() {
            self.extra = None;
        }
        prev
    }
}

/// `None` and `Some(empty)` are the same extra set.
#[inline]
pub(crate) fn extra_eq(
    a: &Option<Box<Map<String, Value>>>,
    b: &Option<Box<Map<String, Value>>>,
) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(x), Some(y)) => x == y,
        (Some(m), None) | (None, Some(m)) => m.is_empty(),
    }
}

impl PartialEq for Node {
    #[inline]
    fn eq(&self, o: &Node) -> bool {
        self.node_type == o.node_type
            && self.text == o.text
            && self.attrs == o.attrs
            && self.marks == o.marks
            && extra_eq(&self.extra, &o.extra)
            && self.content == o.content
    }
}

impl PartialEq for Mark {
    #[inline]
    fn eq(&self, o: &Mark) -> bool {
        self.mark_type == o.mark_type && self.attrs == o.attrs && extra_eq(&self.extra, &o.extra)
    }
}

// Hand-written serde: one pass over the map, known keys straight into typed
// fields, the rest into `extra`. Avoids `#[serde(flatten)]`, which buffers
// every unknown entry through serde's private `Content` tree.

/// Object key: a known field (matched without allocating) or an unknown key.
enum Key {
    Type,
    Attrs,
    Content,
    Marks,
    Text,
    Other(String),
}

impl Key {
    #[inline]
    fn known(s: &str) -> Option<Key> {
        Some(match s {
            "type" => Key::Type,
            "attrs" => Key::Attrs,
            "content" => Key::Content,
            "marks" => Key::Marks,
            "text" => Key::Text,
            _ => return None,
        })
    }
}

struct KeyVisitor;

impl<'de> Visitor<'de> for KeyVisitor {
    type Value = Key;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("field identifier")
    }

    #[inline]
    fn visit_str<E: de::Error>(self, v: &str) -> Result<Key, E> {
        Ok(Key::known(v).unwrap_or_else(|| Key::Other(v.to_owned())))
    }

    #[inline]
    fn visit_string<E: de::Error>(self, v: String) -> Result<Key, E> {
        Ok(Key::known(&v).unwrap_or(Key::Other(v)))
    }

    fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Key, E> {
        match std::str::from_utf8(v) {
            Ok(s) => self.visit_str(s),
            Err(_) => Err(E::invalid_value(de::Unexpected::Bytes(v), &self)),
        }
    }
}

impl<'de> Deserialize<'de> for Key {
    #[inline]
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Key, D::Error> {
        d.deserialize_identifier(KeyVisitor)
    }
}

/// Error on a repeated known field (matches the derive's behaviour).
#[inline]
fn once<E: de::Error>(seen: &mut u8, bit: u8, name: &'static str) -> Result<(), E> {
    if *seen & bit != 0 {
        return Err(E::duplicate_field(name));
    }
    *seen |= bit;
    Ok(())
}

/// Scratch stacks shared by one deserialize call. Children and marks collect
/// here, then move into exactly sized `Vec`s: serde's seq visitor grows by
/// doubling (JSON gives no length), which left ~2x the needed capacity.
#[derive(Default)]
struct Scratch {
    nodes: Vec<Node>,
    marks: Vec<Mark>,
}

impl<'de> Deserialize<'de> for Node {
    #[inline]
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Node, D::Error> {
        NodeSeed(&mut Scratch::default()).deserialize(d)
    }
}

struct NodeSeed<'a>(&'a mut Scratch);

impl<'de> DeserializeSeed<'de> for NodeSeed<'_> {
    type Value = Node;

    #[inline]
    fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Node, D::Error> {
        d.deserialize_map(self)
    }
}

impl<'de> Visitor<'de> for NodeSeed<'_> {
    type Value = Node;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("struct Node")
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
        let mut n = Node::default();
        let mut seen = 0u8;
        while let Some(key) = map.next_key::<Key>()? {
            match key {
                Key::Type => {
                    once(&mut seen, 1, "type")?;
                    n.node_type = map.next_value()?;
                }
                Key::Attrs => {
                    once(&mut seen, 2, "attrs")?;
                    n.attrs = map.next_value()?;
                }
                Key::Content => {
                    once(&mut seen, 4, "content")?;
                    n.content = map.next_value_seed(OptVec::<Node>(self.0, PhantomData))?;
                }
                Key::Marks => {
                    once(&mut seen, 8, "marks")?;
                    n.marks = map.next_value_seed(OptVec::<Mark>(self.0, PhantomData))?;
                }
                Key::Text => {
                    once(&mut seen, 16, "text")?;
                    n.text = map.next_value()?;
                }
                Key::Other(k) => {
                    let v: Value = map.next_value()?;
                    n.extra_mut().insert(k, v);
                }
            }
        }
        Ok(n)
    }
}

/// Element type collected through a [`Scratch`] stack.
trait Stacked: Sized {
    fn stack(s: &mut Scratch) -> &mut Vec<Self>;
    fn next<'de, A: SeqAccess<'de>>(seq: &mut A, s: &mut Scratch)
        -> Result<Option<Self>, A::Error>;
}

impl Stacked for Node {
    #[inline]
    fn stack(s: &mut Scratch) -> &mut Vec<Node> {
        &mut s.nodes
    }

    #[inline]
    fn next<'de, A: SeqAccess<'de>>(
        seq: &mut A,
        s: &mut Scratch,
    ) -> Result<Option<Node>, A::Error> {
        seq.next_element_seed(NodeSeed(s))
    }
}

impl Stacked for Mark {
    #[inline]
    fn stack(s: &mut Scratch) -> &mut Vec<Mark> {
        &mut s.marks
    }

    #[inline]
    fn next<'de, A: SeqAccess<'de>>(
        seq: &mut A,
        _: &mut Scratch,
    ) -> Result<Option<Mark>, A::Error> {
        seq.next_element()
    }
}

/// `Option<Vec<T>>` with the same `null`/error behaviour as serde's impls.
struct OptVec<'a, T>(&'a mut Scratch, PhantomData<T>);

impl<'de, T: Stacked> DeserializeSeed<'de> for OptVec<'_, T> {
    type Value = Option<Vec<T>>;

    #[inline]
    fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
        d.deserialize_option(self)
    }
}

impl<'de, T: Stacked> Visitor<'de> for OptVec<'_, T> {
    type Value = Option<Vec<T>>;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("option")
    }

    #[inline]
    fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
        Ok(None)
    }

    #[inline]
    fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
        Ok(None)
    }

    #[inline]
    fn visit_some<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
        d.deserialize_seq(SeqVec(self.0, PhantomData)).map(Some)
    }
}

/// Seq visitor: push onto the scratch stack, then one exact-capacity move.
struct SeqVec<'a, T>(&'a mut Scratch, PhantomData<T>);

impl<'de, T: Stacked> Visitor<'de> for SeqVec<'_, T> {
    type Value = Vec<T>;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a sequence")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
        let s = self.0;
        let base = T::stack(s).len();
        while let Some(x) = T::next(&mut seq, s)? {
            T::stack(s).push(x);
        }
        let st = T::stack(s);
        let mut v = Vec::with_capacity(st.len() - base);
        v.extend(st.drain(base..));
        Ok(v)
    }
}

impl Serialize for Node {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let len = self.node_type.is_some() as usize
            + self.attrs.is_some() as usize
            + self.content.is_some() as usize
            + self.marks.is_some() as usize
            + self.text.is_some() as usize
            + self.extra.as_ref().map_or(0, |e| e.len());
        let mut m = s.serialize_map(Some(len))?;
        if let Some(t) = &self.node_type {
            m.serialize_entry("type", t)?;
        }
        if let Some(a) = &self.attrs {
            m.serialize_entry("attrs", a)?;
        }
        if let Some(c) = &self.content {
            m.serialize_entry("content", c)?;
        }
        if let Some(mk) = &self.marks {
            m.serialize_entry("marks", mk)?;
        }
        if let Some(t) = &self.text {
            m.serialize_entry("text", t)?;
        }
        for (k, v) in self.extra.iter().flat_map(|e| e.iter()) {
            m.serialize_entry(k, v)?;
        }
        m.end()
    }
}

impl<'de> Deserialize<'de> for Mark {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Mark, D::Error> {
        struct V;
        impl<'de> Visitor<'de> for V {
            type Value = Mark;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("struct Mark")
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Mark, A::Error> {
                let mut mark_type: Option<String> = None;
                let mut attrs = None;
                let mut extra: Option<Box<Map<String, Value>>> = None;
                let mut seen = 0u8;
                while let Some(key) = map.next_key::<Key>()? {
                    match key {
                        Key::Type => {
                            once(&mut seen, 1, "type")?;
                            mark_type = Some(map.next_value()?);
                        }
                        Key::Attrs => {
                            once(&mut seen, 2, "attrs")?;
                            attrs = map.next_value()?;
                        }
                        Key::Content => extra_entry(&mut map, &mut extra, "content")?,
                        Key::Marks => extra_entry(&mut map, &mut extra, "marks")?,
                        Key::Text => extra_entry(&mut map, &mut extra, "text")?,
                        Key::Other(k) => {
                            let v: Value = map.next_value()?;
                            extra.get_or_insert_with(Default::default).insert(k, v);
                        }
                    }
                }
                let mark_type = mark_type.ok_or_else(|| de::Error::missing_field("type"))?;
                Ok(Mark {
                    mark_type,
                    attrs,
                    extra,
                })
            }
        }
        d.deserialize_map(V)
    }
}

/// `Mark` has no `content`/`marks`/`text` fields: those keys are unknown there.
#[inline]
fn extra_entry<'de, A: MapAccess<'de>>(
    map: &mut A,
    extra: &mut Option<Box<Map<String, Value>>>,
    key: &str,
) -> Result<(), A::Error> {
    let v: Value = map.next_value()?;
    extra
        .get_or_insert_with(Default::default)
        .insert(key.to_owned(), v);
    Ok(())
}

impl Serialize for Mark {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let len = 1 + self.attrs.is_some() as usize + self.extra.as_ref().map_or(0, |e| e.len());
        let mut m = s.serialize_map(Some(len))?;
        m.serialize_entry("type", &self.mark_type)?;
        if let Some(a) = &self.attrs {
            m.serialize_entry("attrs", a)?;
        }
        for (k, v) in self.extra.iter().flat_map(|e| e.iter()) {
            m.serialize_entry(k, v)?;
        }
        m.end()
    }
}