Skip to main content

tiptap_rusty_parser/
document.rs

1//! [`Document`] — owning wrapper around a root [`Node`] with (de)serialization.
2
3use crate::error::Result;
4use crate::node::Node;
5use serde_json::Value;
6use std::io::Read;
7use std::ops::{Deref, DerefMut};
8
9/// An owned Tiptap document (its root node, usually `type: "doc"`).
10///
11/// Derefs to the root [`Node`], so all query/mutation methods are available
12/// directly on a `Document`.
13#[derive(Debug, Clone, PartialEq)]
14pub struct Document {
15    root: Node,
16}
17
18impl Document {
19    /// Wrap an existing root node.
20    #[inline]
21    pub fn new(root: Node) -> Self {
22        Document { root }
23    }
24
25    /// Parse from a JSON string.
26    ///
27    /// ```
28    /// use tiptap_rusty_parser::Document;
29    /// let d = Document::from_json_str(r#"{"type":"doc","content":[]}"#).unwrap();
30    /// assert_eq!(d.node_type.as_deref(), Some("doc"));
31    /// ```
32    pub fn from_json_str(s: &str) -> Result<Self> {
33        Ok(Document {
34            root: serde_json::from_str(s)?,
35        })
36    }
37
38    /// Parse from a `serde_json::Value`.
39    pub fn from_value(value: Value) -> Result<Self> {
40        Ok(Document {
41            root: serde_json::from_value(value)?,
42        })
43    }
44
45    /// Parse from any reader.
46    pub fn from_reader(reader: impl Read) -> Result<Self> {
47        Ok(Document {
48            root: serde_json::from_reader(reader)?,
49        })
50    }
51
52    /// Serialize to a compact JSON string.
53    pub fn to_json_str(&self) -> Result<String> {
54        Ok(serde_json::to_string(&self.root)?)
55    }
56
57    /// Serialize to a pretty JSON string.
58    pub fn to_string_pretty(&self) -> Result<String> {
59        Ok(serde_json::to_string_pretty(&self.root)?)
60    }
61
62    /// Serialize to a `serde_json::Value`.
63    pub fn to_value(&self) -> Result<Value> {
64        Ok(serde_json::to_value(&self.root)?)
65    }
66
67    /// Borrow the root node.
68    #[inline]
69    pub fn root(&self) -> &Node {
70        &self.root
71    }
72
73    /// Mutably borrow the root node.
74    #[inline]
75    pub fn root_mut(&mut self) -> &mut Node {
76        &mut self.root
77    }
78
79    /// Consume into the root node.
80    #[inline]
81    pub fn into_root(self) -> Node {
82        self.root
83    }
84}
85
86impl Deref for Document {
87    type Target = Node;
88    #[inline]
89    fn deref(&self) -> &Node {
90        &self.root
91    }
92}
93
94impl DerefMut for Document {
95    #[inline]
96    fn deref_mut(&mut self) -> &mut Node {
97        &mut self.root
98    }
99}
100
101impl From<Node> for Document {
102    #[inline]
103    fn from(root: Node) -> Self {
104        Document { root }
105    }
106}