block_editor.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. use crate::entities::RowPB;
  2. use bytes::Bytes;
  3. use flowy_error::{FlowyError, FlowyResult};
  4. use flowy_grid_data_model::revision::{CellRevision, GridBlockRevision, RowChangeset, RowRevision};
  5. use flowy_revision::{RevisionCloudService, RevisionCompactor, RevisionManager, RevisionObjectBuilder};
  6. use flowy_sync::client_grid::{GridBlockRevisionChangeset, GridBlockRevisionPad};
  7. use flowy_sync::entities::revision::Revision;
  8. use flowy_sync::util::make_delta_from_revisions;
  9. use lib_infra::future::FutureResult;
  10. use std::borrow::Cow;
  11. use std::sync::Arc;
  12. use tokio::sync::RwLock;
  13. pub struct GridBlockRevisionEditor {
  14. user_id: String,
  15. pub block_id: String,
  16. pad: Arc<RwLock<GridBlockRevisionPad>>,
  17. rev_manager: Arc<RevisionManager>,
  18. }
  19. impl GridBlockRevisionEditor {
  20. pub async fn new(
  21. user_id: &str,
  22. token: &str,
  23. block_id: &str,
  24. mut rev_manager: RevisionManager,
  25. ) -> FlowyResult<Self> {
  26. let cloud = Arc::new(GridBlockRevisionCloudService {
  27. token: token.to_owned(),
  28. });
  29. let block_revision_pad = rev_manager.load::<GridBlockRevisionPadBuilder>(Some(cloud)).await?;
  30. let pad = Arc::new(RwLock::new(block_revision_pad));
  31. let rev_manager = Arc::new(rev_manager);
  32. let user_id = user_id.to_owned();
  33. let block_id = block_id.to_owned();
  34. Ok(Self {
  35. user_id,
  36. block_id,
  37. pad,
  38. rev_manager,
  39. })
  40. }
  41. pub async fn duplicate_block(&self, duplicated_block_id: &str) -> GridBlockRevision {
  42. self.pad.read().await.duplicate_data(duplicated_block_id).await
  43. }
  44. /// Create a row after the the with prev_row_id. If prev_row_id is None, the row will be appended to the list
  45. pub(crate) async fn create_row(
  46. &self,
  47. row: RowRevision,
  48. prev_row_id: Option<String>,
  49. ) -> FlowyResult<(i32, Option<i32>)> {
  50. let mut row_count = 0;
  51. let mut row_index = None;
  52. let _ = self
  53. .modify(|block_pad| {
  54. if let Some(start_row_id) = prev_row_id.as_ref() {
  55. match block_pad.index_of_row(start_row_id) {
  56. None => {}
  57. Some(index) => row_index = Some(index as i32 + 1),
  58. }
  59. }
  60. let change = block_pad.add_row_rev(row, prev_row_id)?;
  61. row_count = block_pad.number_of_rows();
  62. if row_index.is_none() {
  63. row_index = Some(row_count - 1);
  64. }
  65. Ok(change)
  66. })
  67. .await?;
  68. Ok((row_count, row_index))
  69. }
  70. pub async fn delete_rows(&self, ids: Vec<Cow<'_, String>>) -> FlowyResult<i32> {
  71. let mut row_count = 0;
  72. let _ = self
  73. .modify(|block_pad| {
  74. let changeset = block_pad.delete_rows(ids)?;
  75. row_count = block_pad.number_of_rows();
  76. Ok(changeset)
  77. })
  78. .await?;
  79. Ok(row_count)
  80. }
  81. pub async fn update_row(&self, changeset: RowChangeset) -> FlowyResult<()> {
  82. let _ = self.modify(|block_pad| Ok(block_pad.update_row(changeset)?)).await?;
  83. Ok(())
  84. }
  85. pub async fn move_row(&self, row_id: &str, from: usize, to: usize) -> FlowyResult<()> {
  86. let _ = self
  87. .modify(|block_pad| Ok(block_pad.move_row(row_id, from, to)?))
  88. .await?;
  89. Ok(())
  90. }
  91. pub async fn index_of_row(&self, row_id: &str) -> Option<usize> {
  92. self.pad.read().await.index_of_row(row_id)
  93. }
  94. pub async fn get_row_rev(&self, row_id: &str) -> FlowyResult<Option<Arc<RowRevision>>> {
  95. let row_ids = vec![Cow::Borrowed(row_id)];
  96. let row_rev = self.get_row_revs(Some(row_ids)).await?.pop();
  97. Ok(row_rev)
  98. }
  99. pub async fn get_row_revs<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<Arc<RowRevision>>>
  100. where
  101. T: AsRef<str> + ToOwned + ?Sized,
  102. {
  103. let row_revs = self.pad.read().await.get_row_revs(row_ids)?;
  104. Ok(row_revs)
  105. }
  106. pub async fn get_cell_revs(
  107. &self,
  108. field_id: &str,
  109. row_ids: Option<Vec<Cow<'_, String>>>,
  110. ) -> FlowyResult<Vec<CellRevision>> {
  111. let cell_revs = self.pad.read().await.get_cell_revs(field_id, row_ids)?;
  112. Ok(cell_revs)
  113. }
  114. pub async fn get_row_pb(&self, row_id: &str) -> FlowyResult<Option<RowPB>> {
  115. let row_ids = Some(vec![Cow::Borrowed(row_id)]);
  116. Ok(self.get_row_infos(row_ids).await?.pop())
  117. }
  118. pub async fn get_row_infos<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<RowPB>>
  119. where
  120. T: AsRef<str> + ToOwned + ?Sized,
  121. {
  122. let row_infos = self
  123. .pad
  124. .read()
  125. .await
  126. .get_row_revs(row_ids)?
  127. .iter()
  128. .map(RowPB::from)
  129. .collect::<Vec<RowPB>>();
  130. Ok(row_infos)
  131. }
  132. async fn modify<F>(&self, f: F) -> FlowyResult<()>
  133. where
  134. F: for<'a> FnOnce(&'a mut GridBlockRevisionPad) -> FlowyResult<Option<GridBlockRevisionChangeset>>,
  135. {
  136. let mut write_guard = self.pad.write().await;
  137. match f(&mut *write_guard)? {
  138. None => {}
  139. Some(change) => {
  140. let _ = self.apply_change(change).await?;
  141. }
  142. }
  143. Ok(())
  144. }
  145. async fn apply_change(&self, change: GridBlockRevisionChangeset) -> FlowyResult<()> {
  146. let GridBlockRevisionChangeset { delta, md5 } = change;
  147. let user_id = self.user_id.clone();
  148. let (base_rev_id, rev_id) = self.rev_manager.next_rev_id_pair();
  149. let delta_data = delta.json_bytes();
  150. let revision = Revision::new(
  151. &self.rev_manager.object_id,
  152. base_rev_id,
  153. rev_id,
  154. delta_data,
  155. &user_id,
  156. md5,
  157. );
  158. let _ = self.rev_manager.add_local_revision(&revision).await?;
  159. Ok(())
  160. }
  161. }
  162. struct GridBlockRevisionCloudService {
  163. #[allow(dead_code)]
  164. token: String,
  165. }
  166. impl RevisionCloudService for GridBlockRevisionCloudService {
  167. #[tracing::instrument(level = "trace", skip(self))]
  168. fn fetch_object(&self, _user_id: &str, _object_id: &str) -> FutureResult<Vec<Revision>, FlowyError> {
  169. FutureResult::new(async move { Ok(vec![]) })
  170. }
  171. }
  172. struct GridBlockRevisionPadBuilder();
  173. impl RevisionObjectBuilder for GridBlockRevisionPadBuilder {
  174. type Output = GridBlockRevisionPad;
  175. fn build_object(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {
  176. let pad = GridBlockRevisionPad::from_revisions(object_id, revisions)?;
  177. Ok(pad)
  178. }
  179. }
  180. pub struct GridBlockRevisionCompactor();
  181. impl RevisionCompactor for GridBlockRevisionCompactor {
  182. fn bytes_from_revisions(&self, revisions: Vec<Revision>) -> FlowyResult<Bytes> {
  183. let delta = make_delta_from_revisions(revisions)?;
  184. Ok(delta.json_bytes())
  185. }
  186. }