Merge pull request #619 from AppFlowy-IO/refactor/add_pb_suffix

This commit is contained in:
Nathan.fooo 2022-07-17 15:14:15 +08:00 committed by GitHub
commit 609d103779
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
93 changed files with 895 additions and 911 deletions

View File

@ -8,7 +8,7 @@ import 'package:flowy_sdk/rust_stream.dart';
import 'notification_helper.dart'; import 'notification_helper.dart';
// Grid // GridPB
typedef GridNotificationCallback = void Function(GridNotification, Either<Uint8List, FlowyError>); typedef GridNotificationCallback = void Function(GridNotification, Either<Uint8List, FlowyError>);
class GridNotificationParser extends NotificationParser<GridNotification, FlowyError> { class GridNotificationParser extends NotificationParser<GridNotification, FlowyError> {

View File

@ -134,7 +134,7 @@ void _resolveDocDeps(GetIt getIt) {
} }
void _resolveGridDeps(GetIt getIt) { void _resolveGridDeps(GetIt getIt) {
// Grid // GridPB
getIt.registerFactoryParam<GridBloc, View, void>( getIt.registerFactoryParam<GridBloc, View, void>(
(view, _) => GridBloc(view: view), (view, _) => GridBloc(view: view),
); );

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 GridBlock block; final GridBlockPB block;
late GridRowCache _rowCache; late GridRowCache _rowCache;
late GridBlockListener _listener; late GridBlockListener _listener;
List<GridRow> get rows => _rowCache.rows; List<GridRowInfo> get rows => _rowCache.rows;
GridRowCache get rowCache => _rowCache; GridRowCache get rowCache => _rowCache;
GridBlockCache({ GridBlockCache({

View File

@ -7,7 +7,7 @@ import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/block_entities.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/block_entities.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/dart_notification.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/dart_notification.pb.dart';
typedef GridBlockUpdateNotifierValue = Either<List<GridBlockChangeset>, FlowyError>; typedef GridBlockUpdateNotifierValue = Either<List<GridBlockChangesetPB>, FlowyError>;
class GridBlockListener { class GridBlockListener {
final String blockId; final String blockId;
@ -33,7 +33,7 @@ class GridBlockListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateGridBlock: case GridNotification.DidUpdateGridBlock:
result.fold( result.fold(
(payload) => _rowsUpdateNotifier?.value = left([GridBlockChangeset.fromBuffer(payload)]), (payload) => _rowsUpdateNotifier?.value = left([GridBlockChangesetPB.fromBuffer(payload)]),
(error) => _rowsUpdateNotifier?.value = right(error), (error) => _rowsUpdateNotifier?.value = right(error),
); );
break; break;

View File

@ -24,7 +24,7 @@ class GridCellDataLoader<T> {
Future<T?> loadData() { Future<T?> loadData() {
final fut = service.getCell(cellId: cellId); final fut = service.getCell(cellId: cellId);
return fut.then( return fut.then(
(result) => result.fold((Cell cell) { (result) => result.fold((GridCellPB cell) {
try { try {
return parser.parserData(cell.data); return parser.parserData(cell.data);
} catch (e, s) { } catch (e, s) {
@ -48,32 +48,32 @@ class StringCellDataParser implements ICellDataParser<String> {
} }
} }
class DateCellDataParser implements ICellDataParser<DateCellData> { class DateCellDataParser implements ICellDataParser<DateCellDataPB> {
@override @override
DateCellData? parserData(List<int> data) { DateCellDataPB? parserData(List<int> data) {
if (data.isEmpty) { if (data.isEmpty) {
return null; return null;
} }
return DateCellData.fromBuffer(data); return DateCellDataPB.fromBuffer(data);
} }
} }
class SelectOptionCellDataParser implements ICellDataParser<SelectOptionCellData> { class SelectOptionCellDataParser implements ICellDataParser<SelectOptionCellDataPB> {
@override @override
SelectOptionCellData? parserData(List<int> data) { SelectOptionCellDataPB? parserData(List<int> data) {
if (data.isEmpty) { if (data.isEmpty) {
return null; return null;
} }
return SelectOptionCellData.fromBuffer(data); return SelectOptionCellDataPB.fromBuffer(data);
} }
} }
class URLCellDataParser implements ICellDataParser<URLCellData> { class URLCellDataParser implements ICellDataParser<URLCellDataPB> {
@override @override
URLCellData? parserData(List<int> data) { URLCellDataPB? parserData(List<int> data) {
if (data.isEmpty) { if (data.isEmpty) {
return null; return null;
} }
return URLCellData.fromBuffer(data); return URLCellDataPB.fromBuffer(data);
} }
} }

View File

@ -40,7 +40,7 @@ class DateCellDataPersistence implements IGridCellDataPersistence<CalendarData>
@override @override
Future<Option<FlowyError>> save(CalendarData data) { Future<Option<FlowyError>> save(CalendarData data) {
var payload = DateChangesetPayload.create()..cellIdentifier = _makeCellIdPayload(cellId); var payload = DateChangesetPayloadPB.create()..cellIdentifier = _makeCellIdPayload(cellId);
final date = (data.date.millisecondsSinceEpoch ~/ 1000).toString(); final date = (data.date.millisecondsSinceEpoch ~/ 1000).toString();
payload.date = date; payload.date = date;
@ -58,8 +58,8 @@ class DateCellDataPersistence implements IGridCellDataPersistence<CalendarData>
} }
} }
CellIdentifierPayload _makeCellIdPayload(GridCellIdentifier cellId) { GridCellIdentifierPayloadPB _makeCellIdPayload(GridCellIdentifier cellId) {
return CellIdentifierPayload.create() return GridCellIdentifierPayloadPB.create()
..gridId = cellId.gridId ..gridId = cellId.gridId
..fieldId = cellId.fieldId ..fieldId = cellId.fieldId
..rowId = cellId.rowId; ..rowId = cellId.rowId;

View File

@ -4,11 +4,11 @@ import 'package:flutter/foundation.dart';
import 'cell_service.dart'; import 'cell_service.dart';
abstract class GridFieldChangedNotifier { abstract class GridFieldChangedNotifier {
void onFieldChanged(void Function(Field) callback); void onFieldChanged(void Function(GridFieldPB) callback);
void dispose(); void dispose();
} }
/// Grid's cell helper wrapper that enables each cell will get notified when the corresponding field was changed. /// GridPB's cell helper wrapper that enables each cell will get notified when the corresponding field was changed.
/// You Register an onFieldChanged callback to listen to the cell changes, and unregister if you don't want to listen. /// You Register an onFieldChanged callback to listen to the cell changes, and unregister if you don't want to listen.
class GridCellFieldNotifier { class GridCellFieldNotifier {
/// fieldId: {objectId: callback} /// fieldId: {objectId: callback}

View File

@ -35,7 +35,7 @@ class CellService {
required GridCellIdentifier cellId, required GridCellIdentifier cellId,
required String data, required String data,
}) { }) {
final payload = CellChangeset.create() final payload = CellChangesetPB.create()
..gridId = cellId.gridId ..gridId = cellId.gridId
..fieldId = cellId.fieldId ..fieldId = cellId.fieldId
..rowId = cellId.rowId ..rowId = cellId.rowId
@ -43,10 +43,10 @@ class CellService {
return GridEventUpdateCell(payload).send(); return GridEventUpdateCell(payload).send();
} }
Future<Either<Cell, FlowyError>> getCell({ Future<Either<GridCellPB, FlowyError>> getCell({
required GridCellIdentifier cellId, required GridCellIdentifier cellId,
}) { }) {
final payload = CellIdentifierPayload.create() final payload = GridCellIdentifierPayloadPB.create()
..gridId = cellId.gridId ..gridId = cellId.gridId
..fieldId = cellId.fieldId ..fieldId = cellId.fieldId
..rowId = cellId.rowId; ..rowId = cellId.rowId;
@ -61,7 +61,7 @@ class GridCellIdentifier with _$GridCellIdentifier {
const factory GridCellIdentifier({ const factory GridCellIdentifier({
required String gridId, required String gridId,
required String rowId, required String rowId,
required Field field, required GridFieldPB field,
}) = _GridCellIdentifier; }) = _GridCellIdentifier;
// ignore: unused_element // ignore: unused_element

View File

@ -1,9 +1,9 @@
part of 'cell_service.dart'; part of 'cell_service.dart';
typedef GridCellController = IGridCellController<String, String>; typedef GridCellController = IGridCellController<String, String>;
typedef GridSelectOptionCellController = IGridCellController<SelectOptionCellData, String>; typedef GridSelectOptionCellController = IGridCellController<SelectOptionCellDataPB, String>;
typedef GridDateCellController = IGridCellController<DateCellData, CalendarData>; typedef GridDateCellController = IGridCellController<DateCellDataPB, CalendarData>;
typedef GridURLCellController = IGridCellController<URLCellData, String>; typedef GridURLCellController = IGridCellController<URLCellDataPB, String>;
class GridCellControllerBuilder { class GridCellControllerBuilder {
final GridCellIdentifier _cellId; final GridCellIdentifier _cellId;
@ -159,7 +159,7 @@ class IGridCellController<T, D> extends Equatable {
String get fieldId => cellId.field.id; String get fieldId => cellId.field.id;
Field get field => cellId.field; GridFieldPB get field => cellId.field;
FieldType get fieldType => cellId.field.fieldType; FieldType get fieldType => cellId.field.fieldType;
@ -223,7 +223,7 @@ class IGridCellController<T, D> extends Equatable {
return data; return data;
} }
/// Return the FieldTypeOptionData that can be parsed into corresponding class using the [parser]. /// Return the FieldTypeOptionDataPB that can be parsed into corresponding class using the [parser].
/// [PD] is the type that the parser return. /// [PD] is the type that the parser return.
Future<Either<PD, FlowyError>> getFieldTypeOption<PD, P extends TypeOptionDataParser>(P parser) { Future<Either<PD, FlowyError>> getFieldTypeOption<PD, P extends TypeOptionDataParser>(P parser) {
return _fieldService.getFieldTypeOptionData(fieldType: fieldType).then((result) { return _fieldService.getFieldTypeOptionData(fieldType: fieldType).then((result) {
@ -305,8 +305,8 @@ class _GridFieldChangedNotifierImpl extends GridFieldChangedNotifier {
} }
@override @override
void onFieldChanged(void Function(Field p1) callback) { void onFieldChanged(void Function(GridFieldPB p1) callback) {
_onChangesetFn = (GridFieldChangeset changeset) { _onChangesetFn = (GridFieldChangesetPB changeset) {
for (final updatedField in changeset.updatedFields) { for (final updatedField in changeset.updatedFields) {
callback(updatedField); callback(updatedField);
} }

View File

@ -22,7 +22,7 @@ class DateCalBloc extends Bloc<DateCalEvent, DateCalState> {
DateCalBloc({ DateCalBloc({
required DateTypeOption dateTypeOption, required DateTypeOption dateTypeOption,
required DateCellData? cellData, required DateCellDataPB? cellData,
required this.cellContext, required this.cellContext,
}) : super(DateCalState.initial(dateTypeOption, cellData)) { }) : super(DateCalState.initial(dateTypeOption, cellData)) {
on<DateCalEvent>( on<DateCalEvent>(
@ -38,7 +38,7 @@ class DateCalBloc extends Bloc<DateCalEvent, DateCalState> {
setFocusedDay: (focusedDay) { setFocusedDay: (focusedDay) {
emit(state.copyWith(focusedDay: focusedDay)); emit(state.copyWith(focusedDay: focusedDay));
}, },
didReceiveCellUpdate: (DateCellData? cellData) { didReceiveCellUpdate: (DateCellDataPB? cellData) {
final calData = calDataFromCellData(cellData); final calData = calDataFromCellData(cellData);
final time = calData.foldRight("", (dateData, previous) => dateData.time); final time = calData.foldRight("", (dateData, previous) => dateData.time);
emit(state.copyWith(calData: calData, time: time)); emit(state.copyWith(calData: calData, time: time));
@ -188,7 +188,7 @@ class DateCalEvent with _$DateCalEvent {
const factory DateCalEvent.setDateFormat(DateFormat dateFormat) = _DateFormat; const factory DateCalEvent.setDateFormat(DateFormat dateFormat) = _DateFormat;
const factory DateCalEvent.setIncludeTime(bool includeTime) = _IncludeTime; const factory DateCalEvent.setIncludeTime(bool includeTime) = _IncludeTime;
const factory DateCalEvent.setTime(String time) = _Time; const factory DateCalEvent.setTime(String time) = _Time;
const factory DateCalEvent.didReceiveCellUpdate(DateCellData? data) = _DidReceiveCellUpdate; const factory DateCalEvent.didReceiveCellUpdate(DateCellDataPB? data) = _DidReceiveCellUpdate;
const factory DateCalEvent.didUpdateCalData(Option<CalendarData> data, Option<String> timeFormatError) = const factory DateCalEvent.didUpdateCalData(Option<CalendarData> data, Option<String> timeFormatError) =
_DidUpdateCalData; _DidUpdateCalData;
} }
@ -207,7 +207,7 @@ class DateCalState with _$DateCalState {
factory DateCalState.initial( factory DateCalState.initial(
DateTypeOption dateTypeOption, DateTypeOption dateTypeOption,
DateCellData? cellData, DateCellDataPB? cellData,
) { ) {
Option<CalendarData> calData = calDataFromCellData(cellData); Option<CalendarData> calData = calDataFromCellData(cellData);
final time = calData.foldRight("", (dateData, previous) => dateData.time); final time = calData.foldRight("", (dateData, previous) => dateData.time);
@ -233,7 +233,7 @@ String _timeHintText(DateTypeOption typeOption) {
return ""; return "";
} }
Option<CalendarData> calDataFromCellData(DateCellData? cellData) { Option<CalendarData> calDataFromCellData(DateCellDataPB? cellData) {
String? time = timeFromCellData(cellData); String? time = timeFromCellData(cellData);
Option<CalendarData> calData = none(); Option<CalendarData> calData = none();
if (cellData != null) { if (cellData != null) {
@ -249,7 +249,7 @@ $fixnum.Int64 timestampFromDateTime(DateTime dateTime) {
return $fixnum.Int64(timestamp); return $fixnum.Int64(timestamp);
} }
String? timeFromCellData(DateCellData? cellData) { String? timeFromCellData(DateCellDataPB? cellData) {
String? time; String? time;
if (cellData?.hasTime() ?? false) { if (cellData?.hasTime() ?? false) {
time = cellData?.time; time = cellData?.time;

View File

@ -15,10 +15,10 @@ class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
(event, emit) async { (event, emit) async {
event.when( event.when(
initial: () => _startListening(), initial: () => _startListening(),
didReceiveCellUpdate: (DateCellData? cellData) { didReceiveCellUpdate: (DateCellDataPB? cellData) {
emit(state.copyWith(data: cellData, dateStr: _dateStrFromCellData(cellData))); emit(state.copyWith(data: cellData, dateStr: _dateStrFromCellData(cellData)));
}, },
didReceiveFieldUpdate: (Field value) => emit(state.copyWith(field: value)), didReceiveFieldUpdate: (GridFieldPB value) => emit(state.copyWith(field: value)),
); );
}, },
); );
@ -48,16 +48,16 @@ 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(DateCellData? data) = _DidReceiveCellUpdate; const factory DateCellEvent.didReceiveCellUpdate(DateCellDataPB? data) = _DidReceiveCellUpdate;
const factory DateCellEvent.didReceiveFieldUpdate(Field field) = _DidReceiveFieldUpdate; const factory DateCellEvent.didReceiveFieldUpdate(GridFieldPB field) = _DidReceiveFieldUpdate;
} }
@freezed @freezed
class DateCellState with _$DateCellState { class DateCellState with _$DateCellState {
const factory DateCellState({ const factory DateCellState({
required DateCellData? data, required DateCellDataPB? data,
required String dateStr, required String dateStr,
required Field field, required GridFieldPB field,
}) = _DateCellState; }) = _DateCellState;
factory DateCellState.initial(GridDateCellController context) { factory DateCellState.initial(GridDateCellController context) {
@ -71,7 +71,7 @@ class DateCellState with _$DateCellState {
} }
} }
String _dateStrFromCellData(DateCellData? cellData) { String _dateStrFromCellData(DateCellDataPB? cellData) {
String dateStr = ""; String dateStr = "";
if (cellData != null) { if (cellData != null) {
dateStr = cellData.date + " " + cellData.time; dateStr = cellData.date + " " + cellData.time;

View File

@ -56,14 +56,14 @@ class SelectOptionCellBloc extends Bloc<SelectOptionCellEvent, SelectOptionCellS
class SelectOptionCellEvent with _$SelectOptionCellEvent { class SelectOptionCellEvent with _$SelectOptionCellEvent {
const factory SelectOptionCellEvent.initial() = _InitialCell; const factory SelectOptionCellEvent.initial() = _InitialCell;
const factory SelectOptionCellEvent.didReceiveOptions( const factory SelectOptionCellEvent.didReceiveOptions(
List<SelectOption> selectedOptions, List<SelectOptionPB> selectedOptions,
) = _DidReceiveOptions; ) = _DidReceiveOptions;
} }
@freezed @freezed
class SelectOptionCellState with _$SelectOptionCellState { class SelectOptionCellState with _$SelectOptionCellState {
const factory SelectOptionCellState({ const factory SelectOptionCellState({
required List<SelectOption> selectedOptions, required List<SelectOptionPB> selectedOptions,
}) = _SelectOptionCellState; }) = _SelectOptionCellState;
factory SelectOptionCellState.initial(GridSelectOptionCellController context) { factory SelectOptionCellState.initial(GridSelectOptionCellController context) {

View File

@ -70,7 +70,7 @@ class SelectOptionCellEditorBloc extends Bloc<SelectOptionEditorEvent, SelectOpt
result.fold((l) => {}, (err) => Log.error(err)); result.fold((l) => {}, (err) => Log.error(err));
} }
void _deleteOption(SelectOption option) async { void _deleteOption(SelectOptionPB option) async {
final result = await _selectOptionService.delete( final result = await _selectOptionService.delete(
option: option, option: option,
); );
@ -78,7 +78,7 @@ class SelectOptionCellEditorBloc extends Bloc<SelectOptionEditorEvent, SelectOpt
result.fold((l) => null, (err) => Log.error(err)); result.fold((l) => null, (err) => Log.error(err));
} }
void _updateOption(SelectOption option) async { void _updateOption(SelectOptionPB option) async {
final result = await _selectOptionService.update( final result = await _selectOptionService.update(
option: option, option: option,
); );
@ -122,8 +122,8 @@ class SelectOptionCellEditorBloc extends Bloc<SelectOptionEditorEvent, SelectOpt
}); });
} }
_MakeOptionResult _makeOptions(Option<String> filter, List<SelectOption> allOptions) { _MakeOptionResult _makeOptions(Option<String> filter, List<SelectOptionPB> allOptions) {
final List<SelectOption> options = List.from(allOptions); final List<SelectOptionPB> options = List.from(allOptions);
Option<String> createOption = filter; Option<String> createOption = filter;
filter.foldRight(null, (filter, previous) { filter.foldRight(null, (filter, previous) {
@ -165,20 +165,20 @@ class SelectOptionCellEditorBloc extends Bloc<SelectOptionEditorEvent, SelectOpt
class SelectOptionEditorEvent with _$SelectOptionEditorEvent { class SelectOptionEditorEvent with _$SelectOptionEditorEvent {
const factory SelectOptionEditorEvent.initial() = _Initial; const factory SelectOptionEditorEvent.initial() = _Initial;
const factory SelectOptionEditorEvent.didReceiveOptions( const factory SelectOptionEditorEvent.didReceiveOptions(
List<SelectOption> options, List<SelectOption> selectedOptions) = _DidReceiveOptions; List<SelectOptionPB> options, List<SelectOptionPB> selectedOptions) = _DidReceiveOptions;
const factory SelectOptionEditorEvent.newOption(String optionName) = _NewOption; const factory SelectOptionEditorEvent.newOption(String optionName) = _NewOption;
const factory SelectOptionEditorEvent.selectOption(String optionId) = _SelectOption; const factory SelectOptionEditorEvent.selectOption(String optionId) = _SelectOption;
const factory SelectOptionEditorEvent.updateOption(SelectOption option) = _UpdateOption; const factory SelectOptionEditorEvent.updateOption(SelectOptionPB option) = _UpdateOption;
const factory SelectOptionEditorEvent.deleteOption(SelectOption option) = _DeleteOption; const factory SelectOptionEditorEvent.deleteOption(SelectOptionPB option) = _DeleteOption;
const factory SelectOptionEditorEvent.filterOption(String optionName) = _SelectOptionFilter; const factory SelectOptionEditorEvent.filterOption(String optionName) = _SelectOptionFilter;
} }
@freezed @freezed
class SelectOptionEditorState with _$SelectOptionEditorState { class SelectOptionEditorState with _$SelectOptionEditorState {
const factory SelectOptionEditorState({ const factory SelectOptionEditorState({
required List<SelectOption> options, required List<SelectOptionPB> options,
required List<SelectOption> allOptions, required List<SelectOptionPB> allOptions,
required List<SelectOption> selectedOptions, required List<SelectOptionPB> selectedOptions,
required Option<String> createOption, required Option<String> createOption,
required Option<String> filter, required Option<String> filter,
}) = _SelectOptionEditorState; }) = _SelectOptionEditorState;
@ -196,7 +196,7 @@ class SelectOptionEditorState with _$SelectOptionEditorState {
} }
class _MakeOptionResult { class _MakeOptionResult {
List<SelectOption> options; List<SelectOptionPB> options;
Option<String> createOption; Option<String> createOption;
_MakeOptionResult({ _MakeOptionResult({

View File

@ -19,11 +19,11 @@ class SelectOptionService {
(result) { (result) {
return result.fold( return result.fold(
(option) { (option) {
final cellIdentifier = CellIdentifierPayload.create() final cellIdentifier = GridCellIdentifierPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..rowId = rowId; ..rowId = rowId;
final payload = SelectOptionChangesetPayload.create() final payload = SelectOptionChangesetPayloadPB.create()
..insertOption = option ..insertOption = option
..cellIdentifier = cellIdentifier; ..cellIdentifier = cellIdentifier;
return GridEventUpdateSelectOption(payload).send(); return GridEventUpdateSelectOption(payload).send();
@ -35,26 +35,26 @@ class SelectOptionService {
} }
Future<Either<Unit, FlowyError>> update({ Future<Either<Unit, FlowyError>> update({
required SelectOption option, required SelectOptionPB option,
}) { }) {
final payload = SelectOptionChangesetPayload.create() final payload = SelectOptionChangesetPayloadPB.create()
..updateOption = option ..updateOption = option
..cellIdentifier = _cellIdentifier(); ..cellIdentifier = _cellIdentifier();
return GridEventUpdateSelectOption(payload).send(); return GridEventUpdateSelectOption(payload).send();
} }
Future<Either<Unit, FlowyError>> delete({ Future<Either<Unit, FlowyError>> delete({
required SelectOption option, required SelectOptionPB option,
}) { }) {
final payload = SelectOptionChangesetPayload.create() final payload = SelectOptionChangesetPayloadPB.create()
..deleteOption = option ..deleteOption = option
..cellIdentifier = _cellIdentifier(); ..cellIdentifier = _cellIdentifier();
return GridEventUpdateSelectOption(payload).send(); return GridEventUpdateSelectOption(payload).send();
} }
Future<Either<SelectOptionCellData, FlowyError>> getOpitonContext() { Future<Either<SelectOptionCellDataPB, FlowyError>> getOpitonContext() {
final payload = CellIdentifierPayload.create() final payload = GridCellIdentifierPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..rowId = rowId; ..rowId = rowId;
@ -63,21 +63,21 @@ class SelectOptionService {
} }
Future<Either<void, FlowyError>> select({required String optionId}) { Future<Either<void, FlowyError>> select({required String optionId}) {
final payload = SelectOptionCellChangesetPayload.create() final payload = SelectOptionCellChangesetPayloadPB.create()
..cellIdentifier = _cellIdentifier() ..cellIdentifier = _cellIdentifier()
..insertOptionId = optionId; ..insertOptionId = optionId;
return GridEventUpdateSelectOptionCell(payload).send(); return GridEventUpdateSelectOptionCell(payload).send();
} }
Future<Either<void, FlowyError>> unSelect({required String optionId}) { Future<Either<void, FlowyError>> unSelect({required String optionId}) {
final payload = SelectOptionCellChangesetPayload.create() final payload = SelectOptionCellChangesetPayloadPB.create()
..cellIdentifier = _cellIdentifier() ..cellIdentifier = _cellIdentifier()
..deleteOptionId = optionId; ..deleteOptionId = optionId;
return GridEventUpdateSelectOptionCell(payload).send(); return GridEventUpdateSelectOptionCell(payload).send();
} }
CellIdentifierPayload _cellIdentifier() { GridCellIdentifierPayloadPB _cellIdentifier() {
return CellIdentifierPayload.create() return GridCellIdentifierPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..rowId = rowId; ..rowId = rowId;

View File

@ -57,7 +57,7 @@ class URLCellBloc extends Bloc<URLCellEvent, URLCellState> {
class URLCellEvent with _$URLCellEvent { class URLCellEvent with _$URLCellEvent {
const factory URLCellEvent.initial() = _InitialCell; const factory URLCellEvent.initial() = _InitialCell;
const factory URLCellEvent.updateURL(String url) = _UpdateURL; const factory URLCellEvent.updateURL(String url) = _UpdateURL;
const factory URLCellEvent.didReceiveCellUpdate(URLCellData? cell) = _DidReceiveCellUpdate; const factory URLCellEvent.didReceiveCellUpdate(URLCellDataPB? cell) = _DidReceiveCellUpdate;
} }
@freezed @freezed

View File

@ -54,7 +54,7 @@ class URLCellEditorBloc extends Bloc<URLCellEditorEvent, URLCellEditorState> {
@freezed @freezed
class URLCellEditorEvent with _$URLCellEditorEvent { class URLCellEditorEvent with _$URLCellEditorEvent {
const factory URLCellEditorEvent.initial() = _InitialCell; const factory URLCellEditorEvent.initial() = _InitialCell;
const factory URLCellEditorEvent.didReceiveCellUpdate(URLCellData? cell) = _DidReceiveCellUpdate; const factory URLCellEditorEvent.didReceiveCellUpdate(URLCellDataPB? cell) = _DidReceiveCellUpdate;
const factory URLCellEditorEvent.updateText(String text) = _UpdateText; const factory URLCellEditorEvent.updateText(String text) = _UpdateText;
} }

View File

@ -10,8 +10,8 @@ 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 Field field, required this.fieldService}) FieldActionSheetBloc({required GridFieldPB field, required this.fieldService})
: super(FieldActionSheetState.initial(FieldTypeOptionData.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(
@ -67,12 +67,12 @@ class FieldActionSheetEvent with _$FieldActionSheetEvent {
@freezed @freezed
class FieldActionSheetState with _$FieldActionSheetState { class FieldActionSheetState with _$FieldActionSheetState {
const factory FieldActionSheetState({ const factory FieldActionSheetState({
required FieldTypeOptionData fieldTypeOptionData, required FieldTypeOptionDataPB fieldTypeOptionData,
required String errorText, required String errorText,
required String fieldName, required String fieldName,
}) = _FieldActionSheetState; }) = _FieldActionSheetState;
factory FieldActionSheetState.initial(FieldTypeOptionData 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

@ -62,7 +62,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(Field field) = _DidReceiveFieldUpdate; const factory FieldCellEvent.didReceiveFieldUpdate(GridFieldPB field) = _DidReceiveFieldUpdate;
const factory FieldCellEvent.startUpdateWidth(double offset) = _StartUpdateWidth; const factory FieldCellEvent.startUpdateWidth(double offset) = _StartUpdateWidth;
const factory FieldCellEvent.endUpdateWidth() = _EndUpdateWidth; const factory FieldCellEvent.endUpdateWidth() = _EndUpdateWidth;
} }
@ -71,7 +71,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 Field field, required GridFieldPB field,
required double width, required double width,
}) = _FieldCellState; }) = _FieldCellState;

View File

@ -30,7 +30,7 @@ class FieldEditorBloc extends Bloc<FieldEditorEvent, FieldEditorState> {
dataController.fieldName = name; dataController.fieldName = name;
emit(state.copyWith(name: name)); emit(state.copyWith(name: name));
}, },
didReceiveFieldChanged: (Field field) { didReceiveFieldChanged: (GridFieldPB field) {
emit(state.copyWith(field: Some(field))); emit(state.copyWith(field: Some(field)));
}, },
); );
@ -48,7 +48,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(Field field) = _DidReceiveFieldChanged; const factory FieldEditorEvent.didReceiveFieldChanged(GridFieldPB field) = _DidReceiveFieldChanged;
} }
@freezed @freezed
@ -57,7 +57,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<Field> field, required Option<GridFieldPB> field,
}) = _FieldEditorState; }) = _FieldEditorState;
factory FieldEditorState.initial( factory FieldEditorState.initial(

View File

@ -7,7 +7,7 @@ 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<Field, FlowyError>; typedef UpdateFieldNotifiedValue = Either<GridFieldPB, FlowyError>;
class SingleFieldListener { class SingleFieldListener {
final String fieldId; final String fieldId;
@ -31,7 +31,7 @@ class SingleFieldListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateField: case GridNotification.DidUpdateField:
result.fold( result.fold(
(payload) => _updateFieldNotifier?.value = left(Field.fromBuffer(payload)), (payload) => _updateFieldNotifier?.value = left(GridFieldPB.fromBuffer(payload)),
(error) => _updateFieldNotifier?.value = right(error), (error) => _updateFieldNotifier?.value = right(error),
); );
break; break;

View File

@ -21,10 +21,10 @@ class FieldService {
FieldService({required this.gridId, required this.fieldId}); FieldService({required this.gridId, required this.fieldId});
Future<Either<Unit, FlowyError>> moveField(int fromIndex, int toIndex) { Future<Either<Unit, FlowyError>> moveField(int fromIndex, int toIndex) {
final payload = MoveItemPayload.create() final payload = MoveItemPayloadPB.create()
..gridId = gridId ..gridId = gridId
..itemId = fieldId ..itemId = fieldId
..ty = MoveItemType.MoveField ..ty = MoveItemTypePB.MoveField
..fromIndex = fromIndex ..fromIndex = fromIndex
..toIndex = toIndex; ..toIndex = toIndex;
@ -39,7 +39,7 @@ class FieldService {
double? width, double? width,
List<int>? typeOptionData, List<int>? typeOptionData,
}) { }) {
var payload = FieldChangesetPayload.create() var payload = FieldChangesetPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId; ..fieldId = fieldId;
@ -73,11 +73,11 @@ 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 Field field, required GridFieldPB field,
List<int>? typeOptionData, List<int>? typeOptionData,
String? startFieldId, String? startFieldId,
}) { }) {
var payload = InsertFieldPayload.create() var payload = InsertFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..field_2 = field ..field_2 = field
..typeOptionData = typeOptionData ?? []; ..typeOptionData = typeOptionData ?? [];
@ -94,7 +94,7 @@ class FieldService {
required String fieldId, required String fieldId,
required List<int> typeOptionData, required List<int> typeOptionData,
}) { }) {
var payload = UpdateFieldTypeOptionPayload.create() var payload = UpdateFieldTypeOptionPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..typeOptionData = typeOptionData; ..typeOptionData = typeOptionData;
@ -103,7 +103,7 @@ class FieldService {
} }
Future<Either<Unit, FlowyError>> deleteField() { Future<Either<Unit, FlowyError>> deleteField() {
final payload = FieldIdentifierPayload.create() final payload = GridFieldIdentifierPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId; ..fieldId = fieldId;
@ -111,17 +111,17 @@ class FieldService {
} }
Future<Either<Unit, FlowyError>> duplicateField() { Future<Either<Unit, FlowyError>> duplicateField() {
final payload = FieldIdentifierPayload.create() final payload = GridFieldIdentifierPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId; ..fieldId = fieldId;
return GridEventDuplicateField(payload).send(); return GridEventDuplicateField(payload).send();
} }
Future<Either<FieldTypeOptionData, FlowyError>> getFieldTypeOptionData({ Future<Either<FieldTypeOptionDataPB, FlowyError>> getFieldTypeOptionData({
required FieldType fieldType, required FieldType fieldType,
}) { }) {
final payload = EditFieldPayload.create() final payload = EditFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..fieldType = fieldType; ..fieldType = fieldType;
@ -138,16 +138,16 @@ class FieldService {
class GridFieldCellContext with _$GridFieldCellContext { class GridFieldCellContext with _$GridFieldCellContext {
const factory GridFieldCellContext({ const factory GridFieldCellContext({
required String gridId, required String gridId,
required Field field, required GridFieldPB field,
}) = _GridFieldCellContext; }) = _GridFieldCellContext;
} }
abstract class IFieldTypeOptionLoader { abstract class IFieldTypeOptionLoader {
String get gridId; String get gridId;
Future<Either<FieldTypeOptionData, FlowyError>> load(); Future<Either<FieldTypeOptionDataPB, FlowyError>> load();
Future<Either<FieldTypeOptionData, FlowyError>> switchToField(String fieldId, FieldType fieldType) { Future<Either<FieldTypeOptionDataPB, FlowyError>> switchToField(String fieldId, FieldType fieldType) {
final payload = EditFieldPayload.create() final payload = EditFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId ..fieldId = fieldId
..fieldType = fieldType; ..fieldType = fieldType;
@ -164,8 +164,8 @@ class NewFieldTypeOptionLoader extends IFieldTypeOptionLoader {
}); });
@override @override
Future<Either<FieldTypeOptionData, FlowyError>> load() { Future<Either<FieldTypeOptionDataPB, FlowyError>> load() {
final payload = EditFieldPayload.create() final payload = EditFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldType = FieldType.RichText; ..fieldType = FieldType.RichText;
@ -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 Field field; final GridFieldPB field;
FieldTypeOptionLoader({ FieldTypeOptionLoader({
required this.gridId, required this.gridId,
@ -184,8 +184,8 @@ class FieldTypeOptionLoader extends IFieldTypeOptionLoader {
}); });
@override @override
Future<Either<FieldTypeOptionData, FlowyError>> load() { Future<Either<FieldTypeOptionDataPB, FlowyError>> load() {
final payload = EditFieldPayload.create() final payload = EditFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = field.id ..fieldId = field.id
..fieldType = field.fieldType; ..fieldType = field.fieldType;
@ -198,8 +198,8 @@ class TypeOptionDataController {
final String gridId; final String gridId;
final IFieldTypeOptionLoader _loader; final IFieldTypeOptionLoader _loader;
late FieldTypeOptionData _data; late FieldTypeOptionDataPB _data;
final PublishNotifier<Field> _fieldNotifier = PublishNotifier(); final PublishNotifier<GridFieldPB> _fieldNotifier = PublishNotifier();
TypeOptionDataController({ TypeOptionDataController({
required this.gridId, required this.gridId,
@ -222,9 +222,9 @@ class TypeOptionDataController {
); );
} }
Field get field => _data.field_2; GridFieldPB get field => _data.field_2;
set field(Field field) { set field(GridFieldPB field) {
_updateData(newField: field); _updateData(newField: field);
} }
@ -238,7 +238,7 @@ class TypeOptionDataController {
_updateData(newTypeOptionData: typeOptionData); _updateData(newTypeOptionData: typeOptionData);
} }
void _updateData({String? newName, Field? newField, List<int>? newTypeOptionData}) { void _updateData({String? newName, GridFieldPB? newField, List<int>? newTypeOptionData}) {
_data = _data.rebuild((rebuildData) { _data = _data.rebuild((rebuildData) {
if (newName != null) { if (newName != null) {
rebuildData.field_2 = rebuildData.field_2.rebuild((rebuildField) { rebuildData.field_2 = rebuildData.field_2.rebuild((rebuildField) {
@ -280,7 +280,7 @@ class TypeOptionDataController {
}); });
} }
void Function() addFieldListener(void Function(Field) callback) { void Function() addFieldListener(void Function(GridFieldPB) callback) {
listener() { listener() {
callback(field); callback(field);
} }

View File

@ -42,13 +42,13 @@ class FieldTypeOptionEditBloc extends Bloc<FieldTypeOptionEditEvent, FieldTypeOp
@freezed @freezed
class FieldTypeOptionEditEvent with _$FieldTypeOptionEditEvent { class FieldTypeOptionEditEvent with _$FieldTypeOptionEditEvent {
const factory FieldTypeOptionEditEvent.initial() = _Initial; const factory FieldTypeOptionEditEvent.initial() = _Initial;
const factory FieldTypeOptionEditEvent.didReceiveFieldUpdated(Field field) = _DidReceiveFieldUpdated; const factory FieldTypeOptionEditEvent.didReceiveFieldUpdated(GridFieldPB field) = _DidReceiveFieldUpdated;
} }
@freezed @freezed
class FieldTypeOptionEditState with _$FieldTypeOptionEditState { class FieldTypeOptionEditState with _$FieldTypeOptionEditState {
const factory FieldTypeOptionEditState({ const factory FieldTypeOptionEditState({
required Field field, required GridFieldPB field,
}) = _FieldTypeOptionEditState; }) = _FieldTypeOptionEditState;
factory FieldTypeOptionEditState.initial(TypeOptionDataController fieldContext) => FieldTypeOptionEditState( factory FieldTypeOptionEditState.initial(TypeOptionDataController fieldContext) => FieldTypeOptionEditState(

View File

@ -7,7 +7,7 @@ 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<GridFieldChangeset, FlowyError>; typedef UpdateFieldNotifiedValue = Either<GridFieldChangesetPB, FlowyError>;
class GridFieldsListener { class GridFieldsListener {
final String gridId; final String gridId;
@ -27,7 +27,7 @@ class GridFieldsListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateGridField: case GridNotification.DidUpdateGridField:
result.fold( result.fold(
(payload) => updateFieldsNotifier?.value = left(GridFieldChangeset.fromBuffer(payload)), (payload) => updateFieldsNotifier?.value = left(GridFieldChangesetPB.fromBuffer(payload)),
(error) => updateFieldsNotifier?.value = right(error), (error) => updateFieldsNotifier?.value = right(error),
); );
break; break;

View File

@ -7,7 +7,7 @@ import 'package:dartz/dartz.dart';
part 'edit_select_option_bloc.freezed.dart'; part 'edit_select_option_bloc.freezed.dart';
class EditSelectOptionBloc extends Bloc<EditSelectOptionEvent, EditSelectOptionState> { class EditSelectOptionBloc extends Bloc<EditSelectOptionEvent, EditSelectOptionState> {
EditSelectOptionBloc({required SelectOption option}) : super(EditSelectOptionState.initial(option)) { EditSelectOptionBloc({required SelectOptionPB option}) : super(EditSelectOptionState.initial(option)) {
on<EditSelectOptionEvent>( on<EditSelectOptionEvent>(
(event, emit) async { (event, emit) async {
event.map( event.map(
@ -30,14 +30,14 @@ class EditSelectOptionBloc extends Bloc<EditSelectOptionEvent, EditSelectOptionS
return super.close(); return super.close();
} }
SelectOption _updateColor(SelectOptionColor color) { SelectOptionPB _updateColor(SelectOptionColorPB color) {
state.option.freeze(); state.option.freeze();
return state.option.rebuild((option) { return state.option.rebuild((option) {
option.color = color; option.color = color;
}); });
} }
SelectOption _updateName(String name) { SelectOptionPB _updateName(String name) {
state.option.freeze(); state.option.freeze();
return state.option.rebuild((option) { return state.option.rebuild((option) {
option.name = name; option.name = name;
@ -48,18 +48,18 @@ class EditSelectOptionBloc extends Bloc<EditSelectOptionEvent, EditSelectOptionS
@freezed @freezed
class EditSelectOptionEvent with _$EditSelectOptionEvent { class EditSelectOptionEvent with _$EditSelectOptionEvent {
const factory EditSelectOptionEvent.updateName(String name) = _UpdateName; const factory EditSelectOptionEvent.updateName(String name) = _UpdateName;
const factory EditSelectOptionEvent.updateColor(SelectOptionColor color) = _UpdateColor; const factory EditSelectOptionEvent.updateColor(SelectOptionColorPB color) = _UpdateColor;
const factory EditSelectOptionEvent.delete() = _Delete; const factory EditSelectOptionEvent.delete() = _Delete;
} }
@freezed @freezed
class EditSelectOptionState with _$EditSelectOptionState { class EditSelectOptionState with _$EditSelectOptionState {
const factory EditSelectOptionState({ const factory EditSelectOptionState({
required SelectOption option, required SelectOptionPB option,
required Option<bool> deleted, required Option<bool> deleted,
}) = _EditSelectOptionState; }) = _EditSelectOptionState;
factory EditSelectOptionState.initial(SelectOption option) => EditSelectOptionState( factory EditSelectOptionState.initial(SelectOptionPB option) => EditSelectOptionState(
option: option, option: option,
deleted: none(), deleted: none(),
); );

View File

@ -21,8 +21,8 @@ class MultiSelectTypeOptionContext extends TypeOptionWidgetContext<MultiSelectTy
super(dataParser: dataBuilder, dataController: dataController); super(dataParser: dataBuilder, dataController: dataController);
@override @override
List<SelectOption> Function(SelectOption) get deleteOption { List<SelectOptionPB> Function(SelectOptionPB) get deleteOption {
return (SelectOption option) { return (SelectOptionPB option) {
typeOption.freeze(); typeOption.freeze();
typeOption = typeOption.rebuild((typeOption) { typeOption = typeOption.rebuild((typeOption) {
final index = typeOption.options.indexWhere((element) => element.id == option.id); final index = typeOption.options.indexWhere((element) => element.id == option.id);
@ -35,7 +35,7 @@ class MultiSelectTypeOptionContext extends TypeOptionWidgetContext<MultiSelectTy
} }
@override @override
Future<List<SelectOption>> Function(String) get insertOption { Future<List<SelectOptionPB>> Function(String) get insertOption {
return (String optionName) { return (String optionName) {
return service.newOption(name: optionName).then((result) { return service.newOption(name: optionName).then((result) {
return result.fold( return result.fold(
@ -57,8 +57,8 @@ class MultiSelectTypeOptionContext extends TypeOptionWidgetContext<MultiSelectTy
} }
@override @override
List<SelectOption> Function(SelectOption) get udpateOption { List<SelectOptionPB> Function(SelectOptionPB) get udpateOption {
return (SelectOption option) { return (SelectOptionPB option) {
typeOption.freeze(); typeOption.freeze();
typeOption = typeOption.rebuild((typeOption) { typeOption = typeOption.rebuild((typeOption) {
final index = typeOption.options.indexWhere((element) => element.id == option.id); final index = typeOption.options.indexWhere((element) => element.id == option.id);

View File

@ -6,25 +6,25 @@ import 'package:dartz/dartz.dart';
part 'select_option_type_option_bloc.freezed.dart'; part 'select_option_type_option_bloc.freezed.dart';
abstract class SelectOptionTypeOptionAction { abstract class SelectOptionTypeOptionAction {
Future<List<SelectOption>> Function(String) get insertOption; Future<List<SelectOptionPB>> Function(String) get insertOption;
List<SelectOption> Function(SelectOption) get deleteOption; List<SelectOptionPB> Function(SelectOptionPB) get deleteOption;
List<SelectOption> Function(SelectOption) get udpateOption; List<SelectOptionPB> Function(SelectOptionPB) get udpateOption;
} }
class SelectOptionTypeOptionBloc extends Bloc<SelectOptionTypeOptionEvent, SelectOptionTypeOptionState> { class SelectOptionTypeOptionBloc extends Bloc<SelectOptionTypeOptionEvent, SelectOptionTypeOptionState> {
final SelectOptionTypeOptionAction typeOptionAction; final SelectOptionTypeOptionAction typeOptionAction;
SelectOptionTypeOptionBloc({ SelectOptionTypeOptionBloc({
required List<SelectOption> options, required List<SelectOptionPB> options,
required this.typeOptionAction, required this.typeOptionAction,
}) : super(SelectOptionTypeOptionState.initial(options)) { }) : super(SelectOptionTypeOptionState.initial(options)) {
on<SelectOptionTypeOptionEvent>( on<SelectOptionTypeOptionEvent>(
(event, emit) async { (event, emit) async {
await event.when( await event.when(
createOption: (optionName) async { createOption: (optionName) async {
final List<SelectOption> options = await typeOptionAction.insertOption(optionName); final List<SelectOptionPB> options = await typeOptionAction.insertOption(optionName);
emit(state.copyWith(options: options)); emit(state.copyWith(options: options));
}, },
addingOption: () { addingOption: () {
@ -34,11 +34,11 @@ class SelectOptionTypeOptionBloc extends Bloc<SelectOptionTypeOptionEvent, Selec
emit(state.copyWith(isEditingOption: false, newOptionName: none())); emit(state.copyWith(isEditingOption: false, newOptionName: none()));
}, },
updateOption: (option) { updateOption: (option) {
final List<SelectOption> options = typeOptionAction.udpateOption(option); final List<SelectOptionPB> options = typeOptionAction.udpateOption(option);
emit(state.copyWith(options: options)); emit(state.copyWith(options: options));
}, },
deleteOption: (option) { deleteOption: (option) {
final List<SelectOption> options = typeOptionAction.deleteOption(option); final List<SelectOptionPB> options = typeOptionAction.deleteOption(option);
emit(state.copyWith(options: options)); emit(state.copyWith(options: options));
}, },
); );
@ -57,19 +57,19 @@ class SelectOptionTypeOptionEvent with _$SelectOptionTypeOptionEvent {
const factory SelectOptionTypeOptionEvent.createOption(String optionName) = _CreateOption; const factory SelectOptionTypeOptionEvent.createOption(String optionName) = _CreateOption;
const factory SelectOptionTypeOptionEvent.addingOption() = _AddingOption; const factory SelectOptionTypeOptionEvent.addingOption() = _AddingOption;
const factory SelectOptionTypeOptionEvent.endAddingOption() = _EndAddingOption; const factory SelectOptionTypeOptionEvent.endAddingOption() = _EndAddingOption;
const factory SelectOptionTypeOptionEvent.updateOption(SelectOption option) = _UpdateOption; const factory SelectOptionTypeOptionEvent.updateOption(SelectOptionPB option) = _UpdateOption;
const factory SelectOptionTypeOptionEvent.deleteOption(SelectOption option) = _DeleteOption; const factory SelectOptionTypeOptionEvent.deleteOption(SelectOptionPB option) = _DeleteOption;
} }
@freezed @freezed
class SelectOptionTypeOptionState with _$SelectOptionTypeOptionState { class SelectOptionTypeOptionState with _$SelectOptionTypeOptionState {
const factory SelectOptionTypeOptionState({ const factory SelectOptionTypeOptionState({
required List<SelectOption> options, required List<SelectOptionPB> options,
required bool isEditingOption, required bool isEditingOption,
required Option<String> newOptionName, required Option<String> newOptionName,
}) = _SelectOptionTyepOptionState; }) = _SelectOptionTyepOptionState;
factory SelectOptionTypeOptionState.initial(List<SelectOption> options) => SelectOptionTypeOptionState( factory SelectOptionTypeOptionState.initial(List<SelectOptionPB> options) => SelectOptionTypeOptionState(
options: options, options: options,
isEditingOption: false, isEditingOption: false,
newOptionName: none(), newOptionName: none(),

View File

@ -7,7 +7,7 @@ import 'package:protobuf/protobuf.dart';
import 'select_option_type_option_bloc.dart'; import 'select_option_type_option_bloc.dart';
import 'type_option_service.dart'; import 'type_option_service.dart';
class SingleSelectTypeOptionContext extends TypeOptionWidgetContext<SingleSelectTypeOption> class SingleSelectTypeOptionContext extends TypeOptionWidgetContext<SingleSelectTypeOptionPB>
with SelectOptionTypeOptionAction { with SelectOptionTypeOptionAction {
final TypeOptionService service; final TypeOptionService service;
@ -21,8 +21,8 @@ class SingleSelectTypeOptionContext extends TypeOptionWidgetContext<SingleSelect
super(dataParser: dataBuilder, dataController: fieldContext); super(dataParser: dataBuilder, dataController: fieldContext);
@override @override
List<SelectOption> Function(SelectOption) get deleteOption { List<SelectOptionPB> Function(SelectOptionPB) get deleteOption {
return (SelectOption option) { return (SelectOptionPB option) {
typeOption.freeze(); typeOption.freeze();
typeOption = typeOption.rebuild((typeOption) { typeOption = typeOption.rebuild((typeOption) {
final index = typeOption.options.indexWhere((element) => element.id == option.id); final index = typeOption.options.indexWhere((element) => element.id == option.id);
@ -35,7 +35,7 @@ class SingleSelectTypeOptionContext extends TypeOptionWidgetContext<SingleSelect
} }
@override @override
Future<List<SelectOption>> Function(String) get insertOption { Future<List<SelectOptionPB>> Function(String) get insertOption {
return (String optionName) { return (String optionName) {
return service.newOption(name: optionName).then((result) { return service.newOption(name: optionName).then((result) {
return result.fold( return result.fold(
@ -57,8 +57,8 @@ class SingleSelectTypeOptionContext extends TypeOptionWidgetContext<SingleSelect
} }
@override @override
List<SelectOption> Function(SelectOption) get udpateOption { List<SelectOptionPB> Function(SelectOptionPB) get udpateOption {
return (SelectOption option) { return (SelectOptionPB option) {
typeOption.freeze(); typeOption.freeze();
typeOption = typeOption.rebuild((typeOption) { typeOption = typeOption.rebuild((typeOption) {
final index = typeOption.options.indexWhere((element) => element.id == option.id); final index = typeOption.options.indexWhere((element) => element.id == option.id);
@ -71,9 +71,9 @@ class SingleSelectTypeOptionContext extends TypeOptionWidgetContext<SingleSelect
} }
} }
class SingleSelectTypeOptionWidgetDataParser extends TypeOptionDataParser<SingleSelectTypeOption> { class SingleSelectTypeOptionWidgetDataParser extends TypeOptionDataParser<SingleSelectTypeOptionPB> {
@override @override
SingleSelectTypeOption fromBuffer(List<int> buffer) { SingleSelectTypeOptionPB fromBuffer(List<int> buffer) {
return SingleSelectTypeOption.fromBuffer(buffer); return SingleSelectTypeOptionPB.fromBuffer(buffer);
} }
} }

View File

@ -18,14 +18,14 @@ class TypeOptionService {
required this.fieldId, required this.fieldId,
}); });
Future<Either<SelectOption, FlowyError>> newOption({ Future<Either<SelectOptionPB, FlowyError>> newOption({
required String name, required String name,
}) { }) {
final fieldIdentifier = FieldIdentifierPayload.create() final fieldIdentifier = GridFieldIdentifierPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldId = fieldId; ..fieldId = fieldId;
final payload = CreateSelectOptionPayload.create() final payload = CreateSelectOptionPayloadPB.create()
..optionName = name ..optionName = name
..fieldIdentifier = fieldIdentifier; ..fieldIdentifier = fieldIdentifier;
@ -49,7 +49,7 @@ class TypeOptionWidgetContext<T extends GeneratedMessage> {
String get gridId => _dataController.gridId; String get gridId => _dataController.gridId;
Field get field => _dataController.field; GridFieldPB get field => _dataController.field;
T get typeOption { T get typeOption {
if (_typeOptionObject != null) { if (_typeOptionObject != null) {
@ -74,7 +74,7 @@ abstract class TypeOptionFieldDelegate {
class TypeOptionContext2<T> { class TypeOptionContext2<T> {
final String gridId; final String gridId;
final Field field; final GridFieldPB field;
final FieldService _fieldService; final FieldService _fieldService;
T? _data; T? _data;
final TypeOptionDataParser dataBuilder; final TypeOptionDataParser dataBuilder;

View File

@ -22,8 +22,8 @@ class GridBloc extends Bloc<GridEvent, GridState> {
// key: the block id // key: the block id
final LinkedHashMap<String, GridBlockCache> _blocks; final LinkedHashMap<String, GridBlockCache> _blocks;
List<GridRow> get rows { List<GridRowInfo> get rowInfos {
final List<GridRow> rows = []; final List<GridRowInfo> rows = [];
for (var block in _blocks.values) { for (var block in _blocks.values) {
rows.addAll(block.rows); rows.addAll(block.rows);
} }
@ -46,11 +46,11 @@ class GridBloc extends Bloc<GridEvent, GridState> {
createRow: () { createRow: () {
_gridService.createRow(); _gridService.createRow();
}, },
didReceiveRowUpdate: (rows, reason) { didReceiveRowUpdate: (newRowInfos, reason) {
emit(state.copyWith(rows: rows, reason: reason)); emit(state.copyWith(rowInfos: newRowInfos, reason: reason));
}, },
didReceiveFieldUpdate: (fields) { didReceiveFieldUpdate: (fields) {
emit(state.copyWith(rows: rows, fields: GridFieldEquatable(fields))); emit(state.copyWith(rowInfos: rowInfos, fields: GridFieldEquatable(fields)));
}, },
); );
}, },
@ -93,8 +93,8 @@ class GridBloc extends Bloc<GridEvent, GridState> {
); );
} }
Future<void> _loadFields(Grid grid, Emitter<GridState> emit) async { Future<void> _loadFields(GridPB grid, Emitter<GridState> emit) async {
final result = await _gridService.getFields(fieldOrders: grid.fieldOrders); final result = await _gridService.getFields(fieldIds: grid.fields);
return Future( return Future(
() => result.fold( () => result.fold(
(fields) { (fields) {
@ -103,7 +103,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
emit(state.copyWith( emit(state.copyWith(
grid: Some(grid), grid: Some(grid),
fields: GridFieldEquatable(fieldCache.fields), fields: GridFieldEquatable(fieldCache.fields),
rows: rows, rowInfos: rowInfos,
loadingState: GridLoadingState.finish(left(unit)), loadingState: GridLoadingState.finish(left(unit)),
)); ));
}, },
@ -112,7 +112,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
); );
} }
void _initialBlocks(List<GridBlock> blocks) { void _initialBlocks(List<GridBlockPB> blocks) {
for (final block in blocks) { for (final block in blocks) {
if (_blocks[block.id] != null) { if (_blocks[block.id] != null) {
Log.warn("Intial duplicate block's cache: ${block.id}"); Log.warn("Intial duplicate block's cache: ${block.id}");
@ -127,7 +127,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
cache.addListener( cache.addListener(
listenWhen: () => !isClosed, listenWhen: () => !isClosed,
onChangeReason: (reason) => add(GridEvent.didReceiveRowUpdate(rows, reason)), onChangeReason: (reason) => add(GridEvent.didReceiveRowUpdate(rowInfos, reason)),
); );
_blocks[block.id] = cache; _blocks[block.id] = cache;
@ -139,24 +139,25 @@ class GridBloc extends Bloc<GridEvent, GridState> {
class GridEvent with _$GridEvent { 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(List<GridRow> rows, GridRowChangeReason listState) = _DidReceiveRowUpdate; const factory GridEvent.didReceiveRowUpdate(List<GridRowInfo> rows, GridRowChangeReason listState) =
const factory GridEvent.didReceiveFieldUpdate(List<Field> fields) = _DidReceiveFieldUpdate; _DidReceiveRowUpdate;
const factory GridEvent.didReceiveFieldUpdate(List<GridFieldPB> fields) = _DidReceiveFieldUpdate;
} }
@freezed @freezed
class GridState with _$GridState { class GridState with _$GridState {
const factory GridState({ const factory GridState({
required String gridId, required String gridId,
required Option<Grid> grid, required Option<GridPB> grid,
required GridFieldEquatable fields, required GridFieldEquatable fields,
required List<GridRow> rows, required List<GridRowInfo> rowInfos,
required GridLoadingState loadingState, required GridLoadingState loadingState,
required GridRowChangeReason reason, required GridRowChangeReason reason,
}) = _GridState; }) = _GridState;
factory GridState.initial(String gridId) => GridState( factory GridState.initial(String gridId) => GridState(
fields: const GridFieldEquatable([]), fields: const GridFieldEquatable([]),
rows: [], rowInfos: [],
grid: none(), grid: none(),
gridId: gridId, gridId: gridId,
loadingState: const _Loading(), loadingState: const _Loading(),
@ -171,8 +172,8 @@ class GridLoadingState with _$GridLoadingState {
} }
class GridFieldEquatable extends Equatable { class GridFieldEquatable extends Equatable {
final List<Field> _fields; final List<GridFieldPB> _fields;
const GridFieldEquatable(List<Field> fields) : _fields = fields; const GridFieldEquatable(List<GridFieldPB> fields) : _fields = fields;
@override @override
List<Object?> get props { List<Object?> get props {
@ -182,5 +183,5 @@ class GridFieldEquatable extends Equatable {
]; ];
} }
UnmodifiableListView<Field> get value => UnmodifiableListView(_fields); UnmodifiableListView<GridFieldPB> get value => UnmodifiableListView(_fields);
} }

View File

@ -34,7 +34,7 @@ class GridHeaderBloc extends Bloc<GridHeaderEvent, GridHeaderState> {
} }
Future<void> _moveField(_MoveField value, Emitter<GridHeaderState> emit) async { Future<void> _moveField(_MoveField value, Emitter<GridHeaderState> emit) async {
final fields = List<Field>.from(state.fields); final fields = List<GridFieldPB>.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));
@ -62,16 +62,16 @@ 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(List<Field> fields) = _DidReceiveFieldUpdate; const factory GridHeaderEvent.didReceiveFieldUpdate(List<GridFieldPB> fields) = _DidReceiveFieldUpdate;
const factory GridHeaderEvent.moveField(Field field, int fromIndex, int toIndex) = _MoveField; const factory GridHeaderEvent.moveField(GridFieldPB field, int fromIndex, int toIndex) = _MoveField;
} }
@freezed @freezed
class GridHeaderState with _$GridHeaderState { class GridHeaderState with _$GridHeaderState {
const factory GridHeaderState({required List<Field> fields}) = _GridHeaderState; const factory GridHeaderState({required List<GridFieldPB> fields}) = _GridHeaderState;
factory GridHeaderState.initial(List<Field> fields) { factory GridHeaderState.initial(List<GridFieldPB> fields) {
// final List<Field> newFields = List.from(fields); // final List<GridFieldPB> newFields = List.from(fields);
// newFields.retainWhere((field) => field.visibility); // newFields.retainWhere((field) => field.visibility);
return GridHeaderState(fields: fields); return GridHeaderState(fields: fields);
} }

View File

@ -19,23 +19,23 @@ class GridService {
required this.gridId, required this.gridId,
}); });
Future<Either<Grid, FlowyError>> loadGrid() async { Future<Either<GridPB, FlowyError>> loadGrid() async {
await FolderEventSetLatestView(ViewId(value: gridId)).send(); await FolderEventSetLatestView(ViewId(value: gridId)).send();
final payload = GridId(value: gridId); final payload = GridIdPB(value: gridId);
return GridEventGetGrid(payload).send(); return GridEventGetGrid(payload).send();
} }
Future<Either<Row, FlowyError>> createRow({Option<String>? startRowId}) { Future<Either<GridRowPB, FlowyError>> createRow({Option<String>? startRowId}) {
CreateRowPayload payload = CreateRowPayload.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<RepeatedField, FlowyError>> getFields({required List<FieldOrder> fieldOrders}) { Future<Either<RepeatedGridFieldPB, FlowyError>> getFields({required List<GridFieldIdPB> fieldIds}) {
final payload = QueryFieldPayload.create() final payload = QueryFieldPayloadPB.create()
..gridId = gridId ..gridId = gridId
..fieldOrders = RepeatedFieldOrder(items: fieldOrders); ..fieldIds = RepeatedGridFieldIdPB(items: fieldIds);
return GridEventGetFields(payload).send(); return GridEventGetFields(payload).send();
} }
@ -46,18 +46,18 @@ class GridService {
} }
class FieldsNotifier extends ChangeNotifier { class FieldsNotifier extends ChangeNotifier {
List<Field> _fields = []; List<GridFieldPB> _fields = [];
set fields(List<Field> fields) { set fields(List<GridFieldPB> fields) {
_fields = fields; _fields = fields;
notifyListeners(); notifyListeners();
} }
List<Field> get fields => _fields; List<GridFieldPB> get fields => _fields;
} }
typedef FieldChangesetCallback = void Function(GridFieldChangeset); typedef FieldChangesetCallback = void Function(GridFieldChangesetPB);
typedef FieldsCallback = void Function(List<Field>); typedef FieldsCallback = void Function(List<GridFieldPB>);
class GridFieldCache { class GridFieldCache {
final String gridId; final String gridId;
@ -88,11 +88,11 @@ class GridFieldCache {
_fieldNotifier = null; _fieldNotifier = null;
} }
UnmodifiableListView<Field> get unmodifiableFields => UnmodifiableListView(_fieldNotifier?.fields ?? []); UnmodifiableListView<GridFieldPB> get unmodifiableFields => UnmodifiableListView(_fieldNotifier?.fields ?? []);
List<Field> get fields => [..._fieldNotifier?.fields ?? []]; List<GridFieldPB> get fields => [..._fieldNotifier?.fields ?? []];
set fields(List<Field> fields) { set fields(List<GridFieldPB> fields) {
_fieldNotifier?.fields = [...fields]; _fieldNotifier?.fields = [...fields];
} }
@ -141,12 +141,12 @@ class GridFieldCache {
} }
} }
void _deleteFields(List<FieldOrder> deletedFields) { void _deleteFields(List<GridFieldIdPB> deletedFields) {
if (deletedFields.isEmpty) { if (deletedFields.isEmpty) {
return; return;
} }
final List<Field> newFields = fields; final List<GridFieldPB> newFields = fields;
final Map<String, FieldOrder> deletedFieldMap = { final Map<String, GridFieldIdPB> deletedFieldMap = {
for (var fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder for (var fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder
}; };
@ -154,11 +154,11 @@ class GridFieldCache {
_fieldNotifier?.fields = newFields; _fieldNotifier?.fields = newFields;
} }
void _insertFields(List<IndexField> insertedFields) { void _insertFields(List<IndexFieldPB> insertedFields) {
if (insertedFields.isEmpty) { if (insertedFields.isEmpty) {
return; return;
} }
final List<Field> newFields = fields; final List<GridFieldPB> 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);
@ -169,11 +169,11 @@ class GridFieldCache {
_fieldNotifier?.fields = newFields; _fieldNotifier?.fields = newFields;
} }
void _updateFields(List<Field> updatedFields) { void _updateFields(List<GridFieldPB> updatedFields) {
if (updatedFields.isEmpty) { if (updatedFields.isEmpty) {
return; return;
} }
final List<Field> newFields = fields; final List<GridFieldPB> newFields = fields;
for (final updatedField in updatedFields) { for (final updatedField in updatedFields) {
final index = newFields.indexWhere((field) => field.id == updatedField.id); final index = newFields.indexWhere((field) => field.id == updatedField.id);
if (index != -1) { if (index != -1) {
@ -192,7 +192,7 @@ class GridRowCacheFieldNotifierImpl extends GridRowCacheFieldNotifier {
GridRowCacheFieldNotifierImpl(GridFieldCache cache) : _cache = cache; GridRowCacheFieldNotifierImpl(GridFieldCache cache) : _cache = cache;
@override @override
UnmodifiableListView<Field> get fields => _cache.unmodifiableFields; UnmodifiableListView<GridFieldPB> get fields => _cache.unmodifiableFields;
@override @override
void onFieldsChanged(VoidCallback callback) { void onFieldsChanged(VoidCallback callback) {
@ -201,8 +201,8 @@ class GridRowCacheFieldNotifierImpl extends GridRowCacheFieldNotifier {
} }
@override @override
void onFieldChanged(void Function(Field) callback) { void onFieldChanged(void Function(GridFieldPB) callback) {
_onChangesetFn = (GridFieldChangeset changeset) { _onChangesetFn = (GridFieldChangesetPB changeset) {
for (final updatedField in changeset.updatedFields) { for (final updatedField in changeset.updatedFields) {
callback(updatedField); callback(updatedField);
} }

View File

@ -4,18 +4,18 @@ export 'row/row_service.dart';
export 'grid_service.dart'; export 'grid_service.dart';
export 'grid_header_bloc.dart'; export 'grid_header_bloc.dart';
// Field // GridFieldPB
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';
// Field Type Option // GridFieldPB 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';
// Cell // GridCellPB
export 'cell/text_cell_bloc.dart'; export 'cell/text_cell_bloc.dart';
export 'cell/number_cell_bloc.dart'; export 'cell/number_cell_bloc.dart';
export 'cell/select_option_cell_bloc.dart'; export 'cell/select_option_cell_bloc.dart';

View File

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

View File

@ -15,15 +15,15 @@ class RowBloc extends Bloc<RowEvent, RowState> {
void Function()? _rowListenFn; void Function()? _rowListenFn;
RowBloc({ RowBloc({
required GridRow rowData, required GridRowInfo rowInfo,
required GridRowCache rowCache, required GridRowCache rowCache,
}) : _rowService = RowService( }) : _rowService = RowService(
gridId: rowData.gridId, gridId: rowInfo.gridId,
blockId: rowData.blockId, blockId: rowInfo.blockId,
rowId: rowData.id, rowId: rowInfo.id,
), ),
_rowCache = rowCache, _rowCache = rowCache,
super(RowState.initial(rowData, rowCache.loadGridCells(rowData.id))) { super(RowState.initial(rowInfo, rowCache.loadGridCells(rowInfo.id))) {
on<RowEvent>( on<RowEvent>(
(event, emit) async { (event, emit) async {
await event.map( await event.map(
@ -58,7 +58,7 @@ class RowBloc extends Bloc<RowEvent, RowState> {
Future<void> _startListening() async { Future<void> _startListening() async {
_rowListenFn = _rowCache.addListener( _rowListenFn = _rowCache.addListener(
rowId: state.rowData.id, rowId: state.rowInfo.id,
onCellUpdated: (cellDatas, reason) => add(RowEvent.didReceiveCellDatas(cellDatas, reason)), onCellUpdated: (cellDatas, reason) => add(RowEvent.didReceiveCellDatas(cellDatas, reason)),
listenWhen: () => !isClosed, listenWhen: () => !isClosed,
); );
@ -76,23 +76,23 @@ class RowEvent with _$RowEvent {
@freezed @freezed
class RowState with _$RowState { class RowState with _$RowState {
const factory RowState({ const factory RowState({
required GridRow rowData, required GridRowInfo rowInfo,
required GridCellMap gridCellMap, required GridCellMap gridCellMap,
required UnmodifiableListView<GridCellEquatable> snapshots, required UnmodifiableListView<GridCellEquatable> snapshots,
GridRowChangeReason? changeReason, GridRowChangeReason? changeReason,
}) = _RowState; }) = _RowState;
factory RowState.initial(GridRow rowData, GridCellMap cellDataMap) => RowState( factory RowState.initial(GridRowInfo rowInfo, GridCellMap cellDataMap) => RowState(
rowData: rowData, rowInfo: rowInfo,
gridCellMap: cellDataMap, gridCellMap: cellDataMap,
snapshots: UnmodifiableListView(cellDataMap.values.map((e) => GridCellEquatable(e.field)).toList()), snapshots: UnmodifiableListView(cellDataMap.values.map((e) => GridCellEquatable(e.field)).toList()),
); );
} }
class GridCellEquatable extends Equatable { class GridCellEquatable extends Equatable {
final Field _field; final GridFieldPB _field;
const GridCellEquatable(Field field) : _field = field; const GridCellEquatable(GridFieldPB field) : _field = field;
@override @override
List<Object?> get props => [ List<Object?> get props => [

View File

@ -7,12 +7,12 @@ import 'row_service.dart';
part 'row_detail_bloc.freezed.dart'; part 'row_detail_bloc.freezed.dart';
class RowDetailBloc extends Bloc<RowDetailEvent, RowDetailState> { class RowDetailBloc extends Bloc<RowDetailEvent, RowDetailState> {
final GridRow rowData; final GridRowInfo rowInfo;
final GridRowCache _rowCache; final GridRowCache _rowCache;
void Function()? _rowListenFn; void Function()? _rowListenFn;
RowDetailBloc({ RowDetailBloc({
required this.rowData, required this.rowInfo,
required GridRowCache rowCache, required GridRowCache rowCache,
}) : _rowCache = rowCache, }) : _rowCache = rowCache,
super(RowDetailState.initial()) { super(RowDetailState.initial()) {
@ -41,14 +41,14 @@ class RowDetailBloc extends Bloc<RowDetailEvent, RowDetailState> {
Future<void> _startListening() async { Future<void> _startListening() async {
_rowListenFn = _rowCache.addListener( _rowListenFn = _rowCache.addListener(
rowId: rowData.id, rowId: rowInfo.id,
onCellUpdated: (cellDatas, reason) => add(RowDetailEvent.didReceiveCellDatas(cellDatas.values.toList())), onCellUpdated: (cellDatas, reason) => add(RowDetailEvent.didReceiveCellDatas(cellDatas.values.toList())),
listenWhen: () => !isClosed, listenWhen: () => !isClosed,
); );
} }
Future<void> _loadCellData() async { Future<void> _loadCellData() async {
final cellDataMap = _rowCache.loadGridCells(rowData.id); final cellDataMap = _rowCache.loadGridCells(rowInfo.id);
if (!isClosed) { if (!isClosed) {
add(RowDetailEvent.didReceiveCellDatas(cellDataMap.values.toList())); add(RowDetailEvent.didReceiveCellDatas(cellDataMap.values.toList()));
} }

View File

@ -8,8 +8,8 @@ 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<Row, FlowyError>; typedef UpdateRowNotifiedValue = Either<GridRowPB, FlowyError>;
typedef UpdateFieldNotifiedValue = Either<List<Field>, FlowyError>; typedef UpdateFieldNotifiedValue = Either<List<GridFieldPB>, FlowyError>;
class RowListener { class RowListener {
final String rowId; final String rowId;
@ -26,7 +26,7 @@ class RowListener {
switch (ty) { switch (ty) {
case GridNotification.DidUpdateRow: case GridNotification.DidUpdateRow:
result.fold( result.fold(
(payload) => updateRowNotifier?.value = left(Row.fromBuffer(payload)), (payload) => updateRowNotifier?.value = left(GridRowPB.fromBuffer(payload)),
(error) => updateRowNotifier?.value = right(error), (error) => updateRowNotifier?.value = right(error),
); );
break; break;

View File

@ -15,9 +15,9 @@ part 'row_service.freezed.dart';
typedef RowUpdateCallback = void Function(); typedef RowUpdateCallback = void Function();
abstract class GridRowCacheFieldNotifier { abstract class GridRowCacheFieldNotifier {
UnmodifiableListView<Field> get fields; UnmodifiableListView<GridFieldPB> get fields;
void onFieldsChanged(VoidCallback callback); void onFieldsChanged(VoidCallback callback);
void onFieldChanged(void Function(Field) callback); void onFieldChanged(void Function(GridFieldPB) callback);
void dispose(); void dispose();
} }
@ -28,20 +28,20 @@ abstract class GridRowCacheFieldNotifier {
class GridRowCache { class GridRowCache {
final String gridId; final String gridId;
final GridBlock block; final GridBlockPB 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<GridRow> _rows = []; List<GridRowInfo> _rowInfos = [];
/// Use Map for faster access the raw row data. /// Use Map for faster access the raw row data.
final HashMap<String, Row> _rowByRowId; final HashMap<String, GridRowPB> _rowByRowId;
final GridCellCache _cellCache; final GridCellCache _cellCache;
final GridRowCacheFieldNotifier _fieldNotifier; final GridRowCacheFieldNotifier _fieldNotifier;
final _GridRowChangesetNotifier _rowChangeReasonNotifier; final _GridRowChangesetNotifier _rowChangeReasonNotifier;
UnmodifiableListView<GridRow> get rows => UnmodifiableListView(_rows); UnmodifiableListView<GridRowInfo> get rows => UnmodifiableListView(_rowInfos);
GridCellCache get cellCache => _cellCache; GridCellCache get cellCache => _cellCache;
GridRowCache({ GridRowCache({
@ -55,7 +55,7 @@ class GridRowCache {
// //
notifier.onFieldsChanged(() => _rowChangeReasonNotifier.receive(const GridRowChangeReason.fieldDidChange())); notifier.onFieldsChanged(() => _rowChangeReasonNotifier.receive(const GridRowChangeReason.fieldDidChange()));
notifier.onFieldChanged((field) => _cellCache.remove(field.id)); notifier.onFieldChanged((field) => _cellCache.remove(field.id));
_rows = block.rowInfos.map((rowInfo) => buildGridRow(rowInfo.rowId, rowInfo.height.toDouble())).toList(); _rowInfos = block.rows.map((rowInfo) => buildGridRow(rowInfo.id, rowInfo.height.toDouble())).toList();
} }
Future<void> dispose() async { Future<void> dispose() async {
@ -64,7 +64,7 @@ class GridRowCache {
await _cellCache.dispose(); await _cellCache.dispose();
} }
void applyChangesets(List<GridBlockChangeset> changesets) { void applyChangesets(List<GridBlockChangesetPB> changesets) {
for (final changeset in changesets) { for (final changeset in changesets) {
_deleteRows(changeset.deletedRows); _deleteRows(changeset.deletedRows);
_insertRows(changeset.insertedRows); _insertRows(changeset.insertedRows);
@ -79,11 +79,11 @@ class GridRowCache {
return; return;
} }
final List<GridRow> newRows = []; final List<GridRowInfo> newRows = [];
final DeletedIndexs deletedIndex = []; final DeletedIndexs deletedIndex = [];
final Map<String, String> deletedRowByRowId = {for (var rowId in deletedRows) rowId: rowId}; final Map<String, String> deletedRowByRowId = {for (var rowId in deletedRows) rowId: rowId};
_rows.asMap().forEach((index, row) { _rowInfos.asMap().forEach((index, row) {
if (deletedRowByRowId[row.id] == null) { if (deletedRowByRowId[row.id] == null) {
newRows.add(row); newRows.add(row);
} else { } else {
@ -91,11 +91,11 @@ class GridRowCache {
deletedIndex.add(DeletedIndex(index: index, row: row)); deletedIndex.add(DeletedIndex(index: index, row: row));
} }
}); });
_rows = newRows; _rowInfos = newRows;
_rowChangeReasonNotifier.receive(GridRowChangeReason.delete(deletedIndex)); _rowChangeReasonNotifier.receive(GridRowChangeReason.delete(deletedIndex));
} }
void _insertRows(List<InsertedRow> insertRows) { void _insertRows(List<InsertedRowPB> insertRows) {
if (insertRows.isEmpty) { if (insertRows.isEmpty) {
return; return;
} }
@ -107,13 +107,13 @@ class GridRowCache {
rowId: insertRow.rowId, rowId: insertRow.rowId,
); );
insertIndexs.add(insertIndex); insertIndexs.add(insertIndex);
_rows.insert(insertRow.index, (buildGridRow(insertRow.rowId, insertRow.height.toDouble()))); _rowInfos.insert(insertRow.index, (buildGridRow(insertRow.rowId, insertRow.height.toDouble())));
} }
_rowChangeReasonNotifier.receive(GridRowChangeReason.insert(insertIndexs)); _rowChangeReasonNotifier.receive(GridRowChangeReason.insert(insertIndexs));
} }
void _updateRows(List<UpdatedRow> updatedRows) { void _updateRows(List<UpdatedRowPB> updatedRows) {
if (updatedRows.isEmpty) { if (updatedRows.isEmpty) {
return; return;
} }
@ -121,12 +121,12 @@ class GridRowCache {
final UpdatedIndexs updatedIndexs = UpdatedIndexs(); final UpdatedIndexs updatedIndexs = UpdatedIndexs();
for (final updatedRow in updatedRows) { for (final updatedRow in updatedRows) {
final rowId = updatedRow.rowId; final rowId = updatedRow.rowId;
final index = _rows.indexWhere((row) => row.id == rowId); final index = _rowInfos.indexWhere((row) => row.id == rowId);
if (index != -1) { if (index != -1) {
_rowByRowId[rowId] = updatedRow.row; _rowByRowId[rowId] = updatedRow.row;
_rows.removeAt(index); _rowInfos.removeAt(index);
_rows.insert(index, buildGridRow(rowId, updatedRow.row.height.toDouble())); _rowInfos.insert(index, buildGridRow(rowId, updatedRow.row.height.toDouble()));
updatedIndexs[rowId] = UpdatedIndex(index: index, rowId: rowId); updatedIndexs[rowId] = UpdatedIndex(index: index, rowId: rowId);
} }
} }
@ -183,7 +183,7 @@ class GridRowCache {
} }
GridCellMap loadGridCells(String rowId) { GridCellMap loadGridCells(String rowId) {
final Row? data = _rowByRowId[rowId]; final GridRowPB? data = _rowByRowId[rowId];
if (data == null) { if (data == null) {
_loadRow(rowId); _loadRow(rowId);
} }
@ -191,7 +191,7 @@ class GridRowCache {
} }
Future<void> _loadRow(String rowId) async { Future<void> _loadRow(String rowId) async {
final payload = GridRowIdPayload.create() final payload = GridRowIdPayloadPB.create()
..gridId = gridId ..gridId = gridId
..blockId = block.id ..blockId = block.id
..rowId = rowId; ..rowId = rowId;
@ -203,7 +203,7 @@ class GridRowCache {
); );
} }
GridCellMap _makeGridCells(String rowId, Row? row) { GridCellMap _makeGridCells(String rowId, GridRowPB? 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) {
@ -217,7 +217,7 @@ class GridRowCache {
return cellDataMap; return cellDataMap;
} }
void _refreshRow(OptionalRow optionRow) { void _refreshRow(OptionalRowPB optionRow) {
if (!optionRow.hasRow()) { if (!optionRow.hasRow()) {
return; return;
} }
@ -225,12 +225,12 @@ class GridRowCache {
updatedRow.freeze(); updatedRow.freeze();
_rowByRowId[updatedRow.id] = updatedRow; _rowByRowId[updatedRow.id] = updatedRow;
final index = _rows.indexWhere((gridRow) => gridRow.id == updatedRow.id); final index = _rowInfos.indexWhere((gridRow) => gridRow.id == updatedRow.id);
if (index != -1) { if (index != -1) {
// update the corresponding row in _rows if they are not the same // update the corresponding row in _rows if they are not the same
if (_rows[index].rawRow != updatedRow) { if (_rowInfos[index].rawRow != updatedRow) {
final row = _rows.removeAt(index).copyWith(rawRow: updatedRow); final row = _rowInfos.removeAt(index).copyWith(rawRow: updatedRow);
_rows.insert(index, row); _rowInfos.insert(index, row);
// Calculate the update index // Calculate the update index
final UpdatedIndexs updatedIndexs = UpdatedIndexs(); final UpdatedIndexs updatedIndexs = UpdatedIndexs();
@ -242,8 +242,8 @@ class GridRowCache {
} }
} }
GridRow buildGridRow(String rowId, double rowHeight) { GridRowInfo buildGridRow(String rowId, double rowHeight) {
return GridRow( return GridRowInfo(
gridId: gridId, gridId: gridId,
blockId: block.id, blockId: block.id,
fields: _fieldNotifier.fields, fields: _fieldNotifier.fields,
@ -277,8 +277,8 @@ class RowService {
RowService({required this.gridId, required this.blockId, required this.rowId}); RowService({required this.gridId, required this.blockId, required this.rowId});
Future<Either<Row, FlowyError>> createRow() { Future<Either<GridRowPB, FlowyError>> createRow() {
CreateRowPayload payload = CreateRowPayload.create() CreateRowPayloadPB payload = CreateRowPayloadPB.create()
..gridId = gridId ..gridId = gridId
..startRowId = rowId; ..startRowId = rowId;
@ -286,18 +286,18 @@ class RowService {
} }
Future<Either<Unit, FlowyError>> moveRow(String rowId, int fromIndex, int toIndex) { Future<Either<Unit, FlowyError>> moveRow(String rowId, int fromIndex, int toIndex) {
final payload = MoveItemPayload.create() final payload = MoveItemPayloadPB.create()
..gridId = gridId ..gridId = gridId
..itemId = rowId ..itemId = rowId
..ty = MoveItemType.MoveRow ..ty = MoveItemTypePB.MoveRow
..fromIndex = fromIndex ..fromIndex = fromIndex
..toIndex = toIndex; ..toIndex = toIndex;
return GridEventMoveItem(payload).send(); return GridEventMoveItem(payload).send();
} }
Future<Either<OptionalRow, FlowyError>> getRow() { Future<Either<OptionalRowPB, FlowyError>> getRow() {
final payload = GridRowIdPayload.create() final payload = GridRowIdPayloadPB.create()
..gridId = gridId ..gridId = gridId
..blockId = blockId ..blockId = blockId
..rowId = rowId; ..rowId = rowId;
@ -306,7 +306,7 @@ class RowService {
} }
Future<Either<Unit, FlowyError>> deleteRow() { Future<Either<Unit, FlowyError>> deleteRow() {
final payload = GridRowIdPayload.create() final payload = GridRowIdPayloadPB.create()
..gridId = gridId ..gridId = gridId
..blockId = blockId ..blockId = blockId
..rowId = rowId; ..rowId = rowId;
@ -315,7 +315,7 @@ class RowService {
} }
Future<Either<Unit, FlowyError>> duplicateRow() { Future<Either<Unit, FlowyError>> duplicateRow() {
final payload = GridRowIdPayload.create() final payload = GridRowIdPayloadPB.create()
..gridId = gridId ..gridId = gridId
..blockId = blockId ..blockId = blockId
..rowId = rowId; ..rowId = rowId;
@ -325,15 +325,15 @@ class RowService {
} }
@freezed @freezed
class GridRow with _$GridRow { class GridRowInfo with _$GridRowInfo {
const factory GridRow({ const factory GridRowInfo({
required String gridId, required String gridId,
required String blockId, required String blockId,
required String id, required String id,
required UnmodifiableListView<Field> fields, required UnmodifiableListView<GridFieldPB> fields,
required double height, required double height,
Row? rawRow, GridRowPB? rawRow,
}) = _GridRow; }) = _GridRowInfo;
} }
typedef InsertedIndexs = List<InsertedIndex>; typedef InsertedIndexs = List<InsertedIndex>;
@ -360,7 +360,7 @@ class InsertedIndex {
class DeletedIndex { class DeletedIndex {
final int index; final int index;
final GridRow row; final GridRowInfo row;
DeletedIndex({ DeletedIndex({
required this.index, required this.index,
required this.row, required this.row,

View File

@ -10,7 +10,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<Field>)? _onFieldsFn; Function(List<GridFieldPB>)? _onFieldsFn;
GridPropertyBloc({required String gridId, required GridFieldCache fieldCache}) GridPropertyBloc({required String gridId, required GridFieldCache fieldCache})
: _fieldCache = fieldCache, : _fieldCache = fieldCache,
@ -62,7 +62,7 @@ class GridPropertyBloc extends Bloc<GridPropertyEvent, GridPropertyState> {
class GridPropertyEvent with _$GridPropertyEvent { class GridPropertyEvent with _$GridPropertyEvent {
const factory GridPropertyEvent.initial() = _Initial; const factory GridPropertyEvent.initial() = _Initial;
const factory GridPropertyEvent.setFieldVisibility(String fieldId, bool visibility) = _SetFieldVisibility; const factory GridPropertyEvent.setFieldVisibility(String fieldId, bool visibility) = _SetFieldVisibility;
const factory GridPropertyEvent.didReceiveFieldUpdate(List<Field> fields) = _DidReceiveFieldUpdate; const factory GridPropertyEvent.didReceiveFieldUpdate(List<GridFieldPB> fields) = _DidReceiveFieldUpdate;
const factory GridPropertyEvent.moveField(int fromIndex, int toIndex) = _MoveField; const factory GridPropertyEvent.moveField(int fromIndex, int toIndex) = _MoveField;
} }
@ -70,10 +70,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<Field> fields, required List<GridFieldPB> fields,
}) = _GridPropertyState; }) = _GridPropertyState;
factory GridPropertyState.initial(String gridId, List<Field> fields) => GridPropertyState( factory GridPropertyState.initial(String gridId, List<GridFieldPB> fields) => GridPropertyState(
gridId: gridId, gridId: gridId,
fields: fields, fields: fields,
); );

View File

@ -212,10 +212,10 @@ class _GridRowsState extends State<_GridRows> {
builder: (context, state) { builder: (context, state) {
return SliverAnimatedList( return SliverAnimatedList(
key: _key, key: _key,
initialItemCount: context.read<GridBloc>().state.rows.length, initialItemCount: context.read<GridBloc>().state.rowInfos.length,
itemBuilder: (BuildContext context, int index, Animation<double> animation) { itemBuilder: (BuildContext context, int index, Animation<double> animation) {
final GridRow rowData = context.read<GridBloc>().state.rows[index]; final GridRowInfo rowInfo = context.read<GridBloc>().state.rowInfos[index];
return _renderRow(context, rowData, animation); return _renderRow(context, rowInfo, animation);
}, },
); );
}, },
@ -224,19 +224,19 @@ class _GridRowsState extends State<_GridRows> {
Widget _renderRow( Widget _renderRow(
BuildContext context, BuildContext context,
GridRow rowData, GridRowInfo rowInfo,
Animation<double> animation, Animation<double> animation,
) { ) {
final rowCache = context.read<GridBloc>().getRowCache(rowData.blockId, rowData.id); final rowCache = context.read<GridBloc>().getRowCache(rowInfo.blockId, rowInfo.id);
final fieldCache = context.read<GridBloc>().fieldCache; final fieldCache = context.read<GridBloc>().fieldCache;
if (rowCache != null) { if (rowCache != null) {
return SizeTransition( return SizeTransition(
sizeFactor: animation, sizeFactor: animation,
child: GridRowWidget( child: GridRowWidget(
rowData: rowData, rowData: rowInfo,
rowCache: rowCache, rowCache: rowCache,
fieldCache: fieldCache, fieldCache: fieldCache,
key: ValueKey(rowData.id), key: ValueKey(rowInfo.id),
), ),
); );
} else { } else {

View File

@ -2,7 +2,7 @@ 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<Field> fields) { static double headerWidth(List<GridFieldPB> 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);

View File

@ -7,27 +7,27 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:app_flowy/generated/locale_keys.g.dart'; import 'package:app_flowy/generated/locale_keys.g.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
extension SelectOptionColorExtension on SelectOptionColor { extension SelectOptionColorExtension on SelectOptionColorPB {
Color make(BuildContext context) { Color make(BuildContext context) {
final theme = context.watch<AppTheme>(); final theme = context.watch<AppTheme>();
switch (this) { switch (this) {
case SelectOptionColor.Purple: case SelectOptionColorPB.Purple:
return theme.tint1; return theme.tint1;
case SelectOptionColor.Pink: case SelectOptionColorPB.Pink:
return theme.tint2; return theme.tint2;
case SelectOptionColor.LightPink: case SelectOptionColorPB.LightPink:
return theme.tint3; return theme.tint3;
case SelectOptionColor.Orange: case SelectOptionColorPB.Orange:
return theme.tint4; return theme.tint4;
case SelectOptionColor.Yellow: case SelectOptionColorPB.Yellow:
return theme.tint5; return theme.tint5;
case SelectOptionColor.Lime: case SelectOptionColorPB.Lime:
return theme.tint6; return theme.tint6;
case SelectOptionColor.Green: case SelectOptionColorPB.Green:
return theme.tint7; return theme.tint7;
case SelectOptionColor.Aqua: case SelectOptionColorPB.Aqua:
return theme.tint8; return theme.tint8;
case SelectOptionColor.Blue: case SelectOptionColorPB.Blue:
return theme.tint9; return theme.tint9;
default: default:
throw ArgumentError; throw ArgumentError;
@ -36,23 +36,23 @@ extension SelectOptionColorExtension on SelectOptionColor {
String optionName() { String optionName() {
switch (this) { switch (this) {
case SelectOptionColor.Purple: case SelectOptionColorPB.Purple:
return LocaleKeys.grid_selectOption_purpleColor.tr(); return LocaleKeys.grid_selectOption_purpleColor.tr();
case SelectOptionColor.Pink: case SelectOptionColorPB.Pink:
return LocaleKeys.grid_selectOption_pinkColor.tr(); return LocaleKeys.grid_selectOption_pinkColor.tr();
case SelectOptionColor.LightPink: case SelectOptionColorPB.LightPink:
return LocaleKeys.grid_selectOption_lightPinkColor.tr(); return LocaleKeys.grid_selectOption_lightPinkColor.tr();
case SelectOptionColor.Orange: case SelectOptionColorPB.Orange:
return LocaleKeys.grid_selectOption_orangeColor.tr(); return LocaleKeys.grid_selectOption_orangeColor.tr();
case SelectOptionColor.Yellow: case SelectOptionColorPB.Yellow:
return LocaleKeys.grid_selectOption_yellowColor.tr(); return LocaleKeys.grid_selectOption_yellowColor.tr();
case SelectOptionColor.Lime: case SelectOptionColorPB.Lime:
return LocaleKeys.grid_selectOption_limeColor.tr(); return LocaleKeys.grid_selectOption_limeColor.tr();
case SelectOptionColor.Green: case SelectOptionColorPB.Green:
return LocaleKeys.grid_selectOption_greenColor.tr(); return LocaleKeys.grid_selectOption_greenColor.tr();
case SelectOptionColor.Aqua: case SelectOptionColorPB.Aqua:
return LocaleKeys.grid_selectOption_aquaColor.tr(); return LocaleKeys.grid_selectOption_aquaColor.tr();
case SelectOptionColor.Blue: case SelectOptionColorPB.Blue:
return LocaleKeys.grid_selectOption_blueColor.tr(); return LocaleKeys.grid_selectOption_blueColor.tr();
default: default:
throw ArgumentError; throw ArgumentError;
@ -75,7 +75,7 @@ class SelectOptionTag extends StatelessWidget {
factory SelectOptionTag.fromSelectOption({ factory SelectOptionTag.fromSelectOption({
required BuildContext context, required BuildContext context,
required SelectOption option, required SelectOptionPB option,
VoidCallback? onSelected, VoidCallback? onSelected,
bool isSelected = false, bool isSelected = false,
}) { }) {
@ -107,8 +107,8 @@ class SelectOptionTag extends StatelessWidget {
class SelectOptionTagCell extends StatelessWidget { class SelectOptionTagCell extends StatelessWidget {
final List<Widget> children; final List<Widget> children;
final void Function(SelectOption) onSelected; final void Function(SelectOptionPB) onSelected;
final SelectOption option; final SelectOptionPB option;
const SelectOptionTagCell({ const SelectOptionTagCell({
required this.option, required this.option,
required this.onSelected, required this.onSelected,

View File

@ -128,7 +128,7 @@ class _MultiSelectCellState extends State<MultiSelectCell> {
} }
class _SelectOptionCell extends StatelessWidget { class _SelectOptionCell extends StatelessWidget {
final List<SelectOption> selectOptions; final List<SelectOptionPB> selectOptions;
final void Function(bool) onFocus; final void Function(bool) onFocus;
final SelectOptionCellStyle? cellStyle; final SelectOptionCellStyle? cellStyle;
final GridCellControllerBuilder cellContorllerBuilder; final GridCellControllerBuilder cellContorllerBuilder;

View File

@ -146,7 +146,7 @@ class _TextField extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<SelectOptionCellEditorBloc, SelectOptionEditorState>( return BlocBuilder<SelectOptionCellEditorBloc, SelectOptionEditorState>(
builder: (context, state) { builder: (context, state) {
final optionMap = LinkedHashMap<String, SelectOption>.fromIterable(state.selectedOptions, final optionMap = LinkedHashMap<String, SelectOptionPB>.fromIterable(state.selectedOptions,
key: (option) => option.name, value: (option) => option); key: (option) => option.name, value: (option) => option);
return SizedBox( return SizedBox(
@ -216,7 +216,7 @@ class _CreateOptionCell extends StatelessWidget {
} }
class _SelectOptionCell extends StatelessWidget { class _SelectOptionCell extends StatelessWidget {
final SelectOption option; final SelectOptionPB option;
final bool isSelected; final bool isSelected;
const _SelectOptionCell(this.option, this.isSelected, {Key? key}) : super(key: key); const _SelectOptionCell(this.option, this.isSelected, {Key? key}) : super(key: key);

View File

@ -15,8 +15,8 @@ class SelectOptionTextField extends StatelessWidget {
final FocusNode _focusNode; final FocusNode _focusNode;
final TextEditingController _controller; final TextEditingController _controller;
final TextfieldTagsController tagController; final TextfieldTagsController tagController;
final List<SelectOption> options; final List<SelectOptionPB> options;
final LinkedHashMap<String, SelectOption> selectedOptionMap; final LinkedHashMap<String, SelectOptionPB> selectedOptionMap;
final double distanceToText; final double distanceToText;

View File

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

View File

@ -15,8 +15,8 @@ import 'package:app_flowy/workspace/presentation/plugins/grid/src/widgets/header
import 'field_type_extension.dart'; import 'field_type_extension.dart';
import 'type_option/builder.dart'; import 'type_option/builder.dart';
typedef UpdateFieldCallback = void Function(Field, Uint8List); typedef UpdateFieldCallback = void Function(GridFieldPB, Uint8List);
typedef SwitchToFieldCallback = Future<Either<FieldTypeOptionData, FlowyError>> Function( typedef SwitchToFieldCallback = Future<Either<FieldTypeOptionDataPB, FlowyError>> Function(
String fieldId, String fieldId,
FieldType fieldType, FieldType fieldType,
); );
@ -59,7 +59,7 @@ class _FieldTypeOptionEditorState extends State<FieldTypeOptionEditor> {
); );
} }
Widget _switchFieldTypeButton(BuildContext context, Field field) { Widget _switchFieldTypeButton(BuildContext context, GridFieldPB field) {
final theme = context.watch<AppTheme>(); final theme = context.watch<AppTheme>();
return SizedBox( return SizedBox(
height: GridSize.typeOptionItemHeight, height: GridSize.typeOptionItemHeight,

View File

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

View File

@ -17,7 +17,7 @@ import 'builder.dart';
import 'select_option_editor.dart'; import 'select_option_editor.dart';
class SelectOptionTypeOptionWidget extends StatelessWidget { class SelectOptionTypeOptionWidget extends StatelessWidget {
final List<SelectOption> options; final List<SelectOptionPB> options;
final VoidCallback beginEdit; final VoidCallback beginEdit;
final TypeOptionOverlayDelegate overlayDelegate; final TypeOptionOverlayDelegate overlayDelegate;
final SelectOptionTypeOptionAction typeOptionAction; final SelectOptionTypeOptionAction typeOptionAction;
@ -131,7 +131,7 @@ class _OptionList extends StatelessWidget {
); );
} }
_OptionCell _makeOptionCell(BuildContext context, SelectOption option) { _OptionCell _makeOptionCell(BuildContext context, SelectOptionPB option) {
return _OptionCell( return _OptionCell(
option: option, option: option,
onSelected: (option) { onSelected: (option) {
@ -154,8 +154,8 @@ class _OptionList extends StatelessWidget {
} }
class _OptionCell extends StatelessWidget { class _OptionCell extends StatelessWidget {
final SelectOption option; final SelectOptionPB option;
final Function(SelectOption) onSelected; final Function(SelectOptionPB) onSelected;
const _OptionCell({ const _OptionCell({
required this.option, required this.option,
required this.onSelected, required this.onSelected,

View File

@ -15,9 +15,9 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:app_flowy/generated/locale_keys.g.dart'; import 'package:app_flowy/generated/locale_keys.g.dart';
class SelectOptionTypeOptionEditor extends StatelessWidget { class SelectOptionTypeOptionEditor extends StatelessWidget {
final SelectOption option; final SelectOptionPB option;
final VoidCallback onDeleted; final VoidCallback onDeleted;
final Function(SelectOption) onUpdated; final Function(SelectOptionPB) onUpdated;
const SelectOptionTypeOptionEditor({ const SelectOptionTypeOptionEditor({
required this.option, required this.option,
required this.onDeleted, required this.onDeleted,
@ -110,12 +110,12 @@ class _OptionNameTextField extends StatelessWidget {
} }
class SelectOptionColorList extends StatelessWidget { class SelectOptionColorList extends StatelessWidget {
final SelectOptionColor selectedColor; final SelectOptionColorPB selectedColor;
const SelectOptionColorList({required this.selectedColor, Key? key}) : super(key: key); const SelectOptionColorList({required this.selectedColor, Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cells = SelectOptionColor.values.map((color) { final cells = SelectOptionColorPB.values.map((color) {
return _SelectOptionColorCell(color: color, isSelected: selectedColor == color); return _SelectOptionColorCell(color: color, isSelected: selectedColor == color);
}).toList(); }).toList();
@ -152,7 +152,7 @@ class SelectOptionColorList extends StatelessWidget {
} }
class _SelectOptionColorCell extends StatelessWidget { class _SelectOptionColorCell extends StatelessWidget {
final SelectOptionColor color; final SelectOptionColorPB color;
final bool isSelected; final bool isSelected;
const _SelectOptionColorCell({required this.color, required this.isSelected, Key? key}) : super(key: key); const _SelectOptionColorCell({required this.color, required this.isSelected, Key? key}) : super(key: key);

View File

@ -15,7 +15,7 @@ import 'row_action_sheet.dart';
import 'row_detail.dart'; import 'row_detail.dart';
class GridRowWidget extends StatefulWidget { class GridRowWidget extends StatefulWidget {
final GridRow rowData; final GridRowInfo rowData;
final GridRowCache rowCache; final GridRowCache rowCache;
final GridCellBuilder cellBuilder; final GridCellBuilder cellBuilder;
@ -40,7 +40,7 @@ class _GridRowWidgetState extends State<GridRowWidget> {
@override @override
void initState() { void initState() {
_rowBloc = RowBloc( _rowBloc = RowBloc(
rowData: widget.rowData, rowInfo: widget.rowData,
rowCache: widget.rowCache, rowCache: widget.rowCache,
); );
_rowBloc.add(const RowEvent.initial()); _rowBloc.add(const RowEvent.initial());
@ -53,7 +53,7 @@ class _GridRowWidgetState extends State<GridRowWidget> {
value: _rowBloc, value: _rowBloc,
child: _RowEnterRegion( child: _RowEnterRegion(
child: BlocBuilder<RowBloc, RowState>( child: BlocBuilder<RowBloc, RowState>(
buildWhen: (p, c) => p.rowData.height != c.rowData.height, buildWhen: (p, c) => p.rowInfo.height != c.rowInfo.height,
builder: (context, state) { builder: (context, state) {
return Row( return Row(
children: [ children: [
@ -80,7 +80,7 @@ class _GridRowWidgetState extends State<GridRowWidget> {
void _expandRow(BuildContext context) { void _expandRow(BuildContext context) {
final page = RowDetailPage( final page = RowDetailPage(
rowData: widget.rowData, rowInfo: widget.rowData,
rowCache: widget.rowCache, rowCache: widget.rowCache,
cellBuilder: widget.cellBuilder, cellBuilder: widget.cellBuilder,
); );
@ -148,7 +148,7 @@ class _DeleteRowButton extends StatelessWidget {
width: 20, width: 20,
height: 30, height: 30,
onPressed: () => GridRowActionSheet( onPressed: () => GridRowActionSheet(
rowData: context.read<RowBloc>().state.rowData, rowData: context.read<RowBloc>().state.rowInfo,
).show(context), ).show(context),
iconPadding: const EdgeInsets.all(3), iconPadding: const EdgeInsets.all(3),
icon: svgWidget("editor/details"), icon: svgWidget("editor/details"),

View File

@ -14,7 +14,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
class GridRowActionSheet extends StatelessWidget { class GridRowActionSheet extends StatelessWidget {
final GridRow rowData; final GridRowInfo 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

@ -21,12 +21,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
class RowDetailPage extends StatefulWidget with FlowyOverlayDelegate { class RowDetailPage extends StatefulWidget with FlowyOverlayDelegate {
final GridRow rowData; final GridRowInfo rowInfo;
final GridRowCache rowCache; final GridRowCache rowCache;
final GridCellBuilder cellBuilder; final GridCellBuilder cellBuilder;
const RowDetailPage({ const RowDetailPage({
required this.rowData, required this.rowInfo,
required this.rowCache, required this.rowCache,
required this.cellBuilder, required this.cellBuilder,
Key? key, Key? key,
@ -62,7 +62,7 @@ class _RowDetailPageState extends State<RowDetailPage> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocProvider( return BlocProvider(
create: (context) { create: (context) {
final bloc = RowDetailBloc(rowData: widget.rowData, rowCache: widget.rowCache); final bloc = RowDetailBloc(rowInfo: widget.rowInfo, rowCache: widget.rowCache);
bloc.add(const RowDetailEvent.initial()); bloc.add(const RowDetailEvent.initial());
return bloc; return bloc;
}, },

View File

@ -75,7 +75,7 @@ class GridPropertyList extends StatelessWidget with FlowyOverlayDelegate {
} }
class _GridPropertyCell extends StatelessWidget { class _GridPropertyCell extends StatelessWidget {
final Field field; final GridFieldPB field;
final String gridId; final String gridId;
const _GridPropertyCell({required this.gridId, required this.field, Key? key}) : super(key: key); const _GridPropertyCell({required this.gridId, required this.field, 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',
'Field Hockey', 'GridFieldPB Hockey',
'Ice Hockey', 'Ice Hockey',
'Lacrosse', 'Lacrosse',
'Ping Pong', 'Ping Pong',

View File

@ -5,38 +5,38 @@ use flowy_grid_data_model::revision::RowRevision;
use std::sync::Arc; use std::sync::Arc;
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridBlock { pub struct GridBlockPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub row_infos: Vec<RowInfo>, pub rows: Vec<GridRowPB>,
} }
impl GridBlock { impl GridBlockPB {
pub fn new(block_id: &str, row_orders: Vec<RowInfo>) -> Self { pub fn new(block_id: &str, rows: Vec<GridRowPB>) -> Self {
Self { Self {
id: block_id.to_owned(), id: block_id.to_owned(),
row_infos: row_orders, rows,
} }
} }
} }
#[derive(Debug, Default, Clone, ProtoBuf)] #[derive(Debug, Default, Clone, ProtoBuf)]
pub struct RowInfo { pub struct GridRowPB {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub row_id: String, pub id: String,
#[pb(index = 3)] #[pb(index = 3)]
pub height: i32, pub height: i32,
} }
impl RowInfo { impl GridRowPB {
pub fn row_id(&self) -> &str { pub fn row_id(&self) -> &str {
&self.row_id &self.id
} }
pub fn block_id(&self) -> &str { pub fn block_id(&self) -> &str {
@ -44,66 +44,57 @@ impl RowInfo {
} }
} }
impl std::convert::From<&RowRevision> for RowInfo { impl std::convert::From<&RowRevision> for GridRowPB {
fn from(rev: &RowRevision) -> Self { fn from(rev: &RowRevision) -> Self {
Self { Self {
block_id: rev.block_id.clone(), block_id: rev.block_id.clone(),
row_id: rev.id.clone(), id: rev.id.clone(),
height: rev.height, height: rev.height,
} }
} }
} }
impl std::convert::From<&Arc<RowRevision>> for RowInfo { impl std::convert::From<&Arc<RowRevision>> for GridRowPB {
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(),
row_id: rev.id.clone(), id: rev.id.clone(),
height: rev.height, height: rev.height,
} }
} }
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct Row { pub struct OptionalRowPB {
#[pb(index = 1)]
pub id: String,
#[pb(index = 2)]
pub height: i32,
}
#[derive(Debug, Default, ProtoBuf)]
pub struct OptionalRow {
#[pb(index = 1, one_of)] #[pb(index = 1, one_of)]
pub row: Option<Row>, pub row: Option<GridRowPB>,
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedRow { pub struct RepeatedRowPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<Row>, pub items: Vec<GridRowPB>,
} }
impl std::convert::From<Vec<Row>> for RepeatedRow { impl std::convert::From<Vec<GridRowPB>> for RepeatedRowPB {
fn from(items: Vec<Row>) -> Self { fn from(items: Vec<GridRowPB>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedGridBlock { pub struct RepeatedGridBlockPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridBlock>, pub items: Vec<GridBlockPB>,
} }
impl std::convert::From<Vec<GridBlock>> for RepeatedGridBlock { impl std::convert::From<Vec<GridBlockPB>> for RepeatedGridBlockPB {
fn from(items: Vec<GridBlock>) -> Self { fn from(items: Vec<GridBlockPB>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct InsertedRow { pub struct InsertedRowPB {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
@ -118,7 +109,7 @@ pub struct InsertedRow {
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct UpdatedRow { pub struct UpdatedRowPB {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
@ -126,11 +117,11 @@ pub struct UpdatedRow {
pub row_id: String, pub row_id: String,
#[pb(index = 3)] #[pb(index = 3)]
pub row: Row, pub row: GridRowPB,
} }
impl UpdatedRow { impl UpdatedRowPB {
pub fn new(row_rev: &RowRevision, row: Row) -> Self { pub fn new(row_rev: &RowRevision, row: GridRowPB) -> 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(),
@ -139,10 +130,10 @@ impl UpdatedRow {
} }
} }
impl std::convert::From<RowInfo> for InsertedRow { impl std::convert::From<GridRowPB> for InsertedRowPB {
fn from(row_info: RowInfo) -> Self { fn from(row_info: GridRowPB) -> Self {
Self { Self {
row_id: row_info.row_id, row_id: row_info.id,
block_id: row_info.block_id, block_id: row_info.block_id,
height: row_info.height, height: row_info.height,
index: None, index: None,
@ -150,26 +141,26 @@ impl std::convert::From<RowInfo> for InsertedRow {
} }
} }
impl std::convert::From<&RowRevision> for InsertedRow { impl std::convert::From<&RowRevision> for InsertedRowPB {
fn from(row: &RowRevision) -> Self { fn from(row: &RowRevision) -> Self {
let row_order = RowInfo::from(row); let row_order = GridRowPB::from(row);
Self::from(row_order) Self::from(row_order)
} }
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct GridBlockChangeset { pub struct GridBlockChangesetPB {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub inserted_rows: Vec<InsertedRow>, pub inserted_rows: Vec<InsertedRowPB>,
#[pb(index = 3)] #[pb(index = 3)]
pub deleted_rows: Vec<String>, pub deleted_rows: Vec<String>,
#[pb(index = 4)] #[pb(index = 4)]
pub updated_rows: Vec<UpdatedRow>, pub updated_rows: Vec<UpdatedRowPB>,
#[pb(index = 5)] #[pb(index = 5)]
pub visible_rows: Vec<String>, pub visible_rows: Vec<String>,
@ -177,8 +168,8 @@ pub struct GridBlockChangeset {
#[pb(index = 6)] #[pb(index = 6)]
pub hide_rows: Vec<String>, pub hide_rows: Vec<String>,
} }
impl GridBlockChangeset { impl GridBlockChangesetPB {
pub fn insert(block_id: &str, inserted_rows: Vec<InsertedRow>) -> Self { pub fn insert(block_id: &str, inserted_rows: Vec<InsertedRowPB>) -> Self {
Self { Self {
block_id: block_id.to_owned(), block_id: block_id.to_owned(),
inserted_rows, inserted_rows,
@ -194,7 +185,7 @@ impl GridBlockChangeset {
} }
} }
pub fn update(block_id: &str, updated_rows: Vec<UpdatedRow>) -> Self { pub fn update(block_id: &str, updated_rows: Vec<UpdatedRowPB>) -> Self {
Self { Self {
block_id: block_id.to_owned(), block_id: block_id.to_owned(),
updated_rows, updated_rows,
@ -204,7 +195,7 @@ impl GridBlockChangeset {
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct QueryGridBlocksPayload { pub struct QueryGridBlocksPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -217,7 +208,7 @@ pub struct QueryGridBlocksParams {
pub block_ids: Vec<String>, pub block_ids: Vec<String>,
} }
impl TryInto<QueryGridBlocksParams> for QueryGridBlocksPayload { impl TryInto<QueryGridBlocksParams> for QueryGridBlocksPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<QueryGridBlocksParams, Self::Error> { fn try_into(self) -> Result<QueryGridBlocksParams, Self::Error> {

View File

@ -1,4 +1,4 @@
use crate::entities::{FieldIdentifier, FieldIdentifierPayload}; use crate::entities::{FieldIdentifierParams, GridFieldIdentifierPayloadPB};
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;
@ -6,28 +6,28 @@ use flowy_grid_data_model::revision::{CellRevision, RowMetaChangeset};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct CreateSelectOptionPayload { pub struct CreateSelectOptionPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_identifier: FieldIdentifierPayload, pub field_identifier: GridFieldIdentifierPayloadPB,
#[pb(index = 2)] #[pb(index = 2)]
pub option_name: String, pub option_name: String,
} }
pub struct CreateSelectOptionParams { pub struct CreateSelectOptionParams {
pub field_identifier: FieldIdentifier, pub field_identifier: FieldIdentifierParams,
pub option_name: String, pub option_name: String,
} }
impl std::ops::Deref for CreateSelectOptionParams { impl std::ops::Deref for CreateSelectOptionParams {
type Target = FieldIdentifier; type Target = FieldIdentifierParams;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.field_identifier &self.field_identifier
} }
} }
impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayload { impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateSelectOptionParams, Self::Error> { fn try_into(self) -> Result<CreateSelectOptionParams, Self::Error> {
@ -41,7 +41,7 @@ impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayload {
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct CellIdentifierPayload { pub struct GridCellIdentifierPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -52,20 +52,20 @@ pub struct CellIdentifierPayload {
pub row_id: String, pub row_id: String,
} }
pub struct CellIdentifier { pub struct CellIdentifierParams {
pub grid_id: String, pub grid_id: String,
pub field_id: String, pub field_id: String,
pub row_id: String, pub row_id: String,
} }
impl TryInto<CellIdentifier> for CellIdentifierPayload { impl TryInto<CellIdentifierParams> for GridCellIdentifierPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CellIdentifier, Self::Error> { fn try_into(self) -> Result<CellIdentifierParams, 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)?;
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(CellIdentifier { Ok(CellIdentifierParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,
row_id: row_id.0, row_id: row_id.0,
@ -73,7 +73,7 @@ impl TryInto<CellIdentifier> for CellIdentifierPayload {
} }
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct Cell { pub struct GridCellPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
@ -81,7 +81,7 @@ pub struct Cell {
pub data: Vec<u8>, pub data: Vec<u8>,
} }
impl Cell { impl GridCellPB {
pub fn new(field_id: &str, data: Vec<u8>) -> Self { pub fn new(field_id: &str, data: Vec<u8>) -> Self {
Self { Self {
field_id: field_id.to_owned(), field_id: field_id.to_owned(),
@ -98,32 +98,32 @@ impl Cell {
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedCell { pub struct RepeatedCellPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<Cell>, pub items: Vec<GridCellPB>,
} }
impl std::ops::Deref for RepeatedCell { impl std::ops::Deref for RepeatedCellPB {
type Target = Vec<Cell>; type Target = Vec<GridCellPB>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.items &self.items
} }
} }
impl std::ops::DerefMut for RepeatedCell { impl std::ops::DerefMut for RepeatedCellPB {
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<Cell>> for RepeatedCell { impl std::convert::From<Vec<GridCellPB>> for RepeatedCellPB {
fn from(items: Vec<Cell>) -> Self { fn from(items: Vec<GridCellPB>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct CellChangeset { pub struct CellChangesetPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -137,8 +137,8 @@ pub struct CellChangeset {
pub content: Option<String>, pub content: Option<String>,
} }
impl std::convert::From<CellChangeset> for RowMetaChangeset { impl std::convert::From<CellChangesetPB> for RowMetaChangeset {
fn from(changeset: CellChangeset) -> Self { fn from(changeset: CellChangesetPB) -> Self {
let mut cell_by_field_id = HashMap::with_capacity(1); let mut cell_by_field_id = HashMap::with_capacity(1);
let field_id = changeset.field_id; let field_id = changeset.field_id;
let cell_rev = CellRevision { let cell_rev = CellRevision {

View File

@ -9,7 +9,7 @@ use std::sync::Arc;
use strum_macros::{Display, EnumCount as EnumCountMacro, EnumIter, EnumString}; use strum_macros::{Display, EnumCount as EnumCountMacro, EnumIter, EnumString};
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct Field { pub struct GridFieldPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
@ -35,7 +35,7 @@ pub struct Field {
pub is_primary: bool, pub is_primary: bool,
} }
impl std::convert::From<FieldRevision> for Field { impl std::convert::From<FieldRevision> for GridFieldPB {
fn from(field_rev: FieldRevision) -> Self { fn from(field_rev: FieldRevision) -> Self {
Self { Self {
id: field_rev.id, id: field_rev.id,
@ -50,31 +50,31 @@ impl std::convert::From<FieldRevision> for Field {
} }
} }
impl std::convert::From<Arc<FieldRevision>> for Field { impl std::convert::From<Arc<FieldRevision>> for GridFieldPB {
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();
Field::from(field_rev) GridFieldPB::from(field_rev)
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct FieldOrder { pub struct GridFieldIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
} }
impl std::convert::From<&str> for FieldOrder { impl std::convert::From<&str> for GridFieldIdPB {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
FieldOrder { field_id: s.to_owned() } GridFieldIdPB { field_id: s.to_owned() }
} }
} }
impl std::convert::From<String> for FieldOrder { impl std::convert::From<String> for GridFieldIdPB {
fn from(s: String) -> Self { fn from(s: String) -> Self {
FieldOrder { field_id: s } GridFieldIdPB { field_id: s }
} }
} }
impl std::convert::From<&Arc<FieldRevision>> for FieldOrder { impl std::convert::From<&Arc<FieldRevision>> for GridFieldIdPB {
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(),
@ -82,22 +82,22 @@ impl std::convert::From<&Arc<FieldRevision>> for FieldOrder {
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridFieldChangeset { pub struct GridFieldChangesetPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub inserted_fields: Vec<IndexField>, pub inserted_fields: Vec<IndexFieldPB>,
#[pb(index = 3)] #[pb(index = 3)]
pub deleted_fields: Vec<FieldOrder>, pub deleted_fields: Vec<GridFieldIdPB>,
#[pb(index = 4)] #[pb(index = 4)]
pub updated_fields: Vec<Field>, pub updated_fields: Vec<GridFieldPB>,
} }
impl GridFieldChangeset { impl GridFieldChangesetPB {
pub fn insert(grid_id: &str, inserted_fields: Vec<IndexField>) -> 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(),
inserted_fields, inserted_fields,
@ -106,7 +106,7 @@ impl GridFieldChangeset {
} }
} }
pub fn delete(grid_id: &str, deleted_fields: Vec<FieldOrder>) -> Self { pub fn delete(grid_id: &str, deleted_fields: Vec<GridFieldIdPB>) -> Self {
Self { Self {
grid_id: grid_id.to_string(), grid_id: grid_id.to_string(),
inserted_fields: vec![], inserted_fields: vec![],
@ -115,7 +115,7 @@ impl GridFieldChangeset {
} }
} }
pub fn update(grid_id: &str, updated_fields: Vec<Field>) -> Self { pub fn update(grid_id: &str, updated_fields: Vec<GridFieldPB>) -> Self {
Self { Self {
grid_id: grid_id.to_string(), grid_id: grid_id.to_string(),
inserted_fields: vec![], inserted_fields: vec![],
@ -126,25 +126,25 @@ impl GridFieldChangeset {
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct IndexField { pub struct IndexFieldPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field: Field, pub field: GridFieldPB,
#[pb(index = 2)] #[pb(index = 2)]
pub index: i32, pub index: i32,
} }
impl IndexField { 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: Field::from(field_rev.as_ref().clone()), field: GridFieldPB::from(field_rev.as_ref().clone()),
index: index as i32, index: index as i32,
} }
} }
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct GetEditFieldContextPayload { pub struct GetEditFieldContextPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -156,7 +156,7 @@ pub struct GetEditFieldContextPayload {
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct EditFieldPayload { pub struct EditFieldPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -176,7 +176,7 @@ pub struct EditFieldParams {
pub field_type: FieldType, pub field_type: FieldType,
} }
impl TryInto<EditFieldParams> for EditFieldPayload { impl TryInto<EditFieldParams> for EditFieldPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<EditFieldParams, Self::Error> { fn try_into(self) -> Result<EditFieldParams, Self::Error> {
@ -195,7 +195,7 @@ pub struct CreateFieldParams {
pub field_type: FieldType, pub field_type: FieldType,
} }
impl TryInto<CreateFieldParams> for EditFieldPayload { impl TryInto<CreateFieldParams> for EditFieldPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateFieldParams, Self::Error> { fn try_into(self) -> Result<CreateFieldParams, Self::Error> {
@ -209,87 +209,75 @@ impl TryInto<CreateFieldParams> for EditFieldPayload {
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct FieldTypeOptionContext { pub struct FieldTypeOptionDataPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub grid_field: Field, pub field: GridFieldPB,
#[pb(index = 3)] #[pb(index = 3)]
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
} }
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct FieldTypeOptionData { pub struct RepeatedGridFieldPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub items: Vec<GridFieldPB>,
#[pb(index = 2)]
pub field: Field,
#[pb(index = 3)]
pub type_option_data: Vec<u8>,
} }
impl std::ops::Deref for RepeatedGridFieldPB {
#[derive(Debug, Default, ProtoBuf)] type Target = Vec<GridFieldPB>;
pub struct RepeatedField {
#[pb(index = 1)]
pub items: Vec<Field>,
}
impl std::ops::Deref for RepeatedField {
type Target = Vec<Field>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.items &self.items
} }
} }
impl std::ops::DerefMut for RepeatedField { impl std::ops::DerefMut for RepeatedGridFieldPB {
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<Field>> for RepeatedField { impl std::convert::From<Vec<GridFieldPB>> for RepeatedGridFieldPB {
fn from(items: Vec<Field>) -> Self { fn from(items: Vec<GridFieldPB>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct RepeatedFieldOrder { pub struct RepeatedGridFieldIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<FieldOrder>, pub items: Vec<GridFieldIdPB>,
} }
impl std::ops::Deref for RepeatedFieldOrder { impl std::ops::Deref for RepeatedGridFieldIdPB {
type Target = Vec<FieldOrder>; type Target = Vec<GridFieldIdPB>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.items &self.items
} }
} }
impl std::convert::From<Vec<FieldOrder>> for RepeatedFieldOrder { impl std::convert::From<Vec<GridFieldIdPB>> for RepeatedGridFieldIdPB {
fn from(field_orders: Vec<FieldOrder>) -> Self { fn from(items: Vec<GridFieldIdPB>) -> Self {
RepeatedFieldOrder { items: field_orders } RepeatedGridFieldIdPB { items }
} }
} }
impl std::convert::From<String> for RepeatedFieldOrder { impl std::convert::From<String> for RepeatedGridFieldIdPB {
fn from(s: String) -> Self { fn from(s: String) -> Self {
RepeatedFieldOrder { RepeatedGridFieldIdPB {
items: vec![FieldOrder::from(s)], items: vec![GridFieldIdPB::from(s)],
} }
} }
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct InsertFieldPayload { pub struct InsertFieldPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field: Field, pub field: GridFieldPB,
#[pb(index = 3)] #[pb(index = 3)]
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
@ -301,12 +289,12 @@ pub struct InsertFieldPayload {
#[derive(Clone)] #[derive(Clone)]
pub struct InsertFieldParams { pub struct InsertFieldParams {
pub grid_id: String, pub grid_id: String,
pub field: Field, pub field: GridFieldPB,
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
pub start_field_id: Option<String>, pub start_field_id: Option<String>,
} }
impl TryInto<InsertFieldParams> for InsertFieldPayload { impl TryInto<InsertFieldParams> for InsertFieldPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<InsertFieldParams, Self::Error> { fn try_into(self) -> Result<InsertFieldParams, Self::Error> {
@ -328,7 +316,7 @@ impl TryInto<InsertFieldParams> for InsertFieldPayload {
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct UpdateFieldTypeOptionPayload { pub struct UpdateFieldTypeOptionPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -346,7 +334,7 @@ pub struct UpdateFieldTypeOptionParams {
pub type_option_data: Vec<u8>, pub type_option_data: Vec<u8>,
} }
impl TryInto<UpdateFieldTypeOptionParams> for UpdateFieldTypeOptionPayload { impl TryInto<UpdateFieldTypeOptionParams> for UpdateFieldTypeOptionPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<UpdateFieldTypeOptionParams, Self::Error> { fn try_into(self) -> Result<UpdateFieldTypeOptionParams, Self::Error> {
@ -362,33 +350,33 @@ impl TryInto<UpdateFieldTypeOptionParams> for UpdateFieldTypeOptionPayload {
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct QueryFieldPayload { pub struct QueryFieldPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field_orders: RepeatedFieldOrder, pub field_ids: RepeatedGridFieldIdPB,
} }
pub struct QueryFieldParams { pub struct QueryFieldParams {
pub grid_id: String, pub grid_id: String,
pub field_orders: RepeatedFieldOrder, pub field_ids: RepeatedGridFieldIdPB,
} }
impl TryInto<QueryFieldParams> for QueryFieldPayload { impl TryInto<QueryFieldParams> for QueryFieldPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<QueryFieldParams, Self::Error> { fn try_into(self) -> Result<QueryFieldParams, 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)?;
Ok(QueryFieldParams { Ok(QueryFieldParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_orders: self.field_orders, field_ids: self.field_ids,
}) })
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct FieldChangesetPayload { pub struct FieldChangesetPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
@ -417,7 +405,7 @@ pub struct FieldChangesetPayload {
pub type_option_data: Option<Vec<u8>>, pub type_option_data: Option<Vec<u8>>,
} }
impl TryInto<FieldChangesetParams> for FieldChangesetPayload { impl TryInto<FieldChangesetParams> for FieldChangesetPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<FieldChangesetParams, Self::Error> { fn try_into(self) -> Result<FieldChangesetParams, Self::Error> {
@ -569,7 +557,7 @@ impl std::convert::From<FieldTypeRevision> for FieldType {
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct FieldIdentifierPayload { pub struct GridFieldIdentifierPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
@ -577,18 +565,18 @@ pub struct FieldIdentifierPayload {
pub grid_id: String, pub grid_id: String,
} }
pub struct FieldIdentifier { pub struct FieldIdentifierParams {
pub field_id: String, pub field_id: String,
pub grid_id: String, pub grid_id: String,
} }
impl TryInto<FieldIdentifier> for FieldIdentifierPayload { impl TryInto<FieldIdentifierParams> for GridFieldIdentifierPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<FieldIdentifier, Self::Error> { fn try_into(self) -> Result<FieldIdentifierParams, 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(FieldIdentifier { Ok(FieldIdentifierParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,
}) })

View File

@ -17,7 +17,7 @@ pub struct GridFilter {
} }
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct RepeatedGridFilter { pub struct RepeatedGridFilterPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridFilter>, pub items: Vec<GridFilter>,
} }
@ -28,22 +28,22 @@ impl std::convert::From<&GridFilterRevision> for GridFilter {
} }
} }
impl std::convert::From<Vec<Arc<GridFilterRevision>>> for RepeatedGridFilter { impl std::convert::From<Vec<Arc<GridFilterRevision>>> for RepeatedGridFilterPB {
fn from(revs: Vec<Arc<GridFilterRevision>>) -> Self { fn from(revs: Vec<Arc<GridFilterRevision>>) -> Self {
RepeatedGridFilter { RepeatedGridFilterPB {
items: revs.into_iter().map(|rev| rev.as_ref().into()).collect(), items: revs.into_iter().map(|rev| rev.as_ref().into()).collect(),
} }
} }
} }
impl std::convert::From<Vec<GridFilter>> for RepeatedGridFilter { impl std::convert::From<Vec<GridFilter>> for RepeatedGridFilterPB {
fn from(items: Vec<GridFilter>) -> Self { fn from(items: Vec<GridFilter>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(ProtoBuf, Debug, Default, Clone)] #[derive(ProtoBuf, Debug, Default, Clone)]
pub struct DeleteFilterPayload { pub struct DeleteFilterPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
@ -54,7 +54,7 @@ pub struct DeleteFilterPayload {
pub field_type: FieldType, pub field_type: FieldType,
} }
impl TryInto<DeleteFilterParams> for DeleteFilterPayload { impl TryInto<DeleteFilterParams> for DeleteFilterPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<DeleteFilterParams, Self::Error> { fn try_into(self) -> Result<DeleteFilterParams, Self::Error> {
@ -73,7 +73,7 @@ impl TryInto<DeleteFilterParams> for DeleteFilterPayload {
} }
#[derive(ProtoBuf, Debug, Default, Clone)] #[derive(ProtoBuf, Debug, Default, Clone)]
pub struct CreateGridFilterPayload { pub struct CreateGridFilterPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
@ -87,7 +87,7 @@ pub struct CreateGridFilterPayload {
pub content: Option<String>, pub content: Option<String>,
} }
impl CreateGridFilterPayload { impl CreateGridFilterPayloadPB {
#[allow(dead_code)] #[allow(dead_code)]
pub fn new<T: Into<i32>>(field_rev: &FieldRevision, condition: T, content: Option<String>) -> Self { pub fn new<T: Into<i32>>(field_rev: &FieldRevision, condition: T, content: Option<String>) -> Self {
Self { Self {
@ -99,7 +99,7 @@ impl CreateGridFilterPayload {
} }
} }
impl TryInto<CreateGridFilterParams> for CreateGridFilterPayload { impl TryInto<CreateGridFilterParams> for CreateGridFilterPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateGridFilterParams, Self::Error> { fn try_into(self) -> Result<CreateGridFilterParams, Self::Error> {

View File

@ -1,69 +1,69 @@
use crate::entities::{FieldOrder, GridBlock}; use crate::entities::{GridBlockPB, GridFieldIdPB};
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;
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct Grid { pub struct GridPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field_orders: Vec<FieldOrder>, pub fields: Vec<GridFieldIdPB>,
#[pb(index = 3)] #[pb(index = 3)]
pub blocks: Vec<GridBlock>, pub blocks: Vec<GridBlockPB>,
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct CreateGridPayload { pub struct CreateGridPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub name: String, pub name: String,
} }
#[derive(Clone, ProtoBuf, Default, Debug)] #[derive(Clone, ProtoBuf, Default, Debug)]
pub struct GridId { pub struct GridIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub value: String, pub value: String,
} }
impl AsRef<str> for GridId { impl AsRef<str> for GridIdPB {
fn as_ref(&self) -> &str { fn as_ref(&self) -> &str {
&self.value &self.value
} }
} }
#[derive(Clone, ProtoBuf, Default, Debug)] #[derive(Clone, ProtoBuf, Default, Debug)]
pub struct GridBlockId { pub struct GridBlockIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub value: String, pub value: String,
} }
impl AsRef<str> for GridBlockId { impl AsRef<str> for GridBlockIdPB {
fn as_ref(&self) -> &str { fn as_ref(&self) -> &str {
&self.value &self.value
} }
} }
impl std::convert::From<&str> for GridBlockId { impl std::convert::From<&str> for GridBlockIdPB {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
GridBlockId { value: s.to_owned() } GridBlockIdPB { value: s.to_owned() }
} }
} }
#[derive(Debug, Clone, ProtoBuf_Enum)] #[derive(Debug, Clone, ProtoBuf_Enum)]
pub enum MoveItemType { pub enum MoveItemTypePB {
MoveField = 0, MoveField = 0,
MoveRow = 1, MoveRow = 1,
} }
impl std::default::Default for MoveItemType { impl std::default::Default for MoveItemTypePB {
fn default() -> Self { fn default() -> Self {
MoveItemType::MoveField MoveItemTypePB::MoveField
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct MoveItemPayload { pub struct MoveItemPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -77,7 +77,7 @@ pub struct MoveItemPayload {
pub to_index: i32, pub to_index: i32,
#[pb(index = 5)] #[pb(index = 5)]
pub ty: MoveItemType, pub ty: MoveItemTypePB,
} }
#[derive(Clone)] #[derive(Clone)]
@ -86,10 +86,10 @@ pub struct MoveItemParams {
pub item_id: String, pub item_id: String,
pub from_index: i32, pub from_index: i32,
pub to_index: i32, pub to_index: i32,
pub ty: MoveItemType, pub ty: MoveItemTypePB,
} }
impl TryInto<MoveItemParams> for MoveItemPayload { impl TryInto<MoveItemParams> for MoveItemPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<MoveItemParams, Self::Error> { fn try_into(self) -> Result<MoveItemParams, Self::Error> {

View File

@ -7,7 +7,7 @@ use std::convert::TryInto;
use std::sync::Arc; use std::sync::Arc;
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct GridGroup { pub struct GridGroupPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
@ -18,9 +18,9 @@ pub struct GridGroup {
pub sub_group_field_id: Option<String>, pub sub_group_field_id: Option<String>,
} }
impl std::convert::From<&GridGroupRevision> for GridGroup { impl std::convert::From<&GridGroupRevision> for GridGroupPB {
fn from(rev: &GridGroupRevision) -> Self { fn from(rev: &GridGroupRevision) -> Self {
GridGroup { GridGroupPB {
id: rev.id.clone(), id: rev.id.clone(),
group_field_id: rev.field_id.clone(), group_field_id: rev.field_id.clone(),
sub_group_field_id: rev.sub_field_id.clone(), sub_group_field_id: rev.sub_field_id.clone(),
@ -29,27 +29,27 @@ impl std::convert::From<&GridGroupRevision> for GridGroup {
} }
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct RepeatedGridGroup { pub struct RepeatedGridGroupPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridGroup>, pub items: Vec<GridGroupPB>,
} }
impl std::convert::From<Vec<GridGroup>> for RepeatedGridGroup { impl std::convert::From<Vec<GridGroupPB>> for RepeatedGridGroupPB {
fn from(items: Vec<GridGroup>) -> Self { fn from(items: Vec<GridGroupPB>) -> Self {
Self { items } Self { items }
} }
} }
impl std::convert::From<Vec<Arc<GridGroupRevision>>> for RepeatedGridGroup { impl std::convert::From<Vec<Arc<GridGroupRevision>>> for RepeatedGridGroupPB {
fn from(revs: Vec<Arc<GridGroupRevision>>) -> Self { fn from(revs: Vec<Arc<GridGroupRevision>>) -> Self {
RepeatedGridGroup { RepeatedGridGroupPB {
items: revs.iter().map(|rev| rev.as_ref().into()).collect(), items: revs.iter().map(|rev| rev.as_ref().into()).collect(),
} }
} }
} }
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct CreateGridGroupPayload { pub struct CreateGridGroupPayloadPB {
#[pb(index = 1, one_of)] #[pb(index = 1, one_of)]
pub field_id: Option<String>, pub field_id: Option<String>,
@ -57,7 +57,7 @@ pub struct CreateGridGroupPayload {
pub sub_field_id: Option<String>, pub sub_field_id: Option<String>,
} }
impl TryInto<CreateGridGroupParams> for CreateGridGroupPayload { impl TryInto<CreateGridGroupParams> for CreateGridGroupPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateGridGroupParams, Self::Error> { fn try_into(self) -> Result<CreateGridGroupParams, Self::Error> {

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(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct GridRowIdPayload { pub struct GridRowIdPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -15,7 +15,7 @@ pub struct GridRowIdPayload {
} }
#[derive(Debug, Default, Clone, ProtoBuf)] #[derive(Debug, Default, Clone, ProtoBuf)]
pub struct GridRowId { pub struct GridRowIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -26,15 +26,15 @@ pub struct GridRowId {
pub row_id: String, pub row_id: String,
} }
impl TryInto<GridRowId> for GridRowIdPayload { impl TryInto<GridRowIdPB> for GridRowIdPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<GridRowId, Self::Error> { fn try_into(self) -> Result<GridRowIdPB, 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(GridRowId { Ok(GridRowIdPB {
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,
@ -43,7 +43,7 @@ impl TryInto<GridRowId> for GridRowIdPayload {
} }
#[derive(Debug, Default, Clone, ProtoBuf)] #[derive(Debug, Default, Clone, ProtoBuf)]
pub struct BlockRowId { pub struct BlockRowIdPB {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
@ -52,7 +52,7 @@ pub struct BlockRowId {
} }
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct CreateRowPayload { pub struct CreateRowPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -66,7 +66,7 @@ pub struct CreateRowParams {
pub start_row_id: Option<String>, pub start_row_id: Option<String>,
} }
impl TryInto<CreateRowParams> for CreateRowPayload { impl TryInto<CreateRowParams> for CreateRowPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateRowParams, Self::Error> { fn try_into(self) -> Result<CreateRowParams, Self::Error> {

View File

@ -1,6 +1,6 @@
use crate::entities::{ use crate::entities::{
CreateGridFilterPayload, CreateGridGroupPayload, CreateGridSortPayload, DeleteFilterPayload, RepeatedGridFilter, CreateGridFilterPayloadPB, CreateGridGroupPayloadPB, CreateGridSortPayloadPB, DeleteFilterPayloadPB,
RepeatedGridGroup, RepeatedGridSort, RepeatedGridFilterPB, RepeatedGridGroupPB, RepeatedGridSortPB,
}; };
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
@ -13,34 +13,34 @@ use strum::IntoEnumIterator;
use strum_macros::EnumIter; use strum_macros::EnumIter;
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct GridSetting { pub struct GridSettingPB {
#[pb(index = 1)] #[pb(index = 1)]
pub layouts: Vec<GridLayout>, pub layouts: Vec<GridLayoutPB>,
#[pb(index = 2)] #[pb(index = 2)]
pub current_layout_type: GridLayoutType, pub current_layout_type: GridLayoutType,
#[pb(index = 3)] #[pb(index = 3)]
pub filters_by_field_id: HashMap<String, RepeatedGridFilter>, pub filters_by_field_id: HashMap<String, RepeatedGridFilterPB>,
#[pb(index = 4)] #[pb(index = 4)]
pub groups_by_field_id: HashMap<String, RepeatedGridGroup>, pub groups_by_field_id: HashMap<String, RepeatedGridGroupPB>,
#[pb(index = 5)] #[pb(index = 5)]
pub sorts_by_field_id: HashMap<String, RepeatedGridSort>, pub sorts_by_field_id: HashMap<String, RepeatedGridSortPB>,
} }
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct GridLayout { pub struct GridLayoutPB {
#[pb(index = 1)] #[pb(index = 1)]
ty: GridLayoutType, ty: GridLayoutType,
} }
impl GridLayout { impl GridLayoutPB {
pub fn all() -> Vec<GridLayout> { pub fn all() -> Vec<GridLayoutPB> {
let mut layouts = vec![]; let mut layouts = vec![];
for layout_ty in GridLayoutType::iter() { for layout_ty in GridLayoutType::iter() {
layouts.push(GridLayout { ty: layout_ty }) layouts.push(GridLayoutPB { ty: layout_ty })
} }
layouts layouts
@ -79,7 +79,7 @@ impl std::convert::From<GridLayoutType> for GridLayoutRevision {
} }
#[derive(Default, ProtoBuf)] #[derive(Default, ProtoBuf)]
pub struct GridSettingChangesetPayload { pub struct GridSettingChangesetPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub grid_id: String, pub grid_id: String,
@ -87,25 +87,25 @@ pub struct GridSettingChangesetPayload {
pub layout_type: GridLayoutType, pub layout_type: GridLayoutType,
#[pb(index = 3, one_of)] #[pb(index = 3, one_of)]
pub insert_filter: Option<CreateGridFilterPayload>, pub insert_filter: Option<CreateGridFilterPayloadPB>,
#[pb(index = 4, one_of)] #[pb(index = 4, one_of)]
pub delete_filter: Option<DeleteFilterPayload>, pub delete_filter: Option<DeleteFilterPayloadPB>,
#[pb(index = 5, one_of)] #[pb(index = 5, one_of)]
pub insert_group: Option<CreateGridGroupPayload>, pub insert_group: Option<CreateGridGroupPayloadPB>,
#[pb(index = 6, one_of)] #[pb(index = 6, one_of)]
pub delete_group: Option<String>, pub delete_group: Option<String>,
#[pb(index = 7, one_of)] #[pb(index = 7, one_of)]
pub insert_sort: Option<CreateGridSortPayload>, pub insert_sort: Option<CreateGridSortPayloadPB>,
#[pb(index = 8, one_of)] #[pb(index = 8, one_of)]
pub delete_sort: Option<String>, pub delete_sort: Option<String>,
} }
impl TryInto<GridSettingChangesetParams> for GridSettingChangesetPayload { impl TryInto<GridSettingChangesetParams> for GridSettingChangesetPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<GridSettingChangesetParams, Self::Error> { fn try_into(self) -> Result<GridSettingChangesetParams, Self::Error> {

View File

@ -26,32 +26,32 @@ impl std::convert::From<&GridSortRevision> for GridSort {
} }
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)] #[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct RepeatedGridSort { pub struct RepeatedGridSortPB {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<GridSort>, pub items: Vec<GridSort>,
} }
impl std::convert::From<Vec<Arc<GridSortRevision>>> for RepeatedGridSort { impl std::convert::From<Vec<Arc<GridSortRevision>>> for RepeatedGridSortPB {
fn from(revs: Vec<Arc<GridSortRevision>>) -> Self { fn from(revs: Vec<Arc<GridSortRevision>>) -> Self {
RepeatedGridSort { RepeatedGridSortPB {
items: revs.into_iter().map(|rev| rev.as_ref().into()).collect(), items: revs.into_iter().map(|rev| rev.as_ref().into()).collect(),
} }
} }
} }
impl std::convert::From<Vec<GridSort>> for RepeatedGridSort { impl std::convert::From<Vec<GridSort>> for RepeatedGridSortPB {
fn from(items: Vec<GridSort>) -> Self { fn from(items: Vec<GridSort>) -> Self {
Self { items } Self { items }
} }
} }
#[derive(ProtoBuf, Debug, Default, Clone)] #[derive(ProtoBuf, Debug, Default, Clone)]
pub struct CreateGridSortPayload { pub struct CreateGridSortPayloadPB {
#[pb(index = 1, one_of)] #[pb(index = 1, one_of)]
pub field_id: Option<String>, pub field_id: Option<String>,
} }
impl TryInto<CreateGridSortParams> for CreateGridSortPayload { impl TryInto<CreateGridSortParams> for CreateGridSortPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateGridSortParams, Self::Error> { fn try_into(self) -> Result<CreateGridSortParams, Self::Error> {

View File

@ -3,9 +3,9 @@ use crate::manager::GridManager;
use crate::services::cell::AnyCellData; use crate::services::cell::AnyCellData;
use crate::services::field::{ use crate::services::field::{
default_type_option_builder_from_type, select_option_operation, type_option_builder_from_json_str, default_type_option_builder_from_type, select_option_operation, type_option_builder_from_json_str,
DateChangesetParams, DateChangesetPayload, SelectOption, SelectOptionCellChangeset, DateChangesetParams, DateChangesetPayloadPB, SelectOptionCellChangeset, SelectOptionCellChangesetParams,
SelectOptionCellChangesetParams, SelectOptionCellChangesetPayload, SelectOptionCellData, SelectOptionChangeset, SelectOptionCellChangesetPayloadPB, SelectOptionCellDataPB, SelectOptionChangeset, SelectOptionChangesetPayloadPB,
SelectOptionChangesetPayload, SelectOptionPB,
}; };
use crate::services::row::make_row_from_row_rev; use crate::services::row::make_row_from_row_rev;
use flowy_error::{ErrorCode, FlowyError, FlowyResult}; use flowy_error::{ErrorCode, FlowyError, FlowyResult};
@ -16,10 +16,10 @@ use std::sync::Arc;
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_grid_handler( pub(crate) async fn get_grid_handler(
data: Data<GridId>, data: Data<GridIdPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<Grid, FlowyError> { ) -> DataResult<GridPB, FlowyError> {
let grid_id: GridId = data.into_inner(); let grid_id: GridIdPB = data.into_inner();
let editor = manager.open_grid(grid_id).await?; let editor = manager.open_grid(grid_id).await?;
let grid = editor.get_grid_data().await?; let grid = editor.get_grid_data().await?;
data_result(grid) data_result(grid)
@ -27,10 +27,10 @@ pub(crate) async fn get_grid_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_grid_setting_handler( pub(crate) async fn get_grid_setting_handler(
data: Data<GridId>, data: Data<GridIdPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<GridSetting, FlowyError> { ) -> DataResult<GridSettingPB, FlowyError> {
let grid_id: GridId = data.into_inner(); let grid_id: GridIdPB = data.into_inner();
let editor = manager.open_grid(grid_id).await?; let editor = manager.open_grid(grid_id).await?;
let grid_setting = editor.get_grid_setting().await?; let grid_setting = editor.get_grid_setting().await?;
data_result(grid_setting) data_result(grid_setting)
@ -38,7 +38,7 @@ pub(crate) async fn get_grid_setting_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn update_grid_setting_handler( pub(crate) async fn update_grid_setting_handler(
data: Data<GridSettingChangesetPayload>, data: Data<GridSettingChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridSettingChangesetParams = data.into_inner().try_into()?; let params: GridSettingChangesetParams = data.into_inner().try_into()?;
@ -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<QueryGridBlocksPayload>, data: Data<QueryGridBlocksPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<RepeatedGridBlock, FlowyError> { ) -> DataResult<RepeatedGridBlockPB, 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?;
@ -60,25 +60,25 @@ pub(crate) async fn get_grid_blocks_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_fields_handler( pub(crate) async fn get_fields_handler(
data: Data<QueryFieldPayload>, data: Data<QueryFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<RepeatedField, FlowyError> { ) -> DataResult<RepeatedGridFieldPB, 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
.field_orders .field_ids
.items .items
.into_iter() .into_iter()
.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: RepeatedField = field_revs.into_iter().map(Field::from).collect::<Vec<_>>().into(); let repeated_field: RepeatedGridFieldPB = field_revs.into_iter().map(GridFieldPB::from).collect::<Vec<_>>().into();
data_result(repeated_field) data_result(repeated_field)
} }
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn update_field_handler( pub(crate) async fn update_field_handler(
data: Data<FieldChangesetPayload>, data: Data<FieldChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let changeset: FieldChangesetParams = data.into_inner().try_into()?; let changeset: FieldChangesetParams = data.into_inner().try_into()?;
@ -89,7 +89,7 @@ pub(crate) async fn update_field_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn insert_field_handler( pub(crate) async fn insert_field_handler(
data: Data<InsertFieldPayload>, data: Data<InsertFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: InsertFieldParams = data.into_inner().try_into()?; let params: InsertFieldParams = data.into_inner().try_into()?;
@ -100,7 +100,7 @@ pub(crate) async fn insert_field_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn update_field_type_option_handler( pub(crate) async fn update_field_type_option_handler(
data: Data<UpdateFieldTypeOptionPayload>, data: Data<UpdateFieldTypeOptionPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: UpdateFieldTypeOptionParams = data.into_inner().try_into()?; let params: UpdateFieldTypeOptionParams = data.into_inner().try_into()?;
@ -113,10 +113,10 @@ pub(crate) async fn update_field_type_option_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn delete_field_handler( pub(crate) async fn delete_field_handler(
data: Data<FieldIdentifierPayload>, data: Data<GridFieldIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: FieldIdentifier = data.into_inner().try_into()?; let params: FieldIdentifierParams = 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(())
@ -124,9 +124,9 @@ pub(crate) async fn delete_field_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn switch_to_field_handler( pub(crate) async fn switch_to_field_handler(
data: Data<EditFieldPayload>, data: Data<EditFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionData, FlowyError> { ) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: EditFieldParams = data.into_inner().try_into()?; let params: EditFieldParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?; let editor = manager.get_grid_editor(&params.grid_id)?;
editor editor
@ -140,7 +140,7 @@ pub(crate) async fn switch_to_field_handler(
.unwrap_or(Arc::new(editor.next_field_rev(&params.field_type).await?)); .unwrap_or(Arc::new(editor.next_field_rev(&params.field_type).await?));
let type_option_data = get_type_option_data(&field_rev, &params.field_type).await?; let type_option_data = get_type_option_data(&field_rev, &params.field_type).await?;
let data = FieldTypeOptionData { let data = FieldTypeOptionDataPB {
grid_id: params.grid_id, grid_id: params.grid_id,
field: field_rev.into(), field: field_rev.into(),
type_option_data, type_option_data,
@ -151,10 +151,10 @@ pub(crate) async fn switch_to_field_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn duplicate_field_handler( pub(crate) async fn duplicate_field_handler(
data: Data<FieldIdentifierPayload>, data: Data<GridFieldIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: FieldIdentifier = data.into_inner().try_into()?; let params: FieldIdentifierParams = 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,9 +163,9 @@ 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<EditFieldPayload>, data: Data<EditFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionData, FlowyError> { ) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: EditFieldParams = data.into_inner().try_into()?; let params: EditFieldParams = 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 {
@ -173,7 +173,7 @@ pub(crate) async fn get_field_type_option_data_handler(
Some(field_rev) => { Some(field_rev) => {
let field_type = field_rev.field_type_rev.into(); let field_type = field_rev.field_type_rev.into();
let type_option_data = get_type_option_data(&field_rev, &field_type).await?; let type_option_data = get_type_option_data(&field_rev, &field_type).await?;
let data = FieldTypeOptionData { let data = FieldTypeOptionDataPB {
grid_id: params.grid_id, grid_id: params.grid_id,
field: field_rev.into(), field: field_rev.into(),
type_option_data, type_option_data,
@ -186,16 +186,16 @@ pub(crate) async fn get_field_type_option_data_handler(
/// Create FieldMeta and save it. Return the FieldTypeOptionData. /// Create FieldMeta and save it. Return the FieldTypeOptionData.
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn create_field_type_option_data_handler( pub(crate) async fn create_field_type_option_data_handler(
data: Data<EditFieldPayload>, data: Data<EditFieldPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionData, FlowyError> { ) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: CreateFieldParams = data.into_inner().try_into()?; let params: CreateFieldParams = 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_rev = editor.create_next_field_rev(&params.field_type).await?; let field_rev = editor.create_next_field_rev(&params.field_type).await?;
let field_type: FieldType = field_rev.field_type_rev.into(); let field_type: FieldType = field_rev.field_type_rev.into();
let type_option_data = get_type_option_data(&field_rev, &field_type).await?; let type_option_data = get_type_option_data(&field_rev, &field_type).await?;
data_result(FieldTypeOptionData { data_result(FieldTypeOptionDataPB {
grid_id: params.grid_id, grid_id: params.grid_id,
field: field_rev.into(), field: field_rev.into(),
type_option_data, type_option_data,
@ -204,7 +204,7 @@ pub(crate) async fn create_field_type_option_data_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn move_item_handler( pub(crate) async fn move_item_handler(
data: Data<MoveItemPayload>, data: Data<MoveItemPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: MoveItemParams = data.into_inner().try_into()?; let params: MoveItemParams = data.into_inner().try_into()?;
@ -227,25 +227,25 @@ 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<GridRowIdPayload>, data: Data<GridRowIdPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<OptionalRow, FlowyError> { ) -> DataResult<OptionalRowPB, FlowyError> {
let params: GridRowId = data.into_inner().try_into()?; let params: GridRowIdPB = 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)
.await? .await?
.and_then(make_row_from_row_rev); .and_then(make_row_from_row_rev);
data_result(OptionalRow { row }) data_result(OptionalRowPB { row })
} }
#[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<GridRowIdPayload>, data: Data<GridRowIdPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridRowId = data.into_inner().try_into()?; let params: GridRowIdPB = 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<GridRowIdPayload>, data: Data<GridRowIdPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: GridRowId = data.into_inner().try_into()?; let params: GridRowIdPB = 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(())
@ -264,7 +264,7 @@ pub(crate) async fn duplicate_row_handler(
#[tracing::instrument(level = "debug", skip(data, manager), err)] #[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn create_row_handler( pub(crate) async fn create_row_handler(
data: Data<CreateRowPayload>, data: Data<CreateRowPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: CreateRowParams = data.into_inner().try_into()?; let params: CreateRowParams = data.into_inner().try_into()?;
@ -275,23 +275,23 @@ pub(crate) async fn create_row_handler(
// #[tracing::instrument(level = "debug", skip_all, err)] // #[tracing::instrument(level = "debug", skip_all, err)]
pub(crate) async fn get_cell_handler( pub(crate) async fn get_cell_handler(
data: Data<CellIdentifierPayload>, data: Data<GridCellIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<Cell, FlowyError> { ) -> DataResult<GridCellPB, FlowyError> {
let params: CellIdentifier = data.into_inner().try_into()?; let params: CellIdentifierParams = 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_cell(&params).await { match editor.get_cell(&params).await {
None => data_result(Cell::empty(&params.field_id)), None => data_result(GridCellPB::empty(&params.field_id)),
Some(cell) => data_result(cell), Some(cell) => data_result(cell),
} }
} }
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn update_cell_handler( pub(crate) async fn update_cell_handler(
data: Data<CellChangeset>, data: Data<CellChangesetPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let changeset: CellChangeset = data.into_inner(); let changeset: CellChangesetPB = data.into_inner();
let editor = manager.get_grid_editor(&changeset.grid_id)?; let editor = manager.get_grid_editor(&changeset.grid_id)?;
let _ = editor.update_cell(changeset).await?; let _ = editor.update_cell(changeset).await?;
Ok(()) Ok(())
@ -299,9 +299,9 @@ pub(crate) async fn update_cell_handler(
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn new_select_option_handler( pub(crate) async fn new_select_option_handler(
data: Data<CreateSelectOptionPayload>, data: Data<CreateSelectOptionPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<SelectOption, FlowyError> { ) -> DataResult<SelectOptionPB, FlowyError> {
let params: CreateSelectOptionParams = data.into_inner().try_into()?; let params: CreateSelectOptionParams = 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 {
@ -316,7 +316,7 @@ pub(crate) async fn new_select_option_handler(
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn update_select_option_handler( pub(crate) async fn update_select_option_handler(
data: Data<SelectOptionChangesetPayload>, data: Data<SelectOptionChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let changeset: SelectOptionChangeset = data.into_inner().try_into()?; let changeset: SelectOptionChangeset = data.into_inner().try_into()?;
@ -344,7 +344,7 @@ pub(crate) async fn update_select_option_handler(
mut_field_rev.insert_type_option_entry(&*type_option); mut_field_rev.insert_type_option_entry(&*type_option);
let _ = editor.replace_field(field_rev).await?; let _ = editor.replace_field(field_rev).await?;
let changeset = CellChangeset { let changeset = CellChangesetPB {
grid_id: changeset.cell_identifier.grid_id, grid_id: changeset.cell_identifier.grid_id,
row_id: changeset.cell_identifier.row_id, row_id: changeset.cell_identifier.row_id,
field_id: changeset.cell_identifier.field_id, field_id: changeset.cell_identifier.field_id,
@ -357,15 +357,15 @@ pub(crate) async fn update_select_option_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)] #[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_select_option_handler( pub(crate) async fn get_select_option_handler(
data: Data<CellIdentifierPayload>, data: Data<GridCellIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> DataResult<SelectOptionCellData, FlowyError> { ) -> DataResult<SelectOptionCellDataPB, FlowyError> {
let params: CellIdentifier = data.into_inner().try_into()?; let params: CellIdentifierParams = 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 => { None => {
tracing::error!("Can't find the select option field with id: {}", params.field_id); tracing::error!("Can't find the select option field with id: {}", params.field_id);
data_result(SelectOptionCellData::default()) data_result(SelectOptionCellDataPB::default())
} }
Some(field_rev) => { Some(field_rev) => {
// //
@ -386,7 +386,7 @@ pub(crate) async fn get_select_option_handler(
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn update_select_option_cell_handler( pub(crate) async fn update_select_option_cell_handler(
data: Data<SelectOptionCellChangesetPayload>, data: Data<SelectOptionCellChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: SelectOptionCellChangesetParams = data.into_inner().try_into()?; let params: SelectOptionCellChangesetParams = data.into_inner().try_into()?;
@ -397,7 +397,7 @@ pub(crate) async fn update_select_option_cell_handler(
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn update_date_cell_handler( pub(crate) async fn update_date_cell_handler(
data: Data<DateChangesetPayload>, data: Data<DateChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>, manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> { ) -> Result<(), FlowyError> {
let params: DateChangesetParams = data.into_inner().try_into()?; let params: DateChangesetParams = data.into_inner().try_into()?;

View File

@ -45,78 +45,78 @@ pub fn create(grid_manager: Arc<GridManager>) -> Module {
#[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)] #[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)]
#[event_err = "FlowyError"] #[event_err = "FlowyError"]
pub enum GridEvent { pub enum GridEvent {
#[event(input = "GridId", output = "Grid")] #[event(input = "GridIdPB", output = "GridPB")]
GetGrid = 0, GetGrid = 0,
#[event(input = "QueryGridBlocksPayload", output = "RepeatedGridBlock")] #[event(input = "QueryGridBlocksPayloadPB", output = "RepeatedGridBlockPB")]
GetGridBlocks = 1, GetGridBlocks = 1,
#[event(input = "GridId", output = "GridSetting")] #[event(input = "GridIdPB", output = "GridSettingPB")]
GetGridSetting = 2, GetGridSetting = 2,
#[event(input = "GridId", input = "GridSettingChangesetPayload")] #[event(input = "GridIdPB", input = "GridSettingChangesetPayloadPB")]
UpdateGridSetting = 3, UpdateGridSetting = 3,
#[event(input = "QueryFieldPayload", output = "RepeatedField")] #[event(input = "QueryFieldPayloadPB", output = "RepeatedGridFieldPB")]
GetFields = 10, GetFields = 10,
#[event(input = "FieldChangesetPayload")] #[event(input = "FieldChangesetPayloadPB")]
UpdateField = 11, UpdateField = 11,
#[event(input = "UpdateFieldTypeOptionPayload")] #[event(input = "UpdateFieldTypeOptionPayloadPB")]
UpdateFieldTypeOption = 12, UpdateFieldTypeOption = 12,
#[event(input = "InsertFieldPayload")] #[event(input = "InsertFieldPayloadPB")]
InsertField = 13, InsertField = 13,
#[event(input = "FieldIdentifierPayload")] #[event(input = "GridFieldIdentifierPayloadPB")]
DeleteField = 14, DeleteField = 14,
#[event(input = "EditFieldPayload", output = "FieldTypeOptionData")] #[event(input = "EditFieldPayloadPB", output = "FieldTypeOptionDataPB")]
SwitchToField = 20, SwitchToField = 20,
#[event(input = "FieldIdentifierPayload")] #[event(input = "GridFieldIdentifierPayloadPB")]
DuplicateField = 21, DuplicateField = 21,
#[event(input = "MoveItemPayload")] #[event(input = "MoveItemPayloadPB")]
MoveItem = 22, MoveItem = 22,
#[event(input = "EditFieldPayload", output = "FieldTypeOptionData")] #[event(input = "EditFieldPayloadPB", output = "FieldTypeOptionDataPB")]
GetFieldTypeOption = 23, GetFieldTypeOption = 23,
#[event(input = "EditFieldPayload", output = "FieldTypeOptionData")] #[event(input = "EditFieldPayloadPB", output = "FieldTypeOptionDataPB")]
CreateFieldTypeOption = 24, CreateFieldTypeOption = 24,
#[event(input = "CreateSelectOptionPayload", output = "SelectOption")] #[event(input = "CreateSelectOptionPayloadPB", output = "SelectOptionPB")]
NewSelectOption = 30, NewSelectOption = 30,
#[event(input = "CellIdentifierPayload", output = "SelectOptionCellData")] #[event(input = "GridCellIdentifierPayloadPB", output = "SelectOptionCellDataPB")]
GetSelectOptionCellData = 31, GetSelectOptionCellData = 31,
#[event(input = "SelectOptionChangesetPayload")] #[event(input = "SelectOptionChangesetPayloadPB")]
UpdateSelectOption = 32, UpdateSelectOption = 32,
#[event(input = "CreateRowPayload", output = "Row")] #[event(input = "CreateRowPayloadPB", output = "GridRowPB")]
CreateRow = 50, CreateRow = 50,
#[event(input = "GridRowIdPayload", output = "OptionalRow")] #[event(input = "GridRowIdPayloadPB", output = "OptionalRowPB")]
GetRow = 51, GetRow = 51,
#[event(input = "GridRowIdPayload")] #[event(input = "GridRowIdPayloadPB")]
DeleteRow = 52, DeleteRow = 52,
#[event(input = "GridRowIdPayload")] #[event(input = "GridRowIdPayloadPB")]
DuplicateRow = 53, DuplicateRow = 53,
#[event(input = "CellIdentifierPayload", output = "Cell")] #[event(input = "GridCellIdentifierPayloadPB", output = "GridCellPB")]
GetCell = 70, GetCell = 70,
#[event(input = "CellChangeset")] #[event(input = "CellChangesetPB")]
UpdateCell = 71, UpdateCell = 71,
#[event(input = "SelectOptionCellChangesetPayload")] #[event(input = "SelectOptionCellChangesetPayloadPB")]
UpdateSelectOptionCell = 72, UpdateSelectOptionCell = 72,
#[event(input = "DateChangesetPayload")] #[event(input = "DateChangesetPayloadPB")]
UpdateDateCell = 80, UpdateDateCell = 80,
} }

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::{CellChangeset, GridBlockChangeset, InsertedRow, Row, RowInfo, UpdatedRow}; use crate::entities::{CellChangesetPB, GridBlockChangesetPB, GridRowPB, InsertedRowPB, UpdatedRowPB};
use crate::manager::GridUser; use crate::manager::GridUser;
use crate::services::block_revision_editor::GridBlockRevisionEditor; use crate::services::block_revision_editor::GridBlockRevisionEditor;
use crate::services::persistence::block_index::BlockIndexCache; use crate::services::persistence::block_index::BlockIndexCache;
@ -71,12 +71,12 @@ impl GridBlockManager {
let _ = self.persistence.insert(&row_rev.block_id, &row_rev.id)?; let _ = self.persistence.insert(&row_rev.block_id, &row_rev.id)?;
let editor = self.get_editor(&row_rev.block_id).await?; let editor = self.get_editor(&row_rev.block_id).await?;
let mut index_row_order = InsertedRow::from(&row_rev); let mut index_row_order = InsertedRowPB::from(&row_rev);
let (row_count, row_index) = editor.create_row(row_rev, start_row_id).await?; let (row_count, row_index) = editor.create_row(row_rev, start_row_id).await?;
index_row_order.index = row_index; index_row_order.index = row_index;
let _ = self let _ = self
.notify_did_update_block(block_id, GridBlockChangeset::insert(block_id, vec![index_row_order])) .notify_did_update_block(block_id, GridBlockChangesetPB::insert(block_id, vec![index_row_order]))
.await?; .await?;
Ok(row_count) Ok(row_count)
} }
@ -92,7 +92,7 @@ impl GridBlockManager {
let mut row_count = 0; let mut row_count = 0;
for row in row_revs { for row in row_revs {
let _ = self.persistence.insert(&row.block_id, &row.id)?; let _ = self.persistence.insert(&row.block_id, &row.id)?;
let mut row_order = InsertedRow::from(&row); let mut row_order = InsertedRowPB::from(&row);
let (count, index) = editor.create_row(row, None).await?; let (count, index) = editor.create_row(row, None).await?;
row_count = count; row_count = count;
row_order.index = index; row_order.index = index;
@ -101,7 +101,7 @@ impl GridBlockManager {
changesets.push(GridBlockMetaRevisionChangeset::from_row_count(&block_id, row_count)); changesets.push(GridBlockMetaRevisionChangeset::from_row_count(&block_id, row_count));
let _ = self let _ = self
.notify_did_update_block(&block_id, GridBlockChangeset::insert(&block_id, inserted_row_orders)) .notify_did_update_block(&block_id, GridBlockChangesetPB::insert(&block_id, inserted_row_orders))
.await?; .await?;
} }
@ -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<Row>, F: FnOnce(Arc<RowRevision>) -> Option<GridRowPB>,
{ {
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?;
@ -118,8 +118,8 @@ impl GridBlockManager {
None => tracing::error!("Internal error: can't find the row with id: {}", changeset.row_id), None => tracing::error!("Internal error: can't find the row with id: {}", changeset.row_id),
Some(row_rev) => { Some(row_rev) => {
if let Some(row) = row_builder(row_rev.clone()) { if let Some(row) = row_builder(row_rev.clone()) {
let row_order = UpdatedRow::new(&row_rev, row); let row_order = UpdatedRowPB::new(&row_rev, row);
let block_order_changeset = GridBlockChangeset::update(&editor.block_id, vec![row_order]); let block_order_changeset = GridBlockChangesetPB::update(&editor.block_id, vec![row_order]);
let _ = self let _ = self
.notify_did_update_block(&editor.block_id, block_order_changeset) .notify_did_update_block(&editor.block_id, block_order_changeset)
.await?; .await?;
@ -138,7 +138,7 @@ impl GridBlockManager {
Some(row_info) => { Some(row_info) => {
let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?; let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?;
let _ = self let _ = self
.notify_did_update_block(&block_id, GridBlockChangeset::delete(&block_id, vec![row_info.row_id])) .notify_did_update_block(&block_id, GridBlockChangesetPB::delete(&block_id, vec![row_info.id]))
.await?; .await?;
} }
} }
@ -148,13 +148,13 @@ impl GridBlockManager {
pub(crate) async fn delete_rows( pub(crate) async fn delete_rows(
&self, &self,
row_orders: Vec<RowInfo>, row_orders: Vec<GridRowPB>,
) -> FlowyResult<Vec<GridBlockMetaRevisionChangeset>> { ) -> 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?;
let row_ids = grid_block let row_ids = grid_block
.row_infos .rows
.into_iter() .into_iter()
.map(|row_info| Cow::Owned(row_info.row_id().to_owned())) .map(|row_info| Cow::Owned(row_info.row_id().to_owned()))
.collect::<Vec<Cow<String>>>(); .collect::<Vec<Cow<String>>>();
@ -173,14 +173,14 @@ impl GridBlockManager {
match editor.get_row_revs(Some(vec![Cow::Borrowed(row_id)])).await?.pop() { match editor.get_row_revs(Some(vec![Cow::Borrowed(row_id)])).await?.pop() {
None => {} None => {}
Some(row_rev) => { Some(row_rev) => {
let insert_row = InsertedRow { let insert_row = InsertedRowPB {
block_id: row_rev.block_id.clone(), block_id: row_rev.block_id.clone(),
row_id: row_rev.id.clone(), row_id: row_rev.id.clone(),
index: Some(to as i32), index: Some(to as i32),
height: row_rev.height, height: row_rev.height,
}; };
let notified_changeset = GridBlockChangeset { let notified_changeset = GridBlockChangesetPB {
block_id: editor.block_id.clone(), block_id: editor.block_id.clone(),
inserted_rows: vec![insert_row], inserted_rows: vec![insert_row],
deleted_rows: vec![row_rev.id.clone()], deleted_rows: vec![row_rev.id.clone()],
@ -196,9 +196,9 @@ impl GridBlockManager {
Ok(()) Ok(())
} }
pub async fn update_cell<F>(&self, changeset: CellChangeset, row_builder: F) -> FlowyResult<()> pub async fn update_cell<F>(&self, changeset: CellChangesetPB, row_builder: F) -> FlowyResult<()>
where where
F: FnOnce(Arc<RowRevision>) -> Option<Row>, F: FnOnce(Arc<RowRevision>) -> Option<GridRowPB>,
{ {
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 +217,7 @@ impl GridBlockManager {
} }
} }
pub async fn get_row_orders(&self, block_id: &str) -> FlowyResult<Vec<RowInfo>> { pub async fn get_row_orders(&self, block_id: &str) -> FlowyResult<Vec<GridRowPB>> {
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
} }
@ -247,14 +247,14 @@ impl GridBlockManager {
Ok(snapshots) Ok(snapshots)
} }
async fn notify_did_update_block(&self, block_id: &str, changeset: GridBlockChangeset) -> FlowyResult<()> { async fn notify_did_update_block(&self, block_id: &str, changeset: GridBlockChangesetPB) -> FlowyResult<()> {
send_dart_notification(block_id, GridNotification::DidUpdateGridBlock) send_dart_notification(block_id, GridNotification::DidUpdateGridBlock)
.payload(changeset) .payload(changeset)
.send(); .send();
Ok(()) Ok(())
} }
async fn notify_did_update_cell(&self, changeset: CellChangeset) -> FlowyResult<()> { async fn notify_did_update_cell(&self, changeset: CellChangesetPB) -> FlowyResult<()> {
let id = format!("{}:{}", changeset.row_id, changeset.field_id); let id = format!("{}:{}", changeset.row_id, changeset.field_id);
send_dart_notification(&id, GridNotification::DidUpdateCell).send(); send_dart_notification(&id, GridNotification::DidUpdateCell).send();
Ok(()) Ok(())

View File

@ -1,4 +1,4 @@
use crate::entities::RowInfo; use crate::entities::GridRowPB;
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<RowInfo>> { pub async fn get_row_info(&self, row_id: &str) -> FlowyResult<Option<GridRowPB>> {
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<RowInfo>> pub async fn get_row_infos<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<GridRowPB>>
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(RowInfo::from) .map(GridRowPB::from)
.collect::<Vec<RowInfo>>(); .collect::<Vec<GridRowPB>>();
Ok(row_infos) Ok(row_infos)
} }

View File

@ -58,7 +58,9 @@ pub fn apply_cell_data_changeset<C: ToString, T: AsRef<FieldRevision>>(
FieldType::RichText => RichTextTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::RichText => RichTextTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev),
FieldType::Number => NumberTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::Number => NumberTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev),
FieldType::DateTime => DateTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::DateTime => DateTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev),
FieldType::SingleSelect => SingleSelectTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::SingleSelect => {
SingleSelectTypeOptionPB::from(field_rev).apply_changeset(changeset.into(), cell_rev)
}
FieldType::MultiSelect => MultiSelectTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::MultiSelect => MultiSelectTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev),
FieldType::Checkbox => CheckboxTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::Checkbox => CheckboxTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev),
FieldType::URL => URLTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev), FieldType::URL => URLTypeOption::from(field_rev).apply_changeset(changeset.into(), cell_rev),
@ -104,7 +106,7 @@ pub fn try_decode_cell_data(
.get_type_option_entry::<DateTypeOption>(field_type)? .get_type_option_entry::<DateTypeOption>(field_type)?
.decode_cell_data(cell_data.into(), s_field_type, field_rev), .decode_cell_data(cell_data.into(), s_field_type, field_rev),
FieldType::SingleSelect => field_rev FieldType::SingleSelect => field_rev
.get_type_option_entry::<SingleSelectTypeOption>(field_type)? .get_type_option_entry::<SingleSelectTypeOptionPB>(field_type)?
.decode_cell_data(cell_data.into(), s_field_type, field_rev), .decode_cell_data(cell_data.into(), s_field_type, field_rev),
FieldType::MultiSelect => field_rev FieldType::MultiSelect => field_rev
.get_type_option_entry::<MultiSelectTypeOption>(field_type)? .get_type_option_entry::<MultiSelectTypeOption>(field_type)?

View File

@ -1,4 +1,4 @@
use crate::entities::{Field, FieldType}; use crate::entities::{FieldType, GridFieldPB};
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: Field, type_option_builder: Box<dyn TypeOptionBuilder>) -> Self { pub fn from_field(field: GridFieldPB, 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,
@ -93,7 +93,7 @@ pub fn default_type_option_builder_from_type(field_type: &FieldType) -> Box<dyn
FieldType::RichText => RichTextTypeOption::default().into(), FieldType::RichText => RichTextTypeOption::default().into(),
FieldType::Number => NumberTypeOption::default().into(), FieldType::Number => NumberTypeOption::default().into(),
FieldType::DateTime => DateTypeOption::default().into(), FieldType::DateTime => DateTypeOption::default().into(),
FieldType::SingleSelect => SingleSelectTypeOption::default().into(), FieldType::SingleSelect => SingleSelectTypeOptionPB::default().into(),
FieldType::MultiSelect => MultiSelectTypeOption::default().into(), FieldType::MultiSelect => MultiSelectTypeOption::default().into(),
FieldType::Checkbox => CheckboxTypeOption::default().into(), FieldType::Checkbox => CheckboxTypeOption::default().into(),
FieldType::URL => URLTypeOption::default().into(), FieldType::URL => URLTypeOption::default().into(),

View File

@ -14,7 +14,7 @@ mod tests {
let field_rev = FieldBuilder::from_field_type(&field_type).build(); let field_rev = FieldBuilder::from_field_type(&field_type).build();
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some("1e".to_string()), date: Some("1e".to_string()),
time: Some("23:00".to_owned()), time: Some("23:00".to_owned()),
}, },
@ -60,7 +60,7 @@ mod tests {
TimeFormat::TwentyFourHour => { TimeFormat::TwentyFourHour => {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(1653609600.to_string()), date: Some(1653609600.to_string()),
time: None, time: None,
}, },
@ -70,7 +70,7 @@ mod tests {
); );
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(1653609600.to_string()), date: Some(1653609600.to_string()),
time: Some("23:00".to_owned()), time: Some("23:00".to_owned()),
}, },
@ -82,7 +82,7 @@ mod tests {
TimeFormat::TwelveHour => { TimeFormat::TwelveHour => {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(1653609600.to_string()), date: Some(1653609600.to_string()),
time: None, time: None,
}, },
@ -93,7 +93,7 @@ mod tests {
// //
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(1653609600.to_string()), date: Some(1653609600.to_string()),
time: Some("".to_owned()), time: Some("".to_owned()),
}, },
@ -104,7 +104,7 @@ mod tests {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(1653609600.to_string()), date: Some(1653609600.to_string()),
time: Some("11:23 pm".to_owned()), time: Some("11:23 pm".to_owned()),
}, },
@ -126,7 +126,7 @@ mod tests {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp.clone()), date: Some(date_timestamp.clone()),
time: None, time: None,
}, },
@ -138,7 +138,7 @@ mod tests {
type_option.include_time = true; type_option.include_time = true;
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp.clone()), date: Some(date_timestamp.clone()),
time: None, time: None,
}, },
@ -149,7 +149,7 @@ mod tests {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp.clone()), date: Some(date_timestamp.clone()),
time: Some("1:00".to_owned()), time: Some("1:00".to_owned()),
}, },
@ -161,7 +161,7 @@ mod tests {
type_option.time_format = TimeFormat::TwelveHour; type_option.time_format = TimeFormat::TwelveHour;
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp), date: Some(date_timestamp),
time: Some("1:00 am".to_owned()), time: Some("1:00 am".to_owned()),
}, },
@ -181,7 +181,7 @@ mod tests {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp.clone()), date: Some(date_timestamp.clone()),
time: Some("1:".to_owned()), time: Some("1:".to_owned()),
}, },
@ -192,7 +192,7 @@ mod tests {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp), date: Some(date_timestamp),
time: Some("1:00".to_owned()), time: Some("1:00".to_owned()),
}, },
@ -212,7 +212,7 @@ mod tests {
assert_changeset_result( assert_changeset_result(
&type_option, &type_option,
DateCellChangeset { DateCellChangesetPB {
date: Some(date_timestamp), date: Some(date_timestamp),
time: Some("1:00 am".to_owned()), time: Some("1:00 am".to_owned()),
}, },
@ -224,7 +224,7 @@ mod tests {
fn assert_changeset_result( fn assert_changeset_result(
type_option: &DateTypeOption, type_option: &DateTypeOption,
changeset: DateCellChangeset, changeset: DateCellChangesetPB,
_field_type: &FieldType, _field_type: &FieldType,
field_rev: &FieldRevision, field_rev: &FieldRevision,
expected: &str, expected: &str,
@ -243,7 +243,7 @@ mod tests {
field_rev: &FieldRevision, field_rev: &FieldRevision,
expected: &str, expected: &str,
) { ) {
let s = serde_json::to_string(&DateCellChangeset { let s = serde_json::to_string(&DateCellChangesetPB {
date: Some(timestamp.to_string()), date: Some(timestamp.to_string()),
time: None, time: None,
}) })

View File

@ -2,7 +2,7 @@ use crate::entities::FieldType;
use crate::impl_type_option; use crate::impl_type_option;
use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable}; use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable};
use crate::services::field::{ use crate::services::field::{
BoxTypeOptionBuilder, DateCellChangeset, DateCellData, DateFormat, DateTimestamp, TimeFormat, TypeOptionBuilder, BoxTypeOptionBuilder, DateCellChangesetPB, DateCellDataPB, DateFormat, DateTimestamp, TimeFormat, TypeOptionBuilder,
}; };
use bytes::Bytes; use bytes::Bytes;
use chrono::format::strftime::StrftimeItems; use chrono::format::strftime::StrftimeItems;
@ -32,15 +32,15 @@ impl DateTypeOption {
Self::default() Self::default()
} }
fn today_desc_from_timestamp<T: AsRef<i64>>(&self, timestamp: T) -> DateCellData { fn today_desc_from_timestamp<T: AsRef<i64>>(&self, timestamp: T) -> DateCellDataPB {
let timestamp = *timestamp.as_ref(); let timestamp = *timestamp.as_ref();
let native = chrono::NaiveDateTime::from_timestamp(timestamp, 0); let native = chrono::NaiveDateTime::from_timestamp(timestamp, 0);
self.date_from_native(native) self.date_from_native(native)
} }
fn date_from_native(&self, native: chrono::NaiveDateTime) -> DateCellData { fn date_from_native(&self, native: chrono::NaiveDateTime) -> DateCellDataPB {
if native.timestamp() == 0 { if native.timestamp() == 0 {
return DateCellData::default(); return DateCellDataPB::default();
} }
let time = native.time(); let time = native.time();
@ -57,7 +57,7 @@ impl DateTypeOption {
} }
let timestamp = native.timestamp(); let timestamp = native.timestamp();
DateCellData { date, time, timestamp } DateCellDataPB { date, time, timestamp }
} }
fn date_fmt(&self, time: &Option<String>) -> String { fn date_fmt(&self, time: &Option<String>) -> String {
@ -129,7 +129,7 @@ impl CellDisplayable<DateTimestamp> for DateTypeOption {
} }
} }
impl CellDataOperation<DateTimestamp, DateCellChangeset> for DateTypeOption { impl CellDataOperation<DateTimestamp, DateCellChangesetPB> for DateTypeOption {
fn decode_cell_data( fn decode_cell_data(
&self, &self,
cell_data: CellData<DateTimestamp>, cell_data: CellData<DateTimestamp>,
@ -148,7 +148,7 @@ impl CellDataOperation<DateTimestamp, DateCellChangeset> for DateTypeOption {
fn apply_changeset( fn apply_changeset(
&self, &self,
changeset: CellDataChangeset<DateCellChangeset>, changeset: CellDataChangeset<DateCellChangesetPB>,
_cell_rev: Option<CellRevision>, _cell_rev: Option<CellRevision>,
) -> Result<String, FlowyError> { ) -> Result<String, FlowyError> {
let changeset = changeset.try_into_inner()?; let changeset = changeset.try_into_inner()?;

View File

@ -1,5 +1,5 @@
use crate::entities::CellChangeset; use crate::entities::CellChangesetPB;
use crate::entities::{CellIdentifier, CellIdentifierPayload}; use crate::entities::{CellIdentifierParams, GridCellIdentifierPayloadPB};
use crate::services::cell::{CellBytesParser, FromCellChangeset, FromCellString}; use crate::services::cell::{CellBytesParser, FromCellChangeset, FromCellString};
use bytes::Bytes; use bytes::Bytes;
@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use strum_macros::EnumIter; use strum_macros::EnumIter;
#[derive(Clone, Debug, Default, ProtoBuf)] #[derive(Clone, Debug, Default, ProtoBuf)]
pub struct DateCellData { pub struct DateCellDataPB {
#[pb(index = 1)] #[pb(index = 1)]
pub date: String, pub date: String,
@ -22,9 +22,9 @@ pub struct DateCellData {
} }
#[derive(Clone, Debug, Default, ProtoBuf)] #[derive(Clone, Debug, Default, ProtoBuf)]
pub struct DateChangesetPayload { pub struct DateChangesetPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub cell_identifier: CellIdentifierPayload, pub cell_identifier: GridCellIdentifierPayloadPB,
#[pb(index = 2, one_of)] #[pb(index = 2, one_of)]
pub date: Option<String>, pub date: Option<String>,
@ -34,16 +34,16 @@ pub struct DateChangesetPayload {
} }
pub struct DateChangesetParams { pub struct DateChangesetParams {
pub cell_identifier: CellIdentifier, pub cell_identifier: CellIdentifierParams,
pub date: Option<String>, pub date: Option<String>,
pub time: Option<String>, pub time: Option<String>,
} }
impl TryInto<DateChangesetParams> for DateChangesetPayload { impl TryInto<DateChangesetParams> for DateChangesetPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<DateChangesetParams, Self::Error> { fn try_into(self) -> Result<DateChangesetParams, Self::Error> {
let cell_identifier: CellIdentifier = self.cell_identifier.try_into()?; let cell_identifier: CellIdentifierParams = self.cell_identifier.try_into()?;
Ok(DateChangesetParams { Ok(DateChangesetParams {
cell_identifier, cell_identifier,
date: self.date, date: self.date,
@ -52,14 +52,14 @@ impl TryInto<DateChangesetParams> for DateChangesetPayload {
} }
} }
impl std::convert::From<DateChangesetParams> for CellChangeset { impl std::convert::From<DateChangesetParams> for CellChangesetPB {
fn from(params: DateChangesetParams) -> Self { fn from(params: DateChangesetParams) -> Self {
let changeset = DateCellChangeset { let changeset = DateCellChangesetPB {
date: params.date, date: params.date,
time: params.time, time: params.time,
}; };
let s = serde_json::to_string(&changeset).unwrap(); let s = serde_json::to_string(&changeset).unwrap();
CellChangeset { CellChangesetPB {
grid_id: params.cell_identifier.grid_id, grid_id: params.cell_identifier.grid_id,
row_id: params.cell_identifier.row_id, row_id: params.cell_identifier.row_id,
field_id: params.cell_identifier.field_id, field_id: params.cell_identifier.field_id,
@ -69,12 +69,12 @@ impl std::convert::From<DateChangesetParams> for CellChangeset {
} }
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
pub struct DateCellChangeset { pub struct DateCellChangesetPB {
pub date: Option<String>, pub date: Option<String>,
pub time: Option<String>, pub time: Option<String>,
} }
impl DateCellChangeset { impl DateCellChangesetPB {
pub fn date_timestamp(&self) -> Option<i64> { pub fn date_timestamp(&self) -> Option<i64> {
if let Some(date) = &self.date { if let Some(date) = &self.date {
match date.parse::<i64>() { match date.parse::<i64>() {
@ -87,12 +87,12 @@ impl DateCellChangeset {
} }
} }
impl FromCellChangeset for DateCellChangeset { impl FromCellChangeset for DateCellChangesetPB {
fn from_changeset(changeset: String) -> FlowyResult<Self> fn from_changeset(changeset: String) -> FlowyResult<Self>
where where
Self: Sized, Self: Sized,
{ {
serde_json::from_str::<DateCellChangeset>(&changeset).map_err(internal_error) serde_json::from_str::<DateCellChangesetPB>(&changeset).map_err(internal_error)
} }
} }
pub struct DateTimestamp(i64); pub struct DateTimestamp(i64);
@ -202,9 +202,9 @@ impl std::default::Default for TimeFormat {
pub struct DateCellDataParser(); pub struct DateCellDataParser();
impl CellBytesParser for DateCellDataParser { impl CellBytesParser for DateCellDataParser {
type Object = DateCellData; type Object = DateCellDataPB;
fn parse(&self, bytes: &Bytes) -> FlowyResult<Self::Object> { fn parse(&self, bytes: &Bytes) -> FlowyResult<Self::Object> {
DateCellData::try_from(bytes.as_ref()).map_err(internal_error) DateCellDataPB::try_from(bytes.as_ref()).map_err(internal_error)
} }
} }

View File

@ -3,8 +3,8 @@ use crate::impl_type_option;
use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable}; use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable};
use crate::services::field::type_options::util::get_cell_data; use crate::services::field::type_options::util::get_cell_data;
use crate::services::field::{ use crate::services::field::{
make_selected_select_options, BoxTypeOptionBuilder, SelectOption, SelectOptionCellChangeset, SelectOptionCellData, make_selected_select_options, BoxTypeOptionBuilder, SelectOptionCellChangeset, SelectOptionCellDataPB,
SelectOptionIds, SelectOptionOperation, TypeOptionBuilder, SELECTION_IDS_SEPARATOR, SelectOptionIds, SelectOptionOperation, SelectOptionPB, TypeOptionBuilder, SELECTION_IDS_SEPARATOR,
}; };
use bytes::Bytes; use bytes::Bytes;
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
@ -16,7 +16,7 @@ use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)] #[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct MultiSelectTypeOption { pub struct MultiSelectTypeOption {
#[pb(index = 1)] #[pb(index = 1)]
pub options: Vec<SelectOption>, pub options: Vec<SelectOptionPB>,
#[pb(index = 2)] #[pb(index = 2)]
pub disable_color: bool, pub disable_color: bool,
@ -24,19 +24,19 @@ pub struct MultiSelectTypeOption {
impl_type_option!(MultiSelectTypeOption, FieldType::MultiSelect); impl_type_option!(MultiSelectTypeOption, FieldType::MultiSelect);
impl SelectOptionOperation for MultiSelectTypeOption { impl SelectOptionOperation for MultiSelectTypeOption {
fn selected_select_option(&self, cell_data: CellData<SelectOptionIds>) -> SelectOptionCellData { fn selected_select_option(&self, cell_data: CellData<SelectOptionIds>) -> SelectOptionCellDataPB {
let select_options = make_selected_select_options(cell_data, &self.options); let select_options = make_selected_select_options(cell_data, &self.options);
SelectOptionCellData { SelectOptionCellDataPB {
options: self.options.clone(), options: self.options.clone(),
select_options, select_options,
} }
} }
fn options(&self) -> &Vec<SelectOption> { fn options(&self) -> &Vec<SelectOptionPB> {
&self.options &self.options
} }
fn mut_options(&mut self) -> &mut Vec<SelectOption> { fn mut_options(&mut self) -> &mut Vec<SelectOptionPB> {
&mut self.options &mut self.options
} }
} }
@ -97,7 +97,7 @@ pub struct MultiSelectTypeOptionBuilder(MultiSelectTypeOption);
impl_into_box_type_option_builder!(MultiSelectTypeOptionBuilder); impl_into_box_type_option_builder!(MultiSelectTypeOptionBuilder);
impl_builder_from_json_str_and_from_bytes!(MultiSelectTypeOptionBuilder, MultiSelectTypeOption); impl_builder_from_json_str_and_from_bytes!(MultiSelectTypeOptionBuilder, MultiSelectTypeOption);
impl MultiSelectTypeOptionBuilder { impl MultiSelectTypeOptionBuilder {
pub fn option(mut self, opt: SelectOption) -> Self { pub fn option(mut self, opt: SelectOptionPB) -> Self {
self.0.options.push(opt); self.0.options.push(opt);
self self
} }
@ -123,9 +123,9 @@ mod tests {
#[test] #[test]
fn multi_select_test() { fn multi_select_test() {
let google_option = SelectOption::new("Google"); let google_option = SelectOptionPB::new("Google");
let facebook_option = SelectOption::new("Facebook"); let facebook_option = SelectOptionPB::new("Facebook");
let twitter_option = SelectOption::new("Twitter"); let twitter_option = SelectOptionPB::new("Twitter");
let multi_select = MultiSelectTypeOptionBuilder::default() let multi_select = MultiSelectTypeOptionBuilder::default()
.option(google_option.clone()) .option(google_option.clone())
.option(facebook_option.clone()) .option(facebook_option.clone())
@ -172,7 +172,7 @@ mod tests {
cell_data: String, cell_data: String,
type_option: &MultiSelectTypeOption, type_option: &MultiSelectTypeOption,
field_rev: &FieldRevision, field_rev: &FieldRevision,
expected: Vec<SelectOption>, expected: Vec<SelectOptionPB>,
) { ) {
let field_type: FieldType = field_rev.field_type_rev.into(); let field_type: FieldType = field_rev.field_type_rev.into();
assert_eq!( assert_eq!(

View File

@ -1,6 +1,6 @@
use crate::entities::{CellChangeset, CellIdentifier, CellIdentifierPayload, FieldType}; use crate::entities::{CellChangesetPB, CellIdentifierParams, FieldType, GridCellIdentifierPayloadPB};
use crate::services::cell::{CellBytes, CellBytesParser, CellData, CellDisplayable, FromCellChangeset, FromCellString}; use crate::services::cell::{CellBytes, CellBytesParser, CellData, CellDisplayable, FromCellChangeset, FromCellString};
use crate::services::field::{MultiSelectTypeOption, SingleSelectTypeOption}; use crate::services::field::{MultiSelectTypeOption, SingleSelectTypeOptionPB};
use bytes::Bytes; use bytes::Bytes;
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::{internal_error, ErrorCode, FlowyResult}; use flowy_error::{internal_error, ErrorCode, FlowyResult};
@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
pub const SELECTION_IDS_SEPARATOR: &str = ","; pub const SELECTION_IDS_SEPARATOR: &str = ",";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ProtoBuf)] #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ProtoBuf)]
pub struct SelectOption { pub struct SelectOptionPB {
#[pb(index = 1)] #[pb(index = 1)]
pub id: String, pub id: String,
@ -20,20 +20,20 @@ pub struct SelectOption {
pub name: String, pub name: String,
#[pb(index = 3)] #[pb(index = 3)]
pub color: SelectOptionColor, pub color: SelectOptionColorPB,
} }
impl SelectOption { impl SelectOptionPB {
pub fn new(name: &str) -> Self { pub fn new(name: &str) -> Self {
SelectOption { SelectOptionPB {
id: nanoid!(4), id: nanoid!(4),
name: name.to_owned(), name: name.to_owned(),
color: SelectOptionColor::default(), color: SelectOptionColorPB::default(),
} }
} }
pub fn with_color(name: &str, color: SelectOptionColor) -> Self { pub fn with_color(name: &str, color: SelectOptionColorPB) -> Self {
SelectOption { SelectOptionPB {
id: nanoid!(4), id: nanoid!(4),
name: name.to_owned(), name: name.to_owned(),
color, color,
@ -43,7 +43,7 @@ impl SelectOption {
#[derive(ProtoBuf_Enum, PartialEq, Eq, Serialize, Deserialize, Debug, Clone)] #[derive(ProtoBuf_Enum, PartialEq, Eq, Serialize, Deserialize, Debug, Clone)]
#[repr(u8)] #[repr(u8)]
pub enum SelectOptionColor { pub enum SelectOptionColorPB {
Purple = 0, Purple = 0,
Pink = 1, Pink = 1,
LightPink = 2, LightPink = 2,
@ -55,16 +55,16 @@ pub enum SelectOptionColor {
Blue = 8, Blue = 8,
} }
impl std::default::Default for SelectOptionColor { impl std::default::Default for SelectOptionColorPB {
fn default() -> Self { fn default() -> Self {
SelectOptionColor::Purple SelectOptionColorPB::Purple
} }
} }
pub fn make_selected_select_options( pub fn make_selected_select_options(
cell_data: CellData<SelectOptionIds>, cell_data: CellData<SelectOptionIds>,
options: &[SelectOption], options: &[SelectOptionPB],
) -> Vec<SelectOption> { ) -> Vec<SelectOptionPB> {
if let Ok(ids) = cell_data.try_into_inner() { if let Ok(ids) = cell_data.try_into_inner() {
ids.iter() ids.iter()
.flat_map(|option_id| options.iter().find(|option| &option.id == option_id).cloned()) .flat_map(|option_id| options.iter().find(|option| &option.id == option_id).cloned())
@ -75,7 +75,7 @@ pub fn make_selected_select_options(
} }
pub trait SelectOptionOperation: TypeOptionDataEntry + Send + Sync { pub trait SelectOptionOperation: TypeOptionDataEntry + Send + Sync {
fn insert_option(&mut self, new_option: SelectOption) { fn insert_option(&mut self, new_option: SelectOptionPB) {
let options = self.mut_options(); let options = self.mut_options();
if let Some(index) = options if let Some(index) = options
.iter() .iter()
@ -88,23 +88,23 @@ pub trait SelectOptionOperation: TypeOptionDataEntry + Send + Sync {
} }
} }
fn delete_option(&mut self, delete_option: SelectOption) { fn delete_option(&mut self, delete_option: SelectOptionPB) {
let options = self.mut_options(); let options = self.mut_options();
if let Some(index) = options.iter().position(|option| option.id == delete_option.id) { if let Some(index) = options.iter().position(|option| option.id == delete_option.id) {
options.remove(index); options.remove(index);
} }
} }
fn create_option(&self, name: &str) -> SelectOption { fn create_option(&self, name: &str) -> SelectOptionPB {
let color = select_option_color_from_index(self.options().len()); let color = select_option_color_from_index(self.options().len());
SelectOption::with_color(name, color) SelectOptionPB::with_color(name, color)
} }
fn selected_select_option(&self, cell_data: CellData<SelectOptionIds>) -> SelectOptionCellData; fn selected_select_option(&self, cell_data: CellData<SelectOptionIds>) -> SelectOptionCellDataPB;
fn options(&self) -> &Vec<SelectOption>; fn options(&self) -> &Vec<SelectOptionPB>;
fn mut_options(&mut self) -> &mut Vec<SelectOption>; fn mut_options(&mut self) -> &mut Vec<SelectOptionPB>;
} }
impl<T> CellDisplayable<SelectOptionIds> for T impl<T> CellDisplayable<SelectOptionIds> for T
@ -125,7 +125,7 @@ pub fn select_option_operation(field_rev: &FieldRevision) -> FlowyResult<Box<dyn
let field_type: FieldType = field_rev.field_type_rev.into(); let field_type: FieldType = field_rev.field_type_rev.into();
match &field_type { match &field_type {
FieldType::SingleSelect => { FieldType::SingleSelect => {
let type_option = SingleSelectTypeOption::from(field_rev); let type_option = SingleSelectTypeOptionPB::from(field_rev);
Ok(Box::new(type_option)) Ok(Box::new(type_option))
} }
FieldType::MultiSelect => { FieldType::MultiSelect => {
@ -139,18 +139,18 @@ pub fn select_option_operation(field_rev: &FieldRevision) -> FlowyResult<Box<dyn
} }
} }
pub fn select_option_color_from_index(index: usize) -> SelectOptionColor { pub fn select_option_color_from_index(index: usize) -> SelectOptionColorPB {
match index % 8 { match index % 8 {
0 => SelectOptionColor::Purple, 0 => SelectOptionColorPB::Purple,
1 => SelectOptionColor::Pink, 1 => SelectOptionColorPB::Pink,
2 => SelectOptionColor::LightPink, 2 => SelectOptionColorPB::LightPink,
3 => SelectOptionColor::Orange, 3 => SelectOptionColorPB::Orange,
4 => SelectOptionColor::Yellow, 4 => SelectOptionColorPB::Yellow,
5 => SelectOptionColor::Lime, 5 => SelectOptionColorPB::Lime,
6 => SelectOptionColor::Green, 6 => SelectOptionColorPB::Green,
7 => SelectOptionColor::Aqua, 7 => SelectOptionColorPB::Aqua,
8 => SelectOptionColor::Blue, 8 => SelectOptionColorPB::Blue,
_ => SelectOptionColor::Purple, _ => SelectOptionColorPB::Purple,
} }
} }
pub struct SelectOptionIds(Vec<String>); pub struct SelectOptionIds(Vec<String>);
@ -215,17 +215,17 @@ impl CellBytesParser for SelectOptionIdsParser {
pub struct SelectOptionCellDataParser(); pub struct SelectOptionCellDataParser();
impl CellBytesParser for SelectOptionCellDataParser { impl CellBytesParser for SelectOptionCellDataParser {
type Object = SelectOptionCellData; type Object = SelectOptionCellDataPB;
fn parse(&self, bytes: &Bytes) -> FlowyResult<Self::Object> { fn parse(&self, bytes: &Bytes) -> FlowyResult<Self::Object> {
SelectOptionCellData::try_from(bytes.as_ref()).map_err(internal_error) SelectOptionCellDataPB::try_from(bytes.as_ref()).map_err(internal_error)
} }
} }
#[derive(Clone, Debug, Default, ProtoBuf)] #[derive(Clone, Debug, Default, ProtoBuf)]
pub struct SelectOptionCellChangesetPayload { pub struct SelectOptionCellChangesetPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub cell_identifier: CellIdentifierPayload, pub cell_identifier: GridCellIdentifierPayloadPB,
#[pb(index = 2, one_of)] #[pb(index = 2, one_of)]
pub insert_option_id: Option<String>, pub insert_option_id: Option<String>,
@ -235,19 +235,19 @@ pub struct SelectOptionCellChangesetPayload {
} }
pub struct SelectOptionCellChangesetParams { pub struct SelectOptionCellChangesetParams {
pub cell_identifier: CellIdentifier, pub cell_identifier: CellIdentifierParams,
pub insert_option_id: Option<String>, pub insert_option_id: Option<String>,
pub delete_option_id: Option<String>, pub delete_option_id: Option<String>,
} }
impl std::convert::From<SelectOptionCellChangesetParams> for CellChangeset { impl std::convert::From<SelectOptionCellChangesetParams> for CellChangesetPB {
fn from(params: SelectOptionCellChangesetParams) -> Self { fn from(params: SelectOptionCellChangesetParams) -> Self {
let changeset = SelectOptionCellChangeset { let changeset = SelectOptionCellChangeset {
insert_option_id: params.insert_option_id, insert_option_id: params.insert_option_id,
delete_option_id: params.delete_option_id, delete_option_id: params.delete_option_id,
}; };
let s = serde_json::to_string(&changeset).unwrap(); let s = serde_json::to_string(&changeset).unwrap();
CellChangeset { CellChangesetPB {
grid_id: params.cell_identifier.grid_id, grid_id: params.cell_identifier.grid_id,
row_id: params.cell_identifier.row_id, row_id: params.cell_identifier.row_id,
field_id: params.cell_identifier.field_id, field_id: params.cell_identifier.field_id,
@ -256,11 +256,11 @@ impl std::convert::From<SelectOptionCellChangesetParams> for CellChangeset {
} }
} }
impl TryInto<SelectOptionCellChangesetParams> for SelectOptionCellChangesetPayload { impl TryInto<SelectOptionCellChangesetParams> for SelectOptionCellChangesetPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<SelectOptionCellChangesetParams, Self::Error> { fn try_into(self) -> Result<SelectOptionCellChangesetParams, Self::Error> {
let cell_identifier: CellIdentifier = self.cell_identifier.try_into()?; let cell_identifier: CellIdentifierParams = self.cell_identifier.try_into()?;
let insert_option_id = match self.insert_option_id { let insert_option_id = match self.insert_option_id {
None => None, None => None,
Some(insert_option_id) => Some( Some(insert_option_id) => Some(
@ -323,37 +323,37 @@ impl SelectOptionCellChangeset {
} }
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)] #[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct SelectOptionCellData { pub struct SelectOptionCellDataPB {
#[pb(index = 1)] #[pb(index = 1)]
pub options: Vec<SelectOption>, pub options: Vec<SelectOptionPB>,
#[pb(index = 2)] #[pb(index = 2)]
pub select_options: Vec<SelectOption>, pub select_options: Vec<SelectOptionPB>,
} }
#[derive(Clone, Debug, Default, ProtoBuf)] #[derive(Clone, Debug, Default, ProtoBuf)]
pub struct SelectOptionChangesetPayload { pub struct SelectOptionChangesetPayloadPB {
#[pb(index = 1)] #[pb(index = 1)]
pub cell_identifier: CellIdentifierPayload, pub cell_identifier: GridCellIdentifierPayloadPB,
#[pb(index = 2, one_of)] #[pb(index = 2, one_of)]
pub insert_option: Option<SelectOption>, pub insert_option: Option<SelectOptionPB>,
#[pb(index = 3, one_of)] #[pb(index = 3, one_of)]
pub update_option: Option<SelectOption>, pub update_option: Option<SelectOptionPB>,
#[pb(index = 4, one_of)] #[pb(index = 4, one_of)]
pub delete_option: Option<SelectOption>, pub delete_option: Option<SelectOptionPB>,
} }
pub struct SelectOptionChangeset { pub struct SelectOptionChangeset {
pub cell_identifier: CellIdentifier, pub cell_identifier: CellIdentifierParams,
pub insert_option: Option<SelectOption>, pub insert_option: Option<SelectOptionPB>,
pub update_option: Option<SelectOption>, pub update_option: Option<SelectOptionPB>,
pub delete_option: Option<SelectOption>, pub delete_option: Option<SelectOptionPB>,
} }
impl TryInto<SelectOptionChangeset> for SelectOptionChangesetPayload { impl TryInto<SelectOptionChangeset> for SelectOptionChangesetPayloadPB {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<SelectOptionChangeset, Self::Error> { fn try_into(self) -> Result<SelectOptionChangeset, Self::Error> {
@ -368,11 +368,11 @@ impl TryInto<SelectOptionChangeset> for SelectOptionChangesetPayload {
} }
pub struct SelectedSelectOptions { pub struct SelectedSelectOptions {
pub(crate) options: Vec<SelectOption>, pub(crate) options: Vec<SelectOptionPB>,
} }
impl std::convert::From<SelectOptionCellData> for SelectedSelectOptions { impl std::convert::From<SelectOptionCellDataPB> for SelectedSelectOptions {
fn from(data: SelectOptionCellData) -> Self { fn from(data: SelectOptionCellDataPB) -> Self {
Self { Self {
options: data.select_options, options: data.select_options,
} }

View File

@ -2,8 +2,8 @@ use crate::entities::FieldType;
use crate::impl_type_option; use crate::impl_type_option;
use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable}; use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable};
use crate::services::field::{ use crate::services::field::{
make_selected_select_options, SelectOption, SelectOptionCellChangeset, SelectOptionCellData, SelectOptionIds, make_selected_select_options, SelectOptionCellChangeset, SelectOptionCellDataPB, SelectOptionIds,
SelectOptionOperation, SelectOptionOperation, SelectOptionPB,
}; };
use crate::services::field::{BoxTypeOptionBuilder, TypeOptionBuilder}; use crate::services::field::{BoxTypeOptionBuilder, TypeOptionBuilder};
use bytes::Bytes; use bytes::Bytes;
@ -14,36 +14,36 @@ use serde::{Deserialize, Serialize};
// Single select // Single select
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)] #[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct SingleSelectTypeOption { pub struct SingleSelectTypeOptionPB {
#[pb(index = 1)] #[pb(index = 1)]
pub options: Vec<SelectOption>, pub options: Vec<SelectOptionPB>,
#[pb(index = 2)] #[pb(index = 2)]
pub disable_color: bool, pub disable_color: bool,
} }
impl_type_option!(SingleSelectTypeOption, FieldType::SingleSelect); impl_type_option!(SingleSelectTypeOptionPB, FieldType::SingleSelect);
impl SelectOptionOperation for SingleSelectTypeOption { impl SelectOptionOperation for SingleSelectTypeOptionPB {
fn selected_select_option(&self, cell_data: CellData<SelectOptionIds>) -> SelectOptionCellData { fn selected_select_option(&self, cell_data: CellData<SelectOptionIds>) -> SelectOptionCellDataPB {
let mut select_options = make_selected_select_options(cell_data, &self.options); let mut select_options = make_selected_select_options(cell_data, &self.options);
// only keep option in single select // only keep option in single select
select_options.truncate(1); select_options.truncate(1);
SelectOptionCellData { SelectOptionCellDataPB {
options: self.options.clone(), options: self.options.clone(),
select_options, select_options,
} }
} }
fn options(&self) -> &Vec<SelectOption> { fn options(&self) -> &Vec<SelectOptionPB> {
&self.options &self.options
} }
fn mut_options(&mut self) -> &mut Vec<SelectOption> { fn mut_options(&mut self) -> &mut Vec<SelectOptionPB> {
&mut self.options &mut self.options
} }
} }
impl CellDataOperation<SelectOptionIds, SelectOptionCellChangeset> for SingleSelectTypeOption { impl CellDataOperation<SelectOptionIds, SelectOptionCellChangeset> for SingleSelectTypeOptionPB {
fn decode_cell_data( fn decode_cell_data(
&self, &self,
cell_data: CellData<SelectOptionIds>, cell_data: CellData<SelectOptionIds>,
@ -77,12 +77,12 @@ impl CellDataOperation<SelectOptionIds, SelectOptionCellChangeset> for SingleSel
} }
#[derive(Default)] #[derive(Default)]
pub struct SingleSelectTypeOptionBuilder(SingleSelectTypeOption); pub struct SingleSelectTypeOptionBuilder(SingleSelectTypeOptionPB);
impl_into_box_type_option_builder!(SingleSelectTypeOptionBuilder); impl_into_box_type_option_builder!(SingleSelectTypeOptionBuilder);
impl_builder_from_json_str_and_from_bytes!(SingleSelectTypeOptionBuilder, SingleSelectTypeOption); impl_builder_from_json_str_and_from_bytes!(SingleSelectTypeOptionBuilder, SingleSelectTypeOptionPB);
impl SingleSelectTypeOptionBuilder { impl SingleSelectTypeOptionBuilder {
pub fn option(mut self, opt: SelectOption) -> Self { pub fn option(mut self, opt: SelectOptionPB) -> Self {
self.0.options.push(opt); self.0.options.push(opt);
self self
} }
@ -109,9 +109,9 @@ mod tests {
#[test] #[test]
fn single_select_test() { fn single_select_test() {
let google_option = SelectOption::new("Google"); let google_option = SelectOptionPB::new("Google");
let facebook_option = SelectOption::new("Facebook"); let facebook_option = SelectOptionPB::new("Facebook");
let twitter_option = SelectOption::new("Twitter"); let twitter_option = SelectOptionPB::new("Twitter");
let single_select = SingleSelectTypeOptionBuilder::default() let single_select = SingleSelectTypeOptionBuilder::default()
.option(google_option.clone()) .option(google_option.clone())
.option(facebook_option.clone()) .option(facebook_option.clone())
@ -122,7 +122,7 @@ mod tests {
.visibility(true) .visibility(true)
.build(); .build();
let type_option = SingleSelectTypeOption::from(&field_rev); let type_option = SingleSelectTypeOptionPB::from(&field_rev);
let option_ids = vec![google_option.id.clone(), facebook_option.id].join(SELECTION_IDS_SEPARATOR); let option_ids = vec![google_option.id.clone(), facebook_option.id].join(SELECTION_IDS_SEPARATOR);
let data = SelectOptionCellChangeset::from_insert(&option_ids).to_str(); let data = SelectOptionCellChangeset::from_insert(&option_ids).to_str();
@ -152,9 +152,9 @@ mod tests {
fn assert_single_select_options( fn assert_single_select_options(
cell_data: String, cell_data: String,
type_option: &SingleSelectTypeOption, type_option: &SingleSelectTypeOptionPB,
field_rev: &FieldRevision, field_rev: &FieldRevision,
expected: Vec<SelectOption>, expected: Vec<SelectOptionPB>,
) { ) {
let field_type: FieldType = field_rev.field_type_rev.into(); let field_type: FieldType = field_rev.field_type_rev.into();
assert_eq!( assert_eq!(

View File

@ -131,7 +131,7 @@ mod tests {
); );
// Single select // Single select
let done_option = SelectOption::new("Done"); let done_option = SelectOptionPB::new("Done");
let done_option_id = done_option.id.clone(); let done_option_id = done_option.id.clone();
let single_select = SingleSelectTypeOptionBuilder::default().option(done_option.clone()); let single_select = SingleSelectTypeOptionBuilder::default().option(done_option.clone());
let single_select_field_rev = FieldBuilder::new(single_select).build(); let single_select_field_rev = FieldBuilder::new(single_select).build();
@ -151,8 +151,8 @@ mod tests {
); );
// Multiple select // Multiple select
let google_option = SelectOption::new("Google"); let google_option = SelectOptionPB::new("Google");
let facebook_option = SelectOption::new("Facebook"); let facebook_option = SelectOptionPB::new("Facebook");
let ids = vec![google_option.id.clone(), facebook_option.id.clone()].join(SELECTION_IDS_SEPARATOR); let ids = vec![google_option.id.clone(), facebook_option.id.clone()].join(SELECTION_IDS_SEPARATOR);
let cell_data_changeset = SelectOptionCellChangeset::from_insert(&ids).to_str(); let cell_data_changeset = SelectOptionCellChangeset::from_insert(&ids).to_str();
let multi_select = MultiSelectTypeOptionBuilder::default() let multi_select = MultiSelectTypeOptionBuilder::default()

View File

@ -3,7 +3,7 @@ mod tests {
use crate::entities::FieldType; use crate::entities::FieldType;
use crate::services::cell::{CellData, CellDataOperation}; use crate::services::cell::{CellData, CellDataOperation};
use crate::services::field::{FieldBuilder, URLCellDataParser}; use crate::services::field::{FieldBuilder, URLCellDataParser};
use crate::services::field::{URLCellData, URLTypeOption}; use crate::services::field::{URLCellDataPB, URLTypeOption};
use flowy_grid_data_model::revision::FieldRevision; use flowy_grid_data_model::revision::FieldRevision;
#[test] #[test]
@ -52,12 +52,12 @@ mod tests {
assert_eq!(expected_url.to_owned(), decode_cell_data.url); assert_eq!(expected_url.to_owned(), decode_cell_data.url);
} }
fn decode_cell_data<T: Into<CellData<URLCellData>>>( fn decode_cell_data<T: Into<CellData<URLCellDataPB>>>(
encoded_data: T, encoded_data: T,
type_option: &URLTypeOption, type_option: &URLTypeOption,
field_rev: &FieldRevision, field_rev: &FieldRevision,
field_type: &FieldType, field_type: &FieldType,
) -> URLCellData { ) -> URLCellDataPB {
type_option type_option
.decode_cell_data(encoded_data.into(), field_type, field_rev) .decode_cell_data(encoded_data.into(), field_type, field_rev)
.unwrap() .unwrap()

View File

@ -1,7 +1,7 @@
use crate::entities::FieldType; use crate::entities::FieldType;
use crate::impl_type_option; use crate::impl_type_option;
use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable}; use crate::services::cell::{CellBytes, CellData, CellDataChangeset, CellDataOperation, CellDisplayable};
use crate::services::field::{BoxTypeOptionBuilder, TypeOptionBuilder, URLCellData}; use crate::services::field::{BoxTypeOptionBuilder, TypeOptionBuilder, URLCellDataPB};
use bytes::Bytes; use bytes::Bytes;
use fancy_regex::Regex; use fancy_regex::Regex;
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
@ -32,22 +32,22 @@ pub struct URLTypeOption {
} }
impl_type_option!(URLTypeOption, FieldType::URL); impl_type_option!(URLTypeOption, FieldType::URL);
impl CellDisplayable<URLCellData> for URLTypeOption { impl CellDisplayable<URLCellDataPB> for URLTypeOption {
fn display_data( fn display_data(
&self, &self,
cell_data: CellData<URLCellData>, cell_data: CellData<URLCellDataPB>,
_decoded_field_type: &FieldType, _decoded_field_type: &FieldType,
_field_rev: &FieldRevision, _field_rev: &FieldRevision,
) -> FlowyResult<CellBytes> { ) -> FlowyResult<CellBytes> {
let cell_data: URLCellData = cell_data.try_into_inner()?; let cell_data: URLCellDataPB = cell_data.try_into_inner()?;
CellBytes::from(cell_data) CellBytes::from(cell_data)
} }
} }
impl CellDataOperation<URLCellData, String> for URLTypeOption { impl CellDataOperation<URLCellDataPB, String> for URLTypeOption {
fn decode_cell_data( fn decode_cell_data(
&self, &self,
cell_data: CellData<URLCellData>, cell_data: CellData<URLCellDataPB>,
decoded_field_type: &FieldType, decoded_field_type: &FieldType,
field_rev: &FieldRevision, field_rev: &FieldRevision,
) -> FlowyResult<CellBytes> { ) -> FlowyResult<CellBytes> {
@ -67,7 +67,7 @@ impl CellDataOperation<URLCellData, String> for URLTypeOption {
if let Ok(Some(m)) = URL_REGEX.find(&content) { if let Ok(Some(m)) = URL_REGEX.find(&content) {
url = auto_append_scheme(m.as_str()); url = auto_append_scheme(m.as_str());
} }
URLCellData { url, content }.to_json() URLCellDataPB { url, content }.to_json()
} }
} }

View File

@ -5,7 +5,7 @@ use flowy_error::{internal_error, FlowyResult};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)] #[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct URLCellData { pub struct URLCellDataPB {
#[pb(index = 1)] #[pb(index = 1)]
pub url: String, pub url: String,
@ -13,7 +13,7 @@ pub struct URLCellData {
pub content: String, pub content: String,
} }
impl URLCellData { impl URLCellDataPB {
pub fn new(s: &str) -> Self { pub fn new(s: &str) -> Self {
Self { Self {
url: "".to_string(), url: "".to_string(),
@ -28,15 +28,15 @@ impl URLCellData {
pub struct URLCellDataParser(); pub struct URLCellDataParser();
impl CellBytesParser for URLCellDataParser { impl CellBytesParser for URLCellDataParser {
type Object = URLCellData; type Object = URLCellDataPB;
fn parse(&self, bytes: &Bytes) -> FlowyResult<Self::Object> { fn parse(&self, bytes: &Bytes) -> FlowyResult<Self::Object> {
URLCellData::try_from(bytes.as_ref()).map_err(internal_error) URLCellDataPB::try_from(bytes.as_ref()).map_err(internal_error)
} }
} }
impl FromCellString for URLCellData { impl FromCellString for URLCellDataPB {
fn from_cell_str(s: &str) -> FlowyResult<Self> { fn from_cell_str(s: &str) -> FlowyResult<Self> {
serde_json::from_str::<URLCellData>(s).map_err(internal_error) serde_json::from_str::<URLCellDataPB>(s).map_err(internal_error)
} }
} }

View File

@ -1,10 +1,10 @@
use crate::dart_notification::{send_dart_notification, GridNotification}; use crate::dart_notification::{send_dart_notification, GridNotification};
use crate::entities::{FieldType, GridBlockChangeset}; use crate::entities::{FieldType, GridBlockChangesetPB};
use crate::services::block_manager::GridBlockManager; use crate::services::block_manager::GridBlockManager;
use crate::services::cell::{AnyCellData, CellFilterOperation}; use crate::services::cell::{AnyCellData, CellFilterOperation};
use crate::services::field::{ use crate::services::field::{
CheckboxTypeOption, DateTypeOption, MultiSelectTypeOption, NumberTypeOption, RichTextTypeOption, CheckboxTypeOption, DateTypeOption, MultiSelectTypeOption, NumberTypeOption, RichTextTypeOption,
SingleSelectTypeOption, URLTypeOption, SingleSelectTypeOptionPB, URLTypeOption,
}; };
use crate::services::filter::filter_cache::{ use crate::services::filter::filter_cache::{
refresh_filter_cache, FilterCache, FilterId, FilterResult, FilterResultCache, refresh_filter_cache, FilterCache, FilterId, FilterResult, FilterResultCache,
@ -90,7 +90,7 @@ impl GridFilterService {
} }
} }
let changeset = GridBlockChangeset { let changeset = GridBlockChangesetPB {
block_id: block.block_id, block_id: block.block_id,
hide_rows, hide_rows,
visible_rows, visible_rows,
@ -137,7 +137,7 @@ impl GridFilterService {
} }
} }
async fn notify(&self, changesets: Vec<GridBlockChangeset>) { async fn notify(&self, changesets: Vec<GridBlockChangesetPB>) {
for changeset in changesets { for changeset in changesets {
send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridBlock) send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridBlock)
.payload(changeset) .payload(changeset)
@ -213,7 +213,7 @@ fn filter_cell(
FieldType::SingleSelect => filter_cache.select_option_filter.get(&filter_id).and_then(|filter| { FieldType::SingleSelect => filter_cache.select_option_filter.get(&filter_id).and_then(|filter| {
Some( Some(
field_rev field_rev
.get_type_option_entry::<SingleSelectTypeOption>(field_type_rev)? .get_type_option_entry::<SingleSelectTypeOptionPB>(field_type_rev)?
.apply_filter(any_cell_data, filter.value()) .apply_filter(any_cell_data, filter.value())
.ok(), .ok(),
) )

View File

@ -2,7 +2,7 @@
use crate::entities::{GridSelectOptionFilter, SelectOptionCondition}; use crate::entities::{GridSelectOptionFilter, SelectOptionCondition};
use crate::services::cell::{AnyCellData, CellFilterOperation}; use crate::services::cell::{AnyCellData, CellFilterOperation};
use crate::services::field::{MultiSelectTypeOption, SingleSelectTypeOption}; use crate::services::field::{MultiSelectTypeOption, SingleSelectTypeOptionPB};
use crate::services::field::{SelectOptionOperation, SelectedSelectOptions}; use crate::services::field::{SelectOptionOperation, SelectedSelectOptions};
use flowy_error::FlowyResult; use flowy_error::FlowyResult;
@ -50,7 +50,7 @@ impl CellFilterOperation<GridSelectOptionFilter> for MultiSelectTypeOption {
} }
} }
impl CellFilterOperation<GridSelectOptionFilter> for SingleSelectTypeOption { impl CellFilterOperation<GridSelectOptionFilter> for SingleSelectTypeOptionPB {
fn apply_filter(&self, any_cell_data: AnyCellData, filter: &GridSelectOptionFilter) -> FlowyResult<bool> { fn apply_filter(&self, any_cell_data: AnyCellData, filter: &GridSelectOptionFilter) -> FlowyResult<bool> {
if !any_cell_data.is_single_select() { if !any_cell_data.is_single_select() {
return Ok(true); return Ok(true);
@ -64,13 +64,13 @@ impl CellFilterOperation<GridSelectOptionFilter> for SingleSelectTypeOption {
mod tests { mod tests {
#![allow(clippy::all)] #![allow(clippy::all)]
use crate::entities::{GridSelectOptionFilter, SelectOptionCondition}; use crate::entities::{GridSelectOptionFilter, SelectOptionCondition};
use crate::services::field::selection_type_option::{SelectOption, SelectedSelectOptions}; use crate::services::field::selection_type_option::{SelectOptionPB, SelectedSelectOptions};
#[test] #[test]
fn select_option_filter_is_test() { fn select_option_filter_is_test() {
let option_1 = SelectOption::new("A"); let option_1 = SelectOptionPB::new("A");
let option_2 = SelectOption::new("B"); let option_2 = SelectOptionPB::new("B");
let option_3 = SelectOption::new("C"); let option_3 = SelectOptionPB::new("C");
let filter_1 = GridSelectOptionFilter { let filter_1 = GridSelectOptionFilter {
condition: SelectOptionCondition::OptionIs, condition: SelectOptionCondition::OptionIs,

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::CellIdentifier; use crate::entities::CellIdentifierParams;
use crate::entities::*; use crate::entities::*;
use crate::manager::{GridTaskSchedulerRwLock, GridUser}; use crate::manager::{GridTaskSchedulerRwLock, GridUser};
use crate::services::block_manager::GridBlockManager; use crate::services::block_manager::GridBlockManager;
@ -188,8 +188,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 = FieldOrder::from(field_id); let field_order = GridFieldIdPB::from(field_id);
let notified_changeset = GridFieldChangeset::delete(&self.grid_id, vec![field_order]); let notified_changeset = GridFieldChangesetPB::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(())
} }
@ -268,13 +268,13 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<RowInfo> { pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<GridRowPB> {
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(&field_revs).build(&block_id); let row_rev = RowRevisionBuilder::new(&field_revs).build(&block_id);
let row_order = RowInfo::from(&row_rev); let row_order = GridRowPB::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?;
@ -285,12 +285,12 @@ impl GridRevisionEditor {
Ok(row_order) Ok(row_order)
} }
pub async fn insert_rows(&self, row_revs: Vec<RowRevision>) -> FlowyResult<Vec<RowInfo>> { pub async fn insert_rows(&self, row_revs: Vec<RowRevision>) -> FlowyResult<Vec<GridRowPB>> {
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(RowInfo::from(&row_rev)); row_orders.push(GridRowPB::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)
@ -307,7 +307,7 @@ impl GridRevisionEditor {
self.block_manager.update_row(changeset, make_row_from_row_rev).await self.block_manager.update_row(changeset, make_row_from_row_rev).await
} }
pub async fn get_rows(&self, block_id: &str) -> FlowyResult<RepeatedRow> { pub async fn get_rows(&self, block_id: &str) -> FlowyResult<RepeatedRowPB> {
let block_ids = vec![block_id.to_owned()]; let block_ids = vec![block_id.to_owned()];
let mut grid_block_snapshot = self.grid_block_snapshots(Some(block_ids)).await?; let mut grid_block_snapshot = self.grid_block_snapshots(Some(block_ids)).await?;
@ -339,12 +339,12 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
pub async fn get_cell(&self, params: &CellIdentifier) -> Option<Cell> { pub async fn get_cell(&self, params: &CellIdentifierParams) -> Option<GridCellPB> {
let cell_bytes = self.get_cell_bytes(params).await?; let cell_bytes = self.get_cell_bytes(params).await?;
Some(Cell::new(&params.field_id, cell_bytes.to_vec())) Some(GridCellPB::new(&params.field_id, cell_bytes.to_vec()))
} }
pub async fn get_cell_bytes(&self, params: &CellIdentifier) -> Option<CellBytes> { pub async fn get_cell_bytes(&self, params: &CellIdentifierParams) -> Option<CellBytes> {
let field_rev = self.get_field_rev(&params.field_id).await?; let field_rev = self.get_field_rev(&params.field_id).await?;
let row_rev = self.block_manager.get_row_rev(&params.row_id).await.ok()??; let row_rev = self.block_manager.get_row_rev(&params.row_id).await.ok()??;
@ -364,12 +364,12 @@ impl GridRevisionEditor {
} }
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
pub async fn update_cell(&self, cell_changeset: CellChangeset) -> FlowyResult<()> { pub async fn update_cell(&self, cell_changeset: CellChangesetPB) -> FlowyResult<()> {
if cell_changeset.content.as_ref().is_none() { if cell_changeset.content.as_ref().is_none() {
return Ok(()); return Ok(());
} }
let CellChangeset { let CellChangesetPB {
grid_id, grid_id,
row_id, row_id,
field_id, field_id,
@ -387,7 +387,7 @@ impl GridRevisionEditor {
let cell_rev = self.get_cell_rev(&row_id, &field_id).await?; let cell_rev = self.get_cell_rev(&row_id, &field_id).await?;
// Update the changeset.data property with the return value. // Update the changeset.data property with the return value.
content = Some(apply_cell_data_changeset(content.unwrap(), cell_rev, field_rev)?); content = Some(apply_cell_data_changeset(content.unwrap(), cell_rev, field_rev)?);
let cell_changeset = CellChangeset { let cell_changeset = CellChangesetPB {
grid_id, grid_id,
row_id, row_id,
field_id, field_id,
@ -402,7 +402,7 @@ impl GridRevisionEditor {
} }
} }
pub async fn get_blocks(&self, block_ids: Option<Vec<String>>) -> FlowyResult<RepeatedGridBlock> { pub async fn get_blocks(&self, block_ids: Option<Vec<String>>) -> FlowyResult<RepeatedGridBlockPB> {
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)
} }
@ -412,7 +412,7 @@ impl GridRevisionEditor {
Ok(block_meta_revs) Ok(block_meta_revs)
} }
pub async fn delete_rows(&self, row_orders: Vec<RowInfo>) -> FlowyResult<()> { pub async fn delete_rows(&self, row_orders: Vec<GridRowPB>) -> 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?;
@ -420,31 +420,31 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
pub async fn get_grid_data(&self) -> FlowyResult<Grid> { pub async fn get_grid_data(&self) -> FlowyResult<GridPB> {
let pad_read_guard = self.grid_pad.read().await; let pad_read_guard = self.grid_pad.read().await;
let field_orders = pad_read_guard let field_orders = pad_read_guard
.get_field_revs(None)? .get_field_revs(None)?
.iter() .iter()
.map(FieldOrder::from) .map(GridFieldIdPB::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 = GridBlock { let block_order = GridBlockPB {
id: block_rev.block_id.clone(), id: block_rev.block_id.clone(),
row_infos: row_orders, rows: row_orders,
}; };
block_orders.push(block_order); block_orders.push(block_order);
} }
Ok(Grid { Ok(GridPB {
id: self.grid_id.clone(), id: self.grid_id.clone(),
field_orders, fields: field_orders,
blocks: block_orders, blocks: block_orders,
}) })
} }
pub async fn get_grid_setting(&self) -> FlowyResult<GridSetting> { pub async fn get_grid_setting(&self) -> FlowyResult<GridSettingPB> {
let read_guard = self.grid_pad.read().await; let read_guard = self.grid_pad.read().await;
let grid_setting_rev = read_guard.get_grid_setting_rev(); let grid_setting_rev = read_guard.get_grid_setting_rev();
let field_revs = read_guard.get_field_revs(None)?; let field_revs = read_guard.get_field_revs(None)?;
@ -495,11 +495,11 @@ impl GridRevisionEditor {
pub async fn move_item(&self, params: MoveItemParams) -> FlowyResult<()> { pub async fn move_item(&self, params: MoveItemParams) -> FlowyResult<()> {
match params.ty { match params.ty {
MoveItemType::MoveField => { MoveItemTypePB::MoveField => {
self.move_field(&params.item_id, params.from_index, params.to_index) self.move_field(&params.item_id, params.from_index, params.to_index)
.await .await
} }
MoveItemType::MoveRow => self.move_row(&params.item_id, params.from_index, params.to_index).await, MoveItemTypePB::MoveRow => self.move_row(&params.item_id, params.from_index, params.to_index).await,
} }
} }
@ -508,9 +508,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 = FieldOrder::from(field_id); let delete_field_order = GridFieldIdPB::from(field_id);
let insert_field = IndexField::from_field_rev(field_rev, index); let insert_field = IndexFieldPB::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangeset { let notified_changeset = GridFieldChangesetPB {
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],
@ -599,8 +599,8 @@ impl GridRevisionEditor {
#[tracing::instrument(level = "trace", skip_all, err)] #[tracing::instrument(level = "trace", skip_all, err)]
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 = IndexField::from_field_rev(field_rev, index); let index_field = IndexFieldPB::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangeset::insert(&self.grid_id, vec![index_field]); let notified_changeset = GridFieldChangesetPB::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(())
@ -615,8 +615,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 = Field::from(field_rev); let updated_field = GridFieldPB::from(field_rev);
let notified_changeset = GridFieldChangeset::update(&self.grid_id, vec![updated_field.clone()]); let notified_changeset = GridFieldChangesetPB::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)
@ -627,7 +627,7 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
async fn notify_did_update_grid(&self, changeset: GridFieldChangeset) -> FlowyResult<()> { async fn notify_did_update_grid(&self, changeset: GridFieldChangesetPB) -> 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::{GridBlock, RepeatedGridBlock, Row, RowInfo}; use crate::entities::{GridBlockPB, GridRowPB, RepeatedGridBlockPB};
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,15 +9,15 @@ 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<RowInfo>) -> Vec<GridBlock> { pub(crate) fn block_from_row_orders(row_orders: Vec<GridRowPB>) -> Vec<GridBlockPB> {
let mut map: HashMap<String, GridBlock> = HashMap::new(); let mut map: HashMap<String, GridBlockPB> = 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(|| GridBlock::new(&cloned_block_id, vec![])) .or_insert_with(|| GridBlockPB::new(&cloned_block_id, vec![]))
.row_infos .rows
.push(row_info); .push(row_info);
}); });
map.into_values().collect::<Vec<_>>() map.into_values().collect::<Vec<_>>()
@ -35,16 +35,17 @@ pub(crate) fn block_from_row_orders(row_orders: Vec<RowInfo>) -> Vec<GridBlock>
// Some((field_id, cell)) // Some((field_id, cell))
// } // }
pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<RowInfo> { pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<GridRowPB> {
row_revs.iter().map(RowInfo::from).collect::<Vec<_>>() row_revs.iter().map(GridRowPB::from).collect::<Vec<_>>()
} }
pub(crate) fn make_row_from_row_rev(row_rev: Arc<RowRevision>) -> Option<Row> { pub(crate) fn make_row_from_row_rev(row_rev: Arc<RowRevision>) -> Option<GridRowPB> {
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<Row> { pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<GridRowPB> {
let make_row = |row_rev: &Arc<RowRevision>| Row { let make_row = |row_rev: &Arc<RowRevision>| GridRowPB {
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,
}; };
@ -55,15 +56,15 @@ pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<Row>
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<RepeatedGridBlock> { ) -> FlowyResult<RepeatedGridBlockPB> {
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);
GridBlock::new(&snapshot.block_id, row_orders) GridBlockPB::new(&snapshot.block_id, row_orders)
}) })
.collect::<Vec<GridBlock>>() .collect::<Vec<GridBlockPB>>()
.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
@ -77,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(GridBlock::new(&block_id, row_orders)); grid_blocks.push(GridBlockPB::new(&block_id, row_orders));
} }
} }
} }

View File

@ -1,5 +1,5 @@
use crate::entities::{ use crate::entities::{
GridLayout, GridLayoutType, GridSetting, RepeatedGridFilter, RepeatedGridGroup, RepeatedGridSort, GridLayoutPB, GridLayoutType, GridSettingPB, RepeatedGridFilterPB, RepeatedGridGroupPB, RepeatedGridSortPB,
}; };
use flowy_grid_data_model::revision::{FieldRevision, GridSettingRevision}; use flowy_grid_data_model::revision::{FieldRevision, GridSettingRevision};
use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams}; use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams};
@ -40,7 +40,7 @@ impl GridSettingChangesetBuilder {
} }
} }
pub fn make_grid_setting(grid_setting_rev: &GridSettingRevision, field_revs: &[Arc<FieldRevision>]) -> GridSetting { pub fn make_grid_setting(grid_setting_rev: &GridSettingRevision, field_revs: &[Arc<FieldRevision>]) -> GridSettingPB {
let current_layout_type: GridLayoutType = grid_setting_rev.layout.clone().into(); let current_layout_type: GridLayoutType = grid_setting_rev.layout.clone().into();
let filters_by_field_id = grid_setting_rev let filters_by_field_id = grid_setting_rev
.get_all_filter(field_revs) .get_all_filter(field_revs)
@ -48,7 +48,7 @@ pub fn make_grid_setting(grid_setting_rev: &GridSettingRevision, field_revs: &[A
filters_by_field_id filters_by_field_id
.into_iter() .into_iter()
.map(|(k, v)| (k, v.into())) .map(|(k, v)| (k, v.into()))
.collect::<HashMap<String, RepeatedGridFilter>>() .collect::<HashMap<String, RepeatedGridFilterPB>>()
}) })
.unwrap_or_default(); .unwrap_or_default();
let groups_by_field_id = grid_setting_rev let groups_by_field_id = grid_setting_rev
@ -57,7 +57,7 @@ pub fn make_grid_setting(grid_setting_rev: &GridSettingRevision, field_revs: &[A
groups_by_field_id groups_by_field_id
.into_iter() .into_iter()
.map(|(k, v)| (k, v.into())) .map(|(k, v)| (k, v.into()))
.collect::<HashMap<String, RepeatedGridGroup>>() .collect::<HashMap<String, RepeatedGridGroupPB>>()
}) })
.unwrap_or_default(); .unwrap_or_default();
let sorts_by_field_id = grid_setting_rev let sorts_by_field_id = grid_setting_rev
@ -66,12 +66,12 @@ pub fn make_grid_setting(grid_setting_rev: &GridSettingRevision, field_revs: &[A
sorts_by_field_id sorts_by_field_id
.into_iter() .into_iter()
.map(|(k, v)| (k, v.into())) .map(|(k, v)| (k, v.into()))
.collect::<HashMap<String, RepeatedGridSort>>() .collect::<HashMap<String, RepeatedGridSortPB>>()
}) })
.unwrap_or_default(); .unwrap_or_default();
GridSetting { GridSettingPB {
layouts: GridLayout::all(), layouts: GridLayoutPB::all(),
current_layout_type, current_layout_type,
filters_by_field_id, filters_by_field_id,
groups_by_field_id, groups_by_field_id,

View File

@ -1,7 +1,8 @@
use crate::grid::block_test::script::RowScript::{AssertCell, CreateRow}; 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::{CellIdentifier, FieldType, RowInfo};
use flowy_grid::entities::{CellIdentifierParams, FieldType, GridRowPB};
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,
@ -96,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<RowInfo>>(); .collect::<Vec<GridRowPB>>();
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;
@ -108,7 +109,7 @@ impl GridRowTest {
field_type, field_type,
expected, expected,
} => { } => {
let id = CellIdentifier { let id = CellIdentifierParams {
grid_id: self.grid_id.clone(), grid_id: self.grid_id.clone(),
field_id, field_id,
row_id, row_id,
@ -153,7 +154,7 @@ impl GridRowTest {
} }
} }
async fn compare_cell_content(&self, cell_id: CellIdentifier, field_type: FieldType, expected: String) { async fn compare_cell_content(&self, cell_id: CellIdentifierParams, field_type: FieldType, expected: String) {
match field_type { match field_type {
FieldType::RichText => { FieldType::RichText => {
let cell_data = self let cell_data = self
@ -288,7 +289,7 @@ impl<'a> CreateRowScriptBuilder<'a> {
pub fn insert_single_select_cell<F>(&mut self, f: F, expected: &str) pub fn insert_single_select_cell<F>(&mut self, f: F, expected: &str)
where where
F: Fn(Vec<SelectOption>) -> SelectOption, F: Fn(Vec<SelectOptionPB>) -> SelectOptionPB,
{ {
let field_id = self.builder.insert_single_select_cell(f); let field_id = self.builder.insert_single_select_cell(f);
self.output_by_field_type.insert( self.output_by_field_type.insert(
@ -302,7 +303,7 @@ impl<'a> CreateRowScriptBuilder<'a> {
pub fn insert_multi_select_cell<F>(&mut self, f: F, expected: &str) pub fn insert_multi_select_cell<F>(&mut self, f: F, expected: &str)
where where
F: Fn(Vec<SelectOption>) -> Vec<SelectOption>, F: Fn(Vec<SelectOptionPB>) -> Vec<SelectOptionPB>,
{ {
let field_id = self.builder.insert_multi_select_cell(f); let field_id = self.builder.insert_multi_select_cell(f);
self.output_by_field_type.insert( self.output_by_field_type.insert(

View File

@ -2,7 +2,7 @@ use flowy_grid::entities::FieldType;
use std::sync::Arc; use std::sync::Arc;
use flowy_grid::services::field::{ use flowy_grid::services::field::{
DateCellChangeset, MultiSelectTypeOption, SelectOption, SingleSelectTypeOption, SELECTION_IDS_SEPARATOR, DateCellChangesetPB, MultiSelectTypeOption, SelectOptionPB, SingleSelectTypeOptionPB, SELECTION_IDS_SEPARATOR,
}; };
use flowy_grid::services::row::RowRevisionBuilder; use flowy_grid::services::row::RowRevisionBuilder;
use flowy_grid_data_model::revision::{FieldRevision, RowRevision}; use flowy_grid_data_model::revision::{FieldRevision, RowRevision};
@ -44,7 +44,7 @@ impl<'a> GridRowTestBuilder<'a> {
} }
pub fn insert_date_cell(&mut self, data: &str) -> String { pub fn insert_date_cell(&mut self, data: &str) -> String {
let value = serde_json::to_string(&DateCellChangeset { let value = serde_json::to_string(&DateCellChangesetPB {
date: Some(data.to_string()), date: Some(data.to_string()),
time: None, time: None,
}) })
@ -71,10 +71,10 @@ impl<'a> GridRowTestBuilder<'a> {
pub fn insert_single_select_cell<F>(&mut self, f: F) -> String pub fn insert_single_select_cell<F>(&mut self, f: F) -> String
where where
F: Fn(Vec<SelectOption>) -> SelectOption, F: Fn(Vec<SelectOptionPB>) -> SelectOptionPB,
{ {
let single_select_field = self.field_rev_with_type(&FieldType::SingleSelect); let single_select_field = self.field_rev_with_type(&FieldType::SingleSelect);
let type_option = SingleSelectTypeOption::from(&single_select_field); let type_option = SingleSelectTypeOptionPB::from(&single_select_field);
let option = f(type_option.options); let option = f(type_option.options);
self.inner_builder self.inner_builder
.insert_select_option_cell(&single_select_field.id, option.id) .insert_select_option_cell(&single_select_field.id, option.id)
@ -85,7 +85,7 @@ impl<'a> GridRowTestBuilder<'a> {
pub fn insert_multi_select_cell<F>(&mut self, f: F) -> String pub fn insert_multi_select_cell<F>(&mut self, f: F) -> String
where where
F: Fn(Vec<SelectOption>) -> Vec<SelectOption>, F: Fn(Vec<SelectOptionPB>) -> Vec<SelectOptionPB>,
{ {
let multi_select_field = self.field_rev_with_type(&FieldType::MultiSelect); let multi_select_field = self.field_rev_with_type(&FieldType::MultiSelect);
let type_option = MultiSelectTypeOption::from(&multi_select_field); let type_option = MultiSelectTypeOption::from(&multi_select_field);

View File

@ -1,8 +1,8 @@
use crate::grid::grid_editor::GridEditorTest; use crate::grid::grid_editor::GridEditorTest;
use flowy_grid::entities::CellChangeset; use flowy_grid::entities::CellChangesetPB;
pub enum CellScript { pub enum CellScript {
UpdateCell { changeset: CellChangeset, is_err: bool }, UpdateCell { changeset: CellChangesetPB, is_err: bool },
} }
pub struct GridCellTest { pub struct GridCellTest {

View File

@ -1,9 +1,9 @@
use crate::grid::cell_test::script::CellScript::*; use crate::grid::cell_test::script::CellScript::*;
use crate::grid::cell_test::script::GridCellTest; use crate::grid::cell_test::script::GridCellTest;
use crate::grid::field_test::util::make_date_cell_string; use crate::grid::field_test::util::make_date_cell_string;
use flowy_grid::entities::{CellChangeset, FieldType}; use flowy_grid::entities::{CellChangesetPB, FieldType};
use flowy_grid::services::field::selection_type_option::SelectOptionCellChangeset; use flowy_grid::services::field::selection_type_option::SelectOptionCellChangeset;
use flowy_grid::services::field::{MultiSelectTypeOption, SingleSelectTypeOption}; use flowy_grid::services::field::{MultiSelectTypeOption, SingleSelectTypeOptionPB};
#[tokio::test] #[tokio::test]
async fn grid_cell_update() { async fn grid_cell_update() {
@ -24,7 +24,7 @@ async fn grid_cell_update() {
FieldType::Number => "123".to_string(), FieldType::Number => "123".to_string(),
FieldType::DateTime => make_date_cell_string("123"), FieldType::DateTime => make_date_cell_string("123"),
FieldType::SingleSelect => { FieldType::SingleSelect => {
let type_option = SingleSelectTypeOption::from(field_rev); let type_option = SingleSelectTypeOptionPB::from(field_rev);
SelectOptionCellChangeset::from_insert(&type_option.options.first().unwrap().id).to_str() SelectOptionCellChangeset::from_insert(&type_option.options.first().unwrap().id).to_str()
} }
FieldType::MultiSelect => { FieldType::MultiSelect => {
@ -36,7 +36,7 @@ async fn grid_cell_update() {
}; };
scripts.push(UpdateCell { scripts.push(UpdateCell {
changeset: CellChangeset { changeset: CellChangesetPB {
grid_id: block_id.to_string(), grid_id: block_id.to_string(),
row_id: row_rev.id.clone(), row_id: row_rev.id.clone(),
field_id: field_rev.id.clone(), field_id: field_rev.id.clone(),

View File

@ -1,8 +1,8 @@
use crate::grid::field_test::script::FieldScript::*; use crate::grid::field_test::script::FieldScript::*;
use crate::grid::field_test::script::GridFieldTest; use crate::grid::field_test::script::GridFieldTest;
use crate::grid::field_test::util::*; use crate::grid::field_test::util::*;
use flowy_grid::services::field::selection_type_option::SelectOption; use flowy_grid::services::field::selection_type_option::SelectOptionPB;
use flowy_grid::services::field::SingleSelectTypeOption; use flowy_grid::services::field::SingleSelectTypeOptionPB;
use flowy_grid_data_model::revision::TypeOptionDataEntry; use flowy_grid_data_model::revision::TypeOptionDataEntry;
use flowy_sync::entities::grid::FieldChangesetParams; use flowy_sync::entities::grid::FieldChangesetParams;
@ -71,8 +71,8 @@ async fn grid_update_field() {
let mut test = GridFieldTest::new().await; let mut test = GridFieldTest::new().await;
let (params, single_select_field) = create_single_select_field(&test.grid_id()); let (params, single_select_field) = create_single_select_field(&test.grid_id());
let mut single_select_type_option = SingleSelectTypeOption::from(&single_select_field); let mut single_select_type_option = SingleSelectTypeOptionPB::from(&single_select_field);
single_select_type_option.options.push(SelectOption::new("Unknown")); single_select_type_option.options.push(SelectOptionPB::new("Unknown"));
let changeset = FieldChangesetParams { let changeset = FieldChangesetParams {
field_id: single_select_field.id.clone(), field_id: single_select_field.id.clone(),
grid_id: test.grid_id(), grid_id: test.grid_id(),

View File

@ -1,5 +1,5 @@
use flowy_grid::entities::*; use flowy_grid::entities::*;
use flowy_grid::services::field::selection_type_option::SelectOption; use flowy_grid::services::field::selection_type_option::SelectOptionPB;
use flowy_grid::services::field::*; use flowy_grid::services::field::*;
use flowy_grid_data_model::revision::*; use flowy_grid_data_model::revision::*;
@ -17,7 +17,7 @@ pub fn create_text_field(grid_id: &str) -> (InsertFieldParams, FieldRevision) {
.protobuf_bytes() .protobuf_bytes()
.to_vec(); .to_vec();
let field = Field { let field = GridFieldPB {
id: field_rev.id, id: field_rev.id,
name: field_rev.name, name: field_rev.name,
desc: field_rev.desc, desc: field_rev.desc,
@ -39,18 +39,18 @@ pub fn create_text_field(grid_id: &str) -> (InsertFieldParams, FieldRevision) {
pub fn create_single_select_field(grid_id: &str) -> (InsertFieldParams, FieldRevision) { pub fn create_single_select_field(grid_id: &str) -> (InsertFieldParams, FieldRevision) {
let single_select = SingleSelectTypeOptionBuilder::default() let single_select = SingleSelectTypeOptionBuilder::default()
.option(SelectOption::new("Done")) .option(SelectOptionPB::new("Done"))
.option(SelectOption::new("Progress")); .option(SelectOptionPB::new("Progress"));
let field_rev = FieldBuilder::new(single_select).name("Name").visibility(true).build(); let field_rev = FieldBuilder::new(single_select).name("Name").visibility(true).build();
let cloned_field_rev = field_rev.clone(); let cloned_field_rev = field_rev.clone();
let type_option_data = field_rev let type_option_data = field_rev
.get_type_option_entry::<SingleSelectTypeOption>(field_rev.field_type_rev) .get_type_option_entry::<SingleSelectTypeOptionPB>(field_rev.field_type_rev)
.unwrap() .unwrap()
.protobuf_bytes() .protobuf_bytes()
.to_vec(); .to_vec();
let field = Field { let field = GridFieldPB {
id: field_rev.id, id: field_rev.id,
name: field_rev.name, name: field_rev.name,
desc: field_rev.desc, desc: field_rev.desc,
@ -73,7 +73,7 @@ pub fn create_single_select_field(grid_id: &str) -> (InsertFieldParams, FieldRev
// The grid will contains all existing field types and there are three empty rows in this grid. // The grid will contains all existing field types and there are three empty rows in this grid.
pub fn make_date_cell_string(s: &str) -> String { pub fn make_date_cell_string(s: &str) -> String {
serde_json::to_string(&DateCellChangeset { serde_json::to_string(&DateCellChangesetPB {
date: Some(s.to_string()), date: Some(s.to_string()),
time: None, time: None,
}) })

View File

@ -3,7 +3,7 @@
#![allow(dead_code)] #![allow(dead_code)]
#![allow(unused_imports)] #![allow(unused_imports)]
use flowy_grid::entities::{CreateGridFilterPayload, GridLayoutType, GridSetting}; use flowy_grid::entities::{CreateGridFilterPayloadPB, GridLayoutType, GridSettingPB};
use flowy_grid::services::setting::GridSettingChangesetBuilder; use flowy_grid::services::setting::GridSettingChangesetBuilder;
use flowy_grid_data_model::revision::{FieldRevision, FieldTypeRevision}; use flowy_grid_data_model::revision::{FieldRevision, FieldTypeRevision};
use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams}; use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams};
@ -15,7 +15,7 @@ pub enum FilterScript {
params: GridSettingChangesetParams, params: GridSettingChangesetParams,
}, },
InsertGridTableFilter { InsertGridTableFilter {
payload: CreateGridFilterPayload, payload: CreateGridFilterPayloadPB,
}, },
AssertTableFilterCount { AssertTableFilterCount {
count: i32, count: i32,
@ -26,7 +26,7 @@ pub enum FilterScript {
}, },
#[allow(dead_code)] #[allow(dead_code)]
AssertGridSetting { AssertGridSetting {
expected_setting: GridSetting, expected_setting: GridSettingPB,
}, },
} }

View File

@ -1,13 +1,13 @@
use crate::grid::filter_test::script::FilterScript::*; use crate::grid::filter_test::script::FilterScript::*;
use crate::grid::filter_test::script::*; use crate::grid::filter_test::script::*;
use flowy_grid::entities::{CreateGridFilterPayload, FieldType, TextFilterCondition}; use flowy_grid::entities::{CreateGridFilterPayloadPB, FieldType, TextFilterCondition};
use flowy_grid_data_model::revision::FieldRevision; use flowy_grid_data_model::revision::FieldRevision;
#[tokio::test] #[tokio::test]
async fn grid_filter_create_test() { async fn grid_filter_create_test() {
let mut test = GridFilterTest::new().await; let mut test = GridFilterTest::new().await;
let field_rev = test.get_field_rev(FieldType::RichText); let field_rev = test.get_field_rev(FieldType::RichText);
let payload = CreateGridFilterPayload::new(field_rev, TextFilterCondition::TextIsEmpty, Some("abc".to_owned())); let payload = CreateGridFilterPayloadPB::new(field_rev, TextFilterCondition::TextIsEmpty, Some("abc".to_owned()));
let scripts = vec![InsertGridTableFilter { payload }, AssertTableFilterCount { count: 1 }]; let scripts = vec![InsertGridTableFilter { payload }, AssertTableFilterCount { count: 1 }];
test.run_scripts(scripts).await; test.run_scripts(scripts).await;
} }
@ -19,7 +19,7 @@ async fn grid_filter_invalid_condition_panic_test() {
let field_rev = test.get_field_rev(FieldType::RichText).clone(); let field_rev = test.get_field_rev(FieldType::RichText).clone();
// 100 is not a valid condition, so this test should be panic. // 100 is not a valid condition, so this test should be panic.
let payload = CreateGridFilterPayload::new(&field_rev, 100, Some("".to_owned())); let payload = CreateGridFilterPayloadPB::new(&field_rev, 100, Some("".to_owned()));
let scripts = vec![InsertGridTableFilter { payload }]; let scripts = vec![InsertGridTableFilter { payload }];
test.run_scripts(scripts).await; test.run_scripts(scripts).await;
} }
@ -46,6 +46,6 @@ async fn grid_filter_delete_test() {
#[tokio::test] #[tokio::test]
async fn grid_filter_get_rows_test() {} async fn grid_filter_get_rows_test() {}
fn create_filter(field_rev: &FieldRevision, condition: TextFilterCondition, s: &str) -> CreateGridFilterPayload { fn create_filter(field_rev: &FieldRevision, condition: TextFilterCondition, s: &str) -> CreateGridFilterPayloadPB {
CreateGridFilterPayload::new(field_rev, condition, Some(s.to_owned())) CreateGridFilterPayloadPB::new(field_rev, condition, Some(s.to_owned()))
} }

View File

@ -4,7 +4,7 @@
use crate::grid::block_test::util::GridRowTestBuilder; use crate::grid::block_test::util::GridRowTestBuilder;
use bytes::Bytes; use bytes::Bytes;
use flowy_grid::entities::*; use flowy_grid::entities::*;
use flowy_grid::services::field::SelectOption; use flowy_grid::services::field::SelectOptionPB;
use flowy_grid::services::field::*; use flowy_grid::services::field::*;
use flowy_grid::services::grid_editor::{GridPadBuilder, GridRevisionEditor}; use flowy_grid::services::grid_editor::{GridPadBuilder, GridRevisionEditor};
use flowy_grid::services::row::{CreateRowRevisionPayload, RowRevisionBuilder}; use flowy_grid::services::row::{CreateRowRevisionPayload, RowRevisionBuilder};
@ -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, RowInfo>, pub row_order_by_row_id: HashMap<String, GridRowPB>,
} }
impl GridEditorTest { impl GridEditorTest {
@ -138,18 +138,18 @@ fn make_test_grid() -> BuildGridContext {
FieldType::SingleSelect => { FieldType::SingleSelect => {
// Single Select // Single Select
let single_select = SingleSelectTypeOptionBuilder::default() let single_select = SingleSelectTypeOptionBuilder::default()
.option(SelectOption::new(COMPLETED)) .option(SelectOptionPB::new(COMPLETED))
.option(SelectOption::new(PLANNED)) .option(SelectOptionPB::new(PLANNED))
.option(SelectOption::new(PAUSED)); .option(SelectOptionPB::new(PAUSED));
let single_select_field = FieldBuilder::new(single_select).name("Status").visibility(true).build(); let single_select_field = FieldBuilder::new(single_select).name("Status").visibility(true).build();
grid_builder.add_field(single_select_field); grid_builder.add_field(single_select_field);
} }
FieldType::MultiSelect => { FieldType::MultiSelect => {
// MultiSelect // MultiSelect
let multi_select = MultiSelectTypeOptionBuilder::default() let multi_select = MultiSelectTypeOptionBuilder::default()
.option(SelectOption::new(GOOGLE)) .option(SelectOptionPB::new(GOOGLE))
.option(SelectOption::new(FACEBOOK)) .option(SelectOptionPB::new(FACEBOOK))
.option(SelectOption::new(TWITTER)); .option(SelectOptionPB::new(TWITTER));
let multi_select_field = FieldBuilder::new(multi_select) let multi_select_field = FieldBuilder::new(multi_select)
.name("Platform") .name("Platform")
.visibility(true) .visibility(true)