261 lines
8.5 KiB
Rust
Raw Normal View History

2022-03-05 10:59:44 +08:00
use crate::entities::revision::{md5, RepeatedRevision, Revision};
2022-03-04 18:11:12 +08:00
use crate::errors::{internal_error, CollaborateError, CollaborateResult};
use crate::util::{cal_diff, make_delta_from_revisions};
2022-03-11 21:36:00 +08:00
use flowy_grid_data_model::entities::{
2022-03-13 23:16:52 +08:00
Field, FieldChangeset, GridBlock, GridBlockChangeset, GridMeta, RepeatedFieldOrder,
2022-03-11 21:36:00 +08:00
};
2022-03-04 18:11:12 +08:00
use lib_infra::uuid;
2022-03-06 09:03:02 +08:00
use lib_ot::core::{OperationTransformable, PlainTextAttributes, PlainTextDelta, PlainTextDeltaBuilder};
2022-03-11 21:36:00 +08:00
use std::collections::HashMap;
2022-03-04 18:11:12 +08:00
use std::sync::Arc;
2022-03-12 09:30:13 +08:00
pub type GridMetaDelta = PlainTextDelta;
2022-03-04 18:11:12 +08:00
pub type GridDeltaBuilder = PlainTextDeltaBuilder;
2022-03-10 12:01:31 +08:00
pub struct GridMetaPad {
pub(crate) grid_meta: Arc<GridMeta>,
2022-03-12 09:30:13 +08:00
pub(crate) delta: GridMetaDelta,
2022-03-04 18:11:12 +08:00
}
2022-03-10 12:01:31 +08:00
impl GridMetaPad {
2022-03-12 09:30:13 +08:00
pub fn from_delta(delta: GridMetaDelta) -> CollaborateResult<Self> {
2022-03-04 18:11:12 +08:00
let s = delta.to_str()?;
2022-03-10 12:01:31 +08:00
let grid: GridMeta = serde_json::from_str(&s)
2022-03-04 18:11:12 +08:00
.map_err(|e| CollaborateError::internal().context(format!("Deserialize delta to grid failed: {}", e)))?;
Ok(Self {
2022-03-10 12:01:31 +08:00
grid_meta: Arc::new(grid),
2022-03-04 18:11:12 +08:00
delta,
})
}
2022-03-05 10:59:44 +08:00
pub fn from_revisions(_grid_id: &str, revisions: Vec<Revision>) -> CollaborateResult<Self> {
2022-03-12 09:30:13 +08:00
let grid_delta: GridMetaDelta = make_delta_from_revisions::<PlainTextAttributes>(revisions)?;
2022-03-10 12:01:31 +08:00
Self::from_delta(grid_delta)
2022-03-04 18:11:12 +08:00
}
2022-03-10 12:01:31 +08:00
pub fn create_field(&mut self, field: Field) -> CollaborateResult<Option<GridChange>> {
2022-03-04 18:11:12 +08:00
self.modify_grid(|grid| {
2022-03-13 11:06:28 +08:00
if grid.fields.contains(&field) {
tracing::warn!("Duplicate grid field");
Ok(None)
} else {
grid.fields.push(field);
Ok(Some(()))
}
2022-03-04 18:11:12 +08:00
})
}
pub fn delete_field(&mut self, field_id: &str) -> CollaborateResult<Option<GridChange>> {
2022-03-10 12:01:31 +08:00
self.modify_grid(|grid| match grid.fields.iter().position(|field| field.id == field_id) {
None => Ok(None),
Some(index) => {
grid.fields.remove(index);
Ok(Some(()))
2022-03-04 18:11:12 +08:00
}
})
}
2022-03-13 11:06:28 +08:00
pub fn get_fields(&self, field_orders: Option<RepeatedFieldOrder>) -> CollaborateResult<Vec<Field>> {
2022-03-12 22:52:24 +08:00
match field_orders {
2022-03-13 23:16:52 +08:00
None => Ok(self.grid_meta.fields.clone()),
2022-03-12 22:52:24 +08:00
Some(field_orders) => {
let field_by_field_id = self
.grid_meta
.fields
.iter()
.map(|field| (&field.id, field))
.collect::<HashMap<&String, &Field>>();
2022-03-11 21:36:00 +08:00
2022-03-12 22:52:24 +08:00
let fields = field_orders
.iter()
.flat_map(|field_order| match field_by_field_id.get(&field_order.field_id) {
None => {
tracing::error!("Can't find the field with id: {}", field_order.field_id);
None
}
Some(field) => Some((*field).clone()),
})
.collect::<Vec<Field>>();
2022-03-13 11:06:28 +08:00
Ok(fields)
2022-03-12 22:52:24 +08:00
}
}
2022-03-11 21:36:00 +08:00
}
pub fn update_field(&mut self, change: FieldChangeset) -> CollaborateResult<Option<GridChange>> {
let field_id = change.field_id.clone();
self.modify_field(&field_id, |field| {
let mut is_changed = None;
if let Some(name) = change.name {
field.name = name;
is_changed = Some(())
}
if let Some(desc) = change.desc {
field.desc = desc;
is_changed = Some(())
}
if let Some(field_type) = change.field_type {
field.field_type = field_type;
is_changed = Some(())
}
if let Some(frozen) = change.frozen {
field.frozen = frozen;
is_changed = Some(())
}
if let Some(visibility) = change.visibility {
field.visibility = visibility;
is_changed = Some(())
}
if let Some(width) = change.width {
field.width = width;
is_changed = Some(())
}
if let Some(type_options) = change.type_options {
field.type_options = type_options;
is_changed = Some(())
}
Ok(is_changed)
})
}
pub fn create_block(&mut self, block: GridBlock) -> CollaborateResult<Option<GridChange>> {
self.modify_grid(|grid| {
2022-03-13 23:16:52 +08:00
if grid.blocks.iter().any(|b| b.id == block.id) {
2022-03-13 11:06:28 +08:00
tracing::warn!("Duplicate grid block");
Ok(None)
} else {
grid.blocks.push(block);
Ok(Some(()))
}
2022-03-11 21:36:00 +08:00
})
}
2022-03-12 09:30:13 +08:00
pub fn get_blocks(&self) -> Vec<GridBlock> {
self.grid_meta.blocks.clone()
}
2022-03-11 21:36:00 +08:00
pub fn update_block(&mut self, change: GridBlockChangeset) -> CollaborateResult<Option<GridChange>> {
let block_id = change.block_id.clone();
self.modify_block(&block_id, |block| {
let mut is_changed = None;
if let Some(row_count) = change.row_count {
block.row_count = row_count;
is_changed = Some(());
}
2022-03-13 11:06:28 +08:00
if let Some(start_row_index) = change.start_row_index {
block.start_row_index = start_row_index;
is_changed = Some(());
}
2022-03-11 21:36:00 +08:00
Ok(is_changed)
})
}
pub fn md5(&self) -> String {
md5(&self.delta.to_bytes())
2022-03-05 10:59:44 +08:00
}
2022-03-05 22:30:42 +08:00
pub fn delta_str(&self) -> String {
self.delta.to_delta_str()
}
2022-03-10 12:01:31 +08:00
pub fn fields(&self) -> &[Field] {
&self.grid_meta.fields
2022-03-05 17:52:25 +08:00
}
2022-03-11 21:36:00 +08:00
fn modify_grid<F>(&mut self, f: F) -> CollaborateResult<Option<GridChange>>
2022-03-04 18:11:12 +08:00
where
2022-03-10 12:01:31 +08:00
F: FnOnce(&mut GridMeta) -> CollaborateResult<Option<()>>,
2022-03-04 18:11:12 +08:00
{
2022-03-10 12:01:31 +08:00
let cloned_grid = self.grid_meta.clone();
match f(Arc::make_mut(&mut self.grid_meta))? {
2022-03-04 18:11:12 +08:00
None => Ok(None),
Some(_) => {
let old = json_from_grid(&cloned_grid)?;
2022-03-10 12:01:31 +08:00
let new = json_from_grid(&self.grid_meta)?;
2022-03-04 18:11:12 +08:00
match cal_diff::<PlainTextAttributes>(old, new) {
None => Ok(None),
Some(delta) => {
self.delta = self.delta.compose(&delta)?;
Ok(Some(GridChange { delta, md5: self.md5() }))
}
}
}
}
}
2022-03-11 21:36:00 +08:00
pub fn modify_block<F>(&mut self, block_id: &str, f: F) -> CollaborateResult<Option<GridChange>>
where
F: FnOnce(&mut GridBlock) -> CollaborateResult<Option<()>>,
{
self.modify_grid(|grid| match grid.blocks.iter().position(|block| block.id == block_id) {
None => {
tracing::warn!("[GridMetaPad]: Can't find any block with id: {}", block_id);
Ok(None)
}
Some(index) => f(&mut grid.blocks[index]),
})
}
pub fn modify_field<F>(&mut self, field_id: &str, f: F) -> CollaborateResult<Option<GridChange>>
where
F: FnOnce(&mut Field) -> CollaborateResult<Option<()>>,
{
self.modify_grid(|grid| match grid.fields.iter().position(|field| field.id == field_id) {
None => {
tracing::warn!("[GridMetaPad]: Can't find any field with id: {}", field_id);
Ok(None)
}
Some(index) => f(&mut grid.fields[index]),
})
}
2022-03-04 18:11:12 +08:00
}
2022-03-10 12:01:31 +08:00
fn json_from_grid(grid: &Arc<GridMeta>) -> CollaborateResult<String> {
2022-03-04 18:11:12 +08:00
let json = serde_json::to_string(grid)
.map_err(|err| internal_error(format!("Serialize grid to json str failed. {:?}", err)))?;
Ok(json)
}
pub struct GridChange {
2022-03-12 09:30:13 +08:00
pub delta: GridMetaDelta,
2022-03-04 18:11:12 +08:00
/// md5: the md5 of the grid after applying the change.
pub md5: String,
}
2022-03-12 09:30:13 +08:00
pub fn make_grid_delta(grid_meta: &GridMeta) -> GridMetaDelta {
2022-03-10 12:01:31 +08:00
let json = serde_json::to_string(&grid_meta).unwrap();
2022-03-04 18:11:12 +08:00
PlainTextDeltaBuilder::new().insert(&json).build()
}
2022-03-10 12:01:31 +08:00
pub fn make_grid_revisions(user_id: &str, grid_meta: &GridMeta) -> RepeatedRevision {
let delta = make_grid_delta(grid_meta);
2022-03-05 10:59:44 +08:00
let bytes = delta.to_bytes();
2022-03-10 12:01:31 +08:00
let revision = Revision::initial_revision(user_id, &grid_meta.grid_id, bytes);
2022-03-05 10:59:44 +08:00
revision.into()
}
2022-03-10 12:01:31 +08:00
impl std::default::Default for GridMetaPad {
2022-03-04 18:11:12 +08:00
fn default() -> Self {
2022-03-10 12:01:31 +08:00
let grid = GridMeta {
grid_id: uuid(),
fields: vec![],
2022-03-10 17:14:10 +08:00
blocks: vec![],
2022-03-04 18:11:12 +08:00
};
2022-03-05 10:59:44 +08:00
let delta = make_grid_delta(&grid);
2022-03-10 12:01:31 +08:00
GridMetaPad {
grid_meta: Arc::new(grid),
2022-03-04 18:11:12 +08:00
delta,
}
}
}