document_serde.rs 16 KB

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