document_serde.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. use crate::editor::document::Document;
  2. use bytes::Bytes;
  3. use flowy_error::FlowyResult;
  4. use lib_ot::core::{
  5. AttributeHashMap, Body, Changeset, Extension, NodeData, NodeId, NodeOperation, NodeTree, NodeTreeContext, Path,
  6. Selection, Transaction,
  7. };
  8. use lib_ot::text_delta::DeltaTextOperations;
  9. use serde::de::{self, MapAccess, Unexpected, Visitor};
  10. use serde::ser::{SerializeMap, SerializeSeq};
  11. use serde::{Deserialize, Deserializer, Serialize, Serializer};
  12. use std::fmt;
  13. impl Serialize for Document {
  14. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  15. where
  16. S: Serializer,
  17. {
  18. let mut map = serializer.serialize_map(Some(1))?;
  19. let _ = map.serialize_key("document")?;
  20. let _ = map.serialize_value(&DocumentContentSerializer(self))?;
  21. map.end()
  22. }
  23. }
  24. const FIELDS: &[&str] = &["Document"];
  25. impl<'de> Deserialize<'de> for Document {
  26. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  27. where
  28. D: Deserializer<'de>,
  29. {
  30. struct DocumentVisitor();
  31. impl<'de> Visitor<'de> for DocumentVisitor {
  32. type Value = Document;
  33. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  34. formatter.write_str("Expect document tree")
  35. }
  36. fn visit_map<M>(self, mut map: M) -> Result<Document, M::Error>
  37. where
  38. M: MapAccess<'de>,
  39. {
  40. let mut document_node = None;
  41. while let Some(key) = map.next_key()? {
  42. match key {
  43. "document" => {
  44. if document_node.is_some() {
  45. return Err(de::Error::duplicate_field("document"));
  46. }
  47. document_node = Some(map.next_value::<DocumentNode>()?)
  48. }
  49. s => {
  50. return Err(de::Error::unknown_field(s, FIELDS));
  51. }
  52. }
  53. }
  54. match document_node {
  55. Some(document_node) => {
  56. match NodeTree::from_node_data(document_node.into(), NodeTreeContext::default()) {
  57. Ok(tree) => Ok(Document::new(tree)),
  58. Err(err) => Err(de::Error::invalid_value(Unexpected::Other(&format!("{}", err)), &"")),
  59. }
  60. }
  61. None => Err(de::Error::missing_field("document")),
  62. }
  63. }
  64. }
  65. deserializer.deserialize_any(DocumentVisitor())
  66. }
  67. }
  68. pub fn make_transaction_from_document_content(content: &str) -> FlowyResult<Transaction> {
  69. let document_node: DocumentNode = serde_json::from_str::<DocumentContentDeserializer>(content)?.document;
  70. let document_operation = DocumentOperation::Insert {
  71. path: 0_usize.into(),
  72. nodes: vec![document_node],
  73. };
  74. let mut document_transaction = DocumentTransaction::default();
  75. document_transaction.operations.push(document_operation);
  76. Ok(document_transaction.into())
  77. }
  78. pub struct DocumentContentSerde {}
  79. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  80. pub struct DocumentTransaction {
  81. #[serde(default)]
  82. operations: Vec<DocumentOperation>,
  83. #[serde(default)]
  84. before_selection: Selection,
  85. #[serde(default)]
  86. after_selection: Selection,
  87. }
  88. impl DocumentTransaction {
  89. pub fn to_json(&self) -> FlowyResult<String> {
  90. let json = serde_json::to_string(self)?;
  91. Ok(json)
  92. }
  93. pub fn to_bytes(&self) -> FlowyResult<Bytes> {
  94. let data = serde_json::to_vec(&self)?;
  95. Ok(Bytes::from(data))
  96. }
  97. pub fn from_bytes(bytes: Bytes) -> FlowyResult<Self> {
  98. let transaction = serde_json::from_slice(&bytes)?;
  99. Ok(transaction)
  100. }
  101. }
  102. impl std::convert::From<Transaction> for DocumentTransaction {
  103. fn from(transaction: Transaction) -> Self {
  104. let (operations, extension) = transaction.split();
  105. let (before_selection, after_selection) = match extension {
  106. Extension::Empty => (Selection::default(), Selection::default()),
  107. Extension::TextSelection {
  108. before_selection,
  109. after_selection,
  110. } => (before_selection, after_selection),
  111. };
  112. DocumentTransaction {
  113. operations: operations
  114. .into_iter()
  115. .map(|operation| operation.as_ref().into())
  116. .collect(),
  117. before_selection,
  118. after_selection,
  119. }
  120. }
  121. }
  122. impl std::convert::From<DocumentTransaction> for Transaction {
  123. fn from(document_transaction: DocumentTransaction) -> Self {
  124. let mut transaction = Transaction::new();
  125. for document_operation in document_transaction.operations {
  126. transaction.push_operation(document_operation);
  127. }
  128. transaction.extension = Extension::TextSelection {
  129. before_selection: document_transaction.before_selection,
  130. after_selection: document_transaction.after_selection,
  131. };
  132. transaction
  133. }
  134. }
  135. #[derive(Debug, Clone, Serialize, Deserialize)]
  136. #[serde(tag = "op")]
  137. pub enum DocumentOperation {
  138. #[serde(rename = "insert")]
  139. Insert { path: Path, nodes: Vec<DocumentNode> },
  140. #[serde(rename = "delete")]
  141. Delete { path: Path, nodes: Vec<DocumentNode> },
  142. #[serde(rename = "update")]
  143. Update {
  144. path: Path,
  145. attributes: AttributeHashMap,
  146. #[serde(rename = "oldAttributes")]
  147. old_attributes: AttributeHashMap,
  148. },
  149. #[serde(rename = "update_text")]
  150. UpdateText {
  151. path: Path,
  152. delta: DeltaTextOperations,
  153. inverted: DeltaTextOperations,
  154. },
  155. }
  156. impl std::convert::From<DocumentOperation> for NodeOperation {
  157. fn from(document_operation: DocumentOperation) -> Self {
  158. match document_operation {
  159. DocumentOperation::Insert { path, nodes } => NodeOperation::Insert {
  160. path,
  161. nodes: nodes.into_iter().map(|node| node.into()).collect(),
  162. },
  163. DocumentOperation::Delete { path, nodes } => NodeOperation::Delete {
  164. path,
  165. nodes: nodes.into_iter().map(|node| node.into()).collect(),
  166. },
  167. DocumentOperation::Update {
  168. path,
  169. attributes,
  170. old_attributes,
  171. } => NodeOperation::Update {
  172. path,
  173. changeset: Changeset::Attributes {
  174. new: attributes,
  175. old: old_attributes,
  176. },
  177. },
  178. DocumentOperation::UpdateText { path, delta, inverted } => NodeOperation::Update {
  179. path,
  180. changeset: Changeset::Delta { delta, inverted },
  181. },
  182. }
  183. }
  184. }
  185. impl std::convert::From<&NodeOperation> for DocumentOperation {
  186. fn from(node_operation: &NodeOperation) -> Self {
  187. let node_operation = node_operation.clone();
  188. match node_operation {
  189. NodeOperation::Insert { path, nodes } => DocumentOperation::Insert {
  190. path,
  191. nodes: nodes.into_iter().map(|node| node.into()).collect(),
  192. },
  193. NodeOperation::Update { path, changeset } => match changeset {
  194. Changeset::Delta { delta, inverted } => DocumentOperation::UpdateText { path, delta, inverted },
  195. Changeset::Attributes { new, old } => DocumentOperation::Update {
  196. path,
  197. attributes: new,
  198. old_attributes: old,
  199. },
  200. },
  201. NodeOperation::Delete { path, nodes } => DocumentOperation::Delete {
  202. path,
  203. nodes: nodes.into_iter().map(|node| node.into()).collect(),
  204. },
  205. }
  206. }
  207. }
  208. #[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
  209. pub struct DocumentNode {
  210. #[serde(rename = "type")]
  211. pub node_type: String,
  212. #[serde(skip_serializing_if = "AttributeHashMap::is_empty")]
  213. #[serde(default)]
  214. pub attributes: AttributeHashMap,
  215. #[serde(skip_serializing_if = "DeltaTextOperations::is_empty")]
  216. #[serde(default)]
  217. pub delta: DeltaTextOperations,
  218. #[serde(skip_serializing_if = "Vec::is_empty")]
  219. #[serde(default)]
  220. pub children: Vec<DocumentNode>,
  221. }
  222. impl DocumentNode {
  223. pub fn new() -> Self {
  224. Self::default()
  225. }
  226. }
  227. impl std::convert::From<NodeData> for DocumentNode {
  228. fn from(node_data: NodeData) -> Self {
  229. let delta = if let Body::Delta(operations) = node_data.body {
  230. operations
  231. } else {
  232. DeltaTextOperations::default()
  233. };
  234. DocumentNode {
  235. node_type: node_data.node_type,
  236. attributes: node_data.attributes,
  237. delta,
  238. children: node_data.children.into_iter().map(DocumentNode::from).collect(),
  239. }
  240. }
  241. }
  242. impl std::convert::From<DocumentNode> for NodeData {
  243. fn from(document_node: DocumentNode) -> Self {
  244. NodeData {
  245. node_type: document_node.node_type,
  246. attributes: document_node.attributes,
  247. body: Body::Delta(document_node.delta),
  248. children: document_node.children.into_iter().map(|child| child.into()).collect(),
  249. }
  250. }
  251. }
  252. #[derive(Debug, Deserialize)]
  253. struct DocumentContentDeserializer {
  254. document: DocumentNode,
  255. }
  256. #[derive(Debug)]
  257. struct DocumentContentSerializer<'a>(pub &'a Document);
  258. impl<'a> Serialize for DocumentContentSerializer<'a> {
  259. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  260. where
  261. S: Serializer,
  262. {
  263. let tree = self.0.get_tree();
  264. let root_node_id = tree.root_node_id();
  265. // transform the NodeData to DocumentNodeData
  266. let get_document_node_data = |node_id: NodeId| tree.get_node_data(node_id).map(DocumentNode::from);
  267. let mut children = tree.get_children_ids(root_node_id);
  268. if children.len() == 1 {
  269. let node_id = children.pop().unwrap();
  270. match get_document_node_data(node_id) {
  271. None => serializer.serialize_str(""),
  272. Some(node_data) => node_data.serialize(serializer),
  273. }
  274. } else {
  275. let mut seq = serializer.serialize_seq(Some(children.len()))?;
  276. for child in children {
  277. if let Some(node_data) = get_document_node_data(child) {
  278. let _ = seq.serialize_element(&node_data)?;
  279. }
  280. }
  281. seq.end()
  282. }
  283. }
  284. }
  285. #[cfg(test)]
  286. mod tests {
  287. use crate::editor::document::Document;
  288. use crate::editor::document_serde::DocumentTransaction;
  289. use crate::editor::initial_read_me;
  290. #[test]
  291. fn load_read_me() {
  292. let _ = initial_read_me();
  293. }
  294. #[test]
  295. fn transaction_deserialize_update_text_operation_test() {
  296. // bold
  297. let json = r#"{"operations":[{"op":"update_text","path":[0],"delta":[{"retain":3,"attributes":{"bold":true}}],"inverted":[{"retain":3,"attributes":{"bold":null}}]}],"after_selection":{"start":{"path":[0],"offset":0},"end":{"path":[0],"offset":3}},"before_selection":{"start":{"path":[0],"offset":0},"end":{"path":[0],"offset":3}}}"#;
  298. let _ = serde_json::from_str::<DocumentTransaction>(json).unwrap();
  299. // delete character
  300. let json = r#"{"operations":[{"op":"update_text","path":[0],"delta":[{"retain":2},{"delete":1}],"inverted":[{"retain":2},{"insert":"C","attributes":{"bold":true}}]}],"after_selection":{"start":{"path":[0],"offset":2},"end":{"path":[0],"offset":2}},"before_selection":{"start":{"path":[0],"offset":3},"end":{"path":[0],"offset":3}}}"#;
  301. let _ = serde_json::from_str::<DocumentTransaction>(json).unwrap();
  302. }
  303. #[test]
  304. fn transaction_deserialize_insert_operation_test() {
  305. let json = r#"{"operations":[{"op":"update_text","path":[0],"delta":[{"insert":"a"}],"inverted":[{"delete":1}]}],"after_selection":{"start":{"path":[0],"offset":1},"end":{"path":[0],"offset":1}},"before_selection":{"start":{"path":[0],"offset":0},"end":{"path":[0],"offset":0}}}"#;
  306. let _ = serde_json::from_str::<DocumentTransaction>(json).unwrap();
  307. }
  308. #[test]
  309. fn transaction_deserialize_delete_operation_test() {
  310. let json = r#"{"operations": [{"op":"delete","path":[1],"nodes":[{"type":"text","delta":[]}]}],"after_selection":{"start":{"path":[0],"offset":2},"end":{"path":[0],"offset":2}},"before_selection":{"start":{"path":[1],"offset":0},"end":{"path":[1],"offset":0}}}"#;
  311. let _transaction = serde_json::from_str::<DocumentTransaction>(json).unwrap();
  312. }
  313. #[test]
  314. fn transaction_deserialize_update_attribute_operation_test() {
  315. // let json = r#"{"operations":[{"op":"update","path":[0],"attributes":{"retain":3,"attributes":{"bold":true}},"oldAttributes":{"retain":3,"attributes":{"bold":null}}}]}"#;
  316. // let transaction = serde_json::from_str::<DocumentTransaction>(&json).unwrap();
  317. let json =
  318. r#"{"operations":[{"op":"update","path":[0],"attributes":{"retain":3},"oldAttributes":{"retain":3}}]}"#;
  319. let _ = serde_json::from_str::<DocumentTransaction>(json).unwrap();
  320. }
  321. #[test]
  322. fn document_serde_test() {
  323. let document: Document = serde_json::from_str(EXAMPLE_DOCUMENT).unwrap();
  324. let _ = serde_json::to_string_pretty(&document).unwrap();
  325. }
  326. // #[test]
  327. // fn document_operation_compose_test() {
  328. // let json = include_str!("./test.json");
  329. // let transaction: Transaction = Transaction::from_json(json).unwrap();
  330. // let json = transaction.to_json().unwrap();
  331. // // let transaction: Transaction = Transaction::from_json(&json).unwrap();
  332. // let document = Document::from_transaction(transaction).unwrap();
  333. // let content = document.get_content(false).unwrap();
  334. // println!("{}", json);
  335. // }
  336. const EXAMPLE_DOCUMENT: &str = r#"{
  337. "document": {
  338. "type": "editor",
  339. "children": [
  340. {
  341. "type": "image",
  342. "attributes": {
  343. "image_src": "https://s1.ax1x.com/2022/08/26/v2sSbR.jpg",
  344. "align": "center"
  345. }
  346. },
  347. {
  348. "type": "text",
  349. "attributes": { "subtype": "heading", "heading": "h1" },
  350. "delta": [
  351. { "insert": "👋 " },
  352. { "insert": "Welcome to ", "attributes": { "bold": true } },
  353. {
  354. "insert": "AppFlowy Editor",
  355. "attributes": {
  356. "href": "appflowy.io",
  357. "italic": true,
  358. "bold": true
  359. }
  360. }
  361. ]
  362. },
  363. { "type": "text", "delta": [] },
  364. {
  365. "type": "text",
  366. "delta": [
  367. { "insert": "AppFlowy Editor is a " },
  368. { "insert": "highly customizable", "attributes": { "bold": true } },
  369. { "insert": " " },
  370. { "insert": "rich-text editor", "attributes": { "italic": true } },
  371. { "insert": " for " },
  372. { "insert": "Flutter", "attributes": { "underline": true } }
  373. ]
  374. },
  375. {
  376. "type": "text",
  377. "attributes": { "checkbox": true, "subtype": "checkbox" },
  378. "delta": [{ "insert": "Customizable" }]
  379. },
  380. {
  381. "type": "text",
  382. "attributes": { "checkbox": true, "subtype": "checkbox" },
  383. "delta": [{ "insert": "Test-covered" }]
  384. },
  385. {
  386. "type": "text",
  387. "attributes": { "checkbox": false, "subtype": "checkbox" },
  388. "delta": [{ "insert": "more to come!" }]
  389. },
  390. { "type": "text", "delta": [] },
  391. {
  392. "type": "text",
  393. "attributes": { "subtype": "quote" },
  394. "delta": [{ "insert": "Here is an example you can give a try" }]
  395. },
  396. { "type": "text", "delta": [] },
  397. {
  398. "type": "text",
  399. "delta": [
  400. { "insert": "You can also use " },
  401. {
  402. "insert": "AppFlowy Editor",
  403. "attributes": {
  404. "italic": true,
  405. "bold": true,
  406. "backgroundColor": "0x6000BCF0"
  407. }
  408. },
  409. { "insert": " as a component to build your own app." }
  410. ]
  411. },
  412. { "type": "text", "delta": [] },
  413. {
  414. "type": "text",
  415. "attributes": { "subtype": "bulleted-list" },
  416. "delta": [{ "insert": "Use / to insert blocks" }]
  417. },
  418. {
  419. "type": "text",
  420. "attributes": { "subtype": "bulleted-list" },
  421. "delta": [
  422. {
  423. "insert": "Select text to trigger to the toolbar to format your notes."
  424. }
  425. ]
  426. },
  427. { "type": "text", "delta": [] },
  428. {
  429. "type": "text",
  430. "delta": [
  431. {
  432. "insert": "If you have questions or feedback, please submit an issue on Github or join the community along with 1000+ builders!"
  433. }
  434. ]
  435. }
  436. ]
  437. }
  438. }
  439. "#;
  440. }