doc_bloc.dart 8.1 KB

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