i_doc.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import 'dart:convert';
  2. import 'dart:async';
  3. import 'package:dartz/dartz.dart';
  4. // ignore: implementation_imports
  5. import 'package:editor/flutter_quill.dart';
  6. // import 'package:flowy_editor/flowy_editor.dart';
  7. import 'package:flowy_log/flowy_log.dart';
  8. import 'package:flowy_sdk/protobuf/flowy-document/doc.pb.dart';
  9. import 'package:flowy_sdk/protobuf/flowy-workspace/errors.pb.dart';
  10. class FlowyDoc {
  11. final DocDelta doc;
  12. final IDoc iDocImpl;
  13. late Document document;
  14. late StreamSubscription _subscription;
  15. FlowyDoc({required this.doc, required this.iDocImpl}) {
  16. document = _decodeJsonToDocument(doc.data);
  17. _subscription = document.changes.listen((event) {
  18. final delta = event.item2;
  19. final documentDelta = document.toDelta();
  20. _composeDelta(delta, documentDelta);
  21. });
  22. }
  23. String get id => doc.docId;
  24. Future<void> close() async {
  25. await _subscription.cancel();
  26. }
  27. void _composeDelta(Delta composedDelta, Delta documentDelta) async {
  28. final json = jsonEncode(composedDelta.toJson());
  29. Log.debug("Send json: $json");
  30. final result = await iDocImpl.composeDelta(json: json);
  31. result.fold((rustDoc) {
  32. // final json = utf8.decode(doc.data);
  33. final rustDelta = Delta.fromJson(jsonDecode(rustDoc.data));
  34. if (documentDelta != rustDelta) {
  35. Log.error("Receive : $rustDelta");
  36. Log.error("Expected : $documentDelta");
  37. }
  38. }, (r) => null);
  39. }
  40. Document _decodeJsonToDocument(String data) {
  41. final json = jsonDecode(data);
  42. final document = Document.fromJson(json);
  43. return document;
  44. }
  45. }
  46. abstract class IDoc {
  47. Future<Either<DocDelta, WorkspaceError>> readDoc();
  48. Future<Either<DocDelta, WorkspaceError>> composeDelta({required String json});
  49. Future<Either<Unit, WorkspaceError>> closeDoc();
  50. }