board_bloc.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import 'dart:async';
  2. import 'dart:collection';
  3. import 'package:app_flowy/plugins/grid/application/field/field_controller.dart';
  4. import 'package:app_flowy/plugins/grid/application/row/row_cache.dart';
  5. import 'package:app_flowy/plugins/grid/application/row/row_service.dart';
  6. import 'package:appflowy_board/appflowy_board.dart';
  7. import 'package:dartz/dartz.dart';
  8. import 'package:equatable/equatable.dart';
  9. import 'package:appflowy_backend/log.dart';
  10. import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
  11. import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
  12. import 'package:appflowy_backend/protobuf/flowy-database/protobuf.dart';
  13. import 'package:flutter_bloc/flutter_bloc.dart';
  14. import 'package:freezed_annotation/freezed_annotation.dart';
  15. import 'board_data_controller.dart';
  16. import 'group_controller.dart';
  17. part 'board_bloc.freezed.dart';
  18. class BoardBloc extends Bloc<BoardEvent, BoardState> {
  19. final BoardDataController _gridDataController;
  20. late final AppFlowyBoardController boardController;
  21. final MoveRowFFIService _rowService;
  22. final LinkedHashMap<String, GroupController> groupControllers =
  23. LinkedHashMap();
  24. GridFieldController get fieldController =>
  25. _gridDataController.fieldController;
  26. String get databaseId => _gridDataController.viewId;
  27. BoardBloc({required ViewPB view})
  28. : _rowService = MoveRowFFIService(viewId: 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 _openGrid(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: (DatabasePB 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 fieldInfo = fieldController.getField(group.fieldId);
  131. if (fieldInfo == null) {
  132. Log.warn("fieldInfo should not be null");
  133. return;
  134. }
  135. boardController.enableGroupDragging(!isEdit);
  136. // boardController.updateGroupItem(
  137. // group.groupId,
  138. // GroupItem(
  139. // row: row,
  140. // fieldInfo: fieldInfo,
  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 fromGroupId, String toGroupId) {
  159. _rowService
  160. .moveGroup(
  161. fromGroupId: fromGroupId,
  162. toGroupId: toGroupId,
  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. fieldInfo: 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. databaseId: state.databaseId,
  207. group: group,
  208. delegate: delegate,
  209. );
  210. controller.startListening();
  211. groupControllers[controller.group.groupId] = (controller);
  212. }
  213. }
  214. GridRowCache? getRowCache(String blockId) {
  215. return _gridDataController.rowCache;
  216. }
  217. void _startListening() {
  218. _gridDataController.addListener(
  219. onGridChanged: (grid) {
  220. if (!isClosed) {
  221. add(BoardEvent.didReceiveGridUpdate(grid));
  222. }
  223. },
  224. didLoadGroups: (groups) {
  225. if (isClosed) return;
  226. initializeGroups(groups);
  227. add(BoardEvent.didReceiveGroups(groups));
  228. },
  229. onDeletedGroup: (groupIds) {
  230. if (isClosed) return;
  231. //
  232. },
  233. onInsertedGroup: (insertedGroups) {
  234. if (isClosed) return;
  235. //
  236. },
  237. onUpdatedGroup: (updatedGroups) {
  238. if (isClosed) return;
  239. for (final group in updatedGroups) {
  240. final columnController =
  241. boardController.getGroupController(group.groupId);
  242. columnController?.updateGroupName(group.desc);
  243. }
  244. },
  245. onError: (err) {
  246. Log.error(err);
  247. },
  248. onResetGroups: (groups) {
  249. if (isClosed) return;
  250. initializeGroups(groups);
  251. add(BoardEvent.didReceiveGroups(groups));
  252. },
  253. );
  254. }
  255. List<AppFlowyGroupItem> _buildGroupItems(GroupPB group) {
  256. final items = group.rows.map((row) {
  257. final fieldInfo = fieldController.getField(group.fieldId);
  258. return GroupItem(
  259. row: row,
  260. fieldInfo: fieldInfo!,
  261. );
  262. }).toList();
  263. return <AppFlowyGroupItem>[...items];
  264. }
  265. Future<void> _openGrid(Emitter<BoardState> emit) async {
  266. final result = await _gridDataController.openGrid();
  267. result.fold(
  268. (grid) => emit(
  269. state.copyWith(loadingState: GridLoadingState.finish(left(unit))),
  270. ),
  271. (err) => emit(
  272. state.copyWith(loadingState: GridLoadingState.finish(right(err))),
  273. ),
  274. );
  275. }
  276. }
  277. @freezed
  278. class BoardEvent with _$BoardEvent {
  279. const factory BoardEvent.initial() = _InitialBoard;
  280. const factory BoardEvent.createBottomRow(String groupId) = _CreateBottomRow;
  281. const factory BoardEvent.createHeaderRow(String groupId) = _CreateHeaderRow;
  282. const factory BoardEvent.didCreateRow(
  283. GroupPB group,
  284. RowPB row,
  285. int? index,
  286. ) = _DidCreateRow;
  287. const factory BoardEvent.startEditingRow(
  288. GroupPB group,
  289. RowPB row,
  290. ) = _StartEditRow;
  291. const factory BoardEvent.endEditingRow(String rowId) = _EndEditRow;
  292. const factory BoardEvent.didReceiveError(FlowyError error) = _DidReceiveError;
  293. const factory BoardEvent.didReceiveGridUpdate(
  294. DatabasePB grid,
  295. ) = _DidReceiveGridUpdate;
  296. const factory BoardEvent.didReceiveGroups(List<GroupPB> groups) =
  297. _DidReceiveGroups;
  298. }
  299. @freezed
  300. class BoardState with _$BoardState {
  301. const factory BoardState({
  302. required String databaseId,
  303. required Option<DatabasePB> grid,
  304. required List<String> groupIds,
  305. required Option<BoardEditingRow> editingRow,
  306. required GridLoadingState loadingState,
  307. required Option<FlowyError> noneOrError,
  308. }) = _BoardState;
  309. factory BoardState.initial(String databaseId) => BoardState(
  310. grid: none(),
  311. databaseId: databaseId,
  312. groupIds: [],
  313. editingRow: none(),
  314. noneOrError: none(),
  315. loadingState: const _Loading(),
  316. );
  317. }
  318. @freezed
  319. class GridLoadingState with _$GridLoadingState {
  320. const factory GridLoadingState.loading() = _Loading;
  321. const factory GridLoadingState.finish(
  322. Either<Unit, FlowyError> successOrFail) = _Finish;
  323. }
  324. class GridFieldEquatable extends Equatable {
  325. final UnmodifiableListView<FieldPB> _fields;
  326. const GridFieldEquatable(
  327. UnmodifiableListView<FieldPB> fields,
  328. ) : _fields = fields;
  329. @override
  330. List<Object?> get props {
  331. if (_fields.isEmpty) {
  332. return [];
  333. }
  334. return [
  335. _fields.length,
  336. _fields
  337. .map((field) => field.width)
  338. .reduce((value, element) => value + element),
  339. ];
  340. }
  341. UnmodifiableListView<FieldPB> get value => UnmodifiableListView(_fields);
  342. }
  343. class GroupItem extends AppFlowyGroupItem {
  344. final RowPB row;
  345. final FieldInfo fieldInfo;
  346. GroupItem({
  347. required this.row,
  348. required this.fieldInfo,
  349. bool draggable = true,
  350. }) {
  351. super.draggable = draggable;
  352. }
  353. @override
  354. String get id => row.id;
  355. }
  356. class GroupControllerDelegateImpl extends GroupControllerDelegate {
  357. final GridFieldController fieldController;
  358. final AppFlowyBoardController controller;
  359. final void Function(String, RowPB, int?) onNewColumnItem;
  360. GroupControllerDelegateImpl({
  361. required this.controller,
  362. required this.fieldController,
  363. required this.onNewColumnItem,
  364. });
  365. @override
  366. void insertRow(GroupPB group, RowPB row, int? index) {
  367. final fieldInfo = fieldController.getField(group.fieldId);
  368. if (fieldInfo == null) {
  369. Log.warn("fieldInfo should not be null");
  370. return;
  371. }
  372. if (index != null) {
  373. final item = GroupItem(
  374. row: row,
  375. fieldInfo: fieldInfo,
  376. );
  377. controller.insertGroupItem(group.groupId, index, item);
  378. } else {
  379. final item = GroupItem(
  380. row: row,
  381. fieldInfo: fieldInfo,
  382. );
  383. controller.addGroupItem(group.groupId, item);
  384. }
  385. }
  386. @override
  387. void removeRow(GroupPB group, String rowId) {
  388. controller.removeGroupItem(group.groupId, rowId);
  389. }
  390. @override
  391. void updateRow(GroupPB group, RowPB row) {
  392. final fieldInfo = fieldController.getField(group.fieldId);
  393. if (fieldInfo == null) {
  394. Log.warn("fieldInfo should not be null");
  395. return;
  396. }
  397. controller.updateGroupItem(
  398. group.groupId,
  399. GroupItem(
  400. row: row,
  401. fieldInfo: fieldInfo,
  402. ),
  403. );
  404. }
  405. @override
  406. void addNewRow(GroupPB group, RowPB row, int? index) {
  407. final fieldInfo = fieldController.getField(group.fieldId);
  408. if (fieldInfo == null) {
  409. Log.warn("fieldInfo should not be null");
  410. return;
  411. }
  412. final item = GroupItem(
  413. row: row,
  414. fieldInfo: fieldInfo,
  415. draggable: false,
  416. );
  417. if (index != null) {
  418. controller.insertGroupItem(group.groupId, index, item);
  419. } else {
  420. controller.addGroupItem(group.groupId, item);
  421. }
  422. onNewColumnItem(group.groupId, row, index);
  423. }
  424. }
  425. class BoardEditingRow {
  426. GroupPB group;
  427. RowPB row;
  428. int? index;
  429. BoardEditingRow({
  430. required this.group,
  431. required this.row,
  432. required this.index,
  433. });
  434. }
  435. class GroupData {
  436. final GroupPB group;
  437. final FieldInfo fieldInfo;
  438. GroupData({
  439. required this.group,
  440. required this.fieldInfo,
  441. });
  442. CheckboxGroup? asCheckboxGroup() {
  443. if (fieldType != FieldType.Checkbox) return null;
  444. return CheckboxGroup(group);
  445. }
  446. FieldType get fieldType => fieldInfo.fieldType;
  447. }
  448. class CheckboxGroup {
  449. final GroupPB group;
  450. CheckboxGroup(this.group);
  451. // Hardcode value: "Yes" that equal to the value defined in Rust
  452. // pub const CHECK: &str = "Yes";
  453. bool get isCheck => group.groupId == "Yes";
  454. }