row_cache.dart 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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/row_entities.pb.dart';
  8. import 'package:flutter/foundation.dart';
  9. import 'package:freezed_annotation/freezed_annotation.dart';
  10. import 'row_list.dart';
  11. part 'row_cache.freezed.dart';
  12. typedef RowUpdateCallback = void Function();
  13. abstract class IGridRowFieldNotifier {
  14. UnmodifiableListView<FieldInfo> get fields;
  15. void onRowFieldsChanged(VoidCallback callback);
  16. void onRowFieldChanged(void Function(FieldInfo) 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. final RowList _rowList = RowList();
  29. final GridCellCache _cellCache;
  30. final IGridRowFieldNotifier _fieldNotifier;
  31. final _RowChangesetNotifier _rowChangeReasonNotifier;
  32. UnmodifiableListView<RowInfo> get visibleRows {
  33. var visibleRows = [..._rowList.rows];
  34. visibleRows.retainWhere((element) => element.visible);
  35. return UnmodifiableListView(visibleRows);
  36. }
  37. GridCellCache get cellCache => _cellCache;
  38. GridRowCache({
  39. required this.gridId,
  40. required this.block,
  41. required IGridRowFieldNotifier notifier,
  42. }) : _cellCache = GridCellCache(gridId: gridId),
  43. _rowChangeReasonNotifier = _RowChangesetNotifier(),
  44. _fieldNotifier = notifier {
  45. //
  46. notifier.onRowFieldsChanged(() => _rowChangeReasonNotifier
  47. .receive(const RowsChangedReason.fieldDidChange()));
  48. notifier.onRowFieldChanged(
  49. (field) => _cellCache.removeCellWithFieldId(field.id));
  50. for (final row in block.rows) {
  51. final rowInfo = buildGridRow(row);
  52. _rowList.add(rowInfo);
  53. }
  54. }
  55. Future<void> dispose() async {
  56. _fieldNotifier.onRowDispose();
  57. _rowChangeReasonNotifier.dispose();
  58. await _cellCache.dispose();
  59. }
  60. void applyChangesets(GridBlockChangesetPB changeset) {
  61. _deleteRows(changeset.deletedRows);
  62. _insertRows(changeset.insertedRows);
  63. _updateRows(changeset.updatedRows);
  64. _hideRows(changeset.invisibleRows);
  65. _showRows(changeset.visibleRows);
  66. }
  67. void _deleteRows(List<String> deletedRowIds) {
  68. for (final rowId in deletedRowIds) {
  69. final deletedRow = _rowList.remove(rowId);
  70. if (deletedRow != null) {
  71. _rowChangeReasonNotifier.receive(RowsChangedReason.delete(deletedRow));
  72. }
  73. }
  74. }
  75. void _insertRows(List<InsertedRowPB> insertRows) {
  76. for (final insertedRow in insertRows) {
  77. final insertedIndex =
  78. _rowList.insert(insertedRow.index, buildGridRow(insertedRow.row));
  79. if (insertedIndex != null) {
  80. _rowChangeReasonNotifier
  81. .receive(RowsChangedReason.insert(insertedIndex));
  82. }
  83. }
  84. }
  85. void _updateRows(List<RowPB> updatedRows) {
  86. if (updatedRows.isEmpty) return;
  87. final updatedIndexs =
  88. _rowList.updateRows(updatedRows, (rowPB) => buildGridRow(rowPB));
  89. if (updatedIndexs.isNotEmpty) {
  90. _rowChangeReasonNotifier.receive(RowsChangedReason.update(updatedIndexs));
  91. }
  92. }
  93. void _hideRows(List<String> invisibleRows) {
  94. for (final rowId in invisibleRows) {
  95. final deletedRow = _rowList.remove(rowId);
  96. if (deletedRow != null) {
  97. _rowChangeReasonNotifier.receive(RowsChangedReason.delete(deletedRow));
  98. }
  99. }
  100. }
  101. void _showRows(List<InsertedRowPB> visibleRows) {
  102. for (final insertedRow in visibleRows) {
  103. final insertedIndex =
  104. _rowList.insert(insertedRow.index, buildGridRow(insertedRow.row));
  105. if (insertedIndex != null) {
  106. _rowChangeReasonNotifier
  107. .receive(RowsChangedReason.insert(insertedIndex));
  108. }
  109. }
  110. }
  111. void onRowsChanged(void Function(RowsChangedReason) onRowChanged) {
  112. _rowChangeReasonNotifier.addListener(() {
  113. onRowChanged(_rowChangeReasonNotifier.reason);
  114. });
  115. }
  116. RowUpdateCallback addListener({
  117. required String rowId,
  118. void Function(GridCellMap, RowsChangedReason)? onCellUpdated,
  119. bool Function()? listenWhen,
  120. }) {
  121. listenerHandler() async {
  122. if (listenWhen != null && listenWhen() == false) {
  123. return;
  124. }
  125. notifyUpdate() {
  126. if (onCellUpdated != null) {
  127. final rowInfo = _rowList.get(rowId);
  128. if (rowInfo != null) {
  129. final GridCellMap cellDataMap =
  130. _makeGridCells(rowId, rowInfo.rowPB);
  131. onCellUpdated(cellDataMap, _rowChangeReasonNotifier.reason);
  132. }
  133. }
  134. }
  135. _rowChangeReasonNotifier.reason.whenOrNull(
  136. update: (indexs) {
  137. if (indexs[rowId] != null) notifyUpdate();
  138. },
  139. fieldDidChange: () => notifyUpdate(),
  140. );
  141. }
  142. _rowChangeReasonNotifier.addListener(listenerHandler);
  143. return listenerHandler;
  144. }
  145. void removeRowListener(VoidCallback callback) {
  146. _rowChangeReasonNotifier.removeListener(callback);
  147. }
  148. GridCellMap loadGridCells(String rowId) {
  149. final RowPB? data = _rowList.get(rowId)?.rowPB;
  150. if (data == null) {
  151. _loadRow(rowId);
  152. }
  153. return _makeGridCells(rowId, data);
  154. }
  155. Future<void> _loadRow(String rowId) async {
  156. final payload = RowIdPB.create()
  157. ..gridId = gridId
  158. ..blockId = block.id
  159. ..rowId = rowId;
  160. final result = await GridEventGetRow(payload).send();
  161. result.fold(
  162. (optionRow) => _refreshRow(optionRow),
  163. (err) => Log.error(err),
  164. );
  165. }
  166. GridCellMap _makeGridCells(String rowId, RowPB? row) {
  167. // ignore: prefer_collection_literals
  168. var cellDataMap = GridCellMap();
  169. for (final field in _fieldNotifier.fields) {
  170. if (field.visibility) {
  171. cellDataMap[field.id] = GridCellIdentifier(
  172. rowId: rowId,
  173. gridId: gridId,
  174. fieldInfo: field,
  175. );
  176. }
  177. }
  178. return cellDataMap;
  179. }
  180. void _refreshRow(OptionalRowPB optionRow) {
  181. if (!optionRow.hasRow()) {
  182. return;
  183. }
  184. final updatedRow = optionRow.row;
  185. updatedRow.freeze();
  186. final rowInfo = _rowList.get(updatedRow.id);
  187. final rowIndex = _rowList.indexOfRow(updatedRow.id);
  188. if (rowInfo != null && rowIndex != null) {
  189. final updatedRowInfo = rowInfo.copyWith(rowPB: updatedRow);
  190. _rowList.remove(updatedRow.id);
  191. _rowList.insert(rowIndex, updatedRowInfo);
  192. final UpdatedIndexMap updatedIndexs = UpdatedIndexMap();
  193. updatedIndexs[rowInfo.rowPB.id] = UpdatedIndex(
  194. index: rowIndex,
  195. rowId: updatedRowInfo.rowPB.id,
  196. );
  197. _rowChangeReasonNotifier.receive(RowsChangedReason.update(updatedIndexs));
  198. }
  199. }
  200. RowInfo buildGridRow(RowPB rowPB) {
  201. return RowInfo(
  202. gridId: gridId,
  203. fields: _fieldNotifier.fields,
  204. rowPB: rowPB,
  205. visible: true,
  206. );
  207. }
  208. }
  209. class _RowChangesetNotifier extends ChangeNotifier {
  210. RowsChangedReason reason = const InitialListState();
  211. _RowChangesetNotifier();
  212. void receive(RowsChangedReason newReason) {
  213. reason = newReason;
  214. reason.map(
  215. insert: (_) => notifyListeners(),
  216. delete: (_) => notifyListeners(),
  217. update: (_) => notifyListeners(),
  218. fieldDidChange: (_) => notifyListeners(),
  219. initial: (_) {},
  220. );
  221. }
  222. }
  223. @unfreezed
  224. class RowInfo with _$RowInfo {
  225. factory RowInfo({
  226. required String gridId,
  227. required UnmodifiableListView<FieldInfo> fields,
  228. required RowPB rowPB,
  229. required bool visible,
  230. }) = _RowInfo;
  231. }
  232. typedef InsertedIndexs = List<InsertedIndex>;
  233. typedef DeletedIndexs = List<DeletedIndex>;
  234. // key: id of the row
  235. // value: UpdatedIndex
  236. typedef UpdatedIndexMap = LinkedHashMap<String, UpdatedIndex>;
  237. @freezed
  238. class RowsChangedReason with _$RowsChangedReason {
  239. const factory RowsChangedReason.insert(InsertedIndex item) = _Insert;
  240. const factory RowsChangedReason.delete(DeletedIndex item) = _Delete;
  241. const factory RowsChangedReason.update(UpdatedIndexMap indexs) = _Update;
  242. const factory RowsChangedReason.fieldDidChange() = _FieldDidChange;
  243. const factory RowsChangedReason.initial() = InitialListState;
  244. }
  245. class InsertedIndex {
  246. final int index;
  247. final String rowId;
  248. InsertedIndex({
  249. required this.index,
  250. required this.rowId,
  251. });
  252. }
  253. class DeletedIndex {
  254. final int index;
  255. final RowInfo rowInfo;
  256. DeletedIndex({
  257. required this.index,
  258. required this.rowInfo,
  259. });
  260. }
  261. class UpdatedIndex {
  262. final int index;
  263. final String rowId;
  264. UpdatedIndex({
  265. required this.index,
  266. required this.rowId,
  267. });
  268. }