i_doc_impl.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import 'dart:convert';
  2. import 'package:dartz/dartz.dart';
  3. import 'package:flowy_editor/flowy_editor.dart';
  4. import 'package:flowy_sdk/protobuf/flowy-document/errors.pb.dart';
  5. import 'package:app_flowy/workspace/domain/i_doc.dart';
  6. import 'package:app_flowy/workspace/infrastructure/repos/doc_repo.dart';
  7. class IDocImpl extends IDoc {
  8. DocRepository repo;
  9. IDocImpl({required this.repo});
  10. @override
  11. Future<Either<Unit, DocError>> closeDoc() {
  12. return repo.closeDoc();
  13. }
  14. @override
  15. Future<Either<Doc, DocError>> readDoc() async {
  16. final docInfoOrFail = await repo.readDoc();
  17. return docInfoOrFail.fold(
  18. (info) => _loadDocument(info.path).then((result) => result.fold(
  19. (document) => left(Doc(info: info, data: document)),
  20. (error) => right(error))),
  21. (error) => right(error),
  22. );
  23. }
  24. @override
  25. Future<Either<Unit, DocError>> updateDoc(
  26. {String? name, String? desc, String? text}) {
  27. final json = jsonEncode(text ?? "");
  28. return repo.updateDoc(name: name, desc: desc, text: json);
  29. }
  30. Future<Either<Document, DocError>> _loadDocument(String path) {
  31. return repo.readDocData(path).then((docDataOrFail) {
  32. return docDataOrFail.fold(
  33. (docData) => left(_decodeToDocument(docData.text)),
  34. (error) => right(error),
  35. );
  36. });
  37. }
  38. Document _decodeToDocument(String text) {
  39. final json = jsonDecode(text);
  40. final document = Document.fromJson(json);
  41. return document;
  42. }
  43. }
  44. class EditorPersistenceImpl extends EditorPersistence {
  45. DocRepository repo;
  46. EditorPersistenceImpl({
  47. required this.repo,
  48. });
  49. @override
  50. Future<bool> save(List<dynamic> jsonList) async {
  51. final json = jsonEncode(jsonList);
  52. return repo.updateDoc(text: json).then((result) {
  53. return result.fold(
  54. (l) => true,
  55. (r) => false,
  56. );
  57. });
  58. }
  59. }