app_bloc.dart 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import 'dart:collection';
  2. import 'package:appflowy/startup/plugin/plugin.dart';
  3. import 'package:appflowy/startup/startup.dart';
  4. import 'package:appflowy/workspace/application/app/app_listener.dart';
  5. import 'package:appflowy/workspace/application/view/view_service.dart';
  6. import 'package:appflowy/workspace/presentation/home/menu/menu.dart';
  7. import 'package:expandable/expandable.dart';
  8. import 'package:appflowy_backend/log.dart';
  9. import 'package:appflowy_backend/protobuf/flowy-folder2/view.pb.dart';
  10. import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
  11. import 'package:flutter/foundation.dart';
  12. import 'package:freezed_annotation/freezed_annotation.dart';
  13. import 'package:flutter_bloc/flutter_bloc.dart';
  14. import 'package:dartz/dartz.dart';
  15. part 'app_bloc.freezed.dart';
  16. class AppBloc extends Bloc<AppEvent, AppState> {
  17. final ViewBackendService appService;
  18. final AppListener appListener;
  19. AppBloc({required ViewPB view})
  20. : appService = ViewBackendService(),
  21. appListener = AppListener(viewId: view.id),
  22. super(AppState.initial(view)) {
  23. on<AppEvent>((event, emit) async {
  24. await event.map(
  25. initial: (e) async {
  26. _startListening();
  27. await _loadViews(emit);
  28. },
  29. createView: (CreateView value) async {
  30. await _createView(value, emit);
  31. },
  32. loadViews: (_) async {
  33. await _loadViews(emit);
  34. },
  35. delete: (e) async {
  36. await _deleteApp(emit);
  37. },
  38. deleteView: (deletedView) async {
  39. await _deleteView(emit, deletedView.viewId);
  40. },
  41. rename: (e) async {
  42. await _renameView(e, emit);
  43. },
  44. appDidUpdate: (e) async {
  45. final latestCreatedView = state.latestCreatedView;
  46. final views = e.app.childViews;
  47. AppState newState = state.copyWith(
  48. views: views,
  49. view: e.app,
  50. );
  51. if (latestCreatedView != null) {
  52. final index = views
  53. .indexWhere((element) => element.id == latestCreatedView.id);
  54. if (index == -1) {
  55. newState = newState.copyWith(latestCreatedView: null);
  56. }
  57. emit(newState);
  58. }
  59. emit(newState);
  60. },
  61. );
  62. });
  63. }
  64. void _startListening() {
  65. appListener.start(
  66. onAppUpdated: (app) {
  67. if (!isClosed) {
  68. add(AppEvent.appDidUpdate(app));
  69. }
  70. },
  71. );
  72. }
  73. Future<void> _renameView(Rename e, Emitter<AppState> emit) async {
  74. final result = await ViewBackendService.updateView(
  75. viewId: state.view.id,
  76. name: e.newName,
  77. );
  78. result.fold(
  79. (l) => emit(state.copyWith(successOrFailure: left(unit))),
  80. (error) => emit(state.copyWith(successOrFailure: right(error))),
  81. );
  82. }
  83. // Delete the current app
  84. Future<void> _deleteApp(Emitter<AppState> emit) async {
  85. final result = await ViewBackendService.delete(viewId: state.view.id);
  86. result.fold(
  87. (unit) => emit(state.copyWith(successOrFailure: left(unit))),
  88. (error) => emit(state.copyWith(successOrFailure: right(error))),
  89. );
  90. }
  91. Future<void> _deleteView(Emitter<AppState> emit, String viewId) async {
  92. final result = await ViewBackendService.deleteView(viewId: viewId);
  93. result.fold(
  94. (unit) => emit(state.copyWith(successOrFailure: left(unit))),
  95. (error) => emit(state.copyWith(successOrFailure: right(error))),
  96. );
  97. }
  98. Future<void> _createView(CreateView value, Emitter<AppState> emit) async {
  99. final result = await ViewBackendService.createView(
  100. parentViewId: state.view.id,
  101. name: value.name,
  102. desc: value.desc ?? "",
  103. layoutType: value.pluginBuilder.layoutType!,
  104. initialDataBytes: value.initialDataBytes,
  105. ext: value.ext ?? {},
  106. );
  107. result.fold(
  108. (view) => emit(
  109. state.copyWith(
  110. latestCreatedView: value.openAfterCreated ? view : null,
  111. successOrFailure: left(unit),
  112. ),
  113. ),
  114. (error) {
  115. Log.error(error);
  116. emit(state.copyWith(successOrFailure: right(error)));
  117. },
  118. );
  119. }
  120. @override
  121. Future<void> close() async {
  122. await appListener.stop();
  123. return super.close();
  124. }
  125. Future<void> _loadViews(Emitter<AppState> emit) async {
  126. final viewsOrFailed =
  127. await ViewBackendService.getViews(viewId: state.view.id);
  128. viewsOrFailed.fold(
  129. (views) => emit(state.copyWith(views: views)),
  130. (error) {
  131. Log.error(error);
  132. emit(state.copyWith(successOrFailure: right(error)));
  133. },
  134. );
  135. }
  136. }
  137. @freezed
  138. class AppEvent with _$AppEvent {
  139. const factory AppEvent.initial() = Initial;
  140. const factory AppEvent.createView(
  141. String name,
  142. PluginBuilder pluginBuilder, {
  143. String? desc,
  144. /// ~~The initial data should be the JSON of the document~~
  145. /// ~~For example: {"document":{"type":"editor","children":[]}}~~
  146. ///
  147. /// - Document:
  148. /// the initial data should be the string that can be converted into [DocumentDataPB]
  149. ///
  150. List<int>? initialDataBytes,
  151. Map<String, String>? ext,
  152. /// open the view after created
  153. @Default(true) bool openAfterCreated,
  154. }) = CreateView;
  155. const factory AppEvent.loadViews() = LoadApp;
  156. const factory AppEvent.delete() = DeleteApp;
  157. const factory AppEvent.deleteView(String viewId) = DeleteView;
  158. const factory AppEvent.rename(String newName) = Rename;
  159. const factory AppEvent.appDidUpdate(ViewPB app) = AppDidUpdate;
  160. }
  161. @freezed
  162. class AppState with _$AppState {
  163. const factory AppState({
  164. required ViewPB view,
  165. required List<ViewPB> views,
  166. ViewPB? latestCreatedView,
  167. required Either<Unit, FlowyError> successOrFailure,
  168. }) = _AppState;
  169. factory AppState.initial(ViewPB view) => AppState(
  170. view: view,
  171. views: view.childViews,
  172. successOrFailure: left(unit),
  173. );
  174. }
  175. class AppViewDataContext extends ChangeNotifier {
  176. final String viewId;
  177. final ValueNotifier<List<ViewPB>> _viewsNotifier = ValueNotifier([]);
  178. final ValueNotifier<ViewPB?> _selectedViewNotifier = ValueNotifier(null);
  179. VoidCallback? _menuSharedStateListener;
  180. ExpandableController expandController =
  181. ExpandableController(initialExpanded: false);
  182. AppViewDataContext({required this.viewId}) {
  183. _setLatestView(getIt<MenuSharedState>().latestOpenView);
  184. _menuSharedStateListener =
  185. getIt<MenuSharedState>().addLatestViewListener((view) {
  186. _setLatestView(view);
  187. });
  188. }
  189. VoidCallback addSelectedViewChangeListener(void Function(ViewPB?) callback) {
  190. listener() {
  191. callback(_selectedViewNotifier.value);
  192. }
  193. _selectedViewNotifier.addListener(listener);
  194. return listener;
  195. }
  196. void removeSelectedViewListener(VoidCallback listener) {
  197. _selectedViewNotifier.removeListener(listener);
  198. }
  199. void _setLatestView(ViewPB? view) {
  200. view?.freeze();
  201. if (_selectedViewNotifier.value != view) {
  202. _selectedViewNotifier.value = view;
  203. _expandIfNeed();
  204. notifyListeners();
  205. }
  206. }
  207. ViewPB? get selectedView => _selectedViewNotifier.value;
  208. set views(List<ViewPB> views) {
  209. if (_viewsNotifier.value != views) {
  210. _viewsNotifier.value = views;
  211. _expandIfNeed();
  212. notifyListeners();
  213. }
  214. }
  215. UnmodifiableListView<ViewPB> get views =>
  216. UnmodifiableListView(_viewsNotifier.value);
  217. VoidCallback addViewsChangeListener(
  218. void Function(UnmodifiableListView<ViewPB>) callback,
  219. ) {
  220. listener() {
  221. callback(views);
  222. }
  223. _viewsNotifier.addListener(listener);
  224. return listener;
  225. }
  226. void removeViewsListener(VoidCallback listener) {
  227. _viewsNotifier.removeListener(listener);
  228. }
  229. void _expandIfNeed() {
  230. if (_selectedViewNotifier.value == null) {
  231. return;
  232. }
  233. if (!_viewsNotifier.value.contains(_selectedViewNotifier.value)) {
  234. return;
  235. }
  236. if (expandController.expanded == false) {
  237. // Workaround: Delay 150 milliseconds to make the smooth animation while expanding
  238. Future.delayed(const Duration(milliseconds: 150), () {
  239. expandController.expanded = true;
  240. });
  241. }
  242. }
  243. @override
  244. void dispose() {
  245. if (_menuSharedStateListener != null) {
  246. getIt<MenuSharedState>()
  247. .removeLatestViewListener(_menuSharedStateListener!);
  248. }
  249. super.dispose();
  250. }
  251. }