tiptap-rusty-parser 0.3.3

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
//! Render [`Node`] trees to an HTML string (`to_html`).
//!
//! Schema-agnostic with Tiptap-sensible defaults: `paragraph`→`<p>`,
//! `heading`→`<h1>`..`<h6>`, marks like `bold`→`<strong>`, etc. Output is
//! compact; **text content and attribute values are HTML-escaped** (the element
//! tags themselves are emitted as markup). Behavior is tuned with [`HtmlOptions`]
//! — a plain data struct (no closures), so the same surface works over WASM/FFI.
//!
//! Escaping is not sanitization: URLs (e.g. a `link` `href`) are emitted as-is,
//! so a `javascript:` href survives. Sanitize output from untrusted documents.
//!
//! ```
//! use tiptap_rusty_parser::Document;
//! let doc = Document::from_json_str(
//!     r#"{"type":"doc","content":[{"type":"paragraph","content":[
//!         {"type":"text","text":"hi","marks":[{"type":"bold"}]}]}]}"#,
//! ).unwrap();
//! assert_eq!(doc.to_html(), "<p><strong>hi</strong></p>");
//! ```

use crate::node::{Mark, Node};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::borrow::Cow;
use std::collections::HashMap;

/// How to render a node whose type has no built-in or configured mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum UnknownNodePolicy {
    /// Render the children with no wrapping element (default).
    #[default]
    Transparent,
    /// Wrap the children in `<div data-type="…">`.
    DataTypeDiv,
    /// Emit nothing (drop the subtree).
    Skip,
}

/// How to render a mark whose type has no built-in or configured mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum UnknownMarkPolicy {
    /// Render the text without the mark's element (default).
    #[default]
    Transparent,
    /// Wrap the text in `<span data-mark="…">`.
    DataMarkSpan,
    /// Drop the marked text entirely.
    Skip,
}

/// Whether void elements self-close (`<br/>`) or use the HTML5 form (`<br>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SelfClosingStyle {
    /// `<br>`, `<hr>`, `<img …>` (default).
    #[default]
    Html5,
    /// `<br/>`, `<hr/>`, `<img …/>`.
    Xhtml,
}

/// Options controlling HTML rendering. [`Default`] matches Tiptap conventions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct HtmlOptions {
    /// Override/extend the node→tag map with simple wrappers (e.g. `callout`→`aside`).
    pub node_tags: HashMap<String, String>,
    /// Override/extend the mark→tag map with simple wrappers (e.g. `highlight`→`mark`).
    pub mark_tags: HashMap<String, String>,
    /// How to render unknown node types.
    pub unknown_node: UnknownNodePolicy,
    /// How to render unknown mark types.
    pub unknown_mark: UnknownMarkPolicy,
    /// Void-element style.
    pub self_closing: SelfClosingStyle,
    /// Emit a node's remaining (non-structural) `attrs` as HTML attributes.
    /// Off by default — arbitrary attribute names are an injection footgun.
    pub spread_attrs: bool,
    /// Emit `style="text-align:…"` for `paragraph`/`heading` `textAlign` attrs.
    pub text_align: bool,
}

impl Default for HtmlOptions {
    fn default() -> Self {
        Self {
            node_tags: HashMap::new(),
            mark_tags: HashMap::new(),
            unknown_node: UnknownNodePolicy::default(),
            unknown_mark: UnknownMarkPolicy::default(),
            self_closing: SelfClosingStyle::default(),
            spread_attrs: false,
            text_align: true,
        }
    }
}

impl Node {
    /// Render this node (and its subtree) to an HTML string with default options.
    pub fn to_html(&self) -> String {
        self.to_html_with(&HtmlOptions::default())
    }

    /// Render to HTML with custom [`HtmlOptions`].
    pub fn to_html_with(&self, opts: &HtmlOptions) -> String {
        let mut out = String::with_capacity(256);
        render_node(self, opts, &mut out);
        out
    }
}

/// Render a node to an HTML string. Free-function form of [`Node::to_html`].
pub fn to_html(node: &Node) -> String {
    node.to_html()
}

// ---- rendering ----------------------------------------------------------

