80 lines
2.1 KiB
Dart
Raw Normal View History

2021-09-11 21:30:58 +08:00
import 'package:flowy_sdk/protobuf/flowy-workspace/errors.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
2021-07-24 18:55:13 +08:00
import 'package:app_flowy/workspace/domain/i_doc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
2021-10-19 13:56:11 +08:00
import 'package:dartz/dartz.dart';
2021-07-24 18:55:13 +08:00
part 'doc_bloc.freezed.dart';
class DocBloc extends Bloc<DocEvent, DocState> {
2021-10-19 13:56:11 +08:00
final IDoc docManager;
2021-07-24 18:55:13 +08:00
2021-10-19 13:56:11 +08:00
DocBloc({required this.docManager}) : super(DocState.initial());
2021-07-24 18:55:13 +08:00
@override
Stream<DocState> mapEventToState(DocEvent event) async* {
yield* event.map(
2021-10-19 13:56:11 +08:00
initial: _initial,
2021-07-24 18:55:13 +08:00
);
}
2021-09-11 21:30:58 +08:00
2021-10-19 13:56:11 +08:00
@override
Future<void> close() async {
docManager.closeDoc();
await state.doc.fold(() => null, (doc) async {
await doc.close();
});
return super.close();
}
Stream<DocState> _initial(Initial value) async* {
final result = await docManager.readDoc();
yield result.fold(
2021-09-11 21:30:58 +08:00
(doc) {
2021-10-19 13:56:11 +08:00
final flowyDoc = FlowyDoc(doc: doc, iDocImpl: docManager);
return state.copyWith(
doc: some(flowyDoc),
loadState: DocLoadState.finish(left(flowyDoc)),
);
2021-09-11 21:30:58 +08:00
},
2021-10-19 13:56:11 +08:00
(err) {
return state.copyWith(
doc: none(),
loadState: DocLoadState.finish(right(err)),
);
2021-09-11 21:30:58 +08:00
},
);
}
2021-10-10 11:40:45 +08:00
// Document _decodeListToDocument(Uint8List data) {
// final json = jsonDecode(utf8.decode(data));
// final document = Document.fromJson(json);
// return document;
// }
// Document _decodeJsonToDocument(String data) {
// final json = jsonDecode(data);
// final document = Document.fromJson(json);
// return document;
// }
2021-07-24 18:55:13 +08:00
}
@freezed
2021-09-11 21:30:58 +08:00
class DocEvent with _$DocEvent {
2021-10-19 13:56:11 +08:00
const factory DocEvent.initial() = Initial;
2021-07-24 18:55:13 +08:00
}
@freezed
2021-09-11 21:30:58 +08:00
class DocState with _$DocState {
2021-10-19 13:56:11 +08:00
const factory DocState({required Option<FlowyDoc> doc, required DocLoadState loadState}) = _DocState;
factory DocState.initial() => DocState(doc: none(), loadState: const _Loading());
}
@freezed
class DocLoadState with _$DocLoadState {
const factory DocLoadState.loading() = _Loading;
const factory DocLoadState.finish(Either<FlowyDoc, WorkspaceError> successOrFail) = _Finish;
2021-07-24 18:55:13 +08:00
}