row_cache.dart 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import 'dart:collection';
  2. import 'package:app_flowy/plugins/grid/application/cell/cell_service/cell_service.dart';
  3. import 'package:flowy_sdk/dispatch/dispatch.dart';
  4. import 'package:flowy_sdk/log.dart';
  5. import 'package:flowy_sdk/protobuf/flowy-grid/block_entities.pb.dart';
  6. import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
  7. import 'package:flowy_sdk/protobuf/flowy-grid/row_entities.pb.dart';
  8. import 'package:flutter/foundation.dart';
  9. import 'package:freezed_annotation/freezed_annotation.dart';
  10. part 'row_cache.freezed.dart';
  11. typedef RowUpdateCallback = void Function();
  12. abstract class IGridRowFieldNotifier {
  13. UnmodifiableListView<FieldPB> get fields;
  14. void onRowFieldsChanged(VoidCallback callback);
  15. void onRowFieldChanged(void Function(FieldPB) callback);
  16. void onRowDispose();
  17. }
  18. /// Cache the rows in memory
  19. /// Insert / delete / update row
  20. ///
  21. /// Read https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/frontend/grid for more information.
  22. class GridRowCache {
  23. final String gridId;
  24. final BlockPB block;
  25. /// _rows containers the current block's rows
  26. /// Use List to reverse the order of the GridRow.
  27. List<RowInfo> _rowInfos = [];
  28. /// Use Map for faster access the raw row data.
  29. final HashMap<String, RowPB> _rowByRowId;
  30. final GridCellCache _cellCache;
  31. final IGridRowFieldNotifier _fieldNotifier;
  32. final _RowChangesetNotifier _rowChangeReasonNotifier;
  33. UnmodifiableListView<RowInfo> get rows => UnmodifiableListView(_rowInfos);
  34. GridCellCache get cellCache => _cellCache;
  35. GridRowCache({
  36. required this.gridId,
  37. required this.block,
  38. required IGridRowFieldNotifier notifier,
  39. }) : _cellCache = GridCellCache(gridId: gridId),
  40. _rowByRowId = HashMap(),
  41. _rowChangeReasonNotifier = _RowChangesetNotifier(),
  42. _fieldNotifier = notifier {
  43. //
  44. notifier.onRowFieldsChanged(() => _rowChangeReasonNotifier
  45. .receive(const RowsChangedReason.fieldDidChange()));
  46. notifier.onRowFieldChanged(
  47. (field) => _cellCache.removeCellWithFieldId(field.id));
  48. _rowInfos = block.rows.map((rowPB) => buildGridRow(rowPB)).toList();
  49. }
  50. Future<void> dispose() async {
  51. _fieldNotifier.onRowDispose();
  52. _rowChangeReasonNotifier.dispose();
  53. await _cellCache.dispose();
  54. }
  55. void applyChangesets(List<GridBlockChangesetPB> changesets) {
  56. for (final changeset in changesets) {
  57. _deleteRows(changeset.deletedRows);
  58. _insertRows(changeset.insertedRows);
  59. _updateRows(changeset.updatedRows);
  60. _hideRows(changeset.hideRows);
  61. _showRows(changeset.visibleRows);
  62. }
  63. }
  64. void _deleteRows(List<String> deletedRows) {
  65. if (deletedRows.isEmpty) {
  66. return;
  67. }
  68. final List<RowInfo> newRows = [];
  69. final DeletedIndexs deletedIndex = [];
  70. final Map<String, String> deletedRowByRowId = {
  71. for (var rowId in deletedRows) rowId: rowId
  72. };
  73. _rowInfos.asMap().forEach((index, RowInfo rowInfo) {
  74. if (deletedRowByRowId[rowInfo.rowPB.id] == null) {
  75. newRows.add(rowInfo);
  76. } else {
  77. _rowByRowId.remove(rowInfo.rowPB.id);
  78. deletedIndex.add(DeletedIndex(index: index, row: rowInfo));
  79. }
  80. });
  81. _rowInfos = newRows;
  82. _rowChangeReasonNotifier.receive(RowsChangedReason.delete(deletedIndex));
  83. }
  84. void _insertRows(List<InsertedRowPB> insertRows) {
  85. if (insertRows.isEmpty) {
  86. return;
  87. }
  88. InsertedIndexs insertIndexs = [];
  89. for (final InsertedRowPB insertRow in insertRows) {
  90. final insertIndex = InsertedIndex(
  91. index: insertRow.index,
  92. rowId: insertRow.row.id,
  93. );
  94. insertIndexs.add(insertIndex);
  95. _rowInfos.insert(
  96. insertRow.index,
  97. (buildGridRow(insertRow.row)),
  98. );
  99. }
  100. _rowChangeReasonNotifier.receive(RowsChangedReason.insert(insertIndexs));
  101. }
  102. void _updateRows(List<RowPB> updatedRows) {
  103. if (updatedRows.isEmpty) {
  104. return;
  105. }
  106. final UpdatedIndexs updatedIndexs = UpdatedIndexs();
  107. for (final RowPB updatedRow in updatedRows) {
  108. final rowId = updatedRow.id;
  109. final index = _rowInfos.indexWhere(
  110. (rowInfo) => rowInfo.rowPB.id == rowId,
  111. );
  112. if (index != -1) {
  113. _rowByRowId[rowId] = updatedRow;
  114. _rowInfos.removeAt(index);
  115. _rowInfos.insert(index, buildGridRow(updatedRow));
  116. updatedIndexs[rowId] = UpdatedIndex(index: index, rowId: rowId);
  117. }
  118. }
  119. _rowChangeReasonNotifier.receive(RowsChangedReason.update(updatedIndexs));
  120. }
  121. void _hideRows(List<String> hideRows) {}
  122. void _showRows(List<String> visibleRows) {}
  123. void onRowsChanged(
  124. void Function(RowsChangedReason) onRowChanged,
  125. ) {
  126. _rowChangeReasonNotifier.addListener(() {
  127. onRowChanged(_rowChangeReasonNotifier.reason);
  128. });
  129. }
  130. RowUpdateCallback addListener({
  131. required String rowId,
  132. void Function(GridCellMap, RowsChangedReason)? onCellUpdated,
  133. bool Function()? listenWhen,
  134. }) {
  135. listenerHandler() async {
  136. if (listenWhen != null && listenWhen() == false) {
  137. return;
  138. }
  139. notifyUpdate() {
  140. if (onCellUpdated != null) {
  141. final row = _rowByRowId[rowId];
  142. if (row != null) {
  143. final GridCellMap cellDataMap = _makeGridCells(rowId, row);
  144. onCellUpdated(cellDataMap, _rowChangeReasonNotifier.reason);
  145. }
  146. }
  147. }
  148. _rowChangeReasonNotifier.reason.whenOrNull(
  149. update: (indexs) {
  150. if (indexs[rowId] != null) notifyUpdate();
  151. },
  152. fieldDidChange: () => notifyUpdate(),
  153. );
  154. }
  155. _rowChangeReasonNotifier.addListener(listenerHandler);
  156. return listenerHandler;
  157. }
  158. void removeRowListener(VoidCallback callback) {
  159. _rowChangeReasonNotifier.removeListener(callback);
  160. }
  161. GridCellMap loadGridCells(String rowId) {
  162. final RowPB? data = _rowByRowId[rowId];
  163. if (data == null) {
  164. _loadRow(rowId);
  165. }
  166. return _makeGridCells(rowId, data);
  167. }
  168. Future<void> _loadRow(String rowId) async {
  169. final payload = RowIdPB.create()
  170. ..gridId = gridId
  171. ..blockId = block.id
  172. ..rowId = rowId;
  173. final result = await GridEventGetRow(payload).send();
  174. result.fold(
  175. (optionRow) => _refreshRow(optionRow),
  176. (err) => Log.error(err),
  177. );
  178. }
  179. GridCellMap _makeGridCells(String rowId, RowPB? row) {
  180. // ignore: prefer_collection_literals
  181. var cellDataMap = GridCellMap();
  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((rowInfo) => rowInfo.rowPB.id == updatedRow.id);
  202. if (index != -1) {
  203. // update the corresponding row in _rows if they are not the same
  204. if (_rowInfos[index].rowPB != updatedRow) {
  205. final rowInfo = _rowInfos.removeAt(index).copyWith(rowPB: updatedRow);
  206. _rowInfos.insert(index, rowInfo);
  207. // Calculate the update index
  208. final UpdatedIndexs updatedIndexs = UpdatedIndexs();
  209. updatedIndexs[rowInfo.rowPB.id] = UpdatedIndex(
  210. index: index,
  211. rowId: rowInfo.rowPB.id,
  212. );
  213. //
  214. _rowChangeReasonNotifier
  215. .receive(RowsChangedReason.update(updatedIndexs));
  216. }
  217. }
  218. }
  219. RowInfo buildGridRow(RowPB rowPB) {
  220. return RowInfo(
  221. gridId: gridId,
  222. fields: _fieldNotifier.fields,
  223. rowPB: rowPB,
  224. );
  225. }
  226. }
  227. class _RowChangesetNotifier extends ChangeNotifier {
  228. RowsChangedReason reason = const InitialListState();
  229. _RowChangesetNotifier();
  230. void receive(RowsChangedReason newReason) {
  231. reason = newReason;
  232. reason.map(
  233. insert: (_) => notifyListeners(),
  234. delete: (_) => notifyListeners(),
  235. update: (_) => notifyListeners(),
  236. fieldDidChange: (_) => notifyListeners(),
  237. initial: (_) {},
  238. );
  239. }
  240. }
  241. @freezed
  242. class RowInfo with _$RowInfo {
  243. const factory RowInfo({
  244. required String gridId,
  245. required UnmodifiableListView<FieldPB> fields,
  246. required RowPB rowPB,
  247. }) = _RowInfo;
  248. }
  249. typedef InsertedIndexs = List<InsertedIndex>;
  250. typedef DeletedIndexs = List<DeletedIndex>;
  251. typedef UpdatedIndexs = LinkedHashMap<String, UpdatedIndex>;
  252. @freezed
  253. class RowsChangedReason with _$RowsChangedReason {
  254. const factory RowsChangedReason.insert(InsertedIndexs items) = _Insert;
  255. const factory RowsChangedReason.delete(DeletedIndexs items) = _Delete;
  256. const factory RowsChangedReason.update(UpdatedIndexs indexs) = _Update;
  257. const factory RowsChangedReason.fieldDidChange() = _FieldDidChange;
  258. const factory RowsChangedReason.initial() = InitialListState;
  259. }
  260. class InsertedIndex {
  261. final int index;
  262. final String rowId;
  263. InsertedIndex({
  264. required this.index,
  265. required this.rowId,
  266. });
  267. }
  268. class DeletedIndex {
  269. final int index;
  270. final RowInfo row;
  271. DeletedIndex({
  272. required this.index,
  273. required this.row,
  274. });
  275. }
  276. class UpdatedIndex {
  277. final int index;
  278. final String rowId;
  279. UpdatedIndex({
  280. required this.index,
  281. required this.rowId,
  282. });
  283. }