chore: remove row listener from rowbloc

This commit is contained in:
appflowy 2022-04-17 09:46:38 +08:00
parent e647fd0a57
commit 0a19364ea7
13 changed files with 158 additions and 124 deletions

View file

@ -46,7 +46,6 @@ class GridBloc extends Bloc<GridEvent, GridState> {
await _gridService.closeGrid(); await _gridService.closeGrid();
await fieldCache.dispose(); await fieldCache.dispose();
await rowCache.dispose(); await rowCache.dispose();
fieldCache.dispose();
return super.close(); return super.close();
} }

View file

@ -23,7 +23,7 @@ class GridRowListener {
void _handler(GridNotification ty, Either<Uint8List, FlowyError> result) { void _handler(GridNotification ty, Either<Uint8List, FlowyError> result) {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateGridBlock: case GridNotification.DidUpdateGridRow:
result.fold( result.fold(
(payload) => rowsUpdateNotifier.value = left([GridRowsChangeset.fromBuffer(payload)]), (payload) => rowsUpdateNotifier.value = left([GridRowsChangeset.fromBuffer(payload)]),
(error) => rowsUpdateNotifier.value = right(error), (error) => rowsUpdateNotifier.value = right(error),

View file

@ -1,12 +1,9 @@
import 'dart:collection'; import 'dart:collection';
import 'package:app_flowy/workspace/application/grid/grid_service.dart'; import 'package:app_flowy/workspace/application/grid/grid_service.dart';
import 'package:flowy_sdk/log.dart';
import 'package:flowy_sdk/protobuf/flowy-grid-data-model/grid.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid-data-model/grid.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:async'; import 'dart:async';
import 'row_listener.dart';
import 'row_service.dart'; import 'row_service.dart';
import 'package:dartz/dartz.dart'; import 'package:dartz/dartz.dart';
@ -16,7 +13,7 @@ typedef CellDataMap = LinkedHashMap<String, GridCellIdentifier>;
class RowBloc extends Bloc<RowEvent, RowState> { class RowBloc extends Bloc<RowEvent, RowState> {
final RowService _rowService; final RowService _rowService;
final RowListener _rowlistener;
final GridFieldCache _fieldCache; final GridFieldCache _fieldCache;
final GridRowCache _rowCache; final GridRowCache _rowCache;
@ -25,7 +22,6 @@ class RowBloc extends Bloc<RowEvent, RowState> {
required GridFieldCache fieldCache, required GridFieldCache fieldCache,
required GridRowCache rowCache, required GridRowCache rowCache,
}) : _rowService = RowService(gridId: rowData.gridId, rowId: rowData.rowId), }) : _rowService = RowService(gridId: rowData.gridId, rowId: rowData.rowId),
_rowlistener = RowListener(rowId: rowData.rowId),
_fieldCache = fieldCache, _fieldCache = fieldCache,
_rowCache = rowCache, _rowCache = rowCache,
super(RowState.initial(rowData)) { super(RowState.initial(rowData)) {
@ -76,27 +72,20 @@ class RowBloc extends Bloc<RowEvent, RowState> {
@override @override
Future<void> close() async { Future<void> close() async {
await _rowlistener.stop();
return super.close(); return super.close();
} }
Future<void> _startListening() async { Future<void> _startListening() async {
_rowlistener.updateRowNotifier?.addPublishListener(
(result) {
result.fold(
(row) => add(RowEvent.didUpdateRow(row)),
(err) => Log.error(err),
);
},
listenWhen: () => !isClosed,
);
_fieldCache.addListener( _fieldCache.addListener(
listener: () => add(const RowEvent.fieldsDidUpdate()), listener: () => add(const RowEvent.fieldsDidUpdate()),
listenWhen: () => !isClosed, listenWhen: () => !isClosed,
); );
_rowlistener.start(); _rowCache.addRowListener(
rowId: state.rowData.rowId,
onUpdated: (row) => add(RowEvent.didUpdateRow(row)),
listenWhen: () => !isClosed,
);
} }
Future<void> _loadRow(Emitter<RowState> emit) async { Future<void> _loadRow(Emitter<RowState> emit) async {

View file

@ -1,6 +1,5 @@
import 'dart:collection'; import 'dart:collection';
import 'package:app_flowy/workspace/application/grid/grid_listener.dart';
import 'package:dartz/dartz.dart'; import 'package:dartz/dartz.dart';
import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/dispatch/dispatch.dart';
import 'package:flowy_sdk/log.dart'; import 'package:flowy_sdk/log.dart';
@ -10,6 +9,8 @@ import 'package:flowy_sdk/protobuf/flowy-grid/row_entities.pb.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:app_flowy/workspace/application/grid/grid_listener.dart';
part 'row_service.freezed.dart'; part 'row_service.freezed.dart';
class RowService { class RowService {
@ -86,7 +87,6 @@ class GridRowCache {
late GridRowListener _rowsListener; late GridRowListener _rowsListener;
final RowsNotifier _rowNotifier = RowsNotifier(); final RowsNotifier _rowNotifier = RowsNotifier();
final HashMap<String, Row> _rowDataMap = HashMap(); final HashMap<String, Row> _rowDataMap = HashMap();
UnmodifiableListView<Field> _fields = UnmodifiableListView([]); UnmodifiableListView<Field> _fields = UnmodifiableListView([]);
GridRowCache({required this.gridId}) { GridRowCache({required this.gridId}) {
@ -113,8 +113,11 @@ class GridRowCache {
_rowNotifier.dispose(); _rowNotifier.dispose();
} }
void addListener({void Function(List<GridRow>, GridRowChangeReason)? onChanged, bool Function()? listenWhen}) { void addListener({
_rowNotifier.addListener(() { void Function(List<GridRow>, GridRowChangeReason)? onChanged,
bool Function()? listenWhen,
}) {
listener() {
if (listenWhen != null && listenWhen() == false) { if (listenWhen != null && listenWhen() == false) {
return; return;
} }
@ -122,6 +125,32 @@ class GridRowCache {
if (onChanged != null) { if (onChanged != null) {
onChanged(clonedRows, _rowNotifier._changeReason); onChanged(clonedRows, _rowNotifier._changeReason);
} }
}
_rowNotifier.addListener(listener);
}
void addRowListener({
required String rowId,
void Function(Row)? onUpdated,
bool Function()? listenWhen,
}) {
_rowNotifier.addListener(() {
if (onUpdated == null) {
return;
}
if (listenWhen != null && listenWhen() == false) {
return;
}
_rowNotifier._changeReason.whenOrNull(update: (indexs) {
final updatedIndex = indexs.firstWhereOrNull((updatedIndex) => updatedIndex.rowId == rowId);
final row = _rowDataMap[rowId];
if (updatedIndex != null && row != null) {
onUpdated(row);
}
});
}); });
} }
@ -166,14 +195,14 @@ class GridRowCache {
} }
final List<GridRow> newRows = []; final List<GridRow> newRows = [];
final DeletedIndex deletedIndex = []; final DeletedIndexs deletedIndex = [];
final Map<String, RowOrder> deletedRowMap = {for (var rowOrder in deletedRows) rowOrder.rowId: rowOrder}; final Map<String, RowOrder> deletedRowMap = {for (var rowOrder in deletedRows) rowOrder.rowId: rowOrder};
_rowNotifier.rows.asMap().forEach((index, value) { _rowNotifier.rows.asMap().forEach((index, row) {
if (deletedRowMap[value.rowId] == null) { if (deletedRowMap[row.rowId] == null) {
newRows.add(value); newRows.add(row);
} else { } else {
deletedIndex.add(Tuple2(index, value)); deletedIndex.add(DeletedIndex(index: index, row: row));
} }
}); });
@ -189,7 +218,12 @@ class GridRowCache {
final List<GridRow> newRows = _rowNotifier.rows; final List<GridRow> newRows = _rowNotifier.rows;
for (final createdRow in createdRows) { for (final createdRow in createdRows) {
final gridRow = GridRow.fromBlockRow(gridId, createdRow.rowOrder, _fields); final gridRow = GridRow.fromBlockRow(gridId, createdRow.rowOrder, _fields);
insertIndexs.add(Tuple2(createdRow.index, gridRow.rowId)); insertIndexs.add(
InsertedIndex(
index: createdRow.index,
rowId: gridRow.rowId,
),
);
newRows.insert(createdRow.index, gridRow); newRows.insert(createdRow.index, gridRow);
} }
_rowNotifier.updateRows(newRows, GridRowChangeReason.insert(insertIndexs)); _rowNotifier.updateRows(newRows, GridRowChangeReason.insert(insertIndexs));
@ -200,14 +234,15 @@ class GridRowCache {
return; return;
} }
final List<int> updatedIndexs = []; final UpdatedIndexs updatedIndexs = [];
final List<GridRow> newRows = _rowNotifier.rows; final List<GridRow> newRows = _rowNotifier.rows;
for (final rowOrder in updatedRows) { for (final rowOrder in updatedRows) {
final index = newRows.indexWhere((row) => row.rowId == rowOrder.rowId); final index = newRows.indexWhere((row) => row.rowId == rowOrder.rowId);
if (index != -1) { if (index != -1) {
newRows.removeAt(index); newRows.removeAt(index);
newRows.insert(index, GridRow.fromBlockRow(gridId, rowOrder, _fields)); newRows.insert(index, GridRow.fromBlockRow(gridId, rowOrder, _fields));
updatedIndexs.add(index); _rowDataMap.remove(rowOrder.rowId);
updatedIndexs.add(UpdatedIndex(index: index, rowId: rowOrder.rowId));
} }
} }
@ -246,13 +281,41 @@ class GridRow with _$GridRow {
} }
} }
typedef InsertedIndexs = List<Tuple2<int, String>>; typedef InsertedIndexs = List<InsertedIndex>;
typedef DeletedIndex = List<Tuple2<int, GridRow>>; typedef DeletedIndexs = List<DeletedIndex>;
typedef UpdatedIndexs = List<UpdatedIndex>;
class InsertedIndex {
int index;
String rowId;
InsertedIndex({
required this.index,
required this.rowId,
});
}
class DeletedIndex {
int index;
GridRow row;
DeletedIndex({
required this.index,
required this.row,
});
}
class UpdatedIndex {
int index;
String rowId;
UpdatedIndex({
required this.index,
required this.rowId,
});
}
@freezed @freezed
class GridRowChangeReason with _$GridRowChangeReason { class GridRowChangeReason with _$GridRowChangeReason {
const factory GridRowChangeReason.insert(InsertedIndexs items) = _Insert; const factory GridRowChangeReason.insert(InsertedIndexs items) = _Insert;
const factory GridRowChangeReason.delete(DeletedIndex items) = _Delete; const factory GridRowChangeReason.delete(DeletedIndexs items) = _Delete;
const factory GridRowChangeReason.update(List<int> indexs) = _Update; const factory GridRowChangeReason.update(UpdatedIndexs indexs) = _Update;
const factory GridRowChangeReason.initial() = InitialListState; const factory GridRowChangeReason.initial() = InitialListState;
} }

View file

@ -191,22 +191,20 @@ class _GridRowsState extends State<_GridRows> {
return BlocConsumer<GridBloc, GridState>( return BlocConsumer<GridBloc, GridState>(
listenWhen: (previous, current) => previous.listState != current.listState, listenWhen: (previous, current) => previous.listState != current.listState,
listener: (context, state) { listener: (context, state) {
state.listState.map( state.listState.mapOrNull(
insert: (value) { insert: (value) {
for (final item in value.items) { for (final item in value.items) {
_key.currentState?.insertItem(item.value1); _key.currentState?.insertItem(item.index);
} }
}, },
delete: (value) { delete: (value) {
for (final item in value.items) { for (final item in value.items) {
_key.currentState?.removeItem( _key.currentState?.removeItem(
item.value1, item.index,
(context, animation) => _renderRow(context, item.value2, animation), (context, animation) => _renderRow(context, item.row, animation),
); );
} }
}, },
initial: (_) {},
update: (_) {},
); );
}, },
buildWhen: (previous, current) => false, buildWhen: (previous, current) => false,

View file

@ -12,19 +12,19 @@ import 'package:protobuf/protobuf.dart' as $pb;
class GridNotification extends $pb.ProtobufEnum { class GridNotification extends $pb.ProtobufEnum {
static const GridNotification Unknown = GridNotification._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'Unknown'); static const GridNotification Unknown = GridNotification._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'Unknown');
static const GridNotification DidCreateBlock = GridNotification._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidCreateBlock'); static const GridNotification DidCreateBlock = GridNotification._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidCreateBlock');
static const GridNotification DidUpdateGridBlock = GridNotification._(20, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateGridBlock'); static const GridNotification DidUpdateGridRow = GridNotification._(20, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateGridRow');
static const GridNotification DidUpdateGridField = GridNotification._(21, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateGridField');
static const GridNotification DidUpdateRow = GridNotification._(30, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateRow'); static const GridNotification DidUpdateRow = GridNotification._(30, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateRow');
static const GridNotification DidUpdateCell = GridNotification._(31, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateCell'); static const GridNotification DidUpdateCell = GridNotification._(40, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateCell');
static const GridNotification DidUpdateGridField = GridNotification._(40, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateGridField'); static const GridNotification DidUpdateField = GridNotification._(50, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateField');
static const GridNotification DidUpdateField = GridNotification._(41, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DidUpdateField');
static const $core.List<GridNotification> values = <GridNotification> [ static const $core.List<GridNotification> values = <GridNotification> [
Unknown, Unknown,
DidCreateBlock, DidCreateBlock,
DidUpdateGridBlock, DidUpdateGridRow,
DidUpdateGridField,
DidUpdateRow, DidUpdateRow,
DidUpdateCell, DidUpdateCell,
DidUpdateGridField,
DidUpdateField, DidUpdateField,
]; ];

View file

@ -14,13 +14,13 @@ const GridNotification$json = const {
'2': const [ '2': const [
const {'1': 'Unknown', '2': 0}, const {'1': 'Unknown', '2': 0},
const {'1': 'DidCreateBlock', '2': 11}, const {'1': 'DidCreateBlock', '2': 11},
const {'1': 'DidUpdateGridBlock', '2': 20}, const {'1': 'DidUpdateGridRow', '2': 20},
const {'1': 'DidUpdateGridField', '2': 21},
const {'1': 'DidUpdateRow', '2': 30}, const {'1': 'DidUpdateRow', '2': 30},
const {'1': 'DidUpdateCell', '2': 31}, const {'1': 'DidUpdateCell', '2': 40},
const {'1': 'DidUpdateGridField', '2': 40}, const {'1': 'DidUpdateField', '2': 50},
const {'1': 'DidUpdateField', '2': 41},
], ],
}; };
/// Descriptor for `GridNotification`. Decode as a `google.protobuf.EnumDescriptorProto`. /// Descriptor for `GridNotification`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List gridNotificationDescriptor = $convert.base64Decode('ChBHcmlkTm90aWZpY2F0aW9uEgsKB1Vua25vd24QABISCg5EaWRDcmVhdGVCbG9jaxALEhYKEkRpZFVwZGF0ZUdyaWRCbG9jaxAUEhAKDERpZFVwZGF0ZVJvdxAeEhEKDURpZFVwZGF0ZUNlbGwQHxIWChJEaWRVcGRhdGVHcmlkRmllbGQQKBISCg5EaWRVcGRhdGVGaWVsZBAp'); final $typed_data.Uint8List gridNotificationDescriptor = $convert.base64Decode('ChBHcmlkTm90aWZpY2F0aW9uEgsKB1Vua25vd24QABISCg5EaWRDcmVhdGVCbG9jaxALEhQKEERpZFVwZGF0ZUdyaWRSb3cQFBIWChJEaWRVcGRhdGVHcmlkRmllbGQQFRIQCgxEaWRVcGRhdGVSb3cQHhIRCg1EaWRVcGRhdGVDZWxsECgSEgoORGlkVXBkYXRlRmllbGQQMg==');

View file

@ -6,11 +6,11 @@ const OBSERVABLE_CATEGORY: &str = "Grid";
pub enum GridNotification { pub enum GridNotification {
Unknown = 0, Unknown = 0,
DidCreateBlock = 11, DidCreateBlock = 11,
DidUpdateGridBlock = 20, DidUpdateGridRow = 20,
DidUpdateGridField = 21,
DidUpdateRow = 30, DidUpdateRow = 30,
DidUpdateCell = 31, DidUpdateCell = 40,
DidUpdateGridField = 40, DidUpdateField = 50,
DidUpdateField = 41,
} }
impl std::default::Default for GridNotification { impl std::default::Default for GridNotification {

View file

@ -27,11 +27,11 @@
pub enum GridNotification { pub enum GridNotification {
Unknown = 0, Unknown = 0,
DidCreateBlock = 11, DidCreateBlock = 11,
DidUpdateGridBlock = 20, DidUpdateGridRow = 20,
DidUpdateGridField = 21,
DidUpdateRow = 30, DidUpdateRow = 30,
DidUpdateCell = 31, DidUpdateCell = 40,
DidUpdateGridField = 40, DidUpdateField = 50,
DidUpdateField = 41,
} }
impl ::protobuf::ProtobufEnum for GridNotification { impl ::protobuf::ProtobufEnum for GridNotification {
@ -43,11 +43,11 @@ impl ::protobuf::ProtobufEnum for GridNotification {
match value { match value {
0 => ::std::option::Option::Some(GridNotification::Unknown), 0 => ::std::option::Option::Some(GridNotification::Unknown),
11 => ::std::option::Option::Some(GridNotification::DidCreateBlock), 11 => ::std::option::Option::Some(GridNotification::DidCreateBlock),
20 => ::std::option::Option::Some(GridNotification::DidUpdateGridBlock), 20 => ::std::option::Option::Some(GridNotification::DidUpdateGridRow),
21 => ::std::option::Option::Some(GridNotification::DidUpdateGridField),
30 => ::std::option::Option::Some(GridNotification::DidUpdateRow), 30 => ::std::option::Option::Some(GridNotification::DidUpdateRow),
31 => ::std::option::Option::Some(GridNotification::DidUpdateCell), 40 => ::std::option::Option::Some(GridNotification::DidUpdateCell),
40 => ::std::option::Option::Some(GridNotification::DidUpdateGridField), 50 => ::std::option::Option::Some(GridNotification::DidUpdateField),
41 => ::std::option::Option::Some(GridNotification::DidUpdateField),
_ => ::std::option::Option::None _ => ::std::option::Option::None
} }
} }
@ -56,10 +56,10 @@ impl ::protobuf::ProtobufEnum for GridNotification {
static values: &'static [GridNotification] = &[ static values: &'static [GridNotification] = &[
GridNotification::Unknown, GridNotification::Unknown,
GridNotification::DidCreateBlock, GridNotification::DidCreateBlock,
GridNotification::DidUpdateGridBlock, GridNotification::DidUpdateGridRow,
GridNotification::DidUpdateGridField,
GridNotification::DidUpdateRow, GridNotification::DidUpdateRow,
GridNotification::DidUpdateCell, GridNotification::DidUpdateCell,
GridNotification::DidUpdateGridField,
GridNotification::DidUpdateField, GridNotification::DidUpdateField,
]; ];
values values
@ -89,11 +89,11 @@ impl ::protobuf::reflect::ProtobufValue for GridNotification {
} }
static file_descriptor_proto_data: &'static [u8] = b"\ static file_descriptor_proto_data: &'static [u8] = b"\
\n\x17dart_notification.proto*\x9c\x01\n\x10GridNotification\x12\x0b\n\ \n\x17dart_notification.proto*\x9a\x01\n\x10GridNotification\x12\x0b\n\
\x07Unknown\x10\0\x12\x12\n\x0eDidCreateBlock\x10\x0b\x12\x16\n\x12DidUp\ \x07Unknown\x10\0\x12\x12\n\x0eDidCreateBlock\x10\x0b\x12\x14\n\x10DidUp\
dateGridBlock\x10\x14\x12\x10\n\x0cDidUpdateRow\x10\x1e\x12\x11\n\rDidUp\ dateGridRow\x10\x14\x12\x16\n\x12DidUpdateGridField\x10\x15\x12\x10\n\
dateCell\x10\x1f\x12\x16\n\x12DidUpdateGridField\x10(\x12\x12\n\x0eDidUp\ \x0cDidUpdateRow\x10\x1e\x12\x11\n\rDidUpdateCell\x10(\x12\x12\n\x0eDidU\
dateField\x10)b\x06proto3\ pdateField\x102b\x06proto3\
"; ";
static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT;

View file

@ -3,9 +3,9 @@ syntax = "proto3";
enum GridNotification { enum GridNotification {
Unknown = 0; Unknown = 0;
DidCreateBlock = 11; DidCreateBlock = 11;
DidUpdateGridBlock = 20; DidUpdateGridRow = 20;
DidUpdateGridField = 21;
DidUpdateRow = 30; DidUpdateRow = 30;
DidUpdateCell = 31; DidUpdateCell = 40;
DidUpdateGridField = 40; DidUpdateField = 50;
DidUpdateField = 41;
} }

View file

@ -2,13 +2,13 @@ use crate::dart_notification::{send_dart_notification, GridNotification};
use crate::manager::GridUser; use crate::manager::GridUser;
use crate::services::block_meta_editor::ClientGridBlockMetaEditor; use crate::services::block_meta_editor::ClientGridBlockMetaEditor;
use crate::services::persistence::block_index::BlockIndexPersistence; use crate::services::persistence::block_index::BlockIndexPersistence;
use crate::services::row::{group_row_orders, make_rows_from_row_metas, GridBlockSnapshot}; use crate::services::row::{group_row_orders, GridBlockSnapshot};
use std::borrow::Cow; use std::borrow::Cow;
use dashmap::DashMap; use dashmap::DashMap;
use flowy_error::FlowyResult; use flowy_error::FlowyResult;
use flowy_grid_data_model::entities::{ use flowy_grid_data_model::entities::{
CellChangeset, CellMeta, CellNotificationData, FieldMeta, GridBlockMeta, GridBlockMetaChangeset, GridRowsChangeset, CellChangeset, CellMeta, CellNotificationData, GridBlockMeta, GridBlockMetaChangeset, GridRowsChangeset,
IndexRowOrder, RowMeta, RowMetaChangeset, RowOrder, IndexRowOrder, RowMeta, RowMetaChangeset, RowOrder,
}; };
use flowy_revision::disk::SQLiteGridBlockMetaRevisionPersistence; use flowy_revision::disk::SQLiteGridBlockMetaRevisionPersistence;
@ -76,7 +76,7 @@ impl GridBlockMetaEditorManager {
index_row_order.index = row_index; index_row_order.index = row_index;
let _ = self let _ = self
.notify_did_update_rows(GridRowsChangeset::insert(block_id, vec![index_row_order])) .notify_did_update_block(GridRowsChangeset::insert(block_id, vec![index_row_order]))
.await?; .await?;
Ok(row_count) Ok(row_count)
} }
@ -98,7 +98,7 @@ impl GridBlockMetaEditorManager {
changesets.push(GridBlockMetaChangeset::from_row_count(&block_id, row_count)); changesets.push(GridBlockMetaChangeset::from_row_count(&block_id, row_count));
let _ = self let _ = self
.notify_did_update_rows(GridRowsChangeset::insert(&block_id, inserted_row_orders)) .notify_did_update_block(GridRowsChangeset::insert(&block_id, inserted_row_orders))
.await?; .await?;
} }
@ -108,19 +108,7 @@ impl GridBlockMetaEditorManager {
pub async fn update_row(&self, changeset: RowMetaChangeset) -> FlowyResult<()> { pub async fn update_row(&self, changeset: RowMetaChangeset) -> FlowyResult<()> {
let editor = self.get_editor_from_row_id(&changeset.row_id).await?; let editor = self.get_editor_from_row_id(&changeset.row_id).await?;
let _ = editor.update_row(changeset.clone()).await?; let _ = editor.update_row(changeset.clone()).await?;
let _ = self.notify_did_update_block_row(&changeset.row_id).await?;
match editor
.get_row_orders(Some(vec![Cow::Borrowed(&changeset.row_id)]))
.await?
.pop()
{
None => {}
Some(row_order) => {
let block_order_changeset = GridRowsChangeset::update(&editor.block_id, vec![row_order]);
let _ = self.notify_did_update_rows(block_order_changeset).await?;
}
}
Ok(()) Ok(())
} }
@ -131,7 +119,7 @@ impl GridBlockMetaEditorManager {
let row_orders = editor.get_row_orders(Some(vec![Cow::Borrowed(&row_id)])).await?; let row_orders = editor.get_row_orders(Some(vec![Cow::Borrowed(&row_id)])).await?;
let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?; let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?;
let _ = self let _ = self
.notify_did_update_rows(GridRowsChangeset::delete(&block_id, row_orders)) .notify_did_update_block(GridRowsChangeset::delete(&block_id, row_orders))
.await?; .await?;
Ok(()) Ok(())
@ -173,7 +161,7 @@ impl GridBlockMetaEditorManager {
updated_rows: vec![], updated_rows: vec![],
}; };
let _ = self.notify_did_update_rows(notified_changeset).await?; let _ = self.notify_did_update_block(notified_changeset).await?;
} }
} }
@ -181,10 +169,8 @@ impl GridBlockMetaEditorManager {
} }
pub async fn update_cell(&self, changeset: CellChangeset) -> FlowyResult<()> { pub async fn update_cell(&self, changeset: CellChangeset) -> FlowyResult<()> {
let row_id = changeset.row_id.clone();
let editor = self.get_editor_from_row_id(&row_id).await?;
let row_changeset: RowMetaChangeset = changeset.clone().into(); let row_changeset: RowMetaChangeset = changeset.clone().into();
let _ = editor.update_row(row_changeset).await?; let _ = self.update_row(row_changeset).await?;
let cell_notification_data = CellNotificationData { let cell_notification_data = CellNotificationData {
grid_id: changeset.grid_id, grid_id: changeset.grid_id,
@ -193,6 +179,7 @@ impl GridBlockMetaEditorManager {
content: changeset.data, content: changeset.data,
}; };
self.notify_did_update_cell(cell_notification_data).await?; self.notify_did_update_cell(cell_notification_data).await?;
Ok(()) Ok(())
} }
@ -239,8 +226,22 @@ impl GridBlockMetaEditorManager {
Ok(block_cell_metas) Ok(block_cell_metas)
} }
async fn notify_did_update_rows(&self, changeset: GridRowsChangeset) -> FlowyResult<()> { async fn notify_did_update_block_row(&self, row_id: &str) -> FlowyResult<()> {
send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridBlock) let editor = self.get_editor_from_row_id(row_id).await?;
let row_ids = Some(vec![Cow::Borrowed(&row_id)]);
match editor.get_row_orders(row_ids).await?.pop() {
None => {}
Some(row_order) => {
let block_order_changeset = GridRowsChangeset::update(&editor.block_id, vec![row_order]);
let _ = self.notify_did_update_block(block_order_changeset).await?;
}
}
Ok(())
}
async fn notify_did_update_block(&self, changeset: GridRowsChangeset) -> FlowyResult<()> {
send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridRow)
.payload(changeset) .payload(changeset)
.send(); .send();
Ok(()) Ok(())
@ -253,22 +254,6 @@ impl GridBlockMetaEditorManager {
.send(); .send();
Ok(()) Ok(())
} }
#[allow(dead_code)]
async fn notify_did_update_row(&self, row_id: &str, field_metas: &[FieldMeta]) -> FlowyResult<()> {
match self.get_row_meta(row_id).await? {
None => {}
Some(row_meta) => {
let row_metas = vec![row_meta];
if let Some(row) = make_rows_from_row_metas(field_metas, &row_metas).pop() {
send_dart_notification(row_id, GridNotification::DidUpdateRow)
.payload(row)
.send();
}
}
}
Ok(())
}
} }
async fn make_block_meta_editor_map( async fn make_block_meta_editor_map(

View file

@ -77,7 +77,7 @@ impl ClientGridEditor {
Ok(grid.update_field_meta(changeset, deserializer)?) Ok(grid.update_field_meta(changeset, deserializer)?)
}) })
.await?; .await?;
let _ = self.notify_grid_did_update_field(&field_id).await?; let _ = self.notify_did_update_grid_field(&field_id).await?;
} else { } else {
let _ = self let _ = self
.modify(|grid| { .modify(|grid| {
@ -87,7 +87,7 @@ impl ClientGridEditor {
Ok(grid.create_field_meta(field_meta, start_field_id)?) Ok(grid.create_field_meta(field_meta, start_field_id)?)
}) })
.await?; .await?;
let _ = self.notify_grid_did_insert_field(&field_id).await?; let _ = self.notify_did_insert_grid_field(&field_id).await?;
} }
Ok(()) Ok(())
@ -114,14 +114,14 @@ impl ClientGridEditor {
.modify(|grid| Ok(grid.update_field_meta(params, json_deserializer)?)) .modify(|grid| Ok(grid.update_field_meta(params, json_deserializer)?))
.await?; .await?;
let _ = self.notify_grid_did_update_field(&field_id).await?; let _ = self.notify_did_update_grid_field(&field_id).await?;
Ok(()) Ok(())
} }
pub async fn replace_field(&self, field_meta: FieldMeta) -> FlowyResult<()> { pub async fn replace_field(&self, field_meta: FieldMeta) -> FlowyResult<()> {
let field_id = field_meta.id.clone(); let field_id = field_meta.id.clone();
let _ = self.modify(|pad| Ok(pad.replace_field_meta(field_meta)?)).await?; let _ = self.modify(|pad| Ok(pad.replace_field_meta(field_meta)?)).await?;
let _ = self.notify_grid_did_update_field(&field_id).await?; let _ = self.notify_did_update_grid_field(&field_id).await?;
Ok(()) Ok(())
} }
@ -153,7 +153,7 @@ impl ClientGridEditor {
.modify(|grid| Ok(grid.switch_to_field(field_id, field_type.clone(), type_option_json_builder)?)) .modify(|grid| Ok(grid.switch_to_field(field_id, field_type.clone(), type_option_json_builder)?))
.await?; .await?;
let _ = self.notify_grid_did_update_field(field_id).await?; let _ = self.notify_did_update_grid_field(field_id).await?;
Ok(()) Ok(())
} }
@ -164,7 +164,7 @@ impl ClientGridEditor {
.modify(|grid| Ok(grid.duplicate_field_meta(field_id, &duplicated_field_id)?)) .modify(|grid| Ok(grid.duplicate_field_meta(field_id, &duplicated_field_id)?))
.await?; .await?;
let _ = self.notify_grid_did_insert_field(field_id).await?; let _ = self.notify_did_insert_grid_field(field_id).await?;
Ok(()) Ok(())
} }
@ -462,7 +462,7 @@ impl ClientGridEditor {
} }
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
async fn notify_grid_did_insert_field(&self, field_id: &str) -> FlowyResult<()> { async fn notify_did_insert_grid_field(&self, field_id: &str) -> FlowyResult<()> {
if let Some((index, field_meta)) = self.pad.read().await.get_field_meta(field_id) { if let Some((index, field_meta)) = self.pad.read().await.get_field_meta(field_id) {
let index_field = IndexField::from_field_meta(field_meta, index); let index_field = IndexField::from_field_meta(field_meta, index);
let notified_changeset = GridFieldChangeset::insert(&self.grid_id, vec![index_field]); let notified_changeset = GridFieldChangeset::insert(&self.grid_id, vec![index_field]);
@ -472,7 +472,7 @@ impl ClientGridEditor {
} }
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
async fn notify_grid_did_update_field(&self, field_id: &str) -> FlowyResult<()> { async fn notify_did_update_grid_field(&self, field_id: &str) -> FlowyResult<()> {
let mut field_metas = self.get_field_metas(Some(vec![field_id])).await?; let mut field_metas = self.get_field_metas(Some(vec![field_id])).await?;
debug_assert!(field_metas.len() == 1); debug_assert!(field_metas.len() == 1);

View file

@ -208,7 +208,7 @@ impl GridMetaPad {
pub fn move_field( pub fn move_field(
&mut self, &mut self,
field_id: &str, field_id: &str,
from_index: usize, _from_index: usize,
to_index: usize, to_index: usize,
) -> CollaborateResult<Option<GridChangeset>> { ) -> CollaborateResult<Option<GridChangeset>> {
self.modify_grid( self.modify_grid(