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';
// Grid
// GridPB
typedef GridNotificationCallback = void Function(GridNotification, Either<Uint8List, FlowyError>);
class GridNotificationParser extends NotificationParser<GridNotification, FlowyError> {

View File

@ -134,7 +134,7 @@ void _resolveDocDeps(GetIt getIt) {
}
void _resolveGridDeps(GetIt getIt) {
// Grid
// GridPB
getIt.registerFactoryParam<GridBloc, View, void>(
(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
class GridBlockCache {
final String gridId;
final GridBlock block;
final GridBlockPB block;
late GridRowCache _rowCache;
late GridBlockListener _listener;
List<GridRow> get rows => _rowCache.rows;
List<GridRowInfo> get rows => _rowCache.rows;
GridRowCache get rowCache => _rowCache;
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/dart_notification.pb.dart';
typedef GridBlockUpdateNotifierValue = Either<List<GridBlockChangeset>, FlowyError>;
typedef GridBlockUpdateNotifierValue = Either<List<GridBlockChangesetPB>, FlowyError>;
class GridBlockListener {
final String blockId;
@ -33,7 +33,7 @@ class GridBlockListener {
switch (ty) {
case GridNotification.DidUpdateGridBlock:
result.fold(
(payload) => _rowsUpdateNotifier?.value = left([GridBlockChangeset.fromBuffer(payload)]),
(payload) => _rowsUpdateNotifier?.value = left([GridBlockChangesetPB.fromBuffer(payload)]),
(error) => _rowsUpdateNotifier?.value = right(error),
);
break;

View File

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

View File

@ -40,7 +40,7 @@ class DateCellDataPersistence implements IGridCellDataPersistence<CalendarData>
@override
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();
payload.date = date;
@ -58,8 +58,8 @@ class DateCellDataPersistence implements IGridCellDataPersistence<CalendarData>
}
}
CellIdentifierPayload _makeCellIdPayload(GridCellIdentifier cellId) {
return CellIdentifierPayload.create()
GridCellIdentifierPayloadPB _makeCellIdPayload(GridCellIdentifier cellId) {
return GridCellIdentifierPayloadPB.create()
..gridId = cellId.gridId
..fieldId = cellId.fieldId
..rowId = cellId.rowId;

View File

@ -4,11 +4,11 @@ import 'package:flutter/foundation.dart';
import 'cell_service.dart';
abstract class GridFieldChangedNotifier {
void onFieldChanged(void Function(Field) callback);
void onFieldChanged(void Function(GridFieldPB) callback);
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.
class GridCellFieldNotifier {
/// fieldId: {objectId: callback}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -54,7 +54,7 @@ class URLCellEditorBloc extends Bloc<URLCellEditorEvent, URLCellEditorState> {
@freezed
class URLCellEditorEvent with _$URLCellEditorEvent {
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;
}

View File

@ -10,8 +10,8 @@ part 'field_action_sheet_bloc.freezed.dart';
class FieldActionSheetBloc extends Bloc<FieldActionSheetEvent, FieldActionSheetState> {
final FieldService fieldService;
FieldActionSheetBloc({required Field field, required this.fieldService})
: super(FieldActionSheetState.initial(FieldTypeOptionData.create()..field_2 = field)) {
FieldActionSheetBloc({required GridFieldPB field, required this.fieldService})
: super(FieldActionSheetState.initial(FieldTypeOptionDataPB.create()..field_2 = field)) {
on<FieldActionSheetEvent>(
(event, emit) async {
await event.map(
@ -67,12 +67,12 @@ class FieldActionSheetEvent with _$FieldActionSheetEvent {
@freezed
class FieldActionSheetState with _$FieldActionSheetState {
const factory FieldActionSheetState({
required FieldTypeOptionData fieldTypeOptionData,
required FieldTypeOptionDataPB fieldTypeOptionData,
required String errorText,
required String fieldName,
}) = _FieldActionSheetState;
factory FieldActionSheetState.initial(FieldTypeOptionData data) => FieldActionSheetState(
factory FieldActionSheetState.initial(FieldTypeOptionDataPB data) => FieldActionSheetState(
fieldTypeOptionData: data,
errorText: '',
fieldName: data.field_2.name,

View File

@ -62,7 +62,7 @@ class FieldCellBloc extends Bloc<FieldCellEvent, FieldCellState> {
@freezed
class FieldCellEvent with _$FieldCellEvent {
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.endUpdateWidth() = _EndUpdateWidth;
}
@ -71,7 +71,7 @@ class FieldCellEvent with _$FieldCellEvent {
class FieldCellState with _$FieldCellState {
const factory FieldCellState({
required String gridId,
required Field field,
required GridFieldPB field,
required double width,
}) = _FieldCellState;

View File

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

View File

@ -7,7 +7,7 @@ import 'dart:async';
import 'dart:typed_data';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
typedef UpdateFieldNotifiedValue = Either<Field, FlowyError>;
typedef UpdateFieldNotifiedValue = Either<GridFieldPB, FlowyError>;
class SingleFieldListener {
final String fieldId;
@ -31,7 +31,7 @@ class SingleFieldListener {
switch (ty) {
case GridNotification.DidUpdateField:
result.fold(
(payload) => _updateFieldNotifier?.value = left(Field.fromBuffer(payload)),
(payload) => _updateFieldNotifier?.value = left(GridFieldPB.fromBuffer(payload)),
(error) => _updateFieldNotifier?.value = right(error),
);
break;

View File

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

View File

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

View File

@ -7,7 +7,7 @@ import 'dart:async';
import 'dart:typed_data';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
typedef UpdateFieldNotifiedValue = Either<GridFieldChangeset, FlowyError>;
typedef UpdateFieldNotifiedValue = Either<GridFieldChangesetPB, FlowyError>;
class GridFieldsListener {
final String gridId;
@ -27,7 +27,7 @@ class GridFieldsListener {
switch (ty) {
case GridNotification.DidUpdateGridField:
result.fold(
(payload) => updateFieldsNotifier?.value = left(GridFieldChangeset.fromBuffer(payload)),
(payload) => updateFieldsNotifier?.value = left(GridFieldChangesetPB.fromBuffer(payload)),
(error) => updateFieldsNotifier?.value = right(error),
);
break;

View File

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

View File

@ -21,8 +21,8 @@ class MultiSelectTypeOptionContext extends TypeOptionWidgetContext<MultiSelectTy
super(dataParser: dataBuilder, dataController: dataController);
@override
List<SelectOption> Function(SelectOption) get deleteOption {
return (SelectOption option) {
List<SelectOptionPB> Function(SelectOptionPB) get deleteOption {
return (SelectOptionPB option) {
typeOption.freeze();
typeOption = typeOption.rebuild((typeOption) {
final index = typeOption.options.indexWhere((element) => element.id == option.id);
@ -35,7 +35,7 @@ class MultiSelectTypeOptionContext extends TypeOptionWidgetContext<MultiSelectTy
}
@override
Future<List<SelectOption>> Function(String) get insertOption {
Future<List<SelectOptionPB>> Function(String) get insertOption {
return (String optionName) {
return service.newOption(name: optionName).then((result) {
return result.fold(
@ -57,8 +57,8 @@ class MultiSelectTypeOptionContext extends TypeOptionWidgetContext<MultiSelectTy
}
@override
List<SelectOption> Function(SelectOption) get udpateOption {
return (SelectOption option) {
List<SelectOptionPB> Function(SelectOptionPB) get udpateOption {
return (SelectOptionPB option) {
typeOption.freeze();
typeOption = typeOption.rebuild((typeOption) {
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';
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> {
final SelectOptionTypeOptionAction typeOptionAction;
SelectOptionTypeOptionBloc({
required List<SelectOption> options,
required List<SelectOptionPB> options,
required this.typeOptionAction,
}) : super(SelectOptionTypeOptionState.initial(options)) {
on<SelectOptionTypeOptionEvent>(
(event, emit) async {
await event.when(
createOption: (optionName) async {
final List<SelectOption> options = await typeOptionAction.insertOption(optionName);
final List<SelectOptionPB> options = await typeOptionAction.insertOption(optionName);
emit(state.copyWith(options: options));
},
addingOption: () {
@ -34,11 +34,11 @@ class SelectOptionTypeOptionBloc extends Bloc<SelectOptionTypeOptionEvent, Selec
emit(state.copyWith(isEditingOption: false, newOptionName: none()));
},
updateOption: (option) {
final List<SelectOption> options = typeOptionAction.udpateOption(option);
final List<SelectOptionPB> options = typeOptionAction.udpateOption(option);
emit(state.copyWith(options: options));
},
deleteOption: (option) {
final List<SelectOption> options = typeOptionAction.deleteOption(option);
final List<SelectOptionPB> options = typeOptionAction.deleteOption(option);
emit(state.copyWith(options: options));
},
);
@ -57,19 +57,19 @@ class SelectOptionTypeOptionEvent with _$SelectOptionTypeOptionEvent {
const factory SelectOptionTypeOptionEvent.createOption(String optionName) = _CreateOption;
const factory SelectOptionTypeOptionEvent.addingOption() = _AddingOption;
const factory SelectOptionTypeOptionEvent.endAddingOption() = _EndAddingOption;
const factory SelectOptionTypeOptionEvent.updateOption(SelectOption option) = _UpdateOption;
const factory SelectOptionTypeOptionEvent.deleteOption(SelectOption option) = _DeleteOption;
const factory SelectOptionTypeOptionEvent.updateOption(SelectOptionPB option) = _UpdateOption;
const factory SelectOptionTypeOptionEvent.deleteOption(SelectOptionPB option) = _DeleteOption;
}
@freezed
class SelectOptionTypeOptionState with _$SelectOptionTypeOptionState {
const factory SelectOptionTypeOptionState({
required List<SelectOption> options,
required List<SelectOptionPB> options,
required bool isEditingOption,
required Option<String> newOptionName,
}) = _SelectOptionTyepOptionState;
factory SelectOptionTypeOptionState.initial(List<SelectOption> options) => SelectOptionTypeOptionState(
factory SelectOptionTypeOptionState.initial(List<SelectOptionPB> options) => SelectOptionTypeOptionState(
options: options,
isEditingOption: false,
newOptionName: none(),

View File

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

View File

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

View File

@ -22,8 +22,8 @@ class GridBloc extends Bloc<GridEvent, GridState> {
// key: the block id
final LinkedHashMap<String, GridBlockCache> _blocks;
List<GridRow> get rows {
final List<GridRow> rows = [];
List<GridRowInfo> get rowInfos {
final List<GridRowInfo> rows = [];
for (var block in _blocks.values) {
rows.addAll(block.rows);
}
@ -46,11 +46,11 @@ class GridBloc extends Bloc<GridEvent, GridState> {
createRow: () {
_gridService.createRow();
},
didReceiveRowUpdate: (rows, reason) {
emit(state.copyWith(rows: rows, reason: reason));
didReceiveRowUpdate: (newRowInfos, reason) {
emit(state.copyWith(rowInfos: newRowInfos, reason: reason));
},
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 {
final result = await _gridService.getFields(fieldOrders: grid.fieldOrders);
Future<void> _loadFields(GridPB grid, Emitter<GridState> emit) async {
final result = await _gridService.getFields(fieldIds: grid.fields);
return Future(
() => result.fold(
(fields) {
@ -103,7 +103,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
emit(state.copyWith(
grid: Some(grid),
fields: GridFieldEquatable(fieldCache.fields),
rows: rows,
rowInfos: rowInfos,
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) {
if (_blocks[block.id] != null) {
Log.warn("Intial duplicate block's cache: ${block.id}");
@ -127,7 +127,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
cache.addListener(
listenWhen: () => !isClosed,
onChangeReason: (reason) => add(GridEvent.didReceiveRowUpdate(rows, reason)),
onChangeReason: (reason) => add(GridEvent.didReceiveRowUpdate(rowInfos, reason)),
);
_blocks[block.id] = cache;
@ -139,24 +139,25 @@ class GridBloc extends Bloc<GridEvent, GridState> {
class GridEvent with _$GridEvent {
const factory GridEvent.initial() = InitialGrid;
const factory GridEvent.createRow() = _CreateRow;
const factory GridEvent.didReceiveRowUpdate(List<GridRow> rows, GridRowChangeReason listState) = _DidReceiveRowUpdate;
const factory GridEvent.didReceiveFieldUpdate(List<Field> fields) = _DidReceiveFieldUpdate;
const factory GridEvent.didReceiveRowUpdate(List<GridRowInfo> rows, GridRowChangeReason listState) =
_DidReceiveRowUpdate;
const factory GridEvent.didReceiveFieldUpdate(List<GridFieldPB> fields) = _DidReceiveFieldUpdate;
}
@freezed
class GridState with _$GridState {
const factory GridState({
required String gridId,
required Option<Grid> grid,
required Option<GridPB> grid,
required GridFieldEquatable fields,
required List<GridRow> rows,
required List<GridRowInfo> rowInfos,
required GridLoadingState loadingState,
required GridRowChangeReason reason,
}) = _GridState;
factory GridState.initial(String gridId) => GridState(
fields: const GridFieldEquatable([]),
rows: [],
rowInfos: [],
grid: none(),
gridId: gridId,
loadingState: const _Loading(),
@ -171,8 +172,8 @@ class GridLoadingState with _$GridLoadingState {
}
class GridFieldEquatable extends Equatable {
final List<Field> _fields;
const GridFieldEquatable(List<Field> fields) : _fields = fields;
final List<GridFieldPB> _fields;
const GridFieldEquatable(List<GridFieldPB> fields) : _fields = fields;
@override
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 {
final fields = List<Field>.from(state.fields);
final fields = List<GridFieldPB>.from(state.fields);
fields.insert(value.toIndex, fields.removeAt(value.fromIndex));
emit(state.copyWith(fields: fields));
@ -62,16 +62,16 @@ class GridHeaderBloc extends Bloc<GridHeaderEvent, GridHeaderState> {
@freezed
class GridHeaderEvent with _$GridHeaderEvent {
const factory GridHeaderEvent.initial() = _InitialHeader;
const factory GridHeaderEvent.didReceiveFieldUpdate(List<Field> fields) = _DidReceiveFieldUpdate;
const factory GridHeaderEvent.moveField(Field field, int fromIndex, int toIndex) = _MoveField;
const factory GridHeaderEvent.didReceiveFieldUpdate(List<GridFieldPB> fields) = _DidReceiveFieldUpdate;
const factory GridHeaderEvent.moveField(GridFieldPB field, int fromIndex, int toIndex) = _MoveField;
}
@freezed
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) {
// final List<Field> newFields = List.from(fields);
factory GridHeaderState.initial(List<GridFieldPB> fields) {
// final List<GridFieldPB> newFields = List.from(fields);
// newFields.retainWhere((field) => field.visibility);
return GridHeaderState(fields: fields);
}

View File

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

View File

@ -4,18 +4,18 @@ export 'row/row_service.dart';
export 'grid_service.dart';
export 'grid_header_bloc.dart';
// Field
// GridFieldPB
export 'field/field_service.dart';
export 'field/field_action_sheet_bloc.dart';
export 'field/field_editor_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/number_bloc.dart';
export 'field/type_option/single_select_type_option.dart';
// Cell
// GridCellPB
export 'cell/text_cell_bloc.dart';
export 'cell/number_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> {
final RowService _rowService;
RowActionSheetBloc({required GridRow rowData})
RowActionSheetBloc({required GridRowInfo rowData})
: _rowService = RowService(
gridId: rowData.gridId,
blockId: rowData.blockId,
@ -53,10 +53,10 @@ class RowActionSheetEvent with _$RowActionSheetEvent {
@freezed
class RowActionSheetState with _$RowActionSheetState {
const factory RowActionSheetState({
required GridRow rowData,
required GridRowInfo rowData,
}) = _RowActionSheetState;
factory RowActionSheetState.initial(GridRow rowData) => RowActionSheetState(
factory RowActionSheetState.initial(GridRowInfo rowData) => RowActionSheetState(
rowData: rowData,
);
}

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ part 'property_bloc.freezed.dart';
class GridPropertyBloc extends Bloc<GridPropertyEvent, GridPropertyState> {
final GridFieldCache _fieldCache;
Function(List<Field>)? _onFieldsFn;
Function(List<GridFieldPB>)? _onFieldsFn;
GridPropertyBloc({required String gridId, required GridFieldCache fieldCache})
: _fieldCache = fieldCache,
@ -62,7 +62,7 @@ class GridPropertyBloc extends Bloc<GridPropertyEvent, GridPropertyState> {
class GridPropertyEvent with _$GridPropertyEvent {
const factory GridPropertyEvent.initial() = _Initial;
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;
}
@ -70,10 +70,10 @@ class GridPropertyEvent with _$GridPropertyEvent {
class GridPropertyState with _$GridPropertyState {
const factory GridPropertyState({
required String gridId,
required List<Field> fields,
required List<GridFieldPB> fields,
}) = _GridPropertyState;
factory GridPropertyState.initial(String gridId, List<Field> fields) => GridPropertyState(
factory GridPropertyState.initial(String gridId, List<GridFieldPB> fields) => GridPropertyState(
gridId: gridId,
fields: fields,
);

View File

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

View File

@ -2,7 +2,7 @@ import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
import 'sizes.dart';
class GridLayout {
static double headerWidth(List<Field> fields) {
static double headerWidth(List<GridFieldPB> fields) {
if (fields.isEmpty) return 0;
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:flutter_bloc/flutter_bloc.dart';
extension SelectOptionColorExtension on SelectOptionColor {
extension SelectOptionColorExtension on SelectOptionColorPB {
Color make(BuildContext context) {
final theme = context.watch<AppTheme>();
switch (this) {
case SelectOptionColor.Purple:
case SelectOptionColorPB.Purple:
return theme.tint1;
case SelectOptionColor.Pink:
case SelectOptionColorPB.Pink:
return theme.tint2;
case SelectOptionColor.LightPink:
case SelectOptionColorPB.LightPink:
return theme.tint3;
case SelectOptionColor.Orange:
case SelectOptionColorPB.Orange:
return theme.tint4;
case SelectOptionColor.Yellow:
case SelectOptionColorPB.Yellow:
return theme.tint5;
case SelectOptionColor.Lime:
case SelectOptionColorPB.Lime:
return theme.tint6;
case SelectOptionColor.Green:
case SelectOptionColorPB.Green:
return theme.tint7;
case SelectOptionColor.Aqua:
case SelectOptionColorPB.Aqua:
return theme.tint8;
case SelectOptionColor.Blue:
case SelectOptionColorPB.Blue:
return theme.tint9;
default:
throw ArgumentError;
@ -36,23 +36,23 @@ extension SelectOptionColorExtension on SelectOptionColor {
String optionName() {
switch (this) {
case SelectOptionColor.Purple:
case SelectOptionColorPB.Purple:
return LocaleKeys.grid_selectOption_purpleColor.tr();
case SelectOptionColor.Pink:
case SelectOptionColorPB.Pink:
return LocaleKeys.grid_selectOption_pinkColor.tr();
case SelectOptionColor.LightPink:
case SelectOptionColorPB.LightPink:
return LocaleKeys.grid_selectOption_lightPinkColor.tr();
case SelectOptionColor.Orange:
case SelectOptionColorPB.Orange:
return LocaleKeys.grid_selectOption_orangeColor.tr();
case SelectOptionColor.Yellow:
case SelectOptionColorPB.Yellow:
return LocaleKeys.grid_selectOption_yellowColor.tr();
case SelectOptionColor.Lime:
case SelectOptionColorPB.Lime:
return LocaleKeys.grid_selectOption_limeColor.tr();
case SelectOptionColor.Green:
case SelectOptionColorPB.Green:
return LocaleKeys.grid_selectOption_greenColor.tr();
case SelectOptionColor.Aqua:
case SelectOptionColorPB.Aqua:
return LocaleKeys.grid_selectOption_aquaColor.tr();
case SelectOptionColor.Blue:
case SelectOptionColorPB.Blue:
return LocaleKeys.grid_selectOption_blueColor.tr();
default:
throw ArgumentError;
@ -75,7 +75,7 @@ class SelectOptionTag extends StatelessWidget {
factory SelectOptionTag.fromSelectOption({
required BuildContext context,
required SelectOption option,
required SelectOptionPB option,
VoidCallback? onSelected,
bool isSelected = false,
}) {
@ -107,8 +107,8 @@ class SelectOptionTag extends StatelessWidget {
class SelectOptionTagCell extends StatelessWidget {
final List<Widget> children;
final void Function(SelectOption) onSelected;
final SelectOption option;
final void Function(SelectOptionPB) onSelected;
final SelectOptionPB option;
const SelectOptionTagCell({
required this.option,
required this.onSelected,

View File

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

View File

@ -146,7 +146,7 @@ class _TextField extends StatelessWidget {
Widget build(BuildContext context) {
return BlocBuilder<SelectOptionCellEditorBloc, SelectOptionEditorState>(
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);
return SizedBox(
@ -216,7 +216,7 @@ class _CreateOptionCell extends StatelessWidget {
}
class _SelectOptionCell extends StatelessWidget {
final SelectOption option;
final SelectOptionPB option;
final bool isSelected;
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 TextEditingController _controller;
final TextfieldTagsController tagController;
final List<SelectOption> options;
final LinkedHashMap<String, SelectOption> selectedOptionMap;
final List<SelectOptionPB> options;
final LinkedHashMap<String, SelectOptionPB> selectedOptionMap;
final double distanceToText;

View File

@ -135,7 +135,7 @@ class _DragToExpandLine extends StatelessWidget {
class FieldCellButton extends StatelessWidget {
final VoidCallback onTap;
final Field field;
final GridFieldPB field;
const FieldCellButton({
required this.field,
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 'type_option/builder.dart';
typedef UpdateFieldCallback = void Function(Field, Uint8List);
typedef SwitchToFieldCallback = Future<Either<FieldTypeOptionData, FlowyError>> Function(
typedef UpdateFieldCallback = void Function(GridFieldPB, Uint8List);
typedef SwitchToFieldCallback = Future<Either<FieldTypeOptionDataPB, FlowyError>> Function(
String fieldId,
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>();
return SizedBox(
height: GridSize.typeOptionItemHeight,

View File

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

View File

@ -17,7 +17,7 @@ import 'builder.dart';
import 'select_option_editor.dart';
class SelectOptionTypeOptionWidget extends StatelessWidget {
final List<SelectOption> options;
final List<SelectOptionPB> options;
final VoidCallback beginEdit;
final TypeOptionOverlayDelegate overlayDelegate;
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(
option: option,
onSelected: (option) {
@ -154,8 +154,8 @@ class _OptionList extends StatelessWidget {
}
class _OptionCell extends StatelessWidget {
final SelectOption option;
final Function(SelectOption) onSelected;
final SelectOptionPB option;
final Function(SelectOptionPB) onSelected;
const _OptionCell({
required this.option,
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';
class SelectOptionTypeOptionEditor extends StatelessWidget {
final SelectOption option;
final SelectOptionPB option;
final VoidCallback onDeleted;
final Function(SelectOption) onUpdated;
final Function(SelectOptionPB) onUpdated;
const SelectOptionTypeOptionEditor({
required this.option,
required this.onDeleted,
@ -110,12 +110,12 @@ class _OptionNameTextField extends StatelessWidget {
}
class SelectOptionColorList extends StatelessWidget {
final SelectOptionColor selectedColor;
final SelectOptionColorPB selectedColor;
const SelectOptionColorList({required this.selectedColor, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final cells = SelectOptionColor.values.map((color) {
final cells = SelectOptionColorPB.values.map((color) {
return _SelectOptionColorCell(color: color, isSelected: selectedColor == color);
}).toList();
@ -152,7 +152,7 @@ class SelectOptionColorList extends StatelessWidget {
}
class _SelectOptionColorCell extends StatelessWidget {
final SelectOptionColor color;
final SelectOptionColorPB color;
final bool isSelected;
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';
class GridRowWidget extends StatefulWidget {
final GridRow rowData;
final GridRowInfo rowData;
final GridRowCache rowCache;
final GridCellBuilder cellBuilder;
@ -40,7 +40,7 @@ class _GridRowWidgetState extends State<GridRowWidget> {
@override
void initState() {
_rowBloc = RowBloc(
rowData: widget.rowData,
rowInfo: widget.rowData,
rowCache: widget.rowCache,
);
_rowBloc.add(const RowEvent.initial());
@ -53,7 +53,7 @@ class _GridRowWidgetState extends State<GridRowWidget> {
value: _rowBloc,
child: _RowEnterRegion(
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) {
return Row(
children: [
@ -80,7 +80,7 @@ class _GridRowWidgetState extends State<GridRowWidget> {
void _expandRow(BuildContext context) {
final page = RowDetailPage(
rowData: widget.rowData,
rowInfo: widget.rowData,
rowCache: widget.rowCache,
cellBuilder: widget.cellBuilder,
);
@ -148,7 +148,7 @@ class _DeleteRowButton extends StatelessWidget {
width: 20,
height: 30,
onPressed: () => GridRowActionSheet(
rowData: context.read<RowBloc>().state.rowData,
rowData: context.read<RowBloc>().state.rowInfo,
).show(context),
iconPadding: const EdgeInsets.all(3),
icon: svgWidget("editor/details"),

View File

@ -14,7 +14,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class GridRowActionSheet extends StatelessWidget {
final GridRow rowData;
final GridRowInfo rowData;
const GridRowActionSheet({required this.rowData, Key? key}) : super(key: key);
@override

View File

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

View File

@ -75,7 +75,7 @@ class GridPropertyList extends StatelessWidget with FlowyOverlayDelegate {
}
class _GridPropertyCell extends StatelessWidget {
final Field field;
final GridFieldPB field;
final String gridId;
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',
'Bowling',
'Cricket Game',
'Field Hockey',
'GridFieldPB Hockey',
'Ice Hockey',
'Lacrosse',
'Ping Pong',

View File

@ -5,38 +5,38 @@ use flowy_grid_data_model::revision::RowRevision;
use std::sync::Arc;
#[derive(Debug, Clone, Default, ProtoBuf)]
pub struct GridBlock {
pub struct GridBlockPB {
#[pb(index = 1)]
pub id: String,
#[pb(index = 2)]
pub row_infos: Vec<RowInfo>,
pub rows: Vec<GridRowPB>,
}
impl GridBlock {
pub fn new(block_id: &str, row_orders: Vec<RowInfo>) -> Self {
impl GridBlockPB {
pub fn new(block_id: &str, rows: Vec<GridRowPB>) -> Self {
Self {
id: block_id.to_owned(),
row_infos: row_orders,
rows,
}
}
}
#[derive(Debug, Default, Clone, ProtoBuf)]
pub struct RowInfo {
pub struct GridRowPB {
#[pb(index = 1)]
pub block_id: String,
#[pb(index = 2)]
pub row_id: String,
pub id: String,
#[pb(index = 3)]
pub height: i32,
}
impl RowInfo {
impl GridRowPB {
pub fn row_id(&self) -> &str {
&self.row_id
&self.id
}
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 {
Self {
block_id: rev.block_id.clone(),
row_id: rev.id.clone(),
id: rev.id.clone(),
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 {
Self {
block_id: rev.block_id.clone(),
row_id: rev.id.clone(),
id: rev.id.clone(),
height: rev.height,
}
}
}
#[derive(Debug, Default, ProtoBuf)]
pub struct Row {
#[pb(index = 1)]
pub id: String,
#[pb(index = 2)]
pub height: i32,
}
#[derive(Debug, Default, ProtoBuf)]
pub struct OptionalRow {
pub struct OptionalRowPB {
#[pb(index = 1, one_of)]
pub row: Option<Row>,
pub row: Option<GridRowPB>,
}
#[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedRow {
pub struct RepeatedRowPB {
#[pb(index = 1)]
pub items: Vec<Row>,
pub items: Vec<GridRowPB>,
}
impl std::convert::From<Vec<Row>> for RepeatedRow {
fn from(items: Vec<Row>) -> Self {
impl std::convert::From<Vec<GridRowPB>> for RepeatedRowPB {
fn from(items: Vec<GridRowPB>) -> Self {
Self { items }
}
}
#[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedGridBlock {
pub struct RepeatedGridBlockPB {
#[pb(index = 1)]
pub items: Vec<GridBlock>,
pub items: Vec<GridBlockPB>,
}
impl std::convert::From<Vec<GridBlock>> for RepeatedGridBlock {
fn from(items: Vec<GridBlock>) -> Self {
impl std::convert::From<Vec<GridBlockPB>> for RepeatedGridBlockPB {
fn from(items: Vec<GridBlockPB>) -> Self {
Self { items }
}
}
#[derive(Debug, Clone, Default, ProtoBuf)]
pub struct InsertedRow {
pub struct InsertedRowPB {
#[pb(index = 1)]
pub block_id: String,
@ -118,7 +109,7 @@ pub struct InsertedRow {
}
#[derive(Debug, Default, ProtoBuf)]
pub struct UpdatedRow {
pub struct UpdatedRowPB {
#[pb(index = 1)]
pub block_id: String,
@ -126,11 +117,11 @@ pub struct UpdatedRow {
pub row_id: String,
#[pb(index = 3)]
pub row: Row,
pub row: GridRowPB,
}
impl UpdatedRow {
pub fn new(row_rev: &RowRevision, row: Row) -> Self {
impl UpdatedRowPB {
pub fn new(row_rev: &RowRevision, row: GridRowPB) -> Self {
Self {
row_id: row_rev.id.clone(),
block_id: row_rev.block_id.clone(),
@ -139,10 +130,10 @@ impl UpdatedRow {
}
}
impl std::convert::From<RowInfo> for InsertedRow {
fn from(row_info: RowInfo) -> Self {
impl std::convert::From<GridRowPB> for InsertedRowPB {
fn from(row_info: GridRowPB) -> Self {
Self {
row_id: row_info.row_id,
row_id: row_info.id,
block_id: row_info.block_id,
height: row_info.height,
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 {
let row_order = RowInfo::from(row);
let row_order = GridRowPB::from(row);
Self::from(row_order)
}
}
#[derive(Debug, Default, ProtoBuf)]
pub struct GridBlockChangeset {
pub struct GridBlockChangesetPB {
#[pb(index = 1)]
pub block_id: String,
#[pb(index = 2)]
pub inserted_rows: Vec<InsertedRow>,
pub inserted_rows: Vec<InsertedRowPB>,
#[pb(index = 3)]
pub deleted_rows: Vec<String>,
#[pb(index = 4)]
pub updated_rows: Vec<UpdatedRow>,
pub updated_rows: Vec<UpdatedRowPB>,
#[pb(index = 5)]
pub visible_rows: Vec<String>,
@ -177,8 +168,8 @@ pub struct GridBlockChangeset {
#[pb(index = 6)]
pub hide_rows: Vec<String>,
}
impl GridBlockChangeset {
pub fn insert(block_id: &str, inserted_rows: Vec<InsertedRow>) -> Self {
impl GridBlockChangesetPB {
pub fn insert(block_id: &str, inserted_rows: Vec<InsertedRowPB>) -> Self {
Self {
block_id: block_id.to_owned(),
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 {
block_id: block_id.to_owned(),
updated_rows,
@ -204,7 +195,7 @@ impl GridBlockChangeset {
}
#[derive(ProtoBuf, Default)]
pub struct QueryGridBlocksPayload {
pub struct QueryGridBlocksPayloadPB {
#[pb(index = 1)]
pub grid_id: String,
@ -217,7 +208,7 @@ pub struct QueryGridBlocksParams {
pub block_ids: Vec<String>,
}
impl TryInto<QueryGridBlocksParams> for QueryGridBlocksPayload {
impl TryInto<QueryGridBlocksParams> for QueryGridBlocksPayloadPB {
type Error = ErrorCode;
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_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr;
@ -6,28 +6,28 @@ use flowy_grid_data_model::revision::{CellRevision, RowMetaChangeset};
use std::collections::HashMap;
#[derive(ProtoBuf, Default)]
pub struct CreateSelectOptionPayload {
pub struct CreateSelectOptionPayloadPB {
#[pb(index = 1)]
pub field_identifier: FieldIdentifierPayload,
pub field_identifier: GridFieldIdentifierPayloadPB,
#[pb(index = 2)]
pub option_name: String,
}
pub struct CreateSelectOptionParams {
pub field_identifier: FieldIdentifier,
pub field_identifier: FieldIdentifierParams,
pub option_name: String,
}
impl std::ops::Deref for CreateSelectOptionParams {
type Target = FieldIdentifier;
type Target = FieldIdentifierParams;
fn deref(&self) -> &Self::Target {
&self.field_identifier
}
}
impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayload {
impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayloadPB {
type Error = ErrorCode;
fn try_into(self) -> Result<CreateSelectOptionParams, Self::Error> {
@ -41,7 +41,7 @@ impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayload {
}
#[derive(Debug, Clone, Default, ProtoBuf)]
pub struct CellIdentifierPayload {
pub struct GridCellIdentifierPayloadPB {
#[pb(index = 1)]
pub grid_id: String,
@ -52,20 +52,20 @@ pub struct CellIdentifierPayload {
pub row_id: String,
}
pub struct CellIdentifier {
pub struct CellIdentifierParams {
pub grid_id: String,
pub field_id: String,
pub row_id: String,
}
impl TryInto<CellIdentifier> for CellIdentifierPayload {
impl TryInto<CellIdentifierParams> for GridCellIdentifierPayloadPB {
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 field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;
Ok(CellIdentifier {
Ok(CellIdentifierParams {
grid_id: grid_id.0,
field_id: field_id.0,
row_id: row_id.0,
@ -73,7 +73,7 @@ impl TryInto<CellIdentifier> for CellIdentifierPayload {
}
}
#[derive(Debug, Default, ProtoBuf)]
pub struct Cell {
pub struct GridCellPB {
#[pb(index = 1)]
pub field_id: String,
@ -81,7 +81,7 @@ pub struct Cell {
pub data: Vec<u8>,
}
impl Cell {
impl GridCellPB {
pub fn new(field_id: &str, data: Vec<u8>) -> Self {
Self {
field_id: field_id.to_owned(),
@ -98,32 +98,32 @@ impl Cell {
}
#[derive(Debug, Default, ProtoBuf)]
pub struct RepeatedCell {
pub struct RepeatedCellPB {
#[pb(index = 1)]
pub items: Vec<Cell>,
pub items: Vec<GridCellPB>,
}
impl std::ops::Deref for RepeatedCell {
type Target = Vec<Cell>;
impl std::ops::Deref for RepeatedCellPB {
type Target = Vec<GridCellPB>;
fn deref(&self) -> &Self::Target {
&self.items
}
}
impl std::ops::DerefMut for RepeatedCell {
impl std::ops::DerefMut for RepeatedCellPB {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.items
}
}
impl std::convert::From<Vec<Cell>> for RepeatedCell {
fn from(items: Vec<Cell>) -> Self {
impl std::convert::From<Vec<GridCellPB>> for RepeatedCellPB {
fn from(items: Vec<GridCellPB>) -> Self {
Self { items }
}
}
#[derive(Debug, Clone, Default, ProtoBuf)]
pub struct CellChangeset {
pub struct CellChangesetPB {
#[pb(index = 1)]
pub grid_id: String,
@ -137,8 +137,8 @@ pub struct CellChangeset {
pub content: Option<String>,
}
impl std::convert::From<CellChangeset> for RowMetaChangeset {
fn from(changeset: CellChangeset) -> Self {
impl std::convert::From<CellChangesetPB> for RowMetaChangeset {
fn from(changeset: CellChangesetPB) -> Self {
let mut cell_by_field_id = HashMap::with_capacity(1);
let field_id = changeset.field_id;
let cell_rev = CellRevision {

View File

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

View File

@ -17,7 +17,7 @@ pub struct GridFilter {
}
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct RepeatedGridFilter {
pub struct RepeatedGridFilterPB {
#[pb(index = 1)]
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 {
RepeatedGridFilter {
RepeatedGridFilterPB {
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 {
Self { items }
}
}
#[derive(ProtoBuf, Debug, Default, Clone)]
pub struct DeleteFilterPayload {
pub struct DeleteFilterPayloadPB {
#[pb(index = 1)]
pub field_id: String,
@ -54,7 +54,7 @@ pub struct DeleteFilterPayload {
pub field_type: FieldType,
}
impl TryInto<DeleteFilterParams> for DeleteFilterPayload {
impl TryInto<DeleteFilterParams> for DeleteFilterPayloadPB {
type Error = ErrorCode;
fn try_into(self) -> Result<DeleteFilterParams, Self::Error> {
@ -73,7 +73,7 @@ impl TryInto<DeleteFilterParams> for DeleteFilterPayload {
}
#[derive(ProtoBuf, Debug, Default, Clone)]
pub struct CreateGridFilterPayload {
pub struct CreateGridFilterPayloadPB {
#[pb(index = 1)]
pub field_id: String,
@ -87,7 +87,7 @@ pub struct CreateGridFilterPayload {
pub content: Option<String>,
}
impl CreateGridFilterPayload {
impl CreateGridFilterPayloadPB {
#[allow(dead_code)]
pub fn new<T: Into<i32>>(field_rev: &FieldRevision, condition: T, content: Option<String>) -> Self {
Self {
@ -99,7 +99,7 @@ impl CreateGridFilterPayload {
}
}
impl TryInto<CreateGridFilterParams> for CreateGridFilterPayload {
impl TryInto<CreateGridFilterParams> for CreateGridFilterPayloadPB {
type Error = ErrorCode;
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_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr;
#[derive(Debug, Clone, Default, ProtoBuf)]
pub struct Grid {
pub struct GridPB {
#[pb(index = 1)]
pub id: String,
#[pb(index = 2)]
pub field_orders: Vec<FieldOrder>,
pub fields: Vec<GridFieldIdPB>,
#[pb(index = 3)]
pub blocks: Vec<GridBlock>,
pub blocks: Vec<GridBlockPB>,
}
#[derive(ProtoBuf, Default)]
pub struct CreateGridPayload {
pub struct CreateGridPayloadPB {
#[pb(index = 1)]
pub name: String,
}
#[derive(Clone, ProtoBuf, Default, Debug)]
pub struct GridId {
pub struct GridIdPB {
#[pb(index = 1)]
pub value: String,
}
impl AsRef<str> for GridId {
impl AsRef<str> for GridIdPB {
fn as_ref(&self) -> &str {
&self.value
}
}
#[derive(Clone, ProtoBuf, Default, Debug)]
pub struct GridBlockId {
pub struct GridBlockIdPB {
#[pb(index = 1)]
pub value: String,
}
impl AsRef<str> for GridBlockId {
impl AsRef<str> for GridBlockIdPB {
fn as_ref(&self) -> &str {
&self.value
}
}
impl std::convert::From<&str> for GridBlockId {
impl std::convert::From<&str> for GridBlockIdPB {
fn from(s: &str) -> Self {
GridBlockId { value: s.to_owned() }
GridBlockIdPB { value: s.to_owned() }
}
}
#[derive(Debug, Clone, ProtoBuf_Enum)]
pub enum MoveItemType {
pub enum MoveItemTypePB {
MoveField = 0,
MoveRow = 1,
}
impl std::default::Default for MoveItemType {
impl std::default::Default for MoveItemTypePB {
fn default() -> Self {
MoveItemType::MoveField
MoveItemTypePB::MoveField
}
}
#[derive(Debug, Clone, Default, ProtoBuf)]
pub struct MoveItemPayload {
pub struct MoveItemPayloadPB {
#[pb(index = 1)]
pub grid_id: String,
@ -77,7 +77,7 @@ pub struct MoveItemPayload {
pub to_index: i32,
#[pb(index = 5)]
pub ty: MoveItemType,
pub ty: MoveItemTypePB,
}
#[derive(Clone)]
@ -86,10 +86,10 @@ pub struct MoveItemParams {
pub item_id: String,
pub from_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;
fn try_into(self) -> Result<MoveItemParams, Self::Error> {

View File

@ -7,7 +7,7 @@ use std::convert::TryInto;
use std::sync::Arc;
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct GridGroup {
pub struct GridGroupPB {
#[pb(index = 1)]
pub id: String,
@ -18,9 +18,9 @@ pub struct GridGroup {
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 {
GridGroup {
GridGroupPB {
id: rev.id.clone(),
group_field_id: rev.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)]
pub struct RepeatedGridGroup {
pub struct RepeatedGridGroupPB {
#[pb(index = 1)]
pub items: Vec<GridGroup>,
pub items: Vec<GridGroupPB>,
}
impl std::convert::From<Vec<GridGroup>> for RepeatedGridGroup {
fn from(items: Vec<GridGroup>) -> Self {
impl std::convert::From<Vec<GridGroupPB>> for RepeatedGridGroupPB {
fn from(items: Vec<GridGroupPB>) -> Self {
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 {
RepeatedGridGroup {
RepeatedGridGroupPB {
items: revs.iter().map(|rev| rev.as_ref().into()).collect(),
}
}
}
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct CreateGridGroupPayload {
pub struct CreateGridGroupPayloadPB {
#[pb(index = 1, one_of)]
pub field_id: Option<String>,
@ -57,7 +57,7 @@ pub struct CreateGridGroupPayload {
pub sub_field_id: Option<String>,
}
impl TryInto<CreateGridGroupParams> for CreateGridGroupPayload {
impl TryInto<CreateGridGroupParams> for CreateGridGroupPayloadPB {
type Error = ErrorCode;
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;
#[derive(ProtoBuf, Default)]
pub struct GridRowIdPayload {
pub struct GridRowIdPayloadPB {
#[pb(index = 1)]
pub grid_id: String,
@ -15,7 +15,7 @@ pub struct GridRowIdPayload {
}
#[derive(Debug, Default, Clone, ProtoBuf)]
pub struct GridRowId {
pub struct GridRowIdPB {
#[pb(index = 1)]
pub grid_id: String,
@ -26,15 +26,15 @@ pub struct GridRowId {
pub row_id: String,
}
impl TryInto<GridRowId> for GridRowIdPayload {
impl TryInto<GridRowIdPB> for GridRowIdPayloadPB {
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 block_id = NotEmptyStr::parse(self.block_id).map_err(|_| ErrorCode::BlockIdIsEmpty)?;
let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;
Ok(GridRowId {
Ok(GridRowIdPB {
grid_id: grid_id.0,
block_id: block_id.0,
row_id: row_id.0,
@ -43,7 +43,7 @@ impl TryInto<GridRowId> for GridRowIdPayload {
}
#[derive(Debug, Default, Clone, ProtoBuf)]
pub struct BlockRowId {
pub struct BlockRowIdPB {
#[pb(index = 1)]
pub block_id: String,
@ -52,7 +52,7 @@ pub struct BlockRowId {
}
#[derive(ProtoBuf, Default)]
pub struct CreateRowPayload {
pub struct CreateRowPayloadPB {
#[pb(index = 1)]
pub grid_id: String,
@ -66,7 +66,7 @@ pub struct CreateRowParams {
pub start_row_id: Option<String>,
}
impl TryInto<CreateRowParams> for CreateRowPayload {
impl TryInto<CreateRowParams> for CreateRowPayloadPB {
type Error = ErrorCode;
fn try_into(self) -> Result<CreateRowParams, Self::Error> {

View File

@ -1,6 +1,6 @@
use crate::entities::{
CreateGridFilterPayload, CreateGridGroupPayload, CreateGridSortPayload, DeleteFilterPayload, RepeatedGridFilter,
RepeatedGridGroup, RepeatedGridSort,
CreateGridFilterPayloadPB, CreateGridGroupPayloadPB, CreateGridSortPayloadPB, DeleteFilterPayloadPB,
RepeatedGridFilterPB, RepeatedGridGroupPB, RepeatedGridSortPB,
};
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::ErrorCode;
@ -13,34 +13,34 @@ use strum::IntoEnumIterator;
use strum_macros::EnumIter;
#[derive(Eq, PartialEq, ProtoBuf, Debug, Default, Clone)]
pub struct GridSetting {
pub struct GridSettingPB {
#[pb(index = 1)]
pub layouts: Vec<GridLayout>,
pub layouts: Vec<GridLayoutPB>,
#[pb(index = 2)]
pub current_layout_type: GridLayoutType,
#[pb(index = 3)]
pub filters_by_field_id: HashMap<String, RepeatedGridFilter>,
pub filters_by_field_id: HashMap<String, RepeatedGridFilterPB>,
#[pb(index = 4)]
pub groups_by_field_id: HashMap<String, RepeatedGridGroup>,
pub groups_by_field_id: HashMap<String, RepeatedGridGroupPB>,
#[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)]
pub struct GridLayout {
pub struct GridLayoutPB {
#[pb(index = 1)]
ty: GridLayoutType,
}
impl GridLayout {
pub fn all() -> Vec<GridLayout> {
impl GridLayoutPB {
pub fn all() -> Vec<GridLayoutPB> {
let mut layouts = vec![];
for layout_ty in GridLayoutType::iter() {
layouts.push(GridLayout { ty: layout_ty })
layouts.push(GridLayoutPB { ty: layout_ty })
}
layouts
@ -79,7 +79,7 @@ impl std::convert::From<GridLayoutType> for GridLayoutRevision {
}
#[derive(Default, ProtoBuf)]
pub struct GridSettingChangesetPayload {
pub struct GridSettingChangesetPayloadPB {
#[pb(index = 1)]
pub grid_id: String,
@ -87,25 +87,25 @@ pub struct GridSettingChangesetPayload {
pub layout_type: GridLayoutType,
#[pb(index = 3, one_of)]
pub insert_filter: Option<CreateGridFilterPayload>,
pub insert_filter: Option<CreateGridFilterPayloadPB>,
#[pb(index = 4, one_of)]
pub delete_filter: Option<DeleteFilterPayload>,
pub delete_filter: Option<DeleteFilterPayloadPB>,
#[pb(index = 5, one_of)]
pub insert_group: Option<CreateGridGroupPayload>,
pub insert_group: Option<CreateGridGroupPayloadPB>,
#[pb(index = 6, one_of)]
pub delete_group: Option<String>,
#[pb(index = 7, one_of)]
pub insert_sort: Option<CreateGridSortPayload>,
pub insert_sort: Option<CreateGridSortPayloadPB>,
#[pb(index = 8, one_of)]
pub delete_sort: Option<String>,
}
impl TryInto<GridSettingChangesetParams> for GridSettingChangesetPayload {
impl TryInto<GridSettingChangesetParams> for GridSettingChangesetPayloadPB {
type Error = ErrorCode;
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)]
pub struct RepeatedGridSort {
pub struct RepeatedGridSortPB {
#[pb(index = 1)]
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 {
RepeatedGridSort {
RepeatedGridSortPB {
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 {
Self { items }
}
}
#[derive(ProtoBuf, Debug, Default, Clone)]
pub struct CreateGridSortPayload {
pub struct CreateGridSortPayloadPB {
#[pb(index = 1, one_of)]
pub field_id: Option<String>,
}
impl TryInto<CreateGridSortParams> for CreateGridSortPayload {
impl TryInto<CreateGridSortParams> for CreateGridSortPayloadPB {
type Error = ErrorCode;
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::field::{
default_type_option_builder_from_type, select_option_operation, type_option_builder_from_json_str,
DateChangesetParams, DateChangesetPayload, SelectOption, SelectOptionCellChangeset,
SelectOptionCellChangesetParams, SelectOptionCellChangesetPayload, SelectOptionCellData, SelectOptionChangeset,
SelectOptionChangesetPayload,
DateChangesetParams, DateChangesetPayloadPB, SelectOptionCellChangeset, SelectOptionCellChangesetParams,
SelectOptionCellChangesetPayloadPB, SelectOptionCellDataPB, SelectOptionChangeset, SelectOptionChangesetPayloadPB,
SelectOptionPB,
};
use crate::services::row::make_row_from_row_rev;
use flowy_error::{ErrorCode, FlowyError, FlowyResult};
@ -16,10 +16,10 @@ use std::sync::Arc;
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_grid_handler(
data: Data<GridId>,
data: Data<GridIdPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<Grid, FlowyError> {
let grid_id: GridId = data.into_inner();
) -> DataResult<GridPB, FlowyError> {
let grid_id: GridIdPB = data.into_inner();
let editor = manager.open_grid(grid_id).await?;
let grid = editor.get_grid_data().await?;
data_result(grid)
@ -27,10 +27,10 @@ pub(crate) async fn get_grid_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_grid_setting_handler(
data: Data<GridId>,
data: Data<GridIdPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<GridSetting, FlowyError> {
let grid_id: GridId = data.into_inner();
) -> DataResult<GridSettingPB, FlowyError> {
let grid_id: GridIdPB = data.into_inner();
let editor = manager.open_grid(grid_id).await?;
let grid_setting = editor.get_grid_setting().await?;
data_result(grid_setting)
@ -38,7 +38,7 @@ pub(crate) async fn get_grid_setting_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn update_grid_setting_handler(
data: Data<GridSettingChangesetPayload>,
data: Data<GridSettingChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn get_grid_blocks_handler(
data: Data<QueryGridBlocksPayload>,
data: Data<QueryGridBlocksPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<RepeatedGridBlock, FlowyError> {
) -> DataResult<RepeatedGridBlockPB, FlowyError> {
let params: QueryGridBlocksParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
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)]
pub(crate) async fn get_fields_handler(
data: Data<QueryFieldPayload>,
data: Data<QueryFieldPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<RepeatedField, FlowyError> {
) -> DataResult<RepeatedGridFieldPB, FlowyError> {
let params: QueryFieldParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
let field_orders = params
.field_orders
.field_ids
.items
.into_iter()
.map(|field_order| field_order.field_id)
.collect();
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)
}
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn update_field_handler(
data: Data<FieldChangesetPayload>,
data: Data<FieldChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn insert_field_handler(
data: Data<InsertFieldPayload>,
data: Data<InsertFieldPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn update_field_type_option_handler(
data: Data<UpdateFieldTypeOptionPayload>,
data: Data<UpdateFieldTypeOptionPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn delete_field_handler(
data: Data<FieldIdentifierPayload>,
data: Data<GridFieldIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> 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.delete_field(&params.field_id).await?;
Ok(())
@ -124,9 +124,9 @@ pub(crate) async fn delete_field_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn switch_to_field_handler(
data: Data<EditFieldPayload>,
data: Data<EditFieldPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionData, FlowyError> {
) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: EditFieldParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
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?));
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,
field: field_rev.into(),
type_option_data,
@ -151,10 +151,10 @@ pub(crate) async fn switch_to_field_handler(
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn duplicate_field_handler(
data: Data<FieldIdentifierPayload>,
data: Data<GridFieldIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> 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.duplicate_field(&params.field_id).await?;
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.
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn get_field_type_option_data_handler(
data: Data<EditFieldPayload>,
data: Data<EditFieldPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionData, FlowyError> {
) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: EditFieldParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
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) => {
let field_type = field_rev.field_type_rev.into();
let type_option_data = get_type_option_data(&field_rev, &field_type).await?;
let data = FieldTypeOptionData {
let data = FieldTypeOptionDataPB {
grid_id: params.grid_id,
field: field_rev.into(),
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.
#[tracing::instrument(level = "trace", skip(data, manager), err)]
pub(crate) async fn create_field_type_option_data_handler(
data: Data<EditFieldPayload>,
data: Data<EditFieldPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<FieldTypeOptionData, FlowyError> {
) -> DataResult<FieldTypeOptionDataPB, FlowyError> {
let params: CreateFieldParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
let field_rev = editor.create_next_field_rev(&params.field_type).await?;
let field_type: FieldType = field_rev.field_type_rev.into();
let type_option_data = get_type_option_data(&field_rev, &field_type).await?;
data_result(FieldTypeOptionData {
data_result(FieldTypeOptionDataPB {
grid_id: params.grid_id,
field: field_rev.into(),
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)]
pub(crate) async fn move_item_handler(
data: Data<MoveItemPayload>,
data: Data<MoveItemPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn get_row_handler(
data: Data<GridRowIdPayload>,
data: Data<GridRowIdPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<OptionalRow, FlowyError> {
let params: GridRowId = data.into_inner().try_into()?;
) -> DataResult<OptionalRowPB, FlowyError> {
let params: GridRowIdPB = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
let row = editor
.get_row_rev(&params.row_id)
.await?
.and_then(make_row_from_row_rev);
data_result(OptionalRow { row })
data_result(OptionalRowPB { row })
}
#[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn delete_row_handler(
data: Data<GridRowIdPayload>,
data: Data<GridRowIdPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> 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.delete_row(&params.row_id).await?;
Ok(())
@ -253,10 +253,10 @@ pub(crate) async fn delete_row_handler(
#[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn duplicate_row_handler(
data: Data<GridRowIdPayload>,
data: Data<GridRowIdPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> 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.duplicate_row(&params.row_id).await?;
Ok(())
@ -264,7 +264,7 @@ pub(crate) async fn duplicate_row_handler(
#[tracing::instrument(level = "debug", skip(data, manager), err)]
pub(crate) async fn create_row_handler(
data: Data<CreateRowPayload>,
data: Data<CreateRowPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn get_cell_handler(
data: Data<CellIdentifierPayload>,
data: Data<GridCellIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<Cell, FlowyError> {
let params: CellIdentifier = data.into_inner().try_into()?;
) -> DataResult<GridCellPB, FlowyError> {
let params: CellIdentifierParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
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),
}
}
#[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn update_cell_handler(
data: Data<CellChangeset>,
data: Data<CellChangesetPB>,
manager: AppData<Arc<GridManager>>,
) -> 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.update_cell(changeset).await?;
Ok(())
@ -299,9 +299,9 @@ pub(crate) async fn update_cell_handler(
#[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn new_select_option_handler(
data: Data<CreateSelectOptionPayload>,
data: Data<CreateSelectOptionPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<SelectOption, FlowyError> {
) -> DataResult<SelectOptionPB, FlowyError> {
let params: CreateSelectOptionParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
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)]
pub(crate) async fn update_select_option_handler(
data: Data<SelectOptionChangesetPayload>,
data: Data<SelectOptionChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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);
let _ = editor.replace_field(field_rev).await?;
let changeset = CellChangeset {
let changeset = CellChangesetPB {
grid_id: changeset.cell_identifier.grid_id,
row_id: changeset.cell_identifier.row_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)]
pub(crate) async fn get_select_option_handler(
data: Data<CellIdentifierPayload>,
data: Data<GridCellIdentifierPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> DataResult<SelectOptionCellData, FlowyError> {
let params: CellIdentifier = data.into_inner().try_into()?;
) -> DataResult<SelectOptionCellDataPB, FlowyError> {
let params: CellIdentifierParams = data.into_inner().try_into()?;
let editor = manager.get_grid_editor(&params.grid_id)?;
match editor.get_field_rev(&params.field_id).await {
None => {
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) => {
//
@ -386,7 +386,7 @@ pub(crate) async fn get_select_option_handler(
#[tracing::instrument(level = "trace", skip_all, err)]
pub(crate) async fn update_select_option_cell_handler(
data: Data<SelectOptionCellChangesetPayload>,
data: Data<SelectOptionCellChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
pub(crate) async fn update_date_cell_handler(
data: Data<DateChangesetPayload>,
data: Data<DateChangesetPayloadPB>,
manager: AppData<Arc<GridManager>>,
) -> Result<(), FlowyError> {
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)]
#[event_err = "FlowyError"]
pub enum GridEvent {
#[event(input = "GridId", output = "Grid")]
#[event(input = "GridIdPB", output = "GridPB")]
GetGrid = 0,
#[event(input = "QueryGridBlocksPayload", output = "RepeatedGridBlock")]
#[event(input = "QueryGridBlocksPayloadPB", output = "RepeatedGridBlockPB")]
GetGridBlocks = 1,
#[event(input = "GridId", output = "GridSetting")]
#[event(input = "GridIdPB", output = "GridSettingPB")]
GetGridSetting = 2,
#[event(input = "GridId", input = "GridSettingChangesetPayload")]
#[event(input = "GridIdPB", input = "GridSettingChangesetPayloadPB")]
UpdateGridSetting = 3,
#[event(input = "QueryFieldPayload", output = "RepeatedField")]
#[event(input = "QueryFieldPayloadPB", output = "RepeatedGridFieldPB")]
GetFields = 10,
#[event(input = "FieldChangesetPayload")]
#[event(input = "FieldChangesetPayloadPB")]
UpdateField = 11,
#[event(input = "UpdateFieldTypeOptionPayload")]
#[event(input = "UpdateFieldTypeOptionPayloadPB")]
UpdateFieldTypeOption = 12,
#[event(input = "InsertFieldPayload")]
#[event(input = "InsertFieldPayloadPB")]
InsertField = 13,
#[event(input = "FieldIdentifierPayload")]
#[event(input = "GridFieldIdentifierPayloadPB")]
DeleteField = 14,
#[event(input = "EditFieldPayload", output = "FieldTypeOptionData")]
#[event(input = "EditFieldPayloadPB", output = "FieldTypeOptionDataPB")]
SwitchToField = 20,
#[event(input = "FieldIdentifierPayload")]
#[event(input = "GridFieldIdentifierPayloadPB")]
DuplicateField = 21,
#[event(input = "MoveItemPayload")]
#[event(input = "MoveItemPayloadPB")]
MoveItem = 22,
#[event(input = "EditFieldPayload", output = "FieldTypeOptionData")]
#[event(input = "EditFieldPayloadPB", output = "FieldTypeOptionDataPB")]
GetFieldTypeOption = 23,
#[event(input = "EditFieldPayload", output = "FieldTypeOptionData")]
#[event(input = "EditFieldPayloadPB", output = "FieldTypeOptionDataPB")]
CreateFieldTypeOption = 24,
#[event(input = "CreateSelectOptionPayload", output = "SelectOption")]
#[event(input = "CreateSelectOptionPayloadPB", output = "SelectOptionPB")]
NewSelectOption = 30,
#[event(input = "CellIdentifierPayload", output = "SelectOptionCellData")]
#[event(input = "GridCellIdentifierPayloadPB", output = "SelectOptionCellDataPB")]
GetSelectOptionCellData = 31,
#[event(input = "SelectOptionChangesetPayload")]
#[event(input = "SelectOptionChangesetPayloadPB")]
UpdateSelectOption = 32,
#[event(input = "CreateRowPayload", output = "Row")]
#[event(input = "CreateRowPayloadPB", output = "GridRowPB")]
CreateRow = 50,
#[event(input = "GridRowIdPayload", output = "OptionalRow")]
#[event(input = "GridRowIdPayloadPB", output = "OptionalRowPB")]
GetRow = 51,
#[event(input = "GridRowIdPayload")]
#[event(input = "GridRowIdPayloadPB")]
DeleteRow = 52,
#[event(input = "GridRowIdPayload")]
#[event(input = "GridRowIdPayloadPB")]
DuplicateRow = 53,
#[event(input = "CellIdentifierPayload", output = "Cell")]
#[event(input = "GridCellIdentifierPayloadPB", output = "GridCellPB")]
GetCell = 70,
#[event(input = "CellChangeset")]
#[event(input = "CellChangesetPB")]
UpdateCell = 71,
#[event(input = "SelectOptionCellChangesetPayload")]
#[event(input = "SelectOptionCellChangesetPayloadPB")]
UpdateSelectOptionCell = 72,
#[event(input = "DateChangesetPayload")]
#[event(input = "DateChangesetPayloadPB")]
UpdateDateCell = 80,
}

View File

@ -1,5 +1,5 @@
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::services::block_revision_editor::GridBlockRevisionEditor;
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 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?;
index_row_order.index = row_index;
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?;
Ok(row_count)
}
@ -92,7 +92,7 @@ impl GridBlockManager {
let mut row_count = 0;
for row in row_revs {
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?;
row_count = count;
row_order.index = index;
@ -101,7 +101,7 @@ impl GridBlockManager {
changesets.push(GridBlockMetaRevisionChangeset::from_row_count(&block_id, row_count));
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?;
}
@ -110,7 +110,7 @@ impl GridBlockManager {
pub async fn update_row<F>(&self, changeset: RowMetaChangeset, row_builder: F) -> FlowyResult<()>
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.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),
Some(row_rev) => {
if let Some(row) = row_builder(row_rev.clone()) {
let row_order = UpdatedRow::new(&row_rev, row);
let block_order_changeset = GridBlockChangeset::update(&editor.block_id, vec![row_order]);
let row_order = UpdatedRowPB::new(&row_rev, row);
let block_order_changeset = GridBlockChangesetPB::update(&editor.block_id, vec![row_order]);
let _ = self
.notify_did_update_block(&editor.block_id, block_order_changeset)
.await?;
@ -138,7 +138,7 @@ impl GridBlockManager {
Some(row_info) => {
let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?;
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?;
}
}
@ -148,13 +148,13 @@ impl GridBlockManager {
pub(crate) async fn delete_rows(
&self,
row_orders: Vec<RowInfo>,
row_orders: Vec<GridRowPB>,
) -> FlowyResult<Vec<GridBlockMetaRevisionChangeset>> {
let mut changesets = vec![];
for grid_block in block_from_row_orders(row_orders) {
let editor = self.get_editor(&grid_block.id).await?;
let row_ids = grid_block
.row_infos
.rows
.into_iter()
.map(|row_info| Cow::Owned(row_info.row_id().to_owned()))
.collect::<Vec<Cow<String>>>();
@ -173,14 +173,14 @@ impl GridBlockManager {
match editor.get_row_revs(Some(vec![Cow::Borrowed(row_id)])).await?.pop() {
None => {}
Some(row_rev) => {
let insert_row = InsertedRow {
let insert_row = InsertedRowPB {
block_id: row_rev.block_id.clone(),
row_id: row_rev.id.clone(),
index: Some(to as i32),
height: row_rev.height,
};
let notified_changeset = GridBlockChangeset {
let notified_changeset = GridBlockChangesetPB {
block_id: editor.block_id.clone(),
inserted_rows: vec![insert_row],
deleted_rows: vec![row_rev.id.clone()],
@ -196,9 +196,9 @@ impl GridBlockManager {
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
F: FnOnce(Arc<RowRevision>) -> Option<Row>,
F: FnOnce(Arc<RowRevision>) -> Option<GridRowPB>,
{
let row_changeset: RowMetaChangeset = changeset.clone().into();
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?;
editor.get_row_infos::<&str>(None).await
}
@ -247,14 +247,14 @@ impl GridBlockManager {
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)
.payload(changeset)
.send();
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);
send_dart_notification(&id, GridNotification::DidUpdateCell).send();
Ok(())

View File

@ -1,4 +1,4 @@
use crate::entities::RowInfo;
use crate::entities::GridRowPB;
use bytes::Bytes;
use flowy_error::{FlowyError, FlowyResult};
use flowy_grid_data_model::revision::{CellRevision, GridBlockRevision, RowMetaChangeset, RowRevision};
@ -123,12 +123,12 @@ impl GridBlockRevisionEditor {
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)]);
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
T: AsRef<str> + ToOwned + ?Sized,
{
@ -138,8 +138,8 @@ impl GridBlockRevisionEditor {
.await
.get_row_revs(row_ids)?
.iter()
.map(RowInfo::from)
.collect::<Vec<RowInfo>>();
.map(GridRowPB::from)
.collect::<Vec<GridRowPB>>();
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::Number => NumberTypeOption::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::Checkbox => CheckboxTypeOption::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)?
.decode_cell_data(cell_data.into(), s_field_type, 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),
FieldType::MultiSelect => field_rev
.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 bytes::Bytes;
use flowy_grid_data_model::revision::{FieldRevision, TypeOptionDataEntry};
@ -28,7 +28,7 @@ impl FieldBuilder {
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 {
id: field.id,
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::Number => NumberTypeOption::default().into(),
FieldType::DateTime => DateTypeOption::default().into(),
FieldType::SingleSelect => SingleSelectTypeOption::default().into(),
FieldType::SingleSelect => SingleSelectTypeOptionPB::default().into(),
FieldType::MultiSelect => MultiSelectTypeOption::default().into(),
FieldType::Checkbox => CheckboxTypeOption::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();
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some("1e".to_string()),
time: Some("23:00".to_owned()),
},
@ -60,7 +60,7 @@ mod tests {
TimeFormat::TwentyFourHour => {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(1653609600.to_string()),
time: None,
},
@ -70,7 +70,7 @@ mod tests {
);
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(1653609600.to_string()),
time: Some("23:00".to_owned()),
},
@ -82,7 +82,7 @@ mod tests {
TimeFormat::TwelveHour => {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(1653609600.to_string()),
time: None,
},
@ -93,7 +93,7 @@ mod tests {
//
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(1653609600.to_string()),
time: Some("".to_owned()),
},
@ -104,7 +104,7 @@ mod tests {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(1653609600.to_string()),
time: Some("11:23 pm".to_owned()),
},
@ -126,7 +126,7 @@ mod tests {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp.clone()),
time: None,
},
@ -138,7 +138,7 @@ mod tests {
type_option.include_time = true;
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp.clone()),
time: None,
},
@ -149,7 +149,7 @@ mod tests {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp.clone()),
time: Some("1:00".to_owned()),
},
@ -161,7 +161,7 @@ mod tests {
type_option.time_format = TimeFormat::TwelveHour;
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp),
time: Some("1:00 am".to_owned()),
},
@ -181,7 +181,7 @@ mod tests {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp.clone()),
time: Some("1:".to_owned()),
},
@ -192,7 +192,7 @@ mod tests {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp),
time: Some("1:00".to_owned()),
},
@ -212,7 +212,7 @@ mod tests {
assert_changeset_result(
&type_option,
DateCellChangeset {
DateCellChangesetPB {
date: Some(date_timestamp),
time: Some("1:00 am".to_owned()),
},
@ -224,7 +224,7 @@ mod tests {
fn assert_changeset_result(
type_option: &DateTypeOption,
changeset: DateCellChangeset,
changeset: DateCellChangesetPB,
_field_type: &FieldType,
field_rev: &FieldRevision,
expected: &str,
@ -243,7 +243,7 @@ mod tests {
field_rev: &FieldRevision,
expected: &str,
) {
let s = serde_json::to_string(&DateCellChangeset {
let s = serde_json::to_string(&DateCellChangesetPB {
date: Some(timestamp.to_string()),
time: None,
})

View File

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

View File

@ -1,5 +1,5 @@
use crate::entities::CellChangeset;
use crate::entities::{CellIdentifier, CellIdentifierPayload};
use crate::entities::CellChangesetPB;
use crate::entities::{CellIdentifierParams, GridCellIdentifierPayloadPB};
use crate::services::cell::{CellBytesParser, FromCellChangeset, FromCellString};
use bytes::Bytes;
@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
#[derive(Clone, Debug, Default, ProtoBuf)]
pub struct DateCellData {
pub struct DateCellDataPB {
#[pb(index = 1)]
pub date: String,
@ -22,9 +22,9 @@ pub struct DateCellData {
}
#[derive(Clone, Debug, Default, ProtoBuf)]
pub struct DateChangesetPayload {
pub struct DateChangesetPayloadPB {
#[pb(index = 1)]
pub cell_identifier: CellIdentifierPayload,
pub cell_identifier: GridCellIdentifierPayloadPB,
#[pb(index = 2, one_of)]
pub date: Option<String>,
@ -34,16 +34,16 @@ pub struct DateChangesetPayload {
}
pub struct DateChangesetParams {
pub cell_identifier: CellIdentifier,
pub cell_identifier: CellIdentifierParams,
pub date: Option<String>,
pub time: Option<String>,
}
impl TryInto<DateChangesetParams> for DateChangesetPayload {
impl TryInto<DateChangesetParams> for DateChangesetPayloadPB {
type Error = ErrorCode;
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 {
cell_identifier,
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 {
let changeset = DateCellChangeset {
let changeset = DateCellChangesetPB {
date: params.date,
time: params.time,
};
let s = serde_json::to_string(&changeset).unwrap();
CellChangeset {
CellChangesetPB {
grid_id: params.cell_identifier.grid_id,
row_id: params.cell_identifier.row_id,
field_id: params.cell_identifier.field_id,
@ -69,12 +69,12 @@ impl std::convert::From<DateChangesetParams> for CellChangeset {
}
#[derive(Clone, Serialize, Deserialize)]
pub struct DateCellChangeset {
pub struct DateCellChangesetPB {
pub date: Option<String>,
pub time: Option<String>,
}
impl DateCellChangeset {
impl DateCellChangesetPB {
pub fn date_timestamp(&self) -> Option<i64> {
if let Some(date) = &self.date {
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>
where
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);
@ -202,9 +202,9 @@ impl std::default::Default for TimeFormat {
pub struct DateCellDataParser();
impl CellBytesParser for DateCellDataParser {
type Object = DateCellData;
type Object = DateCellDataPB;
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::field::type_options::util::get_cell_data;
use crate::services::field::{
make_selected_select_options, BoxTypeOptionBuilder, SelectOption, SelectOptionCellChangeset, SelectOptionCellData,
SelectOptionIds, SelectOptionOperation, TypeOptionBuilder, SELECTION_IDS_SEPARATOR,
make_selected_select_options, BoxTypeOptionBuilder, SelectOptionCellChangeset, SelectOptionCellDataPB,
SelectOptionIds, SelectOptionOperation, SelectOptionPB, TypeOptionBuilder, SELECTION_IDS_SEPARATOR,
};
use bytes::Bytes;
use flowy_derive::ProtoBuf;
@ -16,7 +16,7 @@ use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct MultiSelectTypeOption {
#[pb(index = 1)]
pub options: Vec<SelectOption>,
pub options: Vec<SelectOptionPB>,
#[pb(index = 2)]
pub disable_color: bool,
@ -24,19 +24,19 @@ pub struct MultiSelectTypeOption {
impl_type_option!(MultiSelectTypeOption, FieldType::MultiSelect);
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);
SelectOptionCellData {
SelectOptionCellDataPB {
options: self.options.clone(),
select_options,
}
}
fn options(&self) -> &Vec<SelectOption> {
fn options(&self) -> &Vec<SelectOptionPB> {
&self.options
}
fn mut_options(&mut self) -> &mut Vec<SelectOption> {
fn mut_options(&mut self) -> &mut Vec<SelectOptionPB> {
&mut self.options
}
}
@ -97,7 +97,7 @@ pub struct MultiSelectTypeOptionBuilder(MultiSelectTypeOption);
impl_into_box_type_option_builder!(MultiSelectTypeOptionBuilder);
impl_builder_from_json_str_and_from_bytes!(MultiSelectTypeOptionBuilder, MultiSelectTypeOption);
impl MultiSelectTypeOptionBuilder {
pub fn option(mut self, opt: SelectOption) -> Self {
pub fn option(mut self, opt: SelectOptionPB) -> Self {
self.0.options.push(opt);
self
}
@ -123,9 +123,9 @@ mod tests {
#[test]
fn multi_select_test() {
let google_option = SelectOption::new("Google");
let facebook_option = SelectOption::new("Facebook");
let twitter_option = SelectOption::new("Twitter");
let google_option = SelectOptionPB::new("Google");
let facebook_option = SelectOptionPB::new("Facebook");
let twitter_option = SelectOptionPB::new("Twitter");
let multi_select = MultiSelectTypeOptionBuilder::default()
.option(google_option.clone())
.option(facebook_option.clone())
@ -172,7 +172,7 @@ mod tests {
cell_data: String,
type_option: &MultiSelectTypeOption,
field_rev: &FieldRevision,
expected: Vec<SelectOption>,
expected: Vec<SelectOptionPB>,
) {
let field_type: FieldType = field_rev.field_type_rev.into();
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::field::{MultiSelectTypeOption, SingleSelectTypeOption};
use crate::services::field::{MultiSelectTypeOption, SingleSelectTypeOptionPB};
use bytes::Bytes;
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::{internal_error, ErrorCode, FlowyResult};
@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
pub const SELECTION_IDS_SEPARATOR: &str = ",";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ProtoBuf)]
pub struct SelectOption {
pub struct SelectOptionPB {
#[pb(index = 1)]
pub id: String,
@ -20,20 +20,20 @@ pub struct SelectOption {
pub name: String,
#[pb(index = 3)]
pub color: SelectOptionColor,
pub color: SelectOptionColorPB,
}
impl SelectOption {
impl SelectOptionPB {
pub fn new(name: &str) -> Self {
SelectOption {
SelectOptionPB {
id: nanoid!(4),
name: name.to_owned(),
color: SelectOptionColor::default(),
color: SelectOptionColorPB::default(),
}
}
pub fn with_color(name: &str, color: SelectOptionColor) -> Self {
SelectOption {
pub fn with_color(name: &str, color: SelectOptionColorPB) -> Self {
SelectOptionPB {
id: nanoid!(4),
name: name.to_owned(),
color,
@ -43,7 +43,7 @@ impl SelectOption {
#[derive(ProtoBuf_Enum, PartialEq, Eq, Serialize, Deserialize, Debug, Clone)]
#[repr(u8)]
pub enum SelectOptionColor {
pub enum SelectOptionColorPB {
Purple = 0,
Pink = 1,
LightPink = 2,
@ -55,16 +55,16 @@ pub enum SelectOptionColor {
Blue = 8,
}
impl std::default::Default for SelectOptionColor {
impl std::default::Default for SelectOptionColorPB {
fn default() -> Self {
SelectOptionColor::Purple
SelectOptionColorPB::Purple
}
}
pub fn make_selected_select_options(
cell_data: CellData<SelectOptionIds>,
options: &[SelectOption],
) -> Vec<SelectOption> {
options: &[SelectOptionPB],
) -> Vec<SelectOptionPB> {
if let Ok(ids) = cell_data.try_into_inner() {
ids.iter()
.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 {
fn insert_option(&mut self, new_option: SelectOption) {
fn insert_option(&mut self, new_option: SelectOptionPB) {
let options = self.mut_options();
if let Some(index) = options
.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();
if let Some(index) = options.iter().position(|option| option.id == delete_option.id) {
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());
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
@ -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();
match &field_type {
FieldType::SingleSelect => {
let type_option = SingleSelectTypeOption::from(field_rev);
let type_option = SingleSelectTypeOptionPB::from(field_rev);
Ok(Box::new(type_option))
}
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 {
0 => SelectOptionColor::Purple,
1 => SelectOptionColor::Pink,
2 => SelectOptionColor::LightPink,
3 => SelectOptionColor::Orange,
4 => SelectOptionColor::Yellow,
5 => SelectOptionColor::Lime,
6 => SelectOptionColor::Green,
7 => SelectOptionColor::Aqua,
8 => SelectOptionColor::Blue,
_ => SelectOptionColor::Purple,
0 => SelectOptionColorPB::Purple,
1 => SelectOptionColorPB::Pink,
2 => SelectOptionColorPB::LightPink,
3 => SelectOptionColorPB::Orange,
4 => SelectOptionColorPB::Yellow,
5 => SelectOptionColorPB::Lime,
6 => SelectOptionColorPB::Green,
7 => SelectOptionColorPB::Aqua,
8 => SelectOptionColorPB::Blue,
_ => SelectOptionColorPB::Purple,
}
}
pub struct SelectOptionIds(Vec<String>);
@ -215,17 +215,17 @@ impl CellBytesParser for SelectOptionIdsParser {
pub struct SelectOptionCellDataParser();
impl CellBytesParser for SelectOptionCellDataParser {
type Object = SelectOptionCellData;
type Object = SelectOptionCellDataPB;
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)]
pub struct SelectOptionCellChangesetPayload {
pub struct SelectOptionCellChangesetPayloadPB {
#[pb(index = 1)]
pub cell_identifier: CellIdentifierPayload,
pub cell_identifier: GridCellIdentifierPayloadPB,
#[pb(index = 2, one_of)]
pub insert_option_id: Option<String>,
@ -235,19 +235,19 @@ pub struct SelectOptionCellChangesetPayload {
}
pub struct SelectOptionCellChangesetParams {
pub cell_identifier: CellIdentifier,
pub cell_identifier: CellIdentifierParams,
pub insert_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 {
let changeset = SelectOptionCellChangeset {
insert_option_id: params.insert_option_id,
delete_option_id: params.delete_option_id,
};
let s = serde_json::to_string(&changeset).unwrap();
CellChangeset {
CellChangesetPB {
grid_id: params.cell_identifier.grid_id,
row_id: params.cell_identifier.row_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;
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 {
None => None,
Some(insert_option_id) => Some(
@ -323,37 +323,37 @@ impl SelectOptionCellChangeset {
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct SelectOptionCellData {
pub struct SelectOptionCellDataPB {
#[pb(index = 1)]
pub options: Vec<SelectOption>,
pub options: Vec<SelectOptionPB>,
#[pb(index = 2)]
pub select_options: Vec<SelectOption>,
pub select_options: Vec<SelectOptionPB>,
}
#[derive(Clone, Debug, Default, ProtoBuf)]
pub struct SelectOptionChangesetPayload {
pub struct SelectOptionChangesetPayloadPB {
#[pb(index = 1)]
pub cell_identifier: CellIdentifierPayload,
pub cell_identifier: GridCellIdentifierPayloadPB,
#[pb(index = 2, one_of)]
pub insert_option: Option<SelectOption>,
pub insert_option: Option<SelectOptionPB>,
#[pb(index = 3, one_of)]
pub update_option: Option<SelectOption>,
pub update_option: Option<SelectOptionPB>,
#[pb(index = 4, one_of)]
pub delete_option: Option<SelectOption>,
pub delete_option: Option<SelectOptionPB>,
}
pub struct SelectOptionChangeset {
pub cell_identifier: CellIdentifier,
pub insert_option: Option<SelectOption>,
pub update_option: Option<SelectOption>,
pub delete_option: Option<SelectOption>,
pub cell_identifier: CellIdentifierParams,
pub insert_option: Option<SelectOptionPB>,
pub update_option: Option<SelectOptionPB>,
pub delete_option: Option<SelectOptionPB>,
}
impl TryInto<SelectOptionChangeset> for SelectOptionChangesetPayload {
impl TryInto<SelectOptionChangeset> for SelectOptionChangesetPayloadPB {
type Error = ErrorCode;
fn try_into(self) -> Result<SelectOptionChangeset, Self::Error> {
@ -368,11 +368,11 @@ impl TryInto<SelectOptionChangeset> for SelectOptionChangesetPayload {
}
pub struct SelectedSelectOptions {
pub(crate) options: Vec<SelectOption>,
pub(crate) options: Vec<SelectOptionPB>,
}
impl std::convert::From<SelectOptionCellData> for SelectedSelectOptions {
fn from(data: SelectOptionCellData) -> Self {
impl std::convert::From<SelectOptionCellDataPB> for SelectedSelectOptions {
fn from(data: SelectOptionCellDataPB) -> Self {
Self {
options: data.select_options,
}

View File

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

View File

@ -131,7 +131,7 @@ mod tests {
);
// Single select
let done_option = SelectOption::new("Done");
let done_option = SelectOptionPB::new("Done");
let done_option_id = done_option.id.clone();
let single_select = SingleSelectTypeOptionBuilder::default().option(done_option.clone());
let single_select_field_rev = FieldBuilder::new(single_select).build();
@ -151,8 +151,8 @@ mod tests {
);
// Multiple select
let google_option = SelectOption::new("Google");
let facebook_option = SelectOption::new("Facebook");
let google_option = SelectOptionPB::new("Google");
let facebook_option = SelectOptionPB::new("Facebook");
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 multi_select = MultiSelectTypeOptionBuilder::default()

View File

@ -3,7 +3,7 @@ mod tests {
use crate::entities::FieldType;
use crate::services::cell::{CellData, CellDataOperation};
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;
#[test]
@ -52,12 +52,12 @@ mod tests {
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,
type_option: &URLTypeOption,
field_rev: &FieldRevision,
field_type: &FieldType,
) -> URLCellData {
) -> URLCellDataPB {
type_option
.decode_cell_data(encoded_data.into(), field_type, field_rev)
.unwrap()

View File

@ -1,7 +1,7 @@
use crate::entities::FieldType;
use crate::impl_type_option;
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 fancy_regex::Regex;
use flowy_derive::ProtoBuf;
@ -32,22 +32,22 @@ pub struct URLTypeOption {
}
impl_type_option!(URLTypeOption, FieldType::URL);
impl CellDisplayable<URLCellData> for URLTypeOption {
impl CellDisplayable<URLCellDataPB> for URLTypeOption {
fn display_data(
&self,
cell_data: CellData<URLCellData>,
cell_data: CellData<URLCellDataPB>,
_decoded_field_type: &FieldType,
_field_rev: &FieldRevision,
) -> FlowyResult<CellBytes> {
let cell_data: URLCellData = cell_data.try_into_inner()?;
let cell_data: URLCellDataPB = cell_data.try_into_inner()?;
CellBytes::from(cell_data)
}
}
impl CellDataOperation<URLCellData, String> for URLTypeOption {
impl CellDataOperation<URLCellDataPB, String> for URLTypeOption {
fn decode_cell_data(
&self,
cell_data: CellData<URLCellData>,
cell_data: CellData<URLCellDataPB>,
decoded_field_type: &FieldType,
field_rev: &FieldRevision,
) -> FlowyResult<CellBytes> {
@ -67,7 +67,7 @@ impl CellDataOperation<URLCellData, String> for URLTypeOption {
if let Ok(Some(m)) = URL_REGEX.find(&content) {
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};
#[derive(Clone, Debug, Default, Serialize, Deserialize, ProtoBuf)]
pub struct URLCellData {
pub struct URLCellDataPB {
#[pb(index = 1)]
pub url: String,
@ -13,7 +13,7 @@ pub struct URLCellData {
pub content: String,
}
impl URLCellData {
impl URLCellDataPB {
pub fn new(s: &str) -> Self {
Self {
url: "".to_string(),
@ -28,15 +28,15 @@ impl URLCellData {
pub struct URLCellDataParser();
impl CellBytesParser for URLCellDataParser {
type Object = URLCellData;
type Object = URLCellDataPB;
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> {
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::entities::{FieldType, GridBlockChangeset};
use crate::entities::{FieldType, GridBlockChangesetPB};
use crate::services::block_manager::GridBlockManager;
use crate::services::cell::{AnyCellData, CellFilterOperation};
use crate::services::field::{
CheckboxTypeOption, DateTypeOption, MultiSelectTypeOption, NumberTypeOption, RichTextTypeOption,
SingleSelectTypeOption, URLTypeOption,
SingleSelectTypeOptionPB, URLTypeOption,
};
use crate::services::filter::filter_cache::{
refresh_filter_cache, FilterCache, FilterId, FilterResult, FilterResultCache,
@ -90,7 +90,7 @@ impl GridFilterService {
}
}
let changeset = GridBlockChangeset {
let changeset = GridBlockChangesetPB {
block_id: block.block_id,
hide_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 {
send_dart_notification(&self.grid_id, GridNotification::DidUpdateGridBlock)
.payload(changeset)
@ -213,7 +213,7 @@ fn filter_cell(
FieldType::SingleSelect => filter_cache.select_option_filter.get(&filter_id).and_then(|filter| {
Some(
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())
.ok(),
)

View File

@ -2,7 +2,7 @@
use crate::entities::{GridSelectOptionFilter, SelectOptionCondition};
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 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> {
if !any_cell_data.is_single_select() {
return Ok(true);
@ -64,13 +64,13 @@ impl CellFilterOperation<GridSelectOptionFilter> for SingleSelectTypeOption {
mod tests {
#![allow(clippy::all)]
use crate::entities::{GridSelectOptionFilter, SelectOptionCondition};
use crate::services::field::selection_type_option::{SelectOption, SelectedSelectOptions};
use crate::services::field::selection_type_option::{SelectOptionPB, SelectedSelectOptions};
#[test]
fn select_option_filter_is_test() {
let option_1 = SelectOption::new("A");
let option_2 = SelectOption::new("B");
let option_3 = SelectOption::new("C");
let option_1 = SelectOptionPB::new("A");
let option_2 = SelectOptionPB::new("B");
let option_3 = SelectOptionPB::new("C");
let filter_1 = GridSelectOptionFilter {
condition: SelectOptionCondition::OptionIs,

View File

@ -1,5 +1,5 @@
use crate::dart_notification::{send_dart_notification, GridNotification};
use crate::entities::CellIdentifier;
use crate::entities::CellIdentifierParams;
use crate::entities::*;
use crate::manager::{GridTaskSchedulerRwLock, GridUser};
use crate::services::block_manager::GridBlockManager;
@ -188,8 +188,8 @@ impl GridRevisionEditor {
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 field_order = FieldOrder::from(field_id);
let notified_changeset = GridFieldChangeset::delete(&self.grid_id, vec![field_order]);
let field_order = GridFieldIdPB::from(field_id);
let notified_changeset = GridFieldChangesetPB::delete(&self.grid_id, vec![field_order]);
let _ = self.notify_did_update_grid(notified_changeset).await?;
Ok(())
}
@ -268,13 +268,13 @@ impl GridRevisionEditor {
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 block_id = self.block_id().await?;
// insert empty row below the row whose id is upper_row_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
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)
}
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 mut rows_by_block_id: HashMap<String, Vec<RowRevision>> = HashMap::new();
let mut row_orders = vec![];
for row_rev in row_revs {
row_orders.push(RowInfo::from(&row_rev));
row_orders.push(GridRowPB::from(&row_rev));
rows_by_block_id
.entry(block_id.clone())
.or_insert_with(Vec::new)
@ -307,7 +307,7 @@ impl GridRevisionEditor {
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 mut grid_block_snapshot = self.grid_block_snapshots(Some(block_ids)).await?;
@ -339,12 +339,12 @@ impl GridRevisionEditor {
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?;
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 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)]
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() {
return Ok(());
}
let CellChangeset {
let CellChangesetPB {
grid_id,
row_id,
field_id,
@ -387,7 +387,7 @@ impl GridRevisionEditor {
let cell_rev = self.get_cell_rev(&row_id, &field_id).await?;
// Update the changeset.data property with the return value.
content = Some(apply_cell_data_changeset(content.unwrap(), cell_rev, field_rev)?);
let cell_changeset = CellChangeset {
let cell_changeset = CellChangesetPB {
grid_id,
row_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?;
make_grid_blocks(block_ids, block_snapshots)
}
@ -412,7 +412,7 @@ impl GridRevisionEditor {
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?;
for changeset in changesets {
let _ = self.update_block(changeset).await?;
@ -420,31 +420,31 @@ impl GridRevisionEditor {
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 field_orders = pad_read_guard
.get_field_revs(None)?
.iter()
.map(FieldOrder::from)
.map(GridFieldIdPB::from)
.collect();
let mut block_orders = vec![];
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 block_order = GridBlock {
let block_order = GridBlockPB {
id: block_rev.block_id.clone(),
row_infos: row_orders,
rows: row_orders,
};
block_orders.push(block_order);
}
Ok(Grid {
Ok(GridPB {
id: self.grid_id.clone(),
field_orders,
fields: field_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 grid_setting_rev = read_guard.get_grid_setting_rev();
let field_revs = read_guard.get_field_revs(None)?;
@ -495,11 +495,11 @@ impl GridRevisionEditor {
pub async fn move_item(&self, params: MoveItemParams) -> FlowyResult<()> {
match params.ty {
MoveItemType::MoveField => {
MoveItemTypePB::MoveField => {
self.move_field(&params.item_id, params.from_index, params.to_index)
.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)?))
.await?;
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 insert_field = IndexField::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangeset {
let delete_field_order = GridFieldIdPB::from(field_id);
let insert_field = IndexFieldPB::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangesetPB {
grid_id: self.grid_id.clone(),
inserted_fields: vec![insert_field],
deleted_fields: vec![delete_field_order],
@ -599,8 +599,8 @@ impl GridRevisionEditor {
#[tracing::instrument(level = "trace", skip_all, err)]
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) {
let index_field = IndexField::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangeset::insert(&self.grid_id, vec![index_field]);
let index_field = IndexFieldPB::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangesetPB::insert(&self.grid_id, vec![index_field]);
let _ = self.notify_did_update_grid(notified_changeset).await?;
}
Ok(())
@ -615,8 +615,8 @@ impl GridRevisionEditor {
.get_field_rev(field_id)
.map(|(index, field)| (index, field.clone()))
{
let updated_field = Field::from(field_rev);
let notified_changeset = GridFieldChangeset::update(&self.grid_id, vec![updated_field.clone()]);
let updated_field = GridFieldPB::from(field_rev);
let notified_changeset = GridFieldChangesetPB::update(&self.grid_id, vec![updated_field.clone()]);
let _ = self.notify_did_update_grid(notified_changeset).await?;
send_dart_notification(field_id, GridNotification::DidUpdateField)
@ -627,7 +627,7 @@ impl GridRevisionEditor {
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)
.payload(changeset)
.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_grid_data_model::revision::RowRevision;
use std::collections::HashMap;
@ -9,15 +9,15 @@ pub struct GridBlockSnapshot {
pub row_revs: Vec<Arc<RowRevision>>,
}
pub(crate) fn block_from_row_orders(row_orders: Vec<RowInfo>) -> Vec<GridBlock> {
let mut map: HashMap<String, GridBlock> = HashMap::new();
pub(crate) fn block_from_row_orders(row_orders: Vec<GridRowPB>) -> Vec<GridBlockPB> {
let mut map: HashMap<String, GridBlockPB> = HashMap::new();
row_orders.into_iter().for_each(|row_info| {
// Memory Optimization: escape clone block_id
let block_id = row_info.block_id().to_owned();
let cloned_block_id = block_id.clone();
map.entry(block_id)
.or_insert_with(|| GridBlock::new(&cloned_block_id, vec![]))
.row_infos
.or_insert_with(|| GridBlockPB::new(&cloned_block_id, vec![]))
.rows
.push(row_info);
});
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))
// }
pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<RowInfo> {
row_revs.iter().map(RowInfo::from).collect::<Vec<_>>()
pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<GridRowPB> {
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()
}
pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<Row> {
let make_row = |row_rev: &Arc<RowRevision>| Row {
pub(crate) fn make_rows_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<GridRowPB> {
let make_row = |row_rev: &Arc<RowRevision>| GridRowPB {
block_id: row_rev.block_id.clone(),
id: row_rev.id.clone(),
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(
block_ids: Option<Vec<String>>,
block_snapshots: Vec<GridBlockSnapshot>,
) -> FlowyResult<RepeatedGridBlock> {
) -> FlowyResult<RepeatedGridBlockPB> {
match block_ids {
None => Ok(block_snapshots
.into_iter()
.map(|snapshot| {
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()),
Some(block_ids) => {
let block_meta_data_map: HashMap<&String, &Vec<Arc<RowRevision>>> = block_snapshots
@ -77,7 +78,7 @@ pub(crate) fn make_grid_blocks(
None => {}
Some(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::{
GridLayout, GridLayoutType, GridSetting, RepeatedGridFilter, RepeatedGridGroup, RepeatedGridSort,
GridLayoutPB, GridLayoutType, GridSettingPB, RepeatedGridFilterPB, RepeatedGridGroupPB, RepeatedGridSortPB,
};
use flowy_grid_data_model::revision::{FieldRevision, GridSettingRevision};
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 filters_by_field_id = grid_setting_rev
.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
.into_iter()
.map(|(k, v)| (k, v.into()))
.collect::<HashMap<String, RepeatedGridFilter>>()
.collect::<HashMap<String, RepeatedGridFilterPB>>()
})
.unwrap_or_default();
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
.into_iter()
.map(|(k, v)| (k, v.into()))
.collect::<HashMap<String, RepeatedGridGroup>>()
.collect::<HashMap<String, RepeatedGridGroupPB>>()
})
.unwrap_or_default();
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
.into_iter()
.map(|(k, v)| (k, v.into()))
.collect::<HashMap<String, RepeatedGridSort>>()
.collect::<HashMap<String, RepeatedGridSortPB>>()
})
.unwrap_or_default();
GridSetting {
layouts: GridLayout::all(),
GridSettingPB {
layouts: GridLayoutPB::all(),
current_layout_type,
filters_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::util::GridRowTestBuilder;
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_data_model::revision::{
GridBlockMetaRevision, GridBlockMetaRevisionChangeset, RowMetaChangeset, RowRevision,
@ -96,7 +97,7 @@ impl GridRowTest {
let row_orders = row_ids
.into_iter()
.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.row_revs = self.get_row_revs().await;
@ -108,7 +109,7 @@ impl GridRowTest {
field_type,
expected,
} => {
let id = CellIdentifier {
let id = CellIdentifierParams {
grid_id: self.grid_id.clone(),
field_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 {
FieldType::RichText => {
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)
where
F: Fn(Vec<SelectOption>) -> SelectOption,
F: Fn(Vec<SelectOptionPB>) -> SelectOptionPB,
{
let field_id = self.builder.insert_single_select_cell(f);
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)
where
F: Fn(Vec<SelectOption>) -> Vec<SelectOption>,
F: Fn(Vec<SelectOptionPB>) -> Vec<SelectOptionPB>,
{
let field_id = self.builder.insert_multi_select_cell(f);
self.output_by_field_type.insert(

View File

@ -2,7 +2,7 @@ use flowy_grid::entities::FieldType;
use std::sync::Arc;
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_data_model::revision::{FieldRevision, RowRevision};
@ -44,7 +44,7 @@ impl<'a> GridRowTestBuilder<'a> {
}
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()),
time: None,
})
@ -71,10 +71,10 @@ impl<'a> GridRowTestBuilder<'a> {
pub fn insert_single_select_cell<F>(&mut self, f: F) -> String
where
F: Fn(Vec<SelectOption>) -> SelectOption,
F: Fn(Vec<SelectOptionPB>) -> SelectOptionPB,
{
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);
self.inner_builder
.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
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 type_option = MultiSelectTypeOption::from(&multi_select_field);

View File

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

View File

@ -1,9 +1,9 @@
use crate::grid::cell_test::script::CellScript::*;
use crate::grid::cell_test::script::GridCellTest;
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::{MultiSelectTypeOption, SingleSelectTypeOption};
use flowy_grid::services::field::{MultiSelectTypeOption, SingleSelectTypeOptionPB};
#[tokio::test]
async fn grid_cell_update() {
@ -24,7 +24,7 @@ async fn grid_cell_update() {
FieldType::Number => "123".to_string(),
FieldType::DateTime => make_date_cell_string("123"),
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()
}
FieldType::MultiSelect => {
@ -36,7 +36,7 @@ async fn grid_cell_update() {
};
scripts.push(UpdateCell {
changeset: CellChangeset {
changeset: CellChangesetPB {
grid_id: block_id.to_string(),
row_id: row_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::GridFieldTest;
use crate::grid::field_test::util::*;
use flowy_grid::services::field::selection_type_option::SelectOption;
use flowy_grid::services::field::SingleSelectTypeOption;
use flowy_grid::services::field::selection_type_option::SelectOptionPB;
use flowy_grid::services::field::SingleSelectTypeOptionPB;
use flowy_grid_data_model::revision::TypeOptionDataEntry;
use flowy_sync::entities::grid::FieldChangesetParams;
@ -71,8 +71,8 @@ async fn grid_update_field() {
let mut test = GridFieldTest::new().await;
let (params, single_select_field) = create_single_select_field(&test.grid_id());
let mut single_select_type_option = SingleSelectTypeOption::from(&single_select_field);
single_select_type_option.options.push(SelectOption::new("Unknown"));
let mut single_select_type_option = SingleSelectTypeOptionPB::from(&single_select_field);
single_select_type_option.options.push(SelectOptionPB::new("Unknown"));
let changeset = FieldChangesetParams {
field_id: single_select_field.id.clone(),
grid_id: test.grid_id(),

View File

@ -1,5 +1,5 @@
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_data_model::revision::*;
@ -17,7 +17,7 @@ pub fn create_text_field(grid_id: &str) -> (InsertFieldParams, FieldRevision) {
.protobuf_bytes()
.to_vec();
let field = Field {
let field = GridFieldPB {
id: field_rev.id,
name: field_rev.name,
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) {
let single_select = SingleSelectTypeOptionBuilder::default()
.option(SelectOption::new("Done"))
.option(SelectOption::new("Progress"));
.option(SelectOptionPB::new("Done"))
.option(SelectOptionPB::new("Progress"));
let field_rev = FieldBuilder::new(single_select).name("Name").visibility(true).build();
let cloned_field_rev = field_rev.clone();
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()
.protobuf_bytes()
.to_vec();
let field = Field {
let field = GridFieldPB {
id: field_rev.id,
name: field_rev.name,
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.
pub fn make_date_cell_string(s: &str) -> String {
serde_json::to_string(&DateCellChangeset {
serde_json::to_string(&DateCellChangesetPB {
date: Some(s.to_string()),
time: None,
})

View File

@ -3,7 +3,7 @@
#![allow(dead_code)]
#![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_data_model::revision::{FieldRevision, FieldTypeRevision};
use flowy_sync::entities::grid::{CreateGridFilterParams, DeleteFilterParams, GridSettingChangesetParams};
@ -15,7 +15,7 @@ pub enum FilterScript {
params: GridSettingChangesetParams,
},
InsertGridTableFilter {
payload: CreateGridFilterPayload,
payload: CreateGridFilterPayloadPB,
},
AssertTableFilterCount {
count: i32,
@ -26,7 +26,7 @@ pub enum FilterScript {
},
#[allow(dead_code)]
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::*;
use flowy_grid::entities::{CreateGridFilterPayload, FieldType, TextFilterCondition};
use flowy_grid::entities::{CreateGridFilterPayloadPB, FieldType, TextFilterCondition};
use flowy_grid_data_model::revision::FieldRevision;
#[tokio::test]
async fn grid_filter_create_test() {
let mut test = GridFilterTest::new().await;
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 }];
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();
// 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 }];
test.run_scripts(scripts).await;
}
@ -46,6 +46,6 @@ async fn grid_filter_delete_test() {
#[tokio::test]
async fn grid_filter_get_rows_test() {}
fn create_filter(field_rev: &FieldRevision, condition: TextFilterCondition, s: &str) -> CreateGridFilterPayload {
CreateGridFilterPayload::new(field_rev, condition, Some(s.to_owned()))
fn create_filter(field_rev: &FieldRevision, condition: TextFilterCondition, s: &str) -> CreateGridFilterPayloadPB {
CreateGridFilterPayloadPB::new(field_rev, condition, Some(s.to_owned()))
}

View File

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