refactor: prefer namespace isolation, remove Grid keyword in some structs

This commit is contained in:
appflowy 2022-08-11 13:25:55 +08:00
parent aae2d96a4f
commit 08b9930510
57 changed files with 493 additions and 352 deletions

View File

@ -56,7 +56,7 @@ class BoardBloc extends Bloc<BoardEvent, BoardState> {
didReceiveGridUpdate: (GridPB grid) { didReceiveGridUpdate: (GridPB grid) {
emit(state.copyWith(grid: Some(grid))); emit(state.copyWith(grid: Some(grid)));
}, },
groupByField: (GridFieldPB field) { groupByField: (FieldPB field) {
emit(state.copyWith(groupField: Some(field))); emit(state.copyWith(groupField: Some(field)));
}, },
); );
@ -95,12 +95,12 @@ class BoardBloc extends Bloc<BoardEvent, BoardState> {
); );
} }
void _buildColumnItems(List<GridRowInfo> rowInfos) { void _buildColumnItems(List<RowInfo> rowInfos) {
for (final rowInfo in rowInfos) {} for (final rowInfo in rowInfos) {}
} }
void _buildColumns(UnmodifiableListView<GridFieldPB> fields) { void _buildColumns(UnmodifiableListView<FieldPB> fields) {
GridFieldPB? groupField; FieldPB? groupField;
for (final field in fields) { for (final field in fields) {
if (field.fieldType == FieldType.SingleSelect) { if (field.fieldType == FieldType.SingleSelect) {
groupField = field; groupField = field;
@ -112,7 +112,7 @@ class BoardBloc extends Bloc<BoardEvent, BoardState> {
add(BoardEvent.groupByField(groupField!)); add(BoardEvent.groupByField(groupField!));
} }
void _buildColumnsFromSingleSelect(GridFieldPB field) { void _buildColumnsFromSingleSelect(FieldPB field) {
final typeOptionContext = makeTypeOptionContext<SingleSelectTypeOptionPB>( final typeOptionContext = makeTypeOptionContext<SingleSelectTypeOptionPB>(
gridId: _gridDataController.gridId, gridId: _gridDataController.gridId,
field: field, field: field,
@ -151,7 +151,7 @@ class BoardBloc extends Bloc<BoardEvent, BoardState> {
class BoardEvent with _$BoardEvent { class BoardEvent with _$BoardEvent {
const factory BoardEvent.initial() = InitialGrid; const factory BoardEvent.initial() = InitialGrid;
const factory BoardEvent.createRow() = _CreateRow; const factory BoardEvent.createRow() = _CreateRow;
const factory BoardEvent.groupByField(GridFieldPB field) = _GroupByField; const factory BoardEvent.groupByField(FieldPB field) = _GroupByField;
const factory BoardEvent.didReceiveGridUpdate( const factory BoardEvent.didReceiveGridUpdate(
GridPB grid, GridPB grid,
) = _DidReceiveGridUpdate; ) = _DidReceiveGridUpdate;
@ -162,8 +162,8 @@ class BoardState with _$BoardState {
const factory BoardState({ const factory BoardState({
required String gridId, required String gridId,
required Option<GridPB> grid, required Option<GridPB> grid,
required Option<GridFieldPB> groupField, required Option<FieldPB> groupField,
required List<GridRowInfo> rowInfos, required List<RowInfo> rowInfos,
required GridLoadingState loadingState, required GridLoadingState loadingState,
}) = _BoardState; }) = _BoardState;
@ -184,9 +184,9 @@ class GridLoadingState with _$GridLoadingState {
} }
class GridFieldEquatable extends Equatable { class GridFieldEquatable extends Equatable {
final UnmodifiableListView<GridFieldPB> _fields; final UnmodifiableListView<FieldPB> _fields;
const GridFieldEquatable( const GridFieldEquatable(
UnmodifiableListView<GridFieldPB> fields, UnmodifiableListView<FieldPB> fields,
) : _fields = fields; ) : _fields = fields;
@override @override
@ -203,7 +203,7 @@ class GridFieldEquatable extends Equatable {
]; ];
} }
UnmodifiableListView<GridFieldPB> get value => UnmodifiableListView(_fields); UnmodifiableListView<FieldPB> get value => UnmodifiableListView(_fields);
} }
class TextItem extends ColumnItem { class TextItem extends ColumnItem {

View File

@ -0,0 +1,126 @@
// import 'dart:collection';
// import 'package:flowy_sdk/log.dart';
// import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart';
// import 'package:flowy_sdk/protobuf/flowy-folder/view.pb.dart';
// import 'package:flowy_sdk/protobuf/flowy-grid/block_entities.pb.dart';
// import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
// import 'package:flowy_sdk/protobuf/flowy-grid/grid_entities.pb.dart';
// import 'dart:async';
// import 'package:dartz/dartz.dart';
// typedef OnFieldsChanged = void Function(UnmodifiableListView<FieldPB>);
// typedef OnGridChanged = void Function(GridPB);
// typedef OnRowsChanged = void Function(
// List<GridRowInfo> rowInfos,
// GridRowChangeReason,
// );
// typedef ListenONRowChangedCondition = bool Function();
// class GridDataController {
// final String gridId;
// final GridService _gridFFIService;
// final GridFieldCache fieldCache;
// // key: the block id
// final LinkedHashMap<String, GridBlockCache> _blocks;
// UnmodifiableMapView<String, GridBlockCache> get blocks =>
// UnmodifiableMapView(_blocks);
// OnRowsChanged? _onRowChanged;
// OnFieldsChanged? _onFieldsChanged;
// OnGridChanged? _onGridChanged;
// List<GridRowInfo> get rowInfos {
// final List<GridRowInfo> rows = [];
// for (var block in _blocks.values) {
// rows.addAll(block.rows);
// }
// return rows;
// }
// GridDataController({required ViewPB view})
// : gridId = view.id,
// _blocks = LinkedHashMap.identity(),
// _gridFFIService = GridService(gridId: view.id),
// fieldCache = GridFieldCache(gridId: view.id);
// void addListener({
// required OnGridChanged onGridChanged,
// required OnRowsChanged onRowsChanged,
// required OnFieldsChanged onFieldsChanged,
// }) {
// _onGridChanged = onGridChanged;
// _onRowChanged = onRowsChanged;
// _onFieldsChanged = onFieldsChanged;
// fieldCache.addListener(onFields: (fields) {
// _onFieldsChanged?.call(UnmodifiableListView(fields));
// });
// }
// Future<Either<Unit, FlowyError>> loadData() async {
// final result = await _gridFFIService.loadGrid();
// return Future(
// () => result.fold(
// (grid) async {
// _initialBlocks(grid.blocks);
// _onGridChanged?.call(grid);
// return await _loadFields(grid);
// },
// (err) => right(err),
// ),
// );
// }
// void createRow() {
// _gridFFIService.createRow();
// }
// Future<void> dispose() async {
// await _gridFFIService.closeGrid();
// await fieldCache.dispose();
// for (final blockCache in _blocks.values) {
// blockCache.dispose();
// }
// }
// void _initialBlocks(List<BlockPB> blocks) {
// for (final block in blocks) {
// if (_blocks[block.id] != null) {
// Log.warn("Initial duplicate block's cache: ${block.id}");
// return;
// }
// final cache = GridBlockCache(
// gridId: gridId,
// block: block,
// fieldCache: fieldCache,
// );
// cache.addListener(
// onChangeReason: (reason) {
// _onRowChanged?.call(rowInfos, reason);
// },
// );
// _blocks[block.id] = cache;
// }
// }
// Future<Either<Unit, FlowyError>> _loadFields(GridPB grid) async {
// final result = await _gridFFIService.getFields(fieldIds: grid.fields);
// return Future(
// () => result.fold(
// (fields) {
// fieldCache.fields = fields.items;
// _onFieldsChanged?.call(UnmodifiableListView(fieldCache.fields));
// return left(unit);
// },
// (err) => right(err),
// ),
// );
// }
// }

View File

@ -2,11 +2,11 @@ import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
class BoardGroupService { class BoardGroupService {
final String gridId; final String gridId;
GridFieldPB? groupField; FieldPB? groupField;
BoardGroupService(this.gridId); BoardGroupService(this.gridId);
void setGroupField(GridFieldPB field) { void setGroupField(FieldPB field) {
groupField = field; groupField = field;
} }
} }

View File

@ -88,7 +88,7 @@ class BoardContent extends StatelessWidget {
} }
Widget _buildCard(BuildContext context, ColumnItem item) { Widget _buildCard(BuildContext context, ColumnItem item) {
final rowInfo = item as GridRowInfo; final rowInfo = item as RowInfo;
return AppFlowyColumnItemCard( return AppFlowyColumnItemCard(
key: ObjectKey(item), key: ObjectKey(item),
child: BoardCard(rowInfo: rowInfo), child: BoardCard(rowInfo: rowInfo),

View File

@ -2,7 +2,7 @@ import 'package:app_flowy/plugins/grid/application/row/row_cache.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class BoardCard extends StatelessWidget { class BoardCard extends StatelessWidget {
final GridRowInfo rowInfo; final RowInfo rowInfo;
const BoardCard({required this.rowInfo, Key? key}) : super(key: key); const BoardCard({required this.rowInfo, Key? key}) : super(key: key);

View File

@ -9,11 +9,11 @@ import 'block_listener.dart';
/// Read https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/frontend/grid for more information /// Read https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/frontend/grid for more information
class GridBlockCache { class GridBlockCache {
final String gridId; final String gridId;
final GridBlockPB block; final BlockPB block;
late GridRowCache _rowCache; late GridRowCache _rowCache;
late GridBlockListener _listener; late GridBlockListener _listener;
List<GridRowInfo> get rows => _rowCache.rows; List<RowInfo> get rows => _rowCache.rows;
GridRowCache get rowCache => _rowCache; GridRowCache get rowCache => _rowCache;
GridBlockCache({ GridBlockCache({
@ -42,7 +42,7 @@ class GridBlockCache {
} }
void addListener({ void addListener({
required void Function(GridRowChangeReason) onChangeReason, required void Function(RowChangeReason) onChangeReason,
bool Function()? listenWhen, bool Function()? listenWhen,
}) { }) {
_rowCache.onRowsChanged((reason) { _rowCache.onRowsChanged((reason) {

View File

@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart';
import 'cell_service.dart'; import 'cell_service.dart';
abstract class IGridCellFieldNotifier { abstract class IGridCellFieldNotifier {
void onCellFieldChanged(void Function(GridFieldPB) callback); void onCellFieldChanged(void Function(FieldPB) callback);
void onCellDispose(); void onCellDispose();
} }

View File

@ -60,7 +60,7 @@ class GridCellIdentifier with _$GridCellIdentifier {
const factory GridCellIdentifier({ const factory GridCellIdentifier({
required String gridId, required String gridId,
required String rowId, required String rowId,
required GridFieldPB field, required FieldPB field,
}) = _GridCellIdentifier; }) = _GridCellIdentifier;
// ignore: unused_element // ignore: unused_element

View File

@ -166,7 +166,7 @@ class IGridCellController<T, D> extends Equatable {
String get fieldId => cellId.field.id; String get fieldId => cellId.field.id;
GridFieldPB get field => cellId.field; FieldPB get field => cellId.field;
FieldType get fieldType => cellId.field.fieldType; FieldType get fieldType => cellId.field.fieldType;
@ -321,8 +321,8 @@ class GridCellFieldNotifierImpl extends IGridCellFieldNotifier {
} }
@override @override
void onCellFieldChanged(void Function(GridFieldPB p1) callback) { void onCellFieldChanged(void Function(FieldPB p1) callback) {
_onChangesetFn = (GridFieldChangesetPB changeset) { _onChangesetFn = (FieldChangesetPB changeset) {
for (final updatedField in changeset.updatedFields) { for (final updatedField in changeset.updatedFields) {
callback(updatedField); callback(updatedField);
} }

View File

@ -10,15 +10,18 @@ class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
final GridDateCellController cellContext; final GridDateCellController cellContext;
void Function()? _onCellChangedFn; void Function()? _onCellChangedFn;
DateCellBloc({required this.cellContext}) : super(DateCellState.initial(cellContext)) { DateCellBloc({required this.cellContext})
: super(DateCellState.initial(cellContext)) {
on<DateCellEvent>( on<DateCellEvent>(
(event, emit) async { (event, emit) async {
event.when( event.when(
initial: () => _startListening(), initial: () => _startListening(),
didReceiveCellUpdate: (DateCellDataPB? cellData) { didReceiveCellUpdate: (DateCellDataPB? cellData) {
emit(state.copyWith(data: cellData, dateStr: _dateStrFromCellData(cellData))); emit(state.copyWith(
data: cellData, dateStr: _dateStrFromCellData(cellData)));
}, },
didReceiveFieldUpdate: (GridFieldPB value) => emit(state.copyWith(field: value)), didReceiveFieldUpdate: (FieldPB value) =>
emit(state.copyWith(field: value)),
); );
}, },
); );
@ -48,8 +51,10 @@ class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
@freezed @freezed
class DateCellEvent with _$DateCellEvent { class DateCellEvent with _$DateCellEvent {
const factory DateCellEvent.initial() = _InitialCell; const factory DateCellEvent.initial() = _InitialCell;
const factory DateCellEvent.didReceiveCellUpdate(DateCellDataPB? data) = _DidReceiveCellUpdate; const factory DateCellEvent.didReceiveCellUpdate(DateCellDataPB? data) =
const factory DateCellEvent.didReceiveFieldUpdate(GridFieldPB field) = _DidReceiveFieldUpdate; _DidReceiveCellUpdate;
const factory DateCellEvent.didReceiveFieldUpdate(FieldPB field) =
_DidReceiveFieldUpdate;
} }
@freezed @freezed
@ -57,7 +62,7 @@ class DateCellState with _$DateCellState {
const factory DateCellState({ const factory DateCellState({
required DateCellDataPB? data, required DateCellDataPB? data,
required String dateStr, required String dateStr,
required GridFieldPB field, required FieldPB field,
}) = _DateCellState; }) = _DateCellState;
factory DateCellState.initial(GridDateCellController context) { factory DateCellState.initial(GridDateCellController context) {

View File

@ -7,11 +7,13 @@ import 'field_service.dart';
part 'field_action_sheet_bloc.freezed.dart'; part 'field_action_sheet_bloc.freezed.dart';
class FieldActionSheetBloc extends Bloc<FieldActionSheetEvent, FieldActionSheetState> { class FieldActionSheetBloc
extends Bloc<FieldActionSheetEvent, FieldActionSheetState> {
final FieldService fieldService; final FieldService fieldService;
FieldActionSheetBloc({required GridFieldPB field, required this.fieldService}) FieldActionSheetBloc({required FieldPB field, required this.fieldService})
: super(FieldActionSheetState.initial(FieldTypeOptionDataPB.create()..field_2 = field)) { : super(FieldActionSheetState.initial(
FieldTypeOptionDataPB.create()..field_2 = field)) {
on<FieldActionSheetEvent>( on<FieldActionSheetEvent>(
(event, emit) async { (event, emit) async {
await event.map( await event.map(
@ -57,7 +59,8 @@ class FieldActionSheetBloc extends Bloc<FieldActionSheetEvent, FieldActionSheetS
@freezed @freezed
class FieldActionSheetEvent with _$FieldActionSheetEvent { class FieldActionSheetEvent with _$FieldActionSheetEvent {
const factory FieldActionSheetEvent.updateFieldName(String name) = _UpdateFieldName; const factory FieldActionSheetEvent.updateFieldName(String name) =
_UpdateFieldName;
const factory FieldActionSheetEvent.hideField() = _HideField; const factory FieldActionSheetEvent.hideField() = _HideField;
const factory FieldActionSheetEvent.duplicateField() = _DuplicateField; const factory FieldActionSheetEvent.duplicateField() = _DuplicateField;
const factory FieldActionSheetEvent.deleteField() = _DeleteField; const factory FieldActionSheetEvent.deleteField() = _DeleteField;
@ -72,7 +75,8 @@ class FieldActionSheetState with _$FieldActionSheetState {
required String fieldName, required String fieldName,
}) = _FieldActionSheetState; }) = _FieldActionSheetState;
factory FieldActionSheetState.initial(FieldTypeOptionDataPB data) => FieldActionSheetState( factory FieldActionSheetState.initial(FieldTypeOptionDataPB data) =>
FieldActionSheetState(
fieldTypeOptionData: data, fieldTypeOptionData: data,
errorText: '', errorText: '',
fieldName: data.field_2.name, fieldName: data.field_2.name,

View File

@ -8,18 +8,18 @@ import 'package:flutter/foundation.dart';
import '../row/row_cache.dart'; import '../row/row_cache.dart';
class FieldsNotifier extends ChangeNotifier { class FieldsNotifier extends ChangeNotifier {
List<GridFieldPB> _fields = []; List<FieldPB> _fields = [];
set fields(List<GridFieldPB> fields) { set fields(List<FieldPB> fields) {
_fields = fields; _fields = fields;
notifyListeners(); notifyListeners();
} }
List<GridFieldPB> get fields => _fields; List<FieldPB> get fields => _fields;
} }
typedef FieldChangesetCallback = void Function(GridFieldChangesetPB); typedef FieldChangesetCallback = void Function(FieldChangesetPB);
typedef FieldsCallback = void Function(List<GridFieldPB>); typedef FieldsCallback = void Function(List<FieldPB>);
class GridFieldCache { class GridFieldCache {
final String gridId; final String gridId;
@ -52,12 +52,12 @@ class GridFieldCache {
_fieldNotifier = null; _fieldNotifier = null;
} }
UnmodifiableListView<GridFieldPB> get unmodifiableFields => UnmodifiableListView<FieldPB> get unmodifiableFields =>
UnmodifiableListView(_fieldNotifier?.fields ?? []); UnmodifiableListView(_fieldNotifier?.fields ?? []);
List<GridFieldPB> get fields => [..._fieldNotifier?.fields ?? []]; List<FieldPB> get fields => [..._fieldNotifier?.fields ?? []];
set fields(List<GridFieldPB> fields) { set fields(List<FieldPB> fields) {
_fieldNotifier?.fields = [...fields]; _fieldNotifier?.fields = [...fields];
} }
@ -106,12 +106,12 @@ class GridFieldCache {
} }
} }
void _deleteFields(List<GridFieldIdPB> deletedFields) { void _deleteFields(List<FieldIdPB> deletedFields) {
if (deletedFields.isEmpty) { if (deletedFields.isEmpty) {
return; return;
} }
final List<GridFieldPB> newFields = fields; final List<FieldPB> newFields = fields;
final Map<String, GridFieldIdPB> deletedFieldMap = { final Map<String, FieldIdPB> deletedFieldMap = {
for (var fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder for (var fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder
}; };
@ -123,7 +123,7 @@ class GridFieldCache {
if (insertedFields.isEmpty) { if (insertedFields.isEmpty) {
return; return;
} }
final List<GridFieldPB> newFields = fields; final List<FieldPB> newFields = fields;
for (final indexField in insertedFields) { for (final indexField in insertedFields) {
if (newFields.length > indexField.index) { if (newFields.length > indexField.index) {
newFields.insert(indexField.index, indexField.field_1); newFields.insert(indexField.index, indexField.field_1);
@ -134,11 +134,11 @@ class GridFieldCache {
_fieldNotifier?.fields = newFields; _fieldNotifier?.fields = newFields;
} }
void _updateFields(List<GridFieldPB> updatedFields) { void _updateFields(List<FieldPB> updatedFields) {
if (updatedFields.isEmpty) { if (updatedFields.isEmpty) {
return; return;
} }
final List<GridFieldPB> newFields = fields; final List<FieldPB> newFields = fields;
for (final updatedField in updatedFields) { for (final updatedField in updatedFields) {
final index = final index =
newFields.indexWhere((field) => field.id == updatedField.id); newFields.indexWhere((field) => field.id == updatedField.id);
@ -158,7 +158,7 @@ class GridRowFieldNotifierImpl extends IGridRowFieldNotifier {
GridRowFieldNotifierImpl(GridFieldCache cache) : _cache = cache; GridRowFieldNotifierImpl(GridFieldCache cache) : _cache = cache;
@override @override
UnmodifiableListView<GridFieldPB> get fields => _cache.unmodifiableFields; UnmodifiableListView<FieldPB> get fields => _cache.unmodifiableFields;
@override @override
void onRowFieldsChanged(VoidCallback callback) { void onRowFieldsChanged(VoidCallback callback) {
@ -167,8 +167,8 @@ class GridRowFieldNotifierImpl extends IGridRowFieldNotifier {
} }
@override @override
void onRowFieldChanged(void Function(GridFieldPB) callback) { void onRowFieldChanged(void Function(FieldPB) callback) {
_onChangesetFn = (GridFieldChangesetPB changeset) { _onChangesetFn = (FieldChangesetPB changeset) {
for (final updatedField in changeset.updatedFields) { for (final updatedField in changeset.updatedFields) {
callback(updatedField); callback(updatedField);
} }

View File

@ -63,7 +63,7 @@ class FieldCellBloc extends Bloc<FieldCellEvent, FieldCellState> {
@freezed @freezed
class FieldCellEvent with _$FieldCellEvent { class FieldCellEvent with _$FieldCellEvent {
const factory FieldCellEvent.initial() = _InitialCell; const factory FieldCellEvent.initial() = _InitialCell;
const factory FieldCellEvent.didReceiveFieldUpdate(GridFieldPB field) = const factory FieldCellEvent.didReceiveFieldUpdate(FieldPB field) =
_DidReceiveFieldUpdate; _DidReceiveFieldUpdate;
const factory FieldCellEvent.startUpdateWidth(double offset) = const factory FieldCellEvent.startUpdateWidth(double offset) =
_StartUpdateWidth; _StartUpdateWidth;
@ -74,7 +74,7 @@ class FieldCellEvent with _$FieldCellEvent {
class FieldCellState with _$FieldCellState { class FieldCellState with _$FieldCellState {
const factory FieldCellState({ const factory FieldCellState({
required String gridId, required String gridId,
required GridFieldPB field, required FieldPB field,
required double width, required double width,
}) = _FieldCellState; }) = _FieldCellState;

View File

@ -34,7 +34,7 @@ class FieldEditorBloc extends Bloc<FieldEditorEvent, FieldEditorState> {
dataController.fieldName = name; dataController.fieldName = name;
emit(state.copyWith(name: name)); emit(state.copyWith(name: name));
}, },
didReceiveFieldChanged: (GridFieldPB field) { didReceiveFieldChanged: (FieldPB field) {
emit(state.copyWith(field: Some(field))); emit(state.copyWith(field: Some(field)));
}, },
); );
@ -52,7 +52,7 @@ class FieldEditorBloc extends Bloc<FieldEditorEvent, FieldEditorState> {
class FieldEditorEvent with _$FieldEditorEvent { class FieldEditorEvent with _$FieldEditorEvent {
const factory FieldEditorEvent.initial() = _InitialField; const factory FieldEditorEvent.initial() = _InitialField;
const factory FieldEditorEvent.updateName(String name) = _UpdateName; const factory FieldEditorEvent.updateName(String name) = _UpdateName;
const factory FieldEditorEvent.didReceiveFieldChanged(GridFieldPB field) = const factory FieldEditorEvent.didReceiveFieldChanged(FieldPB field) =
_DidReceiveFieldChanged; _DidReceiveFieldChanged;
} }
@ -62,7 +62,7 @@ class FieldEditorState with _$FieldEditorState {
required String gridId, required String gridId,
required String errorText, required String errorText,
required String name, required String name,
required Option<GridFieldPB> field, required Option<FieldPB> field,
}) = _FieldEditorState; }) = _FieldEditorState;
factory FieldEditorState.initial( factory FieldEditorState.initial(

View File

@ -7,16 +7,18 @@ import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
typedef UpdateFieldNotifiedValue = Either<GridFieldPB, FlowyError>; typedef UpdateFieldNotifiedValue = Either<FieldPB, FlowyError>;
class SingleFieldListener { class SingleFieldListener {
final String fieldId; final String fieldId;
PublishNotifier<UpdateFieldNotifiedValue>? _updateFieldNotifier = PublishNotifier(); PublishNotifier<UpdateFieldNotifiedValue>? _updateFieldNotifier =
PublishNotifier();
GridNotificationListener? _listener; GridNotificationListener? _listener;
SingleFieldListener({required this.fieldId}); SingleFieldListener({required this.fieldId});
void start({required void Function(UpdateFieldNotifiedValue) onFieldChanged}) { void start(
{required void Function(UpdateFieldNotifiedValue) onFieldChanged}) {
_updateFieldNotifier?.addPublishListener(onFieldChanged); _updateFieldNotifier?.addPublishListener(onFieldChanged);
_listener = GridNotificationListener( _listener = GridNotificationListener(
objectId: fieldId, objectId: fieldId,
@ -31,7 +33,8 @@ class SingleFieldListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateField: case GridNotification.DidUpdateField:
result.fold( result.fold(
(payload) => _updateFieldNotifier?.value = left(GridFieldPB.fromBuffer(payload)), (payload) =>
_updateFieldNotifier?.value = left(FieldPB.fromBuffer(payload)),
(error) => _updateFieldNotifier?.value = right(error), (error) => _updateFieldNotifier?.value = right(error),
); );
break; break;

View File

@ -73,7 +73,7 @@ class FieldService {
// Create the field if it does not exist. Otherwise, update the field. // Create the field if it does not exist. Otherwise, update the field.
static Future<Either<Unit, FlowyError>> insertField({ static Future<Either<Unit, FlowyError>> insertField({
required String gridId, required String gridId,
required GridFieldPB field, required FieldPB field,
List<int>? typeOptionData, List<int>? typeOptionData,
String? startFieldId, String? startFieldId,
}) { }) {
@ -121,7 +121,7 @@ class FieldService {
Future<Either<FieldTypeOptionDataPB, FlowyError>> getFieldTypeOptionData({ Future<Either<FieldTypeOptionDataPB, FlowyError>> getFieldTypeOptionData({
required FieldType fieldType, required FieldType fieldType,
}) { }) {
final payload = GridFieldTypeOptionIdPB.create() final payload = FieldTypeOptionIdPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..fieldType = fieldType; ..fieldType = fieldType;
@ -138,6 +138,6 @@ class FieldService {
class GridFieldCellContext with _$GridFieldCellContext { class GridFieldCellContext with _$GridFieldCellContext {
const factory GridFieldCellContext({ const factory GridFieldCellContext({
required String gridId, required String gridId,
required GridFieldPB field, required FieldPB field,
}) = _GridFieldCellContext; }) = _GridFieldCellContext;
} }

View File

@ -42,14 +42,14 @@ class FieldTypeOptionEditBloc
@freezed @freezed
class FieldTypeOptionEditEvent with _$FieldTypeOptionEditEvent { class FieldTypeOptionEditEvent with _$FieldTypeOptionEditEvent {
const factory FieldTypeOptionEditEvent.initial() = _Initial; const factory FieldTypeOptionEditEvent.initial() = _Initial;
const factory FieldTypeOptionEditEvent.didReceiveFieldUpdated( const factory FieldTypeOptionEditEvent.didReceiveFieldUpdated(FieldPB field) =
GridFieldPB field) = _DidReceiveFieldUpdated; _DidReceiveFieldUpdated;
} }
@freezed @freezed
class FieldTypeOptionEditState with _$FieldTypeOptionEditState { class FieldTypeOptionEditState with _$FieldTypeOptionEditState {
const factory FieldTypeOptionEditState({ const factory FieldTypeOptionEditState({
required GridFieldPB field, required FieldPB field,
}) = _FieldTypeOptionEditState; }) = _FieldTypeOptionEditState;
factory FieldTypeOptionEditState.initial( factory FieldTypeOptionEditState.initial(

View File

@ -7,15 +7,17 @@ import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
typedef UpdateFieldNotifiedValue = Either<GridFieldChangesetPB, FlowyError>; typedef UpdateFieldNotifiedValue = Either<FieldChangesetPB, FlowyError>;
class GridFieldsListener { class GridFieldsListener {
final String gridId; final String gridId;
PublishNotifier<UpdateFieldNotifiedValue>? updateFieldsNotifier = PublishNotifier(); PublishNotifier<UpdateFieldNotifiedValue>? updateFieldsNotifier =
PublishNotifier();
GridNotificationListener? _listener; GridNotificationListener? _listener;
GridFieldsListener({required this.gridId}); GridFieldsListener({required this.gridId});
void start({required void Function(UpdateFieldNotifiedValue) onFieldsChanged}) { void start(
{required void Function(UpdateFieldNotifiedValue) onFieldsChanged}) {
updateFieldsNotifier?.addPublishListener(onFieldsChanged); updateFieldsNotifier?.addPublishListener(onFieldsChanged);
_listener = GridNotificationListener( _listener = GridNotificationListener(
objectId: gridId, objectId: gridId,
@ -27,7 +29,8 @@ class GridFieldsListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateGridField: case GridNotification.DidUpdateGridField:
result.fold( result.fold(
(payload) => updateFieldsNotifier?.value = left(GridFieldChangesetPB.fromBuffer(payload)), (payload) => updateFieldsNotifier?.value =
left(FieldChangesetPB.fromBuffer(payload)),
(error) => updateFieldsNotifier?.value = right(error), (error) => updateFieldsNotifier?.value = right(error),
); );
break; break;

View File

@ -176,7 +176,7 @@ class NewFieldTypeOptionLoader extends IFieldTypeOptionLoader {
class FieldTypeOptionLoader extends IFieldTypeOptionLoader { class FieldTypeOptionLoader extends IFieldTypeOptionLoader {
@override @override
final String gridId; final String gridId;
final GridFieldPB field; final FieldPB field;
FieldTypeOptionLoader({ FieldTypeOptionLoader({
required this.gridId, required this.gridId,
@ -185,7 +185,7 @@ class FieldTypeOptionLoader extends IFieldTypeOptionLoader {
@override @override
Future<Either<FieldTypeOptionDataPB, FlowyError>> load() { Future<Either<FieldTypeOptionDataPB, FlowyError>> load() {
final payload = GridFieldTypeOptionIdPB.create() final payload = FieldTypeOptionIdPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = field.id ..fieldId = field.id
..fieldType = field.fieldType; ..fieldType = field.fieldType;

View File

@ -12,12 +12,12 @@ class TypeOptionDataController {
final String gridId; final String gridId;
final IFieldTypeOptionLoader loader; final IFieldTypeOptionLoader loader;
late FieldTypeOptionDataPB _data; late FieldTypeOptionDataPB _data;
final PublishNotifier<GridFieldPB> _fieldNotifier = PublishNotifier(); final PublishNotifier<FieldPB> _fieldNotifier = PublishNotifier();
TypeOptionDataController({ TypeOptionDataController({
required this.gridId, required this.gridId,
required this.loader, required this.loader,
GridFieldPB? field, FieldPB? field,
}) { }) {
if (field != null) { if (field != null) {
_data = FieldTypeOptionDataPB.create() _data = FieldTypeOptionDataPB.create()
@ -42,11 +42,11 @@ class TypeOptionDataController {
); );
} }
GridFieldPB get field { FieldPB get field {
return _data.field_2; return _data.field_2;
} }
set field(GridFieldPB field) { set field(FieldPB field) {
_updateData(newField: field); _updateData(newField: field);
} }
@ -64,7 +64,7 @@ class TypeOptionDataController {
void _updateData({ void _updateData({
String? newName, String? newName,
GridFieldPB? newField, FieldPB? newField,
List<int>? newTypeOptionData, List<int>? newTypeOptionData,
}) { }) {
_data = _data.rebuild((rebuildData) { _data = _data.rebuild((rebuildData) {
@ -108,7 +108,7 @@ class TypeOptionDataController {
}); });
} }
void Function() addFieldListener(void Function(GridFieldPB) callback) { void Function() addFieldListener(void Function(FieldPB) callback) {
listener() { listener() {
callback(field); callback(field);
} }

View File

@ -97,11 +97,11 @@ class GridEvent with _$GridEvent {
const factory GridEvent.initial() = InitialGrid; const factory GridEvent.initial() = InitialGrid;
const factory GridEvent.createRow() = _CreateRow; const factory GridEvent.createRow() = _CreateRow;
const factory GridEvent.didReceiveRowUpdate( const factory GridEvent.didReceiveRowUpdate(
List<GridRowInfo> rows, List<RowInfo> rows,
GridRowChangeReason listState, RowChangeReason listState,
) = _DidReceiveRowUpdate; ) = _DidReceiveRowUpdate;
const factory GridEvent.didReceiveFieldUpdate( const factory GridEvent.didReceiveFieldUpdate(
UnmodifiableListView<GridFieldPB> fields, UnmodifiableListView<FieldPB> fields,
) = _DidReceiveFieldUpdate; ) = _DidReceiveFieldUpdate;
const factory GridEvent.didReceiveGridUpdate( const factory GridEvent.didReceiveGridUpdate(
@ -115,9 +115,9 @@ class GridState with _$GridState {
required String gridId, required String gridId,
required Option<GridPB> grid, required Option<GridPB> grid,
required GridFieldEquatable fields, required GridFieldEquatable fields,
required List<GridRowInfo> rowInfos, required List<RowInfo> rowInfos,
required GridLoadingState loadingState, required GridLoadingState loadingState,
required GridRowChangeReason reason, required RowChangeReason reason,
}) = _GridState; }) = _GridState;
factory GridState.initial(String gridId) => GridState( factory GridState.initial(String gridId) => GridState(
@ -138,9 +138,9 @@ class GridLoadingState with _$GridLoadingState {
} }
class GridFieldEquatable extends Equatable { class GridFieldEquatable extends Equatable {
final UnmodifiableListView<GridFieldPB> _fields; final UnmodifiableListView<FieldPB> _fields;
const GridFieldEquatable( const GridFieldEquatable(
UnmodifiableListView<GridFieldPB> fields, UnmodifiableListView<FieldPB> fields,
) : _fields = fields; ) : _fields = fields;
@override @override
@ -157,5 +157,5 @@ class GridFieldEquatable extends Equatable {
]; ];
} }
UnmodifiableListView<GridFieldPB> get value => UnmodifiableListView(_fields); UnmodifiableListView<FieldPB> get value => UnmodifiableListView(_fields);
} }

View File

@ -13,12 +13,12 @@ import 'field/field_cache.dart';
import 'prelude.dart'; import 'prelude.dart';
import 'row/row_cache.dart'; import 'row/row_cache.dart';
typedef OnFieldsChanged = void Function(UnmodifiableListView<GridFieldPB>); typedef OnFieldsChanged = void Function(UnmodifiableListView<FieldPB>);
typedef OnGridChanged = void Function(GridPB); typedef OnGridChanged = void Function(GridPB);
typedef OnRowsChanged = void Function( typedef OnRowsChanged = void Function(
List<GridRowInfo> rowInfos, List<RowInfo> rowInfos,
GridRowChangeReason, RowChangeReason,
); );
typedef ListenONRowChangedCondition = bool Function(); typedef ListenONRowChangedCondition = bool Function();
@ -36,8 +36,8 @@ class GridDataController {
OnFieldsChanged? _onFieldsChanged; OnFieldsChanged? _onFieldsChanged;
OnGridChanged? _onGridChanged; OnGridChanged? _onGridChanged;
List<GridRowInfo> get rowInfos { List<RowInfo> get rowInfos {
final List<GridRowInfo> rows = []; final List<RowInfo> rows = [];
for (var block in _blocks.values) { for (var block in _blocks.values) {
rows.addAll(block.rows); rows.addAll(block.rows);
} }
@ -91,7 +91,7 @@ class GridDataController {
} }
} }
void _initialBlocks(List<GridBlockPB> blocks) { void _initialBlocks(List<BlockPB> blocks) {
for (final block in blocks) { for (final block in blocks) {
if (_blocks[block.id] != null) { if (_blocks[block.id] != null) {
Log.warn("Initial duplicate block's cache: ${block.id}"); Log.warn("Initial duplicate block's cache: ${block.id}");

View File

@ -36,7 +36,7 @@ class GridHeaderBloc extends Bloc<GridHeaderEvent, GridHeaderState> {
Future<void> _moveField( Future<void> _moveField(
_MoveField value, Emitter<GridHeaderState> emit) async { _MoveField value, Emitter<GridHeaderState> emit) async {
final fields = List<GridFieldPB>.from(state.fields); final fields = List<FieldPB>.from(state.fields);
fields.insert(value.toIndex, fields.removeAt(value.fromIndex)); fields.insert(value.toIndex, fields.removeAt(value.fromIndex));
emit(state.copyWith(fields: fields)); emit(state.copyWith(fields: fields));
@ -64,19 +64,19 @@ class GridHeaderBloc extends Bloc<GridHeaderEvent, GridHeaderState> {
@freezed @freezed
class GridHeaderEvent with _$GridHeaderEvent { class GridHeaderEvent with _$GridHeaderEvent {
const factory GridHeaderEvent.initial() = _InitialHeader; const factory GridHeaderEvent.initial() = _InitialHeader;
const factory GridHeaderEvent.didReceiveFieldUpdate( const factory GridHeaderEvent.didReceiveFieldUpdate(List<FieldPB> fields) =
List<GridFieldPB> fields) = _DidReceiveFieldUpdate; _DidReceiveFieldUpdate;
const factory GridHeaderEvent.moveField( const factory GridHeaderEvent.moveField(
GridFieldPB field, int fromIndex, int toIndex) = _MoveField; FieldPB field, int fromIndex, int toIndex) = _MoveField;
} }
@freezed @freezed
class GridHeaderState with _$GridHeaderState { class GridHeaderState with _$GridHeaderState {
const factory GridHeaderState({required List<GridFieldPB> fields}) = const factory GridHeaderState({required List<FieldPB> fields}) =
_GridHeaderState; _GridHeaderState;
factory GridHeaderState.initial(List<GridFieldPB> fields) { factory GridHeaderState.initial(List<FieldPB> fields) {
// final List<GridFieldPB> newFields = List.from(fields); // final List<FieldPB> newFields = List.from(fields);
// newFields.retainWhere((field) => field.visibility); // newFields.retainWhere((field) => field.visibility);
return GridHeaderState(fields: fields); return GridHeaderState(fields: fields);
} }

View File

@ -20,18 +20,17 @@ class GridService {
return GridEventGetGrid(payload).send(); return GridEventGetGrid(payload).send();
} }
Future<Either<GridRowPB, FlowyError>> createRow( Future<Either<RowPB, FlowyError>> createRow({Option<String>? startRowId}) {
{Option<String>? startRowId}) {
CreateRowPayloadPB payload = CreateRowPayloadPB.create()..gridId = gridId; CreateRowPayloadPB payload = CreateRowPayloadPB.create()..gridId = gridId;
startRowId?.fold(() => null, (id) => payload.startRowId = id); startRowId?.fold(() => null, (id) => payload.startRowId = id);
return GridEventCreateRow(payload).send(); return GridEventCreateRow(payload).send();
} }
Future<Either<RepeatedGridFieldPB, FlowyError>> getFields( Future<Either<RepeatedFieldPB, FlowyError>> getFields(
{required List<GridFieldIdPB> fieldIds}) { {required List<FieldIdPB> fieldIds}) {
final payload = QueryFieldPayloadPB.create() final payload = QueryFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldIds = RepeatedGridFieldIdPB(items: fieldIds); ..fieldIds = RepeatedFieldIdPB(items: fieldIds);
return GridEventGetFields(payload).send(); return GridEventGetFields(payload).send();
} }

View File

@ -4,13 +4,13 @@ export 'row/row_service.dart';
export 'grid_service.dart'; export 'grid_service.dart';
export 'grid_header_bloc.dart'; export 'grid_header_bloc.dart';
// GridFieldPB // FieldPB
export 'field/field_service.dart'; export 'field/field_service.dart';
export 'field/field_action_sheet_bloc.dart'; export 'field/field_action_sheet_bloc.dart';
export 'field/field_editor_bloc.dart'; export 'field/field_editor_bloc.dart';
export 'field/field_type_option_edit_bloc.dart'; export 'field/field_type_option_edit_bloc.dart';
// GridFieldPB Type Option // FieldPB Type Option
export 'field/type_option/date_bloc.dart'; export 'field/type_option/date_bloc.dart';
export 'field/type_option/number_bloc.dart'; export 'field/type_option/number_bloc.dart';
export 'field/type_option/single_select_type_option.dart'; export 'field/type_option/single_select_type_option.dart';

View File

@ -14,7 +14,7 @@ class RowActionSheetBloc
extends Bloc<RowActionSheetEvent, RowActionSheetState> { extends Bloc<RowActionSheetEvent, RowActionSheetState> {
final RowService _rowService; final RowService _rowService;
RowActionSheetBloc({required GridRowInfo rowData}) RowActionSheetBloc({required RowInfo rowData})
: _rowService = RowService( : _rowService = RowService(
gridId: rowData.gridId, gridId: rowData.gridId,
blockId: rowData.blockId, blockId: rowData.blockId,
@ -56,11 +56,10 @@ class RowActionSheetEvent with _$RowActionSheetEvent {
@freezed @freezed
class RowActionSheetState with _$RowActionSheetState { class RowActionSheetState with _$RowActionSheetState {
const factory RowActionSheetState({ const factory RowActionSheetState({
required GridRowInfo rowData, required RowInfo rowData,
}) = _RowActionSheetState; }) = _RowActionSheetState;
factory RowActionSheetState.initial(GridRowInfo rowData) => factory RowActionSheetState.initial(RowInfo rowData) => RowActionSheetState(
RowActionSheetState(
rowData: rowData, rowData: rowData,
); );
} }

View File

@ -16,7 +16,7 @@ class RowBloc extends Bloc<RowEvent, RowState> {
final GridRowDataController _dataController; final GridRowDataController _dataController;
RowBloc({ RowBloc({
required GridRowInfo rowInfo, required RowInfo rowInfo,
required GridRowDataController dataController, required GridRowDataController dataController,
}) : _rowService = RowService( }) : _rowService = RowService(
gridId: rowInfo.gridId, gridId: rowInfo.gridId,
@ -72,19 +72,19 @@ class RowEvent with _$RowEvent {
const factory RowEvent.initial() = _InitialRow; const factory RowEvent.initial() = _InitialRow;
const factory RowEvent.createRow() = _CreateRow; const factory RowEvent.createRow() = _CreateRow;
const factory RowEvent.didReceiveCells( const factory RowEvent.didReceiveCells(
GridCellMap gridCellMap, GridRowChangeReason reason) = _DidReceiveCells; GridCellMap gridCellMap, RowChangeReason reason) = _DidReceiveCells;
} }
@freezed @freezed
class RowState with _$RowState { class RowState with _$RowState {
const factory RowState({ const factory RowState({
required GridRowInfo rowInfo, required RowInfo rowInfo,
required GridCellMap gridCellMap, required GridCellMap gridCellMap,
required UnmodifiableListView<GridCellEquatable> snapshots, required UnmodifiableListView<GridCellEquatable> snapshots,
GridRowChangeReason? changeReason, RowChangeReason? changeReason,
}) = _RowState; }) = _RowState;
factory RowState.initial(GridRowInfo rowInfo, GridCellMap cellDataMap) => factory RowState.initial(RowInfo rowInfo, GridCellMap cellDataMap) =>
RowState( RowState(
rowInfo: rowInfo, rowInfo: rowInfo,
gridCellMap: cellDataMap, gridCellMap: cellDataMap,
@ -94,9 +94,9 @@ class RowState with _$RowState {
} }
class GridCellEquatable extends Equatable { class GridCellEquatable extends Equatable {
final GridFieldPB _field; final FieldPB _field;
const GridCellEquatable(GridFieldPB field) : _field = field; const GridCellEquatable(FieldPB field) : _field = field;
@override @override
List<Object?> get props => [ List<Object?> get props => [

View File

@ -12,9 +12,9 @@ part 'row_cache.freezed.dart';
typedef RowUpdateCallback = void Function(); typedef RowUpdateCallback = void Function();
abstract class IGridRowFieldNotifier { abstract class IGridRowFieldNotifier {
UnmodifiableListView<GridFieldPB> get fields; UnmodifiableListView<FieldPB> get fields;
void onRowFieldsChanged(VoidCallback callback); void onRowFieldsChanged(VoidCallback callback);
void onRowFieldChanged(void Function(GridFieldPB) callback); void onRowFieldChanged(void Function(FieldPB) callback);
void onRowDispose(); void onRowDispose();
} }
@ -25,20 +25,20 @@ abstract class IGridRowFieldNotifier {
class GridRowCache { class GridRowCache {
final String gridId; final String gridId;
final GridBlockPB block; final BlockPB block;
/// _rows containers the current block's rows /// _rows containers the current block's rows
/// Use List to reverse the order of the GridRow. /// Use List to reverse the order of the GridRow.
List<GridRowInfo> _rowInfos = []; List<RowInfo> _rowInfos = [];
/// Use Map for faster access the raw row data. /// Use Map for faster access the raw row data.
final HashMap<String, GridRowPB> _rowByRowId; final HashMap<String, RowPB> _rowByRowId;
final GridCellCache _cellCache; final GridCellCache _cellCache;
final IGridRowFieldNotifier _fieldNotifier; final IGridRowFieldNotifier _fieldNotifier;
final _GridRowChangesetNotifier _rowChangeReasonNotifier; final _RowChangesetNotifier _rowChangeReasonNotifier;
UnmodifiableListView<GridRowInfo> get rows => UnmodifiableListView(_rowInfos); UnmodifiableListView<RowInfo> get rows => UnmodifiableListView(_rowInfos);
GridCellCache get cellCache => _cellCache; GridCellCache get cellCache => _cellCache;
GridRowCache({ GridRowCache({
@ -47,11 +47,11 @@ class GridRowCache {
required IGridRowFieldNotifier notifier, required IGridRowFieldNotifier notifier,
}) : _cellCache = GridCellCache(gridId: gridId), }) : _cellCache = GridCellCache(gridId: gridId),
_rowByRowId = HashMap(), _rowByRowId = HashMap(),
_rowChangeReasonNotifier = _GridRowChangesetNotifier(), _rowChangeReasonNotifier = _RowChangesetNotifier(),
_fieldNotifier = notifier { _fieldNotifier = notifier {
// //
notifier.onRowFieldsChanged(() => _rowChangeReasonNotifier notifier.onRowFieldsChanged(() => _rowChangeReasonNotifier
.receive(const GridRowChangeReason.fieldDidChange())); .receive(const RowChangeReason.fieldDidChange()));
notifier.onRowFieldChanged((field) => _cellCache.remove(field.id)); notifier.onRowFieldChanged((field) => _cellCache.remove(field.id));
_rowInfos = block.rows _rowInfos = block.rows
.map((rowInfo) => buildGridRow(rowInfo.id, rowInfo.height.toDouble())) .map((rowInfo) => buildGridRow(rowInfo.id, rowInfo.height.toDouble()))
@ -79,7 +79,7 @@ class GridRowCache {
return; return;
} }
final List<GridRowInfo> newRows = []; final List<RowInfo> newRows = [];
final DeletedIndexs deletedIndex = []; final DeletedIndexs deletedIndex = [];
final Map<String, String> deletedRowByRowId = { final Map<String, String> deletedRowByRowId = {
for (var rowId in deletedRows) rowId: rowId for (var rowId in deletedRows) rowId: rowId
@ -94,7 +94,7 @@ class GridRowCache {
} }
}); });
_rowInfos = newRows; _rowInfos = newRows;
_rowChangeReasonNotifier.receive(GridRowChangeReason.delete(deletedIndex)); _rowChangeReasonNotifier.receive(RowChangeReason.delete(deletedIndex));
} }
void _insertRows(List<InsertedRowPB> insertRows) { void _insertRows(List<InsertedRowPB> insertRows) {
@ -113,7 +113,7 @@ class GridRowCache {
(buildGridRow(insertRow.rowId, insertRow.height.toDouble()))); (buildGridRow(insertRow.rowId, insertRow.height.toDouble())));
} }
_rowChangeReasonNotifier.receive(GridRowChangeReason.insert(insertIndexs)); _rowChangeReasonNotifier.receive(RowChangeReason.insert(insertIndexs));
} }
void _updateRows(List<UpdatedRowPB> updatedRows) { void _updateRows(List<UpdatedRowPB> updatedRows) {
@ -135,7 +135,7 @@ class GridRowCache {
} }
} }
_rowChangeReasonNotifier.receive(GridRowChangeReason.update(updatedIndexs)); _rowChangeReasonNotifier.receive(RowChangeReason.update(updatedIndexs));
} }
void _hideRows(List<String> hideRows) {} void _hideRows(List<String> hideRows) {}
@ -143,7 +143,7 @@ class GridRowCache {
void _showRows(List<String> visibleRows) {} void _showRows(List<String> visibleRows) {}
void onRowsChanged( void onRowsChanged(
void Function(GridRowChangeReason) onRowChanged, void Function(RowChangeReason) onRowChanged,
) { ) {
_rowChangeReasonNotifier.addListener(() { _rowChangeReasonNotifier.addListener(() {
onRowChanged(_rowChangeReasonNotifier.reason); onRowChanged(_rowChangeReasonNotifier.reason);
@ -152,7 +152,7 @@ class GridRowCache {
RowUpdateCallback addListener({ RowUpdateCallback addListener({
required String rowId, required String rowId,
void Function(GridCellMap, GridRowChangeReason)? onCellUpdated, void Function(GridCellMap, RowChangeReason)? onCellUpdated,
bool Function()? listenWhen, bool Function()? listenWhen,
}) { }) {
listenerHandler() async { listenerHandler() async {
@ -187,7 +187,7 @@ class GridRowCache {
} }
GridCellMap loadGridCells(String rowId) { GridCellMap loadGridCells(String rowId) {
final GridRowPB? data = _rowByRowId[rowId]; final RowPB? data = _rowByRowId[rowId];
if (data == null) { if (data == null) {
_loadRow(rowId); _loadRow(rowId);
} }
@ -195,7 +195,7 @@ class GridRowCache {
} }
Future<void> _loadRow(String rowId) async { Future<void> _loadRow(String rowId) async {
final payload = GridRowIdPB.create() final payload = RowIdPB.create()
..gridId = gridId ..gridId = gridId
..blockId = block.id ..blockId = block.id
..rowId = rowId; ..rowId = rowId;
@ -207,7 +207,7 @@ class GridRowCache {
); );
} }
GridCellMap _makeGridCells(String rowId, GridRowPB? row) { GridCellMap _makeGridCells(String rowId, RowPB? row) {
var cellDataMap = GridCellMap.new(); var cellDataMap = GridCellMap.new();
for (final field in _fieldNotifier.fields) { for (final field in _fieldNotifier.fields) {
if (field.visibility) { if (field.visibility) {
@ -242,14 +242,13 @@ class GridRowCache {
updatedIndexs[row.id] = UpdatedIndex(index: index, rowId: row.id); updatedIndexs[row.id] = UpdatedIndex(index: index, rowId: row.id);
// //
_rowChangeReasonNotifier _rowChangeReasonNotifier.receive(RowChangeReason.update(updatedIndexs));
.receive(GridRowChangeReason.update(updatedIndexs));
} }
} }
} }
GridRowInfo buildGridRow(String rowId, double rowHeight) { RowInfo buildGridRow(String rowId, double rowHeight) {
return GridRowInfo( return RowInfo(
gridId: gridId, gridId: gridId,
blockId: block.id, blockId: block.id,
fields: _fieldNotifier.fields, fields: _fieldNotifier.fields,
@ -259,12 +258,12 @@ class GridRowCache {
} }
} }
class _GridRowChangesetNotifier extends ChangeNotifier { class _RowChangesetNotifier extends ChangeNotifier {
GridRowChangeReason reason = const InitialListState(); RowChangeReason reason = const InitialListState();
_GridRowChangesetNotifier(); _RowChangesetNotifier();
void receive(GridRowChangeReason newReason) { void receive(RowChangeReason newReason) {
reason = newReason; reason = newReason;
reason.map( reason.map(
insert: (_) => notifyListeners(), insert: (_) => notifyListeners(),
@ -277,15 +276,15 @@ class _GridRowChangesetNotifier extends ChangeNotifier {
} }
@freezed @freezed
class GridRowInfo with _$GridRowInfo { class RowInfo with _$RowInfo {
const factory GridRowInfo({ const factory RowInfo({
required String gridId, required String gridId,
required String blockId, required String blockId,
required String id, required String id,
required UnmodifiableListView<GridFieldPB> fields, required UnmodifiableListView<FieldPB> fields,
required double height, required double height,
GridRowPB? rawRow, RowPB? rawRow,
}) = _GridRowInfo; }) = _RowInfo;
} }
typedef InsertedIndexs = List<InsertedIndex>; typedef InsertedIndexs = List<InsertedIndex>;
@ -293,12 +292,12 @@ typedef DeletedIndexs = List<DeletedIndex>;
typedef UpdatedIndexs = LinkedHashMap<String, UpdatedIndex>; typedef UpdatedIndexs = LinkedHashMap<String, UpdatedIndex>;
@freezed @freezed
class GridRowChangeReason with _$GridRowChangeReason { class RowChangeReason with _$RowChangeReason {
const factory GridRowChangeReason.insert(InsertedIndexs items) = _Insert; const factory RowChangeReason.insert(InsertedIndexs items) = _Insert;
const factory GridRowChangeReason.delete(DeletedIndexs items) = _Delete; const factory RowChangeReason.delete(DeletedIndexs items) = _Delete;
const factory GridRowChangeReason.update(UpdatedIndexs indexs) = _Update; const factory RowChangeReason.update(UpdatedIndexs indexs) = _Update;
const factory GridRowChangeReason.fieldDidChange() = _FieldDidChange; const factory RowChangeReason.fieldDidChange() = _FieldDidChange;
const factory GridRowChangeReason.initial() = InitialListState; const factory RowChangeReason.initial() = InitialListState;
} }
class InsertedIndex { class InsertedIndex {
@ -312,7 +311,7 @@ class InsertedIndex {
class DeletedIndex { class DeletedIndex {
final int index; final int index;
final GridRowInfo row; final RowInfo row;
DeletedIndex({ DeletedIndex({
required this.index, required this.index,
required this.row, required this.row,

View File

@ -5,10 +5,10 @@ import '../cell/cell_service/cell_service.dart';
import '../field/field_cache.dart'; import '../field/field_cache.dart';
import 'row_cache.dart'; import 'row_cache.dart';
typedef OnRowChanged = void Function(GridCellMap, GridRowChangeReason); typedef OnRowChanged = void Function(GridCellMap, RowChangeReason);
class GridRowDataController extends GridCellBuilderDelegate { class GridRowDataController extends GridCellBuilderDelegate {
final GridRowInfo rowInfo; final RowInfo rowInfo;
final List<VoidCallback> _onRowChangedListeners = []; final List<VoidCallback> _onRowChangedListeners = [];
final GridFieldCache _fieldCache; final GridFieldCache _fieldCache;
final GridRowCache _rowCache; final GridRowCache _rowCache;

View File

@ -8,12 +8,13 @@ import 'dart:typed_data';
import 'package:dartz/dartz.dart'; import 'package:dartz/dartz.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
typedef UpdateRowNotifiedValue = Either<GridRowPB, FlowyError>; typedef UpdateRowNotifiedValue = Either<RowPB, FlowyError>;
typedef UpdateFieldNotifiedValue = Either<List<GridFieldPB>, FlowyError>; typedef UpdateFieldNotifiedValue = Either<List<FieldPB>, FlowyError>;
class RowListener { class RowListener {
final String rowId; final String rowId;
PublishNotifier<UpdateRowNotifiedValue>? updateRowNotifier = PublishNotifier(); PublishNotifier<UpdateRowNotifiedValue>? updateRowNotifier =
PublishNotifier();
GridNotificationListener? _listener; GridNotificationListener? _listener;
RowListener({required this.rowId}); RowListener({required this.rowId});
@ -26,7 +27,8 @@ class RowListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateRow: case GridNotification.DidUpdateRow:
result.fold( result.fold(
(payload) => updateRowNotifier?.value = left(GridRowPB.fromBuffer(payload)), (payload) =>
updateRowNotifier?.value = left(RowPB.fromBuffer(payload)),
(error) => updateRowNotifier?.value = right(error), (error) => updateRowNotifier?.value = right(error),
); );
break; break;

View File

@ -13,7 +13,7 @@ class RowService {
RowService( RowService(
{required this.gridId, required this.blockId, required this.rowId}); {required this.gridId, required this.blockId, required this.rowId});
Future<Either<GridRowPB, FlowyError>> createRow() { Future<Either<RowPB, FlowyError>> createRow() {
CreateRowPayloadPB payload = CreateRowPayloadPB.create() CreateRowPayloadPB payload = CreateRowPayloadPB.create()
..gridId = gridId ..gridId = gridId
..startRowId = rowId; ..startRowId = rowId;
@ -34,7 +34,7 @@ class RowService {
} }
Future<Either<OptionalRowPB, FlowyError>> getRow() { Future<Either<OptionalRowPB, FlowyError>> getRow() {
final payload = GridRowIdPB.create() final payload = RowIdPB.create()
..gridId = gridId ..gridId = gridId
..blockId = blockId ..blockId = blockId
..rowId = rowId; ..rowId = rowId;
@ -43,7 +43,7 @@ class RowService {
} }
Future<Either<Unit, FlowyError>> deleteRow() { Future<Either<Unit, FlowyError>> deleteRow() {
final payload = GridRowIdPB.create() final payload = RowIdPB.create()
..gridId = gridId ..gridId = gridId
..blockId = blockId ..blockId = blockId
..rowId = rowId; ..rowId = rowId;
@ -52,7 +52,7 @@ class RowService {
} }
Future<Either<Unit, FlowyError>> duplicateRow() { Future<Either<Unit, FlowyError>> duplicateRow() {
final payload = GridRowIdPB.create() final payload = RowIdPB.create()
..gridId = gridId ..gridId = gridId
..blockId = blockId ..blockId = blockId
..rowId = rowId; ..rowId = rowId;

View File

@ -11,7 +11,7 @@ part 'property_bloc.freezed.dart';
class GridPropertyBloc extends Bloc<GridPropertyEvent, GridPropertyState> { class GridPropertyBloc extends Bloc<GridPropertyEvent, GridPropertyState> {
final GridFieldCache _fieldCache; final GridFieldCache _fieldCache;
Function(List<GridFieldPB>)? _onFieldsFn; Function(List<FieldPB>)? _onFieldsFn;
GridPropertyBloc({required String gridId, required GridFieldCache fieldCache}) GridPropertyBloc({required String gridId, required GridFieldCache fieldCache})
: _fieldCache = fieldCache, : _fieldCache = fieldCache,
@ -67,8 +67,8 @@ class GridPropertyEvent with _$GridPropertyEvent {
const factory GridPropertyEvent.initial() = _Initial; const factory GridPropertyEvent.initial() = _Initial;
const factory GridPropertyEvent.setFieldVisibility( const factory GridPropertyEvent.setFieldVisibility(
String fieldId, bool visibility) = _SetFieldVisibility; String fieldId, bool visibility) = _SetFieldVisibility;
const factory GridPropertyEvent.didReceiveFieldUpdate( const factory GridPropertyEvent.didReceiveFieldUpdate(List<FieldPB> fields) =
List<GridFieldPB> fields) = _DidReceiveFieldUpdate; _DidReceiveFieldUpdate;
const factory GridPropertyEvent.moveField(int fromIndex, int toIndex) = const factory GridPropertyEvent.moveField(int fromIndex, int toIndex) =
_MoveField; _MoveField;
} }
@ -77,10 +77,10 @@ class GridPropertyEvent with _$GridPropertyEvent {
class GridPropertyState with _$GridPropertyState { class GridPropertyState with _$GridPropertyState {
const factory GridPropertyState({ const factory GridPropertyState({
required String gridId, required String gridId,
required List<GridFieldPB> fields, required List<FieldPB> fields,
}) = _GridPropertyState; }) = _GridPropertyState;
factory GridPropertyState.initial(String gridId, List<GridFieldPB> fields) => factory GridPropertyState.initial(String gridId, List<FieldPB> fields) =>
GridPropertyState( GridPropertyState(
gridId: gridId, gridId: gridId,
fields: fields, fields: fields,

View File

@ -225,7 +225,7 @@ class _GridRowsState extends State<_GridRows> {
initialItemCount: context.read<GridBloc>().state.rowInfos.length, initialItemCount: context.read<GridBloc>().state.rowInfos.length,
itemBuilder: itemBuilder:
(BuildContext context, int index, Animation<double> animation) { (BuildContext context, int index, Animation<double> animation) {
final GridRowInfo rowInfo = final RowInfo rowInfo =
context.read<GridBloc>().state.rowInfos[index]; context.read<GridBloc>().state.rowInfos[index];
return _renderRow(context, rowInfo, animation); return _renderRow(context, rowInfo, animation);
}, },
@ -236,7 +236,7 @@ class _GridRowsState extends State<_GridRows> {
Widget _renderRow( Widget _renderRow(
BuildContext context, BuildContext context,
GridRowInfo rowInfo, RowInfo rowInfo,
Animation<double> animation, Animation<double> animation,
) { ) {
final rowCache = final rowCache =
@ -274,7 +274,7 @@ class _GridRowsState extends State<_GridRows> {
void _openRowDetailPage( void _openRowDetailPage(
BuildContext context, BuildContext context,
GridRowInfo rowInfo, RowInfo rowInfo,
GridFieldCache fieldCache, GridFieldCache fieldCache,
GridRowCache rowCache, GridRowCache rowCache,
GridCellBuilder cellBuilder, GridCellBuilder cellBuilder,

View File

@ -2,11 +2,15 @@ import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
import 'sizes.dart'; import 'sizes.dart';
class GridLayout { class GridLayout {
static double headerWidth(List<GridFieldPB> fields) { static double headerWidth(List<FieldPB> fields) {
if (fields.isEmpty) return 0; if (fields.isEmpty) return 0;
final fieldsWidth = fields.map((field) => field.width.toDouble()).reduce((value, element) => value + element); final fieldsWidth = fields
.map((field) => field.width.toDouble())
.reduce((value, element) => value + element);
return fieldsWidth + GridSize.leadingHeaderPadding + GridSize.trailHeaderPadding; return fieldsWidth +
GridSize.leadingHeaderPadding +
GridSize.trailHeaderPadding;
} }
} }

View File

@ -144,7 +144,7 @@ class _DragToExpandLine extends StatelessWidget {
class FieldCellButton extends StatelessWidget { class FieldCellButton extends StatelessWidget {
final VoidCallback onTap; final VoidCallback onTap;
final GridFieldPB field; final FieldPB field;
const FieldCellButton({ const FieldCellButton({
required this.field, required this.field,
required this.onTap, required this.onTap,

View File

@ -16,7 +16,7 @@ import 'field_type_extension.dart';
import 'field_type_list.dart'; import 'field_type_list.dart';
import 'type_option/builder.dart'; import 'type_option/builder.dart';
typedef UpdateFieldCallback = void Function(GridFieldPB, Uint8List); typedef UpdateFieldCallback = void Function(FieldPB, Uint8List);
typedef SwitchToFieldCallback typedef SwitchToFieldCallback
= Future<Either<FieldTypeOptionDataPB, FlowyError>> Function( = Future<Either<FieldTypeOptionDataPB, FlowyError>> Function(
String fieldId, String fieldId,
@ -64,7 +64,7 @@ class _FieldTypeOptionEditorState extends State<FieldTypeOptionEditor> {
); );
} }
Widget _switchFieldTypeButton(BuildContext context, GridFieldPB field) { Widget _switchFieldTypeButton(BuildContext context, FieldPB field) {
final theme = context.watch<AppTheme>(); final theme = context.watch<AppTheme>();
return SizedBox( return SizedBox(
height: GridSize.typeOptionItemHeight, height: GridSize.typeOptionItemHeight,

View File

@ -170,7 +170,7 @@ class CreateFieldButton extends StatelessWidget {
class SliverHeaderDelegateImplementation class SliverHeaderDelegateImplementation
extends SliverPersistentHeaderDelegate { extends SliverPersistentHeaderDelegate {
final String gridId; final String gridId;
final List<GridFieldPB> fields; final List<FieldPB> fields;
SliverHeaderDelegateImplementation( SliverHeaderDelegateImplementation(
{required this.gridId, required this.fields}); {required this.gridId, required this.fields});

View File

@ -131,7 +131,7 @@ TypeOptionWidgetBuilder makeTypeOptionWidgetBuilder({
TypeOptionContext<T> makeTypeOptionContext<T extends GeneratedMessage>({ TypeOptionContext<T> makeTypeOptionContext<T extends GeneratedMessage>({
required String gridId, required String gridId,
required GridFieldPB field, required FieldPB field,
}) { }) {
final loader = FieldTypeOptionLoader(gridId: gridId, field: field); final loader = FieldTypeOptionLoader(gridId: gridId, field: field);
final dataController = TypeOptionDataController( final dataController = TypeOptionDataController(

View File

@ -16,7 +16,7 @@ import '../cell/prelude.dart';
import 'row_action_sheet.dart'; import 'row_action_sheet.dart';
class GridRowWidget extends StatefulWidget { class GridRowWidget extends StatefulWidget {
final GridRowInfo rowInfo; final RowInfo rowInfo;
final GridRowDataController dataController; final GridRowDataController dataController;
final GridCellBuilder cellBuilder; final GridCellBuilder cellBuilder;
final void Function(BuildContext, GridCellBuilder) openDetailPage; final void Function(BuildContext, GridCellBuilder) openDetailPage;

View File

@ -15,7 +15,7 @@ import '../../../application/row/row_cache.dart';
import '../../layout/sizes.dart'; import '../../layout/sizes.dart';
class GridRowActionSheet extends StatelessWidget { class GridRowActionSheet extends StatelessWidget {
final GridRowInfo rowData; final RowInfo rowData;
const GridRowActionSheet({required this.rowData, Key? key}) : super(key: key); const GridRowActionSheet({required this.rowData, Key? key}) : super(key: key);
@override @override

View File

@ -78,7 +78,7 @@ class GridPropertyList extends StatelessWidget with FlowyOverlayDelegate {
} }
class _GridPropertyCell extends StatelessWidget { class _GridPropertyCell extends StatelessWidget {
final GridFieldPB field; final FieldPB field;
final String gridId; final String gridId;
const _GridPropertyCell({required this.gridId, required this.field, Key? key}) const _GridPropertyCell({required this.gridId, required this.field, Key? key})
: super(key: key); : super(key: key);

View File

@ -1632,7 +1632,7 @@ final Map<String, String> activities = Map.fromIterables([
'Flying Disc', 'Flying Disc',
'Bowling', 'Bowling',
'Cricket Game', 'Cricket Game',
'GridFieldPB Hockey', 'FieldPB Hockey',
'Ice Hockey', 'Ice Hockey',
'Lacrosse', 'Lacrosse',
'Ping Pong', 'Ping Pong',

View File

@ -4,24 +4,24 @@ use flowy_grid_data_model::parser::NotEmptyStr;
use flowy_grid_data_model::revision::RowRevision; use flowy_grid_data_model::revision::RowRevision;
use std::sync::Arc; use std::sync::Arc;
/// [GridBlockPB] contains list of row ids. The rows here does not contain any data, just the id /// [BlockPB] contains list of row ids. The rows here does not contain any data, just the id
/// of the row. Check out [GridRowPB] for more details. /// of the row. Check out [RowPB] for more details.
/// ///
/// ///
/// A grid can have many rows. Rows are therefore grouped into Blocks in order to make /// A grid can have many rows. Rows are therefore grouped into Blocks in order to make
/// things more efficient. /// things more efficient.
/// | /// |
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridBlockPB { pub struct BlockPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub rows: Vec<GridRowPB>, pub rows: Vec<RowPB>,
} }
impl GridBlockPB { impl BlockPB {
pub fn new(block_id: &str, rows: Vec<GridRowPB>) -> Self { pub fn new(block_id: &str, rows: Vec<RowPB>) -> Self {
Self { Self {
id: block_id.to_owned(), id: block_id.to_owned(),
rows, rows,
@ -29,9 +29,9 @@ impl GridBlockPB {
} }
} }
/// [GridRowPB] Describes a row. Has the id of the parent Block. Has the metadata of the row. /// [RowPB] Describes a row. Has the id of the parent Block. Has the metadata of the row.
#[derive(Debug, Default, Clone, ProtoBuf)] #[derive(Debug, Default, Clone, ProtoBuf)]
pub struct GridRowPB { pub struct RowPB {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
@ -42,7 +42,7 @@ pub struct GridRowPB {
pub height: i32, pub height: i32,
} }
impl GridRowPB { impl RowPB {
pub fn row_id(&self) -> &str { pub fn row_id(&self) -> &str {
&self.id &self.id
} }
@ -52,7 +52,7 @@ impl GridRowPB {
} }
} }
impl std::convert::From<&RowRevision> for GridRowPB { impl std::convert::From<&RowRevision> for RowPB {
fn from(rev: &RowRevision) -> Self { fn from(rev: &RowRevision) -> Self {
Self { Self {
block_id: rev.block_id.clone(), block_id: rev.block_id.clone(),
@ -62,7 +62,7 @@ impl std::convert::From<&RowRevision> for GridRowPB {
} }
} }
impl std::convert::From<&Arc<RowRevision>> for GridRowPB { impl std::convert::From<&Arc<RowRevision>> for RowPB {
fn from(rev: &Arc<RowRevision>) -> Self { fn from(rev: &Arc<RowRevision>) -> Self {
Self { Self {
block_id: rev.block_id.clone(), block_id: rev.block_id.clone(),
@ -75,30 +75,30 @@ impl std::convert::From<&Arc<RowRevision>> for GridRowPB {
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct OptionalRowPB { pub struct OptionalRowPB {
#[pb(index = 1, one_of)] #[pb(index = 1, one_of)]
pub row: Option<GridRowPB>, pub row: Option<RowPB>,
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedRowPB { pub struct RepeatedRowPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridRowPB>, pub items: Vec<RowPB>,
} }
impl std::convert::From<Vec<GridRowPB>> for RepeatedRowPB { impl std::convert::From<Vec<RowPB>> for RepeatedRowPB {
fn from(items: Vec<GridRowPB>) -> Self { fn from(items: Vec<RowPB>) -> Self {
Self { items } Self { items }
} }
} }
/// [RepeatedGridBlockPB] contains list of [GridBlockPB] /// [RepeatedBlockPB] contains list of [BlockPB]
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedGridBlockPB { pub struct RepeatedBlockPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridBlockPB>, pub items: Vec<BlockPB>,
} }
impl std::convert::From<Vec<GridBlockPB>> for RepeatedGridBlockPB { impl std::convert::From<Vec<BlockPB>> for RepeatedBlockPB {
fn from(items: Vec<GridBlockPB>) -> Self { fn from(items: Vec<BlockPB>) -> Self {
Self { items } Self { items }
} }
} }
@ -127,11 +127,11 @@ pub struct UpdatedRowPB {
pub row_id: String, pub row_id: String,
#[pb(index = 3)] #[pb(index = 3)]
pub row: GridRowPB, pub row: RowPB,
} }
impl UpdatedRowPB { impl UpdatedRowPB {
pub fn new(row_rev: &RowRevision, row: GridRowPB) -> Self { pub fn new(row_rev: &RowRevision, row: RowPB) -> Self {
Self { Self {
row_id: row_rev.id.clone(), row_id: row_rev.id.clone(),
block_id: row_rev.block_id.clone(), block_id: row_rev.block_id.clone(),
@ -140,8 +140,8 @@ impl UpdatedRowPB {
} }
} }
impl std::convert::From<GridRowPB> for InsertedRowPB { impl std::convert::From<RowPB> for InsertedRowPB {
fn from(row_info: GridRowPB) -> Self { fn from(row_info: RowPB) -> Self {
Self { Self {
row_id: row_info.id, row_id: row_info.id,
block_id: row_info.block_id, block_id: row_info.block_id,
@ -153,7 +153,7 @@ impl std::convert::From<GridRowPB> for InsertedRowPB {
impl std::convert::From<&RowRevision> for InsertedRowPB { impl std::convert::From<&RowRevision> for InsertedRowPB {
fn from(row: &RowRevision) -> Self { fn from(row: &RowRevision) -> Self {
let row_order = GridRowPB::from(row); let row_order = RowPB::from(row);
Self::from(row_order) Self::from(row_order)
} }
} }
@ -204,10 +204,10 @@ impl GridBlockChangesetPB {
} }
} }
/// [QueryGridBlocksPayloadPB] is used to query the data of the block that belongs to the grid whose /// [QueryBlocksPayloadPB] is used to query the data of the block that belongs to the grid whose
/// id is grid_id. /// id is grid_id.
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct QueryGridBlocksPayloadPB { pub struct QueryBlocksPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -220,7 +220,7 @@ pub struct QueryGridBlocksParams {
pub block_ids: Vec<String>, pub block_ids: Vec<String>,
} }
impl TryInto<QueryGridBlocksParams> for QueryGridBlocksPayloadPB { impl TryInto<QueryGridBlocksParams> for QueryBlocksPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<QueryGridBlocksParams, Self::Error> { fn try_into(self) -> Result<QueryGridBlocksParams, Self::Error> {

View File

@ -8,9 +8,9 @@ use std::sync::Arc;
use strum_macros::{Display, EnumCount as EnumCountMacro, EnumIter, EnumString}; use strum_macros::{Display, EnumCount as EnumCountMacro, EnumIter, EnumString};
/// [GridFieldPB] defines a Field's attributes. Such as the name, field_type, and width. etc. /// [FieldPB] defines a Field's attributes. Such as the name, field_type, and width. etc.
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridFieldPB { pub struct FieldPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
@ -36,7 +36,7 @@ pub struct GridFieldPB {
pub is_primary: bool, pub is_primary: bool,
} }
impl std::convert::From<FieldRevision> for GridFieldPB { impl std::convert::From<FieldRevision> for FieldPB {
fn from(field_rev: FieldRevision) -> Self { fn from(field_rev: FieldRevision) -> Self {
Self { Self {
id: field_rev.id, id: field_rev.id,
@ -51,33 +51,33 @@ impl std::convert::From<FieldRevision> for GridFieldPB {
} }
} }
impl std::convert::From<Arc<FieldRevision>> for GridFieldPB { impl std::convert::From<Arc<FieldRevision>> for FieldPB {
fn from(field_rev: Arc<FieldRevision>) -> Self { fn from(field_rev: Arc<FieldRevision>) -> Self {
let field_rev = field_rev.as_ref().clone(); let field_rev = field_rev.as_ref().clone();
GridFieldPB::from(field_rev) FieldPB::from(field_rev)
} }
} }
/// [GridFieldIdPB] id of the [Field] /// [FieldIdPB] id of the [Field]
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridFieldIdPB { pub struct FieldIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
} }
impl std::convert::From<&str> for GridFieldIdPB { impl std::convert::From<&str> for FieldIdPB {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
GridFieldIdPB { field_id: s.to_owned() } FieldIdPB { field_id: s.to_owned() }
} }
} }
impl std::convert::From<String> for GridFieldIdPB { impl std::convert::From<String> for FieldIdPB {
fn from(s: String) -> Self { fn from(s: String) -> Self {
GridFieldIdPB { field_id: s } FieldIdPB { field_id: s }
} }
} }
impl std::convert::From<&Arc<FieldRevision>> for GridFieldIdPB { impl std::convert::From<&Arc<FieldRevision>> for FieldIdPB {
fn from(field_rev: &Arc<FieldRevision>) -> Self { fn from(field_rev: &Arc<FieldRevision>) -> Self {
Self { Self {
field_id: field_rev.id.clone(), field_id: field_rev.id.clone(),
@ -85,7 +85,7 @@ impl std::convert::From<&Arc<FieldRevision>> for GridFieldIdPB {
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridFieldChangesetPB { pub struct FieldChangesetPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -93,13 +93,13 @@ pub struct GridFieldChangesetPB {
pub inserted_fields: Vec<IndexFieldPB>, pub inserted_fields: Vec<IndexFieldPB>,
#[pb(index = 3)] #[pb(index = 3)]
pub deleted_fields: Vec<GridFieldIdPB>, pub deleted_fields: Vec<FieldIdPB>,
#[pb(index = 4)] #[pb(index = 4)]
pub updated_fields: Vec<GridFieldPB>, pub updated_fields: Vec<FieldPB>,
} }
impl GridFieldChangesetPB { impl FieldChangesetPB {
pub fn insert(grid_id: &str, inserted_fields: Vec<IndexFieldPB>) -> Self { pub fn insert(grid_id: &str, inserted_fields: Vec<IndexFieldPB>) -> Self {
Self { Self {
grid_id: grid_id.to_owned(), grid_id: grid_id.to_owned(),
@ -109,7 +109,7 @@ impl GridFieldChangesetPB {
} }
} }
pub fn delete(grid_id: &str, deleted_fields: Vec<GridFieldIdPB>) -> Self { pub fn delete(grid_id: &str, deleted_fields: Vec<FieldIdPB>) -> Self {
Self { Self {
grid_id: grid_id.to_string(), grid_id: grid_id.to_string(),
inserted_fields: vec![], inserted_fields: vec![],
@ -118,7 +118,7 @@ impl GridFieldChangesetPB {
} }
} }
pub fn update(grid_id: &str, updated_fields: Vec<GridFieldPB>) -> Self { pub fn update(grid_id: &str, updated_fields: Vec<FieldPB>) -> Self {
Self { Self {
grid_id: grid_id.to_string(), grid_id: grid_id.to_string(),
inserted_fields: vec![], inserted_fields: vec![],
@ -131,7 +131,7 @@ impl GridFieldChangesetPB {
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct IndexFieldPB { pub struct IndexFieldPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field: GridFieldPB, pub field: FieldPB,
#[pb(index = 2)] #[pb(index = 2)]
pub index: i32, pub index: i32,
@ -140,7 +140,7 @@ pub struct IndexFieldPB {
impl IndexFieldPB { impl IndexFieldPB {
pub fn from_field_rev(field_rev: &Arc<FieldRevision>, index: usize) -> Self { pub fn from_field_rev(field_rev: &Arc<FieldRevision>, index: usize) -> Self {
Self { Self {
field: GridFieldPB::from(field_rev.as_ref().clone()), field: FieldPB::from(field_rev.as_ref().clone()),
index: index as i32, index: index as i32,
} }
} }
@ -220,7 +220,7 @@ impl TryInto<EditFieldParams> for EditFieldPayloadPB {
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct GridFieldTypeOptionIdPB { pub struct FieldTypeOptionIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -231,19 +231,19 @@ pub struct GridFieldTypeOptionIdPB {
pub field_type: FieldType, pub field_type: FieldType,
} }
pub struct GridFieldTypeOptionIdParams { pub struct FieldTypeOptionIdParams {
pub grid_id: String, pub grid_id: String,
pub field_id: String, pub field_id: String,
pub field_type: FieldType, pub field_type: FieldType,
} }
impl TryInto<GridFieldTypeOptionIdParams> for GridFieldTypeOptionIdPB { impl TryInto<FieldTypeOptionIdParams> for FieldTypeOptionIdPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<GridFieldTypeOptionIdParams, Self::Error> { fn try_into(self) -> Result<FieldTypeOptionIdParams, Self::Error> {
let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
Ok(GridFieldTypeOptionIdParams { Ok(FieldTypeOptionIdParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,
field_type: self.field_type, field_type: self.field_type,
@ -264,60 +264,60 @@ pub struct FieldTypeOptionDataPB {
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field: GridFieldPB, pub field: FieldPB,
#[pb(index = 3)] #[pb(index = 3)]
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
} }
/// Collection of the [GridFieldPB] /// Collection of the [FieldPB]
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedGridFieldPB { pub struct RepeatedFieldPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridFieldPB>, pub items: Vec<FieldPB>,
} }
impl std::ops::Deref for RepeatedGridFieldPB { impl std::ops::Deref for RepeatedFieldPB {
type Target = Vec<GridFieldPB>; type Target = Vec<FieldPB>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.items &self.items
} }
} }
impl std::ops::DerefMut for RepeatedGridFieldPB { impl std::ops::DerefMut for RepeatedFieldPB {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.items &mut self.items
} }
} }
impl std::convert::From<Vec<GridFieldPB>> for RepeatedGridFieldPB { impl std::convert::From<Vec<FieldPB>> for RepeatedFieldPB {
fn from(items: Vec<GridFieldPB>) -> Self { fn from(items: Vec<FieldPB>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct RepeatedGridFieldIdPB { pub struct RepeatedFieldIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridFieldIdPB>, pub items: Vec<FieldIdPB>,
} }
impl std::ops::Deref for RepeatedGridFieldIdPB { impl std::ops::Deref for RepeatedFieldIdPB {
type Target = Vec<GridFieldIdPB>; type Target = Vec<FieldIdPB>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.items &self.items
} }
} }
impl std::convert::From<Vec<GridFieldIdPB>> for RepeatedGridFieldIdPB { impl std::convert::From<Vec<FieldIdPB>> for RepeatedFieldIdPB {
fn from(items: Vec<GridFieldIdPB>) -> Self { fn from(items: Vec<FieldIdPB>) -> Self {
RepeatedGridFieldIdPB { items } RepeatedFieldIdPB { items }
} }
} }
impl std::convert::From<String> for RepeatedGridFieldIdPB { impl std::convert::From<String> for RepeatedFieldIdPB {
fn from(s: String) -> Self { fn from(s: String) -> Self {
RepeatedGridFieldIdPB { RepeatedFieldIdPB {
items: vec![GridFieldIdPB::from(s)], items: vec![FieldIdPB::from(s)],
} }
} }
} }
@ -328,7 +328,7 @@ pub struct InsertFieldPayloadPB {
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field: GridFieldPB, pub field: FieldPB,
#[pb(index = 3)] #[pb(index = 3)]
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
@ -340,7 +340,7 @@ pub struct InsertFieldPayloadPB {
#[derive(Clone)] #[derive(Clone)]
pub struct InsertFieldParams { pub struct InsertFieldParams {
pub grid_id: String, pub grid_id: String,
pub field: GridFieldPB, pub field: FieldPB,
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
pub start_field_id: Option<String>, pub start_field_id: Option<String>,
} }
@ -408,12 +408,12 @@ pub struct QueryFieldPayloadPB {
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field_ids: RepeatedGridFieldIdPB, pub field_ids: RepeatedFieldIdPB,
} }
pub struct QueryFieldParams { pub struct QueryFieldParams {
pub grid_id: String, pub grid_id: String,
pub field_ids: RepeatedGridFieldIdPB, pub field_ids: RepeatedFieldIdPB,
} }
impl TryInto<QueryFieldParams> for QueryFieldPayloadPB { impl TryInto<QueryFieldParams> for QueryFieldPayloadPB {
@ -633,13 +633,13 @@ pub struct GridFieldIdentifierPayloadPB {
pub grid_id: String, pub grid_id: String,
} }
impl TryInto<GridFieldIdParams> for DuplicateFieldPayloadPB { impl TryInto<FieldIdParams> for DuplicateFieldPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<GridFieldIdParams, Self::Error> { fn try_into(self) -> Result<FieldIdParams, Self::Error> {
let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
Ok(GridFieldIdParams { Ok(FieldIdParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,
}) })
@ -655,20 +655,20 @@ pub struct DeleteFieldPayloadPB {
pub grid_id: String, pub grid_id: String,
} }
impl TryInto<GridFieldIdParams> for DeleteFieldPayloadPB { impl TryInto<FieldIdParams> for DeleteFieldPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<GridFieldIdParams, Self::Error> { fn try_into(self) -> Result<FieldIdParams, Self::Error> {
let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
Ok(GridFieldIdParams { Ok(FieldIdParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,
}) })
} }
} }
pub struct GridFieldIdParams { pub struct FieldIdParams {
pub field_id: String, pub field_id: String,
pub grid_id: String, pub grid_id: String,
} }

View File

@ -1,4 +1,4 @@
use crate::entities::{GridBlockPB, GridFieldIdPB}; use crate::entities::{BlockPB, FieldIdPB};
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr; use flowy_grid_data_model::parser::NotEmptyStr;
@ -10,10 +10,10 @@ pub struct GridPB {
pub id: String, pub id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub fields: Vec<GridFieldIdPB>, pub fields: Vec<FieldIdPB>,
#[pb(index = 3)] #[pb(index = 3)]
pub blocks: Vec<GridBlockPB>, pub blocks: Vec<BlockPB>,
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]

View File

@ -1,4 +1,4 @@
use crate::entities::{FieldType, GridRowPB}; use crate::entities::{FieldType, RowPB};
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr; use flowy_grid_data_model::parser::NotEmptyStr;
@ -44,7 +44,7 @@ pub struct GroupPB {
pub desc: String, pub desc: String,
#[pb(index = 3)] #[pb(index = 3)]
pub rows: Vec<GridRowPB>, pub rows: Vec<RowPB>,
} }
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]

View File

@ -3,7 +3,7 @@ use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr; use flowy_grid_data_model::parser::NotEmptyStr;
#[derive(Debug, Default, Clone, ProtoBuf)] #[derive(Debug, Default, Clone, ProtoBuf)]
pub struct GridRowIdPB { pub struct RowIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -14,21 +14,21 @@ pub struct GridRowIdPB {
pub row_id: String, pub row_id: String,
} }
pub struct GridRowIdParams { pub struct RowIdParams {
pub grid_id: String, pub grid_id: String,
pub block_id: String, pub block_id: String,
pub row_id: String, pub row_id: String,
} }
impl TryInto<GridRowIdParams> for GridRowIdPB { impl TryInto<RowIdParams> for RowIdPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<GridRowIdParams, Self::Error> { fn try_into(self) -> Result<RowIdParams, Self::Error> {
let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let block_id = NotEmptyStr::parse(self.block_id).map_err(|_| ErrorCode::BlockIdIsEmpty)?; let block_id = NotEmptyStr::parse(self.block_id).map_err(|_| ErrorCode::BlockIdIsEmpty)?;
let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?; let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;
Ok(GridRowIdParams { Ok(RowIdParams {
grid_id: grid_id.0, grid_id: grid_id.0,
block_id: block_id.0, block_id: block_id.0,
row_id: row_id.0, row_id: row_id.0,

View File

@ -49,9 +49,9 @@ pub(crate) async fn update_grid_setting_handler(
#[tracing::instrument(level = "debug", skip(data, manager), err)] #[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn get_grid_blocks_handler( pub(crate) async fn get_grid_blocks_handler(
data: Data<QueryGridBlocksPayloadPB>, data: Data<QueryBlocksPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<RepeatedGridBlockPB, FlowyError> { ) -> DataResult<RepeatedBlockPB, FlowyError> {
let params: QueryGridBlocksParams = data.into_inner().try_into()?; let params: QueryGridBlocksParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let repeated_grid_block = editor.get_blocks(Some(params.block_ids)).await?; let repeated_grid_block = editor.get_blocks(Some(params.block_ids)).await?;
@ -62,7 +62,7 @@ pub(crate) async fn get_grid_blocks_handler(
pub(crate) async fn get_fields_handler( pub(crate) async fn get_fields_handler(
data: Data<QueryFieldPayloadPB>, data: Data<QueryFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<RepeatedGridFieldPB, FlowyError> { ) -> DataResult<RepeatedFieldPB, FlowyError> {
let params: QueryFieldParams = data.into_inner().try_into()?; let params: QueryFieldParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let field_orders = params let field_orders = params
@ -72,7 +72,7 @@ pub(crate) async fn get_fields_handler(
.map(|field_order| field_order.field_id) .map(|field_order| field_order.field_id)
.collect(); .collect();
let field_revs = editor.get_field_revs(Some(field_orders)).await?; let field_revs = editor.get_field_revs(Some(field_orders)).await?;
let repeated_field: RepeatedGridFieldPB = field_revs.into_iter().map(GridFieldPB::from).collect::<Vec<_>>().into(); let repeated_field: RepeatedFieldPB = field_revs.into_iter().map(FieldPB::from).collect::<Vec<_>>().into();
data_result(repeated_field) data_result(repeated_field)
} }
@ -116,7 +116,7 @@ pub(crate) async fn delete_field_handler(
data: Data<DeleteFieldPayloadPB>, data: Data<DeleteFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridFieldIdParams = data.into_inner().try_into()?; let params: FieldIdParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let _ = editor.delete_field(&params.field_id).await?; let _ = editor.delete_field(&params.field_id).await?;
Ok(()) Ok(())
@ -154,7 +154,7 @@ pub(crate) async fn duplicate_field_handler(
data: Data<DuplicateFieldPayloadPB>, data: Data<DuplicateFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridFieldIdParams = data.into_inner().try_into()?; let params: FieldIdParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let _ = editor.duplicate_field(&params.field_id).await?; let _ = editor.duplicate_field(&params.field_id).await?;
Ok(()) Ok(())
@ -163,10 +163,10 @@ pub(crate) async fn duplicate_field_handler(
/// Return the FieldTypeOptionData if the Field exists otherwise return record not found error. /// Return the FieldTypeOptionData if the Field exists otherwise return record not found error.
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_field_type_option_data_handler( pub(crate) async fn get_field_type_option_data_handler(
data: Data<GridFieldTypeOptionIdPB>, data: Data<FieldTypeOptionIdPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionDataPB, FlowyError> { ) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: GridFieldTypeOptionIdParams = data.into_inner().try_into()?; let params: FieldTypeOptionIdParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
match editor.get_field_rev(&params.field_id).await { match editor.get_field_rev(&params.field_id).await {
None => Err(FlowyError::record_not_found()), None => Err(FlowyError::record_not_found()),
@ -227,10 +227,10 @@ async fn get_type_option_data(field_rev: &FieldRevision, field_type: &FieldType)
#[tracing::instrument(level = "debug", skip(data, manager), err)] #[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn get_row_handler( pub(crate) async fn get_row_handler(
data: Data<GridRowIdPB>, data: Data<RowIdPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<OptionalRowPB, FlowyError> { ) -> DataResult<OptionalRowPB, FlowyError> {
let params: GridRowIdParams = data.into_inner().try_into()?; let params: RowIdParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let row = editor let row = editor
.get_row_rev(&params.row_id) .get_row_rev(&params.row_id)
@ -242,10 +242,10 @@ pub(crate) async fn get_row_handler(
#[tracing::instrument(level = "debug", skip(data, manager), err)] #[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn delete_row_handler( pub(crate) async fn delete_row_handler(
data: Data<GridRowIdPB>, data: Data<RowIdPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridRowIdParams = data.into_inner().try_into()?; let params: RowIdParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let _ = editor.delete_row(&params.row_id).await?; let _ = editor.delete_row(&params.row_id).await?;
Ok(()) Ok(())
@ -253,10 +253,10 @@ pub(crate) async fn delete_row_handler(
#[tracing::instrument(level = "debug", skip(data, manager), err)] #[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn duplicate_row_handler( pub(crate) async fn duplicate_row_handler(
data: Data<GridRowIdPB>, data: Data<RowIdPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridRowIdParams = data.into_inner().try_into()?; let params: RowIdParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
let _ = editor.duplicate_row(&params.row_id).await?; let _ = editor.duplicate_row(&params.row_id).await?;
Ok(()) Ok(())

View File

@ -57,9 +57,9 @@ pub enum GridEvent {
/// [GetGridBlocks] event is used to get the grid's block. /// [GetGridBlocks] event is used to get the grid's block.
/// ///
/// The event handler accepts a [QueryGridBlocksPayloadPB] and returns a [RepeatedGridBlockPB] /// The event handler accepts a [QueryBlocksPayloadPB] and returns a [RepeatedBlockPB]
/// if there are no errors. /// if there are no errors.
#[event(input = "QueryGridBlocksPayloadPB", output = "RepeatedGridBlockPB")] #[event(input = "QueryBlocksPayloadPB", output = "RepeatedBlockPB")]
GetGridBlocks = 1, GetGridBlocks = 1,
/// [GetGridSetting] event is used to get the grid's settings. /// [GetGridSetting] event is used to get the grid's settings.
@ -77,9 +77,9 @@ pub enum GridEvent {
/// [GetFields] event is used to get the grid's settings. /// [GetFields] event is used to get the grid's settings.
/// ///
/// The event handler accepts a [QueryFieldPayloadPB] and returns a [RepeatedGridFieldPB] /// The event handler accepts a [QueryFieldPayloadPB] and returns a [RepeatedFieldPB]
/// if there are no errors. /// if there are no errors.
#[event(input = "QueryFieldPayloadPB", output = "RepeatedGridFieldPB")] #[event(input = "QueryFieldPayloadPB", output = "RepeatedFieldPB")]
GetFields = 10, GetFields = 10,
/// [UpdateField] event is used to update a field's attributes. /// [UpdateField] event is used to update a field's attributes.
@ -132,13 +132,13 @@ pub enum GridEvent {
#[event(input = "MoveItemPayloadPB")] #[event(input = "MoveItemPayloadPB")]
MoveItem = 22, MoveItem = 22,
/// [GetFieldTypeOption] event is used to get the FieldTypeOption data for a specific field type. /// [FieldTypeOptionIdPB] event is used to get the FieldTypeOption data for a specific field type.
/// ///
/// Check out the [FieldTypeOptionDataPB] for more details. If the [FieldTypeOptionData] does exist /// Check out the [FieldTypeOptionDataPB] for more details. If the [FieldTypeOptionData] does exist
/// for the target type, the [TypeOptionBuilder] will create the default data for that type. /// for the target type, the [TypeOptionBuilder] will create the default data for that type.
/// ///
/// Return the [FieldTypeOptionDataPB] if there are no errors. /// Return the [FieldTypeOptionDataPB] if there are no errors.
#[event(input = "GridFieldTypeOptionIdPB", output = "FieldTypeOptionDataPB")] #[event(input = "FieldTypeOptionIdPB", output = "FieldTypeOptionDataPB")]
GetFieldTypeOption = 23, GetFieldTypeOption = 23,
/// [CreateFieldTypeOption] event is used to create a new FieldTypeOptionData. /// [CreateFieldTypeOption] event is used to create a new FieldTypeOptionData.
@ -165,18 +165,18 @@ pub enum GridEvent {
#[event(input = "SelectOptionChangesetPayloadPB")] #[event(input = "SelectOptionChangesetPayloadPB")]
UpdateSelectOption = 32, UpdateSelectOption = 32,
#[event(input = "CreateRowPayloadPB", output = "GridRowPB")] #[event(input = "CreateRowPayloadPB", output = "RowPB")]
CreateRow = 50, CreateRow = 50,
/// [GetRow] event is used to get the row data,[GridRowPB]. [OptionalRowPB] is a wrapper that enables /// [GetRow] event is used to get the row data,[RowPB]. [OptionalRowPB] is a wrapper that enables
/// to return a nullable row data. /// to return a nullable row data.
#[event(input = "GridRowIdPB", output = "OptionalRowPB")] #[event(input = "RowIdPB", output = "OptionalRowPB")]
GetRow = 51, GetRow = 51,
#[event(input = "GridRowIdPB")] #[event(input = "RowIdPB")]
DeleteRow = 52, DeleteRow = 52,
#[event(input = "GridRowIdPB")] #[event(input = "RowIdPB")]
DuplicateRow = 53, DuplicateRow = 53,
#[event(input = "GridCellIdPB", output = "GridCellPB")] #[event(input = "GridCellIdPB", output = "GridCellPB")]

View File

@ -1,5 +1,5 @@
use crate::dart_notification::{send_dart_notification, GridNotification}; use crate::dart_notification::{send_dart_notification, GridNotification};
use crate::entities::{CellChangesetPB, GridBlockChangesetPB, GridRowPB, InsertedRowPB, UpdatedRowPB}; use crate::entities::{CellChangesetPB, GridBlockChangesetPB, InsertedRowPB, RowPB, UpdatedRowPB};
use crate::manager::GridUser; use crate::manager::GridUser;
use crate::services::block_revision_editor::{GridBlockRevisionCompactor, GridBlockRevisionEditor}; use crate::services::block_revision_editor::{GridBlockRevisionCompactor, GridBlockRevisionEditor};
use crate::services::persistence::block_index::BlockIndexCache; use crate::services::persistence::block_index::BlockIndexCache;
@ -110,7 +110,7 @@ impl GridBlockManager {
pub async fn update_row<F>(&self, changeset: RowMetaChangeset, row_builder: F) -> FlowyResult<()> pub async fn update_row<F>(&self, changeset: RowMetaChangeset, row_builder: F) -> FlowyResult<()>
where where
F: FnOnce(Arc<RowRevision>) -> Option<GridRowPB>, F: FnOnce(Arc<RowRevision>) -> Option<RowPB>,
{ {
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?;
@ -146,10 +146,7 @@ impl GridBlockManager {
Ok(()) Ok(())
} }
pub(crate) async fn delete_rows( pub(crate) async fn delete_rows(&self, row_orders: Vec<RowPB>) -> FlowyResult<Vec<GridBlockMetaRevisionChangeset>> {
&self,
row_orders: Vec<GridRowPB>,
) -> FlowyResult<Vec<GridBlockMetaRevisionChangeset>> {
let mut changesets = vec![]; let mut changesets = vec![];
for grid_block in block_from_row_orders(row_orders) { for grid_block in block_from_row_orders(row_orders) {
let editor = self.get_editor(&grid_block.id).await?; let editor = self.get_editor(&grid_block.id).await?;
@ -198,7 +195,7 @@ impl GridBlockManager {
pub async fn update_cell<F>(&self, changeset: CellChangesetPB, row_builder: F) -> FlowyResult<()> pub async fn update_cell<F>(&self, changeset: CellChangesetPB, row_builder: F) -> FlowyResult<()>
where where
F: FnOnce(Arc<RowRevision>) -> Option<GridRowPB>, F: FnOnce(Arc<RowRevision>) -> Option<RowPB>,
{ {
let row_changeset: RowMetaChangeset = changeset.clone().into(); let row_changeset: RowMetaChangeset = changeset.clone().into();
let _ = self.update_row(row_changeset, row_builder).await?; let _ = self.update_row(row_changeset, row_builder).await?;
@ -217,7 +214,7 @@ impl GridBlockManager {
} }
} }
pub async fn get_row_orders(&self, block_id: &str) -> FlowyResult<Vec<GridRowPB>> { pub async fn get_row_orders(&self, block_id: &str) -> FlowyResult<Vec<RowPB>> {
let editor = self.get_editor(block_id).await?; let editor = self.get_editor(block_id).await?;
editor.get_row_infos::<&str>(None).await editor.get_row_infos::<&str>(None).await
} }

View File

@ -1,4 +1,4 @@
use crate::entities::GridRowPB; use crate::entities::RowPB;
use bytes::Bytes; use bytes::Bytes;
use flowy_error::{FlowyError, FlowyResult}; use flowy_error::{FlowyError, FlowyResult};
use flowy_grid_data_model::revision::{CellRevision, GridBlockRevision, RowMetaChangeset, RowRevision}; use flowy_grid_data_model::revision::{CellRevision, GridBlockRevision, RowMetaChangeset, RowRevision};
@ -123,12 +123,12 @@ impl GridBlockRevisionEditor {
Ok(cell_revs) Ok(cell_revs)
} }
pub async fn get_row_info(&self, row_id: &str) -> FlowyResult<Option<GridRowPB>> { pub async fn get_row_info(&self, row_id: &str) -> FlowyResult<Option<RowPB>> {
let row_ids = Some(vec![Cow::Borrowed(row_id)]); let row_ids = Some(vec![Cow::Borrowed(row_id)]);
Ok(self.get_row_infos(row_ids).await?.pop()) Ok(self.get_row_infos(row_ids).await?.pop())
} }
pub async fn get_row_infos<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<GridRowPB>> pub async fn get_row_infos<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<RowPB>>
where where
T: AsRef<str> + ToOwned + ?Sized, T: AsRef<str> + ToOwned + ?Sized,
{ {
@ -138,8 +138,8 @@ impl GridBlockRevisionEditor {
.await .await
.get_row_revs(row_ids)? .get_row_revs(row_ids)?
.iter() .iter()
.map(GridRowPB::from) .map(RowPB::from)
.collect::<Vec<GridRowPB>>(); .collect::<Vec<RowPB>>();
Ok(row_infos) Ok(row_infos)
} }

View File

@ -1,4 +1,4 @@
use crate::entities::{FieldType, GridFieldPB}; use crate::entities::{FieldPB, FieldType};
use crate::services::field::type_options::*; use crate::services::field::type_options::*;
use bytes::Bytes; use bytes::Bytes;
use flowy_grid_data_model::revision::{FieldRevision, TypeOptionDataEntry}; use flowy_grid_data_model::revision::{FieldRevision, TypeOptionDataEntry};
@ -28,7 +28,7 @@ impl FieldBuilder {
Self::new(type_option_builder) Self::new(type_option_builder)
} }
pub fn from_field(field: GridFieldPB, type_option_builder: Box<dyn TypeOptionBuilder>) -> Self { pub fn from_field(field: FieldPB, type_option_builder: Box<dyn TypeOptionBuilder>) -> Self {
let field_rev = FieldRevision { let field_rev = FieldRevision {
id: field.id, id: field.id,
name: field.name, name: field.name,

View File

@ -192,8 +192,8 @@ impl GridRevisionEditor {
pub async fn delete_field(&self, field_id: &str) -> FlowyResult<()> { pub async fn delete_field(&self, field_id: &str) -> FlowyResult<()> {
let _ = self.modify(|grid_pad| Ok(grid_pad.delete_field_rev(field_id)?)).await?; let _ = self.modify(|grid_pad| Ok(grid_pad.delete_field_rev(field_id)?)).await?;
let field_order = GridFieldIdPB::from(field_id); let field_order = FieldIdPB::from(field_id);
let notified_changeset = GridFieldChangesetPB::delete(&self.grid_id, vec![field_order]); let notified_changeset = FieldChangesetPB::delete(&self.grid_id, vec![field_order]);
let _ = self.notify_did_update_grid(notified_changeset).await?; let _ = self.notify_did_update_grid(notified_changeset).await?;
Ok(()) Ok(())
} }
@ -272,13 +272,13 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<GridRowPB> { pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<RowPB> {
let field_revs = self.grid_pad.read().await.get_field_revs(None)?; let field_revs = self.grid_pad.read().await.get_field_revs(None)?;
let block_id = self.block_id().await?; let block_id = self.block_id().await?;
// insert empty row below the row whose id is upper_row_id // insert empty row below the row whose id is upper_row_id
let row_rev = RowRevisionBuilder::new(&block_id, &field_revs).build(); let row_rev = RowRevisionBuilder::new(&block_id, &field_revs).build();
let row_order = GridRowPB::from(&row_rev); let row_order = RowPB::from(&row_rev);
// insert the row // insert the row
let row_count = self.block_manager.create_row(&block_id, row_rev, start_row_id).await?; let row_count = self.block_manager.create_row(&block_id, row_rev, start_row_id).await?;
@ -289,12 +289,12 @@ impl GridRevisionEditor {
Ok(row_order) Ok(row_order)
} }
pub async fn insert_rows(&self, row_revs: Vec<RowRevision>) -> FlowyResult<Vec<GridRowPB>> { pub async fn insert_rows(&self, row_revs: Vec<RowRevision>) -> FlowyResult<Vec<RowPB>> {
let block_id = self.block_id().await?; let block_id = self.block_id().await?;
let mut rows_by_block_id: HashMap<String, Vec<RowRevision>> = HashMap::new(); let mut rows_by_block_id: HashMap<String, Vec<RowRevision>> = HashMap::new();
let mut row_orders = vec![]; let mut row_orders = vec![];
for row_rev in row_revs { for row_rev in row_revs {
row_orders.push(GridRowPB::from(&row_rev)); row_orders.push(RowPB::from(&row_rev));
rows_by_block_id rows_by_block_id
.entry(block_id.clone()) .entry(block_id.clone())
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
@ -406,7 +406,7 @@ impl GridRevisionEditor {
} }
} }
pub async fn get_blocks(&self, block_ids: Option<Vec<String>>) -> FlowyResult<RepeatedGridBlockPB> { pub async fn get_blocks(&self, block_ids: Option<Vec<String>>) -> FlowyResult<RepeatedBlockPB> {
let block_snapshots = self.grid_block_snapshots(block_ids.clone()).await?; let block_snapshots = self.grid_block_snapshots(block_ids.clone()).await?;
make_grid_blocks(block_ids, block_snapshots) make_grid_blocks(block_ids, block_snapshots)
} }
@ -416,7 +416,7 @@ impl GridRevisionEditor {
Ok(block_meta_revs) Ok(block_meta_revs)
} }
pub async fn delete_rows(&self, row_orders: Vec<GridRowPB>) -> FlowyResult<()> { pub async fn delete_rows(&self, row_orders: Vec<RowPB>) -> FlowyResult<()> {
let changesets = self.block_manager.delete_rows(row_orders).await?; let changesets = self.block_manager.delete_rows(row_orders).await?;
for changeset in changesets { for changeset in changesets {
let _ = self.update_block(changeset).await?; let _ = self.update_block(changeset).await?;
@ -429,12 +429,12 @@ impl GridRevisionEditor {
let field_orders = pad_read_guard let field_orders = pad_read_guard
.get_field_revs(None)? .get_field_revs(None)?
.iter() .iter()
.map(GridFieldIdPB::from) .map(FieldIdPB::from)
.collect(); .collect();
let mut block_orders = vec![]; let mut block_orders = vec![];
for block_rev in pad_read_guard.get_block_meta_revs() { for block_rev in pad_read_guard.get_block_meta_revs() {
let row_orders = self.block_manager.get_row_orders(&block_rev.block_id).await?; let row_orders = self.block_manager.get_row_orders(&block_rev.block_id).await?;
let block_order = GridBlockPB { let block_order = BlockPB {
id: block_rev.block_id.clone(), id: block_rev.block_id.clone(),
rows: row_orders, rows: row_orders,
}; };
@ -512,9 +512,9 @@ impl GridRevisionEditor {
.modify(|grid_pad| Ok(grid_pad.move_field(field_id, from as usize, to as usize)?)) .modify(|grid_pad| Ok(grid_pad.move_field(field_id, from as usize, to as usize)?))
.await?; .await?;
if let Some((index, field_rev)) = self.grid_pad.read().await.get_field_rev(field_id) { if let Some((index, field_rev)) = self.grid_pad.read().await.get_field_rev(field_id) {
let delete_field_order = GridFieldIdPB::from(field_id); let delete_field_order = FieldIdPB::from(field_id);
let insert_field = IndexFieldPB::from_field_rev(field_rev, index); let insert_field = IndexFieldPB::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangesetPB { let notified_changeset = FieldChangesetPB {
grid_id: self.grid_id.clone(), grid_id: self.grid_id.clone(),
inserted_fields: vec![insert_field], inserted_fields: vec![insert_field],
deleted_fields: vec![delete_field_order], deleted_fields: vec![delete_field_order],
@ -605,7 +605,7 @@ impl GridRevisionEditor {
async fn notify_did_insert_grid_field(&self, field_id: &str) -> FlowyResult<()> { async fn notify_did_insert_grid_field(&self, field_id: &str) -> FlowyResult<()> {
if let Some((index, field_rev)) = self.grid_pad.read().await.get_field_rev(field_id) { if let Some((index, field_rev)) = self.grid_pad.read().await.get_field_rev(field_id) {
let index_field = IndexFieldPB::from_field_rev(field_rev, index); let index_field = IndexFieldPB::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangesetPB::insert(&self.grid_id, vec![index_field]); let notified_changeset = FieldChangesetPB::insert(&self.grid_id, vec![index_field]);
let _ = self.notify_did_update_grid(notified_changeset).await?; let _ = self.notify_did_update_grid(notified_changeset).await?;
} }
Ok(()) Ok(())
@ -620,8 +620,8 @@ impl GridRevisionEditor {
.get_field_rev(field_id) .get_field_rev(field_id)
.map(|(index, field)| (index, field.clone())) .map(|(index, field)| (index, field.clone()))
{ {
let updated_field = GridFieldPB::from(field_rev); let updated_field = FieldPB::from(field_rev);
let notified_changeset = GridFieldChangesetPB::update(&self.grid_id, vec![updated_field.clone()]); let notified_changeset = FieldChangesetPB::update(&self.grid_id, vec![updated_field.clone()]);
let _ = self.notify_did_update_grid(notified_changeset).await?; let _ = self.notify_did_update_grid(notified_changeset).await?;
send_dart_notification(field_id, GridNotification::DidUpdateField) send_dart_notification(field_id, GridNotification::DidUpdateField)
@ -632,7 +632,7 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
async fn notify_did_update_grid(&self, changeset: GridFieldChangesetPB) -> FlowyResult<()> { async fn notify_did_update_grid(&self, changeset: FieldChangesetPB) -> FlowyResult<()> {
send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridField) send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridField)
.payload(changeset) .payload(changeset)
.send(); .send();

View File

@ -1,4 +1,4 @@
use crate::entities::{GridBlockPB, GridRowPB, RepeatedGridBlockPB}; use crate::entities::{BlockPB, RepeatedBlockPB, RowPB};
use flowy_error::FlowyResult; use flowy_error::FlowyResult;
use flowy_grid_data_model::revision::RowRevision; use flowy_grid_data_model::revision::RowRevision;
use std::collections::HashMap; use std::collections::HashMap;
@ -9,14 +9,14 @@ pub struct GridBlockSnapshot {
pub row_revs: Vec<Arc<RowRevision>>, pub row_revs: Vec<Arc<RowRevision>>,
} }
pub(crate) fn block_from_row_orders(row_orders: Vec<GridRowPB>) -> Vec<GridBlockPB> { pub(crate) fn block_from_row_orders(row_orders: Vec<RowPB>) -> Vec<BlockPB> {
let mut map: HashMap<String, GridBlockPB> = HashMap::new(); let mut map: HashMap<String, BlockPB> = HashMap::new();
row_orders.into_iter().for_each(|row_info| { row_orders.into_iter().for_each(|row_info| {
// Memory Optimization: escape clone block_id // Memory Optimization: escape clone block_id
let block_id = row_info.block_id().to_owned(); let block_id = row_info.block_id().to_owned();
let cloned_block_id = block_id.clone(); let cloned_block_id = block_id.clone();
map.entry(block_id) map.entry(block_id)
.or_insert_with(|| GridBlockPB::new(&cloned_block_id, vec![])) .or_insert_with(|| BlockPB::new(&cloned_block_id, vec![]))
.rows .rows
.push(row_info); .push(row_info);
}); });
@ -35,16 +35,16 @@ pub(crate) fn block_from_row_orders(row_orders: Vec<GridRowPB>) -> Vec<GridBlock
// Some((field_id, cell)) // Some((field_id, cell))
// } // }
pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<GridRowPB> { pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<RowPB> {
row_revs.iter().map(GridRowPB::from).collect::<Vec<_>>() row_revs.iter().map(RowPB::from).collect::<Vec<_>>()
} }
pub(crate) fn make_row_from_row_rev(row_rev: Arc<RowRevision>) -> Option<GridRowPB> { pub(crate) fn make_row_from_row_rev(row_rev: Arc<RowRevision>) -> Option<RowPB> {
make_rows_from_row_revs(&[row_rev]).pop() make_rows_from_row_revs(&[row_rev]).pop()
} }
pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<GridRowPB> { pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<RowPB> {
let make_row = |row_rev: &Arc<RowRevision>| GridRowPB { let make_row = |row_rev: &Arc<RowRevision>| RowPB {
block_id: row_rev.block_id.clone(), block_id: row_rev.block_id.clone(),
id: row_rev.id.clone(), id: row_rev.id.clone(),
height: row_rev.height, height: row_rev.height,
@ -56,15 +56,15 @@ pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<Grid
pub(crate) fn make_grid_blocks( pub(crate) fn make_grid_blocks(
block_ids: Option<Vec<String>>, block_ids: Option<Vec<String>>,
block_snapshots: Vec<GridBlockSnapshot>, block_snapshots: Vec<GridBlockSnapshot>,
) -> FlowyResult<RepeatedGridBlockPB> { ) -> FlowyResult<RepeatedBlockPB> {
match block_ids { match block_ids {
None => Ok(block_snapshots None => Ok(block_snapshots
.into_iter() .into_iter()
.map(|snapshot| { .map(|snapshot| {
let row_orders = make_row_orders_from_row_revs(&snapshot.row_revs); let row_orders = make_row_orders_from_row_revs(&snapshot.row_revs);
GridBlockPB::new(&snapshot.block_id, row_orders) BlockPB::new(&snapshot.block_id, row_orders)
}) })
.collect::<Vec<GridBlockPB>>() .collect::<Vec<BlockPB>>()
.into()), .into()),
Some(block_ids) => { Some(block_ids) => {
let block_meta_data_map: HashMap<&String, &Vec<Arc<RowRevision>>> = block_snapshots let block_meta_data_map: HashMap<&String, &Vec<Arc<RowRevision>>> = block_snapshots
@ -78,7 +78,7 @@ pub(crate) fn make_grid_blocks(
None => {} None => {}
Some(row_revs) => { Some(row_revs) => {
let row_orders = make_row_orders_from_row_revs(row_revs); let row_orders = make_row_orders_from_row_revs(row_revs);
grid_blocks.push(GridBlockPB::new(&block_id, row_orders)); grid_blocks.push(BlockPB::new(&block_id, row_orders));
} }
} }
} }

View File

@ -2,7 +2,7 @@ use crate::grid::block_test::script::RowScript::{AssertCell, CreateRow};
use crate::grid::block_test::util::GridRowTestBuilder; use crate::grid::block_test::util::GridRowTestBuilder;
use crate::grid::grid_editor::GridEditorTest; use crate::grid::grid_editor::GridEditorTest;
use flowy_grid::entities::{FieldType, GridCellIdParams, GridRowPB}; use flowy_grid::entities::{FieldType, GridCellIdParams, RowPB};
use flowy_grid::services::field::*; use flowy_grid::services::field::*;
use flowy_grid_data_model::revision::{ use flowy_grid_data_model::revision::{
GridBlockMetaRevision, GridBlockMetaRevisionChangeset, RowMetaChangeset, RowRevision, GridBlockMetaRevision, GridBlockMetaRevisionChangeset, RowMetaChangeset, RowRevision,
@ -97,7 +97,7 @@ impl GridRowTest {
let row_orders = row_ids let row_orders = row_ids
.into_iter() .into_iter()
.map(|row_id| self.row_order_by_row_id.get(&row_id).unwrap().clone()) .map(|row_id| self.row_order_by_row_id.get(&row_id).unwrap().clone())
.collect::<Vec<GridRowPB>>(); .collect::<Vec<RowPB>>();
self.editor.delete_rows(row_orders).await.unwrap(); self.editor.delete_rows(row_orders).await.unwrap();
self.row_revs = self.get_row_revs().await; self.row_revs = self.get_row_revs().await;

View File

@ -17,7 +17,7 @@ pub fn create_text_field(grid_id: &str) -> (InsertFieldParams, FieldRevision) {
.protobuf_bytes() .protobuf_bytes()
.to_vec(); .to_vec();
let field = GridFieldPB { let field = FieldPB {
id: field_rev.id, id: field_rev.id,
name: field_rev.name, name: field_rev.name,
desc: field_rev.desc, desc: field_rev.desc,
@ -50,7 +50,7 @@ pub fn create_single_select_field(grid_id: &str) -> (InsertFieldParams, FieldRev
.protobuf_bytes() .protobuf_bytes()
.to_vec(); .to_vec();
let field = GridFieldPB { let field = FieldPB {
id: field_rev.id, id: field_rev.id,
name: field_rev.name, name: field_rev.name,
desc: field_rev.desc, desc: field_rev.desc,

View File

@ -32,7 +32,7 @@ pub struct GridEditorTest {
pub block_meta_revs: Vec<Arc<GridBlockMetaRevision>>, pub block_meta_revs: Vec<Arc<GridBlockMetaRevision>>,
pub row_revs: Vec<Arc<RowRevision>>, pub row_revs: Vec<Arc<RowRevision>>,
pub field_count: usize, pub field_count: usize,
pub row_order_by_row_id: HashMap<String, GridRowPB>, pub row_order_by_row_id: HashMap<String, RowPB>,
} }
impl GridEditorTest { impl GridEditorTest {