Merge pull request #847 from AppFlowy-IO/feat/grid_view_lens

Feat/grid view lens
This commit is contained in:
Nathan.fooo 2022-08-15 08:50:08 +08:00 committed by GitHub
commit 1ccdbaff9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 547 additions and 320 deletions

View File

@ -5,7 +5,7 @@ use crate::entities::{
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr;
use flowy_grid_data_model::revision::GridLayoutRevision;
use flowy_grid_data_model::revision::LayoutRevision;
use flowy_sync::entities::grid::GridSettingChangesetParams;
use std::collections::HashMap;
use std::convert::TryInto;
@ -19,7 +19,7 @@ pub struct GridSettingPB {
pub layouts: Vec<GridLayoutPB>,
#[pb(index = 2)]
pub current_layout_type: GridLayoutType,
pub current_layout_type: Layout,
#[pb(index = 3)]
pub filter_configuration_by_field_id: HashMap<String, RepeatedGridConfigurationFilterPB>,
@ -34,13 +34,13 @@ pub struct GridSettingPB {
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct GridLayoutPB {
#[pb(index = 1)]
ty: GridLayoutType,
ty: Layout,
}
impl GridLayoutPB {
pub fn all() -> Vec<GridLayoutPB> {
let mut layouts = vec![];
for layout_ty in GridLayoutType::iter() {
for layout_ty in Layout::iter() {
layouts.push(GridLayoutPB { ty: layout_ty })
}
@ -50,31 +50,31 @@ impl GridLayoutPB {
#[derive(Debug, Clone, PartialEq, Eq, ProtoBuf_Enum, EnumIter)]
#[repr(u8)]
pub enum GridLayoutType {
pub enum Layout {
Table = 0,
Board = 1,
}
impl std::default::Default for GridLayoutType {
impl std::default::Default for Layout {
fn default() -> Self {
GridLayoutType::Table
Layout::Table
}
}
impl std::convert::From<GridLayoutRevision> for GridLayoutType {
fn from(rev: GridLayoutRevision) -> Self {
impl std::convert::From<LayoutRevision> for Layout {
fn from(rev: LayoutRevision) -> Self {
match rev {
GridLayoutRevision::Table => GridLayoutType::Table,
GridLayoutRevision::Board => GridLayoutType::Board,
LayoutRevision::Table => Layout::Table,
LayoutRevision::Board => Layout::Board,
}
}
}
impl std::convert::From<GridLayoutType> for GridLayoutRevision {
fn from(layout: GridLayoutType) -> Self {
impl std::convert::From<Layout> for LayoutRevision {
fn from(layout: Layout) -> Self {
match layout {
GridLayoutType::Table => GridLayoutRevision::Table,
GridLayoutType::Board => GridLayoutRevision::Board,
Layout::Table => LayoutRevision::Table,
Layout::Board => LayoutRevision::Board,
}
}
}
@ -85,7 +85,7 @@ pub struct GridSettingChangesetPayloadPB {
pub grid_id: String,
#[pb(index = 2)]
pub layout_type: GridLayoutType,
pub layout_type: Layout,
#[pb(index = 3, one_of)]
pub insert_filter: Option<CreateGridFilterPayloadPB>,

View File

@ -3,7 +3,7 @@ use bytes::Bytes;
use flowy_error::{FlowyError, FlowyResult};
use flowy_grid_data_model::revision::{CellRevision, GridBlockRevision, RowMetaChangeset, RowRevision};
use flowy_revision::{RevisionCloudService, RevisionCompactor, RevisionManager, RevisionObjectBuilder};
use flowy_sync::client_grid::{GridBlockMetaChange, GridBlockRevisionPad};
use flowy_sync::client_grid::{GridBlockRevisionChangeset, GridBlockRevisionPad};
use flowy_sync::entities::revision::Revision;
use flowy_sync::util::make_delta_from_revisions;
use lib_infra::future::FutureResult;
@ -29,8 +29,8 @@ impl GridBlockRevisionEditor {
let cloud = Arc::new(GridBlockRevisionCloudService {
token: token.to_owned(),
});
let block_meta_pad = rev_manager.load::<GridBlockMetaPadBuilder>(Some(cloud)).await?;
let pad = Arc::new(RwLock::new(block_meta_pad));
let block_revision_pad = rev_manager.load::<GridBlockRevisionPadBuilder>(Some(cloud)).await?;
let pad = Arc::new(RwLock::new(block_revision_pad));
let rev_manager = Arc::new(rev_manager);
let user_id = user_id.to_owned();
let block_id = block_id.to_owned();
@ -145,7 +145,7 @@ impl GridBlockRevisionEditor {
async fn modify<F>(&self, f: F) -> FlowyResult<()>
where
F: for<'a> FnOnce(&'a mut GridBlockRevisionPad) -> FlowyResult<Option<GridBlockMetaChange>>,
F: for<'a> FnOnce(&'a mut GridBlockRevisionPad) -> FlowyResult<Option<GridBlockRevisionChangeset>>,
{
let mut write_guard = self.pad.write().await;
match f(&mut *write_guard)? {
@ -157,8 +157,8 @@ impl GridBlockRevisionEditor {
Ok(())
}
async fn apply_change(&self, change: GridBlockMetaChange) -> FlowyResult<()> {
let GridBlockMetaChange { delta, md5 } = change;
async fn apply_change(&self, change: GridBlockRevisionChangeset) -> FlowyResult<()> {
let GridBlockRevisionChangeset { delta, md5 } = change;
let user_id = self.user_id.clone();
let (base_rev_id, rev_id) = self.rev_manager.next_rev_id_pair();
let delta_data = delta.json_bytes();
@ -187,8 +187,8 @@ impl RevisionCloudService for GridBlockRevisionCloudService {
}
}
struct GridBlockMetaPadBuilder();
impl RevisionObjectBuilder for GridBlockMetaPadBuilder {
struct GridBlockRevisionPadBuilder();
impl RevisionObjectBuilder for GridBlockRevisionPadBuilder {
type Output = GridBlockRevisionPad;
fn build_object(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {

View File

@ -108,7 +108,7 @@ pub(crate) async fn refresh_filter_cache(
grid_pad: &Arc<RwLock<GridRevisionPad>>,
) {
let grid_pad = grid_pad.read().await;
let filters_revs = grid_pad.get_filters(None, field_ids).unwrap_or_default();
let filters_revs = grid_pad.get_filters(field_ids).unwrap_or_default();
for filter_rev in filters_revs {
match grid_pad.get_field_rev(&filter_rev.field_id) {

View File

@ -6,6 +6,7 @@ use crate::services::block_manager::GridBlockManager;
use crate::services::cell::{apply_cell_data_changeset, decode_any_cell_data, CellBytes};
use crate::services::field::{default_type_option_builder_from_type, type_option_builder_from_bytes, FieldBuilder};
use crate::services::filter::{GridFilterChangeset, GridFilterService};
use crate::services::group::GridGroupService;
use crate::services::persistence::block_index::BlockIndexCache;
use crate::services::row::{
@ -16,7 +17,7 @@ use bytes::Bytes;
use flowy_error::{ErrorCode, FlowyError, FlowyResult};
use flowy_grid_data_model::revision::*;
use flowy_revision::{RevisionCloudService, RevisionCompactor, RevisionManager, RevisionObjectBuilder};
use flowy_sync::client_grid::{GridChangeset, GridRevisionPad, JsonDeserializer};
use flowy_sync::client_grid::{GridRevisionChangeset, GridRevisionPad, JsonDeserializer};
use flowy_sync::entities::grid::{FieldChangesetParams, GridSettingChangesetParams};
use flowy_sync::entities::revision::Revision;
use flowy_sync::errors::CollaborateResult;
@ -31,8 +32,10 @@ pub struct GridRevisionEditor {
pub(crate) grid_id: String,
user: Arc<dyn GridUser>,
grid_pad: Arc<RwLock<GridRevisionPad>>,
// view_editor: Arc<GridViewRevisionEditor>,
rev_manager: Arc<RevisionManager>,
block_manager: Arc<GridBlockManager>,
#[allow(dead_code)]
pub(crate) filter_service: Arc<GridFilterService>,
@ -59,6 +62,7 @@ impl GridRevisionEditor {
let grid_pad = rev_manager.load::<GridPadBuilder>(Some(cloud)).await?;
let rev_manager = Arc::new(rev_manager);
let grid_pad = Arc::new(RwLock::new(grid_pad));
let block_meta_revs = grid_pad.read().await.get_block_meta_revs();
let block_manager = Arc::new(GridBlockManager::new(grid_id, &user, block_meta_revs, persistence).await?);
let filter_service =
@ -447,10 +451,9 @@ impl GridRevisionEditor {
Ok(grid_setting)
}
pub async fn get_grid_filter(&self, layout_type: &GridLayoutType) -> FlowyResult<Vec<GridFilterConfiguration>> {
pub async fn get_grid_filter(&self) -> FlowyResult<Vec<GridFilterConfiguration>> {
let read_guard = self.grid_pad.read().await;
let layout_rev = layout_type.clone().into();
match read_guard.get_filters(Some(&layout_rev), None) {
match read_guard.get_filters(None) {
Some(filter_revs) => Ok(filter_revs
.iter()
.map(|filter_rev| filter_rev.as_ref().into())
@ -609,7 +612,7 @@ impl GridRevisionEditor {
async fn modify<F>(&self, f: F) -> FlowyResult<()>
where
F: for<'a> FnOnce(&'a mut GridRevisionPad) -> FlowyResult<Option<GridChangeset>>,
F: for<'a> FnOnce(&'a mut GridRevisionPad) -> FlowyResult<Option<GridRevisionChangeset>>,
{
let mut write_guard = self.grid_pad.write().await;
if let Some(changeset) = f(&mut *write_guard)? {
@ -618,8 +621,8 @@ impl GridRevisionEditor {
Ok(())
}
async fn apply_change(&self, change: GridChangeset) -> FlowyResult<()> {
let GridChangeset { delta, md5 } = change;
async fn apply_change(&self, change: GridRevisionChangeset) -> FlowyResult<()> {
let GridRevisionChangeset { delta, md5 } = change;
let user_id = self.user.user_id()?;
let (base_rev_id, rev_id) = self.rev_manager.next_rev_id_pair();
let delta_data = delta.json_bytes();

View File

@ -0,0 +1,52 @@
use flowy_error::{FlowyError, FlowyResult};
use flowy_revision::{RevisionCloudService, RevisionManager, RevisionObjectBuilder};
use flowy_sync::client_grid::GridViewRevisionPad;
use flowy_sync::entities::revision::Revision;
use lib_infra::future::FutureResult;
use std::sync::Arc;
use tokio::sync::RwLock;
#[allow(dead_code)]
pub struct GridViewRevisionEditor {
#[allow(dead_code)]
pad: Arc<RwLock<GridViewRevisionPad>>,
#[allow(dead_code)]
rev_manager: Arc<RevisionManager>,
}
impl GridViewRevisionEditor {
#[allow(dead_code)]
pub async fn new(token: &str, mut rev_manager: RevisionManager) -> FlowyResult<Self> {
let cloud = Arc::new(GridViewRevisionCloudService {
token: token.to_owned(),
});
let view_revision_pad = rev_manager.load::<GridViewRevisionPadBuilder>(Some(cloud)).await?;
let pad = Arc::new(RwLock::new(view_revision_pad));
let rev_manager = Arc::new(rev_manager);
Ok(Self { pad, rev_manager })
}
}
struct GridViewRevisionCloudService {
#[allow(dead_code)]
token: String,
}
impl RevisionCloudService for GridViewRevisionCloudService {
#[tracing::instrument(level = "trace", skip(self))]
fn fetch_object(&self, _user_id: &str, _object_id: &str) -> FutureResult<Vec<Revision>, FlowyError> {
FutureResult::new(async move { Ok(vec![]) })
}
}
struct GridViewRevisionPadBuilder();
impl RevisionObjectBuilder for GridViewRevisionPadBuilder {
type Output = GridViewRevisionPad;
fn build_object(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {
let pad = GridViewRevisionPad::from_revisions(object_id, revisions)?;
Ok(pad)
}
}

View File

@ -83,8 +83,7 @@ impl GridGroupService {
pub(crate) async fn get_group_configuration(&self, field_rev: &FieldRevision) -> GroupConfigurationRevision {
let grid_pad = self.grid_pad.read().await;
let setting = grid_pad.get_setting_rev();
let layout = &setting.layout;
let configurations = setting.get_groups(layout, &field_rev.id, &field_rev.field_type_rev);
let configurations = setting.get_groups(&field_rev.id, &field_rev.field_type_rev);
match configurations {
None => default_group_configuration(field_rev),
Some(mut configurations) => {

View File

@ -7,6 +7,7 @@ pub mod field;
mod filter;
pub mod grid_editor;
mod grid_editor_task;
pub mod grid_view_editor;
pub mod group;
pub mod persistence;
pub mod row;

View File

@ -1,8 +1,8 @@
use crate::entities::{
GridLayoutPB, GridLayoutType, GridSettingPB, RepeatedGridConfigurationFilterPB, RepeatedGridGroupConfigurationPB,
GridLayoutPB, GridSettingPB, Layout, RepeatedGridConfigurationFilterPB, RepeatedGridGroupConfigurationPB,
RepeatedGridSortPB,
};
use flowy_grid_data_model::revision::{FieldRevision, GridSettingRevision};
use flowy_grid_data_model::revision::{FieldRevision, SettingRevision};
use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams};
use std::collections::HashMap;
use std::sync::Arc;
@ -12,7 +12,7 @@ pub struct GridSettingChangesetBuilder {
}
impl GridSettingChangesetBuilder {
pub fn new(grid_id: &str, layout_type: &GridLayoutType) -> Self {
pub fn new(grid_id: &str, layout_type: &Layout) -> Self {
let params = GridSettingChangesetParams {
grid_id: grid_id.to_string(),
layout_type: layout_type.clone().into(),
@ -41,8 +41,8 @@ impl GridSettingChangesetBuilder {
}
}
pub fn make_grid_setting(grid_setting_rev: &GridSettingRevision, field_revs: &[Arc<FieldRevision>]) -> GridSettingPB {
let current_layout_type: GridLayoutType = grid_setting_rev.layout.clone().into();
pub fn make_grid_setting(grid_setting_rev: &SettingRevision, field_revs: &[Arc<FieldRevision>]) -> GridSettingPB {
let current_layout_type: Layout = grid_setting_rev.layout.clone().into();
let filters_by_field_id = grid_setting_rev
.get_all_filters(field_revs)
.map(|filters_by_field_id| {

View File

@ -3,7 +3,7 @@
#![allow(dead_code)]
#![allow(unused_imports)]
use flowy_grid::entities::{CreateGridFilterPayloadPB, GridLayoutType, GridSettingPB};
use flowy_grid::entities::{CreateGridFilterPayloadPB, Layout, GridSettingPB};
use flowy_grid::services::setting::GridSettingChangesetBuilder;
use flowy_grid_data_model::revision::{FieldRevision, FieldTypeRevision};
use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams};
@ -55,19 +55,18 @@ impl GridFilterTest {
}
FilterScript::InsertGridTableFilter { payload } => {
let params: CreateGridFilterParams = payload.try_into().unwrap();
let layout_type = GridLayoutType::Table;
let layout_type = Layout::Table;
let params = GridSettingChangesetBuilder::new(&self.grid_id, &layout_type)
.insert_filter(params)
.build();
let _ = self.editor.update_grid_setting(params).await.unwrap();
}
FilterScript::AssertTableFilterCount { count } => {
let layout_type = GridLayoutType::Table;
let filters = self.editor.get_grid_filter(&layout_type).await.unwrap();
let filters = self.editor.get_grid_filter().await.unwrap();
assert_eq!(count as usize, filters.len());
}
FilterScript::DeleteGridTableFilter { filter_id, field_rev} => {
let layout_type = GridLayoutType::Table;
let layout_type = Layout::Table;
let params = GridSettingChangesetBuilder::new(&self.grid_id, &layout_type)
.delete_filter(DeleteFilterParams { field_id: field_rev.id, filter_id, field_type_rev: field_rev.field_type_rev })
.build();

View File

@ -76,8 +76,7 @@ impl GridEditorTest {
}
pub async fn grid_filters(&self) -> Vec<GridFilterConfiguration> {
let layout_type = GridLayoutType::Table;
self.editor.get_grid_filter(&layout_type).await.unwrap()
self.editor.get_grid_filter().await.unwrap()
}
pub fn get_field_rev(&self, field_type: FieldType) -> &Arc<FieldRevision> {

View File

@ -1,6 +1,5 @@
use crate::cache::disk::RevisionDiskCache;
use crate::disk::{RevisionChangeset, RevisionRecord, RevisionState};
use bytes::Bytes;
use diesel::{sql_types::Integer, update, SqliteConnection};
use flowy_database::{

View File

@ -1,12 +1,10 @@
mod folder_rev_impl;
mod grid_block_meta_rev_impl;
mod grid_rev_impl;
mod text_rev_impl;
mod document_impl;
mod grid_block_impl;
mod grid_impl;
pub use folder_rev_impl::*;
pub use grid_block_meta_rev_impl::*;
pub use grid_rev_impl::*;
pub use text_rev_impl::*;
pub use document_impl::*;
pub use grid_block_impl::*;
pub use grid_impl::*;
use flowy_error::FlowyResult;
use flowy_sync::entities::revision::{RevId, Revision, RevisionRange};

View File

@ -1,9 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
pub struct FilterConfigurationRevision {
pub id: String,
pub field_id: String,
pub condition: u8,
pub content: Option<String>,
}

View File

@ -0,0 +1,61 @@
use indexmap::IndexMap;
use nanoid::nanoid;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
pub fn gen_row_id() -> String {
nanoid!(6)
}
pub const DEFAULT_ROW_HEIGHT: i32 = 42;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GridBlockRevision {
pub block_id: String,
pub rows: Vec<Arc<RowRevision>>,
}
pub type FieldId = String;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RowRevision {
pub id: String,
pub block_id: String,
/// cells contains key/value pairs.
/// key: field id,
/// value: CellMeta
#[serde(with = "indexmap::serde_seq")]
pub cells: IndexMap<FieldId, CellRevision>,
pub height: i32,
pub visibility: bool,
}
impl RowRevision {
pub fn new(block_id: &str) -> Self {
Self {
id: gen_row_id(),
block_id: block_id.to_owned(),
cells: Default::default(),
height: DEFAULT_ROW_HEIGHT,
visibility: true,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct RowMetaChangeset {
pub row_id: String,
pub height: Option<i32>,
pub visibility: Option<bool>,
pub cell_by_field_id: HashMap<FieldId, CellRevision>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CellRevision {
pub data: String,
}
impl CellRevision {
pub fn new(data: String) -> Self {
Self { data }
}
}

View File

@ -1,10 +0,0 @@
use crate::revision::FieldTypeRevision;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct GroupConfigurationRevision {
pub id: String,
pub field_id: String,
pub field_type_rev: FieldTypeRevision,
pub content: Option<Vec<u8>>,
}

View File

@ -1,13 +1,10 @@
use crate::revision::GridSettingRevision;
use crate::revision::{GridBlockRevision, SettingRevision};
use bytes::Bytes;
use indexmap::IndexMap;
use nanoid::nanoid;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
pub const DEFAULT_ROW_HEIGHT: i32 = 42;
pub fn gen_grid_id() -> String {
// nanoid calculator https://zelark.github.io/nano-id-cc/
nanoid!(10)
@ -17,10 +14,6 @@ pub fn gen_block_id() -> String {
nanoid!(10)
}
pub fn gen_row_id() -> String {
nanoid!(6)
}
pub fn gen_field_id() -> String {
nanoid!(6)
}
@ -32,7 +25,7 @@ pub struct GridRevision {
pub blocks: Vec<Arc<GridBlockMetaRevision>>,
#[serde(default)]
pub setting: GridSettingRevision,
pub setting: SettingRevision,
}
impl GridRevision {
@ -41,7 +34,7 @@ impl GridRevision {
grid_id: grid_id.to_owned(),
fields: vec![],
blocks: vec![],
setting: GridSettingRevision::default(),
setting: SettingRevision::default(),
}
}
@ -97,12 +90,6 @@ impl GridBlockMetaRevisionChangeset {
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GridBlockRevision {
pub block_id: String,
pub rows: Vec<Arc<RowRevision>>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
pub struct FieldRevision {
pub id: String,
@ -201,50 +188,6 @@ pub trait TypeOptionDataDeserializer {
fn from_protobuf_bytes(bytes: Bytes) -> Self;
}
pub type FieldId = String;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RowRevision {
pub id: String,
pub block_id: String,
/// cells contains key/value pairs.
/// key: field id,
/// value: CellMeta
#[serde(with = "indexmap::serde_seq")]
pub cells: IndexMap<FieldId, CellRevision>,
pub height: i32,
pub visibility: bool,
}
impl RowRevision {
pub fn new(block_id: &str) -> Self {
Self {
id: gen_row_id(),
block_id: block_id.to_owned(),
cells: Default::default(),
height: DEFAULT_ROW_HEIGHT,
visibility: true,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct RowMetaChangeset {
pub row_id: String,
pub height: Option<i32>,
pub visibility: Option<bool>,
pub cell_by_field_id: HashMap<FieldId, CellRevision>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CellRevision {
pub data: String,
}
impl CellRevision {
pub fn new(data: String) -> Self {
Self { data }
}
}
#[derive(Clone, Default, Deserialize, Serialize)]
pub struct BuildGridContext {
pub field_revs: Vec<Arc<FieldRevision>>,

View File

@ -1,5 +1,3 @@
use crate::revision::filter_rev::FilterConfigurationRevision;
use crate::revision::grid_group::GroupConfigurationRevision;
use crate::revision::{FieldRevision, FieldTypeRevision};
use indexmap::IndexMap;
use nanoid::nanoid;
@ -21,115 +19,107 @@ pub fn gen_grid_sort_id() -> String {
nanoid!(6)
}
pub type FilterConfigurations = SettingConfiguration<FilterConfigurationRevision>;
pub type FilterConfigurationRevisionMap = GridObjectRevisionMap<FilterConfigurationRevision>;
pub type FilterConfiguration = Configuration<FilterConfigurationRevision>;
pub type FilterConfigurationsByFieldId = HashMap<String, Vec<Arc<FilterConfigurationRevision>>>;
//
pub type GroupConfigurations = SettingConfiguration<GroupConfigurationRevision>;
pub type GroupConfigurationRevisionMap = GridObjectRevisionMap<GroupConfigurationRevision>;
pub type GroupConfiguration = Configuration<GroupConfigurationRevision>;
pub type GroupConfigurationsByFieldId = HashMap<String, Vec<Arc<GroupConfigurationRevision>>>;
//
pub type SortConfigurations = SettingConfiguration<SortConfigurationRevision>;
pub type SortConfigurationRevisionMap = GridObjectRevisionMap<SortConfigurationRevision>;
pub type SortConfiguration = Configuration<SortConfigurationRevision>;
pub type SortConfigurationsByFieldId = HashMap<String, Vec<Arc<SortConfigurationRevision>>>;
#[derive(Debug, Clone, Serialize, Deserialize, Default, Eq, PartialEq)]
pub struct GridSettingRevision {
pub layout: GridLayoutRevision,
pub struct SettingRevision {
pub layout: LayoutRevision,
pub filters: FilterConfigurations,
pub filters: FilterConfiguration,
#[serde(default)]
pub groups: GroupConfigurations,
pub groups: GroupConfiguration,
#[serde(skip)]
pub sorts: SortConfigurations,
pub sorts: SortConfiguration,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize_repr, Deserialize_repr)]
#[repr(u8)]
pub enum GridLayoutRevision {
pub enum LayoutRevision {
Table = 0,
Board = 1,
}
impl ToString for GridLayoutRevision {
impl ToString for LayoutRevision {
fn to_string(&self) -> String {
let layout_rev = self.clone() as u8;
layout_rev.to_string()
}
}
impl std::default::Default for GridLayoutRevision {
impl std::default::Default for LayoutRevision {
fn default() -> Self {
GridLayoutRevision::Table
LayoutRevision::Table
}
}
impl GridSettingRevision {
impl SettingRevision {
pub fn get_all_groups(&self, field_revs: &[Arc<FieldRevision>]) -> Option<GroupConfigurationsByFieldId> {
self.groups.get_all_objects(&self.layout, field_revs)
self.groups.get_all_objects(field_revs)
}
pub fn get_groups(
&self,
layout: &GridLayoutRevision,
field_id: &str,
field_type_rev: &FieldTypeRevision,
) -> Option<Vec<Arc<GroupConfigurationRevision>>> {
self.groups.get_objects(layout, field_id, field_type_rev)
self.groups.get_objects(field_id, field_type_rev)
}
pub fn get_mut_groups(
&mut self,
layout: &GridLayoutRevision,
field_id: &str,
field_type: &FieldTypeRevision,
) -> Option<&mut Vec<Arc<GroupConfigurationRevision>>> {
self.groups.get_mut_objects(layout, field_id, field_type)
self.groups.get_mut_objects(field_id, field_type)
}
pub fn insert_group(
&mut self,
layout: &GridLayoutRevision,
field_id: &str,
field_type: &FieldTypeRevision,
group_rev: GroupConfigurationRevision,
) {
self.groups.remove_all(layout);
self.groups.insert_object(layout, field_id, field_type, group_rev);
// only one group can be set
self.groups.remove_all();
self.groups.insert_object(field_id, field_type, group_rev);
}
pub fn get_all_filters(&self, field_revs: &[Arc<FieldRevision>]) -> Option<FilterConfigurationsByFieldId> {
self.filters.get_all_objects(&self.layout, field_revs)
self.filters.get_all_objects(field_revs)
}
pub fn get_filters(
&self,
layout: &GridLayoutRevision,
field_id: &str,
field_type_rev: &FieldTypeRevision,
) -> Option<Vec<Arc<FilterConfigurationRevision>>> {
self.filters.get_objects(layout, field_id, field_type_rev)
self.filters.get_objects(field_id, field_type_rev)
}
pub fn get_mut_filters(
&mut self,
layout: &GridLayoutRevision,
field_id: &str,
field_type: &FieldTypeRevision,
) -> Option<&mut Vec<Arc<FilterConfigurationRevision>>> {
self.filters.get_mut_objects(layout, field_id, field_type)
self.filters.get_mut_objects(field_id, field_type)
}
pub fn insert_filter(
&mut self,
layout: &GridLayoutRevision,
field_id: &str,
field_type: &FieldTypeRevision,
filter_rev: FilterConfigurationRevision,
) {
self.filters.insert_object(layout, field_id, field_type, filter_rev);
self.filters.insert_object(field_id, field_type, filter_rev);
}
pub fn get_all_sort(&self) -> Option<SortConfigurationsByFieldId> {
@ -145,59 +135,40 @@ pub struct SortConfigurationRevision {
#[derive(Debug, Clone, Serialize, Deserialize, Default, Eq, PartialEq)]
#[serde(transparent)]
pub struct SettingConfiguration<T>
pub struct Configuration<T>
where
T: Debug + Clone + Default + Eq + PartialEq + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
/// Each layout contains multiple key/value.
/// Key: field_id
/// Value: this value contains key/value.
/// Key: FieldType,
/// Value: the corresponding objects.
#[serde(with = "indexmap::serde_seq")]
inner: IndexMap<GridLayoutRevision, IndexMap<String, GridObjectRevisionMap<T>>>,
inner: IndexMap<String, ObjectIndexMap<T>>,
}
impl<T> SettingConfiguration<T>
impl<T> Configuration<T>
where
T: Debug + Clone + Default + Eq + PartialEq + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
pub fn get_mut_objects(
&mut self,
layout: &GridLayoutRevision,
field_id: &str,
field_type: &FieldTypeRevision,
) -> Option<&mut Vec<Arc<T>>> {
pub fn get_mut_objects(&mut self, field_id: &str, field_type: &FieldTypeRevision) -> Option<&mut Vec<Arc<T>>> {
let value = self
.inner
.get_mut(layout)
.and_then(|object_rev_map_by_field_id| object_rev_map_by_field_id.get_mut(field_id))
.get_mut(field_id)
.and_then(|object_rev_map| object_rev_map.get_mut(field_type));
if value.is_none() {
tracing::warn!("Can't find the {:?} with", std::any::type_name::<T>());
}
value
}
pub fn get_objects(
&self,
layout: &GridLayoutRevision,
field_id: &str,
field_type_rev: &FieldTypeRevision,
) -> Option<Vec<Arc<T>>> {
pub fn get_objects(&self, field_id: &str, field_type_rev: &FieldTypeRevision) -> Option<Vec<Arc<T>>> {
self.inner
.get(layout)
.and_then(|object_rev_map_by_field_id| object_rev_map_by_field_id.get(field_id))
.get(field_id)
.and_then(|object_rev_map| object_rev_map.get(field_type_rev))
.cloned()
}
pub fn get_all_objects(
&self,
layout: &GridLayoutRevision,
field_revs: &[Arc<FieldRevision>],
) -> Option<HashMap<String, Vec<Arc<T>>>> {
// Acquire the read lock.
let object_rev_map_by_field_id = self.inner.get(layout)?;
pub fn get_all_objects(&self, field_revs: &[Arc<FieldRevision>]) -> Option<HashMap<String, Vec<Arc<T>>>> {
// Get the objects according to the FieldType, so we need iterate the field_revs.
let objects_by_field_id = field_revs
.iter()
@ -205,7 +176,7 @@ where
let field_type = &field_rev.field_type_rev;
let field_id = &field_rev.id;
let object_rev_map = object_rev_map_by_field_id.get(field_id)?;
let object_rev_map = self.inner.get(field_id)?;
let objects: Vec<Arc<T>> = object_rev_map.get(field_type)?.clone();
Some((field_rev.id.clone(), objects))
})
@ -213,17 +184,11 @@ where
Some(objects_by_field_id)
}
pub fn insert_object(
&mut self,
layout: &GridLayoutRevision,
field_id: &str,
field_type: &FieldTypeRevision,
object: T,
) {
let object_rev_map_by_field_id = self.inner.entry(layout.clone()).or_insert_with(IndexMap::new);
let object_rev_map = object_rev_map_by_field_id
pub fn insert_object(&mut self, field_id: &str, field_type: &FieldTypeRevision, object: T) {
let object_rev_map = self
.inner
.entry(field_id.to_string())
.or_insert_with(GridObjectRevisionMap::<T>::new);
.or_insert_with(ObjectIndexMap::<T>::new);
object_rev_map
.entry(field_type.to_owned())
@ -231,16 +196,14 @@ where
.push(Arc::new(object))
}
pub fn remove_all(&mut self, layout: &GridLayoutRevision) {
if let Some(object_rev_map_by_field_id) = self.inner.get_mut(layout) {
object_rev_map_by_field_id.clear()
}
pub fn remove_all(&mut self) {
self.inner.clear()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, Eq, PartialEq)]
#[serde(transparent)]
pub struct GridObjectRevisionMap<T>
pub struct ObjectIndexMap<T>
where
T: Debug + Clone + Default + Eq + PartialEq + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
@ -248,16 +211,16 @@ where
pub object_by_field_type: IndexMap<FieldTypeRevision, Vec<Arc<T>>>,
}
impl<T> GridObjectRevisionMap<T>
impl<T> ObjectIndexMap<T>
where
T: Debug + Clone + Default + Eq + PartialEq + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
pub fn new() -> Self {
GridObjectRevisionMap::default()
ObjectIndexMap::default()
}
}
impl<T> std::ops::Deref for GridObjectRevisionMap<T>
impl<T> std::ops::Deref for ObjectIndexMap<T>
where
T: Debug + Clone + Default + Eq + PartialEq + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
@ -268,7 +231,7 @@ where
}
}
impl<T> std::ops::DerefMut for GridObjectRevisionMap<T>
impl<T> std::ops::DerefMut for ObjectIndexMap<T>
where
T: Debug + Clone + Default + Eq + PartialEq + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
@ -276,3 +239,19 @@ where
&mut self.object_by_field_type
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct GroupConfigurationRevision {
pub id: String,
pub field_id: String,
pub field_type_rev: FieldTypeRevision,
pub content: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
pub struct FilterConfigurationRevision {
pub id: String,
pub field_id: String,
pub condition: u8,
pub content: Option<String>,
}

View File

@ -0,0 +1,37 @@
use crate::revision::SettingRevision;
use nanoid::nanoid;
use serde::{Deserialize, Serialize};
pub fn gen_grid_view_id() -> String {
nanoid!(6)
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GridViewRevision {
pub view_id: String,
pub grid_id: String,
pub setting: SettingRevision,
// For the moment, we just use the order returned from the GridRevision
#[allow(dead_code)]
#[serde(skip, rename = "row")]
pub row_orders: Vec<RowOrderRevision>,
}
impl GridViewRevision {
pub fn new(grid_id: String) -> Self {
GridViewRevision {
view_id: gen_grid_view_id(),
grid_id,
setting: Default::default(),
row_orders: vec![],
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RowOrderRevision {
pub row_id: String,
}

View File

@ -1,9 +1,9 @@
mod filter_rev;
mod grid_group;
mod grid_block;
mod grid_rev;
mod grid_setting_rev;
mod grid_view;
pub use filter_rev::*;
pub use grid_group::*;
pub use grid_block::*;
pub use grid_rev::*;
pub use grid_setting_rev::*;
pub use grid_view::*;

View File

@ -1,6 +1,6 @@
use crate::entities::revision::{md5, RepeatedRevision, Revision};
use crate::errors::{CollaborateError, CollaborateResult};
use crate::util::{cal_diff, make_delta_from_revisions};
use crate::util::{cal_diff, make_text_delta_from_revisions};
use flowy_grid_data_model::revision::{
gen_block_id, gen_row_id, CellRevision, GridBlockRevision, RowMetaChangeset, RowRevision,
};
@ -9,27 +9,24 @@ use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
pub type GridBlockRevisionDelta = TextDelta;
pub type GridBlockRevisionDeltaBuilder = TextDeltaBuilder;
#[derive(Debug, Clone)]
pub struct GridBlockRevisionPad {
block_revision: GridBlockRevision,
pub(crate) delta: GridBlockRevisionDelta,
block: GridBlockRevision,
delta: TextDelta,
}
impl std::ops::Deref for GridBlockRevisionPad {
type Target = GridBlockRevision;
fn deref(&self) -> &Self::Target {
&self.block_revision
&self.block
}
}
impl GridBlockRevisionPad {
pub async fn duplicate_data(&self, duplicated_block_id: &str) -> GridBlockRevision {
let duplicated_rows = self
.block_revision
.block
.rows
.iter()
.map(|row| {
@ -45,18 +42,18 @@ impl GridBlockRevisionPad {
}
}
pub fn from_delta(delta: GridBlockRevisionDelta) -> CollaborateResult<Self> {
pub fn from_delta(delta: TextDelta) -> CollaborateResult<Self> {
let s = delta.content()?;
let block_revision: GridBlockRevision = serde_json::from_str(&s).map_err(|e| {
let msg = format!("Deserialize delta to block meta failed: {}", e);
let revision: GridBlockRevision = serde_json::from_str(&s).map_err(|e| {
let msg = format!("Deserialize delta to GridBlockRevision failed: {}", e);
tracing::error!("{}", s);
CollaborateError::internal().context(msg)
})?;
Ok(Self { block_revision, delta })
Ok(Self { block: revision, delta })
}
pub fn from_revisions(_grid_id: &str, revisions: Vec<Revision>) -> CollaborateResult<Self> {
let block_delta: GridBlockRevisionDelta = make_delta_from_revisions::<PhantomAttributes>(revisions)?;
let block_delta: TextDelta = make_text_delta_from_revisions(revisions)?;
Self::from_delta(block_delta)
}
@ -65,7 +62,7 @@ impl GridBlockRevisionPad {
&mut self,
row: RowRevision,
start_row_id: Option<String>,
) -> CollaborateResult<Option<GridBlockMetaChange>> {
) -> CollaborateResult<Option<GridBlockRevisionChangeset>> {
self.modify(|rows| {
if let Some(start_row_id) = start_row_id {
if !start_row_id.is_empty() {
@ -81,7 +78,10 @@ impl GridBlockRevisionPad {
})
}
pub fn delete_rows(&mut self, row_ids: Vec<Cow<'_, String>>) -> CollaborateResult<Option<GridBlockMetaChange>> {
pub fn delete_rows(
&mut self,
row_ids: Vec<Cow<'_, String>>,
) -> CollaborateResult<Option<GridBlockRevisionChangeset>> {
self.modify(|rows| {
rows.retain(|row| !row_ids.contains(&Cow::Borrowed(&row.id)));
Ok(Some(()))
@ -93,10 +93,10 @@ impl GridBlockRevisionPad {
T: AsRef<str> + ToOwned + ?Sized,
{
match row_ids {
None => Ok(self.block_revision.rows.clone()),
None => Ok(self.block.rows.clone()),
Some(row_ids) => {
let row_map = self
.block_revision
.block
.rows
.iter()
.map(|row| (row.id.as_str(), row.clone()))
@ -136,18 +136,18 @@ impl GridBlockRevisionPad {
}
pub fn number_of_rows(&self) -> i32 {
self.block_revision.rows.len() as i32
self.block.rows.len() as i32
}
pub fn index_of_row(&self, row_id: &str) -> Option<i32> {
self.block_revision
self.block
.rows
.iter()
.position(|row| row.id == row_id)
.map(|index| index as i32)
}
pub fn update_row(&mut self, changeset: RowMetaChangeset) -> CollaborateResult<Option<GridBlockMetaChange>> {
pub fn update_row(&mut self, changeset: RowMetaChangeset) -> CollaborateResult<Option<GridBlockRevisionChangeset>> {
let row_id = changeset.row_id.clone();
self.modify_row(&row_id, |row| {
let mut is_changed = None;
@ -172,7 +172,12 @@ impl GridBlockRevisionPad {
})
}
pub fn move_row(&mut self, row_id: &str, from: usize, to: usize) -> CollaborateResult<Option<GridBlockMetaChange>> {
pub fn move_row(
&mut self,
row_id: &str,
from: usize,
to: usize,
) -> CollaborateResult<Option<GridBlockRevisionChangeset>> {
self.modify(|row_revs| {
if let Some(position) = row_revs.iter().position(|row_rev| row_rev.id == row_id) {
debug_assert_eq!(from, position);
@ -185,33 +190,36 @@ impl GridBlockRevisionPad {
})
}
pub fn modify<F>(&mut self, f: F) -> CollaborateResult<Option<GridBlockMetaChange>>
pub fn modify<F>(&mut self, f: F) -> CollaborateResult<Option<GridBlockRevisionChangeset>>
where
F: for<'a> FnOnce(&'a mut Vec<Arc<RowRevision>>) -> CollaborateResult<Option<()>>,
{
let cloned_self = self.clone();
match f(&mut self.block_revision.rows)? {
match f(&mut self.block.rows)? {
None => Ok(None),
Some(_) => {
let old = cloned_self.to_json()?;
let new = self.to_json()?;
let old = cloned_self.revision_json()?;
let new = self.revision_json()?;
match cal_diff::<PhantomAttributes>(old, new) {
None => Ok(None),
Some(delta) => {
tracing::trace!("[GridBlockMeta] Composing delta {}", delta.json_str());
tracing::trace!("[GridBlockRevision] Composing delta {}", delta.json_str());
// tracing::debug!(
// "[GridBlockMeta] current delta: {}",
// self.delta.to_str().unwrap_or_else(|_| "".to_string())
// );
self.delta = self.delta.compose(&delta)?;
Ok(Some(GridBlockMetaChange { delta, md5: self.md5() }))
Ok(Some(GridBlockRevisionChangeset {
delta,
md5: md5(&self.delta.json_bytes()),
}))
}
}
}
}
}
fn modify_row<F>(&mut self, row_id: &str, f: F) -> CollaborateResult<Option<GridBlockMetaChange>>
fn modify_row<F>(&mut self, row_id: &str, f: F) -> CollaborateResult<Option<GridBlockRevisionChangeset>>
where
F: FnOnce(&mut RowRevision) -> CollaborateResult<Option<()>>,
{
@ -225,27 +233,23 @@ impl GridBlockRevisionPad {
})
}
pub fn to_json(&self) -> CollaborateResult<String> {
serde_json::to_string(&self.block_revision)
.map_err(|e| CollaborateError::internal().context(format!("serial trash to json failed: {}", e)))
pub fn revision_json(&self) -> CollaborateResult<String> {
serde_json::to_string(&self.block)
.map_err(|e| CollaborateError::internal().context(format!("serial block to json failed: {}", e)))
}
pub fn md5(&self) -> String {
md5(&self.delta.json_bytes())
}
pub fn delta_str(&self) -> String {
pub fn json_str(&self) -> String {
self.delta.json_str()
}
}
pub struct GridBlockMetaChange {
pub delta: GridBlockRevisionDelta,
pub struct GridBlockRevisionChangeset {
pub delta: TextDelta,
/// md5: the md5 of the grid after applying the change.
pub md5: String,
}
pub fn make_grid_block_delta(block_rev: &GridBlockRevision) -> GridBlockRevisionDelta {
pub fn make_grid_block_delta(block_rev: &GridBlockRevision) -> TextDelta {
let json = serde_json::to_string(&block_rev).unwrap();
TextDeltaBuilder::new().insert(&json).build()
}
@ -265,14 +269,18 @@ impl std::default::Default for GridBlockRevisionPad {
};
let delta = make_grid_block_delta(&block_revision);
GridBlockRevisionPad { block_revision, delta }
GridBlockRevisionPad {
block: block_revision,
delta,
}
}
}
#[cfg(test)]
mod tests {
use crate::client_grid::{GridBlockRevisionDelta, GridBlockRevisionPad};
use crate::client_grid::GridBlockRevisionPad;
use flowy_grid_data_model::revision::{RowMetaChangeset, RowRevision};
use lib_ot::core::TextDelta;
use std::borrow::Cow;
#[test]
@ -369,7 +377,7 @@ mod tests {
#[test]
fn block_meta_delete_row() {
let mut pad = test_pad();
let pre_delta_str = pad.delta_str();
let pre_delta_str = pad.json_str();
let row = RowRevision {
id: "1".to_string(),
block_id: pad.block_id.clone(),
@ -382,7 +390,7 @@ mod tests {
let change = pad.delete_rows(vec![Cow::Borrowed(&row.id)]).unwrap().unwrap();
assert_eq!(change.delta.json_str(), r#"[{"retain":24},{"delete":66},{"retain":2}]"#);
assert_eq!(pad.delta_str(), pre_delta_str);
assert_eq!(pad.json_str(), pre_delta_str);
}
#[test]
@ -412,13 +420,13 @@ mod tests {
);
assert_eq!(
pad.to_json().unwrap(),
pad.revision_json().unwrap(),
r#"{"block_id":"1","rows":[{"id":"1","block_id":"1","cells":[],"height":100,"visibility":true}]}"#
);
}
fn test_pad() -> GridBlockRevisionPad {
let delta = GridBlockRevisionDelta::from_json(r#"[{"insert":"{\"block_id\":\"1\",\"rows\":[]}"}]"#).unwrap();
let delta = TextDelta::from_json(r#"[{"insert":"{\"block_id\":\"1\",\"rows\":[]}"}]"#).unwrap();
GridBlockRevisionPad::from_delta(delta).unwrap()
}
}

View File

@ -7,8 +7,8 @@ use crate::util::{cal_diff, make_delta_from_revisions};
use bytes::Bytes;
use flowy_grid_data_model::revision::{
gen_block_id, gen_grid_filter_id, gen_grid_group_id, gen_grid_id, FieldRevision, FieldTypeRevision,
FilterConfigurationRevision, GridBlockMetaRevision, GridBlockMetaRevisionChangeset, GridLayoutRevision,
GridRevision, GridSettingRevision, GroupConfigurationRevision,
FilterConfigurationRevision, GridBlockMetaRevision, GridBlockMetaRevisionChangeset, GridRevision,
GroupConfigurationRevision, SettingRevision,
};
use lib_infra::util::move_vec_element;
use lib_ot::core::{OperationTransform, PhantomAttributes, TextDelta, TextDeltaBuilder};
@ -77,7 +77,7 @@ impl GridRevisionPad {
&mut self,
new_field_rev: FieldRevision,
start_field_id: Option<String>,
) -> CollaborateResult<Option<GridChangeset>> {
) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(|grid_meta| {
// Check if the field exists or not
if grid_meta
@ -102,7 +102,7 @@ impl GridRevisionPad {
})
}
pub fn delete_field_rev(&mut self, field_id: &str) -> CollaborateResult<Option<GridChangeset>> {
pub fn delete_field_rev(&mut self, field_id: &str) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(
|grid_meta| match grid_meta.fields.iter().position(|field| field.id == field_id) {
None => Ok(None),
@ -118,7 +118,7 @@ impl GridRevisionPad {
&mut self,
field_id: &str,
duplicated_field_id: &str,
) -> CollaborateResult<Option<GridChangeset>> {
) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(
|grid_meta| match grid_meta.fields.iter().position(|field| field.id == field_id) {
None => Ok(None),
@ -138,7 +138,7 @@ impl GridRevisionPad {
field_id: &str,
field_type: T,
type_option_json_builder: B,
) -> CollaborateResult<Option<GridChangeset>>
) -> CollaborateResult<Option<GridRevisionChangeset>>
where
B: FnOnce(&FieldTypeRevision) -> String,
T: Into<FieldTypeRevision>,
@ -169,7 +169,7 @@ impl GridRevisionPad {
&mut self,
changeset: FieldChangesetParams,
deserializer: T,
) -> CollaborateResult<Option<GridChangeset>> {
) -> CollaborateResult<Option<GridRevisionChangeset>> {
let field_id = changeset.field_id.clone();
self.modify_field(&field_id, |field| {
let mut is_changed = None;
@ -228,7 +228,10 @@ impl GridRevisionPad {
.find(|(_, field)| field.id == field_id)
}
pub fn replace_field_rev(&mut self, field_rev: Arc<FieldRevision>) -> CollaborateResult<Option<GridChangeset>> {
pub fn replace_field_rev(
&mut self,
field_rev: Arc<FieldRevision>,
) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(
|grid_meta| match grid_meta.fields.iter().position(|field| field.id == field_rev.id) {
None => Ok(None),
@ -246,7 +249,7 @@ impl GridRevisionPad {
field_id: &str,
from_index: usize,
to_index: usize,
) -> CollaborateResult<Option<GridChangeset>> {
) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(|grid_meta| {
match move_vec_element(
&mut grid_meta.fields,
@ -292,7 +295,10 @@ impl GridRevisionPad {
}
}
pub fn create_block_meta_rev(&mut self, block: GridBlockMetaRevision) -> CollaborateResult<Option<GridChangeset>> {
pub fn create_block_meta_rev(
&mut self,
block: GridBlockMetaRevision,
) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(|grid_meta| {
if grid_meta.blocks.iter().any(|b| b.block_id == block.block_id) {
tracing::warn!("Duplicate grid block");
@ -322,7 +328,7 @@ impl GridRevisionPad {
pub fn update_block_rev(
&mut self,
changeset: GridBlockMetaRevisionChangeset,
) -> CollaborateResult<Option<GridChangeset>> {
) -> CollaborateResult<Option<GridRevisionChangeset>> {
let block_id = changeset.block_id.clone();
self.modify_block(&block_id, |block| {
let mut is_changed = None;
@ -341,18 +347,13 @@ impl GridRevisionPad {
})
}
pub fn get_setting_rev(&self) -> &GridSettingRevision {
pub fn get_setting_rev(&self) -> &SettingRevision {
&self.grid_rev.setting
}
/// If layout is None, then the default layout will be the read from GridSettingRevision
pub fn get_filters(
&self,
layout: Option<&GridLayoutRevision>,
field_ids: Option<Vec<String>>,
) -> Option<Vec<Arc<FilterConfigurationRevision>>> {
pub fn get_filters(&self, field_ids: Option<Vec<String>>) -> Option<Vec<Arc<FilterConfigurationRevision>>> {
let mut filter_revs = vec![];
let layout_ty = layout.unwrap_or(&self.grid_rev.setting.layout);
let field_revs = self.get_field_revs(None).ok()?;
field_revs.iter().for_each(|field_rev| {
@ -365,8 +366,7 @@ impl GridRevisionPad {
// Only return the filters for the current fields' type.
let field_id = &field_rev.id;
let field_type_rev = &field_rev.field_type_rev;
if let Some(mut t_filter_revs) = self.grid_rev.setting.get_filters(layout_ty, field_id, field_type_rev)
{
if let Some(mut t_filter_revs) = self.grid_rev.setting.get_filters(field_id, field_type_rev) {
filter_revs.append(&mut t_filter_revs);
}
}
@ -378,43 +378,33 @@ impl GridRevisionPad {
pub fn update_grid_setting_rev(
&mut self,
changeset: GridSettingChangesetParams,
) -> CollaborateResult<Option<GridChangeset>> {
) -> CollaborateResult<Option<GridRevisionChangeset>> {
self.modify_grid(|grid_rev| {
let mut is_changed = None;
let layout_rev = changeset.layout_type;
if let Some(params) = changeset.insert_filter {
grid_rev.setting.insert_filter(
&layout_rev,
&params.field_id,
&params.field_type_rev,
make_filter_revision(&params),
);
grid_rev
.setting
.insert_filter(&params.field_id, &params.field_type_rev, make_filter_revision(&params));
is_changed = Some(())
}
if let Some(params) = changeset.delete_filter {
if let Some(filters) =
grid_rev
.setting
.get_mut_filters(&layout_rev, &params.field_id, &params.field_type_rev)
if let Some(filters) = grid_rev
.setting
.get_mut_filters(&params.field_id, &params.field_type_rev)
{
filters.retain(|filter| filter.id != params.filter_id);
}
}
if let Some(params) = changeset.insert_group {
grid_rev.setting.insert_group(
&layout_rev,
&params.field_id,
&params.field_type_rev,
make_group_revision(&params),
);
grid_rev
.setting
.insert_group(&params.field_id, &params.field_type_rev, make_group_revision(&params));
is_changed = Some(());
}
if let Some(params) = changeset.delete_group {
if let Some(groups) =
grid_rev
.setting
.get_mut_groups(&layout_rev, &params.field_id, &params.field_type_rev)
if let Some(groups) = grid_rev
.setting
.get_mut_groups(&params.field_id, &params.field_type_rev)
{
groups.retain(|filter| filter.id != params.group_id);
}
@ -462,7 +452,7 @@ impl GridRevisionPad {
&self.grid_rev.fields
}
fn modify_grid<F>(&mut self, f: F) -> CollaborateResult<Option<GridChangeset>>
fn modify_grid<F>(&mut self, f: F) -> CollaborateResult<Option<GridRevisionChangeset>>
where
F: FnOnce(&mut GridRevision) -> CollaborateResult<Option<()>>,
{
@ -476,14 +466,14 @@ impl GridRevisionPad {
None => Ok(None),
Some(delta) => {
self.delta = self.delta.compose(&delta)?;
Ok(Some(GridChangeset { delta, md5: self.md5() }))
Ok(Some(GridRevisionChangeset { delta, md5: self.md5() }))
}
}
}
}
}
fn modify_block<F>(&mut self, block_id: &str, f: F) -> CollaborateResult<Option<GridChangeset>>
fn modify_block<F>(&mut self, block_id: &str, f: F) -> CollaborateResult<Option<GridRevisionChangeset>>
where
F: FnOnce(&mut GridBlockMetaRevision) -> CollaborateResult<Option<()>>,
{
@ -501,7 +491,7 @@ impl GridRevisionPad {
)
}
fn modify_field<F>(&mut self, field_id: &str, f: F) -> CollaborateResult<Option<GridChangeset>>
fn modify_field<F>(&mut self, field_id: &str, f: F) -> CollaborateResult<Option<GridRevisionChangeset>>
where
F: FnOnce(&mut FieldRevision) -> CollaborateResult<Option<()>>,
{
@ -524,13 +514,13 @@ impl GridRevisionPad {
}
}
pub fn make_grid_rev_json_str(grid: &GridRevision) -> CollaborateResult<String> {
let json = serde_json::to_string(grid)
pub fn make_grid_rev_json_str(grid_revision: &GridRevision) -> CollaborateResult<String> {
let json = serde_json::to_string(grid_revision)
.map_err(|err| internal_error(format!("Serialize grid to json str failed. {:?}", err)))?;
Ok(json)
}
pub struct GridChangeset {
pub struct GridRevisionChangeset {
pub delta: GridRevisionDelta,
/// md5: the md5 of the grid after applying the change.
pub md5: String,

View File

@ -1,7 +1,9 @@
mod grid_block_revsion_pad;
mod block_revision_pad;
mod grid_builder;
mod grid_revision_pad;
mod view_revision_pad;
pub use grid_block_revsion_pad::*;
pub use block_revision_pad::*;
pub use grid_builder::*;
pub use grid_revision_pad::*;
pub use view_revision_pad::*;

View File

@ -0,0 +1,173 @@
use crate::entities::revision::{md5, Revision};
use crate::errors::{internal_error, CollaborateError, CollaborateResult};
use crate::util::{cal_diff, make_text_delta_from_revisions};
use flowy_grid_data_model::revision::{
FieldRevision, FieldTypeRevision, FilterConfigurationRevision, FilterConfigurationsByFieldId, GridViewRevision,
GroupConfigurationRevision, GroupConfigurationsByFieldId, SortConfigurationsByFieldId,
};
use lib_ot::core::{OperationTransform, PhantomAttributes, TextDelta, TextDeltaBuilder};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct GridViewRevisionPad {
view: Arc<GridViewRevision>,
delta: TextDelta,
}
impl std::ops::Deref for GridViewRevisionPad {
type Target = GridViewRevision;
fn deref(&self) -> &Self::Target {
&self.view
}
}
impl GridViewRevisionPad {
pub fn new(grid_id: String) -> Self {
let view = Arc::new(GridViewRevision::new(grid_id));
let json = serde_json::to_string(&view).unwrap();
let delta = TextDeltaBuilder::new().insert(&json).build();
Self { view, delta }
}
pub fn from_delta(delta: TextDelta) -> CollaborateResult<Self> {
let s = delta.content()?;
let view: GridViewRevision = serde_json::from_str(&s).map_err(|e| {
let msg = format!("Deserialize delta to GridViewRevision failed: {}", e);
tracing::error!("{}", s);
CollaborateError::internal().context(msg)
})?;
Ok(Self {
view: Arc::new(view),
delta,
})
}
pub fn from_revisions(_grid_id: &str, revisions: Vec<Revision>) -> CollaborateResult<Self> {
let delta: TextDelta = make_text_delta_from_revisions(revisions)?;
Self::from_delta(delta)
}
pub fn get_all_groups(&self, field_revs: &[Arc<FieldRevision>]) -> Option<GroupConfigurationsByFieldId> {
self.setting.groups.get_all_objects(field_revs)
}
pub fn get_groups(
&self,
field_id: &str,
field_type_rev: &FieldTypeRevision,
) -> Option<Vec<Arc<GroupConfigurationRevision>>> {
self.setting.groups.get_objects(field_id, field_type_rev)
}
pub fn insert_group(
&mut self,
field_id: &str,
field_type: &FieldTypeRevision,
group_rev: GroupConfigurationRevision,
) -> CollaborateResult<Option<GridViewRevisionChangeset>> {
self.modify(|view| {
// only one group can be set
view.setting.groups.remove_all();
view.setting.groups.insert_object(field_id, field_type, group_rev);
Ok(Some(()))
})
}
pub fn delete_group(
&mut self,
field_id: &str,
field_type: &FieldTypeRevision,
group_id: &str,
) -> CollaborateResult<Option<GridViewRevisionChangeset>> {
self.modify(|view| {
if let Some(groups) = view.setting.groups.get_mut_objects(field_id, field_type) {
groups.retain(|group| group.id != group_id);
Ok(Some(()))
} else {
Ok(None)
}
})
}
pub fn get_all_filters(&self, field_revs: &[Arc<FieldRevision>]) -> Option<FilterConfigurationsByFieldId> {
self.setting.filters.get_all_objects(field_revs)
}
pub fn get_filters(
&self,
field_id: &str,
field_type_rev: &FieldTypeRevision,
) -> Option<Vec<Arc<FilterConfigurationRevision>>> {
self.setting.filters.get_objects(field_id, field_type_rev)
}
pub fn insert_filter(
&mut self,
field_id: &str,
field_type: &FieldTypeRevision,
filter_rev: FilterConfigurationRevision,
) -> CollaborateResult<Option<GridViewRevisionChangeset>> {
self.modify(|view| {
view.setting.filters.insert_object(field_id, field_type, filter_rev);
Ok(Some(()))
})
}
pub fn delete_filter(
&mut self,
field_id: &str,
field_type: &FieldTypeRevision,
filter_id: &str,
) -> CollaborateResult<Option<GridViewRevisionChangeset>> {
self.modify(|view| {
if let Some(filters) = view.setting.filters.get_mut_objects(field_id, field_type) {
filters.retain(|filter| filter.id != filter_id);
Ok(Some(()))
} else {
Ok(None)
}
})
}
pub fn get_all_sort(&self) -> Option<SortConfigurationsByFieldId> {
None
}
pub fn json_str(&self) -> CollaborateResult<String> {
make_grid_view_rev_json_str(&self.view)
}
fn modify<F>(&mut self, f: F) -> CollaborateResult<Option<GridViewRevisionChangeset>>
where
F: FnOnce(&mut GridViewRevision) -> CollaborateResult<Option<()>>,
{
let cloned_view = self.view.clone();
match f(Arc::make_mut(&mut self.view))? {
None => Ok(None),
Some(_) => {
let old = make_grid_view_rev_json_str(&cloned_view)?;
let new = self.json_str()?;
match cal_diff::<PhantomAttributes>(old, new) {
None => Ok(None),
Some(delta) => {
self.delta = self.delta.compose(&delta)?;
let md5 = md5(&self.delta.json_bytes());
Ok(Some(GridViewRevisionChangeset { delta, md5 }))
}
}
}
}
}
}
pub struct GridViewRevisionChangeset {
pub delta: TextDelta,
pub md5: String,
}
pub fn make_grid_view_rev_json_str(grid_revision: &GridViewRevision) -> CollaborateResult<String> {
let json = serde_json::to_string(grid_revision)
.map_err(|err| internal_error(format!("Serialize grid view to json str failed. {:?}", err)))?;
Ok(json)
}

View File

@ -1,8 +1,8 @@
use flowy_grid_data_model::revision::{FieldTypeRevision, GridLayoutRevision};
use flowy_grid_data_model::revision::{FieldTypeRevision, LayoutRevision};
pub struct GridSettingChangesetParams {
pub grid_id: String,
pub layout_type: GridLayoutRevision,
pub layout_type: LayoutRevision,
pub insert_filter: Option<CreateGridFilterParams>,
pub delete_filter: Option<DeleteFilterParams>,
pub insert_group: Option<CreateGridGroupParams>,

View File

@ -7,7 +7,7 @@ use crate::{
errors::{CollaborateError, CollaborateResult},
};
use dissimilar::Chunk;
use lib_ot::core::{DeltaBuilder, OTString};
use lib_ot::core::{DeltaBuilder, OTString, PhantomAttributes, TextDelta};
use lib_ot::{
core::{Attributes, Delta, OperationTransform, NEW_LINE, WHITESPACE},
rich_text::RichTextDelta,
@ -81,6 +81,10 @@ where
Ok(delta)
}
pub fn make_text_delta_from_revisions(revisions: Vec<Revision>) -> CollaborateResult<TextDelta> {
make_delta_from_revisions::<PhantomAttributes>(revisions)
}
pub fn make_delta_from_revision_pb<T>(revisions: Vec<Revision>) -> CollaborateResult<Delta<T>>
where
T: Attributes + DeserializeOwned,

View File

@ -604,7 +604,7 @@ where
serde_json::to_string(self).unwrap_or_else(|_| "".to_owned())
}
/// Get the content the [Delta] represents.
/// Get the content that the [Delta] represents.
pub fn content(&self) -> Result<String, OTError> {
self.apply("")
}