app_bloc.dart 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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/app/app_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 AppBackendService appService;
  18. final AppListener appListener;
  19. AppBloc({required ViewPB view})
  20. : appService = AppBackendService(),
  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 =
  75. await appService.updateApp(appId: state.view.id, name: e.newName);
  76. result.fold(
  77. (l) => emit(state.copyWith(successOrFailure: left(unit))),
  78. (error) => emit(state.copyWith(successOrFailure: right(error))),
  79. );
  80. }
  81. // Delete the current app
  82. Future<void> _deleteApp(Emitter<AppState> emit) async {
  83. final result = await appService.delete(viewId: state.view.id);
  84. result.fold(
  85. (unit) => emit(state.copyWith(successOrFailure: left(unit))),
  86. (error) => emit(state.copyWith(successOrFailure: right(error))),
  87. );
  88. }
  89. Future<void> _deleteView(Emitter<AppState> emit, String viewId) async {
  90. final result = await appService.deleteView(viewId: viewId);
  91. result.fold(
  92. (unit) => emit(state.copyWith(successOrFailure: left(unit))),
  93. (error) => emit(state.copyWith(successOrFailure: right(error))),
  94. );
  95. }
  96. Future<void> _createView(CreateView value, Emitter<AppState> emit) async {
  97. final result = await appService.createView(
  98. parentViewId: state.view.id,
  99. name: value.name,
  100. desc: value.desc ?? "",
  101. layoutType: value.pluginBuilder.layoutType!,
  102. initialDataBytes: value.initialDataBytes,
  103. ext: value.ext ?? {},
  104. );
  105. result.fold(
  106. (view) => emit(
  107. state.copyWith(
  108. latestCreatedView: value.openAfterCreated ? view : null,
  109. successOrFailure: left(unit),
  110. ),
  111. ),
  112. (error) {
  113. Log.error(error);
  114. emit(state.copyWith(successOrFailure: right(error)));
  115. },
  116. );
  117. }
  118. @override
  119. Future<void> close() async {
  120. await appListener.stop();
  121. return super.close();
  122. }
  123. Future<void> _loadViews(Emitter<AppState> emit) async {
  124. final viewsOrFailed = await appService.getViews(viewId: state.view.id);
  125. viewsOrFailed.fold(
  126. (views) => emit(state.copyWith(views: views)),
  127. (error) {
  128. Log.error(error);
  129. emit(state.copyWith(successOrFailure: right(error)));
  130. },
  131. );
  132. }
  133. }
  134. @freezed
  135. class AppEvent with _$AppEvent {
  136. const factory AppEvent.initial() = Initial;
  137. const factory AppEvent.createView(
  138. String name,
  139. PluginBuilder pluginBuilder, {
  140. String? desc,
  141. /// ~~The initial data should be the JSON of the document~~
  142. /// ~~For example: {"document":{"type":"editor","children":[]}}~~
  143. ///
  144. /// - Document:
  145. /// the initial data should be the string that can be converted into [DocumentDataPB]
  146. ///
  147. List<int>? initialDataBytes,
  148. Map<String, String>? ext,
  149. /// open the view after created
  150. @Default(true) bool openAfterCreated,
  151. }) = CreateView;
  152. const factory AppEvent.loadViews() = LoadApp;
  153. const factory AppEvent.delete() = DeleteApp;
  154. const factory AppEvent.deleteView(String viewId) = DeleteView;
  155. const factory AppEvent.rename(String newName) = Rename;
  156. const factory AppEvent.appDidUpdate(ViewPB app) = AppDidUpdate;
  157. }
  158. @freezed
  159. class AppState with _$AppState {
  160. const factory AppState({
  161. required ViewPB view,
  162. required List<ViewPB> views,
  163. ViewPB? latestCreatedView,
  164. required Either<Unit, FlowyError> successOrFailure,
  165. }) = _AppState;
  166. factory AppState.initial(ViewPB view) => AppState(
  167. view: view,
  168. views: view.childViews,
  169. successOrFailure: left(unit),
  170. );
  171. }
  172. class AppViewDataContext extends ChangeNotifier {
  173. final String viewId;
  174. final ValueNotifier<List<ViewPB>> _viewsNotifier = ValueNotifier([]);
  175. final ValueNotifier<ViewPB?> _selectedViewNotifier = ValueNotifier(null);
  176. VoidCallback? _menuSharedStateListener;
  177. ExpandableController expandController =
  178. ExpandableController(initialExpanded: false);
  179. AppViewDataContext({required this.viewId}) {
  180. _setLatestView(getIt<MenuSharedState>().latestOpenView);
  181. _menuSharedStateListener =
  182. getIt<MenuSharedState>().addLatestViewListener((view) {
  183. _setLatestView(view);
  184. });
  185. }
  186. VoidCallback addSelectedViewChangeListener(void Function(ViewPB?) callback) {
  187. listener() {
  188. callback(_selectedViewNotifier.value);
  189. }
  190. _selectedViewNotifier.addListener(listener);
  191. return listener;
  192. }
  193. void removeSelectedViewListener(VoidCallback listener) {
  194. _selectedViewNotifier.removeListener(listener);
  195. }
  196. void _setLatestView(ViewPB? view) {
  197. view?.freeze();
  198. if (_selectedViewNotifier.value != view) {
  199. _selectedViewNotifier.value = view;
  200. _expandIfNeed();
  201. notifyListeners();
  202. }
  203. }
  204. ViewPB? get selectedView => _selectedViewNotifier.value;
  205. set views(List<ViewPB> views) {
  206. if (_viewsNotifier.value != views) {
  207. _viewsNotifier.value = views;
  208. _expandIfNeed();
  209. notifyListeners();
  210. }
  211. }
  212. UnmodifiableListView<ViewPB> get views =>
  213. UnmodifiableListView(_viewsNotifier.value);
  214. VoidCallback addViewsChangeListener(
  215. void Function(UnmodifiableListView<ViewPB>) callback,
  216. ) {
  217. listener() {
  218. callback(views);
  219. }
  220. _viewsNotifier.addListener(listener);
  221. return listener;
  222. }
  223. void removeViewsListener(VoidCallback listener) {
  224. _viewsNotifier.removeListener(listener);
  225. }
  226. void _expandIfNeed() {
  227. if (_selectedViewNotifier.value == null) {
  228. return;
  229. }
  230. if (!_viewsNotifier.value.contains(_selectedViewNotifier.value)) {
  231. return;
  232. }
  233. if (expandController.expanded == false) {
  234. // Workaround: Delay 150 milliseconds to make the smooth animation while expanding
  235. Future.delayed(const Duration(milliseconds: 150), () {
  236. expandController.expanded = true;
  237. });
  238. }
  239. }
  240. @override
  241. void dispose() {
  242. if (_menuSharedStateListener != null) {
  243. getIt<MenuSharedState>()
  244. .removeLatestViewListener(_menuSharedStateListener!);
  245. }
  246. super.dispose();
  247. }
  248. }