doc_bloc.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import 'package:flowy_sdk/protobuf/flowy-workspace/errors.pb.dart';
  2. import 'package:flutter_bloc/flutter_bloc.dart';
  3. import 'package:app_flowy/workspace/domain/i_doc.dart';
  4. import 'package:freezed_annotation/freezed_annotation.dart';
  5. import 'package:dartz/dartz.dart';
  6. part 'doc_bloc.freezed.dart';
  7. class DocBloc extends Bloc<DocEvent, DocState> {
  8. final IDoc docManager;
  9. DocBloc({required this.docManager}) : super(DocState.initial());
  10. @override
  11. Stream<DocState> mapEventToState(DocEvent event) async* {
  12. yield* event.map(
  13. initial: _initial,
  14. );
  15. }
  16. @override
  17. Future<void> close() async {
  18. docManager.closeDoc();
  19. await state.doc.fold(() => null, (doc) async {
  20. await doc.close();
  21. });
  22. return super.close();
  23. }
  24. Stream<DocState> _initial(Initial value) async* {
  25. final result = await docManager.readDoc();
  26. yield result.fold(
  27. (doc) {
  28. final flowyDoc = FlowyDoc(doc: doc, iDocImpl: docManager);
  29. return state.copyWith(
  30. doc: some(flowyDoc),
  31. loadState: DocLoadState.finish(left(flowyDoc)),
  32. );
  33. },
  34. (err) {
  35. return state.copyWith(
  36. doc: none(),
  37. loadState: DocLoadState.finish(right(err)),
  38. );
  39. },
  40. );
  41. }
  42. // Document _decodeListToDocument(Uint8List data) {
  43. // final json = jsonDecode(utf8.decode(data));
  44. // final document = Document.fromJson(json);
  45. // return document;
  46. // }
  47. // Document _decodeJsonToDocument(String data) {
  48. // final json = jsonDecode(data);
  49. // final document = Document.fromJson(json);
  50. // return document;
  51. // }
  52. }
  53. @freezed
  54. class DocEvent with _$DocEvent {
  55. const factory DocEvent.initial() = Initial;
  56. }
  57. @freezed
  58. class DocState with _$DocState {
  59. const factory DocState({required Option<FlowyDoc> doc, required DocLoadState loadState}) = _DocState;
  60. factory DocState.initial() => DocState(doc: none(), loadState: const _Loading());
  61. }
  62. @freezed
  63. class DocLoadState with _$DocLoadState {
  64. const factory DocLoadState.loading() = _Loading;
  65. const factory DocLoadState.finish(Either<FlowyDoc, WorkspaceError> successOrFail) = _Finish;
  66. }