doc_bloc.dart 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import 'dart:convert';
  2. import 'package:appflowy/plugins/document/presentation/plugins/cover/cover_node_widget.dart';
  3. import 'package:appflowy/plugins/trash/application/trash_service.dart';
  4. import 'package:appflowy/user/application/user_service.dart';
  5. import 'package:appflowy/workspace/application/view/view_listener.dart';
  6. import 'package:appflowy/plugins/document/application/doc_service.dart';
  7. import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
  8. import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pbserver.dart';
  9. import 'package:appflowy_editor/appflowy_editor.dart'
  10. show EditorState, Document, Transaction, Node;
  11. import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart';
  12. import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
  13. import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
  14. import 'package:appflowy_backend/log.dart';
  15. import 'package:flutter/foundation.dart';
  16. import 'package:flutter_bloc/flutter_bloc.dart';
  17. import 'package:freezed_annotation/freezed_annotation.dart';
  18. import 'package:dartz/dartz.dart';
  19. import 'dart:async';
  20. import 'package:appflowy/util/either_extension.dart';
  21. part 'doc_bloc.freezed.dart';
  22. class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
  23. final ViewPB view;
  24. final DocumentService _documentService;
  25. final ViewListener _listener;
  26. final TrashService _trashService;
  27. EditorState? editorState;
  28. StreamSubscription? _subscription;
  29. DocumentBloc({
  30. required this.view,
  31. }) : _documentService = DocumentService(),
  32. _listener = ViewListener(view: view),
  33. _trashService = TrashService(),
  34. super(DocumentState.initial()) {
  35. on<DocumentEvent>((event, emit) async {
  36. await event.map(
  37. initial: (Initial value) async {
  38. await _initial(value, emit);
  39. _listenOnViewChange();
  40. },
  41. deleted: (Deleted value) async {
  42. emit(state.copyWith(isDeleted: true));
  43. },
  44. restore: (Restore value) async {
  45. emit(state.copyWith(isDeleted: false));
  46. },
  47. deletePermanently: (DeletePermanently value) async {
  48. final result = await _trashService
  49. .deleteViews([Tuple2(view.id, TrashType.TrashView)]);
  50. final newState = result.fold(
  51. (l) => state.copyWith(forceClose: true), (r) => state);
  52. emit(newState);
  53. },
  54. restorePage: (RestorePage value) async {
  55. final result = await _trashService.putback(view.id);
  56. final newState = result.fold(
  57. (l) => state.copyWith(isDeleted: false), (r) => state);
  58. emit(newState);
  59. },
  60. );
  61. });
  62. }
  63. @override
  64. Future<void> close() async {
  65. await _listener.stop();
  66. if (_subscription != null) {
  67. await _subscription?.cancel();
  68. }
  69. await _documentService.closeDocument(docId: view.id);
  70. return super.close();
  71. }
  72. Future<void> _initial(Initial value, Emitter<DocumentState> emit) async {
  73. final userProfile = await UserBackendService.getCurrentUserProfile();
  74. if (userProfile.isRight()) {
  75. return emit(
  76. state.copyWith(
  77. loadingState: DocumentLoadingState.finish(
  78. right(userProfile.asRight()),
  79. ),
  80. ),
  81. );
  82. }
  83. final result = await _documentService.openDocument(view: view);
  84. return result.fold(
  85. (documentData) async {
  86. await _initEditorState(documentData).whenComplete(() {
  87. emit(
  88. state.copyWith(
  89. loadingState: DocumentLoadingState.finish(left(unit)),
  90. userProfilePB: userProfile.asLeft(),
  91. ),
  92. );
  93. });
  94. },
  95. (err) async {
  96. emit(
  97. state.copyWith(
  98. loadingState: DocumentLoadingState.finish(right(err)),
  99. ),
  100. );
  101. },
  102. );
  103. }
  104. void _listenOnViewChange() {
  105. _listener.start(
  106. onViewDeleted: (result) {
  107. result.fold(
  108. (view) => add(const DocumentEvent.deleted()),
  109. (error) {},
  110. );
  111. },
  112. onViewRestored: (result) {
  113. result.fold(
  114. (view) => add(const DocumentEvent.restore()),
  115. (error) {},
  116. );
  117. },
  118. );
  119. }
  120. Future<void> _initEditorState(DocumentDataPB documentData) async {
  121. final document = Document.fromJson(jsonDecode(documentData.content));
  122. final editorState = EditorState(document: document);
  123. this.editorState = editorState;
  124. // listen on document change
  125. _subscription = editorState.transactionStream.listen((transaction) {
  126. final json = jsonEncode(TransactionAdaptor(transaction).toJson());
  127. _documentService
  128. .applyEdit(docId: view.id, operations: json)
  129. .then((result) {
  130. result.fold(
  131. (l) => null,
  132. (err) => Log.error(err),
  133. );
  134. });
  135. });
  136. // log
  137. if (kDebugMode) {
  138. editorState.logConfiguration.handler = (log) {
  139. Log.debug(log);
  140. };
  141. }
  142. // migration
  143. final migration = DocumentMigration(editorState: editorState);
  144. await migration.apply();
  145. }
  146. }
  147. @freezed
  148. class DocumentEvent with _$DocumentEvent {
  149. const factory DocumentEvent.initial() = Initial;
  150. const factory DocumentEvent.deleted() = Deleted;
  151. const factory DocumentEvent.restore() = Restore;
  152. const factory DocumentEvent.restorePage() = RestorePage;
  153. const factory DocumentEvent.deletePermanently() = DeletePermanently;
  154. }
  155. @freezed
  156. class DocumentState with _$DocumentState {
  157. const factory DocumentState({
  158. required DocumentLoadingState loadingState,
  159. required bool isDeleted,
  160. required bool forceClose,
  161. UserProfilePB? userProfilePB,
  162. }) = _DocumentState;
  163. factory DocumentState.initial() => const DocumentState(
  164. loadingState: _Loading(),
  165. isDeleted: false,
  166. forceClose: false,
  167. userProfilePB: null,
  168. );
  169. }
  170. @freezed
  171. class DocumentLoadingState with _$DocumentLoadingState {
  172. const factory DocumentLoadingState.loading() = _Loading;
  173. const factory DocumentLoadingState.finish(
  174. Either<Unit, FlowyError> successOrFail) = _Finish;
  175. }
  176. /// Uses to erase the different between appflowy editor and the backend
  177. class TransactionAdaptor {
  178. final Transaction transaction;
  179. TransactionAdaptor(this.transaction);
  180. Map<String, dynamic> toJson() {
  181. final json = <String, dynamic>{};
  182. if (transaction.operations.isNotEmpty) {
  183. // The backend uses [0,0] as the beginning path, but the editor uses [0].
  184. // So it needs to extend the path by inserting `0` at the head for all
  185. // operations before passing to the backend.
  186. json['operations'] = transaction.operations
  187. .map((e) => e.copyWith(path: [0, ...e.path]).toJson())
  188. .toList();
  189. }
  190. if (transaction.afterSelection != null) {
  191. final selection = transaction.afterSelection!;
  192. final start = selection.start;
  193. final end = selection.end;
  194. json['after_selection'] = selection
  195. .copyWith(
  196. start: start.copyWith(path: [0, ...start.path]),
  197. end: end.copyWith(path: [0, ...end.path]),
  198. )
  199. .toJson();
  200. }
  201. if (transaction.beforeSelection != null) {
  202. final selection = transaction.beforeSelection!;
  203. final start = selection.start;
  204. final end = selection.end;
  205. json['before_selection'] = selection
  206. .copyWith(
  207. start: start.copyWith(path: [0, ...start.path]),
  208. end: end.copyWith(path: [0, ...end.path]),
  209. )
  210. .toJson();
  211. }
  212. return json;
  213. }
  214. }
  215. class DocumentMigration {
  216. const DocumentMigration({
  217. required this.editorState,
  218. });
  219. final EditorState editorState;
  220. /// Migrate the document to the latest version.
  221. Future<void> apply() async {
  222. final transaction = editorState.transaction;
  223. // A temporary solution to migrate the document to the latest version.
  224. // Once the editor is stable, we can remove this.
  225. // cover plugin
  226. if (editorState.document.nodeAtPath([0])?.type != kCoverType) {
  227. transaction.insertNode(
  228. [0],
  229. Node(type: kCoverType),
  230. );
  231. }
  232. transaction.afterSelection = null;
  233. if (transaction.operations.isNotEmpty) {
  234. editorState.apply(transaction);
  235. }
  236. }
  237. }