row_service.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import 'dart:collection';
  2. import 'package:app_flowy/plugins/grid/application/cell/cell_service/cell_service.dart';
  3. import 'package:dartz/dartz.dart';
  4. import 'package:flowy_sdk/dispatch/dispatch.dart';
  5. import 'package:flowy_sdk/log.dart';
  6. import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart';
  7. import 'package:flowy_sdk/protobuf/flowy-grid/block_entities.pb.dart';
  8. import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
  9. import 'package:flowy_sdk/protobuf/flowy-grid/grid_entities.pb.dart';
  10. import 'package:flowy_sdk/protobuf/flowy-grid/row_entities.pb.dart';
  11. import 'package:flutter/foundation.dart';
  12. import 'package:freezed_annotation/freezed_annotation.dart';
  13. part 'row_service.freezed.dart';
  14. typedef RowUpdateCallback = void Function();
  15. abstract class GridRowCacheFieldNotifier {
  16. UnmodifiableListView<GridFieldPB> get fields;
  17. void onFieldsChanged(VoidCallback callback);
  18. void onFieldChanged(void Function(GridFieldPB) callback);
  19. void dispose();
  20. }
  21. /// Cache the rows in memory
  22. /// Insert / delete / update row
  23. ///
  24. /// Read https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/frontend/grid for more information.
  25. class GridRowCache {
  26. final String gridId;
  27. final GridBlockPB block;
  28. /// _rows containers the current block's rows
  29. /// Use List to reverse the order of the GridRow.
  30. List<GridRowInfo> _rowInfos = [];
  31. /// Use Map for faster access the raw row data.
  32. final HashMap<String, GridRowPB> _rowByRowId;
  33. final GridCellCache _cellCache;
  34. final GridRowCacheFieldNotifier _fieldNotifier;
  35. final _GridRowChangesetNotifier _rowChangeReasonNotifier;
  36. UnmodifiableListView<GridRowInfo> get rows => UnmodifiableListView(_rowInfos);
  37. GridCellCache get cellCache => _cellCache;
  38. GridRowCache({
  39. required this.gridId,
  40. required this.block,
  41. required GridRowCacheFieldNotifier notifier,
  42. }) : _cellCache = GridCellCache(gridId: gridId),
  43. _rowByRowId = HashMap(),
  44. _rowChangeReasonNotifier = _GridRowChangesetNotifier(),
  45. _fieldNotifier = notifier {
  46. //
  47. notifier.onFieldsChanged(() => _rowChangeReasonNotifier
  48. .receive(const GridRowChangeReason.fieldDidChange()));
  49. notifier.onFieldChanged((field) => _cellCache.remove(field.id));
  50. _rowInfos = block.rows
  51. .map((rowInfo) => buildGridRow(rowInfo.id, rowInfo.height.toDouble()))
  52. .toList();
  53. }
  54. Future<void> dispose() async {
  55. _fieldNotifier.dispose();
  56. _rowChangeReasonNotifier.dispose();
  57. await _cellCache.dispose();
  58. }
  59. void applyChangesets(List<GridBlockChangesetPB> changesets) {
  60. for (final changeset in changesets) {
  61. _deleteRows(changeset.deletedRows);
  62. _insertRows(changeset.insertedRows);
  63. _updateRows(changeset.updatedRows);
  64. _hideRows(changeset.hideRows);
  65. _showRows(changeset.visibleRows);
  66. }
  67. }
  68. void _deleteRows(List<String> deletedRows) {
  69. if (deletedRows.isEmpty) {
  70. return;
  71. }
  72. final List<GridRowInfo> newRows = [];
  73. final DeletedIndexs deletedIndex = [];
  74. final Map<String, String> deletedRowByRowId = {
  75. for (var rowId in deletedRows) rowId: rowId
  76. };
  77. _rowInfos.asMap().forEach((index, row) {
  78. if (deletedRowByRowId[row.id] == null) {
  79. newRows.add(row);
  80. } else {
  81. _rowByRowId.remove(row.id);
  82. deletedIndex.add(DeletedIndex(index: index, row: row));
  83. }
  84. });
  85. _rowInfos = newRows;
  86. _rowChangeReasonNotifier.receive(GridRowChangeReason.delete(deletedIndex));
  87. }
  88. void _insertRows(List<InsertedRowPB> insertRows) {
  89. if (insertRows.isEmpty) {
  90. return;
  91. }
  92. InsertedIndexs insertIndexs = [];
  93. for (final insertRow in insertRows) {
  94. final insertIndex = InsertedIndex(
  95. index: insertRow.index,
  96. rowId: insertRow.rowId,
  97. );
  98. insertIndexs.add(insertIndex);
  99. _rowInfos.insert(insertRow.index,
  100. (buildGridRow(insertRow.rowId, insertRow.height.toDouble())));
  101. }
  102. _rowChangeReasonNotifier.receive(GridRowChangeReason.insert(insertIndexs));
  103. }
  104. void _updateRows(List<UpdatedRowPB> updatedRows) {
  105. if (updatedRows.isEmpty) {
  106. return;
  107. }
  108. final UpdatedIndexs updatedIndexs = UpdatedIndexs();
  109. for (final updatedRow in updatedRows) {
  110. final rowId = updatedRow.rowId;
  111. final index = _rowInfos.indexWhere((row) => row.id == rowId);
  112. if (index != -1) {
  113. _rowByRowId[rowId] = updatedRow.row;
  114. _rowInfos.removeAt(index);
  115. _rowInfos.insert(
  116. index, buildGridRow(rowId, updatedRow.row.height.toDouble()));
  117. updatedIndexs[rowId] = UpdatedIndex(index: index, rowId: rowId);
  118. }
  119. }
  120. _rowChangeReasonNotifier.receive(GridRowChangeReason.update(updatedIndexs));
  121. }
  122. void _hideRows(List<String> hideRows) {}
  123. void _showRows(List<String> visibleRows) {}
  124. void onRowsChanged(
  125. void Function(GridRowChangeReason) onRowChanged,
  126. ) {
  127. _rowChangeReasonNotifier.addListener(() {
  128. onRowChanged(_rowChangeReasonNotifier.reason);
  129. });
  130. }
  131. RowUpdateCallback addListener({
  132. required String rowId,
  133. void Function(GridCellMap, GridRowChangeReason)? onCellUpdated,
  134. bool Function()? listenWhen,
  135. }) {
  136. listenerHandler() async {
  137. if (listenWhen != null && listenWhen() == false) {
  138. return;
  139. }
  140. notifyUpdate() {
  141. if (onCellUpdated != null) {
  142. final row = _rowByRowId[rowId];
  143. if (row != null) {
  144. final GridCellMap cellDataMap = _makeGridCells(rowId, row);
  145. onCellUpdated(cellDataMap, _rowChangeReasonNotifier.reason);
  146. }
  147. }
  148. }
  149. _rowChangeReasonNotifier.reason.whenOrNull(
  150. update: (indexs) {
  151. if (indexs[rowId] != null) notifyUpdate();
  152. },
  153. fieldDidChange: () => notifyUpdate(),
  154. );
  155. }
  156. _rowChangeReasonNotifier.addListener(listenerHandler);
  157. return listenerHandler;
  158. }
  159. void removeRowListener(VoidCallback callback) {
  160. _rowChangeReasonNotifier.removeListener(callback);
  161. }
  162. GridCellMap loadGridCells(String rowId) {
  163. final GridRowPB? data = _rowByRowId[rowId];
  164. if (data == null) {
  165. _loadRow(rowId);
  166. }
  167. return _makeGridCells(rowId, data);
  168. }
  169. Future<void> _loadRow(String rowId) async {
  170. final payload = GridRowIdPB.create()
  171. ..gridId = gridId
  172. ..blockId = block.id
  173. ..rowId = rowId;
  174. final result = await GridEventGetRow(payload).send();
  175. result.fold(
  176. (optionRow) => _refreshRow(optionRow),
  177. (err) => Log.error(err),
  178. );
  179. }
  180. GridCellMap _makeGridCells(String rowId, GridRowPB? row) {
  181. var cellDataMap = GridCellMap.new();
  182. for (final field in _fieldNotifier.fields) {
  183. if (field.visibility) {
  184. cellDataMap[field.id] = GridCellIdentifier(
  185. rowId: rowId,
  186. gridId: gridId,
  187. field: field,
  188. );
  189. }
  190. }
  191. return cellDataMap;
  192. }
  193. void _refreshRow(OptionalRowPB optionRow) {
  194. if (!optionRow.hasRow()) {
  195. return;
  196. }
  197. final updatedRow = optionRow.row;
  198. updatedRow.freeze();
  199. _rowByRowId[updatedRow.id] = updatedRow;
  200. final index =
  201. _rowInfos.indexWhere((gridRow) => gridRow.id == updatedRow.id);
  202. if (index != -1) {
  203. // update the corresponding row in _rows if they are not the same
  204. if (_rowInfos[index].rawRow != updatedRow) {
  205. final row = _rowInfos.removeAt(index).copyWith(rawRow: updatedRow);
  206. _rowInfos.insert(index, row);
  207. // Calculate the update index
  208. final UpdatedIndexs updatedIndexs = UpdatedIndexs();
  209. updatedIndexs[row.id] = UpdatedIndex(index: index, rowId: row.id);
  210. //
  211. _rowChangeReasonNotifier
  212. .receive(GridRowChangeReason.update(updatedIndexs));
  213. }
  214. }
  215. }
  216. GridRowInfo buildGridRow(String rowId, double rowHeight) {
  217. return GridRowInfo(
  218. gridId: gridId,
  219. blockId: block.id,
  220. fields: _fieldNotifier.fields,
  221. id: rowId,
  222. height: rowHeight,
  223. );
  224. }
  225. }
  226. class _GridRowChangesetNotifier extends ChangeNotifier {
  227. GridRowChangeReason reason = const InitialListState();
  228. _GridRowChangesetNotifier();
  229. void receive(GridRowChangeReason newReason) {
  230. reason = newReason;
  231. reason.map(
  232. insert: (_) => notifyListeners(),
  233. delete: (_) => notifyListeners(),
  234. update: (_) => notifyListeners(),
  235. fieldDidChange: (_) => notifyListeners(),
  236. initial: (_) {},
  237. );
  238. }
  239. }
  240. class RowService {
  241. final String gridId;
  242. final String blockId;
  243. final String rowId;
  244. RowService(
  245. {required this.gridId, required this.blockId, required this.rowId});
  246. Future<Either<GridRowPB, FlowyError>> createRow() {
  247. CreateRowPayloadPB payload = CreateRowPayloadPB.create()
  248. ..gridId = gridId
  249. ..startRowId = rowId;
  250. return GridEventCreateRow(payload).send();
  251. }
  252. Future<Either<Unit, FlowyError>> moveRow(
  253. String rowId, int fromIndex, int toIndex) {
  254. final payload = MoveItemPayloadPB.create()
  255. ..gridId = gridId
  256. ..itemId = rowId
  257. ..ty = MoveItemTypePB.MoveRow
  258. ..fromIndex = fromIndex
  259. ..toIndex = toIndex;
  260. return GridEventMoveItem(payload).send();
  261. }
  262. Future<Either<OptionalRowPB, FlowyError>> getRow() {
  263. final payload = GridRowIdPB.create()
  264. ..gridId = gridId
  265. ..blockId = blockId
  266. ..rowId = rowId;
  267. return GridEventGetRow(payload).send();
  268. }
  269. Future<Either<Unit, FlowyError>> deleteRow() {
  270. final payload = GridRowIdPB.create()
  271. ..gridId = gridId
  272. ..blockId = blockId
  273. ..rowId = rowId;
  274. return GridEventDeleteRow(payload).send();
  275. }
  276. Future<Either<Unit, FlowyError>> duplicateRow() {
  277. final payload = GridRowIdPB.create()
  278. ..gridId = gridId
  279. ..blockId = blockId
  280. ..rowId = rowId;
  281. return GridEventDuplicateRow(payload).send();
  282. }
  283. }
  284. @freezed
  285. class GridRowInfo with _$GridRowInfo {
  286. const factory GridRowInfo({
  287. required String gridId,
  288. required String blockId,
  289. required String id,
  290. required UnmodifiableListView<GridFieldPB> fields,
  291. required double height,
  292. GridRowPB? rawRow,
  293. }) = _GridRowInfo;
  294. }
  295. typedef InsertedIndexs = List<InsertedIndex>;
  296. typedef DeletedIndexs = List<DeletedIndex>;
  297. typedef UpdatedIndexs = LinkedHashMap<String, UpdatedIndex>;
  298. @freezed
  299. class GridRowChangeReason with _$GridRowChangeReason {
  300. const factory GridRowChangeReason.insert(InsertedIndexs items) = _Insert;
  301. const factory GridRowChangeReason.delete(DeletedIndexs items) = _Delete;
  302. const factory GridRowChangeReason.update(UpdatedIndexs indexs) = _Update;
  303. const factory GridRowChangeReason.fieldDidChange() = _FieldDidChange;
  304. const factory GridRowChangeReason.initial() = InitialListState;
  305. }
  306. class InsertedIndex {
  307. final int index;
  308. final String rowId;
  309. InsertedIndex({
  310. required this.index,
  311. required this.rowId,
  312. });
  313. }
  314. class DeletedIndex {
  315. final int index;
  316. final GridRowInfo row;
  317. DeletedIndex({
  318. required this.index,
  319. required this.row,
  320. });
  321. }
  322. class UpdatedIndex {
  323. final int index;
  324. final String rowId;
  325. UpdatedIndex({
  326. required this.index,
  327. required this.rowId,
  328. });
  329. }