taino-edit-core 0.5.1

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
//! Content expressions: a minimal regex-like grammar describing which child
//! node types a parent may contain, compiled to a deterministic automaton.
//!
//! Supported grammar (v0.1): node/group names, sequence (juxtaposition),
//! `|` choice, parentheses, and the `+`, `*`, `?` quantifiers — e.g.
//! `"paragraph+"`, `"(text | image)*"`, `"heading paragraph+"`. Counted
//! ranges (`{n,m}`) are intentionally deferred (see ROADMAP).
//!
//! The construction (Thompson NFA then subset construction to a DFA) follows
//! ProseMirror's `ContentMatch` so behaviour matches the reference editor.

use std::collections::BTreeMap;
use std::sync::Arc;

use crate::error::SchemaError;

/// One transition out of an automaton state: a node type id and the target
/// state index.
#[derive(Debug, Clone)]
struct Transition {
    type_id: usize,
    to: usize,
}

/// A compiled content-match automaton, shared by every node type that uses
/// the equivalent expression instance.
#[derive(Debug)]
struct Automaton {
    states: Vec<State>,
}

#[derive(Debug, Default)]
struct State {
    valid_end: bool,
    next: Vec<Transition>,
}

/// A position within a node type's content automaton.
///
/// A [`ContentMatch`] is cheap to clone (it is an [`Arc`] handle plus a state
/// index) and is the unit returned by incremental matching:
/// [`match_type`](ContentMatch::match_type) and
/// [`match_types`](ContentMatch::match_types) advance the position, while
/// [`valid_end`](ContentMatch::valid_end) reports whether stopping here
/// satisfies the expression.
#[derive(Debug, Clone)]
pub struct ContentMatch {
    automaton: Arc<Automaton>,
    state: usize,
}

impl ContentMatch {
    /// Whether ending the content here satisfies the expression.
    pub fn valid_end(&self) -> bool {
        self.automaton.states[self.state].valid_end
    }

    /// Advance the match by a single child of type `type_id`, or `None` if no
    /// such child is allowed in this position.
    pub fn match_type(&self, type_id: usize) -> Option<ContentMatch> {
        let st = &self.automaton.states[self.state];
        for t in &st.next {
            if t.type_id == type_id {
                return Some(ContentMatch {
                    automaton: Arc::clone(&self.automaton),
                    state: t.to,
                });
            }
        }
        None
    }

    /// Advance the match across an ordered sequence of child type ids,
    /// returning the resulting position or `None` if the sequence is invalid.
    pub fn match_types<I: IntoIterator<Item = usize>>(&self, types: I) -> Option<ContentMatch> {
        let mut cur = self.clone();
        for ty in types {
            cur = cur.match_type(ty)?;
        }
        Some(cur)
    }

    /// Whether the given ordered child types form valid, complete content.
    pub fn matches_complete<I: IntoIterator<Item = usize>>(&self, types: I) -> bool {
        match self.match_types(types) {
            Some(end) => end.valid_end(),
            None => false,
        }
    }

    /// Whether two content automata share an acceptable first child type —
    /// the condition under which two nodes may be joined (mirrors
    /// ProseMirror's `ContentMatch.compatible`).
    pub fn compatible(&self, other: &ContentMatch) -> bool {
        let a = &self.automaton.states[self.state].next;
        let b = &other.automaton.states[other.state].next;
        a.iter().any(|x| b.iter().any(|y| x.type_id == y.type_id))
    }
}

// ---- expression AST -------------------------------------------------------

enum Expr {
    Choice(Vec<Expr>),
    Seq(Vec<Expr>),
    Plus(Box<Expr>),
    Star(Box<Expr>),
    Opt(Box<Expr>),
    /// The set of node-type ids this token may match (a plain name → one id,
    /// a group name → the group's ids).
    Match(Vec<usize>),
    Empty,
}

// ---- tokenizer ------------------------------------------------------------

#[derive(Debug, PartialEq, Eq)]
enum Tok {
    Name(String),
    Pipe,
    Open,
    Close,
    Plus,
    Star,
    Opt,
}

fn tokenize(src: &str) -> Result<Vec<Tok>, String> {
    let mut toks = Vec::new();
    let mut chars = src.chars().peekable();
    while let Some(&c) = chars.peek() {
        match c {
            c if c.is_whitespace() => {
                chars.next();
            }
            '|' => {
                chars.next();
                toks.push(Tok::Pipe);
            }
            '(' => {
                chars.next();
                toks.push(Tok::Open);
            }
            ')' => {
                chars.next();
                toks.push(Tok::Close);
            }
            '+' => {
                chars.next();
                toks.push(Tok::Plus);
            }
            '*' => {
                chars.next();
                toks.push(Tok::Star);
            }
            '?' => {
                chars.next();
                toks.push(Tok::Opt);
            }
            c if c.is_alphanumeric() || c == '_' || c == '-' => {
                let mut name = String::new();
                while let Some(&c) = chars.peek() {
                    if c.is_alphanumeric() || c == '_' || c == '-' {
                        name.push(c);
                        chars.next();
                    } else {
                        break;
                    }
                }
                toks.push(Tok::Name(name));
            }
            other => return Err(format!("unexpected character `{other}`")),
        }
    }
    Ok(toks)
}

