repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/notifications
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/notifications/widgets/mobile_notification_tab_bar.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/workspace/presentation/notifications/widgets/flowy_tab.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/theme_extension.dart'; import 'package:flutter/material.dart'; class MobileNotificationTabBar extends StatefulWidget { const MobileNotificationTabBar({super.key, required this.controller}); final TabController controller; @override State<MobileNotificationTabBar> createState() => _MobileNotificationTabBarState(); } class _MobileNotificationTabBarState extends State<MobileNotificationTabBar> { @override void initState() { super.initState(); widget.controller.addListener(_updateState); } void _updateState() => setState(() {}); @override Widget build(BuildContext context) { final borderSide = BorderSide( color: AFThemeExtension.of(context).calloutBGColor, ); return DecoratedBox( decoration: BoxDecoration( border: Border( bottom: borderSide, top: borderSide, ), ), child: Row( children: [ Expanded( child: TabBar( controller: widget.controller, padding: const EdgeInsets.symmetric(horizontal: 8), labelPadding: EdgeInsets.zero, indicatorSize: TabBarIndicatorSize.label, indicator: UnderlineTabIndicator( borderSide: BorderSide( color: Theme.of(context).colorScheme.primary, ), ), isScrollable: true, tabs: [ FlowyTabItem( label: LocaleKeys.notificationHub_tabs_inbox.tr(), isSelected: widget.controller.index == 0, ), FlowyTabItem( label: LocaleKeys.notificationHub_tabs_upcoming.tr(), isSelected: widget.controller.index == 1, ), ], ), ), ], ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/user_session_setting_group.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/widgets/show_flowy_mobile_confirm_dialog.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/auth_service.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/widgets.dart'; import 'package:appflowy_backend/log.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class UserSessionSettingGroup extends StatelessWidget { const UserSessionSettingGroup({ super.key, required this.showThirdPartyLogin, }); final bool showThirdPartyLogin; @override Widget build(BuildContext context) { return Column( children: [ if (showThirdPartyLogin) ...[ BlocProvider( create: (context) => getIt<SignInBloc>(), child: BlocConsumer<SignInBloc, SignInState>( listener: (context, state) { state.successOrFail?.fold( (result) => runAppFlowy(), (e) => Log.error(e), ); }, builder: (context, state) { return const ThirdPartySignInButtons(); }, ), ), const VSpace(8), ], MobileSignInOrLogoutButton( labelText: LocaleKeys.settings_menu_logout.tr(), onPressed: () async { await showFlowyMobileConfirmDialog( context, content: FlowyText( LocaleKeys.settings_menu_logoutPrompt.tr(), ), actionButtonTitle: LocaleKeys.button_yes.tr(), actionButtonColor: Theme.of(context).colorScheme.error, onActionButtonPressed: () async { await getIt<AuthService>().signOut(); await runAppFlowy(); }, ); }, ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/language_setting_group.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/setting/language/language_picker_screen.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/language.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'setting.dart'; class LanguageSettingGroup extends StatefulWidget { const LanguageSettingGroup({ super.key, }); @override State<LanguageSettingGroup> createState() => _LanguageSettingGroupState(); } class _LanguageSettingGroupState extends State<LanguageSettingGroup> { @override Widget build(BuildContext context) { return BlocSelector<AppearanceSettingsCubit, AppearanceSettingsState, Locale>( selector: (state) { return state.locale; }, builder: (context, locale) { final theme = Theme.of(context); return MobileSettingGroup( groupTitle: LocaleKeys.settings_menu_language.tr(), settingItemList: [ MobileSettingItem( name: LocaleKeys.settings_menu_language.tr(), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ FlowyText( languageFromLocale(locale), color: theme.colorScheme.onSurface, ), const Icon(Icons.chevron_right), ], ), onTap: () async { final newLocale = await context.push<Locale>(LanguagePickerScreen.routeName); if (newLocale != null && newLocale != locale) { if (context.mounted) { context .read<AppearanceSettingsCubit>() .setLocale(context, newLocale); } } }, ), ], ); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/self_host_setting_group.dart
import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/setting/self_host/self_host_bottom_sheet.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'setting.dart'; class SelfHostSettingGroup extends StatefulWidget { const SelfHostSettingGroup({ super.key, }); @override State<SelfHostSettingGroup> createState() => _SelfHostSettingGroupState(); } class _SelfHostSettingGroupState extends State<SelfHostSettingGroup> { final future = getAppFlowyCloudUrl(); @override Widget build(BuildContext context) { return FutureBuilder( future: future, builder: (context, snapshot) { if (!snapshot.hasData) { return const SizedBox.shrink(); } final url = snapshot.data ?? ''; return MobileSettingGroup( groupTitle: LocaleKeys.settings_menu_cloudAppFlowySelfHost.tr(), settingItemList: [ MobileSettingItem( name: url, onTap: () { showMobileBottomSheet( context, showHeader: true, title: LocaleKeys.editor_urlHint.tr(), showCloseButton: true, showDivider: false, padding: const EdgeInsets.symmetric( horizontal: 16.0, vertical: 8.0, ), builder: (_) { return SelfHostUrlBottomSheet( url: url, ); }, ); }, ), ], ); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/support_setting_group.dart
import 'dart:io'; import 'package:appflowy/core/helpers/url_launcher.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/show_mobile_bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/shared/appflowy_cache_manager.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/util/share_log_files.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'widgets/widgets.dart'; class SupportSettingGroup extends StatelessWidget { const SupportSettingGroup({ super.key, }); @override Widget build(BuildContext context) { return FutureBuilder( future: PackageInfo.fromPlatform(), builder: (context, snapshot) => MobileSettingGroup( groupTitle: LocaleKeys.settings_mobile_support.tr(), settingItemList: [ MobileSettingItem( name: LocaleKeys.settings_mobile_joinDiscord.tr(), trailing: const Icon( Icons.chevron_right, ), onTap: () => afLaunchUrlString('https://discord.gg/JucBXeU2FE'), ), MobileSettingItem( name: LocaleKeys.workspace_errorActions_reportIssue.tr(), trailing: const Icon( Icons.chevron_right, ), onTap: () { showMobileBottomSheet( context, showDragHandle: true, showHeader: true, title: LocaleKeys.workspace_errorActions_reportIssue.tr(), backgroundColor: Theme.of(context).colorScheme.surface, builder: (context) { return _ReportIssuesWidget( version: snapshot.data?.version ?? '', ); }, ); }, ), MobileSettingItem( name: LocaleKeys.settings_files_clearCache.tr(), trailing: const Icon( Icons.chevron_right, ), onTap: () async { await showFlowyMobileConfirmDialog( context, title: FlowyText( LocaleKeys.settings_files_areYouSureToClearCache.tr(), maxLines: 2, ), content: FlowyText( LocaleKeys.settings_files_clearCacheDesc.tr(), fontSize: 12, maxLines: 4, ), actionButtonTitle: LocaleKeys.button_yes.tr(), onActionButtonPressed: () async { await getIt<FlowyCacheManager>().clearAllCache(); if (context.mounted) { showSnackBarMessage( context, LocaleKeys.settings_files_clearCacheSuccess.tr(), ); } }, ); }, ), ], ), ); } } class _ReportIssuesWidget extends StatelessWidget { const _ReportIssuesWidget({ required this.version, }); final String version; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ FlowyOptionTile.text( showTopBorder: false, text: LocaleKeys.workspace_errorActions_reportIssueOnGithub.tr(), onTap: () { final String os = Platform.operatingSystem; afLaunchUrlString( 'https://github.com/AppFlowy-IO/AppFlowy/issues/new?assignees=&labels=&projects=&template=bug_report.yaml&title=[Bug]%20Mobile:%20&version=$version&os=$os', ); }, ), FlowyOptionTile.text( showTopBorder: false, text: LocaleKeys.workspace_errorActions_exportLogFiles.tr(), onTap: () => shareLogFiles(context), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/notifications_setting_group.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'widgets/widgets.dart'; class NotificationsSettingGroup extends StatefulWidget { const NotificationsSettingGroup({super.key}); @override State<NotificationsSettingGroup> createState() => _NotificationsSettingGroupState(); } class _NotificationsSettingGroupState extends State<NotificationsSettingGroup> { bool isPushNotificationOn = false; @override Widget build(BuildContext context) { final theme = Theme.of(context); return MobileSettingGroup( groupTitle: LocaleKeys.notificationHub_title.tr(), settingItemList: [ MobileSettingItem( name: LocaleKeys.settings_mobile_pushNotifications.tr(), trailing: Switch.adaptive( activeColor: theme.colorScheme.primary, value: isPushNotificationOn, onChanged: (bool value) { setState(() { isPushNotificationOn = value; }); }, ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/launch_settings_page.dart
import 'package:appflowy/env/env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/mobile/presentation/presentation.dart'; import 'package:appflowy/mobile/presentation/setting/self_host_setting_group.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MobileLaunchSettingsPage extends StatelessWidget { const MobileLaunchSettingsPage({ super.key, }); static const routeName = '/launch_settings'; @override Widget build(BuildContext context) { context.watch<AppearanceSettingsCubit>(); return Scaffold( appBar: FlowyAppBar( titleText: LocaleKeys.settings_title.tr(), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ const LanguageSettingGroup(), if (Env.enableCustomCloud) const SelfHostSettingGroup(), const SupportSettingGroup(), ], ), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/setting.dart
export 'about/about.dart'; export 'appearance/appearance_setting_group.dart'; export 'font/font_setting.dart'; export 'language_setting_group.dart'; export 'notifications_setting_group.dart'; export 'personal_info/personal_info.dart'; export 'support_setting_group.dart'; export 'widgets/widgets.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/widgets/widgets.dart
export 'mobile_setting_group_widget.dart'; export 'mobile_setting_item_widget.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/widgets/mobile_setting_item_widget.dart
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class MobileSettingItem extends StatelessWidget { const MobileSettingItem({ super.key, required this.name, this.padding = const EdgeInsets.only(bottom: 4), this.trailing, this.leadingIcon, this.subtitle, this.onTap, }); final String name; final EdgeInsets padding; final Widget? trailing; final Widget? leadingIcon; final Widget? subtitle; final VoidCallback? onTap; @override Widget build(BuildContext context) { return Padding( padding: padding, child: ListTile( title: Row( children: [ if (leadingIcon != null) ...[ leadingIcon!, const HSpace(8), ], Expanded( child: FlowyText.medium( name, fontSize: 14.0, overflow: TextOverflow.ellipsis, ), ), ], ), subtitle: subtitle, trailing: trailing, onTap: onTap, visualDensity: VisualDensity.compact, contentPadding: const EdgeInsets.only(left: 8.0), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/widgets/mobile_setting_group_widget.dart
import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class MobileSettingGroup extends StatelessWidget { const MobileSettingGroup({ required this.groupTitle, required this.settingItemList, this.showDivider = true, super.key, }); final String groupTitle; final List<Widget> settingItemList; final bool showDivider; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const VSpace(4.0), FlowyText.semibold( groupTitle, ), const VSpace(4.0), ...settingItemList, showDivider ? const Divider() : const SizedBox.shrink(), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/font/font_picker_screen.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_search_text_field.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/util/google_font_family_extension.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; final List<String> _availableFonts = GoogleFonts.asMap().keys.toList(); class FontPickerScreen extends StatelessWidget { const FontPickerScreen({super.key}); static const routeName = '/font_picker'; @override Widget build(BuildContext context) { return const LanguagePickerPage(); } } class LanguagePickerPage extends StatefulWidget { const LanguagePickerPage({super.key}); @override State<LanguagePickerPage> createState() => _LanguagePickerPageState(); } class _LanguagePickerPageState extends State<LanguagePickerPage> { late List<String> availableFonts; @override void initState() { super.initState(); availableFonts = _availableFonts; } @override Widget build(BuildContext context) { final selectedFontFamilyName = context.watch<AppearanceSettingsCubit>().state.font; return Scaffold( appBar: FlowyAppBar( titleText: LocaleKeys.titleBar_font.tr(), ), body: SafeArea( child: Scrollbar( child: ListView.builder( itemCount: availableFonts.length + 1, // with search bar itemBuilder: (context, index) { if (index == 0) { // search bar return Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 12.0, ), child: FlowyMobileSearchTextField( onChanged: (keyword) { setState(() { availableFonts = _availableFonts .where( (font) => font .parseFontFamilyName() .toLowerCase() .contains(keyword.toLowerCase()), ) .toList(); }); }, ), ); } final fontFamilyName = availableFonts[index - 1]; final displayName = fontFamilyName.parseFontFamilyName(); return FlowyOptionTile.checkbox( text: displayName, isSelected: selectedFontFamilyName == fontFamilyName, showTopBorder: false, onTap: () => context.pop(fontFamilyName), fontFamily: GoogleFonts.getFont(fontFamilyName).fontFamily, backgroundColor: Colors.transparent, ); }, ), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/font/font_setting.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/setting/font/font_picker_screen.dart'; import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; import '../setting.dart'; class FontSetting extends StatelessWidget { const FontSetting({ super.key, }); @override Widget build(BuildContext context) { final theme = Theme.of(context); final selectedFont = context.watch<AppearanceSettingsCubit>().state.font; return MobileSettingItem( name: LocaleKeys.settings_appearance_fontFamily_label.tr(), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ FlowyText( selectedFont, fontFamily: GoogleFonts.getFont(selectedFont).fontFamily, color: theme.colorScheme.onSurface, ), const Icon(Icons.chevron_right), ], ), onTap: () async { final newFont = await context.push<String>(FontPickerScreen.routeName); if (newFont != null && newFont != selectedFont) { if (context.mounted) { context.read<AppearanceSettingsCubit>().setFontFamily(newFont); unawaited( context.read<DocumentAppearanceCubit>().syncFontFamily(newFont), ); } } }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/language/language_picker_screen.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/language.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class LanguagePickerScreen extends StatelessWidget { const LanguagePickerScreen({super.key}); static const routeName = '/language_picker'; @override Widget build(BuildContext context) => const LanguagePickerPage(); } class LanguagePickerPage extends StatefulWidget { const LanguagePickerPage({ super.key, }); @override State<LanguagePickerPage> createState() => _LanguagePickerPageState(); } class _LanguagePickerPageState extends State<LanguagePickerPage> { @override Widget build(BuildContext context) { final supportedLocales = EasyLocalization.of(context)!.supportedLocales; return Scaffold( appBar: FlowyAppBar( titleText: LocaleKeys.titleBar_language.tr(), ), body: SafeArea( child: ListView.builder( itemBuilder: (context, index) { final locale = supportedLocales[index]; return FlowyOptionTile.checkbox( text: languageFromLocale(locale), isSelected: EasyLocalization.of(context)!.locale == locale, showTopBorder: false, onTap: () => context.pop(locale), backgroundColor: Colors.transparent, ); }, itemCount: supportedLocales.length, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/appearance/theme_setting.dart
import 'package:appflowy/generated/flowy_svgs.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/widgets/widgets.dart'; import 'package:appflowy/util/theme_mode_extension.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../setting.dart'; class ThemeSetting extends StatelessWidget { const ThemeSetting({ super.key, }); @override Widget build(BuildContext context) { final theme = Theme.of(context); final themeMode = context.watch<AppearanceSettingsCubit>().state.themeMode; return MobileSettingItem( name: LocaleKeys.settings_appearance_themeMode_label.tr(), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ FlowyText( themeMode.labelText, color: theme.colorScheme.onSurface, ), const Icon(Icons.chevron_right), ], ), onTap: () { showMobileBottomSheet( context, showHeader: true, showDragHandle: true, showDivider: false, showCloseButton: false, title: LocaleKeys.settings_appearance_themeMode_label.tr(), builder: (context) { final themeMode = context.read<AppearanceSettingsCubit>().state.themeMode; return Column( children: [ FlowyOptionTile.checkbox( text: LocaleKeys.settings_appearance_themeMode_system.tr(), leftIcon: const FlowySvg( FlowySvgs.m_theme_mode_system_s, ), isSelected: themeMode == ThemeMode.system, onTap: () { context .read<AppearanceSettingsCubit>() .setThemeMode(ThemeMode.system); Navigator.pop(context); }, ), FlowyOptionTile.checkbox( showTopBorder: false, text: LocaleKeys.settings_appearance_themeMode_light.tr(), leftIcon: const FlowySvg( FlowySvgs.m_theme_mode_light_s, ), isSelected: themeMode == ThemeMode.light, onTap: () { context .read<AppearanceSettingsCubit>() .setThemeMode(ThemeMode.light); Navigator.pop(context); }, ), FlowyOptionTile.checkbox( showTopBorder: false, text: LocaleKeys.settings_appearance_themeMode_dark.tr(), leftIcon: const FlowySvg( FlowySvgs.m_theme_mode_dark_s, ), isSelected: themeMode == ThemeMode.dark, onTap: () { context .read<AppearanceSettingsCubit>() .setThemeMode(ThemeMode.dark); Navigator.pop(context); }, ), ], ); }, ); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/appearance/text_scale_setting.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:appflowy/workspace/presentation/widgets/more_view_actions/widgets/font_size_stepper.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../setting.dart'; const int _divisions = 4; class TextScaleSetting extends StatelessWidget { const TextScaleSetting({ super.key, }); @override Widget build(BuildContext context) { final theme = Theme.of(context); final textScaleFactor = context.watch<AppearanceSettingsCubit>().state.textScaleFactor; return MobileSettingItem( name: LocaleKeys.settings_appearance_fontScaleFactor.tr(), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ FlowyText( // map the text scale factor to the 0-1 // 0.8 - 0.0 // 0.9 - 0.5 // 1.0 - 1.0 ((_divisions + 1) * textScaleFactor - _divisions) .toStringAsFixed(2), color: theme.colorScheme.onSurface, ), const Icon(Icons.chevron_right), ], ), onTap: () { showMobileBottomSheet( context, showHeader: true, showDragHandle: true, showDivider: false, showCloseButton: false, title: LocaleKeys.settings_appearance_fontScaleFactor.tr(), builder: (context) { return FontSizeStepper( value: textScaleFactor, minimumValue: 0.8, maximumValue: 1.0, divisions: _divisions, onChanged: (newTextScaleFactor) { context .read<AppearanceSettingsCubit>() .setTextScaleFactor(newTextScaleFactor); }, ); }, ); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/appearance/rtl_setting.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../setting.dart'; class RTLSetting extends StatelessWidget { const RTLSetting({ super.key, }); @override Widget build(BuildContext context) { final theme = Theme.of(context); final layoutDirection = context.watch<AppearanceSettingsCubit>().state.layoutDirection; return MobileSettingItem( name: LocaleKeys.settings_appearance_textDirection_label.tr(), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ FlowyText( _textDirectionLabelText(layoutDirection), color: theme.colorScheme.onSurface, ), const Icon(Icons.chevron_right), ], ), onTap: () { showMobileBottomSheet( context, showHeader: true, showDragHandle: true, showDivider: false, showCloseButton: false, title: LocaleKeys.settings_appearance_textDirection_label.tr(), builder: (context) { final layoutDirection = context.watch<AppearanceSettingsCubit>().state.layoutDirection; return Column( children: [ FlowyOptionTile.checkbox( text: LocaleKeys.settings_appearance_textDirection_ltr.tr(), isSelected: layoutDirection == LayoutDirection.ltrLayout, onTap: () { context .read<AppearanceSettingsCubit>() .setLayoutDirection(LayoutDirection.ltrLayout); Navigator.pop(context); }, ), FlowyOptionTile.checkbox( showTopBorder: false, text: LocaleKeys.settings_appearance_textDirection_rtl.tr(), isSelected: layoutDirection == LayoutDirection.rtlLayout, onTap: () { context .read<AppearanceSettingsCubit>() .setLayoutDirection(LayoutDirection.rtlLayout); Navigator.pop(context); }, ), ], ); }, ); }, ); } String _textDirectionLabelText(LayoutDirection? textDirection) { switch (textDirection) { case LayoutDirection.rtlLayout: return LocaleKeys.settings_appearance_textDirection_rtl.tr(); case LayoutDirection.ltrLayout: default: return LocaleKeys.settings_appearance_textDirection_ltr.tr(); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/appearance/appearance_setting_group.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/setting/appearance/rtl_setting.dart'; import 'package:appflowy/mobile/presentation/setting/appearance/text_scale_setting.dart'; import 'package:appflowy/mobile/presentation/setting/appearance/theme_setting.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../setting.dart'; class AppearanceSettingGroup extends StatelessWidget { const AppearanceSettingGroup({ super.key, }); @override Widget build(BuildContext context) { return MobileSettingGroup( groupTitle: LocaleKeys.settings_menu_appearance.tr(), settingItemList: const [ ThemeSetting(), FontSetting(), TextScaleSetting(), RTLSetting(), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/about/about_setting_group.dart
import 'package:appflowy/core/helpers/url_launcher.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/tasks/device_info_task.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/feature_flags/mobile_feature_flag_screen.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import '../widgets/widgets.dart'; class AboutSettingGroup extends StatelessWidget { const AboutSettingGroup({ super.key, }); @override Widget build(BuildContext context) { return MobileSettingGroup( groupTitle: LocaleKeys.settings_mobile_about.tr(), settingItemList: [ MobileSettingItem( name: LocaleKeys.settings_mobile_privacyPolicy.tr(), trailing: const Icon( Icons.chevron_right, ), onTap: () => afLaunchUrlString('https://appflowy.io/privacy/app'), ), MobileSettingItem( name: LocaleKeys.settings_mobile_termsAndConditions.tr(), trailing: const Icon( Icons.chevron_right, ), onTap: () => afLaunchUrlString('https://appflowy.io/terms/app'), ), if (kDebugMode) MobileSettingItem( name: 'Feature Flags', trailing: const Icon( Icons.chevron_right, ), onTap: () { context.push(FeatureFlagScreen.routeName); }, ), MobileSettingItem( name: LocaleKeys.settings_mobile_version.tr(), trailing: FlowyText( '${ApplicationInfo.applicationVersion} (${ApplicationInfo.buildNumber})', color: Theme.of(context).colorScheme.onSurface, ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/about/about.dart
export 'about_setting_group.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/self_host/self_host_bottom_sheet.dart
import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/settings/appflowy_cloud_urls_bloc.dart'; import 'package:appflowy_backend/log.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; class SelfHostUrlBottomSheet extends StatefulWidget { const SelfHostUrlBottomSheet({ super.key, required this.url, }); final String url; @override State<SelfHostUrlBottomSheet> createState() => _SelfHostUrlBottomSheetState(); } class _SelfHostUrlBottomSheetState extends State<SelfHostUrlBottomSheet> { final TextEditingController _textFieldController = TextEditingController(); final _formKey = GlobalKey<FormState>(); @override void initState() { super.initState(); _textFieldController.text = widget.url; } @override void dispose() { _textFieldController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Form( key: _formKey, child: TextFormField( controller: _textFieldController, keyboardType: TextInputType.text, validator: (value) { if (value == null || value.isEmpty) { return LocaleKeys.settings_mobile_usernameEmptyError.tr(); } return null; }, onEditingComplete: _saveSelfHostUrl, ), ), const SizedBox( height: 16, ), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: _saveSelfHostUrl, child: Text(LocaleKeys.settings_menu_restartApp.tr()), ), ), ], ); } void _saveSelfHostUrl() { if (_formKey.currentState!.validate()) { final value = _textFieldController.text; if (value.isNotEmpty) { validateUrl(value).fold( (url) async { await useSelfHostedAppFlowyCloudWithURL(url); await runAppFlowy(); }, (err) => Log.error(err), ); } } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/personal_info/edit_username_bottom_sheet.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class EditUsernameBottomSheet extends StatefulWidget { const EditUsernameBottomSheet( this.context, { this.userName, required this.onSubmitted, super.key, }); final BuildContext context; final String? userName; final void Function(String) onSubmitted; @override State<EditUsernameBottomSheet> createState() => _EditUsernameBottomSheetState(); } class _EditUsernameBottomSheetState extends State<EditUsernameBottomSheet> { late TextEditingController _textFieldController; final _formKey = GlobalKey<FormState>(); @override void initState() { super.initState(); _textFieldController = TextEditingController(text: widget.userName); } @override void dispose() { _textFieldController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { void submitUserName() { if (_formKey.currentState!.validate()) { final value = _textFieldController.text; widget.onSubmitted.call(value); widget.context.pop(); } } return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Form( key: _formKey, child: TextFormField( controller: _textFieldController, keyboardType: TextInputType.text, validator: (value) { if (value == null || value.isEmpty) { return LocaleKeys.settings_mobile_usernameEmptyError.tr(); } return null; }, onEditingComplete: submitUserName, ), ), const VSpace(16), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: submitUserName, child: Text(LocaleKeys.button_update.tr()), ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/personal_info/personal_info_setting_group.dart
import 'package:flutter/material.dart'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/user/prelude.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../widgets/widgets.dart'; import 'personal_info.dart'; class PersonalInfoSettingGroup extends StatelessWidget { const PersonalInfoSettingGroup({ super.key, required this.userProfile, }); final UserProfilePB userProfile; @override Widget build(BuildContext context) { final theme = Theme.of(context); return BlocProvider<SettingsUserViewBloc>( create: (context) => getIt<SettingsUserViewBloc>( param1: userProfile, )..add(const SettingsUserEvent.initial()), child: BlocSelector<SettingsUserViewBloc, SettingsUserState, String>( selector: (state) => state.userProfile.name, builder: (context, userName) { return MobileSettingGroup( groupTitle: LocaleKeys.settings_mobile_personalInfo.tr(), settingItemList: [ MobileSettingItem( name: userName, subtitle: isAuthEnabled && userProfile.email.isNotEmpty ? Text( userProfile.email, style: theme.textTheme.bodyMedium?.copyWith( color: theme.colorScheme.onSurface, ), ) : null, trailing: const Icon(Icons.chevron_right), onTap: () { showMobileBottomSheet( context, showHeader: true, title: LocaleKeys.settings_mobile_username.tr(), showCloseButton: true, showDragHandle: true, showDivider: false, padding: const EdgeInsets.symmetric(horizontal: 16), builder: (_) { return EditUsernameBottomSheet( context, userName: userName, onSubmitted: (value) => context .read<SettingsUserViewBloc>() .add(SettingsUserEvent.updateUserName(value)), ); }, ); }, ), ], ); }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/personal_info/personal_info.dart
export 'edit_username_bottom_sheet.dart'; export 'personal_info_setting_group.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/cloud/cloud_setting_group.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/setting/cloud/appflowy_cloud_page.dart'; import 'package:appflowy/mobile/presentation/setting/widgets/mobile_setting_group_widget.dart'; import 'package:appflowy/mobile/presentation/setting/widgets/mobile_setting_item_widget.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:package_info_plus/package_info_plus.dart'; class CloudSettingGroup extends StatelessWidget { const CloudSettingGroup({ super.key, }); @override Widget build(BuildContext context) { return FutureBuilder( future: PackageInfo.fromPlatform(), builder: (context, snapshot) => MobileSettingGroup( groupTitle: LocaleKeys.settings_menu_cloudSettings.tr(), settingItemList: [ MobileSettingItem( name: LocaleKeys.settings_menu_cloudAppFlowy.tr(), trailing: const Icon( Icons.chevron_right, ), onTap: () => context.push(AppFlowyCloudPage.routeName), ), ], ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/setting/cloud/appflowy_cloud_page.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_cloud.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; class AppFlowyCloudPage extends StatelessWidget { const AppFlowyCloudPage({super.key}); static const routeName = '/AppFlowyCloudPage'; @override Widget build(BuildContext context) { return Scaffold( appBar: FlowyAppBar( titleText: LocaleKeys.settings_menu_cloudSettings.tr(), ), body: Padding( padding: const EdgeInsets.all(20.0), child: SettingCloud( restartAppFlowy: () async { await runAppFlowy(); }, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/page_item/mobile_slide_action_button.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; class MobileSlideActionButton extends StatelessWidget { const MobileSlideActionButton({ super.key, required this.svg, this.size = 32.0, this.backgroundColor = Colors.transparent, required this.onPressed, }); final FlowySvgData svg; final double size; final Color backgroundColor; final SlidableActionCallback onPressed; @override Widget build(BuildContext context) { return CustomSlidableAction( backgroundColor: backgroundColor, onPressed: (context) { HapticFeedback.mediumImpact(); onPressed(context); }, child: FlowySvg( svg, size: Size.square(size), color: Colors.white, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/page_item/mobile_view_item_add_button.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; const _iconSize = 32.0; class MobileViewAddButton extends StatelessWidget { const MobileViewAddButton({ super.key, required this.onPressed, }); final VoidCallback onPressed; @override Widget build(BuildContext context) { return FlowyIconButton( iconPadding: const EdgeInsets.all(2), width: _iconSize, height: _iconSize, icon: const FlowySvg( FlowySvgs.add_s, size: Size.square(_iconSize), ), onPressed: onPressed, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/page_item/mobile_view_item.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/page_item/mobile_view_item_add_button.dart'; import 'package:appflowy/plugins/base/emoji/emoji_text.dart'; import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart'; import 'package:appflowy/workspace/application/view/view_bloc.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy/workspace/presentation/home/menu/view/draggable_view_item.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.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_slidable/flutter_slidable.dart'; typedef ViewItemOnSelected = void Function(ViewPB); typedef ActionPaneBuilder = ActionPane Function(BuildContext context); const _itemHeight = 48.0; class MobileViewItem extends StatelessWidget { const MobileViewItem({ super.key, required this.view, this.parentView, required this.categoryType, required this.level, this.leftPadding = 10, required this.onSelected, this.isFirstChild = false, this.isDraggable = true, required this.isFeedback, this.startActionPane, this.endActionPane, }); final ViewPB view; final ViewPB? parentView; final FolderCategoryType categoryType; // indicate the level of the view item // used to calculate the left padding final int level; // the left padding of the view item for each level // the left padding of the each level = level * leftPadding final double leftPadding; // Selected by normal conventions final ViewItemOnSelected onSelected; // used for indicating the first child of the parent view, so that we can // add top border to the first child final bool isFirstChild; // it should be false when it's rendered as feedback widget inside DraggableItem final bool isDraggable; // identify if the view item is rendered as feedback widget inside DraggableItem final bool isFeedback; // the actions of the view item, such as favorite, rename, delete, etc. final ActionPaneBuilder? startActionPane; final ActionPaneBuilder? endActionPane; @override Widget build(BuildContext context) { return BlocProvider( create: (_) => ViewBloc(view: view)..add(const ViewEvent.initial()), child: BlocConsumer<ViewBloc, ViewState>( listenWhen: (p, c) => c.lastCreatedView != null && p.lastCreatedView?.id != c.lastCreatedView!.id, listener: (context, state) => context.pushView(state.lastCreatedView!), builder: (context, state) { return InnerMobileViewItem( view: state.view, parentView: parentView, childViews: state.view.childViews, categoryType: categoryType, level: level, leftPadding: leftPadding, showActions: true, isExpanded: state.isExpanded, onSelected: onSelected, isFirstChild: isFirstChild, isDraggable: isDraggable, isFeedback: isFeedback, startActionPane: startActionPane, endActionPane: endActionPane, ); }, ), ); } } class InnerMobileViewItem extends StatelessWidget { const InnerMobileViewItem({ super.key, required this.view, required this.parentView, required this.childViews, required this.categoryType, this.isDraggable = true, this.isExpanded = true, required this.level, required this.leftPadding, required this.showActions, required this.onSelected, this.isFirstChild = false, required this.isFeedback, this.startActionPane, this.endActionPane, }); final ViewPB view; final ViewPB? parentView; final List<ViewPB> childViews; final FolderCategoryType categoryType; final bool isDraggable; final bool isExpanded; final bool isFirstChild; // identify if the view item is rendered as feedback widget inside DraggableItem final bool isFeedback; final int level; final double leftPadding; final bool showActions; final ViewItemOnSelected onSelected; final ActionPaneBuilder? startActionPane; final ActionPaneBuilder? endActionPane; @override Widget build(BuildContext context) { Widget child = SingleMobileInnerViewItem( view: view, parentView: parentView, level: level, showActions: showActions, categoryType: categoryType, onSelected: onSelected, isExpanded: isExpanded, isDraggable: isDraggable, leftPadding: leftPadding, isFeedback: isFeedback, startActionPane: startActionPane, endActionPane: endActionPane, ); // if the view is expanded and has child views, render its child views if (isExpanded) { if (childViews.isNotEmpty) { final children = childViews.map((childView) { return MobileViewItem( key: ValueKey('${categoryType.name} ${childView.id}'), parentView: view, categoryType: categoryType, isFirstChild: childView.id == childViews.first.id, view: childView, level: level + 1, onSelected: onSelected, isDraggable: isDraggable, leftPadding: leftPadding, isFeedback: isFeedback, startActionPane: startActionPane, endActionPane: endActionPane, ); }).toList(); child = Column( mainAxisSize: MainAxisSize.min, children: [ child, const Divider( height: 1, ), ...children, ], ); } else { child = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ child, const Divider( height: 1, ), Container( height: _itemHeight, alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.only(left: (level + 2) * leftPadding), child: FlowyText.medium( LocaleKeys.noPagesInside.tr(), color: Colors.grey, ), ), ), const Divider( height: 1, ), ], ); } } else { child = Column( mainAxisSize: MainAxisSize.min, children: [ child, const Divider( height: 1, ), ], ); } // wrap the child with DraggableItem if isDraggable is true if (isDraggable && !isReferencedDatabaseView(view, parentView)) { child = DraggableViewItem( isFirstChild: isFirstChild, view: view, // FIXME: use better color centerHighlightColor: Colors.blue.shade200, topHighlightColor: Colors.blue.shade200, bottomHighlightColor: Colors.blue.shade200, feedback: (context) { return MobileViewItem( view: view, parentView: parentView, categoryType: categoryType, level: level, onSelected: onSelected, isDraggable: false, leftPadding: leftPadding, isFeedback: true, startActionPane: startActionPane, endActionPane: endActionPane, ); }, child: child, ); } return child; } } class SingleMobileInnerViewItem extends StatefulWidget { const SingleMobileInnerViewItem({ super.key, required this.view, required this.parentView, required this.isExpanded, required this.level, required this.leftPadding, this.isDraggable = true, required this.categoryType, required this.showActions, required this.onSelected, required this.isFeedback, this.startActionPane, this.endActionPane, }); final ViewPB view; final ViewPB? parentView; final bool isExpanded; // identify if the view item is rendered as feedback widget inside DraggableItem final bool isFeedback; final int level; final double leftPadding; final bool isDraggable; final bool showActions; final ViewItemOnSelected onSelected; final FolderCategoryType categoryType; final ActionPaneBuilder? startActionPane; final ActionPaneBuilder? endActionPane; @override State<SingleMobileInnerViewItem> createState() => _SingleMobileInnerViewItemState(); } class _SingleMobileInnerViewItemState extends State<SingleMobileInnerViewItem> { @override Widget build(BuildContext context) { final children = [ // expand icon _buildLeftIcon(), const HSpace(4), // icon _buildViewIcon(), const HSpace(8), // title Expanded( child: FlowyText.medium( widget.view.name, fontSize: 18.0, overflow: TextOverflow.ellipsis, ), ), ]; // hover action // ··· more action button // children.add(_buildViewMoreActionButton(context)); // only support add button for document layout if (!widget.isFeedback && widget.view.layout == ViewLayoutPB.Document) { // + button children.add(_buildViewAddButton(context)); } Widget child = InkWell( borderRadius: BorderRadius.circular(4.0), onTap: () => widget.onSelected(widget.view), child: SizedBox( height: _itemHeight, child: Padding( padding: EdgeInsets.only(left: widget.level * widget.leftPadding), child: Row( children: children, ), ), ), ); if (widget.startActionPane != null || widget.endActionPane != null) { child = Slidable( // Specify a key if the Slidable is dismissible. key: ValueKey(widget.view.hashCode), startActionPane: widget.startActionPane?.call(context), endActionPane: widget.endActionPane?.call(context), child: child, ); } return child; } Widget _buildViewIcon() { final icon = widget.view.icon.value.isNotEmpty ? EmojiText( emoji: widget.view.icon.value, fontSize: 24.0, ) : SizedBox.square( dimension: 26.0, child: widget.view.defaultIcon(), ); return icon; } // > button or · button // show > if the view is expandable. // show · if the view can't contain child views. Widget _buildLeftIcon() { if (isReferencedDatabaseView(widget.view, widget.parentView)) { return const _DotIconWidget(); } return GestureDetector( child: AnimatedRotation( duration: const Duration(milliseconds: 250), turns: widget.isExpanded ? 0 : -0.25, child: const Icon( Icons.keyboard_arrow_down_rounded, size: 28, ), ), onTap: () { context .read<ViewBloc>() .add(ViewEvent.setIsExpanded(!widget.isExpanded)); }, ); } // + button Widget _buildViewAddButton(BuildContext context) { return MobileViewAddButton( onPressed: () { final title = widget.view.name; showMobileBottomSheet( context, showHeader: true, title: title, showDragHandle: true, showCloseButton: true, useRootNavigator: true, builder: (sheetContext) { return AddNewPageWidgetBottomSheet( view: widget.view, onAction: (layout) { Navigator.of(sheetContext).pop(); context.read<ViewBloc>().add( ViewEvent.createView( LocaleKeys.menuAppHeader_defaultNewPageName.tr(), layout, section: widget.categoryType != FolderCategoryType.favorite ? widget.categoryType.toViewSectionPB : null, ), ); }, ); }, ); }, ); } } class _DotIconWidget extends StatelessWidget { const _DotIconWidget(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(6.0), child: Container( width: 4, height: 4, decoration: BoxDecoration( color: Theme.of(context).iconTheme.color, borderRadius: BorderRadius.circular(2), ), ), ); } } // workaround: we should use view.isEndPoint or something to check if the view can contain child views. But currently, we don't have that field. bool isReferencedDatabaseView(ViewPB view, ViewPB? parentView) { if (parentView == null) { return false; } return view.layout.isDatabaseView && parentView.layout.isDatabaseView; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/favorite/mobile_favorite_page.dart
import 'dart:io'; import 'package:appflowy/mobile/presentation/favorite/mobile_favorite_folder.dart'; import 'package:appflowy/mobile/presentation/home/mobile_home_page_header.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/user/prelude.dart'; import 'package:appflowy/workspace/presentation/home/errors/workspace_failed_screen.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MobileFavoriteScreen extends StatelessWidget { const MobileFavoriteScreen({ super.key, }); static const routeName = '/favorite'; @override Widget build(BuildContext context) { return FutureBuilder( future: Future.wait([ FolderEventGetCurrentWorkspaceSetting().send(), getIt<AuthService>().getUser(), ]), builder: (context, snapshots) { if (!snapshots.hasData) { return const Center(child: CircularProgressIndicator.adaptive()); } final workspaceSetting = snapshots.data?[0].fold( (workspaceSettingPB) { return workspaceSettingPB as WorkspaceSettingPB?; }, (error) => null, ); final userProfile = snapshots.data?[1].fold( (userProfilePB) { return userProfilePB as UserProfilePB?; }, (error) => null, ); // In the unlikely case either of the above is null, eg. // when a workspace is already open this can happen. if (workspaceSetting == null || userProfile == null) { return const WorkspaceFailedScreen(); } return Scaffold( body: SafeArea( child: BlocProvider( create: (_) => UserWorkspaceBloc(userProfile: userProfile) ..add( const UserWorkspaceEvent.initial(), ), child: BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>( buildWhen: (previous, current) => previous.currentWorkspace?.workspaceId != current.currentWorkspace?.workspaceId, builder: (context, state) { return MobileFavoritePage( userProfile: userProfile, workspaceId: state.currentWorkspace?.workspaceId ?? workspaceSetting.workspaceId, ); }, ), ), ), ); }, ); } } class MobileFavoritePage extends StatelessWidget { const MobileFavoritePage({ super.key, required this.userProfile, required this.workspaceId, }); final UserProfilePB userProfile; final String workspaceId; @override Widget build(BuildContext context) { return Column( children: [ // Header Padding( padding: EdgeInsets.only( left: 16, right: 16, top: Platform.isAndroid ? 8.0 : 0.0, ), child: MobileHomePageHeader( userProfile: userProfile, ), ), const Divider(), // Folder Expanded( child: MobileFavoritePageFolder( userProfile: userProfile, workspaceId: workspaceId, ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/favorite/mobile_favorite_folder.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/mobile/presentation/home/favorite_folder/mobile_home_favorite_folder.dart'; import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_state_container.dart'; import 'package:appflowy/workspace/application/favorite/favorite_bloc.dart'; import 'package:appflowy/workspace/application/menu/sidebar_sections_bloc.dart'; import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart'; import 'package:easy_localization/easy_localization.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_slidable/flutter_slidable.dart'; class MobileFavoritePageFolder extends StatelessWidget { const MobileFavoritePageFolder({ super.key, required this.userProfile, required this.workspaceId, }); final UserProfilePB userProfile; final String workspaceId; @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (_) => SidebarSectionsBloc() ..add( SidebarSectionsEvent.initial( userProfile, workspaceId, ), ), ), BlocProvider( create: (_) => FavoriteBloc()..add(const FavoriteEvent.initial()), ), ], child: BlocListener<UserWorkspaceBloc, UserWorkspaceState>( listener: (context, state) { context.read<FavoriteBloc>().add( const FavoriteEvent.initial(), ); }, child: MultiBlocListener( listeners: [ BlocListener<SidebarSectionsBloc, SidebarSectionsState>( listenWhen: (p, c) => p.lastCreatedRootView?.id != c.lastCreatedRootView?.id, listener: (context, state) => context.pushView(state.lastCreatedRootView!), ), ], child: Builder( builder: (context) { final favoriteState = context.watch<FavoriteBloc>().state; if (favoriteState.views.isEmpty) { return FlowyMobileStateContainer.info( emoji: '😁', title: LocaleKeys.favorite_noFavorite.tr(), description: LocaleKeys.favorite_noFavoriteHintText.tr(), ); } return Scrollbar( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8.0), child: SlidableAutoCloseBehavior( child: Column( children: [ MobileFavoriteFolder( showHeader: false, forceExpanded: true, views: favoriteState.views, ), const VSpace(100.0), ], ), ), ), ), ); }, ), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_page_header.dart
import 'package:appflowy/generated/flowy_svgs.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/home/mobile_home_setting_page.dart'; import 'package:appflowy/mobile/presentation/home/workspaces/workspace_menu_bottom_sheet.dart'; import 'package:appflowy/plugins/base/emoji/emoji_picker_screen.dart'; import 'package:appflowy/plugins/base/icon/icon_picker.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/user/settings_user_bloc.dart'; import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_icon.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class MobileHomePageHeader extends StatelessWidget { const MobileHomePageHeader({ super.key, required this.userProfile, }); final UserProfilePB userProfile; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => getIt<SettingsUserViewBloc>(param1: userProfile) ..add(const SettingsUserEvent.initial()), child: BlocBuilder<SettingsUserViewBloc, SettingsUserState>( builder: (context, state) { final isCollaborativeWorkspace = context.read<UserWorkspaceBloc>().state.isCollabWorkspaceOn; return ConstrainedBox( constraints: const BoxConstraints(minHeight: 52), child: Row( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: isCollaborativeWorkspace ? _MobileWorkspace(userProfile: userProfile) : _MobileUser(userProfile: userProfile), ), IconButton( onPressed: () => context.push( MobileHomeSettingPage.routeName, ), icon: const FlowySvg(FlowySvgs.m_setting_m), ), ], ), ); }, ), ); } } class _MobileUser extends StatelessWidget { const _MobileUser({ required this.userProfile, }); final UserProfilePB userProfile; @override Widget build(BuildContext context) { final userIcon = userProfile.iconUrl; return Row( children: [ _UserIcon(userIcon: userIcon), const HSpace(12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const FlowyText.medium('AppFlowy', fontSize: 18), const VSpace(4), FlowyText.regular( userProfile.email.isNotEmpty ? userProfile.email : userProfile.name, fontSize: 12, color: Theme.of(context).colorScheme.onSurface, overflow: TextOverflow.ellipsis, ), ], ), ), ], ); } } class _MobileWorkspace extends StatelessWidget { const _MobileWorkspace({ required this.userProfile, }); final UserProfilePB userProfile; @override Widget build(BuildContext context) { return BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>( builder: (context, state) { final currentWorkspace = state.currentWorkspace; if (currentWorkspace == null) { return const SizedBox.shrink(); } return GestureDetector( onTap: () { context.read<UserWorkspaceBloc>().add( const UserWorkspaceEvent.fetchWorkspaces(), ); _showSwitchWorkspacesBottomSheet(context); }, child: Row( children: [ const HSpace(2.0), SizedBox.square( dimension: 34.0, child: WorkspaceIcon( workspace: currentWorkspace, iconSize: 26, enableEdit: false, ), ), const HSpace(8), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ FlowyText.medium( currentWorkspace.name, fontSize: 16.0, overflow: TextOverflow.ellipsis, ), const HSpace(4.0), const FlowySvg(FlowySvgs.list_dropdown_s), ], ), FlowyText.medium( userProfile.email.isNotEmpty ? userProfile.email : userProfile.name, overflow: TextOverflow.ellipsis, fontSize: 12, color: Theme.of(context).colorScheme.onSurface, ), ], ), ), ], ), ); }, ); } void _showSwitchWorkspacesBottomSheet( BuildContext context, ) { showMobileBottomSheet( context, showDivider: false, showHeader: true, showDragHandle: true, title: LocaleKeys.workspace_menuTitle.tr(), builder: (_) { return BlocProvider.value( value: context.read<UserWorkspaceBloc>(), child: BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>( builder: (context, state) { final currentWorkspace = state.currentWorkspace; final workspaces = state.workspaces; if (currentWorkspace == null || workspaces.isEmpty) { return const SizedBox.shrink(); } return MobileWorkspaceMenu( userProfile: userProfile, currentWorkspace: currentWorkspace, workspaces: workspaces, onWorkspaceSelected: (workspace) { context.pop(); if (workspace == currentWorkspace) { return; } context.read<UserWorkspaceBloc>().add( UserWorkspaceEvent.openWorkspace( workspace.workspaceId, ), ); }, ); }, ), ); }, ); } } class _UserIcon extends StatelessWidget { const _UserIcon({ required this.userIcon, }); final String userIcon; @override Widget build(BuildContext context) { return FlowyButton( useIntrinsicWidth: true, text: builtInSVGIcons.contains(userIcon) // to be compatible with old user icon ? FlowySvg( FlowySvgData('emoji/$userIcon'), size: const Size.square(32), blendMode: null, ) : FlowyText( userIcon.isNotEmpty ? userIcon : '🐻', fontSize: 26, ), onTap: () async { final icon = await context.push<EmojiPickerResult>( Uri( path: MobileEmojiPickerScreen.routeName, queryParameters: { MobileEmojiPickerScreen.pageTitle: LocaleKeys.titleBar_userIcon.tr(), }, ).toString(), ); if (icon != null) { if (context.mounted) { context.read<SettingsUserViewBloc>().add( SettingsUserEvent.updateUserIcon( iconUrl: icon.emoji, ), ); } } }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_folders.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/mobile/presentation/home/section_folder/mobile_home_section_folder.dart'; import 'package:appflowy/workspace/application/favorite/favorite_bloc.dart'; import 'package:appflowy/workspace/application/menu/sidebar_sections_bloc.dart'; import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart'; import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:easy_localization/easy_localization.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_slidable/flutter_slidable.dart'; // Contains Public And Private Sections class MobileFolders extends StatelessWidget { const MobileFolders({ super.key, required this.user, required this.workspaceId, required this.showFavorite, }); final UserProfilePB user; final String workspaceId; final bool showFavorite; @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (_) => SidebarSectionsBloc() ..add( SidebarSectionsEvent.initial( user, workspaceId, ), ), ), BlocProvider( create: (_) => FavoriteBloc()..add(const FavoriteEvent.initial()), ), ], child: BlocListener<UserWorkspaceBloc, UserWorkspaceState>( listener: (context, state) { context.read<SidebarSectionsBloc>().add( SidebarSectionsEvent.initial( user, state.currentWorkspace?.workspaceId ?? workspaceId, ), ); }, child: BlocConsumer<SidebarSectionsBloc, SidebarSectionsState>( listenWhen: (p, c) => p.lastCreatedRootView?.id != c.lastCreatedRootView?.id, listener: (context, state) { final lastCreatedRootView = state.lastCreatedRootView; if (lastCreatedRootView != null) { context.pushView(lastCreatedRootView); } }, builder: (context, state) { final isCollaborativeWorkspace = context.read<UserWorkspaceBloc>().state.isCollabWorkspaceOn; return SlidableAutoCloseBehavior( child: Column( children: [ ...isCollaborativeWorkspace ? [ MobileSectionFolder( title: LocaleKeys.sideBar_workspace.tr(), categoryType: FolderCategoryType.public, views: state.section.publicViews, ), const VSpace(8.0), MobileSectionFolder( title: LocaleKeys.sideBar_private.tr(), categoryType: FolderCategoryType.private, views: state.section.privateViews, ), ] : [ MobileSectionFolder( title: LocaleKeys.sideBar_personal.tr(), categoryType: FolderCategoryType.public, views: state.section.publicViews, ), ], const VSpace(8.0), ], ), ); }, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_setting_page.dart
import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/env/env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/mobile/presentation/presentation.dart'; import 'package:appflowy/mobile/presentation/setting/cloud/cloud_setting_group.dart'; import 'package:appflowy/mobile/presentation/setting/user_session_setting_group.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class MobileHomeSettingPage extends StatefulWidget { const MobileHomeSettingPage({ super.key, }); static const routeName = '/settings'; @override State<MobileHomeSettingPage> createState() => _MobileHomeSettingPageState(); } class _MobileHomeSettingPageState extends State<MobileHomeSettingPage> { @override Widget build(BuildContext context) { return FutureBuilder( future: getIt<AuthService>().getUser(), builder: (context, snapshot) { String? errorMsg; if (!snapshot.hasData) { return const Center(child: CircularProgressIndicator.adaptive()); } final userProfile = snapshot.data?.fold( (userProfile) { return userProfile; }, (error) { errorMsg = error.msg; return null; }, ); return Scaffold( appBar: FlowyAppBar( titleText: LocaleKeys.settings_title.tr(), ), body: userProfile == null ? _buildErrorWidget(errorMsg) : _buildSettingsWidget(userProfile), ); }, ); } Widget _buildErrorWidget(String? errorMsg) { return FlowyMobileStateContainer.error( emoji: '🛸', title: LocaleKeys.settings_mobile_userprofileError.tr(), description: LocaleKeys.settings_mobile_userprofileErrorDescription.tr(), errorMsg: errorMsg, ); } Widget _buildSettingsWidget(UserProfilePB userProfile) { // show the third-party sign in buttons if user logged in with local session and auth is enabled. final showThirdPartyLogin = userProfile.authenticator == AuthenticatorPB.Local && isAuthEnabled; return SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ PersonalInfoSettingGroup( userProfile: userProfile, ), // TODO: Enable and implement along with Push Notifications // const NotificationsSettingGroup(), const AppearanceSettingGroup(), const LanguageSettingGroup(), if (Env.enableCustomCloud) const CloudSettingGroup(), const SupportSettingGroup(), const AboutSettingGroup(), UserSessionSettingGroup( showThirdPartyLogin: showThirdPartyLogin, ), const VSpace(20), ], ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_page.dart
import 'dart:io'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/home/home.dart'; import 'package:appflowy/mobile/presentation/home/mobile_folders.dart'; import 'package:appflowy/mobile/presentation/home/mobile_home_page_header.dart'; import 'package:appflowy/mobile/presentation/home/recent_folder/mobile_home_recent_views.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart'; import 'package:appflowy/workspace/presentation/home/errors/workspace_failed_screen.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; class MobileHomeScreen extends StatelessWidget { const MobileHomeScreen({super.key}); static const routeName = '/home'; @override Widget build(BuildContext context) { return FutureBuilder( future: Future.wait([ FolderEventGetCurrentWorkspaceSetting().send(), getIt<AuthService>().getUser(), ]), builder: (context, snapshots) { if (!snapshots.hasData) { return const Center(child: CircularProgressIndicator.adaptive()); } final workspaceSetting = snapshots.data?[0].fold( (workspaceSettingPB) { return workspaceSettingPB as WorkspaceSettingPB?; }, (error) => null, ); final userProfile = snapshots.data?[1].fold( (userProfilePB) { return userProfilePB as UserProfilePB?; }, (error) => null, ); // In the unlikely case either of the above is null, eg. // when a workspace is already open this can happen. if (workspaceSetting == null || userProfile == null) { return const WorkspaceFailedScreen(); } return Scaffold( body: SafeArea( child: Provider.value( value: userProfile, child: MobileHomePage( userProfile: userProfile, workspaceSetting: workspaceSetting, ), ), ), ); }, ); } } class MobileHomePage extends StatelessWidget { const MobileHomePage({ super.key, required this.userProfile, required this.workspaceSetting, }); final UserProfilePB userProfile; final WorkspaceSettingPB workspaceSetting; @override Widget build(BuildContext context) { return BlocProvider( create: (_) => UserWorkspaceBloc(userProfile: userProfile) ..add( const UserWorkspaceEvent.initial(), ), child: BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>( buildWhen: (previous, current) => previous.currentWorkspace?.workspaceId != current.currentWorkspace?.workspaceId, builder: (context, state) { if (state.currentWorkspace == null) { return const SizedBox.shrink(); } return Column( children: [ // Header Padding( padding: EdgeInsets.only( left: 16, right: 16, top: Platform.isAndroid ? 8.0 : 0.0, ), child: MobileHomePageHeader( userProfile: userProfile, ), ), const Divider(), // Folder Expanded( child: Scrollbar( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ // Recent files const MobileRecentFolder(), // Folders Padding( padding: const EdgeInsets.symmetric(horizontal: 24), child: MobileFolders( user: userProfile, workspaceId: state.currentWorkspace?.workspaceId ?? workspaceSetting.workspaceId, showFavorite: false, ), ), const SizedBox(height: 8), const Padding( padding: EdgeInsets.symmetric(horizontal: 24), child: _TrashButton(), ), ], ), ), ), ), ), ], ); }, ), ); } } class _TrashButton extends StatelessWidget { const _TrashButton(); @override Widget build(BuildContext context) { return FlowyButton( expand: true, margin: const EdgeInsets.symmetric(vertical: 8), leftIcon: FlowySvg( FlowySvgs.m_delete_m, color: Theme.of(context).colorScheme.onSurface, ), leftIconSize: const Size.square(24), text: FlowyText.medium( LocaleKeys.trash_text.tr(), fontSize: 18.0, ), onTap: () => context.push(MobileHomeTrashPage.routeName), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_trash_page.dart
import 'package:appflowy/generated/flowy_svgs.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/widgets/widgets.dart'; import 'package:appflowy/plugins/trash/application/prelude.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:go_router/go_router.dart'; class MobileHomeTrashPage extends StatelessWidget { const MobileHomeTrashPage({super.key}); static const routeName = '/trash'; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => getIt<TrashBloc>()..add(const TrashEvent.initial()), child: BlocBuilder<TrashBloc, TrashState>( builder: (context, state) { return Scaffold( appBar: AppBar( title: Text(LocaleKeys.trash_text.tr()), actions: [ state.objects.isEmpty ? const SizedBox.shrink() : IconButton( splashRadius: 20, icon: const Icon(Icons.more_horiz), onPressed: () { final trashBloc = context.read<TrashBloc>(); showMobileBottomSheet( context, showHeader: true, showCloseButton: true, showDragHandle: true, padding: const EdgeInsets.fromLTRB(16, 8, 16, 32), title: LocaleKeys.trash_mobile_actions.tr(), builder: (_) => Row( children: [ Expanded( child: _TrashActionAllButton( trashBloc: trashBloc, ), ), const SizedBox( width: 16, ), Expanded( child: _TrashActionAllButton( trashBloc: trashBloc, type: _TrashActionType.restoreAll, ), ), ], ), ); }, ), ], ), body: state.objects.isEmpty ? FlowyMobileStateContainer.info( emoji: '🗑️', title: LocaleKeys.trash_mobile_empty.tr(), description: LocaleKeys.trash_mobile_emptyDescription.tr(), ) : _DeletedFilesListView(state), ); }, ), ); } } enum _TrashActionType { restoreAll, deleteAll, } class _TrashActionAllButton extends StatelessWidget { /// Switch between 'delete all' and 'restore all' feature const _TrashActionAllButton({ this.type = _TrashActionType.deleteAll, required this.trashBloc, }); final _TrashActionType type; final TrashBloc trashBloc; @override Widget build(BuildContext context) { final theme = Theme.of(context); final isDeleteAll = type == _TrashActionType.deleteAll; return BlocProvider.value( value: trashBloc, child: BottomSheetActionWidget( svg: isDeleteAll ? FlowySvgs.m_delete_m : FlowySvgs.m_restore_m, text: isDeleteAll ? LocaleKeys.trash_deleteAll.tr() : LocaleKeys.trash_restoreAll.tr(), onTap: () { final trashList = trashBloc.state.objects; if (trashList.isNotEmpty) { context.pop(); showFlowyMobileConfirmDialog( context, title: FlowyText( isDeleteAll ? LocaleKeys.trash_confirmDeleteAll_title.tr() : LocaleKeys.trash_restoreAll.tr(), ), content: FlowyText( isDeleteAll ? LocaleKeys.trash_confirmDeleteAll_caption.tr() : LocaleKeys.trash_confirmRestoreAll_caption.tr(), ), actionButtonTitle: isDeleteAll ? LocaleKeys.trash_deleteAll.tr() : LocaleKeys.trash_restoreAll.tr(), actionButtonColor: isDeleteAll ? theme.colorScheme.error : theme.colorScheme.primary, onActionButtonPressed: () { if (isDeleteAll) { trashBloc.add( const TrashEvent.deleteAll(), ); } else { trashBloc.add( const TrashEvent.restoreAll(), ); } }, cancelButtonTitle: LocaleKeys.button_cancel.tr(), ); } else { // when there is no deleted files // show toast Fluttertoast.showToast( msg: LocaleKeys.trash_mobile_empty.tr(), gravity: ToastGravity.CENTER, ); } }, ), ); } } class _DeletedFilesListView extends StatelessWidget { const _DeletedFilesListView( this.state, ); final TrashState state; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: ListView.builder( itemBuilder: (context, index) { final deletedFile = state.objects[index]; return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), child: ListTile( // TODO: show different file type icon, implement this feature after TrashPB has file type field leading: FlowySvg( FlowySvgs.document_s, size: const Size.square(24), color: theme.colorScheme.onSurface, ), title: Text( deletedFile.name, style: theme.textTheme.labelMedium ?.copyWith(color: theme.colorScheme.onBackground), ), horizontalTitleGap: 0, tileColor: theme.colorScheme.onSurface.withOpacity(0.1), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( splashRadius: 20, icon: FlowySvg( FlowySvgs.m_restore_m, size: const Size.square(24), color: theme.colorScheme.onSurface, ), onPressed: () { context .read<TrashBloc>() .add(TrashEvent.putback(deletedFile.id)); Fluttertoast.showToast( msg: '${deletedFile.name} ${LocaleKeys.trash_mobile_isRestored.tr()}', gravity: ToastGravity.BOTTOM, ); }, ), IconButton( splashRadius: 20, icon: FlowySvg( FlowySvgs.m_delete_m, size: const Size.square(24), color: theme.colorScheme.onSurface, ), onPressed: () { context .read<TrashBloc>() .add(TrashEvent.delete(deletedFile)); Fluttertoast.showToast( msg: '${deletedFile.name} ${LocaleKeys.trash_mobile_isDeleted.tr()}', gravity: ToastGravity.BOTTOM, ); }, ), ], ), ), ); }, itemCount: state.objects.length, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/home.dart
export 'mobile_home_page.dart'; export 'mobile_home_setting_page.dart'; export 'mobile_home_trash_page.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/recent_folder/mobile_recent_view.dart
import 'dart:io'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/mobile/application/recent/recent_view_bloc.dart'; import 'package:appflowy/plugins/base/emoji/emoji_text.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/shared/appflowy_network_image.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:provider/provider.dart'; import 'package:string_validator/string_validator.dart'; class MobileRecentView extends StatelessWidget { const MobileRecentView({ super.key, required this.view, }); final ViewPB view; @override Widget build(BuildContext context) { final theme = Theme.of(context); return BlocProvider<RecentViewBloc>( create: (context) => RecentViewBloc(view: view) ..add( const RecentViewEvent.initial(), ), child: BlocBuilder<RecentViewBloc, RecentViewState>( builder: (context, state) { return GestureDetector( onTap: () => context.pushView(view), child: Stack( children: [ DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), border: Border.all(color: theme.colorScheme.outline), ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(8), topRight: Radius.circular(8), ), child: _RecentCover( coverType: state.coverType, value: state.coverValue, ), ), ), Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(8, 18, 8, 2), // hack: minLines currently not supported in Text widget. // https://github.com/flutter/flutter/issues/31134 child: Stack( children: [ FlowyText.medium( view.name, maxLines: 2, overflow: TextOverflow.ellipsis, ), const FlowyText( "\n\n", maxLines: 2, ), ], ), ), ), ], ), ), Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.only(left: 8.0), child: state.icon.isNotEmpty ? EmojiText( emoji: state.icon, fontSize: 30.0, ) : SizedBox.square( dimension: 32.0, child: view.defaultIcon(), ), ), ), ], ), ); }, ), ); } } class _RecentCover extends StatelessWidget { const _RecentCover({ required this.coverType, this.value, }); final CoverType coverType; final String? value; @override Widget build(BuildContext context) { final placeholder = Container( // random color, update it once we have a better placeholder color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.2), ); final value = this.value; if (value == null) { return placeholder; } switch (coverType) { case CoverType.file: if (isURL(value)) { final userProfilePB = Provider.of<UserProfilePB?>(context); return FlowyNetworkImage( url: value, userProfilePB: userProfilePB, ); } final imageFile = File(value); if (!imageFile.existsSync()) { return placeholder; } return Image.file( imageFile, ); case CoverType.asset: return Image.asset( value, fit: BoxFit.cover, ); case CoverType.color: final color = value.tryToColor() ?? Colors.white; return Container( color: color, ); case CoverType.none: return placeholder; } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/recent_folder/mobile_home_recent_views.dart
import 'package:appflowy/generated/flowy_svgs.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/home/recent_folder/mobile_recent_view.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/workspace/application/recent/prelude.dart'; import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class MobileRecentFolder extends StatefulWidget { const MobileRecentFolder({super.key}); @override State<MobileRecentFolder> createState() => _MobileRecentFolderState(); } class _MobileRecentFolderState extends State<MobileRecentFolder> { @override Widget build(BuildContext context) { return BlocProvider( create: (context) => RecentViewsBloc() ..add( const RecentViewsEvent.initial(), ), child: BlocListener<UserWorkspaceBloc, UserWorkspaceState>( listener: (context, state) { context.read<RecentViewsBloc>().add( const RecentViewsEvent.fetchRecentViews(), ); }, child: BlocBuilder<RecentViewsBloc, RecentViewsState>( builder: (context, state) { final ids = <String>{}; List<ViewPB> recentViews = state.views.reversed.toList(); recentViews.retainWhere((element) => ids.add(element.id)); // only keep the first 20 items. recentViews = recentViews.take(20).toList(); if (recentViews.isEmpty) { return const SizedBox.shrink(); } return Column( children: [ _RecentViews( key: ValueKey(recentViews), // the recent views are in reverse order recentViews: recentViews, ), const VSpace(12.0), ], ); }, ), ), ); } } class _RecentViews extends StatelessWidget { const _RecentViews({ super.key, required this.recentViews, }); final List<ViewPB> recentViews; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 24), child: GestureDetector( child: FlowyText.semibold( LocaleKeys.sideBar_recent.tr(), fontSize: 20.0, ), onTap: () { showMobileBottomSheet( context, showDivider: false, showDragHandle: true, backgroundColor: Theme.of(context).colorScheme.background, builder: (_) { return Column( children: [ FlowyOptionTile.text( text: LocaleKeys.button_clear.tr(), leftIcon: FlowySvg( FlowySvgs.m_delete_s, color: Theme.of(context).colorScheme.error, ), textColor: Theme.of(context).colorScheme.error, onTap: () { context.read<RecentViewsBloc>().add( RecentViewsEvent.removeRecentViews( recentViews.map((e) => e.id).toList(), ), ); context.pop(); }, ), ], ); }, ); }, ), ), SizedBox( height: 148, child: ListView.separated( key: const PageStorageKey('recent_views_page_storage_key'), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8), scrollDirection: Axis.horizontal, itemBuilder: (context, index) { final view = recentViews[index]; return SizedBox.square( dimension: 148, child: MobileRecentView(view: view), ); }, separatorBuilder: (context, index) => const HSpace(8), itemCount: recentViews.length, ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/favorite_folder/mobile_home_favorite_folder_header.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class MobileFavoriteFolderHeader extends StatefulWidget { const MobileFavoriteFolderHeader({ super.key, required this.onPressed, required this.onAdded, required this.isExpanded, }); final VoidCallback onPressed; final VoidCallback onAdded; final bool isExpanded; @override State<MobileFavoriteFolderHeader> createState() => _MobileFavoriteFolderHeaderState(); } class _MobileFavoriteFolderHeaderState extends State<MobileFavoriteFolderHeader> { double _turns = 0; @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: FlowyButton( text: FlowyText.semibold( LocaleKeys.sideBar_favorites.tr(), fontSize: 20.0, ), margin: const EdgeInsets.symmetric(vertical: 8), expandText: false, mainAxisAlignment: MainAxisAlignment.start, rightIcon: AnimatedRotation( duration: const Duration(milliseconds: 200), turns: _turns, child: const Icon( Icons.keyboard_arrow_down_rounded, color: Colors.grey, ), ), onTap: () { setState(() { _turns = widget.isExpanded ? -0.25 : 0; }); widget.onPressed(); }, ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/favorite_folder/mobile_home_favorite_folder.dart
import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/default_mobile_action_pane.dart'; import 'package:appflowy/mobile/presentation/home/favorite_folder/mobile_home_favorite_folder_header.dart'; import 'package:appflowy/mobile/presentation/page_item/mobile_view_item.dart'; import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MobileFavoriteFolder extends StatelessWidget { const MobileFavoriteFolder({ super.key, required this.views, this.showHeader = true, this.forceExpanded = false, }); final bool showHeader; final bool forceExpanded; final List<ViewPB> views; @override Widget build(BuildContext context) { if (views.isEmpty) { return const SizedBox.shrink(); } return BlocProvider<FolderBloc>( create: (context) => FolderBloc(type: FolderCategoryType.favorite) ..add( const FolderEvent.initial(), ), child: BlocBuilder<FolderBloc, FolderState>( builder: (context, state) { return Column( children: [ if (showHeader) ...[ MobileFavoriteFolderHeader( isExpanded: context.read<FolderBloc>().state.isExpanded, onPressed: () => context .read<FolderBloc>() .add(const FolderEvent.expandOrUnExpand()), onAdded: () => context.read<FolderBloc>().add( const FolderEvent.expandOrUnExpand(isExpanded: true), ), ), const VSpace(8.0), const Divider( height: 1, ), ], if (forceExpanded || state.isExpanded) ...views.map( (view) => MobileViewItem( key: ValueKey( '${FolderCategoryType.favorite.name} ${view.id}', ), categoryType: FolderCategoryType.favorite, isDraggable: false, isFirstChild: view.id == views.first.id, isFeedback: false, view: view, level: 0, onSelected: (view) async { await context.pushView(view); }, endActionPane: (context) => buildEndActionPane(context, [ view.isFavorite ? MobilePaneActionType.removeFromFavorites : MobilePaneActionType.addToFavorites, MobilePaneActionType.more, ]), ), ), ], ); }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/section_folder/mobile_home_section_folder.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/default_mobile_action_pane.dart'; import 'package:appflowy/mobile/presentation/home/section_folder/mobile_home_section_folder_header.dart'; import 'package:appflowy/mobile/presentation/page_item/mobile_view_item.dart'; import 'package:appflowy/workspace/application/menu/sidebar_sections_bloc.dart'; import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart'; import 'package:appflowy/workspace/application/view/view_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MobileSectionFolder extends StatelessWidget { const MobileSectionFolder({ super.key, required this.title, required this.views, required this.categoryType, }); final String title; final List<ViewPB> views; final FolderCategoryType categoryType; @override Widget build(BuildContext context) { return BlocProvider<FolderBloc>( create: (context) => FolderBloc(type: categoryType) ..add( const FolderEvent.initial(), ), child: BlocBuilder<FolderBloc, FolderState>( builder: (context, state) { return Column( children: [ MobileSectionFolderHeader( title: title, isExpanded: context.read<FolderBloc>().state.isExpanded, onPressed: () => context .read<FolderBloc>() .add(const FolderEvent.expandOrUnExpand()), onAdded: () { context.read<SidebarSectionsBloc>().add( SidebarSectionsEvent.createRootViewInSection( name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), index: 0, viewSection: categoryType.toViewSectionPB, ), ); context.read<FolderBloc>().add( const FolderEvent.expandOrUnExpand(isExpanded: true), ); }, ), const VSpace(8.0), const Divider( height: 1, ), if (state.isExpanded) ...views.map( (view) => MobileViewItem( key: ValueKey( '${FolderCategoryType.private.name} ${view.id}', ), categoryType: categoryType, isFirstChild: view.id == views.first.id, view: view, level: 0, leftPadding: 16, isFeedback: false, onSelected: (view) async { await context.pushView(view); }, endActionPane: (context) { final view = context.read<ViewBloc>().state.view; return buildEndActionPane(context, [ MobilePaneActionType.delete, view.isFavorite ? MobilePaneActionType.removeFromFavorites : MobilePaneActionType.addToFavorites, MobilePaneActionType.more, ]); }, ), ), ], ); }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/section_folder/mobile_home_section_folder_header.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; @visibleForTesting const Key mobileCreateNewPageButtonKey = Key('mobileCreateNewPageButtonKey'); class MobileSectionFolderHeader extends StatefulWidget { const MobileSectionFolderHeader({ super.key, required this.title, required this.onPressed, required this.onAdded, required this.isExpanded, }); final String title; final VoidCallback onPressed; final VoidCallback onAdded; final bool isExpanded; @override State<MobileSectionFolderHeader> createState() => _MobileSectionFolderHeaderState(); } class _MobileSectionFolderHeaderState extends State<MobileSectionFolderHeader> { double _turns = 0; @override Widget build(BuildContext context) { const iconSize = 32.0; return Row( children: [ Expanded( child: FlowyButton( text: FlowyText.semibold( widget.title, fontSize: 20.0, ), margin: const EdgeInsets.symmetric(vertical: 8), expandText: false, mainAxisAlignment: MainAxisAlignment.start, rightIcon: AnimatedRotation( duration: const Duration(milliseconds: 200), turns: _turns, child: const Icon( Icons.keyboard_arrow_down_rounded, color: Colors.grey, ), ), onTap: () { setState(() { _turns = widget.isExpanded ? -0.25 : 0; }); widget.onPressed(); }, ), ), FlowyIconButton( key: mobileCreateNewPageButtonKey, hoverColor: Theme.of(context).colorScheme.secondaryContainer, iconPadding: const EdgeInsets.all(2), height: iconSize, width: iconSize, icon: const FlowySvg( FlowySvgs.add_s, size: Size.square(iconSize), ), onPressed: widget.onAdded, ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/home/workspaces/workspace_menu_bottom_sheet.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_icon.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/members/workspace_member_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; // Only works on mobile. class MobileWorkspaceMenu extends StatelessWidget { const MobileWorkspaceMenu({ super.key, required this.userProfile, required this.currentWorkspace, required this.workspaces, required this.onWorkspaceSelected, }); final UserProfilePB userProfile; final UserWorkspacePB currentWorkspace; final List<UserWorkspacePB> workspaces; final void Function(UserWorkspacePB workspace) onWorkspaceSelected; @override Widget build(BuildContext context) { final List<Widget> children = []; for (var i = 0; i < workspaces.length; i++) { final workspace = workspaces[i]; children.add( _WorkspaceMenuItem( key: ValueKey(workspace.workspaceId), userProfile: userProfile, workspace: workspace, showTopBorder: i == 0, currentWorkspace: currentWorkspace, onWorkspaceSelected: onWorkspaceSelected, ), ); } return Column( children: children, ); } } class _WorkspaceMenuItem extends StatelessWidget { const _WorkspaceMenuItem({ super.key, required this.userProfile, required this.workspace, required this.showTopBorder, required this.currentWorkspace, required this.onWorkspaceSelected, }); final UserProfilePB userProfile; final UserWorkspacePB workspace; final bool showTopBorder; final UserWorkspacePB currentWorkspace; final void Function(UserWorkspacePB workspace) onWorkspaceSelected; @override Widget build(BuildContext context) { return BlocProvider( create: (_) => WorkspaceMemberBloc( userProfile: userProfile, workspace: workspace, )..add(const WorkspaceMemberEvent.initial()), child: BlocBuilder<WorkspaceMemberBloc, WorkspaceMemberState>( builder: (context, state) { final members = state.members; return FlowyOptionTile.text( content: Expanded( child: Padding( padding: const EdgeInsets.only(left: 12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ FlowyText( workspace.name, fontSize: 14, fontWeight: FontWeight.w500, ), FlowyText( state.isLoading ? '' : LocaleKeys.settings_appearance_members_membersCount .plural( members.length, ), fontSize: 10.0, color: Theme.of(context).hintColor, ), ], ), ), ), height: 60, showTopBorder: showTopBorder, leftIcon: WorkspaceIcon( enableEdit: false, iconSize: 26, workspace: workspace, ), trailing: workspace.workspaceId == currentWorkspace.workspaceId ? const FlowySvg( FlowySvgs.m_blue_check_s, blendMode: null, ) : null, onTap: () => onWorkspaceSelected(workspace), ); }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/type_option_menu_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart' hide WidgetBuilder; import 'package:flutter/material.dart'; class TypeOptionMenuItemValue<T> { const TypeOptionMenuItemValue({ required this.value, required this.icon, required this.text, required this.backgroundColor, required this.onTap, }); final T value; final FlowySvgData icon; final String text; final Color backgroundColor; final void Function(BuildContext context, T value) onTap; } class TypeOptionMenu<T> extends StatelessWidget { const TypeOptionMenu({ super.key, required this.values, this.width = 94, this.iconWidth = 72, this.scaleFactor = 1.0, this.maxAxisSpacing = 18, this.crossAxisCount = 3, }); final List<TypeOptionMenuItemValue<T>> values; final double iconWidth; final double width; final double scaleFactor; final double maxAxisSpacing; final int crossAxisCount; @override Widget build(BuildContext context) { return _GridView( crossAxisCount: crossAxisCount, mainAxisSpacing: maxAxisSpacing * scaleFactor, itemWidth: width * scaleFactor, children: values .map( (value) => _TypeOptionMenuItem<T>( value: value, width: width, iconWidth: iconWidth, scaleFactor: scaleFactor, ), ) .toList(), ); } } class _TypeOptionMenuItem<T> extends StatelessWidget { const _TypeOptionMenuItem({ required this.value, this.width = 94, this.iconWidth = 72, this.scaleFactor = 1.0, }); final TypeOptionMenuItemValue<T> value; final double iconWidth; final double width; final double scaleFactor; double get scaledIconWidth => iconWidth * scaleFactor; double get scaledWidth => width * scaleFactor; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => value.onTap(context, value.value), child: Column( children: [ Container( height: scaledIconWidth, width: scaledIconWidth, decoration: ShapeDecoration( color: value.backgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(24 * scaleFactor), ), ), padding: EdgeInsets.all(21 * scaleFactor), child: FlowySvg( value.icon, ), ), const VSpace(6), ConstrainedBox( constraints: BoxConstraints( maxWidth: scaledWidth, ), child: FlowyText( value.text, fontSize: 14.0, maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, ), ), ], ), ); } } class _GridView extends StatelessWidget { const _GridView({ required this.children, required this.crossAxisCount, required this.mainAxisSpacing, required this.itemWidth, }); final List<Widget> children; final int crossAxisCount; final double mainAxisSpacing; final double itemWidth; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ for (var i = 0; i < children.length; i += crossAxisCount) Padding( padding: EdgeInsets.only(bottom: mainAxisSpacing), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ for (var j = 0; j < crossAxisCount; j++) i + j < children.length ? SizedBox( width: itemWidth, child: children[i + j], ) : HSpace(itemWidth), ], ), ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/flowy_search_text_field.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class FlowySearchTextField extends StatelessWidget { const FlowySearchTextField({ super.key, this.hintText, this.controller, this.onChanged, this.onSubmitted, }); final String? hintText; final TextEditingController? controller; final ValueChanged<String>? onChanged; final ValueChanged<String>? onSubmitted; @override Widget build(BuildContext context) { return SizedBox( height: 44.0, child: CupertinoSearchTextField( controller: controller, onChanged: onChanged, onSubmitted: onSubmitted, placeholder: hintText, prefixIcon: const FlowySvg(FlowySvgs.m_search_m), prefixInsets: const EdgeInsets.only(left: 16.0, right: 2.0), suffixIcon: const Icon(Icons.close), suffixInsets: const EdgeInsets.only(right: 16.0), placeholderStyle: Theme.of(context).textTheme.titleSmall?.copyWith( color: Theme.of(context).hintColor, fontWeight: FontWeight.w400, fontSize: 14.0, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/option_color_list.dart
import 'package:appflowy/generated/flowy_svgs.g.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:flowy_infra/size.dart'; import 'package:flutter/material.dart'; class OptionColorList extends StatelessWidget { const OptionColorList({ super.key, this.selectedColor, required this.onSelectedColor, }); final SelectOptionColorPB? selectedColor; final void Function(SelectOptionColorPB color) onSelectedColor; @override Widget build(BuildContext context) { return GridView.count( crossAxisCount: 6, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, children: SelectOptionColorPB.values.map( (colorPB) { final color = colorPB.toColor(context); final isSelected = selectedColor?.value == colorPB.value; return GestureDetector( onTap: () => onSelectedColor(colorPB), child: Container( margin: const EdgeInsets.all( 8.0, ), decoration: BoxDecoration( color: color, borderRadius: Corners.s12Border, border: Border.all( width: isSelected ? 2.0 : 1.0, color: isSelected ? const Color(0xff00C6F1) : Theme.of(context).dividerColor, ), ), alignment: Alignment.center, child: isSelected ? const FlowySvg( FlowySvgs.m_blue_check_s, size: Size.square(28.0), blendMode: null, ) : null, ), ); }, ).toList(), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/mobile_view_page.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/mobile/presentation/base/app_bar_actions.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_state_container.dart'; import 'package:appflowy/plugins/base/emoji/emoji_text.dart'; import 'package:appflowy/plugins/document/presentation/document_collaborators.dart'; import 'package:appflowy/plugins/document/presentation/editor_notification.dart'; import 'package:appflowy/plugins/shared/sync_indicator.dart'; import 'package:appflowy/shared/feature_flags.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/reminder/reminder_bloc.dart'; import 'package:appflowy/workspace/application/favorite/favorite_bloc.dart'; import 'package:appflowy/workspace/application/view/view_bloc.dart'; import 'package:appflowy/workspace/application/view/view_ext.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-folder/view.pb.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class MobileViewPage extends StatefulWidget { const MobileViewPage({ super.key, required this.id, required this.viewLayout, this.title, this.arguments, }); /// view id final String id; final ViewLayoutPB viewLayout; final String? title; final Map<String, dynamic>? arguments; @override State<MobileViewPage> createState() => _MobileViewPageState(); } class _MobileViewPageState extends State<MobileViewPage> { late final Future<FlowyResult<ViewPB, FlowyError>> future; @override void initState() { super.initState(); future = ViewBackendService.getView(widget.id); } @override Widget build(BuildContext context) { return FutureBuilder( future: future, builder: (context, state) { Widget body; ViewPB? viewPB; final actions = <Widget>[]; if (state.connectionState != ConnectionState.done) { body = const Center( child: CircularProgressIndicator(), ); } else if (!state.hasData) { body = FlowyMobileStateContainer.error( emoji: '😔', title: LocaleKeys.error_weAreSorry.tr(), description: LocaleKeys.error_loadingViewError.tr(), errorMsg: state.error.toString(), ); } else { body = state.data!.fold((view) { viewPB = view; actions.addAll([ if (FeatureFlag.syncDocument.isOn) ...[ DocumentCollaborators( width: 60, height: 44, fontSize: 14, padding: const EdgeInsets.symmetric(vertical: 8), view: view, ), const HSpace(16.0), DocumentSyncIndicator(view: view), const HSpace(8.0), ], _buildAppBarMoreButton(view), ]); final plugin = view.plugin(arguments: widget.arguments ?? const {}) ..init(); return plugin.widgetBuilder.buildWidget(shrinkWrap: false); }, (error) { return FlowyMobileStateContainer.error( emoji: '😔', title: LocaleKeys.error_weAreSorry.tr(), description: LocaleKeys.error_loadingViewError.tr(), errorMsg: error.toString(), ); }); } if (viewPB != null) { return MultiBlocProvider( providers: [ BlocProvider( create: (_) => FavoriteBloc()..add(const FavoriteEvent.initial()), ), BlocProvider( create: (_) => ViewBloc(view: viewPB!)..add(const ViewEvent.initial()), ), BlocProvider.value( value: getIt<ReminderBloc>() ..add(const ReminderEvent.started()), ), ], child: Builder( builder: (context) { final view = context.watch<ViewBloc>().state.view; return _buildApp(view, actions, body); }, ), ); } else { return _buildApp(null, [], body); } }, ); } Widget _buildApp(ViewPB? view, List<Widget> actions, Widget child) { final icon = view?.icon.value; return Scaffold( appBar: FlowyAppBar( title: Row( mainAxisSize: MainAxisSize.min, children: [ if (icon != null && icon.isNotEmpty) EmojiText( emoji: '$icon ', fontSize: 22.0, ), Expanded( child: FlowyText.medium( view?.name ?? widget.title ?? '', fontSize: 15.0, overflow: TextOverflow.ellipsis, ), ), ], ), actions: actions, ), body: SafeArea(child: child), ); } Widget _buildAppBarMoreButton(ViewPB view) { return AppBarMoreButton( onTap: (context) { EditorNotification.exitEditing().post(); showMobileBottomSheet( context, showDragHandle: true, showDivider: false, backgroundColor: Theme.of(context).colorScheme.background, builder: (_) => _buildViewPageBottomSheet(context), ); }, ); } Widget _buildViewPageBottomSheet(BuildContext context) { final view = context.read<ViewBloc>().state.view; return ViewPageBottomSheet( view: view, onAction: (action) { switch (action) { case MobileViewBottomSheetBodyAction.duplicate: context.pop(); context.read<ViewBloc>().add(const ViewEvent.duplicate()); // show toast break; case MobileViewBottomSheetBodyAction.share: // unimplemented context.pop(); break; case MobileViewBottomSheetBodyAction.delete: // pop to home page context ..pop() ..pop(); context.read<ViewBloc>().add(const ViewEvent.delete()); break; case MobileViewBottomSheetBodyAction.addToFavorites: case MobileViewBottomSheetBodyAction.removeFromFavorites: context.pop(); context.read<FavoriteBloc>().add(FavoriteEvent.toggle(view)); break; case MobileViewBottomSheetBodyAction.undo: EditorNotification.undo().post(); context.pop(); break; case MobileViewBottomSheetBodyAction.redo: EditorNotification.redo().post(); context.pop(); break; case MobileViewBottomSheetBodyAction.helpCenter: // unimplemented context.pop(); break; case MobileViewBottomSheetBodyAction.rename: // no need to implement, rename is handled by the onRename callback. throw UnimplementedError(); } }, onRename: (name) { if (name != view.name) { context.read<ViewBloc>().add(ViewEvent.rename(name)); } context.pop(); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/box_container.dart
import 'package:flutter/material.dart'; class FlowyBoxContainer extends StatelessWidget { const FlowyBoxContainer({ super.key, required this.child, }); final Widget child; @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric( horizontal: 6.0, vertical: 8.0, ), decoration: BoxDecoration( border: Border.all( color: Theme.of(context).colorScheme.onSecondary, ), borderRadius: BorderRadius.circular(8.0), ), child: child, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/app_bar.dart
import 'package:appflowy/mobile/presentation/base/app_bar_actions.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; enum FlowyAppBarLeadingType { back, close, cancel; Widget getWidget(VoidCallback? onTap) { switch (this) { case FlowyAppBarLeadingType.back: return AppBarBackButton(onTap: onTap); case FlowyAppBarLeadingType.close: return AppBarCloseButton(onTap: onTap); case FlowyAppBarLeadingType.cancel: return AppBarCancelButton(onTap: onTap); } } double? get width { switch (this) { case FlowyAppBarLeadingType.back: return 40.0; case FlowyAppBarLeadingType.close: return 40.0; case FlowyAppBarLeadingType.cancel: return 120; } } } class FlowyAppBar extends AppBar { FlowyAppBar({ super.key, super.actions, Widget? title, String? titleText, FlowyAppBarLeadingType leadingType = FlowyAppBarLeadingType.back, super.centerTitle, VoidCallback? onTapLeading, bool showDivider = true, }) : super( title: title ?? FlowyText( titleText ?? '', fontSize: 15.0, fontWeight: FontWeight.w500, ), titleSpacing: 0, elevation: 0, leading: leadingType.getWidget(onTapLeading), leadingWidth: leadingType.width, toolbarHeight: 44.0, bottom: showDivider ? const PreferredSize( preferredSize: Size.fromHeight(0.5), child: Divider( height: 0.5, ), ) : null, ); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/mobile/presentation/base/app_bar_actions.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class AppBarBackButton extends StatelessWidget { const AppBarBackButton({ super.key, this.onTap, this.padding, }); final VoidCallback? onTap; final EdgeInsetsGeometry? padding; @override Widget build(BuildContext context) { return AppBarButton( onTap: onTap ?? () => Navigator.pop(context), padding: padding, child: const FlowySvg( FlowySvgs.m_app_bar_back_s, ), ); } } class AppBarCloseButton extends StatelessWidget { const AppBarCloseButton({ super.key, this.onTap, }); final VoidCallback? onTap; @override Widget build(BuildContext context) { return AppBarButton( onTap: onTap ?? () => Navigator.pop(context), child: const FlowySvg( FlowySvgs.m_app_bar_close_s, ), ); } } class AppBarCancelButton extends StatelessWidget { const AppBarCancelButton({ super.key, this.onTap, }); final VoidCallback? onTap; @override Widget build(BuildContext context) { return AppBarButton( onTap: onTap ?? () => Navigator.pop(context), child: FlowyText( LocaleKeys.button_cancel.tr(), overflow: TextOverflow.ellipsis, ), ); } } class AppBarDoneButton extends StatelessWidget { const AppBarDoneButton({ super.key, required this.onTap, }); final VoidCallback onTap; @override Widget build(BuildContext context) { return AppBarButton( onTap: onTap, padding: const EdgeInsets.all(12), child: FlowyText( LocaleKeys.button_done.tr(), color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.w500, textAlign: TextAlign.right, ), ); } } class AppBarSaveButton extends StatelessWidget { const AppBarSaveButton({ super.key, required this.onTap, this.enable = true, this.padding = const EdgeInsets.all(12), }); final VoidCallback onTap; final bool enable; final EdgeInsetsGeometry padding; @override Widget build(BuildContext context) { return AppBarButton( onTap: () { if (enable) { onTap(); } }, padding: padding, child: FlowyText( LocaleKeys.button_save.tr(), color: enable ? Theme.of(context).colorScheme.primary : Theme.of(context).disabledColor, fontWeight: FontWeight.w500, textAlign: TextAlign.right, ), ); } } class AppBarFilledDoneButton extends StatelessWidget { const AppBarFilledDoneButton({super.key, required this.onTap}); final VoidCallback onTap; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(8, 4, 8, 8), child: TextButton( style: TextButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), elevation: 0, visualDensity: VisualDensity.compact, tapTargetSize: MaterialTapTargetSize.shrinkWrap, enableFeedback: true, backgroundColor: Theme.of(context).primaryColor, ), onPressed: onTap, child: FlowyText.medium( LocaleKeys.button_done.tr(), fontSize: 16, color: Theme.of(context).colorScheme.onPrimary, overflow: TextOverflow.ellipsis, ), ), ); } } class AppBarMoreButton extends StatelessWidget { const AppBarMoreButton({ super.key, required this.onTap, }); final void Function(BuildContext context) onTap; @override Widget build(BuildContext context) { return AppBarButton( padding: const EdgeInsets.all(12), onTap: () => onTap(context), child: const FlowySvg(FlowySvgs.three_dots_s), ); } } class AppBarButton extends StatelessWidget { const AppBarButton({ super.key, required this.onTap, required this.child, this.padding, }); final VoidCallback onTap; final Widget child; final EdgeInsetsGeometry? padding; @override Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: onTap, child: Padding( padding: padding ?? const EdgeInsets.all(12), child: child, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/string_extension.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:appflowy/shared/patterns/common_patterns.dart'; extension StringExtension on String { static const _specialCharacters = r'\/:*?"<>| '; /// Encode a string to a file name. /// /// Normalizes the string to remove special characters and replaces the "\/:*?"<>|" with underscores. String toFileName() { final buffer = StringBuffer(); for (final character in characters) { if (_specialCharacters.contains(character)) { buffer.write('_'); } else { buffer.write(character); } } return buffer.toString(); } /// Returns the file size of the file at the given path. /// /// Returns null if the file does not exist. int? get fileSize { final file = File(this); if (file.existsSync()) { return file.lengthSync(); } return null; } /// Returns true if the string is a appflowy cloud url. bool get isAppFlowyCloudUrl => appflowyCloudUrlRegex.hasMatch(this); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/json_print.dart
import 'dart:convert'; import 'package:appflowy_backend/log.dart'; import 'package:flutter/material.dart'; const JsonEncoder _encoder = JsonEncoder.withIndent(' '); void prettyPrintJson(Object? object) { Log.trace(_encoder.convert(object)); debugPrint(_encoder.convert(object)); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/file_extension.dart
import 'dart:io'; extension FileSizeExtension on String { int? get fileSize { final file = File(this); if (file.existsSync()) { return file.lengthSync(); } return null; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/int64_extension.dart
import 'package:fixnum/fixnum.dart'; extension DateConversion on Int64 { DateTime toDateTime() => DateTime.fromMillisecondsSinceEpoch(toInt() * 1000); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/google_font_family_extension.dart
import 'package:appflowy/shared/patterns/common_patterns.dart'; extension GoogleFontsParser on String { String parseFontFamilyName() => replaceAll('_regular', '') .replaceAllMapped(camelCaseRegex, (m) => ' ${m.group(0)}'); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/base64_string.dart
import 'dart:convert'; extension Base64Encode on String { String get base64 => base64Encode(utf8.encode(this)); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/throttle.dart
import 'dart:async'; class Throttler { Throttler({ this.duration = const Duration(milliseconds: 1000), }); final Duration duration; Timer? _timer; void call(Function callback) { if (_timer?.isActive ?? false) return; _timer = Timer(duration, () { callback(); }); } void dispose() { _timer?.cancel(); _timer = null; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/share_log_files.dart
import 'dart:io'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:archive/archive_io.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; Future<void> shareLogFiles(BuildContext? context) async { final dir = await getApplicationSupportDirectory(); final zipEncoder = ZipEncoder(); final archiveLogFiles = dir .listSync(recursive: true) .where((e) => p.basename(e.path).startsWith('log.')) .map((e) { final bytes = File(e.path).readAsBytesSync(); return ArchiveFile(p.basename(e.path), bytes.length, bytes); }); if (archiveLogFiles.isEmpty) { if (context != null && context.mounted) { showSnackBarMessage( context, LocaleKeys.noLogFiles.tr(), ); } return; } final archive = Archive(); for (final file in archiveLogFiles) { archive.addFile(file); } final zip = zipEncoder.encode(archive); if (zip == null) { return; } // create a zipped appflowy logs file final path = Platform.isAndroid ? '/storage/emulated/0/Download' : dir.path; final zipFile = await File(p.join(path, 'appflowy_logs.zip')).writeAsBytes(zip); if (Platform.isIOS) { await Share.shareUri(zipFile.uri); } else { await Share.shareXFiles([XFile(zipFile.path)]); } // delete the zipped appflowy logs file await zipFile.delete(); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/color_to_hex_string.dart
import 'dart:math' as math; import 'package:flutter/material.dart'; extension ColorExtension on Color { /// return a hex string in 0xff000000 format String toHexString() { return '0x${value.toRadixString(16).padLeft(8, '0')}'; } /// return a random color static Color random({double opacity = 1.0}) { return Color((math.Random().nextDouble() * 0xFFFFFF).toInt()) .withOpacity(opacity); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/theme_mode_extension.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; extension LabelTextPhrasing on ThemeMode { String get labelText => switch (this) { ThemeMode.light => LocaleKeys.settings_appearance_themeMode_light.tr(), ThemeMode.dark => LocaleKeys.settings_appearance_themeMode_dark.tr(), ThemeMode.system => LocaleKeys.settings_appearance_themeMode_system.tr(), }; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/debounce.dart
import 'dart:async'; class Debounce { Debounce({ this.duration = const Duration(milliseconds: 1000), }); final Duration duration; Timer? _timer; void call(Function action) { dispose(); _timer = Timer(duration, () { action(); }); } void dispose() { _timer?.cancel(); _timer = null; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/field_type_extension.dart
import 'dart:ui'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:easy_localization/easy_localization.dart'; extension FieldTypeExtension on FieldType { String get i18n => switch (this) { FieldType.RichText => LocaleKeys.grid_field_textFieldName.tr(), FieldType.Number => LocaleKeys.grid_field_numberFieldName.tr(), FieldType.DateTime => LocaleKeys.grid_field_dateFieldName.tr(), FieldType.SingleSelect => LocaleKeys.grid_field_singleSelectFieldName.tr(), FieldType.MultiSelect => LocaleKeys.grid_field_multiSelectFieldName.tr(), FieldType.Checkbox => LocaleKeys.grid_field_checkboxFieldName.tr(), FieldType.Checklist => LocaleKeys.grid_field_checklistFieldName.tr(), FieldType.URL => LocaleKeys.grid_field_urlFieldName.tr(), FieldType.LastEditedTime => LocaleKeys.grid_field_updatedAtFieldName.tr(), FieldType.CreatedTime => LocaleKeys.grid_field_createdAtFieldName.tr(), FieldType.Relation => LocaleKeys.grid_field_relationFieldName.tr(), _ => throw UnimplementedError(), }; FlowySvgData get svgData => switch (this) { FieldType.RichText => FlowySvgs.text_s, FieldType.Number => FlowySvgs.number_s, FieldType.DateTime => FlowySvgs.date_s, FieldType.SingleSelect => FlowySvgs.single_select_s, FieldType.MultiSelect => FlowySvgs.multiselect_s, FieldType.Checkbox => FlowySvgs.checkbox_s, FieldType.URL => FlowySvgs.url_s, FieldType.Checklist => FlowySvgs.checklist_s, FieldType.LastEditedTime => FlowySvgs.last_modified_s, FieldType.CreatedTime => FlowySvgs.created_at_s, FieldType.Relation => FlowySvgs.relation_s, _ => throw UnimplementedError(), }; Color get mobileIconBackgroundColor => switch (this) { FieldType.RichText => const Color(0xFFBECCFF), FieldType.Number => const Color(0xFFCABDFF), FieldType.URL => const Color(0xFFFFB9EF), FieldType.SingleSelect => const Color(0xFFBECCFF), FieldType.MultiSelect => const Color(0xFFBECCFF), FieldType.DateTime => const Color(0xFFFDEDA7), FieldType.LastEditedTime => const Color(0xFFFDEDA7), FieldType.CreatedTime => const Color(0xFFFDEDA7), FieldType.Checkbox => const Color(0xFF98F4CD), FieldType.Checklist => const Color(0xFF98F4CD), FieldType.Relation => const Color(0xFFFDEDA7), _ => throw UnimplementedError(), }; // TODO(RS): inner icon color isn't always white Color get mobileIconBackgroundColorDark => switch (this) { FieldType.RichText => const Color(0xFF6859A7), FieldType.Number => const Color(0xFF6859A7), FieldType.URL => const Color(0xFFA75C96), FieldType.SingleSelect => const Color(0xFF5366AB), FieldType.MultiSelect => const Color(0xFF5366AB), FieldType.DateTime => const Color(0xFFB0A26D), FieldType.LastEditedTime => const Color(0xFFB0A26D), FieldType.CreatedTime => const Color(0xFFB0A26D), FieldType.Checkbox => const Color(0xFF42AD93), FieldType.Checklist => const Color(0xFF42AD93), FieldType.Relation => const Color(0xFFFDEDA7), _ => throw UnimplementedError(), }; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/util/color_generator/color_generator.dart
import 'package:flutter/material.dart'; extension type ColorGenerator(String value) { Color toColor() { final int hash = value.codeUnits.fold(0, (int acc, int unit) => acc + unit); final double hue = (hash % 360).toDouble(); return HSLColor.fromAHSL(1.0, hue, 0.5, 0.8).toColor(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/startup.dart
import 'dart:async'; import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/startup/tasks/feature_flag_task.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy_backend/appflowy_backend.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'deps_resolver.dart'; import 'entry_point.dart'; import 'launch_configuration.dart'; import 'plugin/plugin.dart'; import 'tasks/prelude.dart'; final getIt = GetIt.instance; abstract class EntryPoint { Widget create(LaunchConfiguration config); } class FlowyRunnerContext { FlowyRunnerContext({required this.applicationDataDirectory}); final Directory applicationDataDirectory; } Future<void> runAppFlowy({bool isAnon = false}) async { if (kReleaseMode) { await FlowyRunner.run( AppFlowyApplication(), integrationMode(), isAnon: isAnon, ); } else { // When running the app in integration test mode, we need to // specify the mode to run the app again. await FlowyRunner.run( AppFlowyApplication(), FlowyRunner.currentMode, didInitGetItCallback: IntegrationTestHelper.didInitGetItCallback, rustEnvsBuilder: IntegrationTestHelper.rustEnvsBuilder, isAnon: isAnon, ); } } class FlowyRunner { // This variable specifies the initial mode of the app when it is launched for the first time. // The same mode will be automatically applied in subsequent executions when the runAppFlowy() // method is called. static var currentMode = integrationMode(); static Future<FlowyRunnerContext> run( EntryPoint f, IntegrationMode mode, { // This callback is triggered after the initialization of 'getIt', // which is used for dependency injection throughout the app. // If your functionality depends on 'getIt', ensure to register // your callback here to execute any necessary actions post-initialization. Future Function()? didInitGetItCallback, // Passing the envs to the backend Map<String, String> Function()? rustEnvsBuilder, // Indicate whether the app is running in anonymous mode. // Note: when the app is running in anonymous mode, the user no need to // sign in, and the app will only save the data in the local storage. bool isAnon = false, }) async { currentMode = mode; // Only set the mode when it's not release mode if (!kReleaseMode) { IntegrationTestHelper.didInitGetItCallback = didInitGetItCallback; IntegrationTestHelper.rustEnvsBuilder = rustEnvsBuilder; } // Clear and dispose tasks from previous AppLaunch if (getIt.isRegistered(instance: AppLauncher)) { await getIt<AppLauncher>().dispose(); } // Clear all the states in case of rebuilding. await getIt.reset(); final config = LaunchConfiguration( isAnon: isAnon, // Unit test can't use the package_info_plus plugin version: mode.isUnitTest ? '1.0.0' : await PackageInfo.fromPlatform().then((value) => value.version), rustEnvs: rustEnvsBuilder?.call() ?? {}, ); // Specify the env await initGetIt(getIt, mode, f, config); await didInitGetItCallback?.call(); final applicationDataDirectory = await getIt<ApplicationDataStorage>().getPath().then( (value) => Directory(value), ); // add task final launcher = getIt<AppLauncher>(); launcher.addTasks( [ // this task should be first task, for handling platform errors. // don't catch errors in test mode if (!mode.isUnitTest) const PlatformErrorCatcherTask(), // this task should be second task, for handling memory leak. // there's a flag named _enable in memory_leak_detector.dart. If it's false, the task will be ignored. MemoryLeakDetectorTask(), const DebugTask(), const FeatureFlagTask(), // localization const InitLocalizationTask(), // init the app window const InitAppWindowTask(), // Init Rust SDK InitRustSDKTask(customApplicationPath: applicationDataDirectory), // Load Plugins, like document, grid ... const PluginLoadTask(), // init the app widget // ignore in test mode if (!mode.isUnitTest) ...[ // The DeviceOrApplicationInfoTask should be placed before the AppWidgetTask to fetch the app information. // It is unable to get the device information from the test environment. const ApplicationInfoTask(), const HotKeyTask(), if (isSupabaseEnabled) InitSupabaseTask(), if (isAppFlowyCloudEnabled) InitAppFlowyCloudTask(), const InitAppWidgetTask(), const InitPlatformServiceTask(), ], ], ); await launcher.launch(); // execute the tasks return FlowyRunnerContext( applicationDataDirectory: applicationDataDirectory, ); } } Future<void> initGetIt( GetIt getIt, IntegrationMode mode, EntryPoint f, LaunchConfiguration config, ) async { getIt.registerFactory<EntryPoint>(() => f); getIt.registerLazySingleton<FlowySDK>( () { return FlowySDK(); }, dispose: (sdk) async { await sdk.dispose(); }, ); getIt.registerLazySingleton<AppLauncher>( () => AppLauncher( context: LaunchContext( getIt, mode, config, ), ), dispose: (launcher) async { await launcher.dispose(); }, ); getIt.registerSingleton<PluginSandbox>(PluginSandbox()); await DependencyResolver.resolve(getIt, mode); } class LaunchContext { LaunchContext(this.getIt, this.env, this.config); GetIt getIt; IntegrationMode env; LaunchConfiguration config; } enum LaunchTaskType { dataProcessing, appLauncher, } /// The interface of an app launch task, which will trigger /// some nonresident indispensable task in app launching task. abstract class LaunchTask { const LaunchTask(); LaunchTaskType get type => LaunchTaskType.dataProcessing; Future<void> initialize(LaunchContext context); Future<void> dispose(); } class AppLauncher { AppLauncher({ required this.context, }); final LaunchContext context; final List<LaunchTask> tasks = []; void addTask(LaunchTask task) { tasks.add(task); } void addTasks(Iterable<LaunchTask> tasks) { this.tasks.addAll(tasks); } Future<void> launch() async { for (final task in tasks) { await task.initialize(context); } } Future<void> dispose() async { for (final task in tasks) { await task.dispose(); } tasks.clear(); } } enum IntegrationMode { develop, release, unitTest, integrationTest; // test mode bool get isTest => isUnitTest || isIntegrationTest; bool get isUnitTest => this == IntegrationMode.unitTest; bool get isIntegrationTest => this == IntegrationMode.integrationTest; // release mode bool get isRelease => this == IntegrationMode.release; // develop mode bool get isDevelop => this == IntegrationMode.develop; } IntegrationMode integrationMode() { if (Platform.environment.containsKey('FLUTTER_TEST')) { return IntegrationMode.unitTest; } if (kReleaseMode) { return IntegrationMode.release; } return IntegrationMode.develop; } /// Only used for integration test class IntegrationTestHelper { static Future Function()? didInitGetItCallback; static Map<String, String> Function()? rustEnvsBuilder; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/deps_resolver.dart
import 'package:appflowy/core/config/kv.dart'; import 'package:appflowy/core/network_monitor.dart'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/plugins/document/application/prelude.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_client.dart'; import 'package:appflowy/plugins/trash/application/prelude.dart'; import 'package:appflowy/shared/appflowy_cache_manager.dart'; import 'package:appflowy/shared/custom_image_cache_manager.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/tasks/appflowy_cloud_task.dart'; import 'package:appflowy/user/application/auth/af_cloud_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/application/auth/supabase_auth_service.dart'; import 'package:appflowy/user/application/prelude.dart'; import 'package:appflowy/user/application/reminder/reminder_bloc.dart'; import 'package:appflowy/user/application/user_listener.dart'; import 'package:appflowy/user/application/user_service.dart'; import 'package:appflowy/user/presentation/router.dart'; import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart'; import 'package:appflowy/workspace/application/edit_panel/edit_panel_bloc.dart'; import 'package:appflowy/workspace/application/favorite/favorite_bloc.dart'; import 'package:appflowy/workspace/application/settings/appearance/base_appearance.dart'; import 'package:appflowy/workspace/application/settings/appearance/desktop_appearance.dart'; import 'package:appflowy/workspace/application/settings/appearance/mobile_appearance.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/application/sidebar/rename_view/rename_view_bloc.dart'; import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart'; import 'package:appflowy/workspace/application/user/prelude.dart'; import 'package:appflowy/workspace/application/view/prelude.dart'; import 'package:appflowy/workspace/application/workspace/prelude.dart'; import 'package:appflowy/workspace/presentation/home/menu/menu_shared_state.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:flowy_infra/file_picker/file_picker_impl.dart'; import 'package:flowy_infra/file_picker/file_picker_service.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get_it/get_it.dart'; import 'package:http/http.dart' as http; class DependencyResolver { static Future<void> resolve( GetIt getIt, IntegrationMode mode, ) async { // getIt.registerFactory<KeyValueStorage>(() => RustKeyValue()); getIt.registerFactory<KeyValueStorage>(() => DartKeyValue()); await _resolveCloudDeps(getIt); _resolveUserDeps(getIt, mode); _resolveHomeDeps(getIt); _resolveFolderDeps(getIt); _resolveCommonService(getIt, mode); } } Future<void> _resolveCloudDeps(GetIt getIt) async { final env = await AppFlowyCloudSharedEnv.fromEnv(); Log.info("cloud setting: $env"); getIt.registerFactory<AppFlowyCloudSharedEnv>(() => env); if (isAppFlowyCloudEnabled) { getIt.registerSingleton( AppFlowyCloudDeepLink(), dispose: (obj) async { await obj.dispose(); }, ); } } void _resolveCommonService( GetIt getIt, IntegrationMode mode, ) async { getIt.registerFactory<FilePickerService>(() => FilePicker()); if (mode.isTest) { getIt.registerFactory<ApplicationDataStorage>( () => MockApplicationDataStorage(), ); } else { getIt.registerFactory<ApplicationDataStorage>( () => ApplicationDataStorage(), ); } getIt.registerFactoryAsync<OpenAIRepository>( () async { final result = await UserBackendService.getCurrentUserProfile(); return result.fold( (s) { return HttpOpenAIRepository( client: http.Client(), apiKey: s.openaiKey, ); }, (e) { throw Exception('Failed to get user profile: ${e.msg}'); }, ); }, ); getIt.registerFactoryAsync<StabilityAIRepository>( () async { final result = await UserBackendService.getCurrentUserProfile(); return result.fold( (s) { return HttpStabilityAIRepository( client: http.Client(), apiKey: s.stabilityAiKey, ); }, (e) { throw Exception('Failed to get user profile: ${e.msg}'); }, ); }, ); getIt.registerFactory<ClipboardService>( () => ClipboardService(), ); // theme getIt.registerFactory<BaseAppearance>( () => PlatformExtension.isMobile ? MobileAppearance() : DesktopAppearance(), ); getIt.registerFactory<FlowyCacheManager>( () => FlowyCacheManager() ..registerCache(TemporaryDirectoryCache()) ..registerCache(CustomImageCacheManager()) ..registerCache(FeatureFlagCache()), ); } void _resolveUserDeps(GetIt getIt, IntegrationMode mode) { switch (currentCloudType()) { case AuthenticatorType.local: getIt.registerFactory<AuthService>( () => BackendAuthService( AuthenticatorPB.Local, ), ); break; case AuthenticatorType.supabase: getIt.registerFactory<AuthService>(() => SupabaseAuthService()); break; case AuthenticatorType.appflowyCloud: case AuthenticatorType.appflowyCloudSelfHost: case AuthenticatorType.appflowyCloudDevelop: getIt.registerFactory<AuthService>(() => AppFlowyCloudAuthService()); break; } getIt.registerFactory<AuthRouter>(() => AuthRouter()); getIt.registerFactory<SignInBloc>( () => SignInBloc(getIt<AuthService>()), ); getIt.registerFactory<SignUpBloc>( () => SignUpBloc(getIt<AuthService>()), ); getIt.registerFactory<SplashRouter>(() => SplashRouter()); getIt.registerFactory<EditPanelBloc>(() => EditPanelBloc()); getIt.registerFactory<SplashBloc>(() => SplashBloc()); getIt.registerLazySingleton<NetworkListener>(() => NetworkListener()); } void _resolveHomeDeps(GetIt getIt) { getIt.registerSingleton(FToast()); getIt.registerSingleton(MenuSharedState()); getIt.registerFactoryParam<UserListener, UserProfilePB, void>( (user, _) => UserListener(userProfile: user), ); getIt.registerFactoryParam<WorkspaceBloc, UserProfilePB, void>( (user, _) => WorkspaceBloc( userService: UserBackendService(userId: user.id), ), ); // share getIt.registerFactoryParam<DocumentShareBloc, ViewPB, void>( (view, _) => DocumentShareBloc(view: view), ); getIt.registerSingleton<ActionNavigationBloc>(ActionNavigationBloc()); getIt.registerLazySingleton<TabsBloc>(() => TabsBloc()); getIt.registerSingleton<ReminderBloc>(ReminderBloc()); getIt.registerSingleton<RenameViewBloc>(RenameViewBloc(PopoverController())); } void _resolveFolderDeps(GetIt getIt) { //workspace getIt.registerFactoryParam<WorkspaceListener, UserProfilePB, String>( (user, workspaceId) => WorkspaceListener( user: user, workspaceId: workspaceId, ), ); getIt.registerFactoryParam<ViewBloc, ViewPB, void>( (view, _) => ViewBloc( view: view, ), ); //Settings getIt.registerFactoryParam<SettingsDialogBloc, UserProfilePB, void>( (user, _) => SettingsDialogBloc(user), ); //User getIt.registerFactoryParam<SettingsUserViewBloc, UserProfilePB, void>( (user, _) => SettingsUserViewBloc(user), ); // trash getIt.registerLazySingleton<TrashService>(() => TrashService()); getIt.registerLazySingleton<TrashListener>(() => TrashListener()); getIt.registerFactory<TrashBloc>( () => TrashBloc(), ); getIt.registerFactory<FavoriteBloc>(() => FavoriteBloc()); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/launch_configuration.dart
class LaunchConfiguration { const LaunchConfiguration({ this.isAnon = false, required this.version, required this.rustEnvs, }); // APP will automatically register after launching. final bool isAnon; final String version; // final Map<String, String> rustEnvs; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/entry_point.dart
import 'package:appflowy/startup/launch_configuration.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/presentation/screens/splash_screen.dart'; import 'package:flutter/material.dart'; class AppFlowyApplication implements EntryPoint { @override Widget create(LaunchConfiguration config) { return SplashScreen( isAnon: config.isAnon, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/plugin/plugin.dart
library flowy_plugin; import 'package:flutter/widgets.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/presentation/home/home_stack.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; export "./src/sandbox.dart"; enum PluginType { editor, blank, trash, grid, board, calendar, } typedef PluginId = String; abstract class Plugin<T> { PluginId get id; PluginWidgetBuilder get widgetBuilder; PluginNotifier? get notifier => null; PluginType get pluginType; void init() {} void dispose() { notifier?.dispose(); } } abstract class PluginNotifier<T> { /// Notify if the plugin get deleted ValueNotifier<T> get isDeleted; void dispose() {} } abstract class PluginBuilder { Plugin build(dynamic data); String get menuName; FlowySvgData get icon; /// The type of this [Plugin]. Each [Plugin] should have a unique [PluginType] PluginType get pluginType; /// The layoutType is used in the backend to determine the layout of the view. /// Currently, AppFlowy supports 4 layout types: Document, Grid, Board, Calendar. ViewLayoutPB? get layoutType => ViewLayoutPB.Document; } abstract class PluginConfig { // Return false will disable the user to create it. For example, a trash plugin shouldn't be created by the user, bool get creatable => true; } abstract class PluginWidgetBuilder with NavigationItem { List<NavigationItem> get navigationItems; EdgeInsets get contentPadding => const EdgeInsets.symmetric(horizontal: 40, vertical: 28); Widget buildWidget({PluginContext? context, required bool shrinkWrap}); } class PluginContext { PluginContext({required this.onDeleted}); // calls when widget of the plugin get deleted final Function(ViewPB, int?) onDeleted; } void registerPlugin({required PluginBuilder builder, PluginConfig? config}) { getIt<PluginSandbox>() .registerPlugin(builder.pluginType, builder, config: config); } /// Make the correct plugin from the [pluginType] and [data]. If the plugin /// is not registered, it will return a blank plugin. Plugin makePlugin({required PluginType pluginType, dynamic data}) { final plugin = getIt<PluginSandbox>().buildPlugin(pluginType, data); return plugin; } List<PluginBuilder> pluginBuilders() { final pluginBuilders = getIt<PluginSandbox>().builders; final pluginConfigs = getIt<PluginSandbox>().pluginConfigs; return pluginBuilders.where( (builder) { final config = pluginConfigs[builder.pluginType]?.creatable; return config ?? true; }, ).toList(); } enum FlowyPluginException { invalidData, }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/plugin
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/plugin/src/sandbox.dart
import 'dart:collection'; import 'package:appflowy/plugins/blank/blank.dart'; import 'package:flutter/services.dart'; import '../plugin.dart'; import 'runner.dart'; class PluginSandbox { PluginSandbox() { pluginRunner = PluginRunner(); } final LinkedHashMap<PluginType, PluginBuilder> _pluginBuilders = LinkedHashMap(); final Map<PluginType, PluginConfig> _pluginConfigs = <PluginType, PluginConfig>{}; late PluginRunner pluginRunner; int indexOf(PluginType pluginType) { final index = _pluginBuilders.keys.toList().indexWhere((ty) => ty == pluginType); if (index == -1) { throw PlatformException( code: '-1', message: "Can't find the flowy plugin type: $pluginType", ); } return index; } /// Build a plugin from [data] with [pluginType] /// If the [pluginType] is not registered, it will return a blank plugin Plugin buildPlugin(PluginType pluginType, dynamic data) { final builder = _pluginBuilders[pluginType] ?? BlankPluginBuilder(); return builder.build(data); } void registerPlugin( PluginType pluginType, PluginBuilder builder, { PluginConfig? config, }) { if (_pluginBuilders.containsKey(pluginType)) { return; } _pluginBuilders[pluginType] = builder; if (config != null) { _pluginConfigs[pluginType] = config; } } List<PluginType> get supportPluginTypes => _pluginBuilders.keys.toList(); List<PluginBuilder> get builders => _pluginBuilders.values.toList(); Map<PluginType, PluginConfig> get pluginConfigs => _pluginConfigs; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/plugin
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/plugin/src/runner.dart
class PluginRunner {}
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/app_window_size_manager.dart
import 'dart:convert'; import 'dart:ui'; import 'package:appflowy/core/config/kv.dart'; import 'package:appflowy/core/config/kv_keys.dart'; import 'package:appflowy/startup/startup.dart'; class WindowSizeManager { static const double minWindowHeight = 600.0; static const double minWindowWidth = 800.0; // Preventing failed assertion due to Texture Descriptor Validation static const double maxWindowHeight = 8192.0; static const double maxWindowWidth = 8192.0; static const width = 'width'; static const height = 'height'; static const String dx = 'dx'; static const String dy = 'dy'; Future<void> setSize(Size size) async { final windowSize = { height: size.height.clamp(minWindowHeight, maxWindowHeight), width: size.width.clamp(minWindowWidth, maxWindowWidth), }; await getIt<KeyValueStorage>().set( KVKeys.windowSize, jsonEncode(windowSize), ); } Future<Size> getSize() async { final defaultWindowSize = jsonEncode( {WindowSizeManager.height: 600.0, WindowSizeManager.width: 800.0}, ); final windowSize = await getIt<KeyValueStorage>().get(KVKeys.windowSize); final size = json.decode( windowSize ?? defaultWindowSize, ); final double width = size[WindowSizeManager.width] ?? minWindowWidth; final double height = size[WindowSizeManager.height] ?? minWindowHeight; return Size( width.clamp(minWindowWidth, maxWindowWidth), height.clamp(minWindowHeight, maxWindowHeight), ); } Future<void> setPosition(Offset offset) async { await getIt<KeyValueStorage>().set( KVKeys.windowPosition, jsonEncode({ dx: offset.dx, dy: offset.dy, }), ); } Future<Offset?> getPosition() async { final position = await getIt<KeyValueStorage>().get(KVKeys.windowPosition); if (position == null) { return null; } final offset = json.decode(position); return Offset(offset[dx], offset[dy]); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/app_widget.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/reminder/reminder_bloc.dart'; import 'package:appflowy/user/application/user_settings_service.dart'; import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart'; import 'package:appflowy/workspace/application/action_navigation/navigation_action.dart'; import 'package:appflowy/workspace/application/notification/notification_service.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:appflowy/workspace/application/settings/notifications/notification_settings_cubit.dart'; import 'package:appflowy/workspace/application/sidebar/rename_view/rename_view_bloc.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy/workspace/presentation/command_palette/command_palette.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/theme.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'prelude.dart'; class InitAppWidgetTask extends LaunchTask { const InitAppWidgetTask(); @override LaunchTaskType get type => LaunchTaskType.appLauncher; @override Future<void> initialize(LaunchContext context) async { WidgetsFlutterBinding.ensureInitialized(); await NotificationService.initialize(); final widget = context.getIt<EntryPoint>().create(context.config); final appearanceSetting = await UserSettingsBackendService().getAppearanceSetting(); final dateTimeSettings = await UserSettingsBackendService().getDateTimeSettings(); // If the passed-in context is not the same as the context of the // application widget, the application widget will be rebuilt. final app = ApplicationWidget( key: ValueKey(context), appearanceSetting: appearanceSetting, dateTimeSettings: dateTimeSettings, appTheme: await appTheme(appearanceSetting.theme), child: widget, ); Bloc.observer = ApplicationBlocObserver(); runApp( EasyLocalization( supportedLocales: const [ // In alphabetical order Locale('am', 'ET'), Locale('ar', 'SA'), Locale('ca', 'ES'), Locale('cs', 'CZ'), Locale('ckb', 'KU'), Locale('de', 'DE'), Locale('en'), Locale('es', 'VE'), Locale('eu', 'ES'), Locale('el', 'GR'), Locale('fr', 'FR'), Locale('fr', 'CA'), Locale('hu', 'HU'), Locale('id', 'ID'), Locale('it', 'IT'), Locale('ja', 'JP'), Locale('ko', 'KR'), Locale('pl', 'PL'), Locale('pt', 'BR'), Locale('ru', 'RU'), Locale('sv', 'SE'), Locale('th', 'TH'), Locale('tr', 'TR'), Locale('uk', 'UA'), Locale('ur'), Locale('vi', 'VN'), Locale('zh', 'CN'), Locale('zh', 'TW'), Locale('fa'), Locale('hin'), ], path: 'assets/translations', fallbackLocale: const Locale('en'), useFallbackTranslations: true, child: app, ), ); return; } @override Future<void> dispose() async {} } class ApplicationWidget extends StatefulWidget { const ApplicationWidget({ super.key, required this.child, required this.appTheme, required this.appearanceSetting, required this.dateTimeSettings, }); final Widget child; final AppTheme appTheme; final AppearanceSettingsPB appearanceSetting; final DateTimeSettingsPB dateTimeSettings; @override State<ApplicationWidget> createState() => _ApplicationWidgetState(); } class _ApplicationWidgetState extends State<ApplicationWidget> { late final GoRouter routerConfig; @override void initState() { super.initState(); // avoid rebuild routerConfig when the appTheme is changed. routerConfig = generateRouter(widget.child); } @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider<AppearanceSettingsCubit>( create: (_) => AppearanceSettingsCubit( widget.appearanceSetting, widget.dateTimeSettings, widget.appTheme, )..readLocaleWhenAppLaunch(context), ), BlocProvider<NotificationSettingsCubit>( create: (_) => NotificationSettingsCubit(), ), BlocProvider<DocumentAppearanceCubit>( create: (_) => DocumentAppearanceCubit()..fetch(), ), BlocProvider.value(value: getIt<RenameViewBloc>()), BlocProvider.value( value: getIt<ActionNavigationBloc>() ..add(const ActionNavigationEvent.initialize()), ), BlocProvider.value( value: getIt<ReminderBloc>()..add(const ReminderEvent.started()), ), ], child: BlocListener<ActionNavigationBloc, ActionNavigationState>( listenWhen: (_, curr) => curr.action != null, listener: (context, state) { final action = state.action; WidgetsBinding.instance.addPostFrameCallback((_) { if (action?.type == ActionType.openView && PlatformExtension.isDesktop) { final view = action!.arguments?[ActionArgumentKeys.view]; if (view != null) { AppGlobals.rootNavKey.currentContext?.pushView(view); } } else if (action?.type == ActionType.openRow && PlatformExtension.isMobile) { final view = action!.arguments?[ActionArgumentKeys.view]; if (view != null) { final view = action.arguments?[ActionArgumentKeys.view]; final rowId = action.arguments?[ActionArgumentKeys.rowId]; AppGlobals.rootNavKey.currentContext?.pushView(view, { PluginArgumentKeys.rowId: rowId, }); } } }); }, child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>( builder: (context, state) { _setSystemOverlayStyle(state); return MaterialApp.router( builder: (context, child) => MediaQuery( // use the 1.0 as the textScaleFactor to avoid the text size // affected by the system setting. data: MediaQuery.of(context).copyWith( textScaler: TextScaler.linear(state.textScaleFactor), ), child: overlayManagerBuilder( context, CommandPalette( toggleNotifier: ValueNotifier<bool>(false), child: child, ), ), ), debugShowCheckedModeBanner: false, theme: state.lightTheme, darkTheme: state.darkTheme, themeMode: state.themeMode, localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: state.locale, routerConfig: routerConfig, ); }, ), ), ); } void _setSystemOverlayStyle(AppearanceSettingsState state) { if (Platform.isAndroid) { SystemUiOverlayStyle style = SystemUiOverlayStyle.dark; final themeMode = state.themeMode; if (themeMode == ThemeMode.dark) { style = SystemUiOverlayStyle.light; } else if (themeMode == ThemeMode.light) { style = SystemUiOverlayStyle.dark; } else { final brightness = Theme.of(context).brightness; // reverse the brightness of the system status bar. style = brightness == Brightness.dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark; } SystemChrome.setSystemUIOverlayStyle( style.copyWith( statusBarColor: Colors.transparent, systemNavigationBarColor: Colors.transparent, ), ); } } } class AppGlobals { // static GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey(); static GlobalKey<NavigatorState> rootNavKey = GlobalKey(); static NavigatorState get nav => rootNavKey.currentState!; } class ApplicationBlocObserver extends BlocObserver { @override void onError(BlocBase bloc, Object error, StackTrace stackTrace) { Log.debug(error); super.onError(bloc, error, stackTrace); } } Future<AppTheme> appTheme(String themeName) async { if (themeName.isEmpty) { return AppTheme.fallback; } else { try { return await AppTheme.fromName(themeName); } catch (e) { return AppTheme.fallback; } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/localization.dart
import 'package:easy_localization/easy_localization.dart'; import '../startup.dart'; class InitLocalizationTask extends LaunchTask { const InitLocalizationTask(); @override Future<void> initialize(LaunchContext context) async { await EasyLocalization.ensureInitialized(); EasyLocalization.logger.enableBuildModes = []; } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/load_plugin.dart
import 'package:appflowy/plugins/database/calendar/calendar.dart'; import 'package:appflowy/plugins/database/board/board.dart'; import 'package:appflowy/plugins/database/grid/grid.dart'; import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/plugins/blank/blank.dart'; import 'package:appflowy/plugins/document/document.dart'; import 'package:appflowy/plugins/trash/trash.dart'; class PluginLoadTask extends LaunchTask { const PluginLoadTask(); @override LaunchTaskType get type => LaunchTaskType.dataProcessing; @override Future<void> initialize(LaunchContext context) async { registerPlugin(builder: BlankPluginBuilder(), config: BlankPluginConfig()); registerPlugin(builder: TrashPluginBuilder(), config: TrashPluginConfig()); registerPlugin(builder: DocumentPluginBuilder()); registerPlugin(builder: GridPluginBuilder(), config: GridPluginConfig()); registerPlugin(builder: BoardPluginBuilder(), config: BoardPluginConfig()); registerPlugin( builder: CalendarPluginBuilder(), config: CalendarPluginConfig(), ); } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/prelude.dart
export 'app_widget.dart'; export 'appflowy_cloud_task.dart'; export 'debug_task.dart'; export 'device_info_task.dart'; export 'generate_router.dart'; export 'hot_key.dart'; export 'load_plugin.dart'; export 'localization.dart'; export 'memory_leak_detector.dart'; export 'platform_error_catcher.dart'; export 'platform_service.dart'; export 'rust_sdk.dart'; export 'supabase_task.dart'; export 'windows.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/memory_leak_detector.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:leak_tracker/leak_tracker.dart'; import '../startup.dart'; bool enableMemoryLeakDetect = false; bool dumpMemoryLeakPerSecond = false; void dumpMemoryLeak({ LeakType type = LeakType.notDisposed, }) async { final details = await LeakTracking.collectLeaks(); details.dumpDetails(type); } class MemoryLeakDetectorTask extends LaunchTask { MemoryLeakDetectorTask(); Timer? _timer; @override Future<void> initialize(LaunchContext context) async { if (!kDebugMode || !enableMemoryLeakDetect) { return; } LeakTracking.start(); LeakTracking.phase = const PhaseSettings( leakDiagnosticConfig: LeakDiagnosticConfig( collectRetainingPathForNotGCed: true, collectStackTraceOnStart: true, ), ); FlutterMemoryAllocations.instance.addListener((p0) { LeakTracking.dispatchObjectEvent(p0.toMap()); }); // dump memory leak per second if needed if (dumpMemoryLeakPerSecond) { _timer = Timer.periodic(const Duration(seconds: 1), (_) async { final summary = await LeakTracking.checkLeaks(); if (summary.isEmpty) { return; } dumpMemoryLeak(); }); } } @override Future<void> dispose() async { if (!kDebugMode || !enableMemoryLeakDetect) { return; } if (dumpMemoryLeakPerSecond) { _timer?.cancel(); _timer = null; } LeakTracking.stop(); } } extension on LeakType { String get desc => switch (this) { LeakType.notDisposed => 'not disposed', LeakType.notGCed => 'not GCed', LeakType.gcedLate => 'GCed late' }; } final _dumpablePackages = [ 'package:appflowy/', 'package:appflowy_editor/', ]; extension on Leaks { void dumpDetails(LeakType type) { final summary = '${type.desc}: ${switch (type) { LeakType.notDisposed => '${notDisposed.length}', LeakType.notGCed => '${notGCed.length}', LeakType.gcedLate => '${gcedLate.length}' }}'; debugPrint(summary); final details = switch (type) { LeakType.notDisposed => notDisposed, LeakType.notGCed => notGCed, LeakType.gcedLate => gcedLate }; // only dump the code in appflowy for (final value in details) { final stack = value.context![ContextKeys.startCallstack]! as StackTrace; final stackInAppFlowy = stack .toString() .split('\n') .where( (stack) => // ignore current file call stack !stack.contains('memory_leak_detector') && _dumpablePackages.any((pkg) => stack.contains(pkg)), ) .join('\n'); // ignore the untreatable leak if (stackInAppFlowy.isEmpty) { continue; } final object = value.type; debugPrint(''' $object ${type.desc} $stackInAppFlowy '''); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/feature_flag_task.dart
import 'package:appflowy/shared/feature_flags.dart'; import 'package:flutter/foundation.dart'; import '../startup.dart'; class FeatureFlagTask extends LaunchTask { const FeatureFlagTask(); @override Future<void> initialize(LaunchContext context) async { // the hotkey manager is not supported on mobile if (!kDebugMode) { return; } await FeatureFlag.initialize(); } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/appflowy_cloud_task.dart
import 'dart:async'; import 'dart:io'; import 'package:app_links/app_links.dart'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/tasks/app_widget.dart'; import 'package:appflowy/startup/tasks/supabase_task.dart'; import 'package:appflowy/user/application/auth/auth_error.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/application/auth/device_id.dart'; import 'package:appflowy/user/application/user_auth_listener.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/log.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-user/protobuf.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:flutter/material.dart'; import 'package:url_protocol/url_protocol.dart'; class AppFlowyCloudDeepLink { AppFlowyCloudDeepLink() { if (_deeplinkSubscription == null) { _deeplinkSubscription = _appLinks.uriLinkStream.listen( (Uri? uri) async { Log.info('onDeepLink: ${uri.toString()}'); await _handleUri(uri); }, onError: (Object err, StackTrace stackTrace) { Log.error('on DeepLink stream error: ${err.toString()}', stackTrace); _deeplinkSubscription?.cancel(); _deeplinkSubscription = null; }, ); if (Platform.isWindows) { // register deep link for Windows registerProtocolHandler(appflowyDeepLinkSchema); } } else { _deeplinkSubscription?.resume(); } } final _appLinks = AppLinks(); ValueNotifier<DeepLinkResult?>? _stateNotifier = ValueNotifier(null); Completer<FlowyResult<UserProfilePB, FlowyError>>? _completer; // The AppLinks is a singleton, so we need to cancel the previous subscription // before creating a new one. static StreamSubscription<Uri?>? _deeplinkSubscription; Future<void> dispose() async { _deeplinkSubscription?.pause(); _stateNotifier?.dispose(); _stateNotifier = null; } void registerCompleter( Completer<FlowyResult<UserProfilePB, FlowyError>> completer, ) { _completer = completer; } VoidCallback subscribeDeepLinkLoadingState( ValueChanged<DeepLinkResult> listener, ) { void listenerFn() { if (_stateNotifier?.value != null) { listener(_stateNotifier!.value!); } } _stateNotifier?.addListener(listenerFn); return listenerFn; } void unsubscribeDeepLinkLoadingState(VoidCallback listener) => _stateNotifier?.removeListener(listener); Future<void> _handleUri( Uri? uri, ) async { _stateNotifier?.value = DeepLinkResult(state: DeepLinkState.none); if (uri == null) { Log.error('onDeepLinkError: Unexpected empty deep link callback'); _completer?.complete(FlowyResult.failure(AuthError.emptyDeepLink)); _completer = null; return; } return _isAuthCallbackDeepLink(uri).fold( (_) async { final deviceId = await getDeviceId(); final payload = OauthSignInPB( authenticator: AuthenticatorPB.AppFlowyCloud, map: { AuthServiceMapKeys.signInURL: uri.toString(), AuthServiceMapKeys.deviceId: deviceId, }, ); _stateNotifier?.value = DeepLinkResult(state: DeepLinkState.loading); final result = await UserEventOauthSignIn(payload).send(); _stateNotifier?.value = DeepLinkResult( state: DeepLinkState.finish, result: result, ); // If there is no completer, runAppFlowy() will be called. if (_completer == null) { await result.fold( (_) async { await runAppFlowy(); }, (err) { Log.error(err); final context = AppGlobals.rootNavKey.currentState?.context; if (context != null) { showSnackBarMessage( context, err.msg, ); } }, ); } else { _completer?.complete(result); _completer = null; } }, (err) { Log.error('onDeepLinkError: Unexpected deep link: $err'); if (_completer == null) { final context = AppGlobals.rootNavKey.currentState?.context; if (context != null) { showSnackBarMessage( context, err.msg, ); } } else { _completer?.complete(FlowyResult.failure(err)); _completer = null; } }, ); } FlowyResult<void, FlowyError> _isAuthCallbackDeepLink(Uri uri) { if (uri.fragment.contains('access_token')) { return FlowyResult.success(null); } return FlowyResult.failure( FlowyError.create() ..code = ErrorCode.MissingAuthField ..msg = uri.path, ); } } class InitAppFlowyCloudTask extends LaunchTask { UserAuthStateListener? _authStateListener; bool isLoggingOut = false; @override Future<void> initialize(LaunchContext context) async { if (!isAppFlowyCloudEnabled) { return; } _authStateListener = UserAuthStateListener(); _authStateListener?.start( didSignIn: () { isLoggingOut = false; }, onInvalidAuth: (message) async { Log.error(message); if (!isLoggingOut) { await runAppFlowy(); } }, ); } @override Future<void> dispose() async { await _authStateListener?.stop(); _authStateListener = null; } } class DeepLinkResult { DeepLinkResult({ required this.state, this.result, }); final DeepLinkState state; final FlowyResult<UserProfilePB, FlowyError>? result; } enum DeepLinkState { none, loading, finish, }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/supabase_task.dart
import 'dart:async'; import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/user/application/supabase_realtime.dart'; import 'package:appflowy/workspace/application/settings/application_data_storage.dart'; import 'package:flutter/foundation.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:path/path.dart' as p; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:url_protocol/url_protocol.dart'; import '../startup.dart'; // ONLY supports in macOS and Windows now. // // If you need to update the schema, please update the following files: // - appflowy_flutter/macos/Runner/Info.plist (macOS) // - the callback url in Supabase dashboard const appflowyDeepLinkSchema = 'appflowy-flutter'; const supabaseLoginCallback = '$appflowyDeepLinkSchema://login-callback'; const hiveBoxName = 'appflowy_supabase_authentication'; // Used to store the session of the supabase in case of the user switch the different folder. Supabase? supabase; SupabaseRealtimeService? realtimeService; class InitSupabaseTask extends LaunchTask { @override Future<void> initialize(LaunchContext context) async { if (!isSupabaseEnabled) { return; } await supabase?.dispose(); supabase = null; final initializedSupabase = await Supabase.initialize( url: getIt<AppFlowyCloudSharedEnv>().supabaseConfig.url, anonKey: getIt<AppFlowyCloudSharedEnv>().supabaseConfig.anon_key, debug: kDebugMode, authOptions: const FlutterAuthClientOptions( localStorage: SupabaseLocalStorage(), ), ); if (realtimeService != null) { await realtimeService?.dispose(); realtimeService = null; } realtimeService = SupabaseRealtimeService(supabase: initializedSupabase); supabase = initializedSupabase; if (Platform.isWindows) { // register deep link for Windows registerProtocolHandler(appflowyDeepLinkSchema); } } @override Future<void> dispose() async { await realtimeService?.dispose(); realtimeService = null; await supabase?.dispose(); supabase = null; } } /// customize the supabase auth storage /// /// We don't use the default one because it always save the session in the document directory. /// When we switch to the different folder, the session still exists. class SupabaseLocalStorage extends LocalStorage { const SupabaseLocalStorage(); @override Future<void> initialize() async { HiveCipher? encryptionCipher; // customize the path for Hive final path = await getIt<ApplicationDataStorage>().getPath(); Hive.init(p.join(path, 'supabase_auth')); await Hive.openBox( hiveBoxName, encryptionCipher: encryptionCipher, ); } @override Future<bool> hasAccessToken() { return Future.value( Hive.box(hiveBoxName).containsKey( supabasePersistSessionKey, ), ); } @override Future<String?> accessToken() { return Future.value( Hive.box(hiveBoxName).get(supabasePersistSessionKey) as String?, ); } @override Future<void> removePersistedSession() { return Hive.box(hiveBoxName).delete(supabasePersistSessionKey); } @override Future<void> persistSession(String persistSessionString) { return Hive.box(hiveBoxName).put( supabasePersistSessionKey, persistSessionString, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/rust_sdk.dart
import 'dart:convert'; import 'dart:io'; import 'package:appflowy/env/backend_env.dart'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/user/application/auth/device_id.dart'; import 'package:appflowy_backend/appflowy_backend.dart'; import 'package:flutter/foundation.dart'; import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart' as path; import '../startup.dart'; class InitRustSDKTask extends LaunchTask { const InitRustSDKTask({ this.customApplicationPath, }); // Customize the RustSDK initialization path final Directory? customApplicationPath; @override LaunchTaskType get type => LaunchTaskType.dataProcessing; @override Future<void> initialize(LaunchContext context) async { final root = await getApplicationSupportDirectory(); final applicationPath = await appFlowyApplicationDataDirectory(); final dir = customApplicationPath ?? applicationPath; final deviceId = await getDeviceId(); debugPrint('application path: ${applicationPath.path}'); // Pass the environment variables to the Rust SDK final env = _makeAppFlowyConfiguration( root.path, context.config.version, dir.path, applicationPath.path, deviceId, rustEnvs: context.config.rustEnvs, ); await context.getIt<FlowySDK>().init(jsonEncode(env.toJson())); } @override Future<void> dispose() async {} } AppFlowyConfiguration _makeAppFlowyConfiguration( String root, String appVersion, String customAppPath, String originAppPath, String deviceId, { required Map<String, String> rustEnvs, }) { final env = getIt<AppFlowyCloudSharedEnv>(); return AppFlowyConfiguration( root: root, app_version: appVersion, custom_app_path: customAppPath, origin_app_path: originAppPath, device_id: deviceId, platform: Platform.operatingSystem, authenticator_type: env.authenticatorType.value, supabase_config: env.supabaseConfig, appflowy_cloud_config: env.appflowyCloudConfig, envs: rustEnvs, ); } /// The default directory to store the user data. The directory can be /// customized by the user via the [ApplicationDataStorage] Future<Directory> appFlowyApplicationDataDirectory() async { switch (integrationMode()) { case IntegrationMode.develop: final Directory documentsDir = await getApplicationSupportDirectory() .then((directory) => directory.create()); return Directory(path.join(documentsDir.path, 'data_dev')).create(); case IntegrationMode.release: final Directory documentsDir = await getApplicationSupportDirectory(); return Directory(path.join(documentsDir.path, 'data')).create(); case IntegrationMode.unitTest: case IntegrationMode.integrationTest: return Directory(path.join(Directory.current.path, '.sandbox')); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/windows.dart
import 'dart:ui'; import 'package:appflowy/core/helpers/helpers.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/tasks/app_window_size_manager.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:window_manager/window_manager.dart'; class InitAppWindowTask extends LaunchTask with WindowListener { const InitAppWindowTask({ this.title = 'AppFlowy', }); final String title; @override Future<void> initialize(LaunchContext context) async { // Don't initialize on mobile or web. if (!defaultTargetPlatform.isDesktop || context.env.isIntegrationTest) { return; } await windowManager.ensureInitialized(); windowManager.addListener(this); final windowSize = await WindowSizeManager().getSize(); final windowOptions = WindowOptions( size: windowSize, minimumSize: const Size( WindowSizeManager.minWindowWidth, WindowSizeManager.minWindowHeight, ), maximumSize: const Size( WindowSizeManager.maxWindowWidth, WindowSizeManager.maxWindowHeight, ), title: title, ); await windowManager.waitUntilReadyToShow(windowOptions, () async { await windowManager.show(); await windowManager.focus(); final position = await WindowSizeManager().getPosition(); if (position != null) { await windowManager.setPosition(position); } }); } @override Future<void> onWindowResize() async { super.onWindowResize(); final currentWindowSize = await windowManager.getSize(); return WindowSizeManager().setSize(currentWindowSize); } @override void onWindowMaximize() async { super.onWindowMaximize(); final currentWindowSize = await windowManager.getSize(); return WindowSizeManager().setSize(currentWindowSize); } @override void onWindowMoved() async { super.onWindowMoved(); final position = await windowManager.getPosition(); return WindowSizeManager().setPosition(position); } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/debug_task.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../startup.dart'; class DebugTask extends LaunchTask { const DebugTask(); @override Future<void> initialize(LaunchContext context) async { // the hotkey manager is not supported on mobile if (PlatformExtension.isMobile && kDebugMode) { await SystemChannels.textInput.invokeMethod('TextInput.hide'); } } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/platform_error_catcher.dart
import 'package:appflowy_backend/log.dart'; import 'package:flutter/foundation.dart'; import '../startup.dart'; class PlatformErrorCatcherTask extends LaunchTask { const PlatformErrorCatcherTask(); @override Future<void> initialize(LaunchContext context) async { // Handle platform errors not caught by Flutter. // Reduces the likelihood of the app crashing, and logs the error. // only active in non debug mode. if (!kDebugMode) { PlatformDispatcher.instance.onError = (error, stack) { Log.error('Uncaught platform error', error, stack); return true; }; } } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/platform_service.dart
import 'package:appflowy/core/network_monitor.dart'; import '../startup.dart'; class InitPlatformServiceTask extends LaunchTask { const InitPlatformServiceTask(); @override LaunchTaskType get type => LaunchTaskType.dataProcessing; @override Future<void> initialize(LaunchContext context) async { return getIt<NetworkListener>().start(); } @override Future<void> dispose() async { await getIt<NetworkListener>().stop(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/generate_router.dart
import 'dart:convert'; import 'package:appflowy/mobile/presentation/database/board/mobile_board_screen.dart'; import 'package:appflowy/mobile/presentation/database/card/card.dart'; import 'package:appflowy/mobile/presentation/database/date_picker/mobile_date_picker_screen.dart'; import 'package:appflowy/mobile/presentation/database/field/mobile_create_field_screen.dart'; import 'package:appflowy/mobile/presentation/database/field/mobile_edit_field_screen.dart'; import 'package:appflowy/mobile/presentation/database/mobile_calendar_events_screen.dart'; import 'package:appflowy/mobile/presentation/database/mobile_calendar_screen.dart'; import 'package:appflowy/mobile/presentation/database/mobile_grid_screen.dart'; import 'package:appflowy/mobile/presentation/favorite/mobile_favorite_page.dart'; import 'package:appflowy/mobile/presentation/notifications/mobile_notifications_page.dart'; import 'package:appflowy/mobile/presentation/presentation.dart'; import 'package:appflowy/mobile/presentation/setting/cloud/appflowy_cloud_page.dart'; import 'package:appflowy/mobile/presentation/setting/font/font_picker_screen.dart'; import 'package:appflowy/mobile/presentation/setting/language/language_picker_screen.dart'; import 'package:appflowy/mobile/presentation/setting/launch_settings_page.dart'; import 'package:appflowy/plugins/base/color/color_picker_screen.dart'; import 'package:appflowy/plugins/base/emoji/emoji_picker_screen.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/code_block/code_language_screen.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_picker_screen.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_item/mobile_block_settings_screen.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/tasks/app_widget.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/presentation/presentation.dart'; import 'package:appflowy/workspace/presentation/home/desktop_home_screen.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/feature_flags/mobile_feature_flag_screen.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flowy_infra/time/duration.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:sheet/route.dart'; GoRouter generateRouter(Widget child) { return GoRouter( navigatorKey: AppGlobals.rootNavKey, initialLocation: '/', routes: [ // Root route is SplashScreen. // It needs LaunchConfiguration as a parameter, so we get it from ApplicationWidget's child. _rootRoute(child), // Routes in both desktop and mobile _signInScreenRoute(), _skipLogInScreenRoute(), _encryptSecretScreenRoute(), _workspaceErrorScreenRoute(), // Desktop only if (!PlatformExtension.isMobile) _desktopHomeScreenRoute(), // Mobile only if (PlatformExtension.isMobile) ...[ // settings _mobileHomeSettingPageRoute(), _mobileCloudSettingAppFlowyCloudPageRoute(), _mobileLaunchSettingsPageRoute(), _mobileFeatureFlagPageRoute(), // view page _mobileEditorScreenRoute(), _mobileGridScreenRoute(), _mobileBoardScreenRoute(), _mobileCalendarScreenRoute(), // card detail page _mobileCardDetailScreenRoute(), _mobileDateCellEditScreenRoute(), _mobileNewPropertyPageRoute(), _mobileEditPropertyPageRoute(), // home // MobileHomeSettingPage is outside the bottom navigation bar, thus it is not in the StatefulShellRoute. _mobileHomeScreenWithNavigationBarRoute(), // trash _mobileHomeTrashPageRoute(), // emoji picker _mobileEmojiPickerPageRoute(), _mobileImagePickerPageRoute(), // color picker _mobileColorPickerPageRoute(), // code language picker _mobileCodeLanguagePickerPageRoute(), _mobileLanguagePickerPageRoute(), _mobileFontPickerPageRoute(), // calendar related _mobileCalendarEventsPageRoute(), _mobileBlockSettingsPageRoute(), ], // Desktop and Mobile GoRoute( path: WorkspaceStartScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return CustomTransitionPage( child: WorkspaceStartScreen( userProfile: args[WorkspaceStartScreen.argUserProfile], ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ), GoRoute( path: SignUpScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: SignUpScreen( router: getIt<AuthRouter>(), ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ), ], ); } /// We use StatefulShellRoute to create a StatefulNavigationShell(ScaffoldWithNavBar) to access to multiple pages, and each page retains its own state. StatefulShellRoute _mobileHomeScreenWithNavigationBarRoute() { return StatefulShellRoute.indexedStack( builder: ( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) { // Return the widget that implements the custom shell (in this case // using a BottomNavigationBar). The StatefulNavigationShell is passed // to be able access the state of the shell and to navigate to other // branches in a stateful way. return MobileBottomNavigationBar(navigationShell: navigationShell); }, branches: <StatefulShellBranch>[ StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: MobileHomeScreen.routeName, builder: (BuildContext context, GoRouterState state) { return const MobileHomeScreen(); }, ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: MobileFavoriteScreen.routeName, builder: (BuildContext context, GoRouterState state) { return const MobileFavoriteScreen(); }, ), ], ), // Enable search feature after we have a search page. // StatefulShellBranch( // routes: <RouteBase>[ // GoRoute( // path: '/d', // builder: (BuildContext context, GoRouterState state) => // const RootPlaceholderScreen( // label: 'Search', // detailsPath: '/d/details', // ), // routes: <RouteBase>[ // GoRoute( // path: 'details', // builder: (BuildContext context, GoRouterState state) => // const DetailsPlaceholderScreen( // label: 'Search Page details', // ), // ), // ], // ), // ], // ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: MobileNotificationsScreen.routeName, builder: (_, __) => const MobileNotificationsScreen(), ), ], ), ], ); } GoRoute _mobileHomeSettingPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileHomeSettingPage.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage(child: MobileHomeSettingPage()); }, ); } GoRoute _mobileCloudSettingAppFlowyCloudPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: AppFlowyCloudPage.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage(child: AppFlowyCloudPage()); }, ); } GoRoute _mobileLaunchSettingsPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileLaunchSettingsPage.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage(child: MobileLaunchSettingsPage()); }, ); } GoRoute _mobileFeatureFlagPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: FeatureFlagScreen.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage(child: FeatureFlagScreen()); }, ); } GoRoute _mobileHomeTrashPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileHomeTrashPage.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage(child: MobileHomeTrashPage()); }, ); } GoRoute _mobileBlockSettingsPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileBlockSettingsScreen.routeName, pageBuilder: (context, state) { final actionsString = state.uri.queryParameters[MobileBlockSettingsScreen.supportedActions]; final actions = actionsString ?.split(',') .map(MobileBlockActionType.fromActionString) .toList(); return MaterialExtendedPage( child: MobileBlockSettingsScreen( actions: actions ?? MobileBlockActionType.standard, ), ); }, ); } GoRoute _mobileEmojiPickerPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileEmojiPickerScreen.routeName, pageBuilder: (context, state) { final title = state.uri.queryParameters[MobileEmojiPickerScreen.pageTitle]; return MaterialExtendedPage( child: MobileEmojiPickerScreen( title: title, ), ); }, ); } GoRoute _mobileColorPickerPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileColorPickerScreen.routeName, pageBuilder: (context, state) { final title = state.uri.queryParameters[MobileColorPickerScreen.pageTitle] ?? ''; return MaterialExtendedPage( child: MobileColorPickerScreen( title: title, ), ); }, ); } GoRoute _mobileImagePickerPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileImagePickerScreen.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage( child: MobileImagePickerScreen(), ); }, ); } GoRoute _mobileCodeLanguagePickerPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileCodeLanguagePickerScreen.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage( child: MobileCodeLanguagePickerScreen(), ); }, ); } GoRoute _mobileLanguagePickerPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: LanguagePickerScreen.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage( child: LanguagePickerScreen(), ); }, ); } GoRoute _mobileFontPickerPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: FontPickerScreen.routeName, pageBuilder: (context, state) { return const MaterialExtendedPage( child: FontPickerScreen(), ); }, ); } GoRoute _mobileNewPropertyPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileNewPropertyScreen.routeName, pageBuilder: (context, state) { final viewId = state .uri.queryParameters[MobileNewPropertyScreen.argViewId] as String; final fieldTypeId = state.uri.queryParameters[MobileNewPropertyScreen.argFieldTypeId] ?? FieldType.RichText.value.toString(); final value = int.parse(fieldTypeId); return MaterialExtendedPage( fullscreenDialog: true, child: MobileNewPropertyScreen( viewId: viewId, fieldType: FieldType.valueOf(value), ), ); }, ); } GoRoute _mobileEditPropertyPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileEditPropertyScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return MaterialExtendedPage( fullscreenDialog: true, child: MobileEditPropertyScreen( viewId: args[MobileEditPropertyScreen.argViewId], field: args[MobileEditPropertyScreen.argField], ), ); }, ); } GoRoute _mobileCalendarEventsPageRoute() { return GoRoute( path: MobileCalendarEventsScreen.routeName, parentNavigatorKey: AppGlobals.rootNavKey, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return MaterialExtendedPage( child: MobileCalendarEventsScreen( calendarBloc: args[MobileCalendarEventsScreen.calendarBlocKey], date: args[MobileCalendarEventsScreen.calendarDateKey], events: args[MobileCalendarEventsScreen.calendarEventsKey], rowCache: args[MobileCalendarEventsScreen.calendarRowCacheKey], viewId: args[MobileCalendarEventsScreen.calendarViewIdKey], ), ); }, ); } GoRoute _desktopHomeScreenRoute() { return GoRoute( path: DesktopHomeScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: const DesktopHomeScreen(), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _workspaceErrorScreenRoute() { return GoRoute( path: WorkspaceErrorScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return CustomTransitionPage( child: WorkspaceErrorScreen( error: args[WorkspaceErrorScreen.argError], userFolder: args[WorkspaceErrorScreen.argUserFolder], ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _encryptSecretScreenRoute() { return GoRoute( path: EncryptSecretScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return CustomTransitionPage( child: EncryptSecretScreen( user: args[EncryptSecretScreen.argUser], key: args[EncryptSecretScreen.argKey], ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _skipLogInScreenRoute() { return GoRoute( path: SkipLogInScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: const SkipLogInScreen(), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _signInScreenRoute() { return GoRoute( path: SignInScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: const SignInScreen(), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _mobileEditorScreenRoute() { return GoRoute( path: MobileDocumentScreen.routeName, parentNavigatorKey: AppGlobals.rootNavKey, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileDocumentScreen.viewId]!; final title = state.uri.queryParameters[MobileDocumentScreen.viewTitle]; return MaterialExtendedPage( child: MobileDocumentScreen(id: id, title: title), ); }, ); } GoRoute _mobileGridScreenRoute() { return GoRoute( path: MobileGridScreen.routeName, parentNavigatorKey: AppGlobals.rootNavKey, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileGridScreen.viewId]!; final title = state.uri.queryParameters[MobileGridScreen.viewTitle]; final arguments = state.uri.queryParameters[MobileGridScreen.viewArgs]; return MaterialExtendedPage( child: MobileGridScreen( id: id, title: title, arguments: arguments != null ? jsonDecode(arguments) : null, ), ); }, ); } GoRoute _mobileBoardScreenRoute() { return GoRoute( path: MobileBoardScreen.routeName, parentNavigatorKey: AppGlobals.rootNavKey, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileBoardScreen.viewId]!; final title = state.uri.queryParameters[MobileBoardScreen.viewTitle]; return MaterialExtendedPage( child: MobileBoardScreen( id: id, title: title, ), ); }, ); } GoRoute _mobileCalendarScreenRoute() { return GoRoute( path: MobileCalendarScreen.routeName, parentNavigatorKey: AppGlobals.rootNavKey, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileCalendarScreen.viewId]!; final title = state.uri.queryParameters[MobileCalendarScreen.viewTitle]!; return MaterialExtendedPage( child: MobileCalendarScreen( id: id, title: title, ), ); }, ); } GoRoute _mobileCardDetailScreenRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileRowDetailPage.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; final databaseController = args[MobileRowDetailPage.argDatabaseController]; final rowId = args[MobileRowDetailPage.argRowId]!; return MaterialExtendedPage( child: MobileRowDetailPage( databaseController: databaseController, rowId: rowId, ), ); }, ); } GoRoute _mobileDateCellEditScreenRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileDateCellEditScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; final controller = args[MobileDateCellEditScreen.dateCellController]; final fullScreen = args[MobileDateCellEditScreen.fullScreen]; return CustomTransitionPage( transitionsBuilder: (_, __, ___, child) => child, fullscreenDialog: true, opaque: false, barrierDismissible: true, barrierColor: Theme.of(context).bottomSheetTheme.modalBarrierColor, child: MobileDateCellEditScreen( controller: controller, showAsFullScreen: fullScreen ?? true, ), ); }, ); } GoRoute _rootRoute(Widget child) { return GoRoute( path: '/', redirect: (context, state) async { // Every time before navigating to splash screen, we check if user is already logged in desktop. It is used to skip showing splash screen when user just changes appearance settings like theme mode. final userResponse = await getIt<AuthService>().getUser(); final routeName = userResponse.fold( (user) => DesktopHomeScreen.routeName, (error) => null, ); if (routeName != null && !PlatformExtension.isMobile) return routeName; return null; }, // Root route is SplashScreen. // It needs LaunchConfiguration as a parameter, so we get it from ApplicationWidget's child. pageBuilder: (context, state) => MaterialExtendedPage( child: child, ), ); } Widget _buildFadeTransition( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) => FadeTransition(opacity: animation, child: child); Duration _slowDuration = Duration( milliseconds: RouteDurations.slow.inMilliseconds.round(), );
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/hot_key.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:hotkey_manager/hotkey_manager.dart'; import '../startup.dart'; class HotKeyTask extends LaunchTask { const HotKeyTask(); @override Future<void> initialize(LaunchContext context) async { // the hotkey manager is not supported on mobile if (PlatformExtension.isMobile) { return; } await hotKeyManager.unregisterAll(); } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/startup/tasks/device_info_task.dart
import 'dart:io'; import 'package:appflowy_backend/log.dart'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:package_info_plus/package_info_plus.dart'; import '../startup.dart'; class ApplicationInfo { static int androidSDKVersion = -1; static String applicationVersion = ''; static String buildNumber = ''; static String deviceId = ''; } class ApplicationInfoTask extends LaunchTask { const ApplicationInfoTask(); @override Future<void> initialize(LaunchContext context) async { final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin(); final PackageInfo packageInfo = await PackageInfo.fromPlatform(); if (Platform.isAndroid) { final androidInfo = await deviceInfoPlugin.androidInfo; ApplicationInfo.androidSDKVersion = androidInfo.version.sdkInt; } if (Platform.isAndroid || Platform.isIOS) { ApplicationInfo.applicationVersion = packageInfo.version; ApplicationInfo.buildNumber = packageInfo.buildNumber; } String? deviceId; try { if (Platform.isAndroid) { final AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo; deviceId = androidInfo.device; } else if (Platform.isIOS) { final IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo; deviceId = iosInfo.identifierForVendor; } else if (Platform.isMacOS) { final MacOsDeviceInfo macInfo = await deviceInfoPlugin.macOsInfo; deviceId = macInfo.systemGUID; } else if (Platform.isWindows) { final WindowsDeviceInfo windowsInfo = await deviceInfoPlugin.windowsInfo; deviceId = windowsInfo.deviceId; } else if (Platform.isLinux) { final LinuxDeviceInfo linuxInfo = await deviceInfoPlugin.linuxInfo; deviceId = linuxInfo.machineId; } else { deviceId = null; } } catch (e) { Log.error('Failed to get platform version, $e'); } ApplicationInfo.deviceId = deviceId ?? ''; } @override Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/util.dart
import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/workspace/application/view/view_listener.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:flutter/material.dart'; class ViewPluginNotifier extends PluginNotifier<DeletedViewPB?> { ViewPluginNotifier({ required this.view, }) : _viewListener = ViewListener(viewId: view.id) { _viewListener?.start( onViewUpdated: (updatedView) => view = updatedView, onViewMoveToTrash: (result) => result.fold( (deletedView) => isDeleted.value = deletedView, (err) => Log.error(err), ), ); } ViewPB view; final ViewListener? _viewListener; @override final ValueNotifier<DeletedViewPB?> isDeleted = ValueNotifier(null); @override void dispose() { isDeleted.dispose(); _viewListener?.stop(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/blank/blank.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/workspace/presentation/home/home_stack.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flutter/material.dart'; class BlankPluginBuilder extends PluginBuilder { @override Plugin build(dynamic data) { return BlankPagePlugin(); } @override String get menuName => "Blank"; @override FlowySvgData get icon => const FlowySvgData(''); @override PluginType get pluginType => PluginType.blank; } class BlankPluginConfig implements PluginConfig { @override bool get creatable => false; } class BlankPagePlugin extends Plugin { @override PluginWidgetBuilder get widgetBuilder => BlankPagePluginWidgetBuilder(); @override PluginId get id => "BlankStack"; @override PluginType get pluginType => PluginType.blank; } class BlankPagePluginWidgetBuilder extends PluginWidgetBuilder with NavigationItem { @override Widget get leftBarItem => FlowyText.medium(LocaleKeys.blankPageTitle.tr()); @override Widget tabBarItem(String pluginId) => leftBarItem; @override Widget buildWidget({PluginContext? context, required bool shrinkWrap}) => const BlankPage(); @override List<NavigationItem> get navigationItems => [this]; } class BlankPage extends StatefulWidget { const BlankPage({super.key}); @override State<BlankPage> createState() => _BlankPageState(); } class _BlankPageState extends State<BlankPage> { @override Widget build(BuildContext context) { return SizedBox.expand( child: Container( color: Theme.of(context).colorScheme.surface, child: const Padding( padding: EdgeInsets.all(10), child: SizedBox.shrink(), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/shared/sync_indicator.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/database/application/sync/database_sync_bloc.dart'; import 'package:appflowy/plugins/document/application/document_sync_bloc.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class DocumentSyncIndicator extends StatelessWidget { const DocumentSyncIndicator({ super.key, required this.view, }); final ViewPB view; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => DocumentSyncBloc(view: view)..add(const DocumentSyncEvent.initial()), child: BlocBuilder<DocumentSyncBloc, DocumentSyncBlocState>( builder: (context, state) { // don't show indicator if user is local if (!state.shouldShowIndicator) { return const SizedBox.shrink(); } final Color color; final String hintText; if (!state.isNetworkConnected) { color = Colors.grey; hintText = LocaleKeys.newSettings_syncState_noNetworkConnected.tr(); } else { switch (state.syncState) { case DocumentSyncState.SyncFinished: color = Colors.green; hintText = LocaleKeys.newSettings_syncState_synced.tr(); break; case DocumentSyncState.Syncing: case DocumentSyncState.InitSyncBegin: color = Colors.yellow; hintText = LocaleKeys.newSettings_syncState_syncing.tr(); break; default: return const SizedBox.shrink(); } } return FlowyTooltip( message: hintText, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: color, ), width: 8, height: 8, ), ); }, ), ); } } class DatabaseSyncIndicator extends StatelessWidget { const DatabaseSyncIndicator({ super.key, required this.view, }); final ViewPB view; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => DatabaseSyncBloc(view: view)..add(const DatabaseSyncEvent.initial()), child: BlocBuilder<DatabaseSyncBloc, DatabaseSyncBlocState>( builder: (context, state) { // don't show indicator if user is local if (!state.shouldShowIndicator) { return const SizedBox.shrink(); } final Color color; final String hintText; if (!state.isNetworkConnected) { color = Colors.grey; hintText = LocaleKeys.newSettings_syncState_noNetworkConnected.tr(); } else { switch (state.syncState) { case DatabaseSyncState.SyncFinished: color = Colors.green; hintText = LocaleKeys.newSettings_syncState_synced.tr(); break; case DatabaseSyncState.Syncing: case DatabaseSyncState.InitSyncBegin: color = Colors.yellow; hintText = LocaleKeys.newSettings_syncState_syncing.tr(); break; default: return const SizedBox.shrink(); } } return FlowyTooltip( message: hintText, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: color, ), width: 8, height: 8, ), ); }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/database_view_widget.dart
import 'package:flutter/material.dart'; import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy/workspace/application/view/view_listener.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; class DatabaseViewWidget extends StatefulWidget { const DatabaseViewWidget({ super.key, required this.view, this.shrinkWrap = true, }); final ViewPB view; final bool shrinkWrap; @override State<DatabaseViewWidget> createState() => _DatabaseViewWidgetState(); } class _DatabaseViewWidgetState extends State<DatabaseViewWidget> { /// Listens to the view updates. late final ViewListener _listener; /// Notifies the view layout type changes. When the layout type changes, /// the widget of the view will be updated. late final ValueNotifier<ViewLayoutPB> _layoutTypeChangeNotifier; /// The view will be updated by the [ViewListener]. late ViewPB view; late Plugin viewPlugin; @override void initState() { super.initState(); view = widget.view; viewPlugin = view.plugin()..init(); _listenOnViewUpdated(); } @override void dispose() { _layoutTypeChangeNotifier.dispose(); _listener.stop(); viewPlugin.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ValueListenableBuilder<ViewLayoutPB>( valueListenable: _layoutTypeChangeNotifier, builder: (_, __, ___) => viewPlugin.widgetBuilder.buildWidget( shrinkWrap: widget.shrinkWrap, ), ); } void _listenOnViewUpdated() { _listener = ViewListener(viewId: widget.view.id) ..start( onViewUpdated: (updatedView) { if (mounted) { view = updatedView; _layoutTypeChangeNotifier.value = view.layout; } }, ); _layoutTypeChangeNotifier = ValueNotifier(widget.view.layout); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/share_button.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/database/application/share_bloc.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/util/string_extension.dart'; import 'package:appflowy/workspace/application/view/view_listener.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/file_picker/file_picker_service.dart'; import 'package:flowy_infra_ui/widget/rounded_button.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class DatabaseShareButton extends StatelessWidget { const DatabaseShareButton({ super.key, required this.view, }); final ViewPB view; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => DatabaseShareBloc(view: view), child: BlocListener<DatabaseShareBloc, DatabaseShareState>( listener: (context, state) { state.mapOrNull( finish: (state) { state.successOrFail.fold( (data) => _handleExportData(context), _handleExportError, ); }, ); }, child: BlocBuilder<DatabaseShareBloc, DatabaseShareState>( builder: (context, state) => ConstrainedBox( constraints: const BoxConstraints.expand( height: 30, width: 100, ), child: DatabaseShareActionList(view: view), ), ), ), ); } void _handleExportData(BuildContext context) { showSnackBarMessage( context, LocaleKeys.settings_files_exportFileSuccess.tr(), ); } void _handleExportError(FlowyError error) { showMessageToast(error.msg); } } class DatabaseShareActionList extends StatefulWidget { const DatabaseShareActionList({ super.key, required this.view, }); final ViewPB view; @override State<DatabaseShareActionList> createState() => DatabaseShareActionListState(); } @visibleForTesting class DatabaseShareActionListState extends State<DatabaseShareActionList> { late String name; late final ViewListener viewListener = ViewListener(viewId: widget.view.id); @override void initState() { super.initState(); listenOnViewUpdated(); } @override void dispose() { viewListener.stop(); super.dispose(); } @override Widget build(BuildContext context) { final databaseShareBloc = context.read<DatabaseShareBloc>(); return PopoverActionList<ShareActionWrapper>( direction: PopoverDirection.bottomWithCenterAligned, offset: const Offset(0, 8), actions: ShareAction.values .map((action) => ShareActionWrapper(action)) .toList(), buildChild: (controller) => Listener( onPointerDown: (_) => controller.show(), child: RoundedTextButton( title: LocaleKeys.shareAction_buttonText.tr(), textColor: Theme.of(context).colorScheme.onPrimary, onPressed: () {}, ), ), onSelected: (action, controller) async { switch (action.inner) { case ShareAction.csv: final exportPath = await getIt<FilePickerService>().saveFile( dialogTitle: '', fileName: '${name.toFileName()}.csv', ); if (exportPath != null) { databaseShareBloc.add(DatabaseShareEvent.shareCSV(exportPath)); } break; } controller.close(); }, ); } void listenOnViewUpdated() { name = widget.view.name; viewListener.start( onViewUpdated: (view) { name = view.name; }, ); } } enum ShareAction { csv, } class ShareActionWrapper extends ActionCell { ShareActionWrapper(this.inner); final ShareAction inner; Widget? icon(Color iconColor) => null; @override String get name { switch (inner) { case ShareAction.csv: return LocaleKeys.shareAction_csv.tr(); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/database_layout_ext.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pbenum.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pbenum.dart'; import 'package:easy_localization/easy_localization.dart'; extension DatabaseLayoutExtension on DatabaseLayoutPB { String get layoutName { return switch (this) { DatabaseLayoutPB.Board => LocaleKeys.board_menuName.tr(), DatabaseLayoutPB.Calendar => LocaleKeys.calendar_menuName.tr(), DatabaseLayoutPB.Grid => LocaleKeys.grid_menuName.tr(), _ => "", }; } ViewLayoutPB get layoutType { return switch (this) { DatabaseLayoutPB.Board => ViewLayoutPB.Board, DatabaseLayoutPB.Calendar => ViewLayoutPB.Calendar, DatabaseLayoutPB.Grid => ViewLayoutPB.Grid, _ => throw UnimplementedError(), }; } FlowySvgData get icon { return switch (this) { DatabaseLayoutPB.Board => FlowySvgs.board_s, DatabaseLayoutPB.Calendar => FlowySvgs.date_s, DatabaseLayoutPB.Grid => FlowySvgs.grid_s, _ => throw UnimplementedError(), }; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/card/card.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/mobile/presentation/database/card/card.dart'; import 'package:appflowy/plugins/database/application/cell/cell_controller.dart'; import 'package:appflowy/plugins/database/application/field/field_controller.dart'; import 'package:appflowy/plugins/database/application/row/row_cache.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/row/action.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/row_entities.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:collection/collection.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/style_widget/hover.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'card_bloc.dart'; import '../cell/card_cell_builder.dart'; import '../cell/card_cell_skeleton/card_cell.dart'; import 'container/accessory.dart'; import 'container/card_container.dart'; /// Edit a database row with card style widget class RowCard extends StatefulWidget { const RowCard({ super.key, required this.fieldController, required this.rowMeta, required this.viewId, required this.isEditing, required this.rowCache, required this.cellBuilder, required this.openCard, required this.onStartEditing, required this.onEndEditing, required this.styleConfiguration, this.groupingFieldId, this.groupId, }); final FieldController fieldController; final RowMetaPB rowMeta; final String viewId; final String? groupingFieldId; final String? groupId; final bool isEditing; final RowCache rowCache; /// The [CardCellBuilder] is used to build the card cells. final CardCellBuilder cellBuilder; /// Called when the user taps on the card. final void Function(BuildContext) openCard; /// Called when the user starts editing the card. final VoidCallback onStartEditing; /// Called when the user ends editing the card. final VoidCallback onEndEditing; final RowCardStyleConfiguration styleConfiguration; @override State<RowCard> createState() => _RowCardState(); } class _RowCardState extends State<RowCard> { final popoverController = PopoverController(); late final CardBloc _cardBloc; late final EditableRowNotifier rowNotifier; @override void initState() { super.initState(); rowNotifier = EditableRowNotifier(isEditing: widget.isEditing); _cardBloc = CardBloc( fieldController: widget.fieldController, viewId: widget.viewId, groupFieldId: widget.groupingFieldId, isEditing: widget.isEditing, rowMeta: widget.rowMeta, rowCache: widget.rowCache, )..add(const CardEvent.initial()); rowNotifier.isEditing.addListener(() { if (!mounted) return; _cardBloc.add(CardEvent.setIsEditing(rowNotifier.isEditing.value)); if (rowNotifier.isEditing.value) { widget.onStartEditing(); } else { widget.onEndEditing(); } }); } @override void dispose() { rowNotifier.dispose(); _cardBloc.close(); super.dispose(); } @override Widget build(BuildContext context) { return BlocProvider.value( value: _cardBloc, child: BlocBuilder<CardBloc, CardState>( builder: (context, state) => PlatformExtension.isMobile ? _mobile(state) : _desktop(state), ), ); } Widget _mobile(CardState state) { return GestureDetector( onTap: () => widget.openCard(context), behavior: HitTestBehavior.opaque, child: MobileCardContent( rowMeta: state.rowMeta, cellBuilder: widget.cellBuilder, styleConfiguration: widget.styleConfiguration, cells: state.cells, ), ); } Widget _desktop(CardState state) { final accessories = widget.styleConfiguration.showAccessory ? <CardAccessory>[ EditCardAccessory(rowNotifier: rowNotifier), const MoreCardOptionsAccessory(), ] : null; return AppFlowyPopover( controller: popoverController, triggerActions: PopoverTriggerFlags.none, constraints: BoxConstraints.loose(const Size(140, 200)), direction: PopoverDirection.rightWithCenterAligned, popupBuilder: (_) { return RowActionMenu.board( viewId: _cardBloc.viewId, rowId: _cardBloc.rowId, groupId: widget.groupId, ); }, child: RowCardContainer( buildAccessoryWhen: () => state.isEditing == false, accessories: accessories ?? [], openAccessory: _handleOpenAccessory, openCard: widget.openCard, child: _CardContent( rowMeta: state.rowMeta, rowNotifier: rowNotifier, cellBuilder: widget.cellBuilder, styleConfiguration: widget.styleConfiguration, cells: state.cells, ), ), ); } void _handleOpenAccessory(AccessoryType newAccessoryType) { switch (newAccessoryType) { case AccessoryType.edit: break; case AccessoryType.more: popoverController.show(); break; } } } class _CardContent extends StatelessWidget { const _CardContent({ required this.rowMeta, required this.rowNotifier, required this.cellBuilder, required this.cells, required this.styleConfiguration, }); final RowMetaPB rowMeta; final EditableRowNotifier rowNotifier; final CardCellBuilder cellBuilder; final List<CellContext> cells; final RowCardStyleConfiguration styleConfiguration; @override Widget build(BuildContext context) { final child = Padding( padding: styleConfiguration.cardPadding, child: Column( mainAxisSize: MainAxisSize.min, children: _makeCells(context, rowMeta, cells), ), ); return styleConfiguration.hoverStyle == null ? child : FlowyHover( style: styleConfiguration.hoverStyle, buildWhenOnHover: () => !rowNotifier.isEditing.value, child: child, ); } List<Widget> _makeCells( BuildContext context, RowMetaPB rowMeta, List<CellContext> cells, ) { // Remove all the cell listeners. rowNotifier.unbind(); return cells.mapIndexed((int index, CellContext cellContext) { EditableCardNotifier? cellNotifier; if (index == 0) { cellNotifier = EditableCardNotifier(isEditing: rowNotifier.isEditing.value); rowNotifier.bindCell(cellContext, cellNotifier); } return cellBuilder.build( cellContext: cellContext, cellNotifier: cellNotifier, styleMap: styleConfiguration.cellStyleMap, hasNotes: !rowMeta.isDocumentEmpty, ); }).toList(); } } class MoreCardOptionsAccessory extends StatelessWidget with CardAccessory { const MoreCardOptionsAccessory({super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(3.0), child: FlowySvg( FlowySvgs.three_dots_s, color: Theme.of(context).hintColor, ), ); } @override AccessoryType get type => AccessoryType.more; } class EditCardAccessory extends StatelessWidget with CardAccessory { const EditCardAccessory({super.key, required this.rowNotifier}); final EditableRowNotifier rowNotifier; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(3.0), child: FlowySvg( FlowySvgs.edit_s, color: Theme.of(context).hintColor, ), ); } @override void onTap(BuildContext context) => rowNotifier.becomeFirstResponder(); @override AccessoryType get type => AccessoryType.edit; } class RowCardStyleConfiguration { const RowCardStyleConfiguration({ required this.cellStyleMap, this.showAccessory = true, this.cardPadding = const EdgeInsets.all(8), this.hoverStyle, }); final CardCellStyleMap cellStyleMap; final bool showAccessory; final EdgeInsets cardPadding; final HoverStyle? hoverStyle; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/card/card_bloc.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:appflowy/plugins/database/application/cell/cell_controller.dart'; import 'package:appflowy/plugins/database/application/field/field_controller.dart'; import 'package:appflowy/plugins/database/application/row/row_cache.dart'; import 'package:appflowy/plugins/database/domain/row_listener.dart'; import 'package:appflowy/plugins/database/widgets/setting/field_visibility_extension.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/row_entities.pb.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'card_bloc.freezed.dart'; class CardBloc extends Bloc<CardEvent, CardState> { CardBloc({ required this.fieldController, required this.groupFieldId, required this.viewId, required RowMetaPB rowMeta, required RowCache rowCache, required bool isEditing, }) : rowId = rowMeta.id, _rowListener = RowListener(rowMeta.id), _rowCache = rowCache, super( CardState.initial( rowMeta, _makeCells( fieldController, groupFieldId, rowCache.loadCells(rowMeta), ), isEditing, ), ) { _dispatch(); } final FieldController fieldController; final String rowId; final String? groupFieldId; final RowCache _rowCache; final String viewId; final RowListener _rowListener; VoidCallback? _rowCallback; @override Future<void> close() async { if (_rowCallback != null) { _rowCache.removeRowListener(_rowCallback!); _rowCallback = null; } await _rowListener.stop(); return super.close(); } void _dispatch() { on<CardEvent>( (event, emit) async { await event.when( initial: () async { await _startListening(); }, didReceiveCells: (cells, reason) async { emit( state.copyWith( cells: cells, changeReason: reason, ), ); }, setIsEditing: (bool isEditing) { emit(state.copyWith(isEditing: isEditing)); }, didUpdateRowMeta: (rowMeta) { emit(state.copyWith(rowMeta: rowMeta)); }, ); }, ); } Future<void> _startListening() async { _rowCallback = _rowCache.addListener( rowId: rowId, onRowChanged: (cellMap, reason) { if (!isClosed) { final cells = _makeCells(fieldController, groupFieldId, cellMap); add(CardEvent.didReceiveCells(cells, reason)); } }, ); _rowListener.start( onMetaChanged: (rowMeta) { if (!isClosed) { add(CardEvent.didUpdateRowMeta(rowMeta)); } }, ); } } List<CellContext> _makeCells( FieldController fieldController, String? groupFieldId, List<CellContext> cellContexts, ) { // Only show the non-hidden cells and cells that aren't of the grouping field cellContexts.removeWhere((cellContext) { final fieldInfo = fieldController.getField(cellContext.fieldId); return fieldInfo == null || !(fieldInfo.visibility?.isVisibleState() ?? false) || (groupFieldId != null && cellContext.fieldId == groupFieldId); }); return cellContexts.toList(); } @freezed class CardEvent with _$CardEvent { const factory CardEvent.initial() = _InitialRow; const factory CardEvent.setIsEditing(bool isEditing) = _IsEditing; const factory CardEvent.didReceiveCells( List<CellContext> cells, ChangedReason reason, ) = _DidReceiveCells; const factory CardEvent.didUpdateRowMeta(RowMetaPB rowMeta) = _DidUpdateRowMeta; } @freezed class CardState with _$CardState { const factory CardState({ required List<CellContext> cells, required RowMetaPB rowMeta, required bool isEditing, ChangedReason? changeReason, }) = _RowCardState; factory CardState.initial( RowMetaPB rowMeta, List<CellContext> cells, bool isEditing, ) => CardState( cells: cells, rowMeta: rowMeta, isEditing: isEditing, ); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/card
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/card/container/accessory.dart
import 'package:flowy_infra_ui/style_widget/hover.dart'; import 'package:flutter/material.dart'; enum AccessoryType { edit, more, } abstract mixin class CardAccessory implements Widget { AccessoryType get type; void onTap(BuildContext context) {} } typedef CardAccessoryBuilder = List<CardAccessory> Function( BuildContext buildContext, ); class CardAccessoryContainer extends StatelessWidget { const CardAccessoryContainer({ super.key, required this.accessories, required this.onTapAccessory, }); final List<CardAccessory> accessories; final void Function(AccessoryType) onTapAccessory; @override Widget build(BuildContext context) { final children = accessories.map<Widget>((accessory) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { accessory.onTap(context); onTapAccessory(accessory.type); }, child: _wrapHover(context, accessory), ); }).toList(); children.insert( 1, VerticalDivider( width: 1, thickness: 1, color: Theme.of(context).brightness == Brightness.light ? const Color(0xFF1F2329).withOpacity(0.12) : const Color(0xff59647a), ), ); return _wrapDecoration( context, IntrinsicHeight(child: Row(children: children)), ); } Widget _wrapHover(BuildContext context, CardAccessory accessory) { return SizedBox( width: 24, height: 22, child: FlowyHover( style: HoverStyle( backgroundColor: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.zero, ), child: accessory, ), ); } Widget _wrapDecoration(BuildContext context, Widget child) { final decoration = BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.all(Radius.circular(4)), border: Border.fromBorderSide( BorderSide( color: Theme.of(context).brightness == Brightness.light ? const Color(0xFF1F2329).withOpacity(0.12) : const Color(0xff59647a), ), ), boxShadow: [ BoxShadow( blurRadius: 4, color: const Color(0xFF1F2329).withOpacity(0.02), ), BoxShadow( blurRadius: 4, spreadRadius: -2, color: const Color(0xFF1F2329).withOpacity(0.02), ), ], ); return Container( clipBehavior: Clip.hardEdge, decoration: decoration, child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(4)), child: child, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/card
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/card/container/card_container.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'accessory.dart'; class RowCardContainer extends StatelessWidget { const RowCardContainer({ super.key, required this.child, required this.openCard, required this.openAccessory, required this.accessories, this.buildAccessoryWhen, }); final Widget child; final void Function(BuildContext) openCard; final void Function(AccessoryType) openAccessory; final List<CardAccessory> accessories; final bool Function()? buildAccessoryWhen; @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => _CardContainerNotifier(), child: Consumer<_CardContainerNotifier>( builder: (context, notifier, _) { Widget container = Center(child: child); bool shouldBuildAccessory = true; if (buildAccessoryWhen != null) { shouldBuildAccessory = buildAccessoryWhen!.call(); } if (shouldBuildAccessory && accessories.isNotEmpty) { container = _CardEnterRegion( accessories: accessories, onTapAccessory: openAccessory, child: container, ); } return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => openCard(context), child: ConstrainedBox( constraints: const BoxConstraints(minHeight: 30), child: container, ), ); }, ), ); } } class _CardEnterRegion extends StatelessWidget { const _CardEnterRegion({ required this.child, required this.accessories, required this.onTapAccessory, }); final Widget child; final List<CardAccessory> accessories; final void Function(AccessoryType) onTapAccessory; @override Widget build(BuildContext context) { return Selector<_CardContainerNotifier, bool>( selector: (context, notifier) => notifier.onEnter, builder: (context, onEnter, _) { final List<Widget> children = [child]; if (onEnter) { children.add( Positioned( top: 10.0, right: 10.0, child: CardAccessoryContainer( accessories: accessories, onTapAccessory: onTapAccessory, ), ), ); } return MouseRegion( cursor: SystemMouseCursors.click, onEnter: (p) => Provider.of<_CardContainerNotifier>(context, listen: false) .onEnter = true, onExit: (p) => Provider.of<_CardContainerNotifier>(context, listen: false) .onEnter = false, child: IntrinsicHeight( child: Stack( alignment: AlignmentDirectional.topEnd, fit: StackFit.expand, children: children, ), ), ); }, ); } } class _CardContainerNotifier extends ChangeNotifier { _CardContainerNotifier(); bool _onEnter = false; set onEnter(bool value) { if (_onEnter != value) { _onEnter = value; notifyListeners(); } } bool get onEnter => _onEnter; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/extension.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; extension SelectOptionColorExtension on SelectOptionColorPB { Color toColor(BuildContext context) { switch (this) { case SelectOptionColorPB.Purple: return AFThemeExtension.of(context).tint1; case SelectOptionColorPB.Pink: return AFThemeExtension.of(context).tint2; case SelectOptionColorPB.LightPink: return AFThemeExtension.of(context).tint3; case SelectOptionColorPB.Orange: return AFThemeExtension.of(context).tint4; case SelectOptionColorPB.Yellow: return AFThemeExtension.of(context).tint5; case SelectOptionColorPB.Lime: return AFThemeExtension.of(context).tint6; case SelectOptionColorPB.Green: return AFThemeExtension.of(context).tint7; case SelectOptionColorPB.Aqua: return AFThemeExtension.of(context).tint8; case SelectOptionColorPB.Blue: return AFThemeExtension.of(context).tint9; default: throw ArgumentError; } } String colorName() { switch (this) { case SelectOptionColorPB.Purple: return LocaleKeys.grid_selectOption_purpleColor.tr(); case SelectOptionColorPB.Pink: return LocaleKeys.grid_selectOption_pinkColor.tr(); case SelectOptionColorPB.LightPink: return LocaleKeys.grid_selectOption_lightPinkColor.tr(); case SelectOptionColorPB.Orange: return LocaleKeys.grid_selectOption_orangeColor.tr(); case SelectOptionColorPB.Yellow: return LocaleKeys.grid_selectOption_yellowColor.tr(); case SelectOptionColorPB.Lime: return LocaleKeys.grid_selectOption_limeColor.tr(); case SelectOptionColorPB.Green: return LocaleKeys.grid_selectOption_greenColor.tr(); case SelectOptionColorPB.Aqua: return LocaleKeys.grid_selectOption_aquaColor.tr(); case SelectOptionColorPB.Blue: return LocaleKeys.grid_selectOption_blueColor.tr(); default: throw ArgumentError; } } } class SelectOptionTag extends StatelessWidget { const SelectOptionTag({ super.key, this.option, this.name, this.fontSize, this.color, this.textStyle, this.onRemove, this.textAlign, this.isExpanded = false, required this.padding, }) : assert(option != null || name != null && color != null); final SelectOptionPB? option; final String? name; final double? fontSize; final Color? color; final TextStyle? textStyle; final void Function(String)? onRemove; final EdgeInsets padding; final TextAlign? textAlign; final bool isExpanded; @override Widget build(BuildContext context) { final optionName = option?.name ?? name!; final optionColor = option?.color.toColor(context) ?? color!; final text = FlowyText.medium( optionName, fontSize: fontSize, overflow: TextOverflow.ellipsis, color: AFThemeExtension.of(context).textColor, textAlign: textAlign, ); return Container( padding: onRemove == null ? padding : padding.copyWith(right: 2.0), decoration: BoxDecoration( color: optionColor, borderRadius: BorderRadius.all( Radius.circular( PlatformExtension.isDesktopOrWeb ? 6 : 11, ), ), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ isExpanded ? Expanded(child: text) : Flexible(child: text), if (onRemove != null) ...[ const HSpace(4), FlowyIconButton( width: 16.0, onPressed: () => onRemove?.call(optionName), hoverColor: Colors.transparent, icon: const FlowySvg(FlowySvgs.close_s), ), ], ], ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/select_option_text_field.dart
import 'dart:collection'; import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart'; import 'package:flowy_infra/size.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'extension.dart'; class SelectOptionTextField extends StatefulWidget { const SelectOptionTextField({ super.key, required this.options, required this.selectedOptionMap, required this.distanceToText, required this.textSeparators, required this.textController, required this.focusNode, required this.onSubmitted, required this.newText, required this.onPaste, required this.onRemove, this.scrollController, this.onClick, }); final List<SelectOptionPB> options; final LinkedHashMap<String, SelectOptionPB> selectedOptionMap; final double distanceToText; final List<String> textSeparators; final TextEditingController textController; final ScrollController? scrollController; final FocusNode focusNode; final Function() onSubmitted; final Function(String) newText; final Function(List<String>, String) onPaste; final Function(String) onRemove; final VoidCallback? onClick; @override State<SelectOptionTextField> createState() => _SelectOptionTextFieldState(); } class _SelectOptionTextFieldState extends State<SelectOptionTextField> { @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) { widget.focusNode.requestFocus(); _scrollToEnd(); }); widget.textController.addListener(_onChanged); } @override void didUpdateWidget(covariant oldWidget) { if (oldWidget.selectedOptionMap.length < widget.selectedOptionMap.length) { WidgetsBinding.instance.addPostFrameCallback((_) { _scrollToEnd(); }); } super.didUpdateWidget(oldWidget); } @override void dispose() { widget.textController.removeListener(_onChanged); super.dispose(); } @override Widget build(BuildContext context) { return TextField( controller: widget.textController, focusNode: widget.focusNode, onTap: widget.onClick, onSubmitted: (_) => widget.onSubmitted(), style: Theme.of(context).textTheme.bodyMedium, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).colorScheme.outline), borderRadius: Corners.s10Border, ), isDense: true, prefixIcon: _renderTags(context), prefixIconConstraints: BoxConstraints(maxWidth: widget.distanceToText), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), borderRadius: Corners.s10Border, ), ), ); } void _scrollToEnd() { if (widget.scrollController?.hasClients ?? false) { widget.scrollController?.animateTo( widget.scrollController!.position.maxScrollExtent, duration: const Duration(milliseconds: 150), curve: Curves.easeOut, ); } } void _onChanged() { if (!widget.textController.value.composing.isCollapsed) { return; } // split input final (submitted, remainder) = splitInput( widget.textController.text.trimLeft(), widget.textSeparators, ); if (submitted.isNotEmpty) { widget.textController.text = remainder; widget.textController.selection = TextSelection.collapsed(offset: widget.textController.text.length); } widget.onPaste(submitted, remainder); } Widget? _renderTags(BuildContext context) { if (widget.selectedOptionMap.isEmpty) { return null; } final children = widget.selectedOptionMap.values .map( (option) => SelectOptionTag( option: option, onRemove: (option) => widget.onRemove(option), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1), ), ) .toList(); return Focus( descendantsAreFocusable: false, child: MouseRegion( cursor: SystemMouseCursors.basic, child: Padding( padding: const EdgeInsets.all(8.0), child: ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith( dragDevices: { PointerDeviceKind.mouse, PointerDeviceKind.touch, PointerDeviceKind.trackpad, PointerDeviceKind.stylus, PointerDeviceKind.invertedStylus, }, ), child: SingleChildScrollView( scrollDirection: Axis.horizontal, controller: widget.scrollController, child: Wrap(spacing: 4, children: children), ), ), ), ), ); } } @visibleForTesting (List<String>, String) splitInput(String input, List<String> textSeparators) { final List<String> splits = []; String currentString = ''; // split the string into tokens for (final char in input.split('')) { if (textSeparators.contains(char)) { if (currentString.trim().isNotEmpty) { splits.add(currentString.trim()); } currentString = ''; continue; } currentString += char; } // add the remainder (might be '') splits.add(currentString); final submittedOptions = splits.sublist(0, splits.length - 1).toList(); final remainder = splits.elementAt(splits.length - 1).trimLeft(); return (submittedOptions, remainder); }
0