refactor: rename struct & add documentation

This commit is contained in:
appflowy 2022-07-17 11:29:02 +08:00
parent c860d1bc0b
commit 8073414485
20 changed files with 127 additions and 137 deletions

View File

@ -13,7 +13,7 @@ class GridBlockCache {
late GridRowCache _rowCache; late GridRowCache _rowCache;
late GridBlockListener _listener; late GridBlockListener _listener;
List<GridRow> get rows => _rowCache.rows; List<GridRowInfo> get rows => _rowCache.rows;
GridRowCache get rowCache => _rowCache; GridRowCache get rowCache => _rowCache;
GridBlockCache({ GridBlockCache({

View File

@ -22,8 +22,8 @@ class GridBloc extends Bloc<GridEvent, GridState> {
// key: the block id // key: the block id
final LinkedHashMap<String, GridBlockCache> _blocks; final LinkedHashMap<String, GridBlockCache> _blocks;
List<GridRow> get rows { List<GridRowInfo> get rowInfos {
final List<GridRow> rows = []; final List<GridRowInfo> rows = [];
for (var block in _blocks.values) { for (var block in _blocks.values) {
rows.addAll(block.rows); rows.addAll(block.rows);
} }
@ -46,11 +46,11 @@ class GridBloc extends Bloc<GridEvent, GridState> {
createRow: () { createRow: () {
_gridService.createRow(); _gridService.createRow();
}, },
didReceiveRowUpdate: (rows, reason) { didReceiveRowUpdate: (newRowInfos, reason) {
emit(state.copyWith(rows: rows, reason: reason)); emit(state.copyWith(rowInfos: newRowInfos, reason: reason));
}, },
didReceiveFieldUpdate: (fields) { didReceiveFieldUpdate: (fields) {
emit(state.copyWith(rows: rows, fields: GridFieldEquatable(fields))); emit(state.copyWith(rowInfos: rowInfos, fields: GridFieldEquatable(fields)));
}, },
); );
}, },
@ -94,7 +94,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
} }
Future<void> _loadFields(Grid grid, Emitter<GridState> emit) async { Future<void> _loadFields(Grid grid, Emitter<GridState> emit) async {
final result = await _gridService.getFields(fieldOrders: grid.fieldOrders); final result = await _gridService.getFields(fieldOrders: grid.fields);
return Future( return Future(
() => result.fold( () => result.fold(
(fields) { (fields) {
@ -103,7 +103,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
emit(state.copyWith( emit(state.copyWith(
grid: Some(grid), grid: Some(grid),
fields: GridFieldEquatable(fieldCache.fields), fields: GridFieldEquatable(fieldCache.fields),
rows: rows, rowInfos: rowInfos,
loadingState: GridLoadingState.finish(left(unit)), loadingState: GridLoadingState.finish(left(unit)),
)); ));
}, },
@ -127,7 +127,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
cache.addListener( cache.addListener(
listenWhen: () => !isClosed, listenWhen: () => !isClosed,
onChangeReason: (reason) => add(GridEvent.didReceiveRowUpdate(rows, reason)), onChangeReason: (reason) => add(GridEvent.didReceiveRowUpdate(rowInfos, reason)),
); );
_blocks[block.id] = cache; _blocks[block.id] = cache;
@ -139,7 +139,8 @@ class GridBloc extends Bloc<GridEvent, GridState> {
class GridEvent with _$GridEvent { class GridEvent with _$GridEvent {
const factory GridEvent.initial() = InitialGrid; const factory GridEvent.initial() = InitialGrid;
const factory GridEvent.createRow() = _CreateRow; const factory GridEvent.createRow() = _CreateRow;
const factory GridEvent.didReceiveRowUpdate(List<GridRow> rows, GridRowChangeReason listState) = _DidReceiveRowUpdate; const factory GridEvent.didReceiveRowUpdate(List<GridRowInfo> rows, GridRowChangeReason listState) =
_DidReceiveRowUpdate;
const factory GridEvent.didReceiveFieldUpdate(List<Field> fields) = _DidReceiveFieldUpdate; const factory GridEvent.didReceiveFieldUpdate(List<Field> fields) = _DidReceiveFieldUpdate;
} }
@ -149,14 +150,14 @@ class GridState with _$GridState {
required String gridId, required String gridId,
required Option<Grid> grid, required Option<Grid> grid,
required GridFieldEquatable fields, required GridFieldEquatable fields,
required List<GridRow> rows, required List<GridRowInfo> rowInfos,
required GridLoadingState loadingState, required GridLoadingState loadingState,
required GridRowChangeReason reason, required GridRowChangeReason reason,
}) = _GridState; }) = _GridState;
factory GridState.initial(String gridId) => GridState( factory GridState.initial(String gridId) => GridState(
fields: const GridFieldEquatable([]), fields: const GridFieldEquatable([]),
rows: [], rowInfos: [],
grid: none(), grid: none(),
gridId: gridId, gridId: gridId,
loadingState: const _Loading(), loadingState: const _Loading(),

View File

@ -32,7 +32,7 @@ class GridService {
return GridEventCreateRow(payload).send(); return GridEventCreateRow(payload).send();
} }
Future<Either<RepeatedField, FlowyError>> getFields({required List<FieldOrder> fieldOrders}) { Future<Either<RepeatedField, FlowyError>> getFields({required List<GridField> fieldOrders}) {
final payload = QueryFieldPayload.create() final payload = QueryFieldPayload.create()
..gridId = gridId ..gridId = gridId
..fieldOrders = RepeatedFieldOrder(items: fieldOrders); ..fieldOrders = RepeatedFieldOrder(items: fieldOrders);
@ -141,12 +141,12 @@ class GridFieldCache {
} }
} }
void _deleteFields(List<FieldOrder> deletedFields) { void _deleteFields(List<GridField> deletedFields) {
if (deletedFields.isEmpty) { if (deletedFields.isEmpty) {
return; return;
} }
final List<Field> newFields = fields; final List<Field> newFields = fields;
final Map<String, FieldOrder> deletedFieldMap = { final Map<String, GridField> deletedFieldMap = {
for (var fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder for (var fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder
}; };

View File

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

View File

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

View File

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

View File

@ -32,7 +32,7 @@ class GridRowCache {
/// _rows containers the current block's rows /// _rows containers the current block's rows
/// Use List to reverse the order of the GridRow. /// Use List to reverse the order of the GridRow.
List<GridRow> _rows = []; List<GridRowInfo> _rowInfos = [];
/// Use Map for faster access the raw row data. /// Use Map for faster access the raw row data.
final HashMap<String, Row> _rowByRowId; final HashMap<String, Row> _rowByRowId;
@ -41,7 +41,7 @@ class GridRowCache {
final GridRowCacheFieldNotifier _fieldNotifier; final GridRowCacheFieldNotifier _fieldNotifier;
final _GridRowChangesetNotifier _rowChangeReasonNotifier; final _GridRowChangesetNotifier _rowChangeReasonNotifier;
UnmodifiableListView<GridRow> get rows => UnmodifiableListView(_rows); UnmodifiableListView<GridRowInfo> get rows => UnmodifiableListView(_rowInfos);
GridCellCache get cellCache => _cellCache; GridCellCache get cellCache => _cellCache;
GridRowCache({ GridRowCache({
@ -55,7 +55,7 @@ class GridRowCache {
// //
notifier.onFieldsChanged(() => _rowChangeReasonNotifier.receive(const GridRowChangeReason.fieldDidChange())); notifier.onFieldsChanged(() => _rowChangeReasonNotifier.receive(const GridRowChangeReason.fieldDidChange()));
notifier.onFieldChanged((field) => _cellCache.remove(field.id)); notifier.onFieldChanged((field) => _cellCache.remove(field.id));
_rows = block.rowInfos.map((rowInfo) => buildGridRow(rowInfo.rowId, rowInfo.height.toDouble())).toList(); _rowInfos = block.rows.map((rowInfo) => buildGridRow(rowInfo.id, rowInfo.height.toDouble())).toList();
} }
Future<void> dispose() async { Future<void> dispose() async {
@ -79,11 +79,11 @@ class GridRowCache {
return; return;
} }
final List<GridRow> newRows = []; final List<GridRowInfo> newRows = [];
final DeletedIndexs deletedIndex = []; final DeletedIndexs deletedIndex = [];
final Map<String, String> deletedRowByRowId = {for (var rowId in deletedRows) rowId: rowId}; final Map<String, String> deletedRowByRowId = {for (var rowId in deletedRows) rowId: rowId};
_rows.asMap().forEach((index, row) { _rowInfos.asMap().forEach((index, row) {
if (deletedRowByRowId[row.id] == null) { if (deletedRowByRowId[row.id] == null) {
newRows.add(row); newRows.add(row);
} else { } else {
@ -91,7 +91,7 @@ class GridRowCache {
deletedIndex.add(DeletedIndex(index: index, row: row)); deletedIndex.add(DeletedIndex(index: index, row: row));
} }
}); });
_rows = newRows; _rowInfos = newRows;
_rowChangeReasonNotifier.receive(GridRowChangeReason.delete(deletedIndex)); _rowChangeReasonNotifier.receive(GridRowChangeReason.delete(deletedIndex));
} }
@ -107,7 +107,7 @@ class GridRowCache {
rowId: insertRow.rowId, rowId: insertRow.rowId,
); );
insertIndexs.add(insertIndex); insertIndexs.add(insertIndex);
_rows.insert(insertRow.index, (buildGridRow(insertRow.rowId, insertRow.height.toDouble()))); _rowInfos.insert(insertRow.index, (buildGridRow(insertRow.rowId, insertRow.height.toDouble())));
} }
_rowChangeReasonNotifier.receive(GridRowChangeReason.insert(insertIndexs)); _rowChangeReasonNotifier.receive(GridRowChangeReason.insert(insertIndexs));
@ -121,12 +121,12 @@ class GridRowCache {
final UpdatedIndexs updatedIndexs = UpdatedIndexs(); final UpdatedIndexs updatedIndexs = UpdatedIndexs();
for (final updatedRow in updatedRows) { for (final updatedRow in updatedRows) {
final rowId = updatedRow.rowId; final rowId = updatedRow.rowId;
final index = _rows.indexWhere((row) => row.id == rowId); final index = _rowInfos.indexWhere((row) => row.id == rowId);
if (index != -1) { if (index != -1) {
_rowByRowId[rowId] = updatedRow.row; _rowByRowId[rowId] = updatedRow.row;
_rows.removeAt(index); _rowInfos.removeAt(index);
_rows.insert(index, buildGridRow(rowId, updatedRow.row.height.toDouble())); _rowInfos.insert(index, buildGridRow(rowId, updatedRow.row.height.toDouble()));
updatedIndexs[rowId] = UpdatedIndex(index: index, rowId: rowId); updatedIndexs[rowId] = UpdatedIndex(index: index, rowId: rowId);
} }
} }
@ -225,12 +225,12 @@ class GridRowCache {
updatedRow.freeze(); updatedRow.freeze();
_rowByRowId[updatedRow.id] = updatedRow; _rowByRowId[updatedRow.id] = updatedRow;
final index = _rows.indexWhere((gridRow) => gridRow.id == updatedRow.id); final index = _rowInfos.indexWhere((gridRow) => gridRow.id == updatedRow.id);
if (index != -1) { if (index != -1) {
// update the corresponding row in _rows if they are not the same // update the corresponding row in _rows if they are not the same
if (_rows[index].rawRow != updatedRow) { if (_rowInfos[index].rawRow != updatedRow) {
final row = _rows.removeAt(index).copyWith(rawRow: updatedRow); final row = _rowInfos.removeAt(index).copyWith(rawRow: updatedRow);
_rows.insert(index, row); _rowInfos.insert(index, row);
// Calculate the update index // Calculate the update index
final UpdatedIndexs updatedIndexs = UpdatedIndexs(); final UpdatedIndexs updatedIndexs = UpdatedIndexs();
@ -242,8 +242,8 @@ class GridRowCache {
} }
} }
GridRow buildGridRow(String rowId, double rowHeight) { GridRowInfo buildGridRow(String rowId, double rowHeight) {
return GridRow( return GridRowInfo(
gridId: gridId, gridId: gridId,
blockId: block.id, blockId: block.id,
fields: _fieldNotifier.fields, fields: _fieldNotifier.fields,
@ -325,15 +325,15 @@ class RowService {
} }
@freezed @freezed
class GridRow with _$GridRow { class GridRowInfo with _$GridRowInfo {
const factory GridRow({ const factory GridRowInfo({
required String gridId, required String gridId,
required String blockId, required String blockId,
required String id, required String id,
required UnmodifiableListView<Field> fields, required UnmodifiableListView<Field> fields,
required double height, required double height,
Row? rawRow, Row? rawRow,
}) = _GridRow; }) = _GridRowInfo;
} }
typedef InsertedIndexs = List<InsertedIndex>; typedef InsertedIndexs = List<InsertedIndex>;
@ -360,7 +360,7 @@ class InsertedIndex {
class DeletedIndex { class DeletedIndex {
final int index; final int index;
final GridRow row; final GridRowInfo row;
DeletedIndex({ DeletedIndex({
required this.index, required this.index,
required this.row, required this.row,

View File

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

View File

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

View File

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

View File

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

View File

@ -10,33 +10,33 @@ pub struct GridBlock {
pub id: String, pub id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub row_infos: Vec<RowInfo>, pub rows: Vec<Row>,
} }
impl GridBlock { impl GridBlock {
pub fn new(block_id: &str, row_orders: Vec<RowInfo>) -> Self { pub fn new(block_id: &str, rows: Vec<Row>) -> Self {
Self { Self {
id: block_id.to_owned(), id: block_id.to_owned(),
row_infos: row_orders, rows,
} }
} }
} }
#[derive(Debug, Default, Clone, ProtoBuf)] #[derive(Debug, Default, Clone, ProtoBuf)]
pub struct RowInfo { pub struct Row {
#[pb(index = 1)] #[pb(index = 1)]
pub block_id: String, pub block_id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub row_id: String, pub id: String,
#[pb(index = 3)] #[pb(index = 3)]
pub height: i32, pub height: i32,
} }
impl RowInfo { impl Row {
pub fn row_id(&self) -> &str { pub fn row_id(&self) -> &str {
&self.row_id &self.id
} }
pub fn block_id(&self) -> &str { pub fn block_id(&self) -> &str {
@ -44,35 +44,26 @@ impl RowInfo {
} }
} }
impl std::convert::From<&RowRevision> for RowInfo { impl std::convert::From<&RowRevision> for Row {
fn from(rev: &RowRevision) -> Self { fn from(rev: &RowRevision) -> Self {
Self { Self {
block_id: rev.block_id.clone(), block_id: rev.block_id.clone(),
row_id: rev.id.clone(), id: rev.id.clone(),
height: rev.height, height: rev.height,
} }
} }
} }
impl std::convert::From<&Arc<RowRevision>> for RowInfo { impl std::convert::From<&Arc<RowRevision>> for Row {
fn from(rev: &Arc<RowRevision>) -> Self { fn from(rev: &Arc<RowRevision>) -> Self {
Self { Self {
block_id: rev.block_id.clone(), block_id: rev.block_id.clone(),
row_id: rev.id.clone(), id: rev.id.clone(),
height: rev.height, height: rev.height,
} }
} }
} }
#[derive(Debug, Default, ProtoBuf)]
pub struct Row {
#[pb(index = 1)]
pub id: String,
#[pb(index = 2)]
pub height: i32,
}
#[derive(Debug, Default, ProtoBuf)] #[derive(Debug, Default, ProtoBuf)]
pub struct OptionalRow { pub struct OptionalRow {
#[pb(index = 1, one_of)] #[pb(index = 1, one_of)]
@ -139,10 +130,10 @@ impl UpdatedRow {
} }
} }
impl std::convert::From<RowInfo> for InsertedRow { impl std::convert::From<Row> for InsertedRow {
fn from(row_info: RowInfo) -> Self { fn from(row_info: Row) -> Self {
Self { Self {
row_id: row_info.row_id, row_id: row_info.id,
block_id: row_info.block_id, block_id: row_info.block_id,
height: row_info.height, height: row_info.height,
index: None, index: None,
@ -152,7 +143,7 @@ impl std::convert::From<RowInfo> for InsertedRow {
impl std::convert::From<&RowRevision> for InsertedRow { impl std::convert::From<&RowRevision> for InsertedRow {
fn from(row: &RowRevision) -> Self { fn from(row: &RowRevision) -> Self {
let row_order = RowInfo::from(row); let row_order = Row::from(row);
Self::from(row_order) Self::from(row_order)
} }
} }

View File

@ -57,24 +57,24 @@ impl std::convert::From<Arc<FieldRevision>> for Field {
} }
} }
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct FieldOrder { pub struct GridField {
#[pb(index = 1)] #[pb(index = 1)]
pub field_id: String, pub field_id: String,
} }
impl std::convert::From<&str> for FieldOrder { impl std::convert::From<&str> for GridField {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
FieldOrder { field_id: s.to_owned() } GridField { field_id: s.to_owned() }
} }
} }
impl std::convert::From<String> for FieldOrder { impl std::convert::From<String> for GridField {
fn from(s: String) -> Self { fn from(s: String) -> Self {
FieldOrder { field_id: s } GridField { field_id: s }
} }
} }
impl std::convert::From<&Arc<FieldRevision>> for FieldOrder { impl std::convert::From<&Arc<FieldRevision>> for GridField {
fn from(field_rev: &Arc<FieldRevision>) -> Self { fn from(field_rev: &Arc<FieldRevision>) -> Self {
Self { Self {
field_id: field_rev.id.clone(), field_id: field_rev.id.clone(),
@ -90,7 +90,7 @@ pub struct GridFieldChangeset {
pub inserted_fields: Vec<IndexField>, pub inserted_fields: Vec<IndexField>,
#[pb(index = 3)] #[pb(index = 3)]
pub deleted_fields: Vec<FieldOrder>, pub deleted_fields: Vec<GridField>,
#[pb(index = 4)] #[pb(index = 4)]
pub updated_fields: Vec<Field>, pub updated_fields: Vec<Field>,
@ -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<GridField>) -> Self {
Self { Self {
grid_id: grid_id.to_string(), grid_id: grid_id.to_string(),
inserted_fields: vec![], inserted_fields: vec![],
@ -259,18 +259,18 @@ impl std::convert::From<Vec<Field>> for RepeatedField {
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct RepeatedFieldOrder { pub struct RepeatedFieldOrder {
#[pb(index = 1)] #[pb(index = 1)]
pub items: Vec<FieldOrder>, pub items: Vec<GridField>,
} }
impl std::ops::Deref for RepeatedFieldOrder { impl std::ops::Deref for RepeatedFieldOrder {
type Target = Vec<FieldOrder>; type Target = Vec<GridField>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.items &self.items
} }
} }
impl std::convert::From<Vec<FieldOrder>> for RepeatedFieldOrder { impl std::convert::From<Vec<GridField>> for RepeatedFieldOrder {
fn from(field_orders: Vec<FieldOrder>) -> Self { fn from(field_orders: Vec<GridField>) -> Self {
RepeatedFieldOrder { items: field_orders } RepeatedFieldOrder { items: field_orders }
} }
} }
@ -278,7 +278,7 @@ impl std::convert::From<Vec<FieldOrder>> for RepeatedFieldOrder {
impl std::convert::From<String> for RepeatedFieldOrder { impl std::convert::From<String> for RepeatedFieldOrder {
fn from(s: String) -> Self { fn from(s: String) -> Self {
RepeatedFieldOrder { RepeatedFieldOrder {
items: vec![FieldOrder::from(s)], items: vec![GridField::from(s)],
} }
} }
} }

View File

@ -1,4 +1,4 @@
use crate::entities::{FieldOrder, GridBlock}; use crate::entities::{GridBlock, GridField};
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyStr; use flowy_grid_data_model::parser::NotEmptyStr;
@ -8,7 +8,7 @@ pub struct Grid {
pub id: String, pub id: String,
#[pb(index = 2)] #[pb(index = 2)]
pub field_orders: Vec<FieldOrder>, pub fields: Vec<GridField>,
#[pb(index = 3)] #[pb(index = 3)]
pub blocks: Vec<GridBlock>, pub blocks: Vec<GridBlock>,

View File

@ -1,5 +1,5 @@
use crate::dart_notification::{send_dart_notification, GridNotification}; use crate::dart_notification::{send_dart_notification, GridNotification};
use crate::entities::{CellChangeset, GridBlockChangeset, InsertedRow, Row, RowInfo, UpdatedRow}; use crate::entities::{CellChangeset, GridBlockChangeset, InsertedRow, Row, UpdatedRow};
use crate::manager::GridUser; use crate::manager::GridUser;
use crate::services::block_revision_editor::GridBlockRevisionEditor; use crate::services::block_revision_editor::GridBlockRevisionEditor;
use crate::services::persistence::block_index::BlockIndexCache; use crate::services::persistence::block_index::BlockIndexCache;
@ -138,7 +138,7 @@ impl GridBlockManager {
Some(row_info) => { Some(row_info) => {
let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?; let _ = editor.delete_rows(vec![Cow::Borrowed(&row_id)]).await?;
let _ = self let _ = self
.notify_did_update_block(&block_id, GridBlockChangeset::delete(&block_id, vec![row_info.row_id])) .notify_did_update_block(&block_id, GridBlockChangeset::delete(&block_id, vec![row_info.id]))
.await?; .await?;
} }
} }
@ -146,15 +146,12 @@ impl GridBlockManager {
Ok(()) Ok(())
} }
pub(crate) async fn delete_rows( pub(crate) async fn delete_rows(&self, row_orders: Vec<Row>) -> FlowyResult<Vec<GridBlockMetaRevisionChangeset>> {
&self,
row_orders: Vec<RowInfo>,
) -> FlowyResult<Vec<GridBlockMetaRevisionChangeset>> {
let mut changesets = vec![]; let mut changesets = vec![];
for grid_block in block_from_row_orders(row_orders) { for grid_block in block_from_row_orders(row_orders) {
let editor = self.get_editor(&grid_block.id).await?; let editor = self.get_editor(&grid_block.id).await?;
let row_ids = grid_block let row_ids = grid_block
.row_infos .rows
.into_iter() .into_iter()
.map(|row_info| Cow::Owned(row_info.row_id().to_owned())) .map(|row_info| Cow::Owned(row_info.row_id().to_owned()))
.collect::<Vec<Cow<String>>>(); .collect::<Vec<Cow<String>>>();
@ -217,7 +214,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<Row>> {
let editor = self.get_editor(block_id).await?; let editor = self.get_editor(block_id).await?;
editor.get_row_infos::<&str>(None).await editor.get_row_infos::<&str>(None).await
} }

View File

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

View File

@ -189,7 +189,7 @@ impl GridRevisionEditor {
pub async fn delete_field(&self, field_id: &str) -> FlowyResult<()> { pub async fn delete_field(&self, field_id: &str) -> FlowyResult<()> {
let _ = self.modify(|grid_pad| Ok(grid_pad.delete_field_rev(field_id)?)).await?; let _ = self.modify(|grid_pad| Ok(grid_pad.delete_field_rev(field_id)?)).await?;
let field_order = FieldOrder::from(field_id); let field_order = GridField::from(field_id);
let notified_changeset = GridFieldChangeset::delete(&self.grid_id, vec![field_order]); let notified_changeset = GridFieldChangeset::delete(&self.grid_id, vec![field_order]);
let _ = self.notify_did_update_grid(notified_changeset).await?; let _ = self.notify_did_update_grid(notified_changeset).await?;
Ok(()) Ok(())
@ -269,14 +269,14 @@ impl GridRevisionEditor {
Ok(()) Ok(())
} }
pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<RowInfo> { pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<Row> {
let field_revs = self.grid_pad.read().await.get_field_revs(None)?; let field_revs = self.grid_pad.read().await.get_field_revs(None)?;
let block_id = self.block_id().await?; let block_id = self.block_id().await?;
// insert empty row below the row whose id is upper_row_id // insert empty row below the row whose id is upper_row_id
let row_rev_ctx = CreateRowRevisionBuilder::new(&field_revs).build(); let row_rev_ctx = CreateRowRevisionBuilder::new(&field_revs).build();
let row_rev = make_row_rev_from_context(&block_id, row_rev_ctx); let row_rev = make_row_rev_from_context(&block_id, row_rev_ctx);
let row_order = RowInfo::from(&row_rev); let row_order = Row::from(&row_rev);
// insert the row // insert the row
let row_count = self.block_manager.create_row(&block_id, row_rev, start_row_id).await?; let row_count = self.block_manager.create_row(&block_id, row_rev, start_row_id).await?;
@ -287,13 +287,13 @@ impl GridRevisionEditor {
Ok(row_order) Ok(row_order)
} }
pub async fn insert_rows(&self, contexts: Vec<CreateRowRevisionPayload>) -> FlowyResult<Vec<RowInfo>> { pub async fn insert_rows(&self, contexts: Vec<CreateRowRevisionPayload>) -> FlowyResult<Vec<Row>> {
let block_id = self.block_id().await?; let block_id = self.block_id().await?;
let mut rows_by_block_id: HashMap<String, Vec<RowRevision>> = HashMap::new(); let mut rows_by_block_id: HashMap<String, Vec<RowRevision>> = HashMap::new();
let mut row_orders = vec![]; let mut row_orders = vec![];
for ctx in contexts { for ctx in contexts {
let row_rev = make_row_rev_from_context(&block_id, ctx); let row_rev = make_row_rev_from_context(&block_id, ctx);
row_orders.push(RowInfo::from(&row_rev)); row_orders.push(Row::from(&row_rev));
rows_by_block_id rows_by_block_id
.entry(block_id.clone()) .entry(block_id.clone())
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
@ -421,7 +421,7 @@ impl GridRevisionEditor {
Ok(block_meta_revs) Ok(block_meta_revs)
} }
pub async fn delete_rows(&self, row_orders: Vec<RowInfo>) -> FlowyResult<()> { pub async fn delete_rows(&self, row_orders: Vec<Row>) -> FlowyResult<()> {
let changesets = self.block_manager.delete_rows(row_orders).await?; let changesets = self.block_manager.delete_rows(row_orders).await?;
for changeset in changesets { for changeset in changesets {
let _ = self.update_block(changeset).await?; let _ = self.update_block(changeset).await?;
@ -434,21 +434,21 @@ impl GridRevisionEditor {
let field_orders = pad_read_guard let field_orders = pad_read_guard
.get_field_revs(None)? .get_field_revs(None)?
.iter() .iter()
.map(FieldOrder::from) .map(GridField::from)
.collect(); .collect();
let mut block_orders = vec![]; let mut block_orders = vec![];
for block_rev in pad_read_guard.get_block_meta_revs() { for block_rev in pad_read_guard.get_block_meta_revs() {
let row_orders = self.block_manager.get_row_orders(&block_rev.block_id).await?; let row_orders = self.block_manager.get_row_orders(&block_rev.block_id).await?;
let block_order = GridBlock { let block_order = GridBlock {
id: block_rev.block_id.clone(), id: block_rev.block_id.clone(),
row_infos: row_orders, rows: row_orders,
}; };
block_orders.push(block_order); block_orders.push(block_order);
} }
Ok(Grid { Ok(Grid {
id: self.grid_id.clone(), id: self.grid_id.clone(),
field_orders, fields: field_orders,
blocks: block_orders, blocks: block_orders,
}) })
} }
@ -517,7 +517,7 @@ impl GridRevisionEditor {
.modify(|grid_pad| Ok(grid_pad.move_field(field_id, from as usize, to as usize)?)) .modify(|grid_pad| Ok(grid_pad.move_field(field_id, from as usize, to as usize)?))
.await?; .await?;
if let Some((index, field_rev)) = self.grid_pad.read().await.get_field_rev(field_id) { if let Some((index, field_rev)) = self.grid_pad.read().await.get_field_rev(field_id) {
let delete_field_order = FieldOrder::from(field_id); let delete_field_order = GridField::from(field_id);
let insert_field = IndexField::from_field_rev(field_rev, index); let insert_field = IndexField::from_field_rev(field_rev, index);
let notified_changeset = GridFieldChangeset { let notified_changeset = GridFieldChangeset {
grid_id: self.grid_id.clone(), grid_id: self.grid_id.clone(),

View File

@ -1,4 +1,4 @@
use crate::entities::{GridBlock, RepeatedGridBlock, Row, RowInfo}; use crate::entities::{GridBlock, RepeatedGridBlock, Row};
use flowy_error::FlowyResult; use flowy_error::FlowyResult;
use flowy_grid_data_model::revision::{FieldRevision, RowRevision}; use flowy_grid_data_model::revision::{FieldRevision, RowRevision};
use std::collections::HashMap; use std::collections::HashMap;
@ -9,7 +9,7 @@ pub struct GridBlockSnapshot {
pub row_revs: Vec<Arc<RowRevision>>, pub row_revs: Vec<Arc<RowRevision>>,
} }
pub(crate) fn block_from_row_orders(row_orders: Vec<RowInfo>) -> Vec<GridBlock> { pub(crate) fn block_from_row_orders(row_orders: Vec<Row>) -> Vec<GridBlock> {
let mut map: HashMap<String, GridBlock> = HashMap::new(); let mut map: HashMap<String, GridBlock> = HashMap::new();
row_orders.into_iter().for_each(|row_info| { row_orders.into_iter().for_each(|row_info| {
// Memory Optimization: escape clone block_id // Memory Optimization: escape clone block_id
@ -17,7 +17,7 @@ pub(crate) fn block_from_row_orders(row_orders: Vec<RowInfo>) -> Vec<GridBlock>
let cloned_block_id = block_id.clone(); let cloned_block_id = block_id.clone();
map.entry(block_id) map.entry(block_id)
.or_insert_with(|| GridBlock::new(&cloned_block_id, vec![])) .or_insert_with(|| GridBlock::new(&cloned_block_id, vec![]))
.row_infos .rows
.push(row_info); .push(row_info);
}); });
map.into_values().collect::<Vec<_>>() map.into_values().collect::<Vec<_>>()
@ -35,8 +35,8 @@ pub(crate) fn block_from_row_orders(row_orders: Vec<RowInfo>) -> Vec<GridBlock>
// Some((field_id, cell)) // Some((field_id, cell))
// } // }
pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<RowInfo> { pub(crate) fn make_row_orders_from_row_revs(row_revs: &[Arc<RowRevision>]) -> Vec<Row> {
row_revs.iter().map(RowInfo::from).collect::<Vec<_>>() row_revs.iter().map(Row::from).collect::<Vec<_>>()
} }
pub(crate) fn make_row_from_row_rev(fields: &[Arc<FieldRevision>], row_rev: Arc<RowRevision>) -> Option<Row> { pub(crate) fn make_row_from_row_rev(fields: &[Arc<FieldRevision>], row_rev: Arc<RowRevision>) -> Option<Row> {
@ -58,6 +58,7 @@ pub(crate) fn make_rows_from_row_revs(_fields: &[Arc<FieldRevision>], row_revs:
// .collect::<HashMap<String, Cell>>(); // .collect::<HashMap<String, Cell>>();
Row { Row {
block_id: row_rev.block_id.clone(),
id: row_rev.id.clone(), id: row_rev.id.clone(),
height: row_rev.height, height: row_rev.height,
} }

View File

@ -1,5 +1,5 @@
use crate::grid::grid_editor::GridEditorTest; use crate::grid::grid_editor::GridEditorTest;
use flowy_grid::entities::RowInfo; use flowy_grid::entities::Row;
use flowy_grid::services::row::{CreateRowRevisionBuilder, CreateRowRevisionPayload}; use flowy_grid::services::row::{CreateRowRevisionBuilder, CreateRowRevisionPayload};
use flowy_grid_data_model::revision::{ use flowy_grid_data_model::revision::{
FieldRevision, GridBlockMetaRevision, GridBlockMetaRevisionChangeset, RowMetaChangeset, RowRevision, FieldRevision, GridBlockMetaRevision, GridBlockMetaRevisionChangeset, RowMetaChangeset, RowRevision,
@ -90,7 +90,7 @@ impl GridRowTest {
let row_orders = row_ids let row_orders = row_ids
.into_iter() .into_iter()
.map(|row_id| self.row_order_by_row_id.get(&row_id).unwrap().clone()) .map(|row_id| self.row_order_by_row_id.get(&row_id).unwrap().clone())
.collect::<Vec<RowInfo>>(); .collect::<Vec<Row>>();
self.editor.delete_rows(row_orders).await.unwrap(); self.editor.delete_rows(row_orders).await.unwrap();
self.row_revs = self.get_row_revs().await; self.row_revs = self.get_row_revs().await;

View File

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