fn render_node(n: &Node, opts: &HtmlOptions, out: &mut String) {
    let ty = match n.node_type.as_deref() {
        None => return render_children(n, opts, out),
        Some(t) => t,
    };
    match ty {
        "text" => return render_text(n, opts, out),
        "doc" => return render_children(n, opts, out),
        _ => {}
    }
    // configured simple-wrapper override takes precedence over built-ins
    if let Some(tag) = opts.node_tags.get(ty) {
        out.push('<');
        out.push_str(tag);
        if opts.spread_attrs {
            spread(n, &[], out);
        }
        out.push('>');
        render_children(n, opts, out);
        out.push_str("</");
        out.push_str(tag);
        out.push('>');
        return;
    }
    match ty {
        "paragraph" => wrap(n, opts, out, "p", true, &["textAlign"]),
        "heading" => {
            let level = n
                .attr("level")
                .and_then(Value::as_u64)
                .unwrap_or(1)
                .clamp(1, 6) as u8;
            let digit = (b'0' + level) as char;
            out.push_str("<h");
            out.push(digit);
            write_text_align(n, opts, out);
            if opts.spread_attrs {
                spread(n, &["level", "textAlign"], out);
            }
            out.push('>');
            render_children(n, opts, out);
            out.push_str("</h");
            out.push(digit);
            out.push('>');
        }
        "blockquote" => wrap(n, opts, out, "blockquote", false, &[]),
        "bulletList" => wrap(n, opts, out, "ul", false, &[]),
        "listItem" => wrap(n, opts, out, "li", false, &[]),
        "orderedList" => {
            out.push_str("<ol");
            if let Some(start) = n.attr("start").and_then(Value::as_u64) {
                if start != 1 {
                    out.push_str(" start=\"");
                    out.push_str(&start.to_string());
                    out.push('"');
                }
            }
            if opts.spread_attrs {
                spread(n, &["start"], out);
            }
            out.push('>');
            render_children(n, opts, out);
            out.push_str("</ol>");
        }
        "codeBlock" => {
            out.push_str("<pre><code");
            if let Some(Value::String(lang)) = n.attr("language") {
                if !lang.is_empty() {
                    out.push_str(" class=\"language-");
                    escape_attr(lang, out);
                    out.push('"');
                }
            }
            if opts.spread_attrs {
                spread(n, &["language"], out);
            }
            out.push('>');
            render_code_text(n, out); // raw text, marks ignored
            out.push_str("</code></pre>");
        }
        "hardBreak" => void(out, "br", opts),
        "horizontalRule" => void(out, "hr", opts),
        "image" => {
            out.push_str("<img");
            for key in ["src", "alt", "title"] {
                if let Some(v) = n.attr(key).and_then(attr_string) {
                    write_attr(key, &v, out);
                }
            }
            if opts.spread_attrs {
                spread(n, &["src", "alt", "title"], out);
            }
            void_close(out, opts);
        }
        other => render_unknown(n, opts, out, other),
    }
}

fn render_children(n: &Node, opts: &HtmlOptions, out: &mut String) {
    if let Some(children) = &n.content {
        for c in children {
            render_node(c, opts, out);
        }
    }
}

fn wrap(n: &Node, opts: &HtmlOptions, out: &mut String, tag: &str, align: bool, consumed: &[&str]) {
    out.push('<');
    out.push_str(tag);
    if align {
        write_text_align(n, opts, out);
    }
    if opts.spread_attrs {
        spread(n, consumed, out);
    }
    out.push('>');
    render_children(n, opts, out);
    out.push_str("</");
    out.push_str(tag);
    out.push('>');
}

fn render_unknown(n: &Node, opts: &HtmlOptions, out: &mut String, ty: &str) {
    match opts.unknown_node {
        UnknownNodePolicy::Transparent => render_children(n, opts, out),
        UnknownNodePolicy::Skip => {}
        UnknownNodePolicy::DataTypeDiv => {
            out.push_str("<div data-type=\"");
            escape_attr(ty, out);
            out.push('"');
            if opts.spread_attrs {
                spread(n, &[], out);
            }
            out.push('>');
            render_children(n, opts, out);
            out.push_str("</div>");
        }
    }
}

fn render_text(n: &Node, opts: &HtmlOptions, out: &mut String) {
    let text = n.text.as_deref().unwrap_or("");
    let marks = n.marks.as_deref().unwrap_or(&[]);
    // `Skip` policy drops text carrying an unknown mark entirely.
    if opts.unknown_mark == UnknownMarkPolicy::Skip
        && marks.iter().any(|m| is_unknown_mark(m, opts))
    {
        return;
    }
    for m in marks {
        open_mark(m, opts, out);
    }
    escape_text(text, out);
    for m in marks.iter().rev() {
        close_mark(m, opts, out);
    }
}

/// Concatenate descendant text (escaped), ignoring marks — for `codeBlock`.
fn render_code_text(n: &Node, out: &mut String) {
    if let Some(t) = &n.text {
        escape_text(t, out);
    }
    if let Some(children) = &n.content {
        for c in children {
            render_code_text(c, out);
        }
    }
}

fn builtin_mark_tag(mark_type: &str) -> Option<&'static str> {
    Some(match mark_type {
        "bold" => "strong",
        "italic" => "em",
        "strike" => "s",
        "code" => "code",
        "underline" => "u",
        "subscript" => "sub",
        "superscript" => "sup",
        "link" => "a",
        _ => return None,
    })
}

