feat: use result instead of either (#4724)

* feat: use result instead of either

* chore: remove dartz
This commit is contained in:
Lucas.Xu 2024-02-24 20:54:10 +07:00 committed by GitHub
parent 236b5bfe90
commit 2abb396467
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
190 changed files with 1813 additions and 1527 deletions

View File

@ -306,7 +306,7 @@ extension CommonOperations on WidgetTester {
KVKeys.showRenameDialogWhenCreatingNewFile, KVKeys.showRenameDialogWhenCreatingNewFile,
(value) => bool.parse(value), (value) => bool.parse(value),
); );
final showRenameDialog = settingsOrFailure.fold(() => false, (r) => r); final showRenameDialog = settingsOrFailure ?? false;
if (showRenameDialog) { if (showRenameDialog) {
await tapOKButton(); await tapOKButton();
} }

View File

@ -1,10 +1,9 @@
import 'package:dartz/dartz.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
abstract class KeyValueStorage { abstract class KeyValueStorage {
Future<void> set(String key, String value); Future<void> set(String key, String value);
Future<Option<String>> get(String key); Future<String?> get(String key);
Future<Option<T>> getWithFormat<T>( Future<T?> getWithFormat<T>(
String key, String key,
T Function(String value) formatter, T Function(String value) formatter,
); );
@ -17,26 +16,26 @@ class DartKeyValue implements KeyValueStorage {
SharedPreferences get sharedPreferences => _sharedPreferences!; SharedPreferences get sharedPreferences => _sharedPreferences!;
@override @override
Future<Option<String>> get(String key) async { Future<String?> get(String key) async {
await _initSharedPreferencesIfNeeded(); await _initSharedPreferencesIfNeeded();
final value = sharedPreferences.getString(key); final value = sharedPreferences.getString(key);
if (value != null) { if (value != null) {
return Some(value); return value;
} }
return none(); return null;
} }
@override @override
Future<Option<T>> getWithFormat<T>( Future<T?> getWithFormat<T>(
String key, String key,
T Function(String value) formatter, T Function(String value) formatter,
) async { ) async {
final value = await get(key); final value = await get(key);
return value.fold( if (value == null) {
() => none(), return null;
(s) => Some(formatter(s)), }
); return formatter(value);
} }
@override @override

View File

@ -49,7 +49,7 @@ class KVKeys {
static const String kCloudType = 'kCloudType'; static const String kCloudType = 'kCloudType';
static const String kAppflowyCloudBaseURL = 'kAppFlowyCloudBaseURL'; static const String kAppflowyCloudBaseURL = 'kAppFlowyCloudBaseURL';
static const String kSupabaseURL = 'kSupbaseURL'; static const String kSupabaseURL = 'kSupabaseURL';
static const String kSupabaseAnonKey = 'kSupabaseAnonKey'; static const String kSupabaseAnonKey = 'kSupabaseAnonKey';
/// The key for saving the text scale factor. /// The key for saving the text scale factor.

View File

@ -1,2 +1 @@
export 'target_platform.dart'; export 'target_platform.dart';
export 'url_validator.dart';

View File

@ -1,21 +0,0 @@
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'url_validator.freezed.dart';
Either<UriFailure, Uri> parseValidUrl(String url) {
try {
final uri = Uri.parse(url);
if (uri.scheme.isEmpty || uri.host.isEmpty) {
return left(const UriFailure.invalidSchemeHost());
}
return right(uri);
} on FormatException {
return left(const UriFailure.invalidUriFormat());
}
}
@freezed
class UriFailure with _$UriFailure {
const factory UriFailure.invalidSchemeHost() = _InvalidSchemeHost;
const factory UriFailure.invalidUriFormat() = _InvalidUriFormat;
}

View File

@ -3,11 +3,11 @@ import 'dart:typed_data';
import 'package:appflowy/core/notification/notification_helper.dart'; import 'package:appflowy/core/notification/notification_helper.dart';
import 'package:appflowy_backend/protobuf/flowy-document/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-document/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
typedef DocumentNotificationCallback = void Function( typedef DocumentNotificationCallback = void Function(
DocumentNotification, DocumentNotification,
Either<Uint8List, FlowyError>, FlowyResult<Uint8List, FlowyError>,
); );
class DocumentNotificationParser class DocumentNotificationParser

View File

@ -1,17 +1,18 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/rust_stream.dart'; import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart'; import 'notification_helper.dart';
// Folder // Folder
typedef FolderNotificationCallback = void Function( typedef FolderNotificationCallback = void Function(
FolderNotification, FolderNotification,
Either<Uint8List, FlowyError>, FlowyResult<Uint8List, FlowyError>,
); );
class FolderNotificationParser class FolderNotificationParser
@ -27,7 +28,7 @@ class FolderNotificationParser
typedef FolderNotificationHandler = Function( typedef FolderNotificationHandler = Function(
FolderNotification ty, FolderNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
); );
class FolderNotificationListener { class FolderNotificationListener {

View File

@ -1,17 +1,18 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/rust_stream.dart'; import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart'; import 'notification_helper.dart';
// DatabasePB // DatabasePB
typedef DatabaseNotificationCallback = void Function( typedef DatabaseNotificationCallback = void Function(
DatabaseNotification, DatabaseNotification,
Either<Uint8List, FlowyError>, FlowyResult<Uint8List, FlowyError>,
); );
class DatabaseNotificationParser class DatabaseNotificationParser
@ -27,7 +28,7 @@ class DatabaseNotificationParser
typedef DatabaseNotificationHandler = Function( typedef DatabaseNotificationHandler = Function(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
); );
class DatabaseNotificationListener { class DatabaseNotificationListener {

View File

@ -1,6 +1,7 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class NotificationParser<T, E> { class NotificationParser<T, E> {
NotificationParser({ NotificationParser({
@ -11,7 +12,7 @@ class NotificationParser<T, E> {
}); });
String? id; String? id;
void Function(T, Either<Uint8List, E>) callback; void Function(T, FlowyResult<Uint8List, E>) callback;
E Function(Uint8List) errorParser; E Function(Uint8List) errorParser;
T? Function(int) tyParser; T? Function(int) tyParser;
@ -30,10 +31,10 @@ class NotificationParser<T, E> {
if (subject.hasError()) { if (subject.hasError()) {
final bytes = Uint8List.fromList(subject.error); final bytes = Uint8List.fromList(subject.error);
final error = errorParser(bytes); final error = errorParser(bytes);
callback(ty, right(error)); callback(ty, FlowyResult.failure(error));
} else { } else {
final bytes = Uint8List.fromList(subject.payload); final bytes = Uint8List.fromList(subject.payload);
callback(ty, left(bytes)); callback(ty, FlowyResult.success(bytes));
} }
} }
} }

View File

@ -1,17 +1,18 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/rust_stream.dart'; import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart'; import 'notification_helper.dart';
// User // User
typedef UserNotificationCallback = void Function( typedef UserNotificationCallback = void Function(
UserNotification, UserNotification,
Either<Uint8List, FlowyError>, FlowyResult<Uint8List, FlowyError>,
); );
class UserNotificationParser class UserNotificationParser
@ -27,7 +28,7 @@ class UserNotificationParser
typedef UserNotificationHandler = Function( typedef UserNotificationHandler = Function(
UserNotification ty, UserNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
); );
class UserNotificationListener { class UserNotificationListener {

View File

@ -1,19 +1,25 @@
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-date/entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-date/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class DateService { class DateService {
static Future<Either<FlowyError, DateTime>> queryDate(String search) async { static Future<FlowyResult<DateTime, FlowyError>> queryDate(
String search,
) async {
final query = DateQueryPB.create()..query = search; final query = DateQueryPB.create()..query = search;
final result = (await DateEventQueryDate(query).send()).swap(); final result = await DateEventQueryDate(query).send();
return result.fold((l) => left(l), (r) { return result.fold(
final date = DateTime.tryParse(r.date); (s) {
final date = DateTime.tryParse(s.date);
if (date != null) { if (date != null) {
return right(date); return FlowyResult.success(date);
} }
return FlowyResult.failure(
return left(FlowyError(msg: 'Could not parse Date (NLP) from String')); FlowyError(msg: 'Could not parse Date (NLP) from String'),
}); );
},
(e) => FlowyResult.failure(e),
);
} }
} }

View File

@ -4,7 +4,6 @@ import 'package:appflowy/env/backend_env.dart';
import 'package:appflowy/env/env.dart'; import 'package:appflowy/env/env.dart';
import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:dartz/dartz.dart';
/// Sets the cloud type for the application. /// Sets the cloud type for the application.
/// ///
@ -52,7 +51,7 @@ const String kAppflowyCloudUrl = "https://beta.appflowy.cloud";
/// ///
Future<AuthenticatorType> getAuthenticatorType() async { Future<AuthenticatorType> getAuthenticatorType() async {
final value = await getIt<KeyValueStorage>().get(KVKeys.kCloudType); final value = await getIt<KeyValueStorage>().get(KVKeys.kCloudType);
if (value.isNone() && !integrationMode().isUnitTest) { if (value == null && !integrationMode().isUnitTest) {
// if the cloud type is not set, then set it to AppFlowy Cloud as default. // if the cloud type is not set, then set it to AppFlowy Cloud as default.
await useAppFlowyBetaCloudWithURL( await useAppFlowyBetaCloudWithURL(
kAppflowyCloudUrl, kAppflowyCloudUrl,
@ -61,7 +60,7 @@ Future<AuthenticatorType> getAuthenticatorType() async {
return AuthenticatorType.appflowyCloud; return AuthenticatorType.appflowyCloud;
} }
switch (value.getOrElse(() => "0")) { switch (value ?? "0") {
case "0": case "0":
return AuthenticatorType.local; return AuthenticatorType.local;
case "1": case "1":
@ -177,16 +176,13 @@ AuthenticatorType currentCloudType() {
return getIt<AppFlowyCloudSharedEnv>().authenticatorType; return getIt<AppFlowyCloudSharedEnv>().authenticatorType;
} }
Future<void> _setAppFlowyCloudUrl(Option<String> url) async { Future<void> _setAppFlowyCloudUrl(String? url) async {
await url.fold( await getIt<KeyValueStorage>().set(KVKeys.kAppflowyCloudBaseURL, url ?? '');
() => getIt<KeyValueStorage>().set(KVKeys.kAppflowyCloudBaseURL, ""),
(s) => getIt<KeyValueStorage>().set(KVKeys.kAppflowyCloudBaseURL, s),
);
} }
Future<void> useSelfHostedAppFlowyCloudWithURL(String url) async { Future<void> useSelfHostedAppFlowyCloudWithURL(String url) async {
await _setAuthenticatorType(AuthenticatorType.appflowyCloudSelfHost); await _setAuthenticatorType(AuthenticatorType.appflowyCloudSelfHost);
await _setAppFlowyCloudUrl(Some(url)); await _setAppFlowyCloudUrl(url);
} }
Future<void> useAppFlowyBetaCloudWithURL( Future<void> useAppFlowyBetaCloudWithURL(
@ -194,7 +190,7 @@ Future<void> useAppFlowyBetaCloudWithURL(
AuthenticatorType authenticatorType, AuthenticatorType authenticatorType,
) async { ) async {
await _setAuthenticatorType(authenticatorType); await _setAuthenticatorType(authenticatorType);
await _setAppFlowyCloudUrl(Some(url)); await _setAppFlowyCloudUrl(url);
} }
Future<void> useLocalServer() async { Future<void> useLocalServer() async {
@ -206,7 +202,7 @@ Future<void> useSupabaseCloud({
required String anonKey, required String anonKey,
}) async { }) async {
await _setAuthenticatorType(AuthenticatorType.supabase); await _setAuthenticatorType(AuthenticatorType.supabase);
await setSupbaseServer(Some(url), Some(anonKey)); await setSupabaseServer(url, anonKey);
} }
/// Use getIt<AppFlowyCloudSharedEnv>() to get the shared environment. /// Use getIt<AppFlowyCloudSharedEnv>() to get the shared environment.
@ -314,10 +310,7 @@ Future<AppFlowyCloudConfiguration> getAppFlowyCloudConfig(
Future<String> getAppFlowyCloudUrl() async { Future<String> getAppFlowyCloudUrl() async {
final result = final result =
await getIt<KeyValueStorage>().get(KVKeys.kAppflowyCloudBaseURL); await getIt<KeyValueStorage>().get(KVKeys.kAppflowyCloudBaseURL);
return result.fold( return result ?? kAppflowyCloudUrl;
() => kAppflowyCloudUrl,
(url) => url,
);
} }
Future<String> _getAppFlowyCloudWSUrl(String baseURL) async { Future<String> _getAppFlowyCloudWSUrl(String baseURL) async {
@ -339,27 +332,30 @@ Future<String> _getAppFlowyCloudGotrueUrl(String baseURL) async {
return "$baseURL/gotrue"; return "$baseURL/gotrue";
} }
Future<void> setSupbaseServer( Future<void> setSupabaseServer(
Option<String> url, String? url,
Option<String> anonKey, String? anonKey,
) async { ) async {
assert( assert(
(url.isSome() && anonKey.isSome()) || (url.isNone() && anonKey.isNone()), (url != null && anonKey != null) || (url == null && anonKey == null),
"Either both Supabase URL and anon key must be set, or both should be unset", "Either both Supabase URL and anon key must be set, or both should be unset",
); );
await url.fold( if (url == null) {
() => getIt<KeyValueStorage>().remove(KVKeys.kSupabaseURL), await getIt<KeyValueStorage>().remove(KVKeys.kSupabaseURL);
(s) => getIt<KeyValueStorage>().set(KVKeys.kSupabaseURL, s), } else {
); await getIt<KeyValueStorage>().set(KVKeys.kSupabaseURL, url);
await anonKey.fold( }
() => getIt<KeyValueStorage>().remove(KVKeys.kSupabaseAnonKey),
(s) => getIt<KeyValueStorage>().set(KVKeys.kSupabaseAnonKey, s), if (anonKey == null) {
); await getIt<KeyValueStorage>().remove(KVKeys.kSupabaseAnonKey);
} else {
await getIt<KeyValueStorage>().set(KVKeys.kSupabaseAnonKey, anonKey);
}
} }
Future<SupabaseConfiguration> getSupabaseCloudConfig() async { Future<SupabaseConfiguration> getSupabaseCloudConfig() async {
final url = await _getSupbaseUrl(); final url = await _getSupabaseUrl();
final anonKey = await _getSupabaseAnonKey(); final anonKey = await _getSupabaseAnonKey();
return SupabaseConfiguration( return SupabaseConfiguration(
url: url, url: url,
@ -367,18 +363,12 @@ Future<SupabaseConfiguration> getSupabaseCloudConfig() async {
); );
} }
Future<String> _getSupbaseUrl() async { Future<String> _getSupabaseUrl() async {
final result = await getIt<KeyValueStorage>().get(KVKeys.kSupabaseURL); final result = await getIt<KeyValueStorage>().get(KVKeys.kSupabaseURL);
return result.fold( return result ?? '';
() => "",
(url) => url,
);
} }
Future<String> _getSupabaseAnonKey() async { Future<String> _getSupabaseAnonKey() async {
final result = await getIt<KeyValueStorage>().get(KVKeys.kSupabaseAnonKey); final result = await getIt<KeyValueStorage>().get(KVKeys.kSupabaseAnonKey);
return result.fold( return result ?? '';
() => "",
(url) => url,
);
} }

View File

@ -31,8 +31,8 @@ class UserProfileBloc extends Bloc<UserProfileEvent, UserProfileState> {
); );
final userProfile = userOrFailure.fold( final userProfile = userOrFailure.fold(
(error) => null,
(userProfilePB) => userProfilePB, (userProfilePB) => userProfilePB,
(error) => null,
); );
if (workspaceSetting == null || userProfile == null) { if (workspaceSetting == null || userProfile == null) {

View File

@ -13,7 +13,7 @@ import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view/view_service.dart'; import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:dartz/dartz.dart' hide State; import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -40,7 +40,7 @@ class MobileViewPage extends StatefulWidget {
} }
class _MobileViewPageState extends State<MobileViewPage> { class _MobileViewPageState extends State<MobileViewPage> {
late final Future<Either<ViewPB, FlowyError>> future; late final Future<FlowyResult<ViewPB, FlowyError>> future;
@override @override
void initState() { void initState() {

View File

@ -35,10 +35,12 @@ class MobileFavoriteScreen extends StatelessWidget {
}, },
(error) => null, (error) => null,
); );
final userProfile = final userProfile = snapshots.data?[1].fold(
snapshots.data?[1].fold((error) => null, (userProfilePB) { (userProfilePB) {
return userProfilePB as UserProfilePB?; return userProfilePB as UserProfilePB?;
}); },
(error) => null,
);
// In the unlikely case either of the above is null, eg. // In the unlikely case either of the above is null, eg.
// when a workspace is already open this can happen. // when a workspace is already open this can happen.

View File

@ -41,10 +41,12 @@ class MobileHomeScreen extends StatelessWidget {
}, },
(error) => null, (error) => null,
); );
final userProfile = final userProfile = snapshots.data?[1].fold(
snapshots.data?[1].fold((error) => null, (userProfilePB) { (userProfilePB) {
return userProfilePB as UserProfilePB?; return userProfilePB as UserProfilePB?;
}); },
(error) => null,
);
// In the unlikely case either of the above is null, eg. // In the unlikely case either of the above is null, eg.
// when a workspace is already open this can happen. // when a workspace is already open this can happen.

View File

@ -35,12 +35,15 @@ class _MobileHomeSettingPageState extends State<MobileHomeSettingPage> {
return const Center(child: CircularProgressIndicator.adaptive()); return const Center(child: CircularProgressIndicator.adaptive());
} }
final userProfile = snapshot.data?.fold((error) { final userProfile = snapshot.data?.fold(
(userProfile) {
return userProfile;
},
(error) {
errorMsg = error.msg; errorMsg = error.msg;
return null; return null;
}, (userProfile) { },
return userProfile; );
});
return Scaffold( return Scaffold(
appBar: FlowyAppBar( appBar: FlowyAppBar(

View File

@ -5,6 +5,7 @@ import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/application/sign_in_bloc.dart'; import 'package:appflowy/user/application/sign_in_bloc.dart';
import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/sign_in_or_logout_button.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/sign_in_or_logout_button.dart';
import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart';
import 'package:appflowy_backend/log.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -27,12 +28,9 @@ class UserSessionSettingGroup extends StatelessWidget {
create: (context) => getIt<SignInBloc>(), create: (context) => getIt<SignInBloc>(),
child: BlocConsumer<SignInBloc, SignInState>( child: BlocConsumer<SignInBloc, SignInState>(
listener: (context, state) { listener: (context, state) {
state.successOrFail.fold( state.successOrFail?.fold(
() => null, (result) => runAppFlowy(),
(result) => result.fold( (e) => Log.error(e),
(l) {},
(r) async => runAppFlowy(),
),
); );
}, },
builder: (context, state) { builder: (context, state) {

View File

@ -4,11 +4,11 @@ import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart'; import 'package:flowy_infra/notifier.dart';
typedef UpdateCalculationValue typedef UpdateCalculationValue
= Either<CalculationChangesetNotificationPB, FlowyError>; = FlowyResult<CalculationChangesetNotificationPB, FlowyError>;
class CalculationsListener { class CalculationsListener {
CalculationsListener({required this.viewId}); CalculationsListener({required this.viewId});
@ -31,15 +31,15 @@ class CalculationsListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateCalculation: case DatabaseNotification.DidUpdateCalculation:
_calculationNotifier?.value = result.fold( _calculationNotifier?.value = result.fold(
(payload) => left( (payload) => FlowyResult.success(
CalculationChangesetNotificationPB.fromBuffer(payload), CalculationChangesetNotificationPB.fromBuffer(payload),
), ),
(err) => right(err), (err) => FlowyResult.failure(err),
); );
default: default:
break; break;

View File

@ -1,7 +1,7 @@
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class CalculationsBackendService { class CalculationsBackendService {
const CalculationsBackendService({required this.viewId}); const CalculationsBackendService({required this.viewId});
@ -9,7 +9,9 @@ class CalculationsBackendService {
final String viewId; final String viewId;
// Get Calculations (initial fetch) // Get Calculations (initial fetch)
Future<Either<RepeatedCalculationsPB, FlowyError>> getCalculations() async {
Future<FlowyResult<RepeatedCalculationsPB, FlowyError>>
getCalculations() async {
final payload = DatabaseViewIdPB()..value = viewId; final payload = DatabaseViewIdPB()..value = viewId;
return DatabaseEventGetAllCalculations(payload).send(); return DatabaseEventGetAllCalculations(payload).send();

View File

@ -1,12 +1,10 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart'; import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/cell/select_option_cell_service.dart'; import 'package:appflowy/plugins/database/application/cell/select_option_cell_service.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -52,7 +50,7 @@ class SelectOptionCellEditorBloc
await _createOption(optionName); await _createOption(optionName);
emit( emit(
state.copyWith( state.copyWith(
filter: none(), filter: null,
), ),
); );
}, },
@ -164,7 +162,7 @@ class SelectOptionCellEditorBloc
} }
// clear the filter // clear the filter
emit(state.copyWith(filter: none())); emit(state.copyWith(filter: null));
} }
void _selectMultipleOptions(List<String> optionNames) { void _selectMultipleOptions(List<String> optionNames) {
@ -186,12 +184,12 @@ class SelectOptionCellEditorBloc
void _filterOption(String optionName, Emitter<SelectOptionEditorState> emit) { void _filterOption(String optionName, Emitter<SelectOptionEditorState> emit) {
final _MakeOptionResult result = _makeOptions( final _MakeOptionResult result = _makeOptions(
Some(optionName), optionName,
state.allOptions, state.allOptions,
); );
emit( emit(
state.copyWith( state.copyWith(
filter: Some(optionName), filter: optionName,
options: result.options, options: result.options,
createOption: result.createOption, createOption: result.createOption,
), ),
@ -201,7 +199,7 @@ class SelectOptionCellEditorBloc
Future<void> _loadOptions() async { Future<void> _loadOptions() async {
final result = await _selectOptionService.getCellData(); final result = await _selectOptionService.getCellData();
if (isClosed) { if (isClosed) {
Log.warn("Unexpected closing the bloc"); Log.warn("Unexpecteded closing the bloc");
return; return;
} }
@ -220,28 +218,26 @@ class SelectOptionCellEditorBloc
} }
_MakeOptionResult _makeOptions( _MakeOptionResult _makeOptions(
Option<String> filter, String? filter,
List<SelectOptionPB> allOptions, List<SelectOptionPB> allOptions,
) { ) {
final List<SelectOptionPB> options = List.from(allOptions); final List<SelectOptionPB> options = List.from(allOptions);
Option<String> createOption = filter; String? createOption = filter;
filter.foldRight(null, (filter, previous) { if (filter != null && filter.isNotEmpty) {
if (filter.isNotEmpty) {
options.retainWhere((option) { options.retainWhere((option) {
final name = option.name.toLowerCase(); final name = option.name.toLowerCase();
final lFilter = filter.toLowerCase(); final lFilter = filter.toLowerCase();
if (name == lFilter) { if (name == lFilter) {
createOption = none(); createOption = null;
} }
return name.contains(lFilter); return name.contains(lFilter);
}); });
} else { } else {
createOption = none(); createOption = null;
} }
});
return _MakeOptionResult( return _MakeOptionResult(
options: options, options: options,
@ -295,8 +291,8 @@ class SelectOptionEditorState with _$SelectOptionEditorState {
required List<SelectOptionPB> options, required List<SelectOptionPB> options,
required List<SelectOptionPB> allOptions, required List<SelectOptionPB> allOptions,
required List<SelectOptionPB> selectedOptions, required List<SelectOptionPB> selectedOptions,
required Option<String> createOption, required String? createOption,
required Option<String> filter, required String? filter,
}) = _SelectOptionEditorState; }) = _SelectOptionEditorState;
factory SelectOptionEditorState.initial(SelectOptionCellController context) { factory SelectOptionEditorState.initial(SelectOptionCellController context) {
@ -305,8 +301,8 @@ class SelectOptionEditorState with _$SelectOptionEditorState {
options: data?.options ?? [], options: data?.options ?? [],
allOptions: data?.options ?? [], allOptions: data?.options ?? [],
selectedOptions: data?.selectOptions ?? [], selectedOptions: data?.selectOptions ?? [],
createOption: none(), createOption: null,
filter: none(), filter: null,
); );
} }
} }
@ -318,5 +314,5 @@ class _MakeOptionResult {
}); });
List<SelectOptionPB> options; List<SelectOptionPB> options;
Option<String> createOption; String? createOption;
} }

View File

@ -10,7 +10,6 @@ import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -173,7 +172,7 @@ class CellController<T, D> {
Future<void> saveCellData( Future<void> saveCellData(
D data, { D data, {
bool debounce = false, bool debounce = false,
void Function(Option<FlowyError>)? onFinish, void Function(FlowyError?)? onFinish,
}) async { }) async {
_loadDataOperation?.cancel(); _loadDataOperation?.cancel();
if (debounce) { if (debounce) {

View File

@ -1,5 +1,4 @@
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:dartz/dartz.dart';
import 'cell_controller.dart'; import 'cell_controller.dart';
import 'cell_service.dart'; import 'cell_service.dart';
@ -7,7 +6,7 @@ import 'cell_service.dart';
/// Save the cell data to disk /// Save the cell data to disk
/// You can extend this class to do custom operations. /// You can extend this class to do custom operations.
abstract class CellDataPersistence<D> { abstract class CellDataPersistence<D> {
Future<Option<FlowyError>> save({ Future<FlowyError?> save({
required String viewId, required String viewId,
required CellContext cellContext, required CellContext cellContext,
required D data, required D data,
@ -18,7 +17,7 @@ class TextCellDataPersistence implements CellDataPersistence<String> {
TextCellDataPersistence(); TextCellDataPersistence();
@override @override
Future<Option<FlowyError>> save({ Future<FlowyError?> save({
required String viewId, required String viewId,
required CellContext cellContext, required CellContext cellContext,
required String data, required String data,
@ -30,8 +29,8 @@ class TextCellDataPersistence implements CellDataPersistence<String> {
); );
return fut.then((result) { return fut.then((result) {
return result.fold( return result.fold(
(l) => none(), (l) => null,
(err) => Some(err), (err) => err,
); );
}); });
} }

View File

@ -4,12 +4,12 @@ import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart'; import 'package:flowy_infra/notifier.dart';
import '../row/row_service.dart'; import '../row/row_service.dart';
typedef UpdateFieldNotifiedValue = Either<Unit, FlowyError>; typedef UpdateFieldNotifiedValue = FlowyResult<void, FlowyError>;
class CellListener { class CellListener {
CellListener({required this.rowId, required this.fieldId}); CellListener({required this.rowId, required this.fieldId});
@ -29,12 +29,15 @@ class CellListener {
); );
} }
void _handler(DatabaseNotification ty, Either<Uint8List, FlowyError> result) { void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateCell: case DatabaseNotification.DidUpdateCell:
result.fold( result.fold(
(payload) => _updateCellNotifier?.value = left(unit), (payload) => _updateCellNotifier?.value = FlowyResult.success(null),
(error) => _updateCellNotifier?.value = right(error), (error) => _updateCellNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,16 +1,16 @@
import 'dart:async'; import 'dart:async';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'cell_controller.dart'; import 'cell_controller.dart';
class CellBackendService { class CellBackendService {
CellBackendService(); CellBackendService();
static Future<Either<void, FlowyError>> updateCell({ static Future<FlowyResult<void, FlowyError>> updateCell({
required String viewId, required String viewId,
required CellContext cellContext, required CellContext cellContext,
required String data, required String data,
@ -23,7 +23,7 @@ class CellBackendService {
return DatabaseEventUpdateCell(payload).send(); return DatabaseEventUpdateCell(payload).send();
} }
static Future<Either<CellPB, FlowyError>> getCell({ static Future<FlowyResult<CellPB, FlowyError>> getCell({
required String viewId, required String viewId,
required CellContext cellContext, required CellContext cellContext,
}) { }) {

View File

@ -2,7 +2,7 @@ import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checklist_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/checklist_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:protobuf/protobuf.dart'; import 'package:protobuf/protobuf.dart';
class ChecklistCellBackendService { class ChecklistCellBackendService {
@ -16,7 +16,7 @@ class ChecklistCellBackendService {
final String fieldId; final String fieldId;
final String rowId; final String rowId;
Future<Either<Unit, FlowyError>> create({ Future<FlowyResult<void, FlowyError>> create({
required String name, required String name,
}) { }) {
final payload = ChecklistCellDataChangesetPB.create() final payload = ChecklistCellDataChangesetPB.create()
@ -28,7 +28,7 @@ class ChecklistCellBackendService {
return DatabaseEventUpdateChecklistCell(payload).send(); return DatabaseEventUpdateChecklistCell(payload).send();
} }
Future<Either<Unit, FlowyError>> delete({ Future<FlowyResult<void, FlowyError>> delete({
required List<String> optionIds, required List<String> optionIds,
}) { }) {
final payload = ChecklistCellDataChangesetPB.create() final payload = ChecklistCellDataChangesetPB.create()
@ -40,7 +40,7 @@ class ChecklistCellBackendService {
return DatabaseEventUpdateChecklistCell(payload).send(); return DatabaseEventUpdateChecklistCell(payload).send();
} }
Future<Either<Unit, FlowyError>> select({ Future<FlowyResult<void, FlowyError>> select({
required String optionId, required String optionId,
}) { }) {
final payload = ChecklistCellDataChangesetPB.create() final payload = ChecklistCellDataChangesetPB.create()
@ -52,7 +52,7 @@ class ChecklistCellBackendService {
return DatabaseEventUpdateChecklistCell(payload).send(); return DatabaseEventUpdateChecklistCell(payload).send();
} }
Future<Either<Unit, FlowyError>> updateName({ Future<FlowyResult<void, FlowyError>> updateName({
required SelectOptionPB option, required SelectOptionPB option,
required name, required name,
}) { }) {

View File

@ -2,7 +2,7 @@ import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/cell_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/cell_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:fixnum/fixnum.dart'; import 'package:fixnum/fixnum.dart';
final class DateCellBackendService { final class DateCellBackendService {
@ -17,7 +17,7 @@ final class DateCellBackendService {
final CellIdPB cellId; final CellIdPB cellId;
Future<Either<Unit, FlowyError>> update({ Future<FlowyResult<void, FlowyError>> update({
required bool includeTime, required bool includeTime,
required bool isRange, required bool isRange,
DateTime? date, DateTime? date,
@ -52,7 +52,7 @@ final class DateCellBackendService {
return DatabaseEventUpdateDateCell(payload).send(); return DatabaseEventUpdateDateCell(payload).send();
} }
Future<Either<Unit, FlowyError>> clear() { Future<FlowyResult<void, FlowyError>> clear() {
final payload = DateCellChangesetPB.create() final payload = DateCellChangesetPB.create()
..cellId = cellId ..cellId = cellId
..clearFlag = true; ..clearFlag = true;

View File

@ -1,9 +1,9 @@
import 'package:appflowy/plugins/database/application/field/type_option/type_option_service.dart'; import 'package:appflowy/plugins/database/application/field/type_option/type_option_service.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/cell_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/cell_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class SelectOptionCellBackendService { class SelectOptionCellBackendService {
SelectOptionCellBackendService({ SelectOptionCellBackendService({
@ -16,7 +16,7 @@ class SelectOptionCellBackendService {
final String fieldId; final String fieldId;
final String rowId; final String rowId;
Future<Either<Unit, FlowyError>> create({ Future<FlowyResult<void, FlowyError>> create({
required String name, required String name,
bool isSelected = true, bool isSelected = true,
}) { }) {
@ -34,13 +34,13 @@ class SelectOptionCellBackendService {
return DatabaseEventInsertOrUpdateSelectOption(payload).send(); return DatabaseEventInsertOrUpdateSelectOption(payload).send();
}, },
(r) => right(r), (r) => FlowyResult.failure(r),
); );
}, },
); );
} }
Future<Either<Unit, FlowyError>> update({ Future<FlowyResult<void, FlowyError>> update({
required SelectOptionPB option, required SelectOptionPB option,
}) { }) {
final payload = RepeatedSelectOptionPayload() final payload = RepeatedSelectOptionPayload()
@ -52,7 +52,7 @@ class SelectOptionCellBackendService {
return DatabaseEventInsertOrUpdateSelectOption(payload).send(); return DatabaseEventInsertOrUpdateSelectOption(payload).send();
} }
Future<Either<Unit, FlowyError>> delete({ Future<FlowyResult<void, FlowyError>> delete({
required Iterable<SelectOptionPB> options, required Iterable<SelectOptionPB> options,
}) { }) {
final payload = RepeatedSelectOptionPayload() final payload = RepeatedSelectOptionPayload()
@ -64,7 +64,7 @@ class SelectOptionCellBackendService {
return DatabaseEventDeleteSelectOption(payload).send(); return DatabaseEventDeleteSelectOption(payload).send();
} }
Future<Either<SelectOptionCellDataPB, FlowyError>> getCellData() { Future<FlowyResult<SelectOptionCellDataPB, FlowyError>> getCellData() {
final payload = CellIdPB() final payload = CellIdPB()
..viewId = viewId ..viewId = viewId
..fieldId = fieldId ..fieldId = fieldId
@ -73,7 +73,7 @@ class SelectOptionCellBackendService {
return DatabaseEventGetSelectOptionCellData(payload).send(); return DatabaseEventGetSelectOptionCellData(payload).send();
} }
Future<Either<void, FlowyError>> select({ Future<FlowyResult<void, FlowyError>> select({
required Iterable<String> optionIds, required Iterable<String> optionIds,
}) { }) {
final payload = SelectOptionCellChangesetPB() final payload = SelectOptionCellChangesetPB()
@ -83,7 +83,7 @@ class SelectOptionCellBackendService {
return DatabaseEventUpdateSelectOptionCell(payload).send(); return DatabaseEventUpdateSelectOptionCell(payload).send();
} }
Future<Either<void, FlowyError>> unSelect({ Future<FlowyResult<void, FlowyError>> unSelect({
required Iterable<String> optionIds, required Iterable<String> optionIds,
}) { }) {
final payload = SelectOptionCellChangesetPB() final payload = SelectOptionCellChangesetPB()

View File

@ -1,3 +1,5 @@
import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart'; import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/view/view_cache.dart'; import 'package:appflowy/plugins/database/application/view/view_cache.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
@ -10,17 +12,16 @@ import 'package:appflowy_backend/protobuf/flowy-database2/row_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'dart:async';
import 'package:dartz/dartz.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'database_view_service.dart'; import 'database_view_service.dart';
import 'defines.dart'; import 'defines.dart';
import 'group/group_listener.dart';
import 'layout/layout_service.dart'; import 'layout/layout_service.dart';
import 'layout/layout_setting_listener.dart'; import 'layout/layout_setting_listener.dart';
import 'row/row_cache.dart'; import 'row/row_cache.dart';
import 'group/group_listener.dart';
typedef OnGroupConfigurationChanged = void Function(List<GroupSettingPB>); typedef OnGroupConfigurationChanged = void Function(List<GroupSettingPB>);
typedef OnGroupByField = void Function(List<GroupPB>); typedef OnGroupByField = void Function(List<GroupPB>);
@ -136,7 +137,7 @@ class DatabaseController {
} }
} }
Future<Either<Unit, FlowyError>> open() async { Future<FlowyResult<void, FlowyError>> open() async {
return _databaseViewBackendSvc.openDatabase().then((result) { return _databaseViewBackendSvc.openDatabase().then((result) {
return result.fold( return result.fold(
(DatabasePB database) async { (DatabasePB database) async {
@ -157,21 +158,21 @@ class DatabaseController {
return Future(() async { return Future(() async {
await _loadGroups(); await _loadGroups();
await _loadLayoutSetting(); await _loadLayoutSetting();
return left(fields); return FlowyResult.success(fields);
}); });
}, },
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}, },
(err) => right(err), (err) => FlowyResult.failure(err),
); );
}); });
} }
Future<Either<Unit, FlowyError>> moveGroupRow({ Future<FlowyResult<void, FlowyError>> moveGroupRow({
required RowMetaPB fromRow, required RowMetaPB fromRow,
required String fromGroupId, required String fromGroupId,
required String toGroupId, required String toGroupId,
@ -185,7 +186,7 @@ class DatabaseController {
); );
} }
Future<Either<Unit, FlowyError>> moveRow({ Future<FlowyResult<void, FlowyError>> moveRow({
required String fromRowId, required String fromRowId,
required String toRowId, required String toRowId,
}) { }) {
@ -195,7 +196,7 @@ class DatabaseController {
); );
} }
Future<Either<Unit, FlowyError>> moveGroup({ Future<FlowyResult<void, FlowyError>> moveGroup({
required String fromGroupId, required String fromGroupId,
required String toGroupId, required String toGroupId,
}) { }) {

View File

@ -1,13 +1,16 @@
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class DatabaseBackendService { class DatabaseBackendService {
static Future<Either<List<DatabaseDescriptionPB>, FlowyError>> static Future<FlowyResult<List<DatabaseDescriptionPB>, FlowyError>>
getAllDatabases() { getAllDatabases() {
return DatabaseEventGetDatabases().send().then((result) { return DatabaseEventGetDatabases().send().then((result) {
return result.fold((l) => left(l.items), (r) => right(r)); return result.fold(
(l) => FlowyResult.success(l.items),
(r) => FlowyResult.failure(r),
);
}); });
} }
} }

View File

@ -3,7 +3,7 @@ import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'layout/layout_service.dart'; import 'layout/layout_service.dart';
@ -12,15 +12,15 @@ class DatabaseViewBackendService {
final String viewId; final String viewId;
/// Returns the datbaase id associated with the view. /// Returns the database id associated with the view.
Future<Either<String, FlowyError>> getDatabaseId() async { Future<FlowyResult<String, FlowyError>> getDatabaseId() async {
final payload = DatabaseViewIdPB(value: viewId); final payload = DatabaseViewIdPB(value: viewId);
return DatabaseEventGetDatabaseId(payload) return DatabaseEventGetDatabaseId(payload)
.send() .send()
.then((value) => value.leftMap((l) => l.value)); .then((value) => value.map((l) => l.value));
} }
static Future<Either<ViewPB, FlowyError>> updateLayout({ static Future<FlowyResult<ViewPB, FlowyError>> updateLayout({
required String viewId, required String viewId,
required DatabaseLayoutPB layout, required DatabaseLayoutPB layout,
}) { }) {
@ -31,12 +31,12 @@ class DatabaseViewBackendService {
return FolderEventUpdateView(payload).send(); return FolderEventUpdateView(payload).send();
} }
Future<Either<DatabasePB, FlowyError>> openDatabase() async { Future<FlowyResult<DatabasePB, FlowyError>> openDatabase() async {
final payload = DatabaseViewIdPB(value: viewId); final payload = DatabaseViewIdPB(value: viewId);
return DatabaseEventGetDatabase(payload).send(); return DatabaseEventGetDatabase(payload).send();
} }
Future<Either<Unit, FlowyError>> moveGroupRow({ Future<FlowyResult<void, FlowyError>> moveGroupRow({
required RowId fromRowId, required RowId fromRowId,
required String fromGroupId, required String fromGroupId,
required String toGroupId, required String toGroupId,
@ -55,7 +55,7 @@ class DatabaseViewBackendService {
return DatabaseEventMoveGroupRow(payload).send(); return DatabaseEventMoveGroupRow(payload).send();
} }
Future<Either<Unit, FlowyError>> moveRow({ Future<FlowyResult<void, FlowyError>> moveRow({
required String fromRowId, required String fromRowId,
required String toRowId, required String toRowId,
}) { }) {
@ -67,7 +67,7 @@ class DatabaseViewBackendService {
return DatabaseEventMoveRow(payload).send(); return DatabaseEventMoveRow(payload).send();
} }
Future<Either<Unit, FlowyError>> moveGroup({ Future<FlowyResult<void, FlowyError>> moveGroup({
required String fromGroupId, required String fromGroupId,
required String toGroupId, required String toGroupId,
}) { }) {
@ -79,7 +79,7 @@ class DatabaseViewBackendService {
return DatabaseEventMoveGroup(payload).send(); return DatabaseEventMoveGroup(payload).send();
} }
Future<Either<List<FieldPB>, FlowyError>> getFields({ Future<FlowyResult<List<FieldPB>, FlowyError>> getFields({
List<FieldIdPB>? fieldIds, List<FieldIdPB>? fieldIds,
}) { }) {
final payload = GetFieldPayloadPB.create()..viewId = viewId; final payload = GetFieldPayloadPB.create()..viewId = viewId;
@ -88,11 +88,14 @@ class DatabaseViewBackendService {
payload.fieldIds = RepeatedFieldIdPB(items: fieldIds); payload.fieldIds = RepeatedFieldIdPB(items: fieldIds);
} }
return DatabaseEventGetFields(payload).send().then((result) { return DatabaseEventGetFields(payload).send().then((result) {
return result.fold((l) => left(l.items), (r) => right(r)); return result.fold(
(l) => FlowyResult.success(l.items),
(r) => FlowyResult.failure(r),
);
}); });
} }
Future<Either<DatabaseLayoutSettingPB, FlowyError>> getLayoutSetting( Future<FlowyResult<DatabaseLayoutSettingPB, FlowyError>> getLayoutSetting(
DatabaseLayoutPB layoutType, DatabaseLayoutPB layoutType,
) { ) {
final payload = DatabaseLayoutMetaPB.create() final payload = DatabaseLayoutMetaPB.create()
@ -101,7 +104,7 @@ class DatabaseViewBackendService {
return DatabaseEventGetLayoutSetting(payload).send(); return DatabaseEventGetLayoutSetting(payload).send();
} }
Future<Either<Unit, FlowyError>> updateLayoutSetting({ Future<FlowyResult<void, FlowyError>> updateLayoutSetting({
required DatabaseLayoutPB layoutType, required DatabaseLayoutPB layoutType,
BoardLayoutSettingPB? boardLayoutSetting, BoardLayoutSettingPB? boardLayoutSetting,
CalendarLayoutSettingPB? calendarLayoutSetting, CalendarLayoutSettingPB? calendarLayoutSetting,
@ -121,12 +124,12 @@ class DatabaseViewBackendService {
return DatabaseEventSetLayoutSetting(payload).send(); return DatabaseEventSetLayoutSetting(payload).send();
} }
Future<Either<Unit, FlowyError>> closeView() { Future<FlowyResult<void, FlowyError>> closeView() {
final request = ViewIdPB(value: viewId); final request = ViewIdPB(value: viewId);
return FolderEventCloseView(request).send(); return FolderEventCloseView(request).send();
} }
Future<Either<RepeatedGroupPB, FlowyError>> loadGroups() { Future<FlowyResult<RepeatedGroupPB, FlowyError>> loadGroups() {
final payload = DatabaseViewIdPB(value: viewId); final payload = DatabaseViewIdPB(value: viewId);
return DatabaseEventGetGroups(payload).send(); return DatabaseEventGetGroups(payload).send();
} }

View File

@ -5,7 +5,7 @@ import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filte
import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_info.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'field/field_info.dart'; import 'field/field_info.dart';
@ -38,7 +38,7 @@ class LoadingState with _$LoadingState {
const factory LoadingState.idle() = _Idle; const factory LoadingState.idle() = _Idle;
const factory LoadingState.loading() = _Loading; const factory LoadingState.loading() = _Loading;
const factory LoadingState.finish( const factory LoadingState.finish(
Either<Unit, FlowyError> successOrFail, FlowyResult<void, FlowyError> successOrFail,
) = _Finish; ) = _Finish;
const LoadingState._(); const LoadingState._();

View File

@ -20,8 +20,8 @@ import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.da
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../setting/setting_service.dart'; import '../setting/setting_service.dart';
@ -382,7 +382,7 @@ class FieldController {
); );
} }
/// Listen for databse setting changes in the backend. /// Listen for database setting changes in the backend.
void _listenOnSettingChanges() { void _listenOnSettingChanges() {
_settingListener.start( _settingListener.start(
onSettingUpdated: (result) { onSettingUpdated: (result) {
@ -581,7 +581,7 @@ class FieldController {
} }
/// Load all of the fields. This is required when opening the database /// Load all of the fields. This is required when opening the database
Future<Either<Unit, FlowyError>> loadFields({ Future<FlowyResult<void, FlowyError>> loadFields({
required List<FieldIdPB> fieldIds, required List<FieldIdPB> fieldIds,
}) async { }) async {
final result = await _databaseViewBackendSvc.getFields(fieldIds: fieldIds); final result = await _databaseViewBackendSvc.getFields(fieldIds: fieldIds);
@ -589,7 +589,7 @@ class FieldController {
() => result.fold( () => result.fold(
(newFields) async { (newFields) async {
if (_isDisposed) { if (_isDisposed) {
return left(unit); return FlowyResult.success(null);
} }
_fieldNotifier.fieldInfos = _fieldNotifier.fieldInfos =
@ -602,54 +602,54 @@ class FieldController {
]); ]);
_updateFieldInfos(); _updateFieldInfos();
return left(unit); return FlowyResult.success(null);
}, },
(err) => right(err), (err) => FlowyResult.failure(err),
), ),
); );
} }
/// Load all the filters from the backend. Required by `loadFields` /// Load all the filters from the backend. Required by `loadFields`
Future<Either<Unit, FlowyError>> _loadFilters() async { Future<FlowyResult<void, FlowyError>> _loadFilters() async {
return _filterBackendSvc.getAllFilters().then((result) { return _filterBackendSvc.getAllFilters().then((result) {
return result.fold( return result.fold(
(filterPBs) { (filterPBs) {
_filterNotifier?.filters = _filterInfoListFromPBs(filterPBs); _filterNotifier?.filters = _filterInfoListFromPBs(filterPBs);
return left(unit); return FlowyResult.success(null);
}, },
(err) => right(err), (err) => FlowyResult.failure(err),
); );
}); });
} }
/// Load all the sorts from the backend. Required by `loadFields` /// Load all the sorts from the backend. Required by `loadFields`
Future<Either<Unit, FlowyError>> _loadSorts() async { Future<FlowyResult<void, FlowyError>> _loadSorts() async {
return _sortBackendSvc.getAllSorts().then((result) { return _sortBackendSvc.getAllSorts().then((result) {
return result.fold( return result.fold(
(sortPBs) { (sortPBs) {
_sortNotifier?.sorts = _sortInfoListFromPBs(sortPBs); _sortNotifier?.sorts = _sortInfoListFromPBs(sortPBs);
return left(unit); return FlowyResult.success(null);
}, },
(err) => right(err), (err) => FlowyResult.failure(err),
); );
}); });
} }
/// Load all the field settings from the backend. Required by `loadFields` /// Load all the field settings from the backend. Required by `loadFields`
Future<Either<Unit, FlowyError>> _loadAllFieldSettings() async { Future<FlowyResult<void, FlowyError>> _loadAllFieldSettings() async {
return _fieldSettingsBackendSvc.getAllFieldSettings().then((result) { return _fieldSettingsBackendSvc.getAllFieldSettings().then((result) {
return result.fold( return result.fold(
(fieldSettingsList) { (fieldSettingsList) {
_fieldSettings.clear(); _fieldSettings.clear();
_fieldSettings.addAll(fieldSettingsList); _fieldSettings.addAll(fieldSettingsList);
return left(unit); return FlowyResult.success(null);
}, },
(err) => right(err), (err) => FlowyResult.failure(err),
); );
}); });
} }
Future<Either<Unit, FlowyError>> _loadSettings() async { Future<FlowyResult<void, FlowyError>> _loadSettings() async {
return SettingBackendService(viewId: viewId).getSetting().then( return SettingBackendService(viewId: viewId).getSetting().then(
(result) => result.fold( (result) => result.fold(
(setting) { (setting) {
@ -658,9 +658,9 @@ class FieldController {
_groupConfigurationByFieldId[configuration.fieldId] = _groupConfigurationByFieldId[configuration.fieldId] =
configuration; configuration;
} }
return left(unit); return FlowyResult.success(null);
}, },
(err) => right(err), (err) => FlowyResult.failure(err),
), ),
); );
} }

View File

@ -4,7 +4,7 @@ import 'package:appflowy/plugins/database/application/field_settings/field_setti
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -111,7 +111,7 @@ class FieldEditorBloc extends Bloc<FieldEditorEvent, FieldEditorState> {
); );
} }
void _logIfError(Either<Unit, FlowyError> result) { void _logIfError(FlowyResult<void, FlowyError> result) {
result.fold( result.fold(
(l) => null, (l) => null,
(err) => Log.error(err), (err) => Log.error(err),

View File

@ -5,7 +5,7 @@ import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart'; import 'package:flowy_infra/notifier.dart';
typedef UpdateFieldNotifiedValue = FieldPB; typedef UpdateFieldNotifiedValue = FieldPB;
@ -30,7 +30,7 @@ class SingleFieldListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateField: case DatabaseNotification.DidUpdateField:
@ -51,7 +51,7 @@ class SingleFieldListener {
} }
typedef UpdateFieldsNotifiedValue typedef UpdateFieldsNotifiedValue
= Either<DatabaseFieldChangesetPB, FlowyError>; = FlowyResult<DatabaseFieldChangesetPB, FlowyError>;
class FieldsListener { class FieldsListener {
FieldsListener({required this.viewId}); FieldsListener({required this.viewId});
@ -72,13 +72,16 @@ class FieldsListener {
); );
} }
void _handler(DatabaseNotification ty, Either<Uint8List, FlowyError> result) { void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateFields: case DatabaseNotification.DidUpdateFields:
result.fold( result.fold(
(payload) => updateFieldsNotifier?.value = (payload) => updateFieldsNotifier?.value =
left(DatabaseFieldChangesetPB.fromBuffer(payload)), FlowyResult.success(DatabaseFieldChangesetPB.fromBuffer(payload)),
(error) => updateFieldsNotifier?.value = right(error), (error) => updateFieldsNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -3,7 +3,7 @@ import 'dart:typed_data';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
/// FieldService provides many field-related interfaces event functions. Check out /// FieldService provides many field-related interfaces event functions. Check out
/// `rust-lib/flowy-database/event_map.rs` for a list of events and their /// `rust-lib/flowy-database/event_map.rs` for a list of events and their
@ -16,7 +16,7 @@ class FieldBackendService {
/// Create a field in a database view. The position will only be applicable /// Create a field in a database view. The position will only be applicable
/// in this view; for other views it will be appended to the end /// in this view; for other views it will be appended to the end
static Future<Either<FieldPB, FlowyError>> createField({ static Future<FlowyResult<FieldPB, FlowyError>> createField({
required String viewId, required String viewId,
FieldType fieldType = FieldType.RichText, FieldType fieldType = FieldType.RichText,
String? fieldName, String? fieldName,
@ -35,7 +35,7 @@ class FieldBackendService {
} }
/// Reorder a field within a database view /// Reorder a field within a database view
static Future<Either<Unit, FlowyError>> moveField({ static Future<FlowyResult<void, FlowyError>> moveField({
required String viewId, required String viewId,
required String fromFieldId, required String fromFieldId,
required String toFieldId, required String toFieldId,
@ -50,7 +50,7 @@ class FieldBackendService {
} }
/// Delete a field /// Delete a field
static Future<Either<Unit, FlowyError>> deleteField({ static Future<FlowyResult<void, FlowyError>> deleteField({
required String viewId, required String viewId,
required String fieldId, required String fieldId,
}) { }) {
@ -63,7 +63,7 @@ class FieldBackendService {
} }
/// Duplicate a field /// Duplicate a field
static Future<Either<Unit, FlowyError>> duplicateField({ static Future<FlowyResult<void, FlowyError>> duplicateField({
required String viewId, required String viewId,
required String fieldId, required String fieldId,
}) { }) {
@ -76,7 +76,7 @@ class FieldBackendService {
} }
/// Update a field's properties /// Update a field's properties
Future<Either<Unit, FlowyError>> updateField({ Future<FlowyResult<void, FlowyError>> updateField({
String? name, String? name,
bool? frozen, bool? frozen,
}) { }) {
@ -96,7 +96,7 @@ class FieldBackendService {
} }
/// Change a field's type /// Change a field's type
static Future<Either<Unit, FlowyError>> updateFieldType({ static Future<FlowyResult<void, FlowyError>> updateFieldType({
required String viewId, required String viewId,
required String fieldId, required String fieldId,
required FieldType fieldType, required FieldType fieldType,
@ -110,7 +110,7 @@ class FieldBackendService {
} }
/// Update a field's type option data /// Update a field's type option data
static Future<Either<Unit, FlowyError>> updateFieldTypeOption({ static Future<FlowyResult<void, FlowyError>> updateFieldTypeOption({
required String viewId, required String viewId,
required String fieldId, required String fieldId,
required List<int> typeOptionData, required List<int> typeOptionData,
@ -124,14 +124,14 @@ class FieldBackendService {
} }
/// Returns the primary field of the view. /// Returns the primary field of the view.
static Future<Either<FieldPB, FlowyError>> getPrimaryField({ static Future<FlowyResult<FieldPB, FlowyError>> getPrimaryField({
required String viewId, required String viewId,
}) { }) {
final payload = DatabaseViewIdPB.create()..value = viewId; final payload = DatabaseViewIdPB.create()..value = viewId;
return DatabaseEventGetPrimaryField(payload).send(); return DatabaseEventGetPrimaryField(payload).send();
} }
Future<Either<FieldPB, FlowyError>> createBefore({ Future<FlowyResult<FieldPB, FlowyError>> createBefore({
FieldType fieldType = FieldType.RichText, FieldType fieldType = FieldType.RichText,
String? fieldName, String? fieldName,
Uint8List? typeOptionData, Uint8List? typeOptionData,
@ -148,7 +148,7 @@ class FieldBackendService {
); );
} }
Future<Either<FieldPB, FlowyError>> createAfter({ Future<FlowyResult<FieldPB, FlowyError>> createAfter({
FieldType fieldType = FieldType.RichText, FieldType fieldType = FieldType.RichText,
String? fieldName, String? fieldName,
Uint8List? typeOptionData, Uint8List? typeOptionData,
@ -165,7 +165,7 @@ class FieldBackendService {
); );
} }
Future<Either<Unit, FlowyError>> updateType({ Future<FlowyResult<void, FlowyError>> updateType({
required FieldType fieldType, required FieldType fieldType,
}) => }) =>
updateFieldType( updateFieldType(
@ -174,9 +174,9 @@ class FieldBackendService {
fieldType: fieldType, fieldType: fieldType,
); );
Future<Either<Unit, FlowyError>> delete() => Future<FlowyResult<void, FlowyError>> delete() =>
deleteField(viewId: viewId, fieldId: fieldId); deleteField(viewId: viewId, fieldId: fieldId);
Future<Either<Unit, FlowyError>> duplicate() => Future<FlowyResult<void, FlowyError>> duplicate() =>
duplicateField(viewId: viewId, fieldId: fieldId); duplicateField(viewId: viewId, fieldId: fieldId);
} }

View File

@ -1,5 +1,4 @@
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -28,10 +27,10 @@ class SelectOptionTypeOptionBloc
emit(state.copyWith(options: options)); emit(state.copyWith(options: options));
}, },
addingOption: () { addingOption: () {
emit(state.copyWith(isEditingOption: true, newOptionName: none())); emit(state.copyWith(isEditingOption: true, newOptionName: null));
}, },
endAddingOption: () { endAddingOption: () {
emit(state.copyWith(isEditingOption: false, newOptionName: none())); emit(state.copyWith(isEditingOption: false, newOptionName: null));
}, },
updateOption: (option) { updateOption: (option) {
final List<SelectOptionPB> options = final List<SelectOptionPB> options =
@ -69,13 +68,13 @@ class SelectOptionTypeOptionState with _$SelectOptionTypeOptionState {
const factory SelectOptionTypeOptionState({ const factory SelectOptionTypeOptionState({
required List<SelectOptionPB> options, required List<SelectOptionPB> options,
required bool isEditingOption, required bool isEditingOption,
required Option<String> newOptionName, required String? newOptionName,
}) = _SelectOptionTypeOptionState; }) = _SelectOptionTypeOptionState;
factory SelectOptionTypeOptionState.initial(List<SelectOptionPB> options) => factory SelectOptionTypeOptionState.initial(List<SelectOptionPB> options) =>
SelectOptionTypeOptionState( SelectOptionTypeOptionState(
options: options, options: options,
isEditingOption: false, isEditingOption: false,
newOptionName: none(), newOptionName: null,
); );
} }

View File

@ -1,7 +1,7 @@
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class TypeOptionBackendService { class TypeOptionBackendService {
TypeOptionBackendService({ TypeOptionBackendService({
@ -12,7 +12,7 @@ class TypeOptionBackendService {
final String viewId; final String viewId;
final String fieldId; final String fieldId;
Future<Either<SelectOptionPB, FlowyError>> newOption({ Future<FlowyResult<SelectOptionPB, FlowyError>> newOption({
required String name, required String name,
}) { }) {
final payload = CreateSelectOptionPayloadPB.create() final payload = CreateSelectOptionPayloadPB.create()

View File

@ -3,10 +3,10 @@ import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart'; import 'package:flowy_infra/notifier.dart';
typedef FieldSettingsValue = Either<FieldSettingsPB, FlowyError>; typedef FieldSettingsValue = FlowyResult<FieldSettingsPB, FlowyError>;
class FieldSettingsListener { class FieldSettingsListener {
FieldSettingsListener({required this.viewId}); FieldSettingsListener({required this.viewId});
@ -29,14 +29,14 @@ class FieldSettingsListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateFieldSettings: case DatabaseNotification.DidUpdateFieldSettings:
result.fold( result.fold(
(payload) => _fieldSettingsNotifier?.value = (payload) => _fieldSettingsNotifier?.value =
left(FieldSettingsPB.fromBuffer(payload)), FlowyResult.success(FieldSettingsPB.fromBuffer(payload)),
(error) => _fieldSettingsNotifier?.value = right(error), (error) => _fieldSettingsNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,14 +1,14 @@
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class FieldSettingsBackendService { class FieldSettingsBackendService {
FieldSettingsBackendService({required this.viewId}); FieldSettingsBackendService({required this.viewId});
final String viewId; final String viewId;
Future<Either<FieldSettingsPB, FlowyError>> getFieldSettings( Future<FlowyResult<FieldSettingsPB, FlowyError>> getFieldSettings(
String fieldId, String fieldId,
) { ) {
final id = FieldIdPB(fieldId: fieldId); final id = FieldIdPB(fieldId: fieldId);
@ -25,14 +25,14 @@ class FieldSettingsBackendService {
fieldSetting.visibility = FieldVisibility.AlwaysShown; fieldSetting.visibility = FieldVisibility.AlwaysShown;
} }
return left(fieldSetting); return FlowyResult.success(fieldSetting);
}, },
(r) => right(r), (r) => FlowyResult.failure(r),
); );
}); });
} }
Future<Either<List<FieldSettingsPB>, FlowyError>> getAllFieldSettings() { Future<FlowyResult<List<FieldSettingsPB>, FlowyError>> getAllFieldSettings() {
final payload = DatabaseViewIdPB()..value = viewId; final payload = DatabaseViewIdPB()..value = viewId;
return DatabaseEventGetAllFieldSettings(payload).send().then((result) { return DatabaseEventGetAllFieldSettings(payload).send().then((result) {
@ -47,14 +47,14 @@ class FieldSettingsBackendService {
fieldSettings.add(fieldSetting); fieldSettings.add(fieldSetting);
} }
return left(fieldSettings); return FlowyResult.success(fieldSettings);
}, },
(r) => right(r), (r) => FlowyResult.failure(r),
); );
}); });
} }
Future<Either<Unit, FlowyError>> updateFieldSettings({ Future<FlowyResult<void, FlowyError>> updateFieldSettings({
required String fieldId, required String fieldId,
FieldVisibility? fieldVisibility, FieldVisibility? fieldVisibility,
double? width, double? width,

View File

@ -1,15 +1,15 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:flowy_infra/notifier.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/filter_changeset.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/filter_changeset.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef UpdateFilterNotifiedValue typedef UpdateFilterNotifiedValue
= Either<FilterChangesetNotificationPB, FlowyError>; = FlowyResult<FilterChangesetNotificationPB, FlowyError>;
class FiltersListener { class FiltersListener {
FiltersListener({required this.viewId}); FiltersListener({required this.viewId});
@ -32,14 +32,15 @@ class FiltersListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateFilter: case DatabaseNotification.DidUpdateFilter:
result.fold( result.fold(
(payload) => _filterNotifier?.value = (payload) => _filterNotifier?.value = FlowyResult.success(
left(FilterChangesetNotificationPB.fromBuffer(payload)), FilterChangesetNotificationPB.fromBuffer(payload),
(error) => _filterNotifier?.value = right(error), ),
(error) => _filterNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:
@ -103,7 +104,7 @@ class FilterListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateFilter: case DatabaseNotification.DidUpdateFilter:

View File

@ -1,10 +1,8 @@
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checkbox_filter.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/checkbox_filter.pbserver.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checklist_filter.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/checklist_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/date_filter.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/date_filter.pbserver.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/number_filter.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/number_filter.pb.dart';
@ -12,6 +10,8 @@ import 'package:appflowy_backend/protobuf/flowy-database2/select_option_filter.p
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/text_filter.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/text_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:fixnum/fixnum.dart' as $fixnum;
class FilterBackendService { class FilterBackendService {
@ -19,18 +19,18 @@ class FilterBackendService {
final String viewId; final String viewId;
Future<Either<List<FilterPB>, FlowyError>> getAllFilters() { Future<FlowyResult<List<FilterPB>, FlowyError>> getAllFilters() {
final payload = DatabaseViewIdPB()..value = viewId; final payload = DatabaseViewIdPB()..value = viewId;
return DatabaseEventGetAllFilters(payload).send().then((result) { return DatabaseEventGetAllFilters(payload).send().then((result) {
return result.fold( return result.fold(
(repeated) => left(repeated.items), (repeated) => FlowyResult.success(repeated.items),
(r) => right(r), (r) => FlowyResult.failure(r),
); );
}); });
} }
Future<Either<Unit, FlowyError>> insertTextFilter({ Future<FlowyResult<void, FlowyError>> insertTextFilter({
required String fieldId, required String fieldId,
String? filterId, String? filterId,
required TextFilterConditionPB condition, required TextFilterConditionPB condition,
@ -48,7 +48,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertCheckboxFilter({ Future<FlowyResult<void, FlowyError>> insertCheckboxFilter({
required String fieldId, required String fieldId,
String? filterId, String? filterId,
required CheckboxFilterConditionPB condition, required CheckboxFilterConditionPB condition,
@ -63,7 +63,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertNumberFilter({ Future<FlowyResult<void, FlowyError>> insertNumberFilter({
required String fieldId, required String fieldId,
String? filterId, String? filterId,
required NumberFilterConditionPB condition, required NumberFilterConditionPB condition,
@ -81,7 +81,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertDateFilter({ Future<FlowyResult<void, FlowyError>> insertDateFilter({
required String fieldId, required String fieldId,
String? filterId, String? filterId,
required DateFilterConditionPB condition, required DateFilterConditionPB condition,
@ -120,7 +120,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertURLFilter({ Future<FlowyResult<void, FlowyError>> insertURLFilter({
required String fieldId, required String fieldId,
String? filterId, String? filterId,
required TextFilterConditionPB condition, required TextFilterConditionPB condition,
@ -138,7 +138,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertSelectOptionFilter({ Future<FlowyResult<void, FlowyError>> insertSelectOptionFilter({
required String fieldId, required String fieldId,
required FieldType fieldType, required FieldType fieldType,
required SelectOptionConditionPB condition, required SelectOptionConditionPB condition,
@ -157,7 +157,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertChecklistFilter({ Future<FlowyResult<void, FlowyError>> insertChecklistFilter({
required String fieldId, required String fieldId,
required ChecklistFilterConditionPB condition, required ChecklistFilterConditionPB condition,
String? filterId, String? filterId,
@ -173,7 +173,7 @@ class FilterBackendService {
); );
} }
Future<Either<Unit, FlowyError>> insertFilter({ Future<FlowyResult<void, FlowyError>> insertFilter({
required String fieldId, required String fieldId,
String? filterId, String? filterId,
required FieldType fieldType, required FieldType fieldType,
@ -194,16 +194,16 @@ class FilterBackendService {
..updateFilter = insertFilterPayload; ..updateFilter = insertFilterPayload;
return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) { return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) {
return result.fold( return result.fold(
(l) => left(l), (l) => FlowyResult.success(l),
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}); });
} }
Future<Either<Unit, FlowyError>> deleteFilter({ Future<FlowyResult<void, FlowyError>> deleteFilter({
required String fieldId, required String fieldId,
required String filterId, required String filterId,
required FieldType fieldType, required FieldType fieldType,
@ -220,10 +220,10 @@ class FilterBackendService {
return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) { return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) {
return result.fold( return result.fold(
(l) => left(l), (l) => FlowyResult.success(l),
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}); });

View File

@ -1,17 +1,17 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:flowy_infra/notifier.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/group.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/group.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/group_changeset.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/group_changeset.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef GroupConfigurationUpdateValue typedef GroupConfigurationUpdateValue
= Either<List<GroupSettingPB>, FlowyError>; = FlowyResult<List<GroupSettingPB>, FlowyError>;
typedef GroupUpdateValue = Either<GroupChangesPB, FlowyError>; typedef GroupUpdateValue = FlowyResult<GroupChangesPB, FlowyError>;
typedef GroupByNewFieldValue = Either<List<GroupPB>, FlowyError>; typedef GroupByNewFieldValue = FlowyResult<List<GroupPB>, FlowyError>;
class DatabaseGroupListener { class DatabaseGroupListener {
DatabaseGroupListener(this.viewId); DatabaseGroupListener(this.viewId);
@ -37,21 +37,22 @@ class DatabaseGroupListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateNumOfGroups: case DatabaseNotification.DidUpdateNumOfGroups:
result.fold( result.fold(
(payload) => _numOfGroupsNotifier?.value = (payload) => _numOfGroupsNotifier?.value =
left(GroupChangesPB.fromBuffer(payload)), FlowyResult.success(GroupChangesPB.fromBuffer(payload)),
(error) => _numOfGroupsNotifier?.value = right(error), (error) => _numOfGroupsNotifier?.value = FlowyResult.failure(error),
); );
break; break;
case DatabaseNotification.DidGroupByField: case DatabaseNotification.DidGroupByField:
result.fold( result.fold(
(payload) => _groupByFieldNotifier?.value = (payload) => _groupByFieldNotifier?.value = FlowyResult.success(
left(GroupChangesPB.fromBuffer(payload).initialGroups), GroupChangesPB.fromBuffer(payload).initialGroups,
(error) => _groupByFieldNotifier?.value = right(error), ),
(error) => _groupByFieldNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,14 +1,14 @@
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/group.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/group.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class GroupBackendService { class GroupBackendService {
GroupBackendService(this.viewId); GroupBackendService(this.viewId);
final String viewId; final String viewId;
Future<Either<Unit, FlowyError>> groupByField({ Future<FlowyResult<void, FlowyError>> groupByField({
required String fieldId, required String fieldId,
}) { }) {
final payload = GroupByFieldPayloadPB.create() final payload = GroupByFieldPayloadPB.create()
@ -18,7 +18,7 @@ class GroupBackendService {
return DatabaseEventSetGroupByField(payload).send(); return DatabaseEventSetGroupByField(payload).send();
} }
Future<Either<Unit, FlowyError>> updateGroup({ Future<FlowyResult<void, FlowyError>> updateGroup({
required String groupId, required String groupId,
required String fieldId, required String fieldId,
String? name, String? name,
@ -38,7 +38,7 @@ class GroupBackendService {
return DatabaseEventUpdateGroup(payload).send(); return DatabaseEventUpdateGroup(payload).send();
} }
Future<Either<Unit, FlowyError>> createGroup({ Future<FlowyResult<void, FlowyError>> createGroup({
required String name, required String name,
String groupConfigId = "", String groupConfigId = "",
}) { }) {
@ -49,7 +49,7 @@ class GroupBackendService {
return DatabaseEventCreateGroup(payload).send(); return DatabaseEventCreateGroup(payload).send();
} }
Future<Either<Unit, FlowyError>> deleteGroup({ Future<FlowyResult<void, FlowyError>> deleteGroup({
required String groupId, required String groupId,
}) { }) {
final payload = DeleteGroupPayloadPB.create() final payload = DeleteGroupPayloadPB.create()

View File

@ -1,12 +1,12 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:flowy_infra/notifier.dart';
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef LayoutSettingsValue<T> = Either<T, FlowyError>; typedef LayoutSettingsValue<T> = FlowyResult<T, FlowyError>;
class DatabaseLayoutSettingListener { class DatabaseLayoutSettingListener {
DatabaseLayoutSettingListener(this.viewId); DatabaseLayoutSettingListener(this.viewId);
@ -30,14 +30,14 @@ class DatabaseLayoutSettingListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateLayoutSettings: case DatabaseNotification.DidUpdateLayoutSettings:
result.fold( result.fold(
(payload) => _settingNotifier?.value = (payload) => _settingNotifier?.value =
left(DatabaseLayoutSettingPB.fromBuffer(payload)), FlowyResult.success(DatabaseLayoutSettingPB.fromBuffer(payload)),
(error) => _settingNotifier?.value = right(error), (error) => _settingNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -2,9 +2,9 @@ import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
typedef DidFetchRowCallback = void Function(DidFetchRowPB); typedef DidFetchRowCallback = void Function(DidFetchRowPB);
typedef RowMetaCallback = void Function(RowMetaPB); typedef RowMetaCallback = void Function(RowMetaPB);
@ -34,7 +34,7 @@ class RowListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateRowMeta: case DatabaseNotification.DidUpdateRowMeta:

View File

@ -2,9 +2,9 @@ import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
typedef RowMetaCallback = void Function(RowMetaPB); typedef RowMetaCallback = void Function(RowMetaPB);
@ -26,7 +26,7 @@ class RowMetaListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateRowMeta: case DatabaseNotification.DidUpdateRowMeta:

View File

@ -1,7 +1,7 @@
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import '../field/field_info.dart'; import '../field/field_info.dart';
@ -12,7 +12,7 @@ class RowBackendService {
final String viewId; final String viewId;
static Future<Either<RowMetaPB, FlowyError>> createRow({ static Future<FlowyResult<RowMetaPB, FlowyError>> createRow({
required String viewId, required String viewId,
String? groupId, String? groupId,
void Function(RowDataBuilder builder)? withCells, void Function(RowDataBuilder builder)? withCells,
@ -43,7 +43,7 @@ class RowBackendService {
return DatabaseEventCreateRow(payload).send(); return DatabaseEventCreateRow(payload).send();
} }
Future<Either<RowMetaPB, FlowyError>> createRowBefore(RowId rowId) { Future<FlowyResult<RowMetaPB, FlowyError>> createRowBefore(RowId rowId) {
return createRow( return createRow(
viewId: viewId, viewId: viewId,
position: OrderObjectPositionTypePB.Before, position: OrderObjectPositionTypePB.Before,
@ -51,7 +51,7 @@ class RowBackendService {
); );
} }
Future<Either<RowMetaPB, FlowyError>> createRowAfter(RowId rowId) { Future<FlowyResult<RowMetaPB, FlowyError>> createRowAfter(RowId rowId) {
return createRow( return createRow(
viewId: viewId, viewId: viewId,
position: OrderObjectPositionTypePB.After, position: OrderObjectPositionTypePB.After,
@ -59,7 +59,7 @@ class RowBackendService {
); );
} }
static Future<Either<RowMetaPB, FlowyError>> getRow({ static Future<FlowyResult<RowMetaPB, FlowyError>> getRow({
required String viewId, required String viewId,
required String rowId, required String rowId,
}) { }) {
@ -70,7 +70,7 @@ class RowBackendService {
return DatabaseEventGetRowMeta(payload).send(); return DatabaseEventGetRowMeta(payload).send();
} }
Future<Either<RowMetaPB, FlowyError>> getRowMeta(RowId rowId) { Future<FlowyResult<RowMetaPB, FlowyError>> getRowMeta(RowId rowId) {
final payload = RowIdPB.create() final payload = RowIdPB.create()
..viewId = viewId ..viewId = viewId
..rowId = rowId; ..rowId = rowId;
@ -78,7 +78,7 @@ class RowBackendService {
return DatabaseEventGetRowMeta(payload).send(); return DatabaseEventGetRowMeta(payload).send();
} }
Future<Either<Unit, FlowyError>> updateMeta({ Future<FlowyResult<void, FlowyError>> updateMeta({
required String rowId, required String rowId,
String? iconURL, String? iconURL,
String? coverURL, String? coverURL,
@ -102,7 +102,7 @@ class RowBackendService {
return DatabaseEventUpdateRowMeta(payload).send(); return DatabaseEventUpdateRowMeta(payload).send();
} }
static Future<Either<Unit, FlowyError>> deleteRow( static Future<FlowyResult<void, FlowyError>> deleteRow(
String viewId, String viewId,
RowId rowId, RowId rowId,
) { ) {
@ -113,7 +113,7 @@ class RowBackendService {
return DatabaseEventDeleteRow(payload).send(); return DatabaseEventDeleteRow(payload).send();
} }
static Future<Either<Unit, FlowyError>> duplicateRow( static Future<FlowyResult<void, FlowyError>> duplicateRow(
String viewId, String viewId,
RowId rowId, RowId rowId,
) { ) {

View File

@ -1,13 +1,14 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:dartz/dartz.dart';
import 'package:flowy_infra/notifier.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef UpdateSettingNotifiedValue = Either<DatabaseViewSettingPB, FlowyError>; typedef UpdateSettingNotifiedValue
= FlowyResult<DatabaseViewSettingPB, FlowyError>;
class DatabaseSettingListener { class DatabaseSettingListener {
DatabaseSettingListener({required this.viewId}); DatabaseSettingListener({required this.viewId});
@ -26,14 +27,17 @@ class DatabaseSettingListener {
DatabaseNotificationListener(objectId: viewId, handler: _handler); DatabaseNotificationListener(objectId: viewId, handler: _handler);
} }
void _handler(DatabaseNotification ty, Either<Uint8List, FlowyError> result) { void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateSettings: case DatabaseNotification.DidUpdateSettings:
result.fold( result.fold(
(payload) => _updateSettingNotifier?.value = left( (payload) => _updateSettingNotifier?.value = FlowyResult.success(
DatabaseViewSettingPB.fromBuffer(payload), DatabaseViewSettingPB.fromBuffer(payload),
), ),
(error) => _updateSettingNotifier?.value = right(error), (error) => _updateSettingNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,15 +1,15 @@
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class SettingBackendService { class SettingBackendService {
const SettingBackendService({required this.viewId}); const SettingBackendService({required this.viewId});
final String viewId; final String viewId;
Future<Either<DatabaseViewSettingPB, FlowyError>> getSetting() { Future<FlowyResult<DatabaseViewSettingPB, FlowyError>> getSetting() {
final payload = DatabaseViewIdPB.create()..value = viewId; final payload = DatabaseViewIdPB.create()..value = viewId;
return DatabaseEventGetDatabaseSetting(payload).send(); return DatabaseEventGetDatabaseSetting(payload).send();
} }

View File

@ -1,12 +1,14 @@
import 'dart:io'; import 'dart:io';
import 'package:appflowy/workspace/application/settings/share/export_service.dart'; import 'package:appflowy/workspace/application/settings/share/export_service.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:dartz/dartz.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
part 'share_bloc.freezed.dart'; part 'share_bloc.freezed.dart';
class DatabaseShareBloc extends Bloc<DatabaseShareEvent, DatabaseShareState> { class DatabaseShareBloc extends Bloc<DatabaseShareEvent, DatabaseShareState> {
@ -35,9 +37,9 @@ class DatabaseShareBloc extends Bloc<DatabaseShareEvent, DatabaseShareState> {
result.fold( result.fold(
(l) { (l) {
_saveCSVToPath(l.data, event.path); _saveCSVToPath(l.data, event.path);
return left(unit); return FlowyResult.success(null);
}, },
(r) => right(r), (r) => FlowyResult.failure(r),
), ),
), ),
); );
@ -61,6 +63,6 @@ class DatabaseShareState with _$DatabaseShareState {
const factory DatabaseShareState.initial() = _Initial; const factory DatabaseShareState.initial() = _Initial;
const factory DatabaseShareState.loading() = _Loading; const factory DatabaseShareState.loading() = _Loading;
const factory DatabaseShareState.finish( const factory DatabaseShareState.finish(
Either<Unit, FlowyError> successOrFail, FlowyResult<void, FlowyError> successOrFail,
) = _Finish; ) = _Finish;
} }

View File

@ -1,13 +1,14 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:flowy_infra/notifier.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef SortNotifiedValue = Either<SortChangesetNotificationPB, FlowyError>; typedef SortNotifiedValue
= FlowyResult<SortChangesetNotificationPB, FlowyError>;
class SortsListener { class SortsListener {
SortsListener({required this.viewId}); SortsListener({required this.viewId});
@ -29,14 +30,15 @@ class SortsListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateSort: case DatabaseNotification.DidUpdateSort:
result.fold( result.fold(
(payload) => _notifier?.value = (payload) => _notifier?.value = FlowyResult.success(
left(SortChangesetNotificationPB.fromBuffer(payload)), SortChangesetNotificationPB.fromBuffer(payload),
(error) => _notifier?.value = right(error), ),
(error) => _notifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,28 +1,28 @@
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class SortBackendService { class SortBackendService {
SortBackendService({required this.viewId}); SortBackendService({required this.viewId});
final String viewId; final String viewId;
Future<Either<List<SortPB>, FlowyError>> getAllSorts() { Future<FlowyResult<List<SortPB>, FlowyError>> getAllSorts() {
final payload = DatabaseViewIdPB()..value = viewId; final payload = DatabaseViewIdPB()..value = viewId;
return DatabaseEventGetAllSorts(payload).send().then((result) { return DatabaseEventGetAllSorts(payload).send().then((result) {
return result.fold( return result.fold(
(repeated) => left(repeated.items), (repeated) => FlowyResult.success(repeated.items),
(r) => right(r), (r) => FlowyResult.failure(r),
); );
}); });
} }
Future<Either<Unit, FlowyError>> updateSort({ Future<FlowyResult<void, FlowyError>> updateSort({
required String sortId, required String sortId,
required String fieldId, required String fieldId,
required SortConditionPB condition, required SortConditionPB condition,
@ -38,16 +38,16 @@ class SortBackendService {
..updateSort = insertSortPayload; ..updateSort = insertSortPayload;
return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) { return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) {
return result.fold( return result.fold(
(l) => left(l), (l) => FlowyResult.success(l),
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}); });
} }
Future<Either<Unit, FlowyError>> insertSort({ Future<FlowyResult<void, FlowyError>> insertSort({
required String fieldId, required String fieldId,
required SortConditionPB condition, required SortConditionPB condition,
}) { }) {
@ -61,16 +61,16 @@ class SortBackendService {
..updateSort = insertSortPayload; ..updateSort = insertSortPayload;
return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) { return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) {
return result.fold( return result.fold(
(l) => left(l), (l) => FlowyResult.success(l),
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}); });
} }
Future<Either<Unit, FlowyError>> reorderSort({ Future<FlowyResult<void, FlowyError>> reorderSort({
required String fromSortId, required String fromSortId,
required String toSortId, required String toSortId,
}) { }) {
@ -84,7 +84,7 @@ class SortBackendService {
return DatabaseEventUpdateDatabaseSetting(payload).send(); return DatabaseEventUpdateDatabaseSetting(payload).send();
} }
Future<Either<Unit, FlowyError>> deleteSort({ Future<FlowyResult<void, FlowyError>> deleteSort({
required String fieldId, required String fieldId,
required String sortId, required String sortId,
}) { }) {
@ -98,23 +98,23 @@ class SortBackendService {
return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) { return DatabaseEventUpdateDatabaseSetting(payload).send().then((result) {
return result.fold( return result.fold(
(l) => left(l), (l) => FlowyResult.success(l),
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}); });
} }
Future<Either<Unit, FlowyError>> deleteAllSorts() { Future<FlowyResult<void, FlowyError>> deleteAllSorts() {
final payload = DatabaseViewIdPB(value: viewId); final payload = DatabaseViewIdPB(value: viewId);
return DatabaseEventDeleteAllSorts(payload).send().then((result) { return DatabaseEventDeleteAllSorts(payload).send().then((result) {
return result.fold( return result.fold(
(l) => left(l), (l) => FlowyResult.success(l),
(err) { (err) {
Log.error(err); Log.error(err);
return right(err); return FlowyResult.failure(err);
}, },
); );
}); });

View File

@ -1,19 +1,20 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
import 'package:dartz/dartz.dart';
import 'package:flowy_infra/notifier.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/view_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/view_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef RowsVisibilityNotifierValue typedef RowsVisibilityNotifierValue
= Either<RowsVisibilityChangePB, FlowyError>; = FlowyResult<RowsVisibilityChangePB, FlowyError>;
typedef NumberOfRowsNotifierValue = Either<RowsChangePB, FlowyError>; typedef NumberOfRowsNotifierValue = FlowyResult<RowsChangePB, FlowyError>;
typedef ReorderAllRowsNotifierValue = Either<List<String>, FlowyError>; typedef ReorderAllRowsNotifierValue = FlowyResult<List<String>, FlowyError>;
typedef SingleRowNotifierValue = Either<ReorderSingleRowPB, FlowyError>; typedef SingleRowNotifierValue = FlowyResult<ReorderSingleRowPB, FlowyError>;
class DatabaseViewListener { class DatabaseViewListener {
DatabaseViewListener({required this.viewId}); DatabaseViewListener({required this.viewId});
@ -51,34 +52,38 @@ class DatabaseViewListener {
_reorderSingleRow?.addPublishListener(onReorderSingleRow); _reorderSingleRow?.addPublishListener(onReorderSingleRow);
} }
void _handler(DatabaseNotification ty, Either<Uint8List, FlowyError> result) { void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateViewRowsVisibility: case DatabaseNotification.DidUpdateViewRowsVisibility:
result.fold( result.fold(
(payload) => _rowsVisibility?.value = (payload) => _rowsVisibility?.value =
left(RowsVisibilityChangePB.fromBuffer(payload)), FlowyResult.success(RowsVisibilityChangePB.fromBuffer(payload)),
(error) => _rowsVisibility?.value = right(error), (error) => _rowsVisibility?.value = FlowyResult.failure(error),
); );
break; break;
case DatabaseNotification.DidUpdateViewRows: case DatabaseNotification.DidUpdateViewRows:
result.fold( result.fold(
(payload) => (payload) => _rowsNotifier?.value =
_rowsNotifier?.value = left(RowsChangePB.fromBuffer(payload)), FlowyResult.success(RowsChangePB.fromBuffer(payload)),
(error) => _rowsNotifier?.value = right(error), (error) => _rowsNotifier?.value = FlowyResult.failure(error),
); );
break; break;
case DatabaseNotification.DidReorderRows: case DatabaseNotification.DidReorderRows:
result.fold( result.fold(
(payload) => _reorderAllRows?.value = (payload) => _reorderAllRows?.value = FlowyResult.success(
left(ReorderAllRowsPB.fromBuffer(payload).rowOrders), ReorderAllRowsPB.fromBuffer(payload).rowOrders,
(error) => _reorderAllRows?.value = right(error), ),
(error) => _reorderAllRows?.value = FlowyResult.failure(error),
); );
break; break;
case DatabaseNotification.DidReorderSingleRow: case DatabaseNotification.DidReorderSingleRow:
result.fold( result.fold(
(payload) => _reorderSingleRow?.value = (payload) => _reorderSingleRow?.value =
left(ReorderSingleRowPB.fromBuffer(payload)), FlowyResult.success(ReorderSingleRowPB.fromBuffer(payload)),
(error) => _reorderSingleRow?.value = right(error), (error) => _reorderSingleRow?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,8 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'dart:collection'; import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:appflowy/plugins/database/application/defines.dart'; import 'package:appflowy/plugins/database/application/defines.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart'; import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/group/group_service.dart'; import 'package:appflowy/plugins/database/application/group/group_service.dart';
@ -12,7 +10,8 @@ import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_board/appflowy_board.dart'; import 'package:appflowy_board/appflowy_board.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:protobuf/protobuf.dart' hide FieldInfo; import 'package:protobuf/protobuf.dart' hide FieldInfo;
@ -20,7 +19,6 @@ import 'package:protobuf/protobuf.dart' hide FieldInfo;
import '../../application/database_controller.dart'; import '../../application/database_controller.dart';
import '../../application/field/field_controller.dart'; import '../../application/field/field_controller.dart';
import '../../application/row/row_cache.dart'; import '../../application/row/row_cache.dart';
import 'group_controller.dart'; import 'group_controller.dart';
part 'board_bloc.freezed.dart'; part 'board_bloc.freezed.dart';
@ -141,10 +139,10 @@ class BoardBloc extends Bloc<BoardEvent, BoardState> {
_groupItemStartEditing(group, row, true); _groupItemStartEditing(group, row, true);
}, },
didReceiveGridUpdate: (DatabasePB grid) { didReceiveGridUpdate: (DatabasePB grid) {
emit(state.copyWith(grid: Some(grid))); emit(state.copyWith(grid: grid));
}, },
didReceiveError: (FlowyError error) { didReceiveError: (FlowyError error) {
emit(state.copyWith(noneOrError: some(error))); emit(state.copyWith(noneOrError: error));
}, },
didReceiveGroups: (List<GroupPB> groups) { didReceiveGroups: (List<GroupPB> groups) {
final hiddenGroups = _filterHiddenGroups(hideUngrouped, groups); final hiddenGroups = _filterHiddenGroups(hideUngrouped, groups);
@ -450,11 +448,15 @@ class BoardBloc extends Bloc<BoardEvent, BoardState> {
(grid) { (grid) {
databaseController.setIsLoading(false); databaseController.setIsLoading(false);
emit( emit(
state.copyWith(loadingState: LoadingState.finish(left(unit))), state.copyWith(
loadingState: LoadingState.finish(FlowyResult.success(null)),
),
); );
}, },
(err) => emit( (err) => emit(
state.copyWith(loadingState: LoadingState.finish(right(err))), state.copyWith(
loadingState: LoadingState.finish(FlowyResult.failure(err)),
),
), ),
); );
} }
@ -543,12 +545,12 @@ class BoardEvent with _$BoardEvent {
class BoardState with _$BoardState { class BoardState with _$BoardState {
const factory BoardState({ const factory BoardState({
required String viewId, required String viewId,
required Option<DatabasePB> grid, required DatabasePB? grid,
required List<String> groupIds, required List<String> groupIds,
required bool isEditingHeader, required bool isEditingHeader,
required bool isEditingRow, required bool isEditingRow,
required LoadingState loadingState, required LoadingState loadingState,
required Option<FlowyError> noneOrError, required FlowyError? noneOrError,
required BoardLayoutSettingPB? layoutSettings, required BoardLayoutSettingPB? layoutSettings,
String? editingHeaderId, String? editingHeaderId,
BoardEditingRow? editingRow, BoardEditingRow? editingRow,
@ -557,12 +559,12 @@ class BoardState with _$BoardState {
}) = _BoardState; }) = _BoardState;
factory BoardState.initial(String viewId) => BoardState( factory BoardState.initial(String viewId) => BoardState(
grid: none(), grid: null,
viewId: viewId, viewId: viewId,
groupIds: [], groupIds: [],
isEditingHeader: false, isEditingHeader: false,
isEditingRow: false, isEditingRow: false,
noneOrError: none(), noneOrError: null,
loadingState: const LoadingState.loading(), loadingState: const LoadingState.loading(),
layoutSettings: null, layoutSettings: null,
hiddenGroups: [], hiddenGroups: [],

View File

@ -1,12 +1,12 @@
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart'; import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart'; import 'package:flowy_infra/notifier.dart';
import 'package:dartz/dartz.dart';
import 'package:protobuf/protobuf.dart'; import 'package:protobuf/protobuf.dart';
typedef OnGroupError = void Function(FlowyError); typedef OnGroupError = void Function(FlowyError);
@ -112,7 +112,8 @@ class GroupController {
} }
} }
typedef UpdateGroupNotifiedValue = Either<GroupRowsNotificationPB, FlowyError>; typedef UpdateGroupNotifiedValue
= FlowyResult<GroupRowsNotificationPB, FlowyError>;
class SingleGroupListener { class SingleGroupListener {
SingleGroupListener(this.group); SingleGroupListener(this.group);
@ -134,14 +135,14 @@ class SingleGroupListener {
void _handler( void _handler(
DatabaseNotification ty, DatabaseNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case DatabaseNotification.DidUpdateGroupRow: case DatabaseNotification.DidUpdateGroupRow:
result.fold( result.fold(
(payload) => _groupNotifier?.value = (payload) => _groupNotifier?.value =
left(GroupRowsNotificationPB.fromBuffer(payload)), FlowyResult.success(GroupRowsNotificationPB.fromBuffer(payload)),
(error) => _groupNotifier?.value = right(error), (error) => _groupNotifier?.value = FlowyResult.failure(error),
); );
break; break;
default: default:

View File

@ -1,4 +1,3 @@
import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -11,7 +10,7 @@ class BoardSettingBloc extends Bloc<BoardSettingEvent, BoardSettingState> {
(event, emit) async { (event, emit) async {
event.when( event.when(
performAction: (action) { performAction: (action) {
emit(state.copyWith(selectedAction: Some(action))); emit(state.copyWith(selectedAction: action));
}, },
); );
}, },
@ -30,11 +29,11 @@ class BoardSettingEvent with _$BoardSettingEvent {
@freezed @freezed
class BoardSettingState with _$BoardSettingState { class BoardSettingState with _$BoardSettingState {
const factory BoardSettingState({ const factory BoardSettingState({
required Option<BoardSettingAction> selectedAction, required BoardSettingAction? selectedAction,
}) = _BoardSettingState; }) = _BoardSettingState;
factory BoardSettingState.initial() => BoardSettingState( factory BoardSettingState.initial() => const BoardSettingState(
selectedAction: none(), selectedAction: null,
); );
} }

View File

@ -7,8 +7,8 @@ import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:calendar_view/calendar_view.dart'; import 'package:calendar_view/calendar_view.dart';
import 'package:dartz/dartz.dart';
import 'package:fixnum/fixnum.dart'; import 'package:fixnum/fixnum.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -44,15 +44,13 @@ class CalendarBloc extends Bloc<CalendarEvent, CalendarState> {
}, },
didReceiveCalendarSettings: (CalendarLayoutSettingPB settings) { didReceiveCalendarSettings: (CalendarLayoutSettingPB settings) {
// If the field id changed, reload all events // If the field id changed, reload all events
state.settings.fold(() => null, (oldSetting) { if (state.settings?.fieldId != settings.fieldId) {
if (oldSetting.fieldId != settings.fieldId) {
_loadAllEvents(); _loadAllEvents();
} }
}); emit(state.copyWith(settings: settings));
emit(state.copyWith(settings: Some(settings)));
}, },
didReceiveDatabaseUpdate: (DatabasePB database) { didReceiveDatabaseUpdate: (DatabasePB database) {
emit(state.copyWith(database: Some(database))); emit(state.copyWith(database: database));
}, },
didLoadAllEvents: (events) { didLoadAllEvents: (events) {
final calenderEvents = _calendarEventDataFromEventPBs(events); final calenderEvents = _calendarEventDataFromEventPBs(events);
@ -132,21 +130,25 @@ class CalendarBloc extends Bloc<CalendarEvent, CalendarState> {
(database) { (database) {
databaseController.setIsLoading(false); databaseController.setIsLoading(false);
emit( emit(
state.copyWith(loadingState: LoadingState.finish(left(unit))), state.copyWith(
loadingState: LoadingState.finish(FlowyResult.success(null)),
),
); );
}, },
(err) => emit( (err) => emit(
state.copyWith(loadingState: LoadingState.finish(right(err))), state.copyWith(
loadingState: LoadingState.finish(FlowyResult.failure(err)),
),
), ),
); );
} }
Future<void> _createEvent(DateTime date) async { Future<void> _createEvent(DateTime date) async {
return state.settings.fold( final settings = state.settings;
() { if (settings == null) {
Log.warn('Calendar settings not found'); Log.warn('Calendar settings not found');
}, return;
(settings) async { }
final dateField = _getCalendarFieldInfo(settings.fieldId); final dateField = _getCalendarFieldInfo(settings.fieldId);
if (dateField != null) { if (dateField != null) {
final newRow = await RowBackendService.createRow( final newRow = await RowBackendService.createRow(
@ -169,8 +171,6 @@ class CalendarBloc extends Bloc<CalendarEvent, CalendarState> {
} }
} }
} }
},
);
} }
Future<void> _moveEvent(CalendarDayEvent event, DateTime date) async { Future<void> _moveEvent(CalendarDayEvent event, DateTime date) async {
@ -412,7 +412,7 @@ class CalendarEvent with _$CalendarEvent {
@freezed @freezed
class CalendarState with _$CalendarState { class CalendarState with _$CalendarState {
const factory CalendarState({ const factory CalendarState({
required Option<DatabasePB> database, required DatabasePB? database,
// events by row id // events by row id
required Events allEvents, required Events allEvents,
required Events initialEvents, required Events initialEvents,
@ -420,19 +420,19 @@ class CalendarState with _$CalendarState {
CalendarEventData<CalendarDayEvent>? newEvent, CalendarEventData<CalendarDayEvent>? newEvent,
CalendarEventData<CalendarDayEvent>? updateEvent, CalendarEventData<CalendarDayEvent>? updateEvent,
required List<String> deleteEventIds, required List<String> deleteEventIds,
required Option<CalendarLayoutSettingPB> settings, required CalendarLayoutSettingPB? settings,
required LoadingState loadingState, required LoadingState loadingState,
required Option<FlowyError> noneOrError, required FlowyError? noneOrError,
}) = _CalendarState; }) = _CalendarState;
factory CalendarState.initial() => CalendarState( factory CalendarState.initial() => const CalendarState(
database: none(), database: null,
allEvents: [], allEvents: [],
initialEvents: [], initialEvents: [],
deleteEventIds: [], deleteEventIds: [],
settings: none(), settings: null,
noneOrError: none(), noneOrError: null,
loadingState: const LoadingState.loading(), loadingState: LoadingState.loading(),
); );
} }

View File

@ -5,7 +5,6 @@ import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -160,13 +159,13 @@ class UnscheduleEventsEvent with _$UnscheduleEventsEvent {
@freezed @freezed
class UnscheduleEventsState with _$UnscheduleEventsState { class UnscheduleEventsState with _$UnscheduleEventsState {
const factory UnscheduleEventsState({ const factory UnscheduleEventsState({
required Option<DatabasePB> database, required DatabasePB? database,
required List<CalendarEventPB> allEvents, required List<CalendarEventPB> allEvents,
required List<CalendarEventPB> unscheduleEvents, required List<CalendarEventPB> unscheduleEvents,
}) = _UnscheduleEventsState; }) = _UnscheduleEventsState;
factory UnscheduleEventsState.initial() => UnscheduleEventsState( factory UnscheduleEventsState.initial() => const UnscheduleEventsState(
database: none(), database: null,
allEvents: [], allEvents: [],
unscheduleEvents: [], unscheduleEvents: [],
); );

View File

@ -145,10 +145,7 @@ class _EventCardState extends State<EventCard> {
margin: EdgeInsets.zero, margin: EdgeInsets.zero,
offset: const Offset(10.0, 0), offset: const Offset(10.0, 0),
popupBuilder: (BuildContext popoverContext) { popupBuilder: (BuildContext popoverContext) {
final settings = context.watch<CalendarBloc>().state.settings.fold( final settings = context.watch<CalendarBloc>().state.settings;
() => null,
(layoutSettings) => layoutSettings,
);
if (settings == null) { if (settings == null) {
return const SizedBox.shrink(); return const SizedBox.shrink();
} }

View File

@ -1,5 +1,3 @@
import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
@ -20,12 +18,12 @@ import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import '../../application/row/row_controller.dart'; import '../../application/row/row_controller.dart';
import '../../widgets/row/row_detail.dart'; import '../../widgets/row/row_detail.dart';
import 'calendar_day.dart'; import 'calendar_day.dart';
import 'layout/sizes.dart'; import 'layout/sizes.dart';
import 'toolbar/calendar_setting_bar.dart'; import 'toolbar/calendar_setting_bar.dart';
@ -167,8 +165,7 @@ class _CalendarPageState extends State<CalendarPage> {
return _buildCalendar( return _buildCalendar(
context, context,
_eventController, _eventController,
state.settings state.settings?.firstDayOfWeek ?? 0,
.foldLeft(0, (previous, a) => a.firstDayOfWeek),
); );
}, },
); );

View File

@ -2,7 +2,6 @@ import 'package:appflowy/plugins/database/application/calculations/calculations_
import 'package:appflowy/plugins/database/application/calculations/calculations_service.dart'; import 'package:appflowy/plugins/database/application/calculations/calculations_service.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart'; import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart'; import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/calculation_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/calculation_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_settings_entities.pbenum.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/field_settings_entities.pbenum.dart';
import 'package:bloc/bloc.dart'; import 'package:bloc/bloc.dart';
@ -133,7 +132,7 @@ class CalculationsBloc extends Bloc<CalculationsEvent, CalculationsState> {
final calculationsOrFailure = await _calculationsService.getCalculations(); final calculationsOrFailure = await _calculationsService.getCalculations();
final RepeatedCalculationsPB? calculations = final RepeatedCalculationsPB? calculations =
calculationsOrFailure.getLeftOrNull(); calculationsOrFailure.fold((s) => s, (e) => null);
if (calculations != null) { if (calculations != null) {
final calculationMap = <String, CalculationPB>{}; final calculationMap = <String, CalculationPB>{};
for (final calculation in calculations.items) { for (final calculation in calculations.items) {

View File

@ -11,7 +11,7 @@ import 'package:appflowy_backend/protobuf/flowy-database2/number_filter.pb.dart'
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_filter.pbenum.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_filter.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/text_filter.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/text_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -91,7 +91,9 @@ class GridCreateFilterBloc
fieldController.addListener(onReceiveFields: _onFieldFn); fieldController.addListener(onReceiveFields: _onFieldFn);
} }
Future<Either<Unit, FlowyError>> _createDefaultFilter(FieldInfo field) async { Future<FlowyResult<void, FlowyError>> _createDefaultFilter(
FieldInfo field,
) async {
final fieldId = field.id; final fieldId = field.id;
switch (field.fieldType) { switch (field.fieldType) {
case FieldType.Checkbox: case FieldType.Checkbox:
@ -144,7 +146,7 @@ class GridCreateFilterBloc
); );
} }
return left(unit); return FlowyResult.success(null);
} }
@override @override

View File

@ -9,7 +9,7 @@ import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_in
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -65,7 +65,7 @@ class GridBloc extends Bloc<GridEvent, GridState> {
databaseController.moveRow(fromRowId: fromRow, toRowId: toRow); databaseController.moveRow(fromRowId: fromRow, toRowId: toRow);
}, },
didReceiveGridUpdate: (grid) { didReceiveGridUpdate: (grid) {
emit(state.copyWith(grid: Some(grid))); emit(state.copyWith(grid: grid));
}, },
didReceiveFieldUpdate: (fields) { didReceiveFieldUpdate: (fields) {
emit( emit(
@ -147,11 +147,15 @@ class GridBloc extends Bloc<GridEvent, GridState> {
(grid) { (grid) {
databaseController.setIsLoading(false); databaseController.setIsLoading(false);
emit( emit(
state.copyWith(loadingState: LoadingState.finish(left(unit))), state.copyWith(
loadingState: LoadingState.finish(FlowyResult.success(null)),
),
); );
}, },
(err) => emit( (err) => emit(
state.copyWith(loadingState: LoadingState.finish(right(err))), state.copyWith(
loadingState: LoadingState.finish(FlowyResult.failure(err)),
),
), ),
); );
} }
@ -186,7 +190,7 @@ class GridEvent with _$GridEvent {
class GridState with _$GridState { class GridState with _$GridState {
const factory GridState({ const factory GridState({
required String viewId, required String viewId,
required Option<DatabasePB> grid, required DatabasePB? grid,
required List<FieldInfo> fields, required List<FieldInfo> fields,
required List<RowInfo> rowInfos, required List<RowInfo> rowInfos,
required int rowCount, required int rowCount,
@ -204,7 +208,7 @@ class GridState with _$GridState {
rowInfos: [], rowInfos: [],
rowCount: 0, rowCount: 0,
createdRow: null, createdRow: null,
grid: none(), grid: null,
viewId: viewId, viewId: viewId,
reorderable: true, reorderable: true,
loadingState: const LoadingState.loading(), loadingState: const LoadingState.loading(),

View File

@ -4,13 +4,12 @@ import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pbenum.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pbserver.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import '../../../application/field/field_controller.dart'; import '../../../application/field/field_controller.dart';
import '../../../application/sort/sort_service.dart'; import '../../../application/sort/sort_service.dart';
import 'util.dart'; import 'util.dart';
part 'sort_create_bloc.freezed.dart'; part 'sort_create_bloc.freezed.dart';
@ -88,7 +87,9 @@ class CreateSortBloc extends Bloc<CreateSortEvent, CreateSortState> {
fieldController.addListener(onReceiveFields: _onFieldFn); fieldController.addListener(onReceiveFields: _onFieldFn);
} }
Future<Either<Unit, FlowyError>> _createDefaultSort(FieldInfo field) async { Future<FlowyResult<void, FlowyError>> _createDefaultSort(
FieldInfo field,
) async {
final result = await _sortBackendSvc.insertSort( final result = await _sortBackendSvc.insertSort(
fieldId: field.id, fieldId: field.id,
condition: SortConditionPB.Ascending, condition: SortConditionPB.Ascending,

View File

@ -1,17 +1,17 @@
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/field/type_option/select_option_type_option_bloc.dart'; import 'package:appflowy/plugins/database/application/field/type_option/select_option_type_option_bloc.dart';
import 'package:appflowy/plugins/database/application/field/type_option/select_type_option_actions.dart'; import 'package:appflowy/plugins/database/application/field/type_option/select_type_option_actions.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart'; import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/extension.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/extension.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart'; import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'select_option_editor.dart'; import 'select_option_editor.dart';
@ -218,7 +218,7 @@ class _CreateOptionTextFieldState extends State<CreateOptionTextField> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<SelectOptionTypeOptionBloc, SelectOptionTypeOptionState>( return BlocBuilder<SelectOptionTypeOptionBloc, SelectOptionTypeOptionState>(
builder: (context, state) { builder: (context, state) {
final text = state.newOptionName.foldRight("", (a, previous) => a); final text = state.newOptionName ?? '';
return Padding( return Padding(
padding: const EdgeInsets.symmetric(horizontal: 14.0), padding: const EdgeInsets.symmetric(horizontal: 14.0),
child: FlowyTextField( child: FlowyTextField(

View File

@ -1,5 +1,3 @@
import 'package:flutter/material.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart'; import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/tab_bar_bloc.dart'; import 'package:appflowy/plugins/database/application/tab_bar_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart'; import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
@ -12,6 +10,7 @@ import 'package:appflowy/workspace/presentation/widgets/view_title_bar.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'desktop/tab_bar_header.dart'; import 'desktop/tab_bar_header.dart';
@ -221,12 +220,11 @@ class DatabasePluginWidgetBuilder extends PluginWidgetBuilder {
@override @override
Widget buildWidget({PluginContext? context, required bool shrinkWrap}) { Widget buildWidget({PluginContext? context, required bool shrinkWrap}) {
notifier.isDeleted.addListener(() { notifier.isDeleted.addListener(() {
notifier.isDeleted.value.fold(() => null, (deletedView) { final deletedView = notifier.isDeleted.value;
if (deletedView.hasIndex()) { if (deletedView != null && deletedView.hasIndex()) {
context?.onDeleted(notifier.view, deletedView.index); context?.onDeleted(notifier.view, deletedView.index);
} }
}); });
});
return DatabaseTabBarView( return DatabaseTabBarView(
key: ValueKey(notifier.view.id), key: ValueKey(notifier.view.id),
view: notifier.view, view: notifier.view,

View File

@ -260,17 +260,15 @@ class _OptionList extends StatelessWidget {
final List<Widget> cells = []; final List<Widget> cells = [];
// create an option cell // create an option cell
state.createOption.fold( final createOption = state.createOption;
() => null, if (createOption != null) {
(createOption) {
cells.add( cells.add(
_CreateOptionCell( _CreateOptionCell(
optionName: createOption, optionName: createOption,
onTap: () => onCreateOption(createOption), onTap: () => onCreateOption(createOption),
), ),
); );
}, }
);
cells.addAll( cells.addAll(
state.options.map( state.options.map(

View File

@ -12,11 +12,11 @@ import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../application/cell/bloc/select_option_editor_bloc.dart';
import '../../grid/presentation/layout/sizes.dart'; import '../../grid/presentation/layout/sizes.dart';
import '../../grid/presentation/widgets/common/type_option_separator.dart'; import '../../grid/presentation/widgets/common/type_option_separator.dart';
import '../../grid/presentation/widgets/header/type_option/select/select_option_editor.dart'; import '../../grid/presentation/widgets/header/type_option/select/select_option_editor.dart';
import 'extension.dart'; import 'extension.dart';
import '../../application/cell/bloc/select_option_editor_bloc.dart';
import 'select_option_text_field.dart'; import 'select_option_text_field.dart';
const double _editorPanelWidth = 300; const double _editorPanelWidth = 300;
@ -95,12 +95,10 @@ class _OptionList extends StatelessWidget {
), ),
]; ];
state.createOption.fold( final createOption = state.createOption;
() => null, if (createOption != null) {
(createOption) {
cells.add(_CreateOptionCell(name: createOption)); cells.add(_CreateOptionCell(name: createOption));
}, }
);
return ListView.separated( return ListView.separated(
shrinkWrap: true, shrinkWrap: true,

View File

@ -1,7 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:appflowy/plugins/document/application/doc_service.dart'; import 'package:appflowy/plugins/document/application/doc_service.dart';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart'; import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/application/editor_transaction_adapter.dart'; import 'package:appflowy/plugins/document/application/editor_transaction_adapter.dart';
@ -23,7 +21,8 @@ import 'package:appflowy_editor/appflowy_editor.dart'
Selection, Selection,
Position, Position,
paragraphNode; paragraphNode;
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -77,25 +76,28 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
_onViewChanged(); _onViewChanged();
_onDocumentChanged(); _onDocumentChanged();
await editorState.fold( await editorState.fold(
(l) async => emit( (s) async {
state.copyWith(
error: l,
editorState: null,
isLoading: false,
),
),
(r) async {
final result = await getIt<AuthService>().getUser(); final result = await getIt<AuthService>().getUser();
final userProfilePB = result.fold((l) => null, (r) => r); final userProfilePB = result.fold(
(s) => s,
(e) => null,
);
emit( emit(
state.copyWith( state.copyWith(
error: null, error: null,
editorState: r, editorState: s,
isLoading: false, isLoading: false,
userProfilePB: userProfilePB, userProfilePB: userProfilePB,
), ),
); );
}, },
(f) async => emit(
state.copyWith(
error: f,
editorState: null,
isLoading: false,
),
),
); );
}, },
moveToTrash: () async { moveToTrash: () async {
@ -124,13 +126,12 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
void _onViewChanged() { void _onViewChanged() {
_viewListener.start( _viewListener.start(
onViewMoveToTrash: (r) { onViewMoveToTrash: (r) {
r.swap().map((r) => add(const DocumentEvent.moveToTrash())); r.map((r) => add(const DocumentEvent.moveToTrash()));
}, },
onViewDeleted: (r) { onViewDeleted: (r) {
r.swap().map((r) => add(const DocumentEvent.moveToTrash())); r.map((r) => add(const DocumentEvent.moveToTrash()));
}, },
onViewRestored: (r) => onViewRestored: (r) => r.map((r) => add(const DocumentEvent.restore())),
r.swap().map((r) => add(const DocumentEvent.restore())),
); );
} }
@ -150,11 +151,11 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
} }
/// Fetch document /// Fetch document
Future<Either<FlowyError, EditorState?>> _fetchDocumentState() async { Future<FlowyResult<EditorState?, FlowyError>> _fetchDocumentState() async {
final result = await _documentService.openDocument(viewId: view.id); final result = await _documentService.openDocument(viewId: view.id);
return result.fold( return result.fold(
(l) => left(l), (s) async => FlowyResult.success(await _initAppFlowyEditorState(s)),
(r) async => right(await _initAppFlowyEditorState(r)), (e) => FlowyResult.failure(e),
); );
} }

View File

@ -2,56 +2,56 @@ import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
class DocumentService { class DocumentService {
// unused now. // unused now.
Future<Either<FlowyError, Unit>> createDocument({ Future<FlowyResult<void, FlowyError>> createDocument({
required ViewPB view, required ViewPB view,
}) async { }) async {
final canOpen = await openDocument(viewId: view.id); final canOpen = await openDocument(viewId: view.id);
if (canOpen.isRight()) { if (canOpen.isSuccess()) {
return const Right(unit); return FlowyResult.success(null);
} }
final payload = CreateDocumentPayloadPB()..documentId = view.id; final payload = CreateDocumentPayloadPB()..documentId = view.id;
final result = await DocumentEventCreateDocument(payload).send(); final result = await DocumentEventCreateDocument(payload).send();
return result.swap(); return result;
} }
Future<Either<FlowyError, DocumentDataPB>> openDocument({ Future<FlowyResult<DocumentDataPB, FlowyError>> openDocument({
required String viewId, required String viewId,
}) async { }) async {
final payload = OpenDocumentPayloadPB()..documentId = viewId; final payload = OpenDocumentPayloadPB()..documentId = viewId;
final result = await DocumentEventOpenDocument(payload).send(); final result = await DocumentEventOpenDocument(payload).send();
return result.swap(); return result;
} }
Future<Either<FlowyError, BlockPB>> getBlockFromDocument({ Future<FlowyResult<BlockPB, FlowyError>> getBlockFromDocument({
required DocumentDataPB document, required DocumentDataPB document,
required String blockId, required String blockId,
}) async { }) async {
final block = document.blocks[blockId]; final block = document.blocks[blockId];
if (block != null) { if (block != null) {
return right(block); return FlowyResult.success(block);
} }
return left( return FlowyResult.failure(
FlowyError( FlowyError(
msg: 'Block($blockId) not found in Document(${document.pageId})', msg: 'Block($blockId) not found in Document(${document.pageId})',
), ),
); );
} }
Future<Either<FlowyError, Unit>> closeDocument({ Future<FlowyResult<void, FlowyError>> closeDocument({
required ViewPB view, required ViewPB view,
}) async { }) async {
final payload = CloseDocumentPayloadPB()..documentId = view.id; final payload = CloseDocumentPayloadPB()..documentId = view.id;
final result = await DocumentEventCloseDocument(payload).send(); final result = await DocumentEventCloseDocument(payload).send();
return result.swap(); return result;
} }
Future<Either<FlowyError, Unit>> applyAction({ Future<FlowyResult<void, FlowyError>> applyAction({
required String documentId, required String documentId,
required Iterable<BlockActionPB> actions, required Iterable<BlockActionPB> actions,
}) async { }) async {
@ -60,7 +60,7 @@ class DocumentService {
actions: actions, actions: actions,
); );
final result = await DocumentEventApplyAction(payload).send(); final result = await DocumentEventApplyAction(payload).send();
return result.swap(); return result;
} }
/// Creates a new external text. /// Creates a new external text.
@ -68,7 +68,7 @@ class DocumentService {
/// Normally, it's used to the block that needs sync long text. /// Normally, it's used to the block that needs sync long text.
/// ///
/// the delta parameter is the json representation of the delta. /// the delta parameter is the json representation of the delta.
Future<Either<FlowyError, Unit>> createExternalText({ Future<FlowyResult<void, FlowyError>> createExternalText({
required String documentId, required String documentId,
required String textId, required String textId,
String? delta, String? delta,
@ -79,7 +79,7 @@ class DocumentService {
delta: delta, delta: delta,
); );
final result = await DocumentEventCreateText(payload).send(); final result = await DocumentEventCreateText(payload).send();
return result.swap(); return result;
} }
/// Updates the external text. /// Updates the external text.
@ -87,7 +87,7 @@ class DocumentService {
/// this function is compatible with the [createExternalText] function. /// this function is compatible with the [createExternalText] function.
/// ///
/// the delta parameter is the json representation of the delta too. /// the delta parameter is the json representation of the delta too.
Future<Either<FlowyError, Unit>> updateExternalText({ Future<FlowyResult<void, FlowyError>> updateExternalText({
required String documentId, required String documentId,
required String textId, required String textId,
String? delta, String? delta,
@ -98,11 +98,11 @@ class DocumentService {
delta: delta, delta: delta,
); );
final result = await DocumentEventApplyTextDeltaEvent(payload).send(); final result = await DocumentEventApplyTextDeltaEvent(payload).send();
return result.swap(); return result;
} }
/// Upload a file to the cloud storage. /// Upload a file to the cloud storage.
Future<Either<FlowyError, UploadedFilePB>> uploadFile({ Future<FlowyResult<UploadedFilePB, FlowyError>> uploadFile({
required String localFilePath, required String localFilePath,
bool isAsync = true, bool isAsync = true,
}) async { }) async {
@ -114,14 +114,14 @@ class DocumentService {
isAsync: isAsync, isAsync: isAsync,
); );
final result = await DocumentEventUploadFile(payload).send(); final result = await DocumentEventUploadFile(payload).send();
return result.swap(); return result;
}, (r) async { }, (r) async {
return left(FlowyError(msg: 'Workspace not found')); return FlowyResult.failure(FlowyError(msg: 'Workspace not found'));
}); });
} }
/// Download a file from the cloud storage. /// Download a file from the cloud storage.
Future<Either<FlowyError, Unit>> downloadFile({ Future<FlowyResult<void, FlowyError>> downloadFile({
required String url, required String url,
}) async { }) async {
final workspace = await FolderEventReadCurrentWorkspace().send(); final workspace = await FolderEventReadCurrentWorkspace().send();
@ -130,9 +130,9 @@ class DocumentService {
url: url, url: url,
); );
final result = await DocumentEventDownloadFile(payload).send(); final result = await DocumentEventDownloadFile(payload).send();
return result.swap(); return result;
}, (r) async { }, (r) async {
return left(FlowyError(msg: 'Workspace not found')); return FlowyResult.failure(FlowyError(msg: 'Workspace not found'));
}); });
} }
} }

View File

@ -4,7 +4,7 @@ import 'package:appflowy/workspace/application/export/document_exporter.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -28,8 +28,9 @@ class DocShareBloc extends Bloc<DocShareEvent, DocShareState> {
emit( emit(
DocShareState.finish( DocShareState.finish(
result.fold( result.fold(
(error) => right(error), (markdown) =>
(markdown) => left(_saveMarkdownToPath(markdown, event.path)), FlowyResult.success(_saveMarkdownToPath(markdown, event.path)),
(error) => FlowyResult.failure(error),
), ),
), ),
); );
@ -55,6 +56,6 @@ class DocShareState with _$DocShareState {
const factory DocShareState.initial() = _Initial; const factory DocShareState.initial() = _Initial;
const factory DocShareState.loading() = _Loading; const factory DocShareState.loading() = _Loading;
const factory DocShareState.finish( const factory DocShareState.finish(
Either<ExportDataPB, FlowyError> successOrFail, FlowyResult<ExportDataPB, FlowyError> successOrFail,
) = _Finish; ) = _Finish;
} }

View File

@ -1,14 +1,12 @@
library document_plugin; library document_plugin;
import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/document_page.dart'; import 'package:appflowy/plugins/document/document_page.dart';
import 'package:appflowy/plugins/document/presentation/favorite/favorite_button.dart';
import 'package:appflowy/plugins/document/presentation/more/cubit/document_appearance_cubit.dart'; import 'package:appflowy/plugins/document/presentation/more/cubit/document_appearance_cubit.dart';
import 'package:appflowy/plugins/document/presentation/more/more_button.dart'; import 'package:appflowy/plugins/document/presentation/more/more_button.dart';
import 'package:appflowy/plugins/document/presentation/share/share_button.dart'; import 'package:appflowy/plugins/document/presentation/share/share_button.dart';
import 'package:appflowy/plugins/document/presentation/favorite/favorite_button.dart';
import 'package:appflowy/plugins/util.dart'; import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart'; import 'package:appflowy/workspace/presentation/home/home_stack.dart';
@ -18,6 +16,7 @@ import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
class DocumentPluginBuilder extends PluginBuilder { class DocumentPluginBuilder extends PluginBuilder {
@ -90,14 +89,10 @@ class DocumentPluginWidgetBuilder extends PluginWidgetBuilder
@override @override
Widget buildWidget({PluginContext? context, required bool shrinkWrap}) { Widget buildWidget({PluginContext? context, required bool shrinkWrap}) {
notifier.isDeleted.addListener(() { notifier.isDeleted.addListener(() {
notifier.isDeleted.value.fold( final deletedView = notifier.isDeleted.value;
() => null, if (deletedView != null && deletedView.hasIndex()) {
(deletedView) {
if (deletedView.hasIndex()) {
deletedViewIndex = deletedView.index; deletedViewIndex = deletedView.index;
} }
},
);
}); });
return BlocBuilder<DocumentAppearanceCubit, DocumentAppearance>( return BlocBuilder<DocumentAppearanceCubit, DocumentAppearance>(

View File

@ -1,23 +1,22 @@
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart'; import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view/view_service.dart'; import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:dartz/dartz.dart' as dartz; import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
class BuiltInPageWidget extends StatefulWidget { class BuiltInPageWidget extends StatefulWidget {
const BuiltInPageWidget({ const BuiltInPageWidget({
@ -36,7 +35,8 @@ class BuiltInPageWidget extends StatefulWidget {
} }
class _BuiltInPageWidgetState extends State<BuiltInPageWidget> { class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
late Future<dartz.Either<FlowyError, ViewPB>> future; late Future<FlowyResult<ViewPB, FlowyError>> future;
final focusNode = FocusNode(); final focusNode = FocusNode();
String get parentViewId => widget.node.attributes[DatabaseBlockKeys.parentID]; String get parentViewId => widget.node.attributes[DatabaseBlockKeys.parentID];
@ -45,13 +45,9 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
future = ViewBackendService() future = ViewBackendService().getChildView(
.getChildView(
parentViewId: parentViewId, parentViewId: parentViewId,
childViewId: childViewId, childViewId: childViewId,
)
.then(
(value) => value.swap(),
); );
} }
@ -63,9 +59,9 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return FutureBuilder<dartz.Either<FlowyError, ViewPB>>( return FutureBuilder<FlowyResult<ViewPB, FlowyError>>(
builder: (context, snapshot) { builder: (context, snapshot) {
final page = snapshot.data?.toOption().toNullable(); final page = snapshot.data?.toNullable();
if (snapshot.hasData && page != null) { if (snapshot.hasData && page != null) {
return _build(context, page); return _build(context, page);
} }

View File

@ -87,7 +87,7 @@ extension InsertDatabase on EditorState {
// get the database id that the view is associated with // get the database id that the view is associated with
final databaseId = await DatabaseViewBackendService(viewId: view.id) final databaseId = await DatabaseViewBackendService(viewId: view.id)
.getDatabaseId() .getDatabaseId()
.then((value) => value.swap().toOption().toNullable()); .then((value) => value.toNullable());
if (databaseId == null) { if (databaseId == null) {
throw StateError( throw StateError(
@ -101,7 +101,7 @@ extension InsertDatabase on EditorState {
name: "$prefix ${view.name}", name: "$prefix ${view.name}",
layoutType: view.layout, layoutType: view.layout,
databaseId: databaseId, databaseId: databaseId,
).then((value) => value.swap().toOption().toNullable()); ).then((value) => value.toNullable());
if (ref == null) { if (ref == null) {
throw FlowyError( throw FlowyError(

View File

@ -25,7 +25,7 @@ SelectionMenuItem inlineGridMenuItem(DocumentBloc documentBloc) =>
name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(),
layoutType: ViewLayoutPB.Grid, layoutType: ViewLayoutPB.Grid,
); );
value.swap().map((r) => editorState.insertInlinePage(parentViewId, r)); value.map((r) => editorState.insertInlinePage(parentViewId, r));
}, },
); );
@ -46,7 +46,7 @@ SelectionMenuItem inlineBoardMenuItem(DocumentBloc documentBloc) =>
name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(),
layoutType: ViewLayoutPB.Board, layoutType: ViewLayoutPB.Board,
); );
value.swap().map((r) => editorState.insertInlinePage(parentViewId, r)); value.map((r) => editorState.insertInlinePage(parentViewId, r));
}, },
); );
@ -68,6 +68,6 @@ SelectionMenuItem inlineCalendarMenuItem(DocumentBloc documentBloc) =>
name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(),
layoutType: ViewLayoutPB.Calendar, layoutType: ViewLayoutPB.Calendar,
); );
value.swap().map((r) => editorState.insertInlinePage(parentViewId, r)); value.map((r) => editorState.insertInlinePage(parentViewId, r));
}, },
); );

View File

@ -1,18 +1,18 @@
import 'dart:io'; import 'dart:io';
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/custom_cover_picker_bloc.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/custom_cover_picker_bloc.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/snap_bar.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flowy_infra/size.dart'; import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/button.dart'; import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/snap_bar.dart';
import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/style_widget/text_field.dart'; import 'package:flowy_infra_ui/style_widget/text_field.dart';
import 'package:flowy_infra_ui/widget/rounded_button.dart'; import 'package:flowy_infra_ui/widget/rounded_button.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CoverImagePicker extends StatefulWidget { class CoverImagePicker extends StatefulWidget {
const CoverImagePicker({ const CoverImagePicker({
@ -37,12 +37,13 @@ class _CoverImagePickerState extends State<CoverImagePicker> {
child: BlocListener<CoverImagePickerBloc, CoverImagePickerState>( child: BlocListener<CoverImagePickerBloc, CoverImagePickerState>(
listener: (context, state) { listener: (context, state) {
if (state is NetworkImagePicked) { if (state is NetworkImagePicked) {
state.successOrFail.isRight() state.successOrFail.fold(
? showSnapBar( (s) {},
(e) => showSnapBar(
context, context,
LocaleKeys.document_plugins_cover_invalidImageUrl.tr(), LocaleKeys.document_plugins_cover_invalidImageUrl.tr(),
) ),
: null; );
} }
if (state is Done) { if (state is Done) {
state.successOrFail.fold( state.successOrFail.fold(

View File

@ -4,7 +4,7 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart'; import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
@ -36,11 +36,15 @@ class CoverImagePickerBloc
emit(const CoverImagePickerState.loading()); emit(const CoverImagePickerState.loading());
final validateImage = await _validateURL(urlSubmit.path); final validateImage = await _validateURL(urlSubmit.path);
if (validateImage) { if (validateImage) {
emit(CoverImagePickerState.networkImage(left(urlSubmit.path))); emit(
CoverImagePickerState.networkImage(
FlowyResult.success(urlSubmit.path),
),
);
} else { } else {
emit( emit(
CoverImagePickerState.networkImage( CoverImagePickerState.networkImage(
right( FlowyResult.failure(
FlowyError( FlowyError(
msg: LocaleKeys.document_plugins_cover_couldNotFetchImage msg: LocaleKeys.document_plugins_cover_couldNotFetchImage
.tr(), .tr(),
@ -65,11 +69,11 @@ class CoverImagePickerBloc
emit(const CoverImagePickerState.loading()); emit(const CoverImagePickerState.loading());
final saveImage = await _saveToGallery(saveToGallery.previousState); final saveImage = await _saveToGallery(saveToGallery.previousState);
if (saveImage != null) { if (saveImage != null) {
emit(CoverImagePickerState.done(left(saveImage))); emit(CoverImagePickerState.done(FlowyResult.success(saveImage)));
} else { } else {
emit( emit(
CoverImagePickerState.done( CoverImagePickerState.done(
right( FlowyResult.failure(
FlowyError( FlowyError(
msg: LocaleKeys.document_plugins_cover_imageSavingFailed msg: LocaleKeys.document_plugins_cover_imageSavingFailed
.tr(), .tr(),
@ -208,11 +212,11 @@ class CoverImagePickerState with _$CoverImagePickerState {
const factory CoverImagePickerState.initial() = Initial; const factory CoverImagePickerState.initial() = Initial;
const factory CoverImagePickerState.loading() = Loading; const factory CoverImagePickerState.loading() = Loading;
const factory CoverImagePickerState.networkImage( const factory CoverImagePickerState.networkImage(
Either<String, FlowyError> successOrFail, FlowyResult<String, FlowyError> successOrFail,
) = NetworkImagePicked; ) = NetworkImagePicked;
const factory CoverImagePickerState.fileImage(String path) = FileImagePicked; const factory CoverImagePickerState.fileImage(String path) = FileImagePicked;
const factory CoverImagePickerState.done( const factory CoverImagePickerState.done(
Either<List<String>, FlowyError> successOrFail, FlowyResult<List<String>, FlowyError> successOrFail,
) = Done; ) = Done;
} }

View File

@ -43,13 +43,13 @@ Future<(String? path, String? errorMessage)> saveImageToCloudStorage(
isAsync: false, isAsync: false,
); );
return result.fold( return result.fold(
(l) => (null, l.msg), (s) async {
(r) async {
await CustomImageCacheManager().putFile( await CustomImageCacheManager().putFile(
r.url, s.url,
File(localImagePath).readAsBytesSync(), File(localImagePath).readAsBytesSync(),
); );
return (r.url, null); return (s.url, null);
}, },
(e) => (null, e.msg),
); );
} }

View File

@ -4,7 +4,7 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart';
import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/startup.dart';
import 'package:dartz/dartz.dart' hide State; import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -22,7 +22,7 @@ class OpenAIImageWidget extends StatefulWidget {
} }
class _OpenAIImageWidgetState extends State<OpenAIImageWidget> { class _OpenAIImageWidgetState extends State<OpenAIImageWidget> {
Future<Either<OpenAIError, List<String>>>? future; Future<FlowyResult<List<String>, OpenAIError>>? future;
String query = ''; String query = '';
@override @override
@ -63,19 +63,12 @@ class _OpenAIImageWidgetState extends State<OpenAIImageWidget> {
return const CircularProgressIndicator.adaptive(); return const CircularProgressIndicator.adaptive();
} }
return data.fold( return data.fold(
(l) => Center( (s) => GridView.count(
child: FlowyText(
l.message,
maxLines: 3,
textAlign: TextAlign.center,
),
),
(r) => GridView.count(
crossAxisCount: 3, crossAxisCount: 3,
mainAxisSpacing: 16.0, mainAxisSpacing: 16.0,
crossAxisSpacing: 10.0, crossAxisSpacing: 10.0,
childAspectRatio: 4 / 3, childAspectRatio: 4 / 3,
children: r children: s
.map( .map(
(e) => GestureDetector( (e) => GestureDetector(
onTap: () => widget.onSelectNetworkImage(e), onTap: () => widget.onSelectNetworkImage(e),
@ -84,6 +77,13 @@ class _OpenAIImageWidgetState extends State<OpenAIImageWidget> {
) )
.toList(), .toList(),
), ),
(e) => Center(
child: FlowyText(
e.message,
maxLines: 3,
textAlign: TextAlign.center,
),
),
); );
}, },
), ),

View File

@ -6,7 +6,7 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_client.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_error.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_error.dart';
import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/startup.dart';
import 'package:dartz/dartz.dart' hide State; import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/uuid.dart'; import 'package:flowy_infra/uuid.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@ -27,7 +27,7 @@ class StabilityAIImageWidget extends StatefulWidget {
} }
class _StabilityAIImageWidgetState extends State<StabilityAIImageWidget> { class _StabilityAIImageWidgetState extends State<StabilityAIImageWidget> {
Future<Either<StabilityAIRequestError, List<String>>>? future; Future<FlowyResult<List<String>, StabilityAIRequestError>>? future;
String query = ''; String query = '';
@override @override
@ -70,19 +70,12 @@ class _StabilityAIImageWidgetState extends State<StabilityAIImageWidget> {
return const CircularProgressIndicator.adaptive(); return const CircularProgressIndicator.adaptive();
} }
return data.fold( return data.fold(
(l) => Center( (s) => GridView.count(
child: FlowyText(
l.message,
maxLines: 3,
textAlign: TextAlign.center,
),
),
(r) => GridView.count(
crossAxisCount: 3, crossAxisCount: 3,
mainAxisSpacing: 16.0, mainAxisSpacing: 16.0,
crossAxisSpacing: 10.0, crossAxisSpacing: 10.0,
childAspectRatio: 4 / 3, childAspectRatio: 4 / 3,
children: r.map( children: s.map(
(e) { (e) {
final base64Image = base64Decode(e); final base64Image = base64Decode(e);
return GestureDetector( return GestureDetector(
@ -100,6 +93,13 @@ class _StabilityAIImageWidgetState extends State<StabilityAIImageWidget> {
}, },
).toList(), ).toList(),
), ),
(e) => Center(
child: FlowyText(
e.message,
maxLines: 3,
textAlign: TextAlign.center,
),
),
); );
}, },
), ),

View File

@ -76,12 +76,12 @@ class _UploadImageMenuState extends State<UploadImageMenu> {
UserBackendService.getCurrentUserProfile().then( UserBackendService.getCurrentUserProfile().then(
(value) { (value) {
final supportOpenAI = value.fold( final supportOpenAI = value.fold(
(l) => false, (s) => s.openaiKey.isNotEmpty,
(r) => r.openaiKey.isNotEmpty, (e) => false,
); );
final supportStabilityAI = value.fold( final supportStabilityAI = value.fold(
(l) => false, (s) => s.stabilityAiKey.isNotEmpty,
(r) => r.stabilityAiKey.isNotEmpty, (e) => false,
); );
if (supportOpenAI != this.supportOpenAI || if (supportOpenAI != this.supportOpenAI ||
supportStabilityAI != this.supportStabilityAI) { supportStabilityAI != this.supportStabilityAI) {

View File

@ -12,7 +12,7 @@ class LinkPreviewDataCache implements LinkPreviewDataCacheInterface {
url, url,
(value) => LinkPreviewData.fromJson(jsonDecode(value)), (value) => LinkPreviewData.fromJson(jsonDecode(value)),
); );
return option.fold(() => null, (a) => a); return option;
} }
@override @override

View File

@ -126,7 +126,7 @@ class _MentionPageBlockState extends State<MentionPageBlock> {
Future<ViewPB?> fetchView(String pageId) async { Future<ViewPB?> fetchView(String pageId) async {
final view = await ViewBackendService.getView(pageId).then( final view = await ViewBackendService.getView(pageId).then(
(value) => value.swap().toOption().toNullable(), (value) => value.toNullable(),
); );
if (view == null) { if (view == null) {

View File

@ -2,7 +2,7 @@ import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/text_edit.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/text_edit.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'error.dart'; import 'error.dart';
@ -33,7 +33,7 @@ abstract class OpenAIRepository {
/// [maxTokens] is the maximum number of tokens to generate /// [maxTokens] is the maximum number of tokens to generate
/// [temperature] is the temperature of the model /// [temperature] is the temperature of the model
/// ///
Future<Either<OpenAIError, TextCompletionResponse>> getCompletions({ Future<FlowyResult<TextCompletionResponse, OpenAIError>> getCompletions({
required String prompt, required String prompt,
String? suffix, String? suffix,
int maxTokens = 2048, int maxTokens = 2048,
@ -58,7 +58,7 @@ abstract class OpenAIRepository {
/// [instruction] is the instruction text /// [instruction] is the instruction text
/// [temperature] is the temperature of the model /// [temperature] is the temperature of the model
/// ///
Future<Either<OpenAIError, TextEditResponse>> getEdits({ Future<FlowyResult<TextEditResponse, OpenAIError>> getEdits({
required String input, required String input,
required String instruction, required String instruction,
double temperature = 0.3, double temperature = 0.3,
@ -70,7 +70,7 @@ abstract class OpenAIRepository {
/// [n] is the number of images to generate /// [n] is the number of images to generate
/// ///
/// the result is a list of urls /// the result is a list of urls
Future<Either<OpenAIError, List<String>>> generateImage({ Future<FlowyResult<List<String>, OpenAIError>> generateImage({
required String prompt, required String prompt,
int n = 1, int n = 1,
}); });
@ -91,7 +91,7 @@ class HttpOpenAIRepository implements OpenAIRepository {
}; };
@override @override
Future<Either<OpenAIError, TextCompletionResponse>> getCompletions({ Future<FlowyResult<TextCompletionResponse, OpenAIError>> getCompletions({
required String prompt, required String prompt,
String? suffix, String? suffix,
int maxTokens = 2048, int maxTokens = 2048,
@ -113,7 +113,7 @@ class HttpOpenAIRepository implements OpenAIRepository {
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
return Right( return FlowyResult.success(
TextCompletionResponse.fromJson( TextCompletionResponse.fromJson(
json.decode( json.decode(
utf8.decode(response.bodyBytes), utf8.decode(response.bodyBytes),
@ -121,7 +121,9 @@ class HttpOpenAIRepository implements OpenAIRepository {
), ),
); );
} else { } else {
return Left(OpenAIError.fromJson(json.decode(response.body)['error'])); return FlowyResult.failure(
OpenAIError.fromJson(json.decode(response.body)['error']),
);
} }
} }
@ -206,7 +208,7 @@ class HttpOpenAIRepository implements OpenAIRepository {
} }
@override @override
Future<Either<OpenAIError, TextEditResponse>> getEdits({ Future<FlowyResult<TextEditResponse, OpenAIError>> getEdits({
required String input, required String input,
required String instruction, required String instruction,
double temperature = 0.3, double temperature = 0.3,
@ -227,7 +229,7 @@ class HttpOpenAIRepository implements OpenAIRepository {
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
return Right( return FlowyResult.success(
TextEditResponse.fromJson( TextEditResponse.fromJson(
json.decode( json.decode(
utf8.decode(response.bodyBytes), utf8.decode(response.bodyBytes),
@ -235,12 +237,14 @@ class HttpOpenAIRepository implements OpenAIRepository {
), ),
); );
} else { } else {
return Left(OpenAIError.fromJson(json.decode(response.body)['error'])); return FlowyResult.failure(
OpenAIError.fromJson(json.decode(response.body)['error']),
);
} }
} }
@override @override
Future<Either<OpenAIError, List<String>>> generateImage({ Future<FlowyResult<List<String>, OpenAIError>> generateImage({
required String prompt, required String prompt,
int n = 1, int n = 1,
}) async { }) async {
@ -266,12 +270,14 @@ class HttpOpenAIRepository implements OpenAIRepository {
.expand((e) => e) .expand((e) => e)
.map((e) => e.toString()) .map((e) => e.toString())
.toList(); .toList();
return Right(urls); return FlowyResult.success(urls);
} else { } else {
return Left(OpenAIError.fromJson(json.decode(response.body)['error'])); return FlowyResult.failure(
OpenAIError.fromJson(json.decode(response.body)['error']),
);
} }
} catch (error) { } catch (error) {
return Left(OpenAIError(message: error.toString())); return FlowyResult.failure(OpenAIError(message: error.toString()));
} }
} }
} }

View File

@ -193,7 +193,7 @@ class _AutoCompletionBlockComponentState
await _updateEditingText(); await _updateEditingText();
final userProfile = await UserBackendService.getCurrentUserProfile() final userProfile = await UserBackendService.getCurrentUserProfile()
.then((value) => value.toOption().toNullable()); .then((value) => value.toNullable());
if (userProfile == null) { if (userProfile == null) {
await loading.stop(); await loading.stop();
if (mounted) { if (mounted) {
@ -290,7 +290,7 @@ class _AutoCompletionBlockComponentState
} }
// generate new response // generate new response
final userProfile = await UserBackendService.getCurrentUserProfile() final userProfile = await UserBackendService.getCurrentUserProfile()
.then((value) => value.toOption().toNullable()); .then((value) => value.toNullable());
if (userProfile == null) { if (userProfile == null) {
await loading.stop(); await loading.stop();
if (mounted) { if (mounted) {

View File

@ -41,8 +41,8 @@ class _SmartEditActionListState extends State<SmartEditActionList> {
UserBackendService.getCurrentUserProfile().then((value) { UserBackendService.getCurrentUserProfile().then((value) {
setState(() { setState(() {
isOpenAIEnabled = value.fold( isOpenAIEnabled = value.fold(
(l) => false, (s) => s.openaiKey.isNotEmpty,
(r) => r.openaiKey.isNotEmpty, (_) => false,
); );
}); });
}); });

View File

@ -2,7 +2,7 @@ import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_error.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_error.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
enum StabilityAIRequestType { enum StabilityAIRequestType {
@ -25,7 +25,7 @@ abstract class StabilityAIRepository {
/// [n] is the number of images to generate /// [n] is the number of images to generate
/// ///
/// the return value is a list of base64 encoded images /// the return value is a list of base64 encoded images
Future<Either<StabilityAIRequestError, List<String>>> generateImage({ Future<FlowyResult<List<String>, StabilityAIRequestError>> generateImage({
required String prompt, required String prompt,
int n = 1, int n = 1,
}); });
@ -46,7 +46,7 @@ class HttpStabilityAIRepository implements StabilityAIRepository {
}; };
@override @override
Future<Either<StabilityAIRequestError, List<String>>> generateImage({ Future<FlowyResult<List<String>, StabilityAIRequestError>> generateImage({
required String prompt, required String prompt,
int n = 1, int n = 1,
}) async { }) async {
@ -76,16 +76,16 @@ class HttpStabilityAIRepository implements StabilityAIRepository {
(e) => e['base64'].toString(), (e) => e['base64'].toString(),
) )
.toList(); .toList();
return Right(base64Images); return FlowyResult.success(base64Images);
} else { } else {
return Left( return FlowyResult.failure(
StabilityAIRequestError( StabilityAIRequestError(
data['message'].toString(), data['message'].toString(),
), ),
); );
} }
} catch (error) { } catch (error) {
return Left( return FlowyResult.failure(
StabilityAIRequestError( StabilityAIRequestError(
error.toString(), error.toString(),
), ),

View File

@ -92,8 +92,8 @@ class DateReferenceService {
final result = await DateService.queryDate(search); final result = await DateService.queryDate(search);
result.fold( result.fold(
(l) {},
(date) => options.insert(0, _itemFromDate(date)), (date) => options.insert(0, _itemFromDate(date)),
(_) {},
); );
} }

View File

@ -1,5 +1,3 @@
import 'package:flutter/material.dart';
import 'package:appflowy/date/date_service.dart'; import 'package:appflowy/date/date_service.dart';
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/doc_bloc.dart'; import 'package:appflowy/plugins/document/application/doc_bloc.dart';
@ -13,6 +11,7 @@ import 'package:appflowy_backend/protobuf/flowy-user/reminder.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart'; import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:nanoid/nanoid.dart'; import 'package:nanoid/nanoid.dart';
@ -111,13 +110,13 @@ class ReminderReferenceService {
final result = await DateService.queryDate(search); final result = await DateService.queryDate(search);
result.fold( result.fold(
(l) {},
(date) { (date) {
// Only insert dates in the future // Only insert dates in the future
if (DateTime.now().isBefore(date)) { if (DateTime.now().isBefore(date)) {
options.insert(0, _itemFromDate(date)); options.insert(0, _itemFromDate(date));
} }
}, },
(_) {},
); );
} }

View File

@ -3,7 +3,7 @@ import 'package:appflowy/plugins/trash/application/trash_service.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
@ -26,13 +26,15 @@ class TrashBloc extends Bloc<TrashEvent, TrashState> {
initial: (e) async { initial: (e) async {
_listener.start(trashUpdated: _listenTrashUpdated); _listener.start(trashUpdated: _listenTrashUpdated);
final result = await _service.readTrash(); final result = await _service.readTrash();
emit( emit(
result.fold( result.fold(
(object) => state.copyWith( (object) => state.copyWith(
objects: object.items, objects: object.items,
successOrFailure: left(unit), successOrFailure: FlowyResult.success(null),
), ),
(error) => state.copyWith(successOrFailure: right(error)), (error) =>
state.copyWith(successOrFailure: FlowyResult.failure(error)),
), ),
); );
}, },
@ -60,18 +62,20 @@ class TrashBloc extends Bloc<TrashEvent, TrashState> {
} }
Future<void> _handleResult( Future<void> _handleResult(
Either<dynamic, FlowyError> result, FlowyResult<dynamic, FlowyError> result,
Emitter<TrashState> emit, Emitter<TrashState> emit,
) async { ) async {
emit( emit(
result.fold( result.fold(
(l) => state.copyWith(successOrFailure: left(unit)), (l) => state.copyWith(successOrFailure: FlowyResult.success(null)),
(error) => state.copyWith(successOrFailure: right(error)), (error) => state.copyWith(successOrFailure: FlowyResult.failure(error)),
), ),
); );
} }
void _listenTrashUpdated(Either<List<TrashPB>, FlowyError> trashOrFailed) { void _listenTrashUpdated(
FlowyResult<List<TrashPB>, FlowyError> trashOrFailed,
) {
trashOrFailed.fold( trashOrFailed.fold(
(trash) { (trash) {
add(TrashEvent.didReceiveTrash(trash)); add(TrashEvent.didReceiveTrash(trash));
@ -103,11 +107,11 @@ class TrashEvent with _$TrashEvent {
class TrashState with _$TrashState { class TrashState with _$TrashState {
const factory TrashState({ const factory TrashState({
required List<TrashPB> objects, required List<TrashPB> objects,
required Either<Unit, FlowyError> successOrFailure, required FlowyResult<void, FlowyError> successOrFailure,
}) = _TrashState; }) = _TrashState;
factory TrashState.init() => TrashState( factory TrashState.init() => TrashState(
objects: [], objects: [],
successOrFailure: left(unit), successOrFailure: FlowyResult.success(null),
); );
} }

View File

@ -1,15 +1,16 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:appflowy/core/notification/folder_notification.dart'; import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/rust_stream.dart'; import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
typedef TrashUpdatedCallback = void Function( typedef TrashUpdatedCallback = void Function(
Either<List<TrashPB>, FlowyError> trashOrFailed, FlowyResult<List<TrashPB>, FlowyError> trashOrFailed,
); );
class TrashListener { class TrashListener {
@ -29,7 +30,7 @@ class TrashListener {
void _observableCallback( void _observableCallback(
FolderNotification ty, FolderNotification ty,
Either<Uint8List, FlowyError> result, FlowyResult<Uint8List, FlowyError> result,
) { ) {
switch (ty) { switch (ty) {
case FolderNotification.DidUpdateTrash: case FolderNotification.DidUpdateTrash:
@ -37,9 +38,9 @@ class TrashListener {
result.fold( result.fold(
(payload) { (payload) {
final repeatedTrash = RepeatedTrashPB.fromBuffer(payload); final repeatedTrash = RepeatedTrashPB.fromBuffer(payload);
_trashUpdated!(left(repeatedTrash.items)); _trashUpdated!(FlowyResult.success(repeatedTrash.items));
}, },
(error) => _trashUpdated!(right(error)), (error) => _trashUpdated!(FlowyResult.failure(error)),
); );
} }
break; break;

View File

@ -1,21 +1,22 @@
import 'dart:async'; import 'dart:async';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class TrashService { class TrashService {
Future<Either<RepeatedTrashPB, FlowyError>> readTrash() { Future<FlowyResult<RepeatedTrashPB, FlowyError>> readTrash() {
return FolderEventListTrashItems().send(); return FolderEventListTrashItems().send();
} }
Future<Either<Unit, FlowyError>> putback(String trashId) { Future<FlowyResult<void, FlowyError>> putback(String trashId) {
final id = TrashIdPB.create()..id = trashId; final id = TrashIdPB.create()..id = trashId;
return FolderEventRestoreTrashItem(id).send(); return FolderEventRestoreTrashItem(id).send();
} }
Future<Either<Unit, FlowyError>> deleteViews(List<String> trash) { Future<FlowyResult<void, FlowyError>> deleteViews(List<String> trash) {
final items = trash.map((trash) { final items = trash.map((trash) {
return TrashIdPB.create()..id = trash; return TrashIdPB.create()..id = trash;
}); });
@ -24,11 +25,11 @@ class TrashService {
return FolderEventPermanentlyDeleteTrashItem(ids).send(); return FolderEventPermanentlyDeleteTrashItem(ids).send();
} }
Future<Either<Unit, FlowyError>> restoreAll() { Future<FlowyResult<void, FlowyError>> restoreAll() {
return FolderEventRecoverAllTrashItems().send(); return FolderEventRecoverAllTrashItems().send();
} }
Future<Either<Unit, FlowyError>> deleteAll() { Future<FlowyResult<void, FlowyError>> deleteAll() {
return FolderEventPermanentlyDeleteAllTrashItem().send(); return FolderEventPermanentlyDeleteAllTrashItem().send();
} }
} }

View File

@ -1,18 +1,17 @@
import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_listener.dart'; import 'package:appflowy/workspace/application/view/view_listener.dart';
import 'package:dartz/dartz.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class ViewPluginNotifier extends PluginNotifier<Option<DeletedViewPB>> { class ViewPluginNotifier extends PluginNotifier<DeletedViewPB?> {
ViewPluginNotifier({ ViewPluginNotifier({
required this.view, required this.view,
}) : _viewListener = ViewListener(viewId: view.id) { }) : _viewListener = ViewListener(viewId: view.id) {
_viewListener?.start( _viewListener?.start(
onViewUpdated: (updatedView) => view = updatedView, onViewUpdated: (updatedView) => view = updatedView,
onViewMoveToTrash: (result) => result.fold( onViewMoveToTrash: (result) => result.fold(
(deletedView) => isDeleted.value = some(deletedView), (deletedView) => isDeleted.value = deletedView,
(err) => Log.error(err), (err) => Log.error(err),
), ),
); );
@ -22,7 +21,7 @@ class ViewPluginNotifier extends PluginNotifier<Option<DeletedViewPB>> {
final ViewListener? _viewListener; final ViewListener? _viewListener;
@override @override
final ValueNotifier<Option<DeletedViewPB>> isDeleted = ValueNotifier(none()); final ValueNotifier<DeletedViewPB?> isDeleted = ValueNotifier(null);
@override @override
void dispose() { void dispose() {

View File

@ -90,15 +90,15 @@ void _resolveCommonService(
() async { () async {
final result = await UserBackendService.getCurrentUserProfile(); final result = await UserBackendService.getCurrentUserProfile();
return result.fold( return result.fold(
(l) { (s) {
throw Exception('Failed to get user profile: ${l.msg}');
},
(r) {
return HttpOpenAIRepository( return HttpOpenAIRepository(
client: http.Client(), client: http.Client(),
apiKey: r.openaiKey, apiKey: s.openaiKey,
); );
}, },
(e) {
throw Exception('Failed to get user profile: ${e.msg}');
},
); );
}, },
); );
@ -107,15 +107,15 @@ void _resolveCommonService(
() async { () async {
final result = await UserBackendService.getCurrentUserProfile(); final result = await UserBackendService.getCurrentUserProfile();
return result.fold( return result.fold(
(l) { (s) {
throw Exception('Failed to get user profile: ${l.msg}');
},
(r) {
return HttpStabilityAIRepository( return HttpStabilityAIRepository(
client: http.Client(), client: http.Client(),
apiKey: r.stabilityAiKey, apiKey: s.stabilityAiKey,
); );
}, },
(e) {
throw Exception('Failed to get user profile: ${e.msg}');
},
); );
}, },
); );

View File

@ -32,7 +32,7 @@ class WindowSizeManager {
final defaultWindowSize = jsonEncode({height: 600.0, width: 800.0}); final defaultWindowSize = jsonEncode({height: 600.0, width: 800.0});
final windowSize = await getIt<KeyValueStorage>().get(KVKeys.windowSize); final windowSize = await getIt<KeyValueStorage>().get(KVKeys.windowSize);
final size = json.decode( final size = json.decode(
windowSize.getOrElse(() => defaultWindowSize), windowSize ?? defaultWindowSize,
); );
return Size(size[width]!, size[height]!); return Size(size[width]!, size[height]!);
} }
@ -49,12 +49,10 @@ class WindowSizeManager {
Future<Offset?> getPosition() async { Future<Offset?> getPosition() async {
final position = await getIt<KeyValueStorage>().get(KVKeys.windowPosition); final position = await getIt<KeyValueStorage>().get(KVKeys.windowPosition);
return position.fold( if (position == null) {
() => null, return null;
(r) { }
final offset = json.decode(r); final offset = json.decode(position);
return Offset(offset[dx], offset[dy]); return Offset(offset[dx], offset[dy]);
},
);
} }
} }

View File

@ -16,7 +16,7 @@ import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:url_protocol/url_protocol.dart'; import 'package:url_protocol/url_protocol.dart';
@ -29,7 +29,7 @@ class AppFlowyCloudDeepLink {
await _handleUri(uri); await _handleUri(uri);
}, },
onError: (Object err, StackTrace stackTrace) { onError: (Object err, StackTrace stackTrace) {
Log.error('on deeplink stream error: ${err.toString()}', stackTrace); Log.error('on DeepLink stream error: ${err.toString()}', stackTrace);
_deeplinkSubscription?.cancel(); _deeplinkSubscription?.cancel();
_deeplinkSubscription = null; _deeplinkSubscription = null;
}, },
@ -46,7 +46,7 @@ class AppFlowyCloudDeepLink {
final _appLinks = AppLinks(); final _appLinks = AppLinks();
ValueNotifier<DeepLinkResult?>? _stateNotifier = ValueNotifier(null); ValueNotifier<DeepLinkResult?>? _stateNotifier = ValueNotifier(null);
Completer<Either<FlowyError, UserProfilePB>>? _completer; Completer<FlowyResult<UserProfilePB, FlowyError>>? _completer;
// The AppLinks is a singleton, so we need to cancel the previous subscription // The AppLinks is a singleton, so we need to cancel the previous subscription
// before creating a new one. // before creating a new one.
@ -58,8 +58,8 @@ class AppFlowyCloudDeepLink {
_stateNotifier = null; _stateNotifier = null;
} }
void resigerCompleter( void registerCompleter(
Completer<Either<FlowyError, UserProfilePB>> completer, Completer<FlowyResult<UserProfilePB, FlowyError>> completer,
) { ) {
_completer = completer; _completer = completer;
} }
@ -86,11 +86,11 @@ class AppFlowyCloudDeepLink {
_stateNotifier?.value = DeepLinkResult(state: DeepLinkState.none); _stateNotifier?.value = DeepLinkResult(state: DeepLinkState.none);
if (uri == null) { if (uri == null) {
Log.error('onDeepLinkError: Unexpect empty deep link callback'); Log.error('onDeepLinkError: Unexpected empty deep link callback');
_completer?.complete(left(AuthError.emptyDeeplink)); _completer?.complete(FlowyResult.failure(AuthError.emptyDeepLink));
_completer = null; _completer = null;
} }
return _isAuthCallbackDeeplink(uri!).fold( return _isAuthCallbackDeepLink(uri!).fold(
(_) async { (_) async {
final deviceId = await getDeviceId(); final deviceId = await getDeviceId();
final payload = OauthSignInPB( final payload = OauthSignInPB(
@ -101,9 +101,8 @@ class AppFlowyCloudDeepLink {
}, },
); );
_stateNotifier?.value = DeepLinkResult(state: DeepLinkState.loading); _stateNotifier?.value = DeepLinkResult(state: DeepLinkState.loading);
final result = await UserEventOauthSignIn(payload) final result =
.send() await UserEventOauthSignIn(payload).send().then((value) => value);
.then((value) => value.swap());
_stateNotifier?.value = DeepLinkResult( _stateNotifier?.value = DeepLinkResult(
state: DeepLinkState.finish, state: DeepLinkState.finish,
@ -112,6 +111,9 @@ class AppFlowyCloudDeepLink {
// If there is no completer, runAppFlowy() will be called. // If there is no completer, runAppFlowy() will be called.
if (_completer == null) { if (_completer == null) {
await result.fold( await result.fold(
(_) async {
await runAppFlowy();
},
(err) { (err) {
Log.error(err); Log.error(err);
final context = AppGlobals.rootNavKey.currentState?.context; final context = AppGlobals.rootNavKey.currentState?.context;
@ -122,9 +124,6 @@ class AppFlowyCloudDeepLink {
); );
} }
}, },
(_) async {
await runAppFlowy();
},
); );
} else { } else {
_completer?.complete(result); _completer?.complete(result);
@ -132,7 +131,7 @@ class AppFlowyCloudDeepLink {
} }
}, },
(err) { (err) {
Log.error('onDeepLinkError: Unexpect deep link: $err'); Log.error('onDeepLinkError: Unexpected deep link: $err');
if (_completer == null) { if (_completer == null) {
final context = AppGlobals.rootNavKey.currentState?.context; final context = AppGlobals.rootNavKey.currentState?.context;
if (context != null) { if (context != null) {
@ -142,19 +141,19 @@ class AppFlowyCloudDeepLink {
); );
} }
} else { } else {
_completer?.complete(left(err)); _completer?.complete(FlowyResult.failure(err));
_completer = null; _completer = null;
} }
}, },
); );
} }
Either<(), FlowyError> _isAuthCallbackDeeplink(Uri uri) { FlowyResult<void, FlowyError> _isAuthCallbackDeepLink(Uri uri) {
if (uri.fragment.contains('access_token')) { if (uri.fragment.contains('access_token')) {
return left(()); return FlowyResult.success(null);
} }
return right( return FlowyResult.failure(
FlowyError.create() FlowyError.create()
..code = ErrorCode.MissingAuthField ..code = ErrorCode.MissingAuthField
..msg = uri.path, ..msg = uri.path,
@ -197,7 +196,7 @@ class DeepLinkResult {
DeepLinkResult({required this.state, this.result}); DeepLinkResult({required this.state, this.result});
final DeepLinkState state; final DeepLinkState state;
final Either<FlowyError, UserProfilePB>? result; final FlowyResult<UserProfilePB, FlowyError>? result;
} }
enum DeepLinkState { enum DeepLinkState {

View File

@ -580,8 +580,8 @@ GoRoute _rootRoute(Widget child) {
// Every time before navigating to splash screen, we check if user is already logged in in desktop. It is used to skip showing splash screen when user just changes apperance settings like theme mode. // Every time before navigating to splash screen, we check if user is already logged in in desktop. It is used to skip showing splash screen when user just changes apperance settings like theme mode.
final userResponse = await getIt<AuthService>().getUser(); final userResponse = await getIt<AuthService>().getUser();
final routeName = userResponse.fold( final routeName = userResponse.fold(
(error) => null,
(user) => DesktopHomeScreen.routeName, (user) => DesktopHomeScreen.routeName,
(error) => null,
); );
if (routeName != null && !PlatformExtension.isMobile) return routeName; if (routeName != null && !PlatformExtension.isMobile) return routeName;

View File

@ -2,13 +2,13 @@ import 'dart:async';
import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/startup/tasks/appflowy_cloud_task.dart'; import 'package:appflowy/startup/tasks/appflowy_cloud_task.dart';
import 'package:appflowy/user/application/auth/backend_auth_service.dart';
import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/application/auth/backend_auth_service.dart';
import 'package:appflowy/user/application/user_service.dart'; import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import 'auth_error.dart'; import 'auth_error.dart';
@ -21,7 +21,7 @@ class AppFlowyCloudAuthService implements AuthService {
); );
@override @override
Future<Either<FlowyError, UserProfilePB>> signUp({ Future<FlowyResult<UserProfilePB, FlowyError>> signUp({
required String name, required String name,
required String email, required String email,
required String password, required String password,
@ -31,7 +31,7 @@ class AppFlowyCloudAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signInWithEmailPassword({ Future<FlowyResult<UserProfilePB, FlowyError>> signInWithEmailPassword({
required String email, required String email,
required String password, required String password,
Map<String, String> params = const {}, Map<String, String> params = const {},
@ -40,7 +40,7 @@ class AppFlowyCloudAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signUpWithOAuth({ Future<FlowyResult<UserProfilePB, FlowyError>> signUpWithOAuth({
required String platform, required String platform,
Map<String, String> params = const {}, Map<String, String> params = const {},
}) async { }) async {
@ -61,22 +61,23 @@ class AppFlowyCloudAuthService implements AuthService {
webOnlyWindowName: '_self', webOnlyWindowName: '_self',
); );
final completer = Completer<Either<FlowyError, UserProfilePB>>(); final completer = Completer<FlowyResult<UserProfilePB, FlowyError>>();
if (isSuccess) { if (isSuccess) {
// The [AppFlowyCloudDeepLink] must be registered before using the // The [AppFlowyCloudDeepLink] must be registered before using the
// [AppFlowyCloudAuthService]. // [AppFlowyCloudAuthService].
if (getIt.isRegistered<AppFlowyCloudDeepLink>()) { if (getIt.isRegistered<AppFlowyCloudDeepLink>()) {
getIt<AppFlowyCloudDeepLink>().resigerCompleter(completer); getIt<AppFlowyCloudDeepLink>().registerCompleter(completer);
} else { } else {
throw Exception('AppFlowyCloudDeepLink is not registered'); throw Exception('AppFlowyCloudDeepLink is not registered');
} }
} else { } else {
completer.complete(left(AuthError.signInWithOauthError)); completer
.complete(FlowyResult.failure(AuthError.signInWithOauthError));
} }
return completer.future; return completer.future;
}, },
(r) => left(r), (r) => FlowyResult.failure(r),
); );
} }
@ -86,14 +87,14 @@ class AppFlowyCloudAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signUpAsGuest({ Future<FlowyResult<UserProfilePB, FlowyError>> signUpAsGuest({
Map<String, String> params = const {}, Map<String, String> params = const {},
}) async { }) async {
return _backendAuthService.signUpAsGuest(); return _backendAuthService.signUpAsGuest();
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signInWithMagicLink({ Future<FlowyResult<UserProfilePB, FlowyError>> signInWithMagicLink({
required String email, required String email,
Map<String, String> params = const {}, Map<String, String> params = const {},
}) async { }) async {
@ -101,7 +102,7 @@ class AppFlowyCloudAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> getUser() async { Future<FlowyResult<UserProfilePB, FlowyError>> getUser() async {
return UserBackendService.getCurrentUserProfile(); return UserBackendService.getCurrentUserProfile();
} }
} }

View File

@ -1,14 +1,14 @@
import 'dart:async'; import 'dart:async';
import 'package:appflowy/user/application/auth/backend_auth_service.dart';
import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/application/auth/backend_auth_service.dart';
import 'package:appflowy/user/application/auth/device_id.dart'; import 'package:appflowy/user/application/auth/device_id.dart';
import 'package:appflowy/user/application/user_service.dart'; import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:dartz/dartz.dart'; import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/uuid.dart'; import 'package:flowy_infra/uuid.dart';
/// Only used for testing. /// Only used for testing.
@ -22,7 +22,7 @@ class AppFlowyCloudMockAuthService implements AuthService {
BackendAuthService(AuthenticatorPB.Supabase); BackendAuthService(AuthenticatorPB.Supabase);
@override @override
Future<Either<FlowyError, UserProfilePB>> signUp({ Future<FlowyResult<UserProfilePB, FlowyError>> signUp({
required String name, required String name,
required String email, required String email,
required String password, required String password,
@ -32,7 +32,7 @@ class AppFlowyCloudMockAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signInWithEmailPassword({ Future<FlowyResult<UserProfilePB, FlowyError>> signInWithEmailPassword({
required String email, required String email,
required String password, required String password,
Map<String, String> params = const {}, Map<String, String> params = const {},
@ -41,7 +41,7 @@ class AppFlowyCloudMockAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signUpWithOAuth({ Future<FlowyResult<UserProfilePB, FlowyError>> signUpWithOAuth({
required String platform, required String platform,
Map<String, String> params = const {}, Map<String, String> params = const {},
}) async { }) async {
@ -65,12 +65,12 @@ class AppFlowyCloudMockAuthService implements AuthService {
Log.info("UserEventOauthSignIn with payload: $payload"); Log.info("UserEventOauthSignIn with payload: $payload");
return UserEventOauthSignIn(payload).send().then((value) { return UserEventOauthSignIn(payload).send().then((value) {
value.fold((l) => null, (err) => Log.error(err)); value.fold((l) => null, (err) => Log.error(err));
return value.swap(); return value;
}); });
}, },
(r) { (r) {
Log.error(r); Log.error(r);
return left(r); return FlowyResult.failure(r);
}, },
); );
} }
@ -81,14 +81,14 @@ class AppFlowyCloudMockAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signUpAsGuest({ Future<FlowyResult<UserProfilePB, FlowyError>> signUpAsGuest({
Map<String, String> params = const {}, Map<String, String> params = const {},
}) async { }) async {
return _appFlowyAuthService.signUpAsGuest(); return _appFlowyAuthService.signUpAsGuest();
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> signInWithMagicLink({ Future<FlowyResult<UserProfilePB, FlowyError>> signInWithMagicLink({
required String email, required String email,
Map<String, String> params = const {}, Map<String, String> params = const {},
}) async { }) async {
@ -96,7 +96,7 @@ class AppFlowyCloudMockAuthService implements AuthService {
} }
@override @override
Future<Either<FlowyError, UserProfilePB>> getUser() async { Future<FlowyResult<UserProfilePB, FlowyError>> getUser() async {
return UserBackendService.getCurrentUserProfile(); return UserBackendService.getCurrentUserProfile();
} }
} }

Some files were not shown because too many files have changed in this diff Show More