// ---- recursive-descent parser --------------------------------------------

struct Parser<'a, R: Fn(&str) -> Option<Vec<usize>>> {
    toks: Vec<Tok>,
    pos: usize,
    resolve: &'a R,
    bad_ref: Option<String>,
}

impl<'a, R: Fn(&str) -> Option<Vec<usize>>> Parser<'a, R> {
    fn peek(&self) -> Option<&Tok> {
        self.toks.get(self.pos)
    }

    fn eat(&mut self, t: &Tok) -> bool {
        if self.peek() == Some(t) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    fn parse_expr(&mut self) -> Result<Expr, String> {
        let mut opts = vec![self.parse_seq()?];
        while self.eat(&Tok::Pipe) {
            opts.push(self.parse_seq()?);
        }
        Ok(if opts.len() == 1 {
            opts.pop().unwrap()
        } else {
            Expr::Choice(opts)
        })
    }

    fn parse_seq(&mut self) -> Result<Expr, String> {
        let mut parts = Vec::new();
        while self.at_seq_start() {
            parts.push(self.parse_postfix()?);
        }
        Ok(match parts.len() {
            0 => Expr::Empty,
            1 => parts.pop().unwrap(),
            _ => Expr::Seq(parts),
        })
    }

    fn at_seq_start(&self) -> bool {
        matches!(self.peek(), Some(Tok::Name(_)) | Some(Tok::Open))
    }

    fn parse_postfix(&mut self) -> Result<Expr, String> {
        let mut e = self.parse_atom()?;
        loop {
            if self.eat(&Tok::Plus) {
                e = Expr::Plus(Box::new(e));
            } else if self.eat(&Tok::Star) {
                e = Expr::Star(Box::new(e));
            } else if self.eat(&Tok::Opt) {
                e = Expr::Opt(Box::new(e));
            } else {
                break;
            }
        }
        Ok(e)
    }

    fn parse_atom(&mut self) -> Result<Expr, String> {
        if self.eat(&Tok::Open) {
            let e = self.parse_expr()?;
            if !self.eat(&Tok::Close) {
                return Err("expected `)`".into());
            }
            Ok(e)
        } else if let Some(Tok::Name(_)) = self.peek() {
            let Some(Tok::Name(name)) = self.toks.get(self.pos) else {
                unreachable!()
            };
            let name = name.clone();
            self.pos += 1;
            match (self.resolve)(&name) {
                Some(ids) => Ok(Expr::Match(ids)),
                None => {
                    self.bad_ref = Some(name);
                    Err("unknown reference".into())
                }
            }
        } else {
            Err("expected a name or `(`".into())
        }
    }
}

// ---- NFA construction (Thompson) -----------------------------------------

struct Edge {
    term: Option<usize>,
    to: Option<usize>,
}

struct Nfa {
    nodes: Vec<Vec<Edge>>,
}

impl Nfa {
    fn node(&mut self) -> usize {
        self.nodes.push(Vec::new());
        self.nodes.len() - 1
    }

    fn edge(&mut self, from: usize, to: Option<usize>, term: Option<usize>) -> (usize, usize) {
        self.nodes[from].push(Edge { term, to });
        (from, self.nodes[from].len() - 1)
    }

    fn connect(&mut self, edges: &[(usize, usize)], to: usize) {
        for &(n, i) in edges {
            self.nodes[n][i].to = Some(to);
        }
    }

