doc_bloc.dart 8.3 KB

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