fn is_unknown_mark(m: &Mark, opts: &HtmlOptions) -> bool {
    !opts.mark_tags.contains_key(&m.mark_type) && builtin_mark_tag(&m.mark_type).is_none()
}

fn open_mark(m: &Mark, opts: &HtmlOptions, out: &mut String) {
    if let Some(tag) = opts.mark_tags.get(&m.mark_type) {
        out.push('<');
        out.push_str(tag);
        out.push('>');
        return;
    }
    match m.mark_type.as_str() {
        "link" => {
            out.push_str("<a");
            for key in ["href", "target", "rel"] {
                if let Some(v) = m
                    .attrs
                    .as_ref()
                    .and_then(|a| a.get(key))
                    .and_then(attr_string)
                {
                    write_attr(key, &v, out);
                }
            }
            out.push('>');
        }
        other => match builtin_mark_tag(other) {
            Some(tag) => {
                out.push('<');
                out.push_str(tag);
                out.push('>');
            }
            None => {
                if opts.unknown_mark == UnknownMarkPolicy::DataMarkSpan {
                    out.push_str("<span data-mark=\"");
                    escape_attr(other, out);
                    out.push_str("\">");
                }
            }
        },
    }
}

fn close_mark(m: &Mark, opts: &HtmlOptions, out: &mut String) {
    if let Some(tag) = opts.mark_tags.get(&m.mark_type) {
        out.push_str("</");
        out.push_str(tag);
        out.push('>');
        return;
    }
    let tag = match builtin_mark_tag(&m.mark_type) {
        Some(tag) => tag,
        None => match opts.unknown_mark {
            UnknownMarkPolicy::DataMarkSpan => "span",
            _ => return,
        },
    };
    out.push_str("</");
    out.push_str(tag);
    out.push('>');
}

// ---- attribute / escape helpers -----------------------------------------

fn write_text_align(n: &Node, opts: &HtmlOptions, out: &mut String) {
    if !opts.text_align {
        return;
    }
    if let Some(Value::String(a)) = n.attr("textAlign") {
        // Whitelist known keywords: emitting an arbitrary value into a `style`
        // attribute would allow CSS injection (`;color:red`) despite escaping.
        if matches!(
            a.as_str(),
            "left" | "right" | "center" | "justify" | "start" | "end"
        ) {
            out.push_str(" style=\"text-align:");
            out.push_str(a);
            out.push('"');
        }
    }
}

fn void(out: &mut String, tag: &str, opts: &HtmlOptions) {
    out.push('<');
    out.push_str(tag);
    void_close(out, opts);
}

fn void_close(out: &mut String, opts: &HtmlOptions) {
    match opts.self_closing {
        SelfClosingStyle::Html5 => out.push('>'),
        SelfClosingStyle::Xhtml => out.push_str("/>"),
    }
}

/// Render a JSON scalar as an attribute value; `None` for null/array/object.
fn attr_string(v: &Value) -> Option<Cow<'_, str>> {
    match v {
        Value::String(s) => Some(Cow::Borrowed(s)),
        Value::Bool(b) => Some(Cow::Owned(b.to_string())),
        Value::Number(n) => Some(Cow::Owned(n.to_string())),
        _ => None,
    }
}

fn valid_attr_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b':'))
}

/// Emit a node's remaining attrs (skipping `consumed` keys and invalid names).
fn spread(n: &Node, consumed: &[&str], out: &mut String) {
    if let Some(attrs) = &n.attrs {
        for (k, v) in attrs {
            if consumed.contains(&k.as_str()) || !valid_attr_name(k) {
                continue;
            }
            if let Some(s) = attr_string(v) {
                write_attr(k, &s, out);
            }
        }
    }
}

fn write_attr(name: &str, value: &str, out: &mut String) {
    out.push(' ');
    out.push_str(name);
    out.push_str("=\"");
    escape_attr(value, out);
    out.push('"');
}

fn escape_text(s: &str, out: &mut String) {
    escape_into(s, out, false);
}

fn escape_attr(s: &str, out: &mut String) {
    escape_into(s, out, true);
}

/// Escape `& < >` (and `"` when `quote`), pushing clean runs in bulk.
fn escape_into(s: &str, out: &mut String, quote: bool) {
    let mut last = 0;
    for (i, b) in s.bytes().enumerate() {
        let rep = match b {
            b'&' => "&amp;",
            b'<' => "&lt;",
            b'>' => "&gt;",
            b'"' if quote => "&quot;",
            _ => continue,
        };
        out.push_str(&s[last..i]);
        out.push_str(rep);
        last = i + 1;
    }
    out.push_str(&s[last..]);
}