tiptap_rusty_parser/
document.rs1use crate::diff::{ApplyError, Change};
4use crate::error::Result;
5use crate::node::Node;
6use serde_json::Value;
7use std::io::Read;
8use std::ops::{Deref, DerefMut};
9
10#[derive(Debug, Clone, PartialEq)]
15pub struct Document {
16 root: Node,
17}
18
19impl Document {
20 #[inline]
22 pub fn new(root: Node) -> Self {
23 Document { root }
24 }
25
26 pub fn from_json_str(s: &str) -> Result<Self> {
34 Ok(Document {
35 root: serde_json::from_str(s)?,
36 })
37 }
38
39 pub fn from_value(value: Value) -> Result<Self> {
41 Ok(Document {
42 root: serde_json::from_value(value)?,
43 })
44 }
45
46 pub fn from_reader(reader: impl Read) -> Result<Self> {
48 Ok(Document {
49 root: serde_json::from_reader(reader)?,
50 })
51 }
52
53 pub fn to_json_str(&self) -> Result<String> {
55 Ok(serde_json::to_string(&self.root)?)
56 }
57
58 pub fn to_string_pretty(&self) -> Result<String> {
60 Ok(serde_json::to_string_pretty(&self.root)?)
61 }
62
63 pub fn to_value(&self) -> Result<Value> {
65 Ok(serde_json::to_value(&self.root)?)
66 }
67
68 #[inline]
70 pub fn root(&self) -> &Node {
71 &self.root
72 }
73
74 #[inline]
76 pub fn root_mut(&mut self) -> &mut Node {
77 &mut self.root
78 }
79
80 #[inline]
82 pub fn into_root(self) -> Node {
83 self.root
84 }
85
86 pub fn diff(&self, other: &Document) -> Vec<Change> {
88 self.root.diff(&other.root)
89 }
90
91 pub fn apply(&mut self, changes: &[Change]) -> std::result::Result<(), ApplyError> {
93 crate::diff::apply(&mut self.root, changes)
94 }
95}
96
97impl Deref for Document {
98 type Target = Node;
99 #[inline]
100 fn deref(&self) -> &Node {
101 &self.root
102 }
103}
104
105impl DerefMut for Document {
106 #[inline]
107 fn deref_mut(&mut self) -> &mut Node {
108 &mut self.root
109 }
110}
111
112impl From<Node> for Document {
113 #[inline]
114 fn from(root: Node) -> Self {
115 Document { root }
116 }
117}