doc_bloc.dart 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import 'dart:async';
  2. import 'package:appflowy/plugins/document/application/doc_service.dart';
  3. import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
  4. import 'package:appflowy/plugins/document/application/editor_transaction_adapter.dart';
  5. import 'package:appflowy/plugins/trash/application/trash_service.dart';
  6. import 'package:appflowy/user/application/user_service.dart';
  7. import 'package:appflowy/util/json_print.dart';
  8. import 'package:appflowy/workspace/application/doc/doc_listener.dart';
  9. import 'package:appflowy/workspace/application/view/view_listener.dart';
  10. import 'package:appflowy_backend/protobuf/flowy-document2/protobuf.dart';
  11. import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
  12. import 'package:appflowy_backend/protobuf/flowy-folder2/view.pb.dart';
  13. import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pbserver.dart';
  14. import 'package:appflowy_editor/appflowy_editor.dart'
  15. show
  16. EditorState,
  17. LogLevel,
  18. TransactionTime,
  19. Selection,
  20. Position,
  21. paragraphNode;
  22. import 'package:dartz/dartz.dart';
  23. import 'package:flutter/foundation.dart';
  24. import 'package:flutter_bloc/flutter_bloc.dart';
  25. import 'package:freezed_annotation/freezed_annotation.dart';
  26. part 'doc_bloc.freezed.dart';
  27. class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
  28. DocumentBloc({
  29. required this.view,
  30. }) : _documentListener = DocumentListener(id: view.id),
  31. _viewListener = ViewListener(viewId: view.id),
  32. _documentService = DocumentService(),
  33. _trashService = TrashService(),
  34. super(DocumentState.initial()) {
  35. _transactionAdapter = TransactionAdapter(
  36. documentId: view.id,
  37. documentService: _documentService,
  38. );
  39. on<DocumentEvent>(_onDocumentEvent);
  40. }
  41. final ViewPB view;
  42. final DocumentListener _documentListener;
  43. final ViewListener _viewListener;
  44. final DocumentService _documentService;
  45. final TrashService _trashService;
  46. late final TransactionAdapter _transactionAdapter;
  47. EditorState? editorState;
  48. StreamSubscription? _subscription;
  49. @override
  50. Future<void> close() async {
  51. await _viewListener.stop();
  52. await _subscription?.cancel();
  53. await _documentService.closeDocument(view: view);
  54. editorState?.cancelSubscription();
  55. return super.close();
  56. }
  57. Future<void> _onDocumentEvent(
  58. DocumentEvent event,
  59. Emitter<DocumentState> emit,
  60. ) async {
  61. await event.map(
  62. initial: (Initial value) async {
  63. final state = await _fetchDocumentState();
  64. await _subscribe(state);
  65. emit(state);
  66. },
  67. moveToTrash: (MoveToTrash value) async {
  68. emit(state.copyWith(isDeleted: true));
  69. },
  70. restore: (Restore value) async {
  71. emit(state.copyWith(isDeleted: false));
  72. },
  73. deletePermanently: (DeletePermanently value) async {
  74. final result = await _trashService.deleteViews([view.id]);
  75. final forceClose = result.fold((l) => true, (r) => false);
  76. emit(state.copyWith(forceClose: forceClose));
  77. },
  78. restorePage: (RestorePage value) async {
  79. final result = await _trashService.putback(view.id);
  80. final isDeleted = result.fold((l) => false, (r) => true);
  81. emit(state.copyWith(isDeleted: isDeleted));
  82. },
  83. );
  84. }
  85. Future<void> _subscribe(DocumentState state) async {
  86. _onViewChanged();
  87. _onDocumentChanged();
  88. // create the editor state
  89. await state.loadingState.whenOrNull(
  90. finish: (data) async => data.map((r) {
  91. _initAppFlowyEditorState(r);
  92. }),
  93. );
  94. }
  95. /// subscribe to the view(document page) change
  96. void _onViewChanged() {
  97. _viewListener.start(
  98. onViewMoveToTrash: (r) {
  99. r.swap().map((r) => add(const DocumentEvent.moveToTrash()));
  100. },
  101. onViewDeleted: (r) {
  102. r.swap().map((r) => add(const DocumentEvent.moveToTrash()));
  103. },
  104. onViewRestored: (r) =>
  105. r.swap().map((r) => add(const DocumentEvent.restore())),
  106. );
  107. }
  108. /// subscribe to the document content change
  109. void _onDocumentChanged() {
  110. _documentListener.start(
  111. didReceiveUpdate: (docEvent) {
  112. // todo: integrate the document change to the editor
  113. // prettyPrintJson(docEvent.toProto3Json());
  114. },
  115. );
  116. }
  117. /// Fetch document
  118. Future<DocumentState> _fetchDocumentState() async {
  119. final result = await UserBackendService.getCurrentUserProfile().then(
  120. (value) async => value.andThen(
  121. // open the document
  122. await _documentService.openDocument(view: view),
  123. ),
  124. );
  125. return state.copyWith(
  126. loadingState: DocumentLoadingState.finish(result),
  127. );
  128. }
  129. Future<void> _initAppFlowyEditorState(DocumentDataPB data) async {
  130. if (kDebugMode) {
  131. prettyPrintJson(data.toProto3Json());
  132. }
  133. final document = data.toDocument();
  134. if (document == null) {
  135. assert(false, 'document is null');
  136. return;
  137. }
  138. final editorState = EditorState(document: document);
  139. this.editorState = editorState;
  140. // subscribe to the document change from the editor
  141. _subscription = editorState.transactionStream.listen((event) async {
  142. final time = event.$1;
  143. if (time != TransactionTime.before) {
  144. return;
  145. }
  146. await _transactionAdapter.apply(event.$2, editorState);
  147. // check if the document is empty.
  148. applyRules();
  149. });
  150. // output the log from the editor when debug mode
  151. if (kDebugMode) {
  152. editorState.logConfiguration
  153. ..level = LogLevel.all
  154. ..handler = (log) {
  155. // Log.debug(log);
  156. };
  157. }
  158. }
  159. Future<void> applyRules() async {
  160. ensureAtLeastOneParagraphExists();
  161. ensureLastNodeIsEditable();
  162. }
  163. Future<void> ensureLastNodeIsEditable() async {
  164. final editorState = this.editorState;
  165. if (editorState == null) {
  166. return;
  167. }
  168. final document = editorState.document;
  169. final lastNode = document.root.children.lastOrNull;
  170. if (lastNode == null || lastNode.delta == null) {
  171. final transaction = editorState.transaction;
  172. transaction.insertNode([document.root.children.length], paragraphNode());
  173. transaction.afterSelection = transaction.beforeSelection;
  174. await editorState.apply(transaction);
  175. }
  176. }
  177. Future<void> ensureAtLeastOneParagraphExists() async {
  178. final editorState = this.editorState;
  179. if (editorState == null) {
  180. return;
  181. }
  182. final document = editorState.document;
  183. if (document.root.children.isEmpty) {
  184. final transaction = editorState.transaction;
  185. transaction.insertNode([0], paragraphNode());
  186. transaction.afterSelection = Selection.collapsed(
  187. Position(path: [0], offset: 0),
  188. );
  189. await editorState.apply(transaction);
  190. }
  191. }
  192. }
  193. @freezed
  194. class DocumentEvent with _$DocumentEvent {
  195. const factory DocumentEvent.initial() = Initial;
  196. const factory DocumentEvent.moveToTrash() = MoveToTrash;
  197. const factory DocumentEvent.restore() = Restore;
  198. const factory DocumentEvent.restorePage() = RestorePage;
  199. const factory DocumentEvent.deletePermanently() = DeletePermanently;
  200. }
  201. @freezed
  202. class DocumentState with _$DocumentState {
  203. const factory DocumentState({
  204. required DocumentLoadingState loadingState,
  205. required bool isDeleted,
  206. required bool forceClose,
  207. UserProfilePB? userProfilePB,
  208. }) = _DocumentState;
  209. factory DocumentState.initial() => const DocumentState(
  210. loadingState: _Loading(),
  211. isDeleted: false,
  212. forceClose: false,
  213. userProfilePB: null,
  214. );
  215. }
  216. @freezed
  217. class DocumentLoadingState with _$DocumentLoadingState {
  218. const factory DocumentLoadingState.loading() = _Loading;
  219. const factory DocumentLoadingState.finish(
  220. Either<FlowyError, DocumentDataPB> successOrFail,
  221. ) = _Finish;
  222. }