board_bloc.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import 'dart:async';
  2. import 'dart:collection';
  3. import 'package:app_flowy/plugins/grid/application/block/block_cache.dart';
  4. import 'package:app_flowy/plugins/grid/application/field/field_controller.dart';
  5. import 'package:app_flowy/plugins/grid/application/row/row_cache.dart';
  6. import 'package:app_flowy/plugins/grid/application/row/row_service.dart';
  7. import 'package:appflowy_board/appflowy_board.dart';
  8. import 'package:dartz/dartz.dart';
  9. import 'package:equatable/equatable.dart';
  10. import 'package:flowy_sdk/log.dart';
  11. import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart';
  12. import 'package:flowy_sdk/protobuf/flowy-folder/view.pb.dart';
  13. import 'package:flowy_sdk/protobuf/flowy-grid/protobuf.dart';
  14. import 'package:flutter_bloc/flutter_bloc.dart';
  15. import 'package:freezed_annotation/freezed_annotation.dart';
  16. import 'board_data_controller.dart';
  17. import 'group_controller.dart';
  18. part 'board_bloc.freezed.dart';
  19. class BoardBloc extends Bloc<BoardEvent, BoardState> {
  20. final BoardDataController _gridDataController;
  21. late final AppFlowyBoardController boardController;
  22. final MoveRowFFIService _rowService;
  23. LinkedHashMap<String, GroupController> groupControllers = LinkedHashMap();
  24. GridFieldController get fieldController =>
  25. _gridDataController.fieldController;
  26. String get gridId => _gridDataController.gridId;
  27. BoardBloc({required ViewPB view})
  28. : _rowService = MoveRowFFIService(gridId: view.id),
  29. _gridDataController = BoardDataController(view: view),
  30. super(BoardState.initial(view.id)) {
  31. boardController = AppFlowyBoardController(
  32. onMoveGroup: (
  33. fromGroupId,
  34. fromIndex,
  35. toGroupId,
  36. toIndex,
  37. ) {
  38. _moveGroup(fromGroupId, toGroupId);
  39. },
  40. onMoveGroupItem: (
  41. groupId,
  42. fromIndex,
  43. toIndex,
  44. ) {
  45. final fromRow = groupControllers[groupId]?.rowAtIndex(fromIndex);
  46. final toRow = groupControllers[groupId]?.rowAtIndex(toIndex);
  47. _moveRow(fromRow, groupId, toRow);
  48. },
  49. onMoveGroupItemToGroup: (
  50. fromGroupId,
  51. fromIndex,
  52. toGroupId,
  53. toIndex,
  54. ) {
  55. final fromRow = groupControllers[fromGroupId]?.rowAtIndex(fromIndex);
  56. final toRow = groupControllers[toGroupId]?.rowAtIndex(toIndex);
  57. _moveRow(fromRow, toGroupId, toRow);
  58. },
  59. );
  60. on<BoardEvent>(
  61. (event, emit) async {
  62. await event.when(
  63. initial: () async {
  64. _startListening();
  65. await _loadGrid(emit);
  66. },
  67. createBottomRow: (groupId) async {
  68. final startRowId = groupControllers[groupId]?.lastRow()?.id;
  69. final result = await _gridDataController.createBoardCard(
  70. groupId,
  71. startRowId: startRowId,
  72. );
  73. result.fold(
  74. (_) {},
  75. (err) => Log.error(err),
  76. );
  77. },
  78. createHeaderRow: (String groupId) async {
  79. final result = await _gridDataController.createBoardCard(groupId);
  80. result.fold(
  81. (_) {},
  82. (err) => Log.error(err),
  83. );
  84. },
  85. didCreateRow: (group, row, int? index) {
  86. emit(state.copyWith(
  87. editingRow: Some(BoardEditingRow(
  88. group: group,
  89. row: row,
  90. index: index,
  91. )),
  92. ));
  93. _groupItemStartEditing(group, row, true);
  94. },
  95. startEditingRow: (group, row) {
  96. emit(state.copyWith(
  97. editingRow: Some(BoardEditingRow(
  98. group: group,
  99. row: row,
  100. index: null,
  101. )),
  102. ));
  103. _groupItemStartEditing(group, row, true);
  104. },
  105. endEditingRow: (rowId) {
  106. state.editingRow.fold(() => null, (editingRow) {
  107. assert(editingRow.row.id == rowId);
  108. _groupItemStartEditing(editingRow.group, editingRow.row, false);
  109. emit(state.copyWith(editingRow: none()));
  110. });
  111. },
  112. didReceiveGridUpdate: (GridPB grid) {
  113. emit(state.copyWith(grid: Some(grid)));
  114. },
  115. didReceiveError: (FlowyError error) {
  116. emit(state.copyWith(noneOrError: some(error)));
  117. },
  118. didReceiveGroups: (List<GroupPB> groups) {
  119. emit(
  120. state.copyWith(
  121. groupIds: groups.map((group) => group.groupId).toList(),
  122. ),
  123. );
  124. },
  125. );
  126. },
  127. );
  128. }
  129. void _groupItemStartEditing(GroupPB group, RowPB row, bool isEdit) {
  130. final fieldContext = fieldController.getField(group.fieldId);
  131. if (fieldContext == null) {
  132. Log.warn("FieldContext should not be null");
  133. return;
  134. }
  135. boardController.enableGroupDragging(!isEdit);
  136. // boardController.updateGroupItem(
  137. // group.groupId,
  138. // GroupItem(
  139. // row: row,
  140. // fieldContext: fieldContext,
  141. // isDraggable: !isEdit,
  142. // ),
  143. // );
  144. }
  145. void _moveRow(RowPB? fromRow, String columnId, RowPB? toRow) {
  146. if (fromRow != null) {
  147. _rowService
  148. .moveGroupRow(
  149. fromRowId: fromRow.id,
  150. toGroupId: columnId,
  151. toRowId: toRow?.id,
  152. )
  153. .then((result) {
  154. result.fold((l) => null, (r) => add(BoardEvent.didReceiveError(r)));
  155. });
  156. }
  157. }
  158. void _moveGroup(String fromColumnId, String toColumnId) {
  159. _rowService
  160. .moveGroup(
  161. fromGroupId: fromColumnId,
  162. toGroupId: toColumnId,
  163. )
  164. .then((result) {
  165. result.fold((l) => null, (r) => add(BoardEvent.didReceiveError(r)));
  166. });
  167. }
  168. @override
  169. Future<void> close() async {
  170. await _gridDataController.dispose();
  171. for (final controller in groupControllers.values) {
  172. controller.dispose();
  173. }
  174. return super.close();
  175. }
  176. void initializeGroups(List<GroupPB> groupsData) {
  177. for (var controller in groupControllers.values) {
  178. controller.dispose();
  179. }
  180. groupControllers.clear();
  181. boardController.clear();
  182. //
  183. List<AppFlowyGroupData> groups = groupsData
  184. .where((group) => fieldController.getField(group.fieldId) != null)
  185. .map((group) {
  186. return AppFlowyGroupData(
  187. id: group.groupId,
  188. name: group.desc,
  189. items: _buildGroupItems(group),
  190. customData: GroupData(
  191. group: group,
  192. fieldContext: fieldController.getField(group.fieldId)!,
  193. ),
  194. );
  195. }).toList();
  196. boardController.addGroups(groups);
  197. for (final group in groupsData) {
  198. final delegate = GroupControllerDelegateImpl(
  199. controller: boardController,
  200. fieldController: fieldController,
  201. onNewColumnItem: (groupId, row, index) {
  202. add(BoardEvent.didCreateRow(group, row, index));
  203. },
  204. );
  205. final controller = GroupController(
  206. gridId: state.gridId,
  207. group: group,
  208. delegate: delegate,
  209. );
  210. controller.startListening();
  211. groupControllers[controller.group.groupId] = (controller);
  212. }
  213. }
  214. GridRowCache? getRowCache(String blockId) {
  215. final GridBlockCache? blockCache = _gridDataController.blocks[blockId];
  216. return blockCache?.rowCache;
  217. }
  218. void _startListening() {
  219. _gridDataController.addListener(
  220. onGridChanged: (grid) {
  221. if (!isClosed) {
  222. add(BoardEvent.didReceiveGridUpdate(grid));
  223. }
  224. },
  225. didLoadGroups: (groups) {
  226. if (isClosed) return;
  227. initializeGroups(groups);
  228. add(BoardEvent.didReceiveGroups(groups));
  229. },
  230. onDeletedGroup: (groupIds) {
  231. if (isClosed) return;
  232. //
  233. },
  234. onInsertedGroup: (insertedGroups) {
  235. if (isClosed) return;
  236. //
  237. },
  238. onUpdatedGroup: (updatedGroups) {
  239. if (isClosed) return;
  240. for (final group in updatedGroups) {
  241. final columnController =
  242. boardController.getGroupController(group.groupId);
  243. columnController?.updateGroupName(group.desc);
  244. }
  245. },
  246. onError: (err) {
  247. Log.error(err);
  248. },
  249. onResetGroups: (groups) {
  250. if (isClosed) return;
  251. initializeGroups(groups);
  252. add(BoardEvent.didReceiveGroups(groups));
  253. },
  254. );
  255. }
  256. List<AppFlowyGroupItem> _buildGroupItems(GroupPB group) {
  257. final items = group.rows.map((row) {
  258. final fieldContext = fieldController.getField(group.fieldId);
  259. return GroupItem(
  260. row: row,
  261. fieldContext: fieldContext!,
  262. );
  263. }).toList();
  264. return <AppFlowyGroupItem>[...items];
  265. }
  266. Future<void> _loadGrid(Emitter<BoardState> emit) async {
  267. final result = await _gridDataController.loadData();
  268. result.fold(
  269. (grid) => emit(
  270. state.copyWith(loadingState: GridLoadingState.finish(left(unit))),
  271. ),
  272. (err) => emit(
  273. state.copyWith(loadingState: GridLoadingState.finish(right(err))),
  274. ),
  275. );
  276. }
  277. }
  278. @freezed
  279. class BoardEvent with _$BoardEvent {
  280. const factory BoardEvent.initial() = _InitialBoard;
  281. const factory BoardEvent.createBottomRow(String groupId) = _CreateBottomRow;
  282. const factory BoardEvent.createHeaderRow(String groupId) = _CreateHeaderRow;
  283. const factory BoardEvent.didCreateRow(
  284. GroupPB group,
  285. RowPB row,
  286. int? index,
  287. ) = _DidCreateRow;
  288. const factory BoardEvent.startEditingRow(
  289. GroupPB group,
  290. RowPB row,
  291. ) = _StartEditRow;
  292. const factory BoardEvent.endEditingRow(String rowId) = _EndEditRow;
  293. const factory BoardEvent.didReceiveError(FlowyError error) = _DidReceiveError;
  294. const factory BoardEvent.didReceiveGridUpdate(
  295. GridPB grid,
  296. ) = _DidReceiveGridUpdate;
  297. const factory BoardEvent.didReceiveGroups(List<GroupPB> groups) =
  298. _DidReceiveGroups;
  299. }
  300. @freezed
  301. class BoardState with _$BoardState {
  302. const factory BoardState({
  303. required String gridId,
  304. required Option<GridPB> grid,
  305. required List<String> groupIds,
  306. required Option<BoardEditingRow> editingRow,
  307. required GridLoadingState loadingState,
  308. required Option<FlowyError> noneOrError,
  309. }) = _BoardState;
  310. factory BoardState.initial(String gridId) => BoardState(
  311. grid: none(),
  312. gridId: gridId,
  313. groupIds: [],
  314. editingRow: none(),
  315. noneOrError: none(),
  316. loadingState: const _Loading(),
  317. );
  318. }
  319. @freezed
  320. class GridLoadingState with _$GridLoadingState {
  321. const factory GridLoadingState.loading() = _Loading;
  322. const factory GridLoadingState.finish(
  323. Either<Unit, FlowyError> successOrFail) = _Finish;
  324. }
  325. class GridFieldEquatable extends Equatable {
  326. final UnmodifiableListView<FieldPB> _fields;
  327. const GridFieldEquatable(
  328. UnmodifiableListView<FieldPB> fields,
  329. ) : _fields = fields;
  330. @override
  331. List<Object?> get props {
  332. if (_fields.isEmpty) {
  333. return [];
  334. }
  335. return [
  336. _fields.length,
  337. _fields
  338. .map((field) => field.width)
  339. .reduce((value, element) => value + element),
  340. ];
  341. }
  342. UnmodifiableListView<FieldPB> get value => UnmodifiableListView(_fields);
  343. }
  344. class GroupItem extends AppFlowyGroupItem {
  345. final RowPB row;
  346. final GridFieldContext fieldContext;
  347. GroupItem({
  348. required this.row,
  349. required this.fieldContext,
  350. bool draggable = true,
  351. }) {
  352. super.draggable = draggable;
  353. }
  354. @override
  355. String get id => row.id;
  356. }
  357. class GroupControllerDelegateImpl extends GroupControllerDelegate {
  358. final GridFieldController fieldController;
  359. final AppFlowyBoardController controller;
  360. final void Function(String, RowPB, int?) onNewColumnItem;
  361. GroupControllerDelegateImpl({
  362. required this.controller,
  363. required this.fieldController,
  364. required this.onNewColumnItem,
  365. });
  366. @override
  367. void insertRow(GroupPB group, RowPB row, int? index) {
  368. final fieldContext = fieldController.getField(group.fieldId);
  369. if (fieldContext == null) {
  370. Log.warn("FieldContext should not be null");
  371. return;
  372. }
  373. if (index != null) {
  374. final item = GroupItem(
  375. row: row,
  376. fieldContext: fieldContext,
  377. );
  378. controller.insertGroupItem(group.groupId, index, item);
  379. } else {
  380. final item = GroupItem(
  381. row: row,
  382. fieldContext: fieldContext,
  383. );
  384. controller.addGroupItem(group.groupId, item);
  385. }
  386. }
  387. @override
  388. void removeRow(GroupPB group, String rowId) {
  389. controller.removeGroupItem(group.groupId, rowId);
  390. }
  391. @override
  392. void updateRow(GroupPB group, RowPB row) {
  393. final fieldContext = fieldController.getField(group.fieldId);
  394. if (fieldContext == null) {
  395. Log.warn("FieldContext should not be null");
  396. return;
  397. }
  398. controller.updateGroupItem(
  399. group.groupId,
  400. GroupItem(
  401. row: row,
  402. fieldContext: fieldContext,
  403. ),
  404. );
  405. }
  406. @override
  407. void addNewRow(GroupPB group, RowPB row, int? index) {
  408. final fieldContext = fieldController.getField(group.fieldId);
  409. if (fieldContext == null) {
  410. Log.warn("FieldContext should not be null");
  411. return;
  412. }
  413. final item = GroupItem(
  414. row: row,
  415. fieldContext: fieldContext,
  416. draggable: false,
  417. );
  418. if (index != null) {
  419. controller.insertGroupItem(group.groupId, index, item);
  420. } else {
  421. controller.addGroupItem(group.groupId, item);
  422. }
  423. onNewColumnItem(group.groupId, row, index);
  424. }
  425. }
  426. class BoardEditingRow {
  427. GroupPB group;
  428. RowPB row;
  429. int? index;
  430. BoardEditingRow({
  431. required this.group,
  432. required this.row,
  433. required this.index,
  434. });
  435. }
  436. class GroupData {
  437. final GroupPB group;
  438. final GridFieldContext fieldContext;
  439. GroupData({
  440. required this.group,
  441. required this.fieldContext,
  442. });
  443. CheckboxGroup? asCheckboxGroup() {
  444. if (fieldType != FieldType.Checkbox) return null;
  445. return CheckboxGroup(group);
  446. }
  447. FieldType get fieldType => fieldContext.fieldType;
  448. }
  449. class CheckboxGroup {
  450. final GroupPB group;
  451. CheckboxGroup(this.group);
  452. // Hardcode value: "Yes" that equal to the value defined in Rust
  453. // pub const CHECK: &str = "Yes";
  454. bool get isCheck => group.groupId == "Yes";
  455. }