doc_bloc.dart 7.9 KB

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