doc_bloc.dart 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. import 'package:appflowy_backend/protobuf/flowy-document2/entities.pb.dart';
  22. part 'doc_bloc.freezed.dart';
  23. class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
  24. final ViewPB view;
  25. final DocumentService _documentService;
  26. final DocumentListener _docListener;
  27. final ViewListener _listener;
  28. final TrashService _trashService;
  29. EditorState? editorState;
  30. StreamSubscription? _subscription;
  31. DocumentBloc({
  32. required this.view,
  33. }) : _documentService = DocumentService(),
  34. _docListener = DocumentListener(id: view.id),
  35. _listener = ViewListener(view: view),
  36. _trashService = TrashService(),
  37. super(DocumentState.initial()) {
  38. on<DocumentEvent>((event, emit) async {
  39. await event.map(
  40. initial: (Initial value) async {
  41. _listenOnDocChange();
  42. await _initial(value, emit);
  43. _listenOnViewChange();
  44. },
  45. deleted: (Deleted value) async {
  46. emit(state.copyWith(isDeleted: true));
  47. },
  48. restore: (Restore value) async {
  49. emit(state.copyWith(isDeleted: false));
  50. },
  51. deletePermanently: (DeletePermanently value) async {
  52. final result = await _trashService.deleteViews([view.id]);
  53. final newState = result.fold(
  54. (l) => state.copyWith(forceClose: true), (r) => state);
  55. emit(newState);
  56. },
  57. restorePage: (RestorePage value) async {
  58. final result = await _trashService.putback(view.id);
  59. final newState = result.fold(
  60. (l) => state.copyWith(isDeleted: false), (r) => state);
  61. emit(newState);
  62. },
  63. );
  64. });
  65. }
  66. @override
  67. Future<void> close() async {
  68. await _listener.stop();
  69. if (_subscription != null) {
  70. await _subscription?.cancel();
  71. }
  72. await _documentService.closeDocument(docId: view.id);
  73. await _documentService.closeDocumentV2(view: view);
  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. // test code
  89. final document = await _documentService.openDocumentV2(view: view);
  90. BlockPB? root;
  91. document.fold((l) {
  92. print('---------<open document v2>-----------');
  93. print('page id = ${l.pageId}');
  94. l.blocks.blocks.forEach((key, value) {
  95. print('-----<block begin>-----');
  96. print('block = $value');
  97. if (value.ty == 'page') {
  98. root = value;
  99. }
  100. print('-----<block end>-----');
  101. });
  102. print('---------<open document v2>-----------');
  103. }, (r) {});
  104. if (root != null) {
  105. await _documentService.applyAction(
  106. view: view,
  107. actions: [
  108. BlockActionPB(
  109. action: BlockActionTypePB.Insert,
  110. payload: BlockActionPayloadPB(
  111. block: BlockPB()
  112. ..id = 'id_0'
  113. ..ty = 'text'
  114. ..parentId = root!.id,
  115. ),
  116. ),
  117. ],
  118. );
  119. }
  120. return result.fold(
  121. (documentData) async {
  122. await _initEditorState(documentData).whenComplete(() {
  123. emit(
  124. state.copyWith(
  125. loadingState: DocumentLoadingState.finish(left(unit)),
  126. userProfilePB: userProfile.asLeft(),
  127. ),
  128. );
  129. });
  130. },
  131. (err) async {
  132. emit(
  133. state.copyWith(
  134. loadingState: DocumentLoadingState.finish(right(err)),
  135. ),
  136. );
  137. },
  138. );
  139. }
  140. void _listenOnViewChange() {
  141. _listener.start(
  142. onViewDeleted: (result) {
  143. result.fold(
  144. (view) => add(const DocumentEvent.deleted()),
  145. (error) {},
  146. );
  147. },
  148. onViewRestored: (result) {
  149. result.fold(
  150. (view) => add(const DocumentEvent.restore()),
  151. (error) {},
  152. );
  153. },
  154. );
  155. }
  156. void _listenOnDocChange() {
  157. _docListener.start(
  158. didReceiveUpdate: () {
  159. print('---------<receive document update>-----------');
  160. },
  161. );
  162. }
  163. Future<void> _initEditorState(DocumentDataPB documentData) async {
  164. final document = Document.fromJson(jsonDecode(documentData.content));
  165. final editorState = EditorState(document: document);
  166. this.editorState = editorState;
  167. // listen on document change
  168. _subscription = editorState.transactionStream.listen((transaction) {
  169. final json = jsonEncode(TransactionAdaptor(transaction).toJson());
  170. _documentService
  171. .applyEdit(docId: view.id, operations: json)
  172. .then((result) {
  173. result.fold(
  174. (l) => null,
  175. (err) => Log.error(err),
  176. );
  177. });
  178. });
  179. // log
  180. if (kDebugMode) {
  181. editorState.logConfiguration.handler = (log) {
  182. Log.debug(log);
  183. };
  184. }
  185. // migration
  186. final migration = DocumentMigration(editorState: editorState);
  187. await migration.apply();
  188. }
  189. }
  190. @freezed
  191. class DocumentEvent with _$DocumentEvent {
  192. const factory DocumentEvent.initial() = Initial;
  193. const factory DocumentEvent.deleted() = Deleted;
  194. const factory DocumentEvent.restore() = Restore;
  195. const factory DocumentEvent.restorePage() = RestorePage;
  196. const factory DocumentEvent.deletePermanently() = DeletePermanently;
  197. }
  198. @freezed
  199. class DocumentState with _$DocumentState {
  200. const factory DocumentState({
  201. required DocumentLoadingState loadingState,
  202. required bool isDeleted,
  203. required bool forceClose,
  204. UserProfilePB? userProfilePB,
  205. }) = _DocumentState;
  206. factory DocumentState.initial() => const DocumentState(
  207. loadingState: _Loading(),
  208. isDeleted: false,
  209. forceClose: false,
  210. userProfilePB: null,
  211. );
  212. }
  213. @freezed
  214. class DocumentLoadingState with _$DocumentLoadingState {
  215. const factory DocumentLoadingState.loading() = _Loading;
  216. const factory DocumentLoadingState.finish(
  217. Either<Unit, FlowyError> successOrFail) = _Finish;
  218. }
  219. /// Uses to erase the different between appflowy editor and the backend
  220. class TransactionAdaptor {
  221. final Transaction transaction;
  222. TransactionAdaptor(this.transaction);
  223. Map<String, dynamic> toJson() {
  224. final json = <String, dynamic>{};
  225. if (transaction.operations.isNotEmpty) {
  226. // The backend uses [0,0] as the beginning path, but the editor uses [0].
  227. // So it needs to extend the path by inserting `0` at the head for all
  228. // operations before passing to the backend.
  229. json['operations'] = transaction.operations
  230. .map((e) => e.copyWith(path: [0, ...e.path]).toJson())
  231. .toList();
  232. }
  233. if (transaction.afterSelection != null) {
  234. final selection = transaction.afterSelection!;
  235. final start = selection.start;
  236. final end = selection.end;
  237. json['after_selection'] = selection
  238. .copyWith(
  239. start: start.copyWith(path: [0, ...start.path]),
  240. end: end.copyWith(path: [0, ...end.path]),
  241. )
  242. .toJson();
  243. }
  244. if (transaction.beforeSelection != null) {
  245. final selection = transaction.beforeSelection!;
  246. final start = selection.start;
  247. final end = selection.end;
  248. json['before_selection'] = selection
  249. .copyWith(
  250. start: start.copyWith(path: [0, ...start.path]),
  251. end: end.copyWith(path: [0, ...end.path]),
  252. )
  253. .toJson();
  254. }
  255. return json;
  256. }
  257. }
  258. class DocumentMigration {
  259. const DocumentMigration({
  260. required this.editorState,
  261. });
  262. final EditorState editorState;
  263. /// Migrate the document to the latest version.
  264. Future<void> apply() async {
  265. final transaction = editorState.transaction;
  266. // A temporary solution to migrate the document to the latest version.
  267. // Once the editor is stable, we can remove this.
  268. // cover plugin
  269. if (editorState.document.nodeAtPath([0])?.type != kCoverType) {
  270. transaction.insertNode(
  271. [0],
  272. Node(type: kCoverType),
  273. );
  274. }
  275. transaction.afterSelection = null;
  276. if (transaction.operations.isNotEmpty) {
  277. editorState.apply(transaction);
  278. }
  279. }
  280. }