    fn compile(&mut self, expr: &Expr, from: usize) -> Vec<(usize, usize)> {
        match expr {
            Expr::Choice(opts) => {
                let mut out = Vec::new();
                for o in opts {
                    out.extend(self.compile(o, from));
                }
                out
            }
            Expr::Seq(parts) => {
                let mut from = from;
                for (i, p) in parts.iter().enumerate() {
                    let next = self.compile(p, from);
                    if i == parts.len() - 1 {
                        return next;
                    }
                    let n = self.node();
                    self.connect(&next, n);
                    from = n;
                }
                Vec::new()
            }
            Expr::Star(inner) => {
                let loop_node = self.node();
                let e = self.edge(from, Some(loop_node), None);
                let _ = e;
                let body = self.compile(inner, loop_node);
                self.connect(&body, loop_node);
                vec![self.edge(loop_node, None, None)]
            }
            Expr::Plus(inner) => {
                let loop_node = self.node();
                let body = self.compile(inner, from);
                self.connect(&body, loop_node);
                let body2 = self.compile(inner, loop_node);
                self.connect(&body2, loop_node);
                vec![self.edge(loop_node, None, None)]
            }
            Expr::Opt(inner) => {
                let mut out = vec![self.edge(from, None, None)];
                out.extend(self.compile(inner, from));
                out
            }
            Expr::Match(ids) => {
                let mut out = Vec::new();
                for &id in ids {
                    out.push(self.edge(from, None, Some(id)));
                }
                out
            }
            Expr::Empty => vec![self.edge(from, None, None)],
        }
    }
}

fn null_from(nfa: &Nfa, start: usize) -> Vec<usize> {
    let mut result = Vec::new();
    fn scan(nfa: &Nfa, node: usize, result: &mut Vec<usize>) {
        let edges = &nfa.nodes[node];
        if edges.len() == 1 && edges[0].term.is_none() {
            if let Some(to) = edges[0].to {
                return scan(nfa, to, result);
            }
        }
        if !result.contains(&node) {
            result.push(node);
        }
        for e in edges {
            if e.term.is_none() {
                if let Some(to) = e.to {
                    if !result.contains(&to) {
                        scan(nfa, to, result);
                    }
                }
            }
        }
    }
    scan(nfa, start, &mut result);
    result.sort_unstable();
    result.dedup();
    result
}

fn build_dfa(nfa: &Nfa, accept: usize) -> (Vec<State>, usize) {
    let mut states: Vec<State> = Vec::new();
    let mut labeled: BTreeMap<Vec<usize>, usize> = BTreeMap::new();

    fn explore(
        nfa: &Nfa,
        accept: usize,
        set: Vec<usize>,
        states: &mut Vec<State>,
        labeled: &mut BTreeMap<Vec<usize>, usize>,
    ) -> usize {
        if let Some(&idx) = labeled.get(&set) {
            return idx;
        }
        let idx = states.len();
        states.push(State {
            valid_end: set.contains(&accept),
            next: Vec::new(),
        });
        labeled.insert(set.clone(), idx);

        // Group reachable NFA nodes by transition term.
        let mut grouped: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
        for &node in &set {
            for e in &nfa.nodes[node] {
                if let (Some(term), Some(to)) = (e.term, e.to) {
                    let closure = null_from(nfa, to);
                    let bucket = grouped.entry(term).or_default();
                    for n in closure {
                        if !bucket.contains(&n) {
                            bucket.push(n);
                        }
                    }
                }
            }
        }

        let mut transitions = Vec::new();
        for (term, mut target) in grouped {
            target.sort_unstable();
            target.dedup();
            let to = explore(nfa, accept, target, states, labeled);
            transitions.push(Transition { type_id: term, to });
        }
        states[idx].next = transitions;
        idx
    }

    let start_set = null_from(nfa, 0);
    let start = explore(nfa, accept, start_set, &mut states, &mut labeled);
    (states, start)
}

/// Parse and compile a content expression.
///
/// `resolve` maps a name to the node-type ids it stands for (one id for a
/// plain node name, several for a group name); it returns `None` for unknown
/// references. An empty/whitespace-only expression yields a match that is
/// immediately a valid end and accepts nothing.
pub(crate) fn compile_content<R>(
    in_type: &str,
    src: &str,
    resolve: &R,
) -> Result<ContentMatch, SchemaError>
where
    R: Fn(&str) -> Option<Vec<usize>>,
{
    let toks = tokenize(src).map_err(|message| SchemaError::BadContentExpression {
        in_type: in_type.to_string(),
        message,
    })?;
    let mut parser = Parser {
        toks,
        pos: 0,
        resolve,
        bad_ref: None,
    };
    let expr = parser.parse_expr().map_err(|message| {
        if let Some(reference) = parser.bad_ref.take() {
            SchemaError::UnknownContentRef {
                in_type: in_type.to_string(),
                reference,
            }
        } else {
            SchemaError::BadContentExpression {
                in_type: in_type.to_string(),
                message,
            }
        }
    })?;
    if parser.pos != parser.toks.len() {
        return Err(SchemaError::BadContentExpression {
            in_type: in_type.to_string(),
            message: "trailing tokens after expression".into(),
        });
    }

    let mut nfa = Nfa {
        nodes: vec![Vec::new()],
    };
    let dangling = nfa.compile(&expr, 0);
    let accept = nfa.node();
    nfa.connect(&dangling, accept);

    let (states, start) = build_dfa(&nfa, accept);
    Ok(ContentMatch {
        automaton: Arc::new(Automaton { states }),
        state: start,
    })
}