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
606
607
608
609
610
611
612
613
614
615
616
//! HTML serialization (doc → string) and a strict, dependency-free HTML
//! parser (string → doc).
//!
//! Design and safety notes:
//!
//! - **No third-party HTML engine.** A small hand-written tokenizer keeps
//!   `core` lean and `#![deny(unsafe_code)]`, and minimizes supply-chain and
//!   parsing-attack surface. It deliberately understands only the subset an
//!   editor needs; it is not a full HTML5 conformance parser.
//! - **Output is always escaped.** Text and attribute values are HTML-escaped;
//!   the serializer never emits raw markup, so a document cannot inject
//!   `<script>` or break out of an attribute.
//! - **Input is schema-gated.** Only tags for which the schema declares a
//!   [`ParseRule`] become nodes/marks; unknown elements are unwrapped (their
//!   children are kept) and the assembled tree is validated against the
//!   schema, so structurally invalid HTML is rejected rather than trusted.
//! - **Hostile input is bounded.** Nesting depth is capped
//!   ([`MAX_DEPTH`]); pathological input yields [`DocError::HtmlParse`]
//!   instead of unbounded recursion or memory growth.

use std::collections::BTreeMap;

use crate::attrs::Attrs;
use crate::error::DocError;
use crate::mark::Mark;
use crate::node::Node;
use crate::schema::Schema;

/// Maximum element nesting depth accepted by [`Schema::parse_html`]. Input
/// that nests deeper is rejected with [`DocError::HtmlParse`].
pub const MAX_DEPTH: usize = 100;

const VOID_TAGS: &[&str] = &[
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track",
    "wbr",
];

/// How to render a node or mark as an HTML element.
///
/// Build with [`DomSpec::element`] (a container with a content hole) or
/// [`DomSpec::void`] (a childless element such as `<img>`), then chain
/// [`DomSpec::attr`].
#[derive(Debug, Clone)]
pub struct DomSpec {
    tag: String,
    attrs: Vec<(String, String)>,
    content_hole: bool,
}

impl DomSpec {
    /// A container element whose children are serialized inside it.
    pub fn element(tag: &str) -> Self {
        DomSpec {
            tag: tag.to_string(),
            attrs: Vec::new(),
            content_hole: true,
        }
    }

    /// A childless element (e.g. `<img>`, `<hr>`).
    pub fn void(tag: &str) -> Self {
        DomSpec {
            tag: tag.to_string(),
            attrs: Vec::new(),
            content_hole: false,
        }
    }

    /// Add an attribute. Order is preserved in the output.
    pub fn attr(mut self, name: &str, value: impl Into<String>) -> Self {
        self.attrs.push((name.to_string(), value.into()));
        self
    }

    /// The element tag name.
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// The attributes in declaration order.
    pub fn attrs(&self) -> &[(String, String)] {
        &self.attrs
    }

    /// Whether the element holds the node's content (true) or is a void leaf.
    pub fn content_hole(&self) -> bool {
        self.content_hole
    }
}

/// A parsed HTML element exposed to [`ParseRule`] attribute extractors.
#[derive(Debug, Clone)]
pub struct HtmlElement {
    /// Lowercased tag name.
    pub tag: String,
    attrs: BTreeMap<String, String>,
}

impl HtmlElement {
    /// The value of attribute `name`, if present.
    pub fn attr(&self, name: &str) -> Option<&str> {
        self.attrs.get(name).map(String::as_str)
    }
}

/// A rule mapping an HTML tag back to the node or mark type whose spec
/// declares it.
#[derive(Debug, Clone)]
pub struct ParseRule {
    /// Tag name to match (compared case-insensitively).
    pub tag: String,
    /// Derive attributes from the matched element. `None` means no
    /// attributes; a closure returning `None` declines the match so another
    /// rule may apply.
    pub get_attrs: Option<fn(&HtmlElement) -> Option<Attrs>>,
}

impl ParseRule {
    /// A rule matching `tag` with no attributes.
    pub fn tag(tag: &str) -> Self {
        ParseRule {
            tag: tag.to_string(),
            get_attrs: None,
        }
    }

    /// A rule matching `tag` that derives attributes via `f`.
    pub fn with_attrs(tag: &str, f: fn(&HtmlElement) -> Option<Attrs>) -> Self {
        ParseRule {
            tag: tag.to_string(),
            get_attrs: Some(f),
        }
    }
}

