doc_bloc.dart 6.1 KB

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