row_cache.dart 9.3 KB

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