// ---- serialization --------------------------------------------------------

fn escape_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

fn escape_attr(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}

fn open_tag(spec: &DomSpec) -> String {
    let mut s = String::new();
    s.push('<');
    s.push_str(&spec.tag);
    for (k, v) in &spec.attrs {
        s.push(' ');
        s.push_str(k);
        s.push_str("=\"");
        s.push_str(&escape_attr(v));
        s.push('"');
    }
    s
}

impl Node {
    /// Serialize this node (and its subtree) to an HTML string.
    ///
    /// Text and attribute values are HTML-escaped. A node type whose spec has
    /// no `to_dom` is transparent — only its content is emitted (the usual
    /// case for the document node), which is why a serialized document is a
    /// run of its block children with no wrapper.
    pub fn to_html(&self) -> String {
        if let Some(text) = self.text() {
            let mut s = escape_text(text);
            for mark in self.marks() {
                if let Some(f) = mark.mark_type().spec().to_dom {
                    let spec = f(mark);
                    s = format!("{}>{}</{}>", open_tag(&spec), s, spec.tag);
                }
            }
            return s;
        }

        let children: String = self.content().iter().map(Node::to_html).collect();
        match self.node_type().spec().to_dom {
            None => children,
            Some(f) => {
                let spec = f(self);
                if spec.content_hole {
                    format!("{}>{}</{}>", open_tag(&spec), children, spec.tag)
                } else {
                    format!("{}/>", open_tag(&spec))
                }
            }
        }
    }
}

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

#[derive(Debug)]
enum Token {
    Open {
        tag: String,
        attrs: BTreeMap<String, String>,
        self_closing: bool,
    },
    Close(String),
    Text(String),
}

fn decode_entities(s: &str) -> String {
    if !s.contains('&') {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len());
    let bytes: Vec<char> = s.chars().collect();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == '&' {
            if let Some(semi) = bytes[i + 1..].iter().position(|&c| c == ';') {
                let ent: String = bytes[i + 1..i + 1 + semi].iter().collect();
                let decoded = match ent.as_str() {
                    "amp" => Some('&'),
                    "lt" => Some('<'),
                    "gt" => Some('>'),
                    "quot" => Some('"'),
                    "apos" => Some('\''),
                    _ if ent.starts_with("#x") || ent.starts_with("#X") => {
                        u32::from_str_radix(&ent[2..], 16)
                            .ok()
                            .and_then(char::from_u32)
                    }
                    _ if ent.starts_with('#') => {
                        ent[1..].parse::<u32>().ok().and_then(char::from_u32)
                    }
                    _ => None,
                };
                if let Some(c) = decoded {
                    out.push(c);
                    i += semi + 2;
                    continue;
                }
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    out
}

fn tokenize(html: &str) -> Vec<Token> {
    let chars: Vec<char> = html.chars().collect();
    let n = chars.len();
    let mut i = 0;
    let mut tokens = Vec::new();

    while i < n {
        if chars[i] == '<' {
            // Comment / CDATA / doctype / processing instruction → skipped.
            if chars[i + 1..].starts_with(&['!', '-', '-']) {
                if let Some(end) = find_subseq(&chars, i + 4, &['-', '-', '>']) {
                    i = end + 3;
                } else {
                    i = n;
                }
                continue;
            }
            if chars.get(i + 1) == Some(&'!') || chars.get(i + 1) == Some(&'?') {
                i = chars[i..]
                    .iter()
                    .position(|&c| c == '>')
                    .map_or(n, |p| i + p + 1);
                continue;
            }
            if chars.get(i + 1) == Some(&'/') {
                let mut j = i + 2;
                let mut name = String::new();
                while j < n && chars[j] != '>' {
                    name.push(chars[j]);
                    j += 1;
                }
                tokens.push(Token::Close(name.trim().to_ascii_lowercase()));
                i = j + 1;
                continue;
            }
            // Opening tag.
            let mut j = i + 1;
            let mut tag = String::new();
            while j < n && !chars[j].is_whitespace() && chars[j] != '>' && chars[j] != '/' {
                tag.push(chars[j]);
                j += 1;
            }
            let mut attrs = BTreeMap::new();
            let mut self_closing = false;
            loop {
                while j < n && chars[j].is_whitespace() {
                    j += 1;
                }
                if j >= n || chars[j] == '>' {
                    break;
                }
                if chars[j] == '/' {
                    self_closing = true;
                    j += 1;
                    continue;
                }
                let mut name = String::new();
                while j < n
                    && !chars[j].is_whitespace()
                    && chars[j] != '='
                    && chars[j] != '>'
                    && chars[j] != '/'
                {
                    name.push(chars[j]);
                    j += 1;
                }
                while j < n && chars[j].is_whitespace() {
                    j += 1;
                }
                let mut value = String::new();
                if j < n && chars[j] == '=' {
                    j += 1;
                    while j < n && chars[j].is_whitespace() {
                        j += 1;
                    }
                    if j < n && (chars[j] == '"' || chars[j] == '\'') {
                        let quote = chars[j];
                        j += 1;
                        while j < n && chars[j] != quote {
                            value.push(chars[j]);
                            j += 1;
                        }
                        j += 1;
                    } else {
                        while j < n
                            && !chars[j].is_whitespace()
                            && chars[j] != '>'
                            && chars[j] != '/'
                        {
                            value.push(chars[j]);
                            j += 1;
                        }
                    }
                }
                if !name.is_empty() {
                    attrs.insert(name.to_ascii_lowercase(), decode_entities(&value));
                }
            }
            let tag = tag.to_ascii_lowercase();
            if VOID_TAGS.contains(&tag.as_str()) {
                self_closing = true;
            }
            tokens.push(Token::Open {
                tag,
                attrs,
                self_closing,
            });
            i = j + 1;
        } else {
            let mut text = String::new();
            while i < n && chars[i] != '<' {
                text.push(chars[i]);
                i += 1;
            }
            tokens.push(Token::Text(decode_entities(&text)));
        }
    }
    tokens
}

fn find_subseq(chars: &[char], from: usize, needle: &[char]) -> Option<usize> {
    if from > chars.len() {
        return None;
    }
    chars[from..]
        .windows(needle.len())
        .position(|w| w == needle)
        .map(|p| from + p)
}

// ---- tree ----------------------------------------------------------------

#[derive(Debug)]
enum DomTree {
    Element {
        tag: String,
        attrs: BTreeMap<String, String>,
        children: Vec<DomTree>,
    },
    Text(String),
}

struct Frame {
    tag: String,
    attrs: BTreeMap<String, String>,
    children: Vec<DomTree>,
}

fn build_tree(tokens: Vec<Token>) -> Result<Vec<DomTree>, DocError> {
    let mut root: Vec<DomTree> = Vec::new();
    let mut stack: Vec<Frame> = Vec::new();

    macro_rules! push_child {
        ($node:expr) => {
            match stack.last_mut() {
                Some(f) => f.children.push($node),
                None => root.push($node),
            }
        };
    }

    for tok in tokens {
        match tok {
            Token::Text(t) => push_child!(DomTree::Text(t)),
            Token::Open {
                tag,
                attrs,
                self_closing,
            } => {
                if self_closing {
                    push_child!(DomTree::Element {
                        tag,
                        attrs,
                        children: Vec::new()
                    });
                } else {
                    if stack.len() >= MAX_DEPTH {
                        return Err(DocError::HtmlParse(format!(
                            "element nesting exceeds {MAX_DEPTH}"
                        )));
                    }
                    stack.push(Frame {
                        tag,
                        attrs,
                        children: Vec::new(),
                    });
                }
            }
            Token::Close(tag) => {
                if let Some(depth) = stack.iter().rposition(|f| f.tag == tag) {
                    // Auto-close any intervening unclosed elements.
                    while stack.len() > depth {
                        let f = stack.pop().unwrap();
                        let el = DomTree::Element {
                            tag: f.tag,
                            attrs: f.attrs,
                            children: f.children,
                        };
                        push_child!(el);
                    }
                }
                // A stray close with no matching open is ignored.
            }
        }
    }
    // Unwind anything left open.
    while let Some(f) = stack.pop() {
        let el = DomTree::Element {
            tag: f.tag,
            attrs: f.attrs,
            children: f.children,
        };
        push_child!(el);
    }
    Ok(root)
}

// ---- conversion to nodes -------------------------------------------------

fn is_ws_text(n: &Node) -> bool {
    n.text().is_some_and(|t| t.chars().all(char::is_whitespace))
}

impl Schema {
    fn fill_mark_attrs(&self, mark: &str, mut given: Attrs) -> Attrs {
        if let Some(mt) = self.mark_type(mark) {
            for (k, s) in &mt.spec().attrs {
                if !given.contains_key(k) {
                    if let Some(d) = &s.default {
                        given.insert(k.clone(), d.clone());
                    }
                }
            }
        }
        given
    }

    fn match_mark(&self, el: &HtmlElement) -> Option<(String, Attrs)> {
        for mt in self.mark_types() {
            for rule in &mt.spec().parse_dom {
                if rule.tag.eq_ignore_ascii_case(&el.tag) {
                    let attrs = match rule.get_attrs {
                        None => Some(Attrs::new()),
                        Some(f) => f(el),
                    };
                    if let Some(a) = attrs {
                        return Some((mt.name().to_string(), self.fill_mark_attrs(mt.name(), a)));
                    }
                }
            }
        }
        None
    }

    fn match_node(&self, el: &HtmlElement) -> Option<(String, Attrs)> {
        for nt in self.node_types() {
            for rule in &nt.spec().parse_dom {
                if rule.tag.eq_ignore_ascii_case(&el.tag) {
                    let attrs = match rule.get_attrs {
                        None => Some(Attrs::new()),
                        Some(f) => f(el),
                    };
                    if let Some(a) = attrs {
                        return Some((nt.name().to_string(), a));
                    }
                }
            }
        }
        None
    }

    fn convert(
        &self,
        trees: &[DomTree],
        marks: &[Mark],
        depth: usize,
    ) -> Result<Vec<Node>, DocError> {
        if depth > MAX_DEPTH {
            return Err(DocError::HtmlParse(format!(
                "element nesting exceeds {MAX_DEPTH}"
            )));
        }
        let mut out = Vec::new();
        for tree in trees {
            match tree {
                DomTree::Text(t) => {
                    if !t.is_empty() {
                        out.push(self.text(t, marks.to_vec())?);
                    }
                }
                DomTree::Element {
                    tag,
                    attrs,
                    children,
                } => {
                    let el = HtmlElement {
                        tag: tag.clone(),
                        attrs: attrs.clone(),
                    };
                    if let Some((mark_name, mark_attrs)) = self.match_mark(&el) {
                        let m = self.mark_type(&mark_name).unwrap().create(mark_attrs);
                        let new_marks = m.add_to_set(marks);
                        out.extend(self.convert(children, &new_marks, depth + 1)?);
                    } else if let Some((node_name, node_attrs)) = self.match_node(&el) {
                        // Marks are inline-scoped: a fresh element resets them.
                        let kids = self.convert(children, &[], depth + 1)?;
                        out.push(self.build_node(&node_name, node_attrs, kids)?);
                    } else {
                        // Unknown element: unwrap, keep its content.
                        out.extend(self.convert(children, marks, depth + 1)?);
                    }
                }
            }
        }
        Ok(out)
    }

    /// Build a node, retrying once without whitespace-only text children if
    /// the first attempt violates the content expression (handles insignificant
    /// inter-tag whitespace without loosening strictness for real content).
    fn build_node(&self, name: &str, attrs: Attrs, kids: Vec<Node>) -> Result<Node, DocError> {
        match self.node(name, attrs.clone(), kids.clone(), vec![]) {
            Ok(n) => Ok(n),
            Err(DocError::InvalidContent { .. }) => {
                let filtered: Vec<Node> = kids.into_iter().filter(|n| !is_ws_text(n)).collect();
                self.node(name, attrs, filtered, vec![])
            }
            Err(e) => Err(e),
        }
    }

    /// Parse an HTML string into a document, strictly validated against this
    /// schema.
    ///
    /// Recognized tags (those a node/mark spec declares via [`ParseRule`])
    /// become nodes/marks; unknown elements are unwrapped. The result is
    /// wrapped in (or returned as) the schema's top node and validated, so
    /// content that cannot satisfy the schema yields
    /// [`DocError::InvalidContent`]. Overly deep input yields
    /// [`DocError::HtmlParse`].
    pub fn parse_html(&self, html: &str) -> Result<Node, DocError> {
        let trees = build_tree(tokenize(html))?;
        let children = self.convert(&trees, &[], 0)?;

        let top = self.top_node_type().name().to_string();
        if children.len() == 1 && children[0].node_type().name() == top {
            return Ok(children[0].clone());
        }
        self.build_node(&top, Attrs::new(), children)
    }
}