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/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/math_equation/math_equation_block_component.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/mobile_block_action_buttons.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/style_widget/hover.dart'; import 'package:flowy_infra_ui/widget/buttons/primary_button.dart'; import 'package:flowy_infra_ui/widget/buttons/secondary_button.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_math_fork/flutter_math.dart'; import 'package:provider/provider.dart'; class MathEquationBlockKeys { const MathEquationBlockKeys._(); static const String type = 'math_equation'; /// The content of a math equation block. /// /// The value is a String. static const String formula = 'formula'; } Node mathEquationNode({ String formula = '', }) { final attributes = { MathEquationBlockKeys.formula: formula, }; return Node( type: MathEquationBlockKeys.type, attributes: attributes, ); } // defining the callout block menu item for selection SelectionMenuItem mathEquationItem = SelectionMenuItem.node( getName: LocaleKeys.document_plugins_mathEquation_name.tr, iconData: Icons.text_fields_rounded, keywords: ['tex, latex, katex', 'math equation', 'formula'], nodeBuilder: (editorState, _) => mathEquationNode(), replace: (_, node) => node.delta?.isEmpty ?? false, updateSelection: (editorState, path, __, ___) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) { final mathEquationState = editorState.getNodeAtPath(path)?.key.currentState; if (mathEquationState != null && mathEquationState is MathEquationBlockComponentWidgetState) { mathEquationState.showEditingDialog(); } }); return null; }, ); class MathEquationBlockComponentBuilder extends BlockComponentBuilder { MathEquationBlockComponentBuilder({ super.configuration, }); @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return MathEquationBlockComponentWidget( key: node.key, node: node, configuration: configuration, showActions: showActions(node), actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), ); } @override bool validate(Node node) => node.children.isEmpty && node.attributes[MathEquationBlockKeys.formula] is String; } class MathEquationBlockComponentWidget extends BlockComponentStatefulWidget { const MathEquationBlockComponentWidget({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), }); @override State<MathEquationBlockComponentWidget> createState() => MathEquationBlockComponentWidgetState(); } class MathEquationBlockComponentWidgetState extends State<MathEquationBlockComponentWidget> with BlockComponentConfigurable { @override BlockComponentConfiguration get configuration => widget.configuration; @override Node get node => widget.node; bool isHover = false; String get formula => widget.node.attributes[MathEquationBlockKeys.formula] as String; late final editorState = context.read<EditorState>(); @override Widget build(BuildContext context) { return InkWell( onHover: (value) => setState(() => isHover = value), onTap: showEditingDialog, child: _build(context), ); } Widget _build(BuildContext context) { Widget child = Container( constraints: const BoxConstraints(minHeight: 52), decoration: BoxDecoration( color: formula.isNotEmpty ? Colors.transparent : Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(4), ), child: FlowyHover( style: HoverStyle( borderRadius: BorderRadius.circular(4), ), child: formula.isEmpty ? _buildPlaceholderWidget(context) : _buildMathEquation(context), ), ); child = Padding( padding: padding, child: child, ); if (widget.showActions && widget.actionBuilder != null) { child = BlockComponentActionWrapper( node: node, actionBuilder: widget.actionBuilder!, child: child, ); } if (PlatformExtension.isMobile) { child = MobileBlockActionButtons( node: node, editorState: editorState, child: child, ); } return child; } Widget _buildPlaceholderWidget(BuildContext context) { return SizedBox( height: 52, child: Row( children: [ const HSpace(10), const Icon(Icons.text_fields_outlined), const HSpace(10), FlowyText( LocaleKeys.document_plugins_mathEquation_addMathEquation.tr(), ), ], ), ); } Widget _buildMathEquation(BuildContext context) { return Center( child: Math.tex( formula, textStyle: const TextStyle(fontSize: 20), ), ); } void showEditingDialog() { final controller = TextEditingController(text: formula); showDialog( context: context, builder: (context) { return AlertDialog( backgroundColor: Theme.of(context).canvasColor, title: Text( LocaleKeys.document_plugins_mathEquation_editMathEquation.tr(), ), content: KeyboardListener( focusNode: FocusNode(), onKeyEvent: (key) { if (key.logicalKey == LogicalKeyboardKey.enter && !HardwareKeyboard.instance.isShiftPressed) { updateMathEquation(controller.text, context); } else if (key.logicalKey == LogicalKeyboardKey.escape) { dismiss(context); } }, child: SizedBox( width: MediaQuery.of(context).size.width * 0.3, child: TextField( autofocus: true, controller: controller, maxLines: null, decoration: const InputDecoration( border: OutlineInputBorder(), hintText: 'E = MC^2', ), ), ), ), actions: [ SecondaryTextButton( LocaleKeys.button_cancel.tr(), mode: TextButtonMode.big, onPressed: () => dismiss(context), ), PrimaryTextButton( LocaleKeys.button_done.tr(), onPressed: () => updateMathEquation(controller.text, context), ), ], actionsPadding: const EdgeInsets.only(bottom: 20), actionsAlignment: MainAxisAlignment.spaceAround, ); }, ).then((_) => controller.dispose()); } void updateMathEquation(String mathEquation, BuildContext context) { if (mathEquation == formula) { dismiss(context); return; } final transaction = editorState.transaction ..updateNode( widget.node, { MathEquationBlockKeys.formula: mathEquation, }, ); editorState.apply(transaction); dismiss(context); } void dismiss(BuildContext context) { Navigator.of(context).pop(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/string_extension.dart
extension Capitalize on String { String capitalize() { return "${this[0].toUpperCase()}${substring(1)}"; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/text_robot.dart
import 'package:appflowy_editor/appflowy_editor.dart'; enum TextRobotInputType { character, word, } class TextRobot { const TextRobot({ required this.editorState, }); final EditorState editorState; Future<void> autoInsertText( String text, { TextRobotInputType inputType = TextRobotInputType.word, Duration delay = const Duration(milliseconds: 10), }) async { if (text == '\n') { return editorState.insertNewLine(); } final lines = text.split('\n'); for (final line in lines) { if (line.isEmpty) { await editorState.insertNewLine(); continue; } switch (inputType) { case TextRobotInputType.character: final iterator = line.runes.iterator; while (iterator.moveNext()) { await editorState.insertTextAtCurrentSelection( iterator.currentAsString, ); await Future.delayed(delay); } break; case TextRobotInputType.word: final words = line.split(' '); if (words.length == 1 || (words.length == 2 && (words.first.isEmpty || words.last.isEmpty))) { await editorState.insertTextAtCurrentSelection( line, ); } else { for (final word in words.map((e) => '$e ')) { await editorState.insertTextAtCurrentSelection( word, ); } } await Future.delayed(delay); break; } } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/build_context_extension.dart
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; extension BuildContextExtension on BuildContext { /// returns a boolean value indicating whether the given offset is contained within the bounds of the specified RenderBox or not. bool isOffsetInside(Offset offset) { final box = findRenderObject() as RenderBox?; if (box == null) { return false; } final result = BoxHitTestResult(); box.hitTest(result, position: box.globalToLocal(offset)); return result.path.any((entry) => entry.target == box); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/page_reference_commands.dart
import 'package:flutter/material.dart'; import 'package:appflowy/plugins/inline_actions/handlers/inline_page_reference.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; const _bracketChar = '['; const _plusChar = '+'; CharacterShortcutEvent pageReferenceShortcutBrackets( BuildContext context, String viewId, InlineActionsMenuStyle style, ) => CharacterShortcutEvent( key: 'show the inline page reference menu by [', character: _bracketChar, handler: (editorState) => inlinePageReferenceCommandHandler( _bracketChar, context, viewId, editorState, style, previousChar: _bracketChar, ), ); CharacterShortcutEvent pageReferenceShortcutPlusSign( BuildContext context, String viewId, InlineActionsMenuStyle style, ) => CharacterShortcutEvent( key: 'show the inline page reference menu by +', character: _plusChar, handler: (editorState) => inlinePageReferenceCommandHandler( _plusChar, context, viewId, editorState, style, ), ); InlineActionsMenuService? selectionMenuService; Future<bool> inlinePageReferenceCommandHandler( String character, BuildContext context, String currentViewId, EditorState editorState, InlineActionsMenuStyle style, { String? previousChar, }) async { final selection = editorState.selection; if (PlatformExtension.isMobile || selection == null) { return false; } if (!selection.isCollapsed) { await editorState.deleteSelection(selection); } // Check for previous character if (previousChar != null) { final node = editorState.getNodeAtPath(selection.end.path); final delta = node?.delta; if (node == null || delta == null || delta.isEmpty) { return false; } if (selection.end.offset > 0) { final plain = delta.toPlainText(); final previousCharacter = plain[selection.end.offset - 1]; if (previousCharacter != _bracketChar) { return false; } } } if (!context.mounted) { return false; } final service = InlineActionsService( context: context, handlers: [ InlinePageReferenceService( currentViewId: currentViewId, limitResults: 10, ), ], ); await editorState.insertTextAtPosition(character, position: selection.start); final List<InlineActionsResult> initialResults = []; for (final handler in service.handlers) { final group = await handler.search(null); if (group.results.isNotEmpty) { initialResults.add(group); } } if (context.mounted) { selectionMenuService = InlineActionsMenu( context: service.context!, editorState: editorState, service: service, initialResults: initialResults, style: style, startCharAmount: previousChar != null ? 2 : 1, ); selectionMenuService?.show(); } return true; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/selectable_svg_widget.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; class SelectableSvgWidget extends StatelessWidget { const SelectableSvgWidget({ super.key, required this.data, required this.isSelected, required this.style, }); final FlowySvgData data; final bool isSelected; final SelectionMenuStyle style; @override Widget build(BuildContext context) { return FlowySvg( data, size: const Size.square(18.0), color: isSelected ? style.selectionMenuItemSelectedIconColor : style.selectionMenuItemIconColor, ); } } class SelectableIconWidget extends StatelessWidget { const SelectableIconWidget({ super.key, required this.icon, required this.isSelected, required this.style, }); final IconData icon; final bool isSelected; final SelectionMenuStyle style; @override Widget build(BuildContext context) { return Icon( icon, size: 18.0, color: isSelected ? style.selectionMenuItemSelectedIconColor : style.selectionMenuItemIconColor, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/link_to_page_widget.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/inline_actions/handlers/inline_page_reference.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; InlineActionsMenuService? _actionsMenuService; Future<void> showLinkToPageMenu( EditorState editorState, SelectionMenuService menuService, ViewLayoutPB pageType, ) async { menuService.dismiss(); _actionsMenuService?.dismiss(); final rootContext = editorState.document.root.context; if (rootContext == null) { return; } final service = InlineActionsService( context: rootContext, handlers: [ InlinePageReferenceService( currentViewId: "", viewLayout: pageType, customTitle: titleFromPageType(pageType), insertPage: pageType != ViewLayoutPB.Document, limitResults: 15, ), ], ); final List<InlineActionsResult> initialResults = []; for (final handler in service.handlers) { final group = await handler.search(null); if (group.results.isNotEmpty) { initialResults.add(group); } } if (rootContext.mounted) { _actionsMenuService = InlineActionsMenu( context: rootContext, editorState: editorState, service: service, initialResults: initialResults, style: Theme.of(editorState.document.root.context!).brightness == Brightness.light ? const InlineActionsMenuStyle.light() : const InlineActionsMenuStyle.dark(), startCharAmount: 0, ); _actionsMenuService?.show(); } } String titleFromPageType(ViewLayoutPB layout) => switch (layout) { ViewLayoutPB.Grid => LocaleKeys.inlineActions_gridReference.tr(), ViewLayoutPB.Document => LocaleKeys.inlineActions_docReference.tr(), ViewLayoutPB.Board => LocaleKeys.inlineActions_boardReference.tr(), ViewLayoutPB.Calendar => LocaleKeys.inlineActions_calReference.tr(), _ => LocaleKeys.inlineActions_pageReference.tr(), };
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/built_in_page_widget.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/startup/plugin/plugin.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy/workspace/application/view/view_service.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/style_widget/icon_button.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flutter/material.dart'; class BuiltInPageWidget extends StatefulWidget { const BuiltInPageWidget({ super.key, required this.node, required this.editorState, required this.builder, }); final Node node; final EditorState editorState; final Widget Function(ViewPB viewPB) builder; @override State<BuiltInPageWidget> createState() => _BuiltInPageWidgetState(); } class _BuiltInPageWidgetState extends State<BuiltInPageWidget> { late Future<FlowyResult<ViewPB, FlowyError>> future; final focusNode = FocusNode(); String get parentViewId => widget.node.attributes[DatabaseBlockKeys.parentID]; String get childViewId => widget.node.attributes[DatabaseBlockKeys.viewID]; @override void initState() { super.initState(); future = ViewBackendService().getChildView( parentViewId: parentViewId, childViewId: childViewId, ); } @override void dispose() { focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return FutureBuilder<FlowyResult<ViewPB, FlowyError>>( builder: (context, snapshot) { final page = snapshot.data?.toNullable(); if (snapshot.hasData && page != null) { return _build(context, page); } if (snapshot.connectionState == ConnectionState.done) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) { // just delete the page if it is not found _deletePage(); }); return const Center( child: FlowyText('Cannot load the page'), ); } return const Center( child: CircularProgressIndicator(), ); }, future: future, ); } Widget _build(BuildContext context, ViewPB viewPB) { return MouseRegion( onEnter: (_) => widget.editorState.service.scrollService?.disable(), onExit: (_) => widget.editorState.service.scrollService?.enable(), child: SizedBox( height: viewPB.pluginType == PluginType.calendar ? 700 : 400, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildMenu(context, viewPB), Expanded(child: _buildPage(context, viewPB)), ], ), ), ); } Widget _buildPage(BuildContext context, ViewPB viewPB) { return Focus( focusNode: focusNode, onFocusChange: (value) { if (value) { widget.editorState.service.selectionService.clearSelection(); } }, child: widget.builder(viewPB), ); } Widget _buildMenu(BuildContext context, ViewPB viewPB) { return Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ // information FlowyIconButton( tooltipText: LocaleKeys.tooltip_referencePage.tr( namedArgs: {'name': viewPB.layout.name}, ), width: 24, height: 24, iconPadding: const EdgeInsets.all(3), icon: const FlowySvg( FlowySvgs.information_s, ), iconColorOnHover: Theme.of(context).colorScheme.onSecondary, ), // setting const Space(7, 0), PopoverActionList<_ActionWrapper>( direction: PopoverDirection.bottomWithCenterAligned, actions: _ActionType.values .map((action) => _ActionWrapper(action)) .toList(), buildChild: (controller) => FlowyIconButton( tooltipText: LocaleKeys.tooltip_openMenu.tr(), width: 24, height: 24, iconPadding: const EdgeInsets.all(3), iconColorOnHover: Theme.of(context).colorScheme.onSecondary, icon: const FlowySvg( FlowySvgs.settings_s, ), onPressed: () => controller.show(), ), onSelected: (action, controller) async { switch (action.inner) { case _ActionType.viewDatabase: getIt<TabsBloc>().add( TabsEvent.openPlugin( plugin: viewPB.plugin(), view: viewPB, ), ); break; case _ActionType.delete: final transaction = widget.editorState.transaction; transaction.deleteNode(widget.node); await widget.editorState.apply(transaction); break; } controller.close(); }, ), ], ); } Future<void> _deletePage() async { final transaction = widget.editorState.transaction; transaction.deleteNode(widget.node); await widget.editorState.apply(transaction); } } enum _ActionType { viewDatabase, delete, } class _ActionWrapper extends ActionCell { _ActionWrapper(this.inner); final _ActionType inner; Widget? icon(Color iconColor) => null; @override String get name { switch (inner) { case _ActionType.viewDatabase: return LocaleKeys.tooltip_viewDataBase.tr(); case _ActionType.delete: return LocaleKeys.disclosureAction_delete.tr(); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/format_arrow_character.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; const _greater = '>'; const _equals = '='; const _arrow = 'β‡’'; /// format '=' + '>' into an β‡’ /// /// - support /// - desktop /// - mobile /// - web /// final CharacterShortcutEvent customFormatGreaterEqual = CharacterShortcutEvent( key: 'format = + > into β‡’', character: _greater, handler: (editorState) async => _handleDoubleCharacterReplacement( editorState: editorState, character: _greater, replacement: _arrow, prefixCharacter: _equals, ), ); /// If [prefixCharacter] is null or empty, [character] is used Future<bool> _handleDoubleCharacterReplacement({ required EditorState editorState, required String character, required String replacement, String? prefixCharacter, }) async { assert(character.length == 1); final selection = editorState.selection; if (selection == null) { return false; } if (!selection.isCollapsed) { await editorState.deleteSelection(selection); } final node = editorState.getNodeAtPath(selection.end.path); final delta = node?.delta; if (node == null || delta == null || delta.isEmpty || node.type == CodeBlockKeys.type) { return false; } if (selection.end.offset > 0) { final plain = delta.toPlainText(); final expectedPrevious = prefixCharacter?.isEmpty ?? true ? character : prefixCharacter; final previousCharacter = plain[selection.end.offset - 1]; if (previousCharacter != expectedPrevious) { return false; } final replace = editorState.transaction ..replaceText( node, selection.end.offset - 1, 1, replacement, ); await editorState.apply(replace); return true; } return false; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/insert_page_command.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/database/domain/database_view_service.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.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_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; extension InsertDatabase on EditorState { Future<void> insertInlinePage(String parentViewId, ViewPB childView) async { final selection = this.selection; if (selection == null || !selection.isCollapsed) { return; } final node = getNodeAtPath(selection.end.path); if (node == null) { return; } final transaction = this.transaction; transaction.insertNode( selection.end.path, Node( type: _convertPageType(childView), attributes: { DatabaseBlockKeys.parentID: parentViewId, DatabaseBlockKeys.viewID: childView.id, }, ), ); await apply(transaction); } Future<void> insertReferencePage( ViewPB childView, ViewLayoutPB viewType, ) async { final selection = this.selection; if (selection == null || !selection.isCollapsed) { throw FlowyError( msg: "Could not insert the reference page because the current selection was null or collapsed.", ); } final node = getNodeAtPath(selection.end.path); if (node == null) { throw FlowyError( msg: "Could not insert the reference page because the current node at the selection does not exist.", ); } final Transaction transaction = viewType == ViewLayoutPB.Document ? await _insertDocumentReference(childView, selection, node) : await _insertDatabaseReference(childView, selection.end.path); await apply(transaction); } Future<Transaction> _insertDocumentReference( ViewPB view, Selection selection, Node node, ) async { return transaction ..replaceText( node, selection.end.offset, 0, r'$', attributes: { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.page.name, MentionBlockKeys.pageId: view.id, }, }, ); } Future<Transaction> _insertDatabaseReference( ViewPB view, List<int> path, ) async { // get the database id that the view is associated with final databaseId = await DatabaseViewBackendService(viewId: view.id) .getDatabaseId() .then((value) => value.toNullable()); if (databaseId == null) { throw StateError( 'The database associated with ${view.id} could not be found while attempting to create a referenced ${view.layout.name}.', ); } final prefix = _referencedDatabasePrefix(view.layout); final ref = await ViewBackendService.createDatabaseLinkedView( parentViewId: view.id, name: "$prefix ${view.name}", layoutType: view.layout, databaseId: databaseId, ).then((value) => value.toNullable()); if (ref == null) { throw FlowyError( msg: "The `ViewBackendService` failed to create a database reference view", ); } return transaction ..insertNode( path, Node( type: _convertPageType(view), attributes: { DatabaseBlockKeys.parentID: view.id, DatabaseBlockKeys.viewID: ref.id, }, ), ); } String _referencedDatabasePrefix(ViewLayoutPB layout) { switch (layout) { case ViewLayoutPB.Grid: return LocaleKeys.grid_referencedGridPrefix.tr(); case ViewLayoutPB.Board: return LocaleKeys.board_referencedBoardPrefix.tr(); case ViewLayoutPB.Calendar: return LocaleKeys.calendar_referencedCalendarPrefix.tr(); default: throw UnimplementedError(); } } String _convertPageType(ViewPB viewPB) { switch (viewPB.layout) { case ViewLayoutPB.Grid: return DatabaseBlockKeys.gridType; case ViewLayoutPB.Board: return DatabaseBlockKeys.boardType; case ViewLayoutPB.Calendar: return DatabaseBlockKeys.calendarType; default: throw Exception('Unknown layout type'); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/selectable_item_list_menu.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; class SelectableItemListMenu extends StatelessWidget { const SelectableItemListMenu({ super.key, required this.items, required this.selectedIndex, required this.onSelected, this.shrinkWrap = false, }); final List<String> items; final int selectedIndex; final void Function(int) onSelected; /// shrinkWrapping is useful in cases where you have a list of /// limited amount of items. It will make the list take the minimum /// amount of space required to show all the items. /// final bool shrinkWrap; @override Widget build(BuildContext context) { return ListView.builder( shrinkWrap: shrinkWrap, itemCount: items.length, itemBuilder: (context, index) => SelectableItem( isSelected: index == selectedIndex, item: items[index], onTap: () => onSelected(index), ), ); } } class SelectableItem extends StatelessWidget { const SelectableItem({ super.key, required this.isSelected, required this.item, required this.onTap, }); final bool isSelected; final String item; final VoidCallback onTap; @override Widget build(BuildContext context) { return SizedBox( height: 32, child: FlowyButton( text: FlowyText.medium(item), rightIcon: isSelected ? const FlowySvg(FlowySvgs.check_s) : null, onTap: onTap, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/emoji_picker_button.dart
import 'package:appflowy/plugins/base/emoji/emoji_picker_screen.dart'; import 'package:appflowy/plugins/base/icon/icon_picker.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/emoji_picker/emoji_picker.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class EmojiPickerButton extends StatelessWidget { EmojiPickerButton({ super.key, required this.emoji, required this.onSubmitted, this.emojiPickerSize = const Size(360, 380), this.emojiSize = 18.0, this.defaultIcon, this.offset, this.direction, this.title, }); final String emoji; final double emojiSize; final Size emojiPickerSize; final void Function(String emoji, PopoverController? controller) onSubmitted; final PopoverController popoverController = PopoverController(); final Widget? defaultIcon; final Offset? offset; final PopoverDirection? direction; final String? title; @override Widget build(BuildContext context) { if (PlatformExtension.isDesktopOrWeb) { return AppFlowyPopover( controller: popoverController, constraints: BoxConstraints.expand( width: emojiPickerSize.width, height: emojiPickerSize.height, ), offset: offset, direction: direction ?? PopoverDirection.rightWithTopAligned, popupBuilder: (context) => Container( width: emojiPickerSize.width, height: emojiPickerSize.height, padding: const EdgeInsets.all(4.0), child: EmojiSelectionMenu( onSubmitted: (emoji) => onSubmitted(emoji, popoverController), onExit: () {}, ), ), child: emoji.isEmpty && defaultIcon != null ? FlowyButton( useIntrinsicWidth: true, text: defaultIcon!, onTap: () => popoverController.show(), ) : FlowyTextButton( emoji, overflow: TextOverflow.visible, fontSize: emojiSize, padding: EdgeInsets.zero, constraints: const BoxConstraints(minWidth: 35.0), fillColor: Colors.transparent, mainAxisAlignment: MainAxisAlignment.center, onPressed: () { popoverController.show(); }, ), ); } else { return FlowyTextButton( emoji, overflow: TextOverflow.visible, fontSize: emojiSize, padding: EdgeInsets.zero, constraints: const BoxConstraints(minWidth: 35.0), fillColor: Colors.transparent, mainAxisAlignment: MainAxisAlignment.center, onPressed: () async { final result = await context.push<EmojiPickerResult>( Uri( path: MobileEmojiPickerScreen.routeName, queryParameters: { MobileEmojiPickerScreen.pageTitle: title, }, ).toString(), ); if (result != null) { onSubmitted( result.emoji, null, ); } }, ); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/toolbar_extension.dart
import 'package:appflowy_editor/appflowy_editor.dart'; bool notShowInTable(EditorState editorState) { final selection = editorState.selection; if (selection == null) { return false; } final nodes = editorState.getNodesInSelection(selection); return nodes.every((element) { if (element.type == TableBlockKeys.type) { return false; } var parent = element.parent; while (parent != null) { if (parent.type == TableBlockKeys.type) { return false; } parent = parent.parent; } return true; }); } bool onlyShowInSingleTextTypeSelectionAndExcludeTable( EditorState editorState, ) { return onlyShowInSingleSelectionAndTextType(editorState) && notShowInTable(editorState); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/show_mobile_bottom_sheet.dart'; import 'package:appflowy/plugins/base/drag_handler.dart'; import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart'; import 'package:appflowy/plugins/document/application/document_bloc.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy/user/application/reminder/reminder_bloc.dart'; import 'package:appflowy/user/application/reminder/reminder_extension.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:appflowy/workspace/application/settings/date_time/date_format_ext.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/utils/user_time_format_ext.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_picker_dialog.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/mobile_date_header.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pbenum.dart'; import 'package:appflowy_backend/protobuf/flowy-user/date_time.pbenum.dart'; import 'package:appflowy_backend/protobuf/flowy-user/reminder.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:calendar_view/calendar_view.dart'; import 'package:collection/collection.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fixnum/fixnum.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nanoid/non_secure.dart'; class MentionDateBlock extends StatefulWidget { const MentionDateBlock({ super.key, required this.editorState, required this.date, required this.index, required this.node, this.reminderId, this.reminderOption, this.includeTime = false, }); final EditorState editorState; final String date; final int index; final Node node; /// If [isReminder] is true, then this must not be /// null or empty final String? reminderId; final ReminderOption? reminderOption; final bool includeTime; @override State<MentionDateBlock> createState() => _MentionDateBlockState(); } class _MentionDateBlockState extends State<MentionDateBlock> { final PopoverMutex mutex = PopoverMutex(); late bool _includeTime = widget.includeTime; late DateTime? parsedDate = DateTime.tryParse(widget.date); @override Widget build(BuildContext context) { if (parsedDate == null) { return const SizedBox.shrink(); } final fontSize = context.read<DocumentAppearanceCubit>().state.fontSize; return MultiBlocProvider( providers: [ BlocProvider<ReminderBloc>.value(value: context.read<ReminderBloc>()), BlocProvider<AppearanceSettingsCubit>.value( value: context.read<AppearanceSettingsCubit>(), ), ], child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>( buildWhen: (previous, current) => previous.dateFormat != current.dateFormat || previous.timeFormat != current.timeFormat, builder: (context, appearance) => BlocBuilder<ReminderBloc, ReminderState>( builder: (context, state) { final reminder = state.reminders .firstWhereOrNull((r) => r.id == widget.reminderId); final formattedDate = appearance.dateFormat .formatDate(parsedDate!, _includeTime, appearance.timeFormat); final timeStr = parsedDate != null ? _timeFromDate(parsedDate!, appearance.timeFormat) : null; final options = DatePickerOptions( focusedDay: parsedDate, popoverMutex: mutex, selectedDay: parsedDate, timeStr: timeStr, includeTime: _includeTime, dateFormat: appearance.dateFormat, timeFormat: appearance.timeFormat, selectedReminderOption: widget.reminderOption, onIncludeTimeChanged: (includeTime) { _includeTime = includeTime; if (![null, ReminderOption.none] .contains(widget.reminderOption)) { _updateReminder( widget.reminderOption!, reminder, includeTime, ); } else { _updateBlock( parsedDate!.withoutTime, includeTime: includeTime, ); } }, onStartTimeChanged: (time) { final parsed = _parseTime(time, appearance.timeFormat); parsedDate = parsedDate!.withoutTime .add(Duration(hours: parsed.hour, minutes: parsed.minute)); if (![null, ReminderOption.none] .contains(widget.reminderOption)) { _updateReminder( widget.reminderOption!, reminder, _includeTime, ); } else { _updateBlock(parsedDate!, includeTime: _includeTime); } }, onDaySelected: (selectedDay, focusedDay) { parsedDate = selectedDay; if (![null, ReminderOption.none] .contains(widget.reminderOption)) { _updateReminder( widget.reminderOption!, reminder, _includeTime, ); } else { _updateBlock(selectedDay, includeTime: _includeTime); } }, onReminderSelected: (reminderOption) => _updateReminder(reminderOption, reminder), ); return GestureDetector( onTapDown: (details) { if (widget.editorState.editable) { if (PlatformExtension.isMobile) { showMobileBottomSheet( context, builder: (_) => DraggableScrollableSheet( expand: false, snap: true, initialChildSize: 0.7, minChildSize: 0.4, snapSizes: const [0.4, 0.7, 1.0], builder: (_, controller) => Material( color: Theme.of(context).colorScheme.secondaryContainer, child: ListView( controller: controller, children: [ ColoredBox( color: Theme.of(context).colorScheme.surface, child: const Center(child: DragHandle()), ), const MobileDateHeader(), MobileAppFlowyDatePicker( selectedDay: parsedDate, timeStr: timeStr, dateStr: parsedDate != null ? options.dateFormat .formatDate(parsedDate!, _includeTime) : null, includeTime: options.includeTime, use24hFormat: options.timeFormat == UserTimeFormatPB.TwentyFourHour, rebuildOnDaySelected: true, rebuildOnTimeChanged: true, timeFormat: options.timeFormat.simplified, selectedReminderOption: widget.reminderOption, onDaySelected: options.onDaySelected, onStartTimeChanged: (time) => options .onStartTimeChanged ?.call(time ?? ""), onIncludeTimeChanged: options.onIncludeTimeChanged, liveDateFormatter: (selected) => appearance.dateFormat.formatDate( selected, false, appearance.timeFormat, ), onReminderSelected: (option) => _updateReminder(option, reminder), ), ], ), ), ), ); } else { DatePickerMenu( context: context, editorState: widget.editorState, ).show(details.globalPosition, options: options); } } }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: MouseRegion( cursor: SystemMouseCursors.click, child: Row( mainAxisSize: MainAxisSize.min, children: [ FlowySvg( widget.reminderId != null ? FlowySvgs.clock_alarm_s : FlowySvgs.date_s, size: const Size.square(18.0), color: reminder?.isAck == true ? Theme.of(context).colorScheme.error : null, ), const HSpace(2), FlowyText( formattedDate, fontSize: fontSize, color: reminder?.isAck == true ? Theme.of(context).colorScheme.error : null, ), ], ), ), ), ); }, ), ), ); } DateTime _parseTime(String timeStr, UserTimeFormatPB timeFormat) { final twelveHourFormat = DateFormat('hh:mm a'); final twentyFourHourFormat = DateFormat('HH:mm'); try { if (timeFormat == UserTimeFormatPB.TwelveHour) { return twelveHourFormat.parseStrict(timeStr); } return twentyFourHourFormat.parseStrict(timeStr); } on FormatException { Log.error("failed to parse time string ($timeStr)"); return DateTime.now(); } } String _timeFromDate(DateTime date, UserTimeFormatPB timeFormat) { final twelveHourFormat = DateFormat('HH:mm a'); final twentyFourHourFormat = DateFormat('HH:mm'); if (timeFormat == TimeFormatPB.TwelveHour) { return twelveHourFormat.format(date); } return twentyFourHourFormat.format(date); } void _updateBlock( DateTime date, { bool includeTime = false, String? reminderId, ReminderOption? reminderOption, }) { final rId = reminderId ?? (reminderOption == ReminderOption.none ? null : widget.reminderId); final transaction = widget.editorState.transaction ..formatText(widget.node, widget.index, 1, { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.date.name, MentionBlockKeys.date: date.toIso8601String(), MentionBlockKeys.reminderId: rId, MentionBlockKeys.includeTime: includeTime, MentionBlockKeys.reminderOption: reminderOption?.name ?? widget.reminderOption?.name, }, }); widget.editorState.apply(transaction, withUpdateSelection: false); // Length of rendered block changes, this synchronizes // the cursor with the new block render widget.editorState.updateSelectionWithReason( widget.editorState.selection, ); } void _updateReminder( ReminderOption reminderOption, ReminderPB? reminder, [ bool includeTime = false, ]) { final rootContext = widget.editorState.document.root.context; if (parsedDate == null || rootContext == null) { return; } if (widget.reminderId != null) { _updateBlock( parsedDate!, includeTime: includeTime, reminderOption: reminderOption, ); if (ReminderOption.none == reminderOption && reminder != null) { // Delete existing reminder return rootContext .read<ReminderBloc>() .add(ReminderEvent.remove(reminderId: reminder.id)); } // Update existing reminder return rootContext.read<ReminderBloc>().add( ReminderEvent.update( ReminderUpdate( id: widget.reminderId!, scheduledAt: reminderOption.fromDate(parsedDate!), ), ), ); } final reminderId = nanoid(); _updateBlock( parsedDate!, includeTime: includeTime, reminderId: reminderId, reminderOption: reminderOption, ); // Add new reminder final viewId = rootContext.read<DocumentBloc>().view.id; return rootContext.read<ReminderBloc>().add( ReminderEvent.add( reminder: ReminderPB( id: reminderId, objectId: viewId, title: LocaleKeys.reminderNotification_title.tr(), message: LocaleKeys.reminderNotification_message.tr(), meta: { ReminderMetaKeys.includeTime: false.toString(), ReminderMetaKeys.blockId: widget.node.id, }, scheduledAt: Int64(parsedDate!.millisecondsSinceEpoch ~/ 1000), isAck: parsedDate!.isBefore(DateTime.now()), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/slash_menu_items.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; SelectionMenuItem dateMenuItem = SelectionMenuItem( getName: LocaleKeys.document_plugins_insertDate.tr, icon: (_, isSelected, style) => FlowySvg( FlowySvgs.date_s, color: isSelected ? style.selectionMenuItemSelectedIconColor : style.selectionMenuItemIconColor, ), keywords: ['insert date', 'date', 'time'], handler: (editorState, menuService, context) => _insertDateReference(editorState), ); Future<void> _insertDateReference(EditorState editorState) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = editorState.getNodeAtPath(selection.end.path); final delta = node?.delta; if (node == null || delta == null) { return; } final transaction = editorState.transaction ..replaceText( node, selection.start.offset, 0, '\$', attributes: { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.date.name, MentionBlockKeys.date: DateTime.now().toIso8601String(), }, }, ); await editorState.apply(transaction); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/mobile/application/mobile_router.dart'; import 'package:appflowy/plugins/base/emoji/emoji_text.dart'; import 'package:appflowy/plugins/trash/application/trash_service.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart'; import 'package:appflowy/workspace/application/view/prelude.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart'; import 'package:appflowy_editor/appflowy_editor.dart' show EditorState, PlatformExtension; 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 'package:provider/provider.dart'; final pageMemorizer = <String, ViewPB?>{}; class MentionPageBlock extends StatefulWidget { const MentionPageBlock({ super.key, required this.pageId, required this.textStyle, }); final String pageId; final TextStyle? textStyle; @override State<MentionPageBlock> createState() => _MentionPageBlockState(); } class _MentionPageBlockState extends State<MentionPageBlock> { late final EditorState editorState; late final ViewListener viewListener = ViewListener(viewId: widget.pageId); late Future<ViewPB?> viewPBFuture; @override void initState() { super.initState(); editorState = context.read<EditorState>(); viewPBFuture = fetchView(widget.pageId); viewListener.start( onViewUpdated: (p0) { pageMemorizer[p0.id] = p0; viewPBFuture = fetchView(widget.pageId); editorState.reload(); }, ); } @override void dispose() { viewListener.stop(); super.dispose(); } @override Widget build(BuildContext context) { return FutureBuilder<ViewPB?>( initialData: pageMemorizer[widget.pageId], future: viewPBFuture, builder: (context, state) { final view = state.data; // memorize the result pageMemorizer[widget.pageId] = view; if (view == null) { return const SizedBox.shrink(); } // updateSelection(); final iconSize = widget.textStyle?.fontSize ?? 16.0; return Padding( padding: const EdgeInsets.symmetric(horizontal: 2), child: FlowyHover( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () => openPage(widget.pageId), behavior: HitTestBehavior.translucent, child: Row( mainAxisSize: MainAxisSize.min, children: [ const HSpace(4), view.icon.value.isNotEmpty ? EmojiText( emoji: view.icon.value, fontSize: 12, textAlign: TextAlign.center, lineHeight: 1.3, ) : FlowySvg( view.layout.icon, size: Size.square(iconSize + 2.0), ), const HSpace(2), FlowyText( view.name, decoration: TextDecoration.underline, fontSize: widget.textStyle?.fontSize, fontWeight: widget.textStyle?.fontWeight, ), const HSpace(2), ], ), ), ), ); }, ); } void openPage(String pageId) async { final view = await fetchView(pageId); if (view == null) { Log.error('Page($pageId) not found'); return; } if (PlatformExtension.isDesktopOrWeb) { getIt<TabsBloc>().add( TabsEvent.openPlugin( plugin: view.plugin(), view: view, ), ); } else { if (mounted) { await context.pushView(view); } } } Future<ViewPB?> fetchView(String pageId) async { final view = await ViewBackendService.getView(pageId).then( (value) => value.toNullable(), ); if (view == null) { // try to fetch from trash final trashViews = await TrashService().readTrash(); final trash = trashViews.fold( (l) => l.items.firstWhereOrNull((element) => element.id == pageId), (r) => null, ); if (trash != null) { return ViewPB() ..id = trash.id ..name = trash.name; } } return view; } void updateSelection() { WidgetsBinding.instance.addPostFrameCallback((timeStamp) { editorState.updateSelectionWithReason( editorState.selection, ); }); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; enum MentionType { page, reminder, date; static MentionType fromString(String value) => switch (value) { 'page' => page, 'date' => date, // Backwards compatibility 'reminder' => date, _ => throw UnimplementedError(), }; } Node dateMentionNode() { return paragraphNode( delta: Delta( operations: [ TextInsert( '\$', attributes: { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.date.name, MentionBlockKeys.date: DateTime.now().toIso8601String(), }, }, ), ], ), ); } class MentionBlockKeys { const MentionBlockKeys._(); static const reminderId = 'reminder_id'; // ReminderID static const mention = 'mention'; static const type = 'type'; // MentionType, String static const pageId = 'page_id'; // Related to Reminder and Date blocks static const date = 'date'; // Start Date static const includeTime = 'include_time'; static const reminderOption = 'reminder_option'; } class MentionBlock extends StatelessWidget { const MentionBlock({ super.key, required this.mention, required this.node, required this.index, required this.textStyle, }); final Map<String, dynamic> mention; final Node node; final int index; final TextStyle? textStyle; @override Widget build(BuildContext context) { final type = MentionType.fromString(mention[MentionBlockKeys.type]); switch (type) { case MentionType.page: final String pageId = mention[MentionBlockKeys.pageId]; return MentionPageBlock( key: ValueKey(pageId), pageId: pageId, textStyle: textStyle, ); case MentionType.date: final String date = mention[MentionBlockKeys.date]; final editorState = context.read<EditorState>(); final reminderOption = ReminderOption.values.firstWhereOrNull( (o) => o.name == mention[MentionBlockKeys.reminderOption], ); return MentionDateBlock( key: ValueKey(date), editorState: editorState, date: date, node: node, index: index, reminderId: mention[MentionBlockKeys.reminderId], reminderOption: reminderOption, includeTime: mention[MentionBlockKeys.includeTime] ?? false, ); default: return const SizedBox.shrink(); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/error/error_block_component_builder.dart
import 'dart:convert'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/mobile_block_action_buttons.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy_editor/appflowy_editor.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 ErrorBlockComponentBuilder extends BlockComponentBuilder { ErrorBlockComponentBuilder({ super.configuration, }); @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return ErrorBlockComponentWidget( key: node.key, node: node, configuration: configuration, showActions: showActions(node), actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), ); } @override bool validate(Node node) => true; } class ErrorBlockComponentWidget extends BlockComponentStatefulWidget { const ErrorBlockComponentWidget({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), }); @override State<ErrorBlockComponentWidget> createState() => _ErrorBlockComponentWidgetState(); } class _ErrorBlockComponentWidgetState extends State<ErrorBlockComponentWidget> with BlockComponentConfigurable { @override BlockComponentConfiguration get configuration => widget.configuration; @override Node get node => widget.node; @override Widget build(BuildContext context) { Widget child = DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(4), ), child: FlowyButton( onTap: () async { showSnackBarMessage( context, LocaleKeys.document_errorBlock_blockContentHasBeenCopied.tr(), ); await getIt<ClipboardService>().setData( ClipboardServiceData(plainText: jsonEncode(node.toJson())), ); }, text: SizedBox( height: 52, child: Row( children: [ const HSpace(4), FlowyText( LocaleKeys.document_errorBlock_theBlockIsNotSupported.tr(), ), ], ), ), ), ); child = Padding( padding: padding, child: child, ); if (widget.showActions && widget.actionBuilder != null) { child = BlockComponentActionWrapper( node: node, actionBuilder: widget.actionBuilder!, child: child, ); } if (PlatformExtension.isMobile) { child = MobileBlockActionButtons( node: node, editorState: context.read<EditorState>(), child: child, ); } return child; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/image_picker_screen.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/flowy_image_picker.dart'; import 'package:flutter/material.dart'; class MobileImagePickerScreen extends StatelessWidget { const MobileImagePickerScreen({super.key}); static const routeName = '/image_picker'; @override Widget build(BuildContext context) { return const ImagePickerPage(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/open_ai_image_widget.dart
import 'dart:async'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart'; import 'package:appflowy/startup/startup.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'; class OpenAIImageWidget extends StatefulWidget { const OpenAIImageWidget({ super.key, required this.onSelectNetworkImage, }); final void Function(String url) onSelectNetworkImage; @override State<OpenAIImageWidget> createState() => _OpenAIImageWidgetState(); } class _OpenAIImageWidgetState extends State<OpenAIImageWidget> { Future<FlowyResult<List<String>, OpenAIError>>? future; String query = ''; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: FlowyTextField( hintText: LocaleKeys.document_imageBlock_ai_placeholder.tr(), onChanged: (value) => query = value, onEditingComplete: _search, ), ), const HSpace(4.0), FlowyButton( useIntrinsicWidth: true, text: FlowyText( LocaleKeys.search_label.tr(), ), onTap: _search, ), ], ), const VSpace(12.0), if (future != null) Expanded( child: FutureBuilder( future: future, builder: (context, value) { final data = value.data; if (!value.hasData || value.connectionState != ConnectionState.done || data == null) { return const CircularProgressIndicator.adaptive(); } return data.fold( (s) => GridView.count( crossAxisCount: 3, mainAxisSpacing: 16.0, crossAxisSpacing: 10.0, childAspectRatio: 4 / 3, children: s .map( (e) => GestureDetector( onTap: () => widget.onSelectNetworkImage(e), child: Image.network(e), ), ) .toList(), ), (e) => Center( child: FlowyText( e.message, maxLines: 3, textAlign: TextAlign.center, ), ), ); }, ), ), ], ); } void _search() async { final openAI = await getIt.getAsync<OpenAIRepository>(); setState(() { future = openAI.generateImage( prompt: query, n: 6, ); }); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/image_util.dart
import 'dart:io'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/application/prelude.dart'; import 'package:appflowy/shared/custom_image_cache_manager.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/util/file_extension.dart'; import 'package:appflowy/workspace/application/settings/application_data_storage.dart'; import 'package:appflowy_backend/log.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:path/path.dart' as p; Future<String?> saveImageToLocalStorage(String localImagePath) async { final path = await getIt<ApplicationDataStorage>().getPath(); final imagePath = p.join( path, 'images', ); try { // create the directory if not exists final directory = Directory(imagePath); if (!directory.existsSync()) { await directory.create(recursive: true); } final copyToPath = p.join( imagePath, '${uuid()}${p.extension(localImagePath)}', ); await File(localImagePath).copy( copyToPath, ); return copyToPath; } catch (e) { Log.error('cannot save image file', e); return null; } } Future<(String? path, String? errorMessage)> saveImageToCloudStorage( String localImagePath, ) async { final size = localImagePath.fileSize; if (size == null || size > 10 * 1024 * 1024) { // 10MB return ( null, LocaleKeys.document_imageBlock_uploadImageErrorImageSizeTooBig.tr(), ); } final documentService = DocumentService(); final result = await documentService.uploadFile( localFilePath: localImagePath, isAsync: false, ); return result.fold( (s) async { await CustomImageCacheManager().putFile( s.url, File(localImagePath).readAsBytesSync(), ); return (s.url, null); }, (e) => (null, e.msg), ); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/stability_ai_image_widget.dart
import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_client.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_error.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; class StabilityAIImageWidget extends StatefulWidget { const StabilityAIImageWidget({ super.key, required this.onSelectImage, }); final void Function(String url) onSelectImage; @override State<StabilityAIImageWidget> createState() => _StabilityAIImageWidgetState(); } class _StabilityAIImageWidgetState extends State<StabilityAIImageWidget> { Future<FlowyResult<List<String>, StabilityAIRequestError>>? future; String query = ''; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: FlowyTextField( hintText: LocaleKeys .document_imageBlock_stability_ai_placeholder .tr(), onChanged: (value) => query = value, onEditingComplete: _search, ), ), const HSpace(4.0), FlowyButton( useIntrinsicWidth: true, text: FlowyText( LocaleKeys.search_label.tr(), ), onTap: _search, ), ], ), const VSpace(12.0), if (future != null) Expanded( child: FutureBuilder( future: future, builder: (context, value) { final data = value.data; if (!value.hasData || value.connectionState != ConnectionState.done || data == null) { return const CircularProgressIndicator.adaptive(); } return data.fold( (s) => GridView.count( crossAxisCount: 3, mainAxisSpacing: 16.0, crossAxisSpacing: 10.0, childAspectRatio: 4 / 3, children: s.map( (e) { final base64Image = base64Decode(e); return GestureDetector( onTap: () async { final tempDirectory = await getTemporaryDirectory(); final path = p.join( tempDirectory.path, '${uuid()}.png', ); File(path).writeAsBytesSync(base64Image); widget.onSelectImage(path); }, child: Image.memory(base64Image), ); }, ).toList(), ), (e) => Center( child: FlowyText( e.message, maxLines: 3, textAlign: TextAlign.center, ), ), ); }, ), ), ], ); } void _search() async { final stabilityAI = await getIt.getAsync<StabilityAIRepository>(); setState(() { future = stabilityAI.generateImage( prompt: query, n: 6, ); }); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/flowy_image_picker.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar_actions.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flutter/material.dart'; class ImagePickerPage extends StatefulWidget { const ImagePickerPage({ super.key, // required this.onSelected, }); // final void Function(EmojiPickerResult) onSelected; @override State<ImagePickerPage> createState() => _ImagePickerPageState(); } class _ImagePickerPageState extends State<ImagePickerPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( titleSpacing: 0, title: FlowyText.semibold( LocaleKeys.titleBar_pageIcon.tr(), fontSize: 14.0, ), leading: const AppBarBackButton(), ), body: SafeArea( child: UploadImageMenu( onSubmitted: (_) {}, onUpload: (_) {}, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/image_selection_menu.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custom_image_block_component.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_placeholder.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; import 'package:flutter/material.dart'; final customImageMenuItem = SelectionMenuItem( getName: () => AppFlowyEditorL10n.current.image, icon: (editorState, isSelected, style) => SelectionMenuIconWidget( name: 'image', isSelected: isSelected, style: style, ), keywords: ['image', 'picture', 'img', 'photo'], handler: (editorState, menuService, context) async { // use the key to retrieve the state of the image block to show the popover automatically final imagePlaceholderKey = GlobalKey<ImagePlaceholderState>(); await editorState.insertEmptyImageBlock(imagePlaceholderKey); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { imagePlaceholderKey.currentState?.controller.show(); }); }, ); extension InsertImage on EditorState { Future<void> insertEmptyImageBlock(GlobalKey key) async { final selection = this.selection; if (selection == null || !selection.isCollapsed) { return; } final node = getNodeAtPath(selection.end.path); if (node == null) { return; } final emptyImage = imageNode(url: '') ..extraInfos = { kImagePlaceholderKey: key, }; final transaction = this.transaction; // if the current node is empty paragraph, replace it with image node if (node.type == ParagraphBlockKeys.type && (node.delta?.isEmpty ?? false)) { transaction ..insertNode( node.path, emptyImage, ) ..deleteNode(node); } else { transaction.insertNode( node.path.next, emptyImage, ); } transaction.afterSelection = Selection.collapsed( Position( path: node.path.next, ), ); transaction.selectionExtraInfo = {}; return apply(transaction); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/upload_image_file_widget.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/file_picker/file_picker_service.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:image_picker/image_picker.dart'; class UploadImageFileWidget extends StatelessWidget { const UploadImageFileWidget({ super.key, required this.onPickFile, this.allowedExtensions = const ['jpg', 'png', 'jpeg'], }); final void Function(String? path) onPickFile; final List<String> allowedExtensions; @override Widget build(BuildContext context) { return FlowyHover( child: FlowyButton( showDefaultBoxDecorationOnMobile: true, text: Container( margin: const EdgeInsets.all(4.0), alignment: Alignment.center, child: FlowyText( LocaleKeys.document_imageBlock_upload_placeholder.tr(), ), ), onTap: _uploadImage, ), ); } Future<void> _uploadImage() async { if (PlatformExtension.isDesktopOrWeb) { // on desktop, the users can pick a image file from folder final result = await getIt<FilePickerService>().pickFiles( dialogTitle: '', type: FileType.image, allowedExtensions: allowedExtensions, ); onPickFile(result?.files.firstOrNull?.path); } else { // on mobile, the users can pick a image file from camera or image library final result = await ImagePicker().pickImage(source: ImageSource.gallery); onPickFile(result?.path); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/upload_image_menu.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/cover_editor.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/embed_image_url_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/open_ai_image_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/stability_ai_image_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/unsplash_image_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/upload_image_file_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/user/application/user_service.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide ColorOption; 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:flowy_infra_ui/style_widget/hover.dart'; import 'package:flutter/material.dart'; enum UploadImageType { local, url, unsplash, stabilityAI, openAI, color; String get description { switch (this) { case UploadImageType.local: return LocaleKeys.document_imageBlock_upload_label.tr(); case UploadImageType.url: return LocaleKeys.document_imageBlock_embedLink_label.tr(); case UploadImageType.unsplash: return LocaleKeys.document_imageBlock_unsplash_label.tr(); case UploadImageType.openAI: return LocaleKeys.document_imageBlock_ai_label.tr(); case UploadImageType.stabilityAI: return LocaleKeys.document_imageBlock_stability_ai_label.tr(); case UploadImageType.color: return LocaleKeys.document_plugins_cover_colors.tr(); } } } class UploadImageMenu extends StatefulWidget { const UploadImageMenu({ super.key, required this.onSelectedLocalImage, required this.onSelectedAIImage, required this.onSelectedNetworkImage, this.onSelectedColor, this.supportTypes = UploadImageType.values, this.limitMaximumImageSize = false, }); final void Function(String? path) onSelectedLocalImage; final void Function(String url) onSelectedAIImage; final void Function(String url) onSelectedNetworkImage; final void Function(String color)? onSelectedColor; final List<UploadImageType> supportTypes; final bool limitMaximumImageSize; @override State<UploadImageMenu> createState() => _UploadImageMenuState(); } class _UploadImageMenuState extends State<UploadImageMenu> { late final List<UploadImageType> values; int currentTabIndex = 0; bool supportOpenAI = false; bool supportStabilityAI = false; @override void initState() { super.initState(); values = widget.supportTypes; UserBackendService.getCurrentUserProfile().then( (value) { final supportOpenAI = value.fold( (s) => s.openaiKey.isNotEmpty, (e) => false, ); final supportStabilityAI = value.fold( (s) => s.stabilityAiKey.isNotEmpty, (e) => false, ); if (supportOpenAI != this.supportOpenAI || supportStabilityAI != this.supportStabilityAI) { setState(() { this.supportOpenAI = supportOpenAI; this.supportStabilityAI = supportStabilityAI; }); } }, ); } @override Widget build(BuildContext context) { return DefaultTabController( length: values.length, child: Column( mainAxisSize: MainAxisSize.min, children: [ TabBar( onTap: (value) => setState(() { currentTabIndex = value; }), indicatorSize: TabBarIndicatorSize.label, isScrollable: true, overlayColor: MaterialStatePropertyAll( PlatformExtension.isDesktop ? Theme.of(context).colorScheme.secondary : Colors.transparent, ), padding: EdgeInsets.zero, tabs: values.map( (e) { final child = Padding( padding: EdgeInsets.only( left: 12.0, right: 12.0, bottom: 8.0, top: PlatformExtension.isMobile ? 0 : 8.0, ), child: FlowyText(e.description), ); if (PlatformExtension.isDesktop) { return FlowyHover( style: const HoverStyle(borderRadius: BorderRadius.zero), child: child, ); } return child; }, ).toList(), ), const Divider( height: 2, ), _buildTab(), ], ), ); } Widget _buildTab() { final constraints = PlatformExtension.isMobile ? const BoxConstraints(minHeight: 92) : null; final type = values[currentTabIndex]; switch (type) { case UploadImageType.local: return Container( padding: const EdgeInsets.all(8.0), alignment: Alignment.center, constraints: constraints, child: Column( children: [ UploadImageFileWidget( onPickFile: widget.onSelectedLocalImage, ), if (widget.limitMaximumImageSize) ...[ const VSpace(6.0), FlowyText( LocaleKeys.document_imageBlock_maximumImageSize.tr(), fontSize: 12.0, color: Theme.of(context).hintColor, ), ], ], ), ); case UploadImageType.url: return Container( padding: const EdgeInsets.all(8.0), constraints: constraints, child: EmbedImageUrlWidget( onSubmit: widget.onSelectedNetworkImage, ), ); case UploadImageType.unsplash: return Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: UnsplashImageWidget( onSelectUnsplashImage: widget.onSelectedNetworkImage, ), ), ); case UploadImageType.openAI: return supportOpenAI ? Expanded( child: Container( padding: const EdgeInsets.all(8.0), constraints: constraints, child: OpenAIImageWidget( onSelectNetworkImage: widget.onSelectedAIImage, ), ), ) : Padding( padding: const EdgeInsets.all(8.0), child: FlowyText( LocaleKeys.document_imageBlock_pleaseInputYourOpenAIKey.tr(), ), ); case UploadImageType.stabilityAI: return supportStabilityAI ? Expanded( child: Container( padding: const EdgeInsets.all(8.0), child: StabilityAIImageWidget( onSelectImage: widget.onSelectedLocalImage, ), ), ) : Padding( padding: const EdgeInsets.all(8.0), child: FlowyText( LocaleKeys.document_imageBlock_pleaseInputYourStabilityAIKey .tr(), ), ); case UploadImageType.color: final theme = Theme.of(context); final padding = PlatformExtension.isMobile ? const EdgeInsets.all(16.0) : const EdgeInsets.all(8.0); return Container( constraints: constraints, padding: padding, alignment: Alignment.center, child: CoverColorPicker( pickerBackgroundColor: theme.cardColor, pickerItemHoverColor: theme.hoverColor, backgroundColorOptions: FlowyTint.values .map<ColorOption>( (t) => ColorOption( colorHex: t.color(context).toHex(), name: t.tintName(AppFlowyEditorL10n.current), ), ) .toList(), onSubmittedBackgroundColorHex: (color) { widget.onSelectedColor?.call(color); }, ), ); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/unsupport_image_widget.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:flowy_infra_ui/style_widget/hover.dart'; import 'package:flutter/material.dart'; class UnSupportImageWidget extends StatelessWidget { const UnSupportImageWidget({ super.key, }); @override Widget build(BuildContext context) { return DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(4), ), child: FlowyHover( style: HoverStyle( borderRadius: BorderRadius.circular(4), ), child: SizedBox( height: 52, child: Row( children: [ const HSpace(10), const FlowySvg( FlowySvgs.image_placeholder_s, size: Size.square(24), ), const HSpace(10), FlowyText( LocaleKeys.document_imageBlock_unableToLoadImage.tr(), ), ], ), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/embed_image_url_widget.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/shared/patterns/common_patterns.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; class EmbedImageUrlWidget extends StatefulWidget { const EmbedImageUrlWidget({ super.key, required this.onSubmit, }); final void Function(String url) onSubmit; @override State<EmbedImageUrlWidget> createState() => _EmbedImageUrlWidgetState(); } class _EmbedImageUrlWidgetState extends State<EmbedImageUrlWidget> { bool isUrlValid = true; String inputText = ''; @override Widget build(BuildContext context) { return Column( children: [ FlowyTextField( hintText: LocaleKeys.document_imageBlock_embedLink_placeholder.tr(), onChanged: (value) => inputText = value, onEditingComplete: submit, ), if (!isUrlValid) ...[ const VSpace(8), FlowyText( LocaleKeys.document_plugins_cover_invalidImageUrl.tr(), color: Theme.of(context).colorScheme.error, ), ], const VSpace(8), SizedBox( width: 160, child: FlowyButton( showDefaultBoxDecorationOnMobile: true, margin: const EdgeInsets.all(8.0), text: FlowyText( LocaleKeys.document_imageBlock_embedLink_label.tr(), textAlign: TextAlign.center, ), onTap: submit, ), ), ], ); } void submit() { if (checkUrlValidity(inputText)) { return widget.onSubmit(inputText); } setState(() => isUrlValid = false); } bool checkUrlValidity(String url) => imgUrlRegex.hasMatch(url); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/image_menu.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/align_toolbar_item/align_toolbar_item.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/block_menu/block_menu_button.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custom_image_block_component.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/util/string_extension.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/widget/ignore_parent_gesture.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; class ImageMenu extends StatefulWidget { const ImageMenu({ super.key, required this.node, required this.state, }); final Node node; final CustomImageBlockComponentState state; @override State<ImageMenu> createState() => _ImageMenuState(); } class _ImageMenuState extends State<ImageMenu> { late final String? url = widget.node.attributes[ImageBlockKeys.url]; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Container( height: 32, decoration: BoxDecoration( color: theme.cardColor, boxShadow: [ BoxShadow( blurRadius: 5, spreadRadius: 1, color: Colors.black.withOpacity(0.1), ), ], borderRadius: BorderRadius.circular(4.0), ), child: Row( children: [ const HSpace(4), // disable the copy link button if the image is hosted on appflowy cloud // because the url needs the verification token to be accessible if (!(url?.isAppFlowyCloudUrl ?? false)) ...[ MenuBlockButton( tooltip: LocaleKeys.editor_copyLink.tr(), iconData: FlowySvgs.copy_s, onTap: copyImageLink, ), const HSpace(4), ], _ImageAlignButton( node: widget.node, state: widget.state, ), const _Divider(), MenuBlockButton( tooltip: LocaleKeys.button_delete.tr(), iconData: FlowySvgs.delete_s, onTap: deleteImage, ), const HSpace(4), ], ), ); } void copyImageLink() { if (url != null) { Clipboard.setData(ClipboardData(text: url!)); showSnackBarMessage( context, LocaleKeys.document_plugins_image_copiedToPasteBoard.tr(), ); } } Future<void> deleteImage() async { final node = widget.node; final editorState = context.read<EditorState>(); final transaction = editorState.transaction; transaction.deleteNode(node); transaction.afterSelection = null; await editorState.apply(transaction); } } class _ImageAlignButton extends StatefulWidget { const _ImageAlignButton({ required this.node, required this.state, }); final Node node; final CustomImageBlockComponentState state; @override State<_ImageAlignButton> createState() => _ImageAlignButtonState(); } const interceptorKey = 'image-align'; class _ImageAlignButtonState extends State<_ImageAlignButton> { final gestureInterceptor = SelectionGestureInterceptor( key: interceptorKey, canTap: (details) => false, ); String get align => widget.node.attributes[ImageBlockKeys.align] ?? centerAlignmentKey; final popoverController = PopoverController(); late final EditorState editorState; @override void initState() { super.initState(); editorState = context.read<EditorState>(); } @override void dispose() { allowMenuClose(); super.dispose(); } @override Widget build(BuildContext context) { return IgnoreParentGestureWidget( child: AppFlowyPopover( onClose: allowMenuClose, controller: popoverController, windowPadding: const EdgeInsets.all(0), margin: const EdgeInsets.all(0), direction: PopoverDirection.bottomWithCenterAligned, offset: const Offset(0, 10), child: MenuBlockButton( tooltip: LocaleKeys.document_plugins_optionAction_align.tr(), iconData: iconFor(align), ), popupBuilder: (_) { preventMenuClose(); return _AlignButtons( onAlignChanged: onAlignChanged, ); }, ), ); } void onAlignChanged(String align) { popoverController.close(); final transaction = editorState.transaction; transaction.updateNode(widget.node, { ImageBlockKeys.align: align, }); editorState.apply(transaction); allowMenuClose(); } void preventMenuClose() { widget.state.alwaysShowMenu = true; editorState.service.selectionService.registerGestureInterceptor( gestureInterceptor, ); } void allowMenuClose() { widget.state.alwaysShowMenu = false; editorState.service.selectionService.unregisterGestureInterceptor( interceptorKey, ); } FlowySvgData iconFor(String alignment) { switch (alignment) { case rightAlignmentKey: return FlowySvgs.align_right_s; case centerAlignmentKey: return FlowySvgs.align_center_s; case leftAlignmentKey: default: return FlowySvgs.align_left_s; } } } class _AlignButtons extends StatelessWidget { const _AlignButtons({ required this.onAlignChanged, }); final Function(String align) onAlignChanged; @override Widget build(BuildContext context) { return SizedBox( height: 32, child: Row( mainAxisSize: MainAxisSize.min, children: [ const HSpace(4), MenuBlockButton( tooltip: LocaleKeys.document_plugins_optionAction_left, iconData: FlowySvgs.align_left_s, onTap: () => onAlignChanged(leftAlignmentKey), ), const _Divider(), MenuBlockButton( tooltip: LocaleKeys.document_plugins_optionAction_center, iconData: FlowySvgs.align_center_s, onTap: () => onAlignChanged(centerAlignmentKey), ), const _Divider(), MenuBlockButton( tooltip: LocaleKeys.document_plugins_optionAction_right, iconData: FlowySvgs.align_right_s, onTap: () => onAlignChanged(rightAlignmentKey), ), const HSpace(4), ], ), ); } } class _Divider extends StatelessWidget { const _Divider(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8), child: Container( width: 1, color: Colors.grey, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/mobile_image_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_placeholder.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; final imageMobileToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, __, ___) => const FlowySvg(FlowySvgs.m_toolbar_imae_lg), actionHandler: (_, editorState) async { final imagePlaceholderKey = GlobalKey<ImagePlaceholderState>(); await editorState.insertEmptyImageBlock(imagePlaceholderKey); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { imagePlaceholderKey.currentState?.showUploadImageMenu(); }); }, );
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/custom_image_block_component.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/widgets/widgets.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/mobile_block_action_buttons.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_placeholder.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/resizeable_image.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/unsupport_image_widget.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/util/string_extension.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide ResizableImage; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:string_validator/string_validator.dart'; const kImagePlaceholderKey = 'imagePlaceholderKey'; enum CustomImageType { local, internal, // the images saved in self-host cloud external; // the images linked from network, like unsplash, https://xxx/yyy/zzz.jpg static CustomImageType fromIntValue(int value) { switch (value) { case 0: return CustomImageType.local; case 1: return CustomImageType.internal; case 2: return CustomImageType.external; default: throw UnimplementedError(); } } int toIntValue() { switch (this) { case CustomImageType.local: return 0; case CustomImageType.internal: return 1; case CustomImageType.external: return 2; } } } class CustomImageBlockKeys { const CustomImageBlockKeys._(); static const String type = 'image'; /// The align data of a image block. /// /// The value is a String. /// left, center, right static const String align = 'align'; /// The image src of a image block. /// /// The value is a String. /// It can be a url or a base64 string(web). static const String url = 'url'; /// The height of a image block. /// /// The value is a double. static const String width = 'width'; /// The width of a image block. /// /// The value is a double. static const String height = 'height'; /// The image type of a image block. /// /// The value is a CustomImageType enum. static const String imageType = 'image_type'; } typedef CustomImageBlockComponentMenuBuilder = Widget Function( Node node, CustomImageBlockComponentState state, ); class CustomImageBlockComponentBuilder extends BlockComponentBuilder { CustomImageBlockComponentBuilder({ super.configuration, this.showMenu = false, this.menuBuilder, }); /// Whether to show the menu of this block component. final bool showMenu; /// final CustomImageBlockComponentMenuBuilder? menuBuilder; @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return CustomImageBlockComponent( key: node.key, node: node, showActions: showActions(node), configuration: configuration, actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), showMenu: showMenu, menuBuilder: menuBuilder, ); } @override bool validate(Node node) => node.delta == null && node.children.isEmpty; } class CustomImageBlockComponent extends BlockComponentStatefulWidget { const CustomImageBlockComponent({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), this.showMenu = false, this.menuBuilder, }); /// Whether to show the menu of this block component. final bool showMenu; final CustomImageBlockComponentMenuBuilder? menuBuilder; @override State<CustomImageBlockComponent> createState() => CustomImageBlockComponentState(); } class CustomImageBlockComponentState extends State<CustomImageBlockComponent> with SelectableMixin, BlockComponentConfigurable { @override BlockComponentConfiguration get configuration => widget.configuration; @override Node get node => widget.node; final imageKey = GlobalKey(); RenderBox? get _renderBox => context.findRenderObject() as RenderBox?; late final editorState = Provider.of<EditorState>(context, listen: false); final showActionsNotifier = ValueNotifier<bool>(false); bool alwaysShowMenu = false; @override Widget build(BuildContext context) { final node = widget.node; final attributes = node.attributes; final src = attributes[CustomImageBlockKeys.url]; final alignment = AlignmentExtension.fromString( attributes[CustomImageBlockKeys.align] ?? 'center', ); final width = attributes[CustomImageBlockKeys.width]?.toDouble() ?? MediaQuery.of(context).size.width; final height = attributes[CustomImageBlockKeys.height]?.toDouble(); final rawImageType = attributes[CustomImageBlockKeys.imageType] ?? 0; final imageType = CustomImageType.fromIntValue(rawImageType); final imagePlaceholderKey = node.extraInfos?[kImagePlaceholderKey]; Widget child; if (src.isEmpty) { child = ImagePlaceholder( key: imagePlaceholderKey is GlobalKey ? imagePlaceholderKey : null, node: node, ); } else if (imageType != CustomImageType.internal && !_checkIfURLIsValid(src)) { child = const UnSupportImageWidget(); } else { child = ResizableImage( src: src, width: width, height: height, editable: editorState.editable, alignment: alignment, type: imageType, onResize: (width) { final transaction = editorState.transaction ..updateNode(node, { CustomImageBlockKeys.width: width, }); editorState.apply(transaction); }, ); } if (PlatformExtension.isDesktopOrWeb) { child = BlockSelectionContainer( node: node, delegate: this, listenable: editorState.selectionNotifier, blockColor: editorState.editorStyle.selectionColor, supportTypes: const [ BlockSelectionType.block, ], child: Padding( key: imageKey, padding: padding, child: child, ), ); } else { child = Padding( key: imageKey, padding: padding, child: child, ); } if (widget.showActions && widget.actionBuilder != null) { child = BlockComponentActionWrapper( node: node, actionBuilder: widget.actionBuilder!, child: child, ); } // show a hover menu on desktop or web if (PlatformExtension.isDesktopOrWeb) { if (widget.showMenu && widget.menuBuilder != null) { child = MouseRegion( onEnter: (_) => showActionsNotifier.value = true, onExit: (_) { if (!alwaysShowMenu) { showActionsNotifier.value = false; } }, hitTestBehavior: HitTestBehavior.opaque, opaque: false, child: ValueListenableBuilder<bool>( valueListenable: showActionsNotifier, builder: (context, value, child) { final url = node.attributes[CustomImageBlockKeys.url]; return Stack( children: [ BlockSelectionContainer( node: node, delegate: this, listenable: editorState.selectionNotifier, cursorColor: editorState.editorStyle.cursorColor, selectionColor: editorState.editorStyle.selectionColor, child: child!, ), if (value && url.isNotEmpty == true) widget.menuBuilder!( widget.node, this, ), ], ); }, child: child, ), ); } } else { // show a fixed menu on mobile child = MobileBlockActionButtons( showThreeDots: false, node: node, editorState: editorState, extendActionWidgets: _buildExtendActionWidgets(context), child: child, ); } return child; } @override Position start() => Position(path: widget.node.path); @override Position end() => Position(path: widget.node.path, offset: 1); @override Position getPositionInOffset(Offset start) => end(); @override bool get shouldCursorBlink => false; @override CursorStyle get cursorStyle => CursorStyle.cover; @override Rect getBlockRect({ bool shiftWithBaseOffset = false, }) { final imageBox = imageKey.currentContext?.findRenderObject(); if (imageBox is RenderBox) { return Offset.zero & imageBox.size; } return Rect.zero; } @override Rect? getCursorRectInPosition( Position position, { bool shiftWithBaseOffset = false, }) { final rects = getRectsInSelection(Selection.collapsed(position)); return rects.firstOrNull; } @override List<Rect> getRectsInSelection( Selection selection, { bool shiftWithBaseOffset = false, }) { if (_renderBox == null) { return []; } final parentBox = context.findRenderObject(); final imageBox = imageKey.currentContext?.findRenderObject(); if (parentBox is RenderBox && imageBox is RenderBox) { return [ imageBox.localToGlobal(Offset.zero, ancestor: parentBox) & imageBox.size, ]; } return [Offset.zero & _renderBox!.size]; } @override Selection getSelectionInRange(Offset start, Offset end) => Selection.single( path: widget.node.path, startOffset: 0, endOffset: 1, ); @override Offset localToGlobal( Offset offset, { bool shiftWithBaseOffset = false, }) => _renderBox!.localToGlobal(offset); // only used on mobile platform List<Widget> _buildExtendActionWidgets(BuildContext context) { final String url = widget.node.attributes[CustomImageBlockKeys.url]; if (!_checkIfURLIsValid(url)) { return []; } return [ // disable the copy link button if the image is hosted on appflowy cloud // because the url needs the verification token to be accessible if (!url.isAppFlowyCloudUrl) FlowyOptionTile.text( showTopBorder: false, text: LocaleKeys.editor_copyLink.tr(), leftIcon: const FlowySvg( FlowySvgs.m_field_copy_s, ), onTap: () async { context.pop(); showSnackBarMessage( context, LocaleKeys.document_plugins_image_copiedToPasteBoard.tr(), ); await getIt<ClipboardService>().setPlainText(url); }, ), FlowyOptionTile.text( showTopBorder: false, text: LocaleKeys.document_imageBlock_saveImageToGallery.tr(), leftIcon: const FlowySvg( FlowySvgs.image_placeholder_s, size: Size.square(20), ), onTap: () async { context.pop(); showSnackBarMessage( context, LocaleKeys.document_plugins_image_copiedToPasteBoard.tr(), ); await getIt<ClipboardService>().setPlainText(url); }, ), ]; } bool _checkIfURLIsValid(dynamic url) { if (url is! String) { return false; } if (url.isEmpty) { return false; } if (!isURL(url) && !File(url).existsSync()) { return false; } return true; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/unsplash_image_widget.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:unsplash_client/unsplash_client.dart'; class UnsplashImageWidget extends StatefulWidget { const UnsplashImageWidget({ super.key, required this.onSelectUnsplashImage, }); final void Function(String url) onSelectUnsplashImage; @override State<UnsplashImageWidget> createState() => _UnsplashImageWidgetState(); } class _UnsplashImageWidgetState extends State<UnsplashImageWidget> { final client = UnsplashClient( settings: const ClientSettings( credentials: AppCredentials( // TODO: there're the demo keys, we should replace them with the production keys when releasing and inject them with env file. accessKey: 'YyD-LbW5bVolHWZBq5fWRM_3ezkG2XchRFjhNTnK9TE', secretKey: '5z4EnxaXjWjWMnuBhc0Ku0uYW2bsYCZlO-REZaqmV6A', ), ), ); late Future<List<Photo>> randomPhotos; String query = ''; @override void initState() { super.initState(); randomPhotos = client.photos .random(count: 18, orientation: PhotoOrientation.landscape) .goAndGet(); } @override void dispose() { client.close(); super.dispose(); } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: FlowyTextField( hintText: LocaleKeys.document_imageBlock_searchForAnImage.tr(), onChanged: (value) => query = value, onEditingComplete: _search, ), ), const HSpace(4.0), FlowyButton( useIntrinsicWidth: true, text: FlowyText( LocaleKeys.search_label.tr(), ), onTap: _search, ), ], ), const VSpace(12.0), Expanded( child: FutureBuilder( future: randomPhotos, builder: (context, value) { final data = value.data; if (!value.hasData || value.connectionState != ConnectionState.done || data == null || data.isEmpty) { return const Center( child: CircularProgressIndicator.adaptive(), ); } return GridView.count( crossAxisCount: 3, mainAxisSpacing: 16.0, crossAxisSpacing: 10.0, childAspectRatio: 4 / 3, children: data .map( (photo) => _UnsplashImage( photo: photo, onTap: () => widget.onSelectUnsplashImage( photo.urls.regular.toString(), ), ), ) .toList(), ); }, ), ), ], ); } void _search() { setState(() { randomPhotos = client.photos .random( count: 18, orientation: PhotoOrientation.landscape, query: query, ) .goAndGet(); }); } } class _UnsplashImage extends StatelessWidget { const _UnsplashImage({ required this.photo, required this.onTap, }); final Photo photo; final VoidCallback onTap; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Image.network( photo.urls.thumb.toString(), fit: BoxFit.cover, ), ), const HSpace(2.0), FlowyText( 'by ${photo.name}', fontSize: 10.0, ), ], ), ); } } extension on Photo { String get name { if (user.username.isNotEmpty) { return user.username; } if (user.name.isNotEmpty) { return user.name; } if (user.email?.isNotEmpty == true) { return user.email!; } return user.id; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/image_placeholder.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/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/plugins/document/application/prelude.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/mobile_block_action_buttons.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custom_image_block_component.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_util.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/upload_image_menu.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/settings/application_data_storage.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log, UploadImageMenu; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.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 'package:go_router/go_router.dart'; import 'package:http/http.dart'; import 'package:path/path.dart' as p; import 'package:string_validator/string_validator.dart'; class ImagePlaceholder extends StatefulWidget { const ImagePlaceholder({ super.key, required this.node, }); final Node node; @override State<ImagePlaceholder> createState() => ImagePlaceholderState(); } class ImagePlaceholderState extends State<ImagePlaceholder> { final controller = PopoverController(); final documentService = DocumentService(); late final editorState = context.read<EditorState>(); bool showLoading = false; String? errorMessage; @override Widget build(BuildContext context) { final Widget child = DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(4), ), child: FlowyHover( style: HoverStyle( borderRadius: BorderRadius.circular(4), ), child: SizedBox( height: 52, child: Row( children: [ const HSpace(10), const FlowySvg( FlowySvgs.image_placeholder_s, size: Size.square(24), ), const HSpace(10), ..._buildTrailing(context), ], ), ), ), ); if (PlatformExtension.isDesktopOrWeb) { return AppFlowyPopover( controller: controller, direction: PopoverDirection.bottomWithCenterAligned, constraints: const BoxConstraints( maxWidth: 540, maxHeight: 360, minHeight: 80, ), clickHandler: PopoverClickHandler.gestureDetector, popupBuilder: (context) { return UploadImageMenu( limitMaximumImageSize: !_isLocalMode(), supportTypes: const [ UploadImageType.local, UploadImageType.url, UploadImageType.unsplash, UploadImageType.openAI, UploadImageType.stabilityAI, ], onSelectedLocalImage: (path) { controller.close(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { await insertLocalImage(path); }); }, onSelectedAIImage: (url) { controller.close(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { await insertAIImage(url); }); }, onSelectedNetworkImage: (url) { controller.close(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { await insertNetworkImage(url); }); }, ); }, child: child, ); } else { return MobileBlockActionButtons( node: widget.node, editorState: editorState, child: GestureDetector( onTap: () { editorState.updateSelectionWithReason(null, extraInfo: {}); showUploadImageMenu(); }, child: child, ), ); } } List<Widget> _buildTrailing(BuildContext context) { if (errorMessage != null) { return [ FlowyText( '${LocaleKeys.document_plugins_image_imageUploadFailed.tr()}: ${errorMessage!}', ), ]; } else if (showLoading) { return [ FlowyText( LocaleKeys.document_imageBlock_imageIsUploading.tr(), ), const HSpace(8), const CircularProgressIndicator.adaptive(), ]; } else { return [ FlowyText( LocaleKeys.document_plugins_image_addAnImage.tr(), ), ]; } } void showUploadImageMenu() { if (PlatformExtension.isDesktopOrWeb) { controller.show(); } else { final isLocalMode = _isLocalMode(); showMobileBottomSheet( context, title: LocaleKeys.editor_image.tr(), showHeader: true, showCloseButton: true, showDragHandle: true, builder: (context) { return Container( margin: const EdgeInsets.only(top: 12.0), constraints: const BoxConstraints( maxHeight: 340, minHeight: 80, ), child: UploadImageMenu( limitMaximumImageSize: !isLocalMode, supportTypes: const [ UploadImageType.local, UploadImageType.url, UploadImageType.unsplash, ], onSelectedLocalImage: (path) async { context.pop(); await insertLocalImage(path); }, onSelectedAIImage: (url) async { context.pop(); await insertAIImage(url); }, onSelectedNetworkImage: (url) async { context.pop(); await insertNetworkImage(url); }, ), ); }, ); } } Future<void> insertLocalImage(String? url) async { controller.close(); if (url == null || url.isEmpty) { return; } final transaction = editorState.transaction; String? path; String? errorMessage; CustomImageType imageType = CustomImageType.local; // if the user is using local authenticator, we need to save the image to local storage if (_isLocalMode()) { // don't limit the image size for local mode. path = await saveImageToLocalStorage(url); } else { // else we should save the image to cloud storage setState(() { showLoading = true; this.errorMessage = null; }); (path, errorMessage) = await saveImageToCloudStorage(url); setState(() { showLoading = false; this.errorMessage = errorMessage; }); imageType = CustomImageType.internal; } if (mounted && path == null) { showSnackBarMessage( context, errorMessage == null ? LocaleKeys.document_imageBlock_error_invalidImage.tr() : ': $errorMessage', ); setState(() { this.errorMessage = errorMessage; }); return; } transaction.updateNode(widget.node, { CustomImageBlockKeys.url: path, CustomImageBlockKeys.imageType: imageType.toIntValue(), }); await editorState.apply(transaction); } Future<void> insertAIImage(String url) async { if (url.isEmpty || !isURL(url)) { // show error showSnackBarMessage( context, LocaleKeys.document_imageBlock_error_invalidImage.tr(), ); return; } final path = await getIt<ApplicationDataStorage>().getPath(); final imagePath = p.join( path, 'images', ); try { // create the directory if not exists final directory = Directory(imagePath); if (!directory.existsSync()) { await directory.create(recursive: true); } final uri = Uri.parse(url); final copyToPath = p.join( imagePath, '${uuid()}${p.extension(uri.path)}', ); final response = await get(uri); await File(copyToPath).writeAsBytes(response.bodyBytes); await insertLocalImage(copyToPath); await File(copyToPath).delete(); } catch (e) { Log.error('cannot save image file', e); } } Future<void> insertNetworkImage(String url) async { if (url.isEmpty || !isURL(url)) { // show error showSnackBarMessage( context, LocaleKeys.document_imageBlock_error_invalidImage.tr(), ); return; } final transaction = editorState.transaction; transaction.updateNode(widget.node, { ImageBlockKeys.url: url, }); await editorState.apply(transaction); } bool _isLocalMode() { return context.read<DocumentBloc>().isLocalMode; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/image/resizeable_image.dart
import 'dart:io'; import 'dart:math'; import 'package:appflowy/plugins/document/application/prelude.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custom_image_block_component.dart'; import 'package:appflowy/shared/appflowy_network_image.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:string_validator/string_validator.dart'; class ResizableImage extends StatefulWidget { const ResizableImage({ super.key, required this.type, required this.alignment, required this.editable, required this.onResize, required this.width, required this.src, this.height, }); final String src; final CustomImageType type; final double width; final double? height; final Alignment alignment; final bool editable; final void Function(double width) onResize; @override State<ResizableImage> createState() => _ResizableImageState(); } const _kImageBlockComponentMinWidth = 30.0; class _ResizableImageState extends State<ResizableImage> { late double imageWidth; double initialOffset = 0; double moveDistance = 0; Widget? _cacheImage; @visibleForTesting bool onFocus = false; final documentService = DocumentService(); UserProfilePB? _userProfilePB; @override void initState() { super.initState(); imageWidth = widget.width; _userProfilePB = context.read<DocumentBloc>().state.userProfilePB; } @override Widget build(BuildContext context) { return Align( alignment: widget.alignment, child: SizedBox( width: max(_kImageBlockComponentMinWidth, imageWidth - moveDistance), height: widget.height, child: MouseRegion( onEnter: (event) => setState(() { onFocus = true; }), onExit: (event) => setState(() { onFocus = false; }), child: _buildResizableImage(context), ), ), ); } Widget _buildResizableImage(BuildContext context) { Widget child; final src = widget.src; if (isURL(src)) { // load network image if (widget.type == CustomImageType.internal && _userProfilePB == null) { return _buildLoading(context); } _cacheImage = FlowyNetworkImage( url: widget.src, width: imageWidth - moveDistance, userProfilePB: _userProfilePB, errorWidgetBuilder: (context, url, error) => _buildError(context, error), progressIndicatorBuilder: (context, url, progress) => _buildLoading(context), ); child = _cacheImage!; } else { // load local file _cacheImage ??= Image.file(File(src)); child = _cacheImage!; } return Stack( children: [ child, if (widget.editable) ...[ _buildEdgeGesture( context, top: 0, left: 5, bottom: 0, width: 5, onUpdate: (distance) { setState(() { moveDistance = distance; }); }, ), _buildEdgeGesture( context, top: 0, right: 5, bottom: 0, width: 5, onUpdate: (distance) { setState(() { moveDistance = -distance; }); }, ), ], ], ); } Widget _buildLoading(BuildContext context) { return SizedBox( height: 150, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox.fromSize( size: const Size(18, 18), child: const CircularProgressIndicator(), ), SizedBox.fromSize( size: const Size(10, 10), ), Text(AppFlowyEditorL10n.current.loading), ], ), ); } Widget _buildError(BuildContext context, Object error) { return Container( height: 100, width: imageWidth, alignment: Alignment.center, padding: const EdgeInsets.only(top: 8.0, bottom: 8.0), decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(4.0)), border: Border.all(), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ FlowyText(AppFlowyEditorL10n.current.imageLoadFailed), const VSpace(4), FlowyText.small( error.toString(), textAlign: TextAlign.center, maxLines: 2, ), ], ), ); } Widget _buildEdgeGesture( BuildContext context, { double? top, double? left, double? right, double? bottom, double? width, void Function(double distance)? onUpdate, }) { return Positioned( top: top, left: left, right: right, bottom: bottom, width: width, child: GestureDetector( onHorizontalDragStart: (details) { initialOffset = details.globalPosition.dx; }, onHorizontalDragUpdate: (details) { if (onUpdate != null) { var offset = details.globalPosition.dx - initialOffset; if (widget.alignment == Alignment.center) { offset *= 2.0; } onUpdate(offset); } }, onHorizontalDragEnd: (details) { imageWidth = max(_kImageBlockComponentMinWidth, imageWidth - moveDistance); initialOffset = 0; moveDistance = 0; widget.onResize(imageWidth); }, child: MouseRegion( cursor: SystemMouseCursors.resizeLeftRight, child: onFocus ? Center( child: Container( height: 40, decoration: BoxDecoration( color: Colors.black.withOpacity(0.5), borderRadius: const BorderRadius.all( Radius.circular(5.0), ), border: Border.all(color: Colors.white), ), ), ) : null, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/context_menu/custom_context_menu.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; final List<List<ContextMenuItem>> customContextMenuItems = [ [ ContextMenuItem( getName: LocaleKeys.document_plugins_contextMenu_copy.tr, onPressed: (editorState) => customCopyCommand.execute(editorState), ), ContextMenuItem( getName: LocaleKeys.document_plugins_contextMenu_paste.tr, onPressed: (editorState) => customPasteCommand.execute(editorState), ), ContextMenuItem( getName: LocaleKeys.document_plugins_contextMenu_cut.tr, onPressed: (editorState) => customCutCommand.execute(editorState), ), ], ];
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/menu.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/application/tabs/tabs_bloc.dart'; import 'package:appflowy/workspace/presentation/home/menu/menu_shared_state.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra/size.dart'; import 'package:flowy_infra_ui/style_widget/extension.dart'; import 'package:flowy_infra_ui/style_widget/hover.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; class MenuTrash extends StatelessWidget { const MenuTrash({super.key}); @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: getIt<MenuSharedState>().notifier, builder: (context, value, child) { return FlowyHover( style: HoverStyle( hoverColor: AFThemeExtension.of(context).greySelect, ), isSelected: () => getIt<MenuSharedState>().latestOpenView == null, child: SizedBox( height: 26, child: InkWell( onTap: () { getIt<MenuSharedState>().latestOpenView = null; getIt<TabsBloc>().add( TabsEvent.openPlugin( plugin: makePlugin(pluginType: PluginType.trash), ), ); }, child: _render(context), ), ).padding(horizontal: Insets.l), ).padding(horizontal: 8); }, ); } Widget _render(BuildContext context) { return Row( children: [ const FlowySvg( FlowySvgs.trash_m, size: Size(16, 16), ), const HSpace(6), FlowyText.medium(LocaleKeys.trash_text.tr()), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/trash_page.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/trash/src/sizes.dart'; import 'package:appflowy/plugins/trash/src/trash_header.dart'; import 'package:appflowy/workspace/presentation/widgets/dialogs.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/size.dart'; import 'package:flowy_infra_ui/style_widget/button.dart'; import 'package:flowy_infra_ui/style_widget/scrolling/styled_list.dart'; import 'package:flowy_infra_ui/style_widget/scrolling/styled_scroll_bar.dart'; import 'package:flowy_infra_ui/style_widget/scrolling/styled_scrollview.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:styled_widget/styled_widget.dart'; import 'application/trash_bloc.dart'; import 'src/trash_cell.dart'; class TrashPage extends StatefulWidget { const TrashPage({super.key}); @override State<TrashPage> createState() => _TrashPageState(); } class _TrashPageState extends State<TrashPage> { final ScrollController _scrollController = ScrollController(); @override void dispose() { _scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const horizontalPadding = 80.0; return BlocProvider( create: (context) => getIt<TrashBloc>()..add(const TrashEvent.initial()), child: BlocBuilder<TrashBloc, TrashState>( builder: (context, state) { return SizedBox.expand( child: Column( children: [ _renderTopBar(context, state), const VSpace(32), _renderTrashList(context, state), ], ).padding(horizontal: horizontalPadding, vertical: 48), ); }, ), ); } Widget _renderTrashList(BuildContext context, TrashState state) { const barSize = 6.0; return Expanded( child: ScrollbarListStack( axis: Axis.vertical, controller: _scrollController, scrollbarPadding: EdgeInsets.only(top: TrashSizes.headerHeight), barSize: barSize, child: StyledSingleChildScrollView( barSize: barSize, axis: Axis.horizontal, child: SizedBox( width: TrashSizes.totalWidth, child: ScrollConfiguration( behavior: const ScrollBehavior().copyWith(scrollbars: false), child: CustomScrollView( shrinkWrap: true, physics: StyledScrollPhysics(), controller: _scrollController, slivers: [ _renderListHeader(context, state), _renderListBody(context, state), ], ), ), ), ), ), ); } Widget _renderTopBar(BuildContext context, TrashState state) { return SizedBox( height: 36, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FlowyText.semibold( LocaleKeys.trash_text.tr(), fontSize: FontSizes.s16, color: Theme.of(context).colorScheme.tertiary, ), const Spacer(), IntrinsicWidth( child: FlowyButton( text: FlowyText.medium(LocaleKeys.trash_restoreAll.tr()), leftIcon: const FlowySvg(FlowySvgs.restore_s), onTap: () { NavigatorAlertDialog( title: LocaleKeys.trash_confirmRestoreAll_title.tr(), confirm: () { context .read<TrashBloc>() .add(const TrashEvent.restoreAll()); }, ).show(context); }, ), ), const HSpace(6), IntrinsicWidth( child: FlowyButton( text: FlowyText.medium(LocaleKeys.trash_deleteAll.tr()), leftIcon: const FlowySvg(FlowySvgs.delete_s), onTap: () { NavigatorAlertDialog( title: LocaleKeys.trash_confirmDeleteAll_title.tr(), confirm: () { context.read<TrashBloc>().add(const TrashEvent.deleteAll()); }, ).show(context); }, ), ), ], ), ); } Widget _renderListHeader(BuildContext context, TrashState state) { return SliverPersistentHeader( delegate: TrashHeaderDelegate(), floating: true, pinned: true, ); } Widget _renderListBody(BuildContext context, TrashState state) { return SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { final object = state.objects[index]; return SizedBox( height: 42, child: TrashCell( object: object, onRestore: () { NavigatorAlertDialog( title: LocaleKeys.deletePagePrompt_restore.tr(), confirm: () { context .read<TrashBloc>() .add(TrashEvent.putback(object.id)); }, ).show(context); }, onDelete: () { NavigatorAlertDialog( title: LocaleKeys.deletePagePrompt_deletePermanent.tr(), confirm: () { context.read<TrashBloc>().add(TrashEvent.delete(object)); }, ).show(context); }, ), ); }, childCount: state.objects.length, addAutomaticKeepAlives: false, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/trash.dart
export "./src/sizes.dart"; export "./src/trash_cell.dart"; export "./src/trash_header.dart"; import 'package:appflowy/generated/flowy_svgs.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'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'trash_page.dart'; class TrashPluginBuilder extends PluginBuilder { @override Plugin build(dynamic data) { return TrashPlugin(pluginType: pluginType); } @override String get menuName => "TrashPB"; @override FlowySvgData get icon => FlowySvgs.trash_m; @override PluginType get pluginType => PluginType.trash; } class TrashPluginConfig implements PluginConfig { @override bool get creatable => false; } class TrashPlugin extends Plugin { TrashPlugin({required PluginType pluginType}) : _pluginType = pluginType; final PluginType _pluginType; @override PluginWidgetBuilder get widgetBuilder => TrashPluginDisplay(); @override PluginId get id => "TrashStack"; @override PluginType get pluginType => _pluginType; } class TrashPluginDisplay extends PluginWidgetBuilder { @override Widget get leftBarItem => FlowyText.medium(LocaleKeys.trash_text.tr()); @override Widget tabBarItem(String pluginId) => leftBarItem; @override Widget? get rightBarItem => null; @override Widget buildWidget({PluginContext? context, required bool shrinkWrap}) => const TrashPage( key: ValueKey('TrashPage'), ); @override List<NavigationItem> get navigationItems => [this]; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/application/prelude.dart
export 'trash_bloc.dart'; export 'trash_listener.dart'; export 'trash_service.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/application/trash_service.dart
import 'dart:async'; import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:appflowy_result/appflowy_result.dart'; class TrashService { Future<FlowyResult<RepeatedTrashPB, FlowyError>> readTrash() { return FolderEventListTrashItems().send(); } Future<FlowyResult<void, FlowyError>> putback(String trashId) { final id = TrashIdPB.create()..id = trashId; return FolderEventRestoreTrashItem(id).send(); } Future<FlowyResult<void, FlowyError>> deleteViews(List<String> trash) { final items = trash.map((trash) { return TrashIdPB.create()..id = trash; }); final ids = RepeatedTrashIdPB(items: items); return FolderEventPermanentlyDeleteTrashItem(ids).send(); } Future<FlowyResult<void, FlowyError>> restoreAll() { return FolderEventRecoverAllTrashItems().send(); } Future<FlowyResult<void, FlowyError>> deleteAll() { return FolderEventPermanentlyDeleteAllTrashItem().send(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/application/trash_listener.dart
import 'dart:async'; import 'dart:typed_data'; import 'package:appflowy/core/notification/folder_notification.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart'; import 'package:appflowy_backend/rust_stream.dart'; import 'package:appflowy_result/appflowy_result.dart'; typedef TrashUpdatedCallback = void Function( FlowyResult<List<TrashPB>, FlowyError> trashOrFailed, ); class TrashListener { StreamSubscription<SubscribeObject>? _subscription; TrashUpdatedCallback? _trashUpdated; FolderNotificationParser? _parser; void start({TrashUpdatedCallback? trashUpdated}) { _trashUpdated = trashUpdated; _parser = FolderNotificationParser( id: "trash", callback: _observableCallback, ); _subscription = RustStreamReceiver.listen((observable) => _parser?.parse(observable)); } void _observableCallback( FolderNotification ty, FlowyResult<Uint8List, FlowyError> result, ) { switch (ty) { case FolderNotification.DidUpdateTrash: if (_trashUpdated != null) { result.fold( (payload) { final repeatedTrash = RepeatedTrashPB.fromBuffer(payload); _trashUpdated!(FlowyResult.success(repeatedTrash.items)); }, (error) => _trashUpdated!(FlowyResult.failure(error)), ); } break; default: break; } } Future<void> close() async { _parser = null; await _subscription?.cancel(); _trashUpdated = null; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/application/trash_bloc.dart
import 'package:appflowy/plugins/trash/application/trash_listener.dart'; import 'package:appflowy/plugins/trash/application/trash_service.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'trash_bloc.freezed.dart'; class TrashBloc extends Bloc<TrashEvent, TrashState> { TrashBloc() : _service = TrashService(), _listener = TrashListener(), super(TrashState.init()) { _dispatch(); } final TrashService _service; final TrashListener _listener; void _dispatch() { on<TrashEvent>((event, emit) async { await event.map( initial: (e) async { _listener.start(trashUpdated: _listenTrashUpdated); final result = await _service.readTrash(); emit( result.fold( (object) => state.copyWith( objects: object.items, successOrFailure: FlowyResult.success(null), ), (error) => state.copyWith(successOrFailure: FlowyResult.failure(error)), ), ); }, didReceiveTrash: (e) async { emit(state.copyWith(objects: e.trash)); }, putback: (e) async { final result = await _service.putback(e.trashId); await _handleResult(result, emit); }, delete: (e) async { final result = await _service.deleteViews([e.trash.id]); await _handleResult(result, emit); }, deleteAll: (e) async { final result = await _service.deleteAll(); await _handleResult(result, emit); }, restoreAll: (e) async { final result = await _service.restoreAll(); await _handleResult(result, emit); }, ); }); } Future<void> _handleResult( FlowyResult<dynamic, FlowyError> result, Emitter<TrashState> emit, ) async { emit( result.fold( (l) => state.copyWith(successOrFailure: FlowyResult.success(null)), (error) => state.copyWith(successOrFailure: FlowyResult.failure(error)), ), ); } void _listenTrashUpdated( FlowyResult<List<TrashPB>, FlowyError> trashOrFailed, ) { trashOrFailed.fold( (trash) { add(TrashEvent.didReceiveTrash(trash)); }, (error) { Log.error(error); }, ); } @override Future<void> close() async { await _listener.close(); return super.close(); } } @freezed class TrashEvent with _$TrashEvent { const factory TrashEvent.initial() = Initial; const factory TrashEvent.didReceiveTrash(List<TrashPB> trash) = ReceiveTrash; const factory TrashEvent.putback(String trashId) = Putback; const factory TrashEvent.delete(TrashPB trash) = Delete; const factory TrashEvent.restoreAll() = RestoreAll; const factory TrashEvent.deleteAll() = DeleteAll; } @freezed class TrashState with _$TrashState { const factory TrashState({ required List<TrashPB> objects, required FlowyResult<void, FlowyError> successOrFailure, }) = _TrashState; factory TrashState.init() => TrashState( objects: [], successOrFailure: FlowyResult.success(null), ); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/src/sizes.dart
class TrashSizes { static double scale = 0.8; static double get headerHeight => 60 * scale; static double get fileNameWidth => 320 * scale; static double get lashModifyWidth => 230 * scale; static double get createTimeWidth => 230 * scale; // padding between createTime and action icon static double get padding => 40 * scale; static double get actionIconWidth => 40 * scale; static double get totalWidth => TrashSizes.fileNameWidth + TrashSizes.lashModifyWidth + TrashSizes.createTimeWidth + TrashSizes.padding + // restore and delete icon 2 * TrashSizes.actionIconWidth; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/src/trash_cell.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/style_widget/icon_button.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:fixnum/fixnum.dart' as $fixnum; import 'sizes.dart'; class TrashCell extends StatelessWidget { const TrashCell({ super.key, required this.object, required this.onRestore, required this.onDelete, }); final VoidCallback onRestore; final VoidCallback onDelete; final TrashPB object; @override Widget build(BuildContext context) { return Row( children: [ SizedBox( width: TrashSizes.fileNameWidth, child: FlowyText(object.name), ), SizedBox( width: TrashSizes.lashModifyWidth, child: FlowyText(dateFormatter(object.modifiedTime)), ), SizedBox( width: TrashSizes.createTimeWidth, child: FlowyText(dateFormatter(object.createTime)), ), const Spacer(), FlowyIconButton( iconColorOnHover: Theme.of(context).colorScheme.onSurface, width: TrashSizes.actionIconWidth, onPressed: onRestore, iconPadding: const EdgeInsets.all(5), icon: const FlowySvg(FlowySvgs.restore_s), ), const HSpace(20), FlowyIconButton( iconColorOnHover: Theme.of(context).colorScheme.onSurface, width: TrashSizes.actionIconWidth, onPressed: onDelete, iconPadding: const EdgeInsets.all(5), icon: const FlowySvg(FlowySvgs.delete_s), ), ], ); } String dateFormatter($fixnum.Int64 inputTimestamps) { final outputFormat = DateFormat('MM/dd/yyyy hh:mm a'); final date = DateTime.fromMillisecondsSinceEpoch(inputTimestamps.toInt() * 1000); final outputDate = outputFormat.format(date); return outputDate; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/trash/src/trash_header.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'sizes.dart'; class TrashHeaderDelegate extends SliverPersistentHeaderDelegate { TrashHeaderDelegate(); @override Widget build( BuildContext context, double shrinkOffset, bool overlapsContent, ) { return TrashHeader(); } @override double get maxExtent => TrashSizes.headerHeight; @override double get minExtent => TrashSizes.headerHeight; @override bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) { return false; } } class TrashHeaderItem { TrashHeaderItem({required this.width, required this.title}); double width; String title; } class TrashHeader extends StatelessWidget { TrashHeader({super.key}); final List<TrashHeaderItem> items = [ TrashHeaderItem( title: LocaleKeys.trash_pageHeader_fileName.tr(), width: TrashSizes.fileNameWidth, ), TrashHeaderItem( title: LocaleKeys.trash_pageHeader_lastModified.tr(), width: TrashSizes.lashModifyWidth, ), TrashHeaderItem( title: LocaleKeys.trash_pageHeader_created.tr(), width: TrashSizes.createTimeWidth, ), ]; @override Widget build(BuildContext context) { final headerItems = List<Widget>.empty(growable: true); items.asMap().forEach((index, item) { headerItems.add( SizedBox( width: item.width, child: FlowyText( item.title, color: Theme.of(context).disabledColor, ), ), ); }); return Container( color: Theme.of(context).colorScheme.surface, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ ...headerItems, ], ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_menu.dart
import 'package:flutter/material.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart'; import 'package:appflowy/plugins/inline_actions/widgets/inline_actions_handler.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; abstract class InlineActionsMenuService { InlineActionsMenuStyle get style; void show(); void dismiss(); } class InlineActionsMenu extends InlineActionsMenuService { InlineActionsMenu({ required this.context, required this.editorState, required this.service, required this.initialResults, required this.style, this.startCharAmount = 1, }); final BuildContext context; final EditorState editorState; final InlineActionsService service; final List<InlineActionsResult> initialResults; @override final InlineActionsMenuStyle style; final int startCharAmount; OverlayEntry? _menuEntry; bool selectionChangedByMenu = false; @override void dismiss() { if (_menuEntry != null) { editorState.service.keyboardService?.enable(); editorState.service.scrollService?.enable(); } _menuEntry?.remove(); _menuEntry = null; // workaround: SelectionService has been released after hot reload. final isSelectionDisposed = editorState.service.selectionServiceKey.currentState == null; if (!isSelectionDisposed) { final selectionService = editorState.service.selectionService; selectionService.currentSelection.removeListener(_onSelectionChange); } } void _onSelectionUpdate() => selectionChangedByMenu = true; @override void show() { WidgetsBinding.instance.addPostFrameCallback((_) => _show()); } void _show() { dismiss(); final selectionService = editorState.service.selectionService; final selectionRects = selectionService.selectionRects; if (selectionRects.isEmpty) { return; } const double menuHeight = 300.0; const double menuWidth = 200.0; const Offset menuOffset = Offset(0, 10); final Offset editorOffset = editorState.renderBox?.localToGlobal(Offset.zero) ?? Offset.zero; final Size editorSize = editorState.renderBox!.size; // Default to opening the overlay below Alignment alignment = Alignment.topLeft; final firstRect = selectionRects.first; Offset offset = firstRect.bottomRight + menuOffset; // Show above if (offset.dy + menuHeight >= editorOffset.dy + editorSize.height) { offset = firstRect.topRight - menuOffset; alignment = Alignment.bottomLeft; offset = Offset( offset.dx, MediaQuery.of(context).size.height - offset.dy, ); } // Show on the left final windowWidth = MediaQuery.of(context).size.width; if (offset.dx > (windowWidth - menuWidth)) { alignment = alignment == Alignment.topLeft ? Alignment.topRight : Alignment.bottomRight; offset = Offset( windowWidth - offset.dx, offset.dy, ); } final (left, top, right, bottom) = _getPosition(alignment, offset); _menuEntry = OverlayEntry( builder: (context) => SizedBox( height: editorSize.height, width: editorSize.width, // GestureDetector handles clicks outside of the context menu, // to dismiss the context menu. child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: dismiss, child: Stack( children: [ Positioned( top: top, bottom: bottom, left: left, right: right, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: InlineActionsHandler( service: service, results: initialResults, editorState: editorState, menuService: this, onDismiss: dismiss, onSelectionUpdate: _onSelectionUpdate, style: style, startCharAmount: startCharAmount, ), ), ), ], ), ), ), ); Overlay.of(context).insert(_menuEntry!); editorState.service.keyboardService?.disable(showCursor: true); editorState.service.scrollService?.disable(); selectionService.currentSelection.addListener(_onSelectionChange); } void _onSelectionChange() { // workaround: SelectionService has been released after hot reload. final isSelectionDisposed = editorState.service.selectionServiceKey.currentState == null; if (!isSelectionDisposed) { final selectionService = editorState.service.selectionService; if (selectionService.currentSelection.value == null) { return; } } if (!selectionChangedByMenu) { return dismiss(); } selectionChangedByMenu = false; } (double? left, double? top, double? right, double? bottom) _getPosition( Alignment alignment, Offset offset, ) { double? left, top, right, bottom; switch (alignment) { case Alignment.topLeft: left = offset.dx; top = offset.dy; break; case Alignment.bottomLeft: left = offset.dx; bottom = offset.dy; break; case Alignment.topRight: right = offset.dx; top = offset.dy; break; case Alignment.bottomRight: right = offset.dx; bottom = offset.dy; break; } return (left, top, right, bottom); } } class InlineActionsMenuStyle { InlineActionsMenuStyle({ required this.backgroundColor, required this.groupTextColor, required this.menuItemTextColor, required this.menuItemSelectedColor, required this.menuItemSelectedTextColor, }); const InlineActionsMenuStyle.light() : backgroundColor = Colors.white, groupTextColor = const Color(0xFF555555), menuItemTextColor = const Color(0xFF333333), menuItemSelectedColor = const Color(0xFFE0F8FF), menuItemSelectedTextColor = const Color.fromARGB(255, 56, 91, 247); const InlineActionsMenuStyle.dark() : backgroundColor = const Color(0xFF282E3A), groupTextColor = const Color(0xFFBBC3CD), menuItemTextColor = const Color(0xFFBBC3CD), menuItemSelectedColor = const Color(0xFF00BCF0), menuItemSelectedTextColor = const Color(0xFF131720); /// The background color of the context menu itself /// final Color backgroundColor; /// The color of the [InlineActionsGroup]'s title text /// final Color groupTextColor; /// The text color of an [InlineActionsMenuItem] /// final Color menuItemTextColor; /// The background of the currently selected [InlineActionsMenuItem] /// final Color menuItemSelectedColor; /// The text color of the currently selected [InlineActionsMenuItem] /// final Color menuItemSelectedTextColor; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_result.dart
import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; typedef SelectItemHandler = void Function( BuildContext context, EditorState editorState, InlineActionsMenuService menuService, (int start, int end) replacement, ); class InlineActionsMenuItem { InlineActionsMenuItem({ required this.label, this.icon, this.keywords, this.onSelected, }); final String label; final Widget Function(bool onSelected)? icon; final List<String>? keywords; final SelectItemHandler? onSelected; } class InlineActionsResult { InlineActionsResult({ required this.title, required this.results, this.startsWithKeywords, }); /// Localized title to be displayed above the results /// of the current group. /// final String title; /// List of results that will be displayed for this group /// made up of [SelectionMenuItem]s. /// final List<InlineActionsMenuItem> results; /// If the search term start with one of these keyword, /// the results will be reordered such that these results /// will be above. /// final List<String>? startsWithKeywords; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/service_handler.dart
import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; abstract class InlineActionsDelegate { Future<InlineActionsResult> search(String? search); Future<void> dispose() async {} }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_command.dart
import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; const inlineActionCharacter = '@'; CharacterShortcutEvent inlineActionsCommand( InlineActionsService inlineActionsService, { InlineActionsMenuStyle style = const InlineActionsMenuStyle.light(), }) => CharacterShortcutEvent( key: 'Opens Inline Actions Menu', character: inlineActionCharacter, handler: (editorState) => inlineActionsCommandHandler( editorState, inlineActionsService, style, ), ); InlineActionsMenuService? selectionMenuService; Future<bool> inlineActionsCommandHandler( EditorState editorState, InlineActionsService service, InlineActionsMenuStyle style, ) async { final selection = editorState.selection; if (PlatformExtension.isMobile || selection == null) { return false; } if (!selection.isCollapsed) { await editorState.deleteSelection(selection); } await editorState.insertTextAtPosition( inlineActionCharacter, position: selection.start, ); final List<InlineActionsResult> initialResults = []; for (final handler in service.handlers) { final group = await handler.search(null); if (group.results.isNotEmpty) { initialResults.add(group); } } if (service.context != null) { selectionMenuService = InlineActionsMenu( context: service.context!, editorState: editorState, service: service, initialResults: initialResults, style: style, ); selectionMenuService?.show(); } return true; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_service.dart
import 'package:flutter/material.dart'; import 'package:appflowy/plugins/inline_actions/service_handler.dart'; abstract class _InlineActionsProvider { void dispose(); } class InlineActionsService extends _InlineActionsProvider { InlineActionsService({ required this.context, required this.handlers, }); /// The [BuildContext] in which to show the [InlineActionsMenu] /// BuildContext? context; final List<InlineActionsDelegate> handlers; /// This is a workaround for not having a mounted check. /// Thus when the widget that uses the service is disposed, /// we set the [BuildContext] to null. /// @override Future<void> dispose() async { for (final handler in handlers) { await handler.dispose(); } context = null; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/widgets/inline_actions_menu_group.dart
import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:flowy_infra_ui/style_widget/button.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flutter/material.dart'; class InlineActionsGroup extends StatelessWidget { const InlineActionsGroup({ super.key, required this.result, required this.editorState, required this.menuService, required this.style, required this.onSelected, required this.startOffset, required this.endOffset, this.isLastGroup = false, this.isGroupSelected = false, this.selectedIndex = 0, }); final InlineActionsResult result; final EditorState editorState; final InlineActionsMenuService menuService; final InlineActionsMenuStyle style; final VoidCallback onSelected; final int startOffset; final int endOffset; final bool isLastGroup; final bool isGroupSelected; final int selectedIndex; @override Widget build(BuildContext context) { return Padding( padding: isLastGroup ? EdgeInsets.zero : const EdgeInsets.only(bottom: 6), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FlowyText.medium(result.title, color: style.groupTextColor), const SizedBox(height: 4), ...result.results.mapIndexed( (index, item) => InlineActionsWidget( item: item, editorState: editorState, menuService: menuService, isSelected: isGroupSelected && index == selectedIndex, style: style, onSelected: onSelected, startOffset: startOffset, endOffset: endOffset, ), ), ], ), ); } } class InlineActionsWidget extends StatefulWidget { const InlineActionsWidget({ super.key, required this.item, required this.editorState, required this.menuService, required this.isSelected, required this.style, required this.onSelected, required this.startOffset, required this.endOffset, }); final InlineActionsMenuItem item; final EditorState editorState; final InlineActionsMenuService menuService; final bool isSelected; final InlineActionsMenuStyle style; final VoidCallback onSelected; final int startOffset; final int endOffset; @override State<InlineActionsWidget> createState() => _InlineActionsWidgetState(); } class _InlineActionsWidgetState extends State<InlineActionsWidget> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 2), child: SizedBox( width: 200, child: FlowyButton( isSelected: widget.isSelected, leftIcon: widget.item.icon?.call(widget.isSelected), text: FlowyText.regular(widget.item.label), onTap: _onPressed, ), ), ); } void _onPressed() { widget.onSelected(); widget.item.onSelected?.call( context, widget.editorState, widget.menuService, (widget.startOffset, widget.endOffset), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/widgets/inline_actions_handler.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart'; import 'package:appflowy/plugins/inline_actions/widgets/inline_actions_menu_group.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; /// All heights are in physical pixels const double _groupTextHeight = 14; // 12 height + 2 bottom spacing const double _groupBottomSpacing = 6; const double _itemHeight = 30; // 26 height + 4 vertical spacing (2*2) const double _menuHeight = 300; const double _contentHeight = 260; extension _StartWithsSort on List<InlineActionsResult> { void sortByStartsWithKeyword(String search) => sort( (a, b) { final aCount = a.startsWithKeywords ?.where( (key) => search.toLowerCase().startsWith(key), ) .length ?? 0; final bCount = b.startsWithKeywords ?.where( (key) => search.toLowerCase().startsWith(key), ) .length ?? 0; if (aCount > bCount) { return -1; } else if (bCount > aCount) { return 1; } return 0; }, ); } const _invalidSearchesAmount = 20; class InlineActionsHandler extends StatefulWidget { const InlineActionsHandler({ super.key, required this.service, required this.results, required this.editorState, required this.menuService, required this.onDismiss, required this.onSelectionUpdate, required this.style, this.startCharAmount = 1, }); final InlineActionsService service; final List<InlineActionsResult> results; final EditorState editorState; final InlineActionsMenuService menuService; final VoidCallback onDismiss; final VoidCallback onSelectionUpdate; final InlineActionsMenuStyle style; final int startCharAmount; @override State<InlineActionsHandler> createState() => _InlineActionsHandlerState(); } class _InlineActionsHandlerState extends State<InlineActionsHandler> { final _focusNode = FocusNode(debugLabel: 'inline_actions_menu_handler'); final _scrollController = ScrollController(); late List<InlineActionsResult> results = widget.results; int invalidCounter = 0; late int startOffset; String _search = ''; set search(String search) { _search = search; _doSearch(); } Future<void> _doSearch() async { final List<InlineActionsResult> newResults = []; for (final handler in widget.service.handlers) { final group = await handler.search(_search); if (group.results.isNotEmpty) { newResults.add(group); } } invalidCounter = results.every((group) => group.results.isEmpty) ? invalidCounter + 1 : 0; if (invalidCounter >= _invalidSearchesAmount) { // Workaround to bring focus back to editor await widget.editorState .updateSelectionWithReason(widget.editorState.selection); return widget.onDismiss(); } _resetSelection(); newResults.sortByStartsWithKeyword(_search); setState(() => results = newResults); } void _resetSelection() { _selectedGroup = 0; _selectedIndex = 0; } int _selectedGroup = 0; int _selectedIndex = 0; @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback( (_) => _focusNode.requestFocus(), ); startOffset = widget.editorState.selection?.endIndex ?? 0; } @override void dispose() { _scrollController.dispose(); _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Focus( focusNode: _focusNode, onKeyEvent: onKeyEvent, child: Container( constraints: BoxConstraints.loose(const Size(200, _menuHeight)), decoration: BoxDecoration( color: widget.style.backgroundColor, borderRadius: BorderRadius.circular(6.0), boxShadow: [ BoxShadow( blurRadius: 5, spreadRadius: 1, color: Colors.black.withOpacity(0.1), ), ], ), child: Padding( padding: const EdgeInsets.all(8.0), child: noResults ? SizedBox( width: 150, child: FlowyText.regular( LocaleKeys.inlineActions_noResults.tr(), ), ) : SingleChildScrollView( controller: _scrollController, physics: const ClampingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: results .where((g) => g.results.isNotEmpty) .mapIndexed( (index, group) => InlineActionsGroup( result: group, editorState: widget.editorState, menuService: widget.menuService, style: widget.style, onSelected: widget.onDismiss, startOffset: startOffset - widget.startCharAmount, endOffset: _search.length + widget.startCharAmount, isLastGroup: index == results.length - 1, isGroupSelected: _selectedGroup == index, selectedIndex: _selectedIndex, ), ) .toList(), ), ), ), ), ); } bool get noResults => results.isEmpty || results.every((e) => e.results.isEmpty); int get groupLength => results.length; int lengthOfGroup(int index) => results.length > index ? results[index].results.length : -1; InlineActionsMenuItem handlerOf(int groupIndex, int handlerIndex) => results[groupIndex].results[handlerIndex]; KeyEventResult onKeyEvent(focus, KeyEvent event) { if (event is! KeyDownEvent) { return KeyEventResult.ignored; } const moveKeys = [ LogicalKeyboardKey.arrowUp, LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.tab, ]; if (event.logicalKey == LogicalKeyboardKey.enter) { if (_selectedGroup <= groupLength && _selectedIndex <= lengthOfGroup(_selectedGroup)) { handlerOf(_selectedGroup, _selectedIndex).onSelected?.call( context, widget.editorState, widget.menuService, ( startOffset - widget.startCharAmount, _search.length + widget.startCharAmount ), ); widget.onDismiss(); return KeyEventResult.handled; } if (noResults) { // Workaround to bring focus back to editor widget.editorState .updateSelectionWithReason(widget.editorState.selection); widget.editorState.insertNewLine(); widget.onDismiss(); return KeyEventResult.handled; } } else if (event.logicalKey == LogicalKeyboardKey.escape) { // Workaround to bring focus back to editor widget.editorState .updateSelectionWithReason(widget.editorState.selection); widget.onDismiss(); } else if (event.logicalKey == LogicalKeyboardKey.backspace) { if (_search.isEmpty) { if (_canDeleteLastCharacter()) { widget.editorState.deleteBackward(); } else { // Workaround for editor regaining focus widget.editorState.apply( widget.editorState.transaction ..afterSelection = widget.editorState.selection, ); } widget.onDismiss(); } else { widget.onSelectionUpdate(); widget.editorState.deleteBackward(); _deleteCharacterAtSelection(); } return KeyEventResult.handled; } else if (event.character != null && ![ ...moveKeys, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowRight, ].contains(event.logicalKey)) { /// Prevents dismissal of context menu by notifying the parent /// that the selection change occurred from the handler. widget.onSelectionUpdate(); // Interpolation to avoid having a getter for private variable _insertCharacter(event.character!); return KeyEventResult.handled; } if (moveKeys.contains(event.logicalKey)) { _moveSelection(event.logicalKey); return KeyEventResult.handled; } if ([LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowRight] .contains(event.logicalKey)) { widget.onSelectionUpdate(); event.logicalKey == LogicalKeyboardKey.arrowLeft ? widget.editorState.moveCursorForward() : widget.editorState.moveCursorBackward(SelectionMoveRange.character); /// If cursor moves before @ then dismiss menu /// If cursor moves after @search.length then dismiss menu final selection = widget.editorState.selection; if (selection != null && (selection.endIndex < startOffset || selection.endIndex > (startOffset + _search.length))) { widget.onDismiss(); } /// Workaround: When using the move cursor methods, it seems the /// focus goes back to the editor, this makes sure this handler /// receives the next keypress. /// _focusNode.requestFocus(); return KeyEventResult.handled; } return KeyEventResult.handled; } void _insertCharacter(String character) { widget.editorState.insertTextAtCurrentSelection(character); final selection = widget.editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final delta = widget.editorState.getNodeAtPath(selection.end.path)?.delta; if (delta == null) { return; } search = widget.editorState .getTextInSelection( selection.copyWith( start: selection.start.copyWith(offset: startOffset), end: selection.start .copyWith(offset: startOffset + _search.length + 1), ), ) .join(); } void _moveSelection(LogicalKeyboardKey key) { bool didChange = false; if (key == LogicalKeyboardKey.arrowUp || (key == LogicalKeyboardKey.tab && HardwareKeyboard.instance.isShiftPressed)) { if (_selectedIndex == 0 && _selectedGroup > 0) { _selectedGroup -= 1; _selectedIndex = lengthOfGroup(_selectedGroup) - 1; didChange = true; } else if (_selectedIndex > 0) { _selectedIndex -= 1; didChange = true; } } else if ([LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.tab] .contains(key)) { if (_selectedIndex < lengthOfGroup(_selectedGroup) - 1) { _selectedIndex += 1; didChange = true; } else if (_selectedGroup < groupLength - 1) { _selectedGroup += 1; _selectedIndex = 0; didChange = true; } } if (mounted && didChange) { setState(() {}); _scrollToItem(); } } void _scrollToItem() { final groups = _selectedGroup + 1; int items = 0; for (int i = 0; i <= _selectedGroup; i++) { items += lengthOfGroup(i); } // Remove the leftover items items -= lengthOfGroup(_selectedGroup) - (_selectedIndex + 1); /// The offset is roughly calculated by: /// - Amount of Groups passed /// - Amount of Items passed final double offset = (_groupTextHeight + _groupBottomSpacing) * groups + _itemHeight * items; // We have a buffer so that when moving up, we show items above the currently // selected item. The buffer is the height of 2 items if (offset <= _scrollController.offset + _itemHeight * 2) { // We want to show the user some options above the newly // focused one, therefore we take the offset and subtract // the height of three items (current + 2) _scrollController.animateTo( offset - _itemHeight * 3, duration: const Duration(milliseconds: 200), curve: Curves.easeIn, ); } else if (offset > _scrollController.offset + _contentHeight - _itemHeight - _groupTextHeight) { // The same here, we want to show the options below the // newly focused item when moving downwards, therefore we add // 2 times the item height to the offset _scrollController.animateTo( offset - _contentHeight + _itemHeight * 2, duration: const Duration(milliseconds: 200), curve: Curves.easeIn, ); } } void _deleteCharacterAtSelection() { final selection = widget.editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = widget.editorState.getNodeAtPath(selection.end.path); final delta = node?.delta; if (node == null || delta == null) { return; } search = delta.toPlainText().substring( startOffset, startOffset - 1 + _search.length, ); } bool _canDeleteLastCharacter() { final selection = widget.editorState.selection; if (selection == null || !selection.isCollapsed) { return false; } final delta = widget.editorState.getNodeAtPath(selection.start.path)?.delta; if (delta == null) { return false; } return delta.isNotEmpty; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/date_reference.dart
import 'package:flutter/material.dart'; import 'package:appflowy/date/date_service.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/string_extension.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/service_handler.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; final _keywords = [ LocaleKeys.inlineActions_date.tr().toLowerCase(), ]; class DateReferenceService extends InlineActionsDelegate { DateReferenceService(this.context) { // Initialize locale _locale = context.locale.toLanguageTag(); // Initializes options _setOptions(); } final BuildContext context; late String _locale; late List<InlineActionsMenuItem> _allOptions; List<InlineActionsMenuItem> options = []; @override Future<InlineActionsResult> search([ String? search, ]) async { // Checks if Locale has changed since last _setLocale(); // Filters static options _filterOptions(search); // Searches for date by pattern _searchDate(search); // Searches for date by natural language prompt await _searchDateNLP(search); return InlineActionsResult( title: LocaleKeys.inlineActions_date.tr(), results: options, ); } void _filterOptions(String? search) { if (search == null || search.isEmpty) { options = _allOptions; return; } options = _allOptions .where( (option) => option.keywords != null && option.keywords!.isNotEmpty && option.keywords!.any( (keyword) => keyword.contains(search.toLowerCase()), ), ) .toList(); if (options.isEmpty && _keywords.any((k) => search.startsWith(k))) { _setOptions(); options = _allOptions; } } void _searchDate(String? search) { if (search == null || search.isEmpty) { return; } try { final date = DateFormat.yMd(_locale).parse(search); options.insert(0, _itemFromDate(date)); } catch (_) { return; } } Future<void> _searchDateNLP(String? search) async { if (search == null || search.isEmpty) { return; } final result = await DateService.queryDate(search); result.fold( (date) => options.insert(0, _itemFromDate(date)), (_) {}, ); } Future<void> _insertDateReference( EditorState editorState, DateTime date, int start, int end, ) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = editorState.getNodeAtPath(selection.end.path); final delta = node?.delta; if (node == null || delta == null) { return; } final transaction = editorState.transaction ..replaceText( node, start, end, '\$', attributes: { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.date.name, MentionBlockKeys.date: date.toIso8601String(), }, }, ); await editorState.apply(transaction); } void _setOptions() { final today = DateTime.now(); final tomorrow = today.add(const Duration(days: 1)); final yesterday = today.subtract(const Duration(days: 1)); _allOptions = [ _itemFromDate( today, LocaleKeys.relativeDates_today.tr(), [DateFormat.yMd(_locale).format(today)], ), _itemFromDate( tomorrow, LocaleKeys.relativeDates_tomorrow.tr(), [DateFormat.yMd(_locale).format(tomorrow)], ), _itemFromDate( yesterday, LocaleKeys.relativeDates_yesterday.tr(), [DateFormat.yMd(_locale).format(yesterday)], ), ]; } /// Sets Locale on each search to make sure /// keywords are localized void _setLocale() { final locale = context.locale.toLanguageTag(); if (locale != _locale) { _locale = locale; _setOptions(); } } InlineActionsMenuItem _itemFromDate( DateTime date, [ String? label, List<String>? keywords, ]) { final labelStr = label ?? DateFormat.yMd(_locale).format(date); return InlineActionsMenuItem( label: labelStr.capitalize(), keywords: [labelStr.toLowerCase(), ...?keywords], onSelected: (context, editorState, menuService, replace) => _insertDateReference( editorState, date, replace.$1, replace.$2, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/reminder_reference.dart
import 'package:appflowy/date/date_service.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/application/document_bloc.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/string_extension.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/service_handler.dart'; import 'package:appflowy/user/application/reminder/reminder_bloc.dart'; import 'package:appflowy/user/application/reminder/reminder_extension.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart'; import 'package:appflowy_backend/protobuf/flowy-user/reminder.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fixnum/fixnum.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nanoid/nanoid.dart'; final _keywords = [ LocaleKeys.inlineActions_reminder_groupTitle.tr().toLowerCase(), LocaleKeys.inlineActions_reminder_shortKeyword.tr().toLowerCase(), ]; class ReminderReferenceService extends InlineActionsDelegate { ReminderReferenceService(this.context) { // Initialize locale _locale = context.locale.toLanguageTag(); // Initializes options _setOptions(); } final BuildContext context; late String _locale; late List<InlineActionsMenuItem> _allOptions; List<InlineActionsMenuItem> options = []; @override Future<InlineActionsResult> search([ String? search, ]) async { // Checks if Locale has changed since last _setLocale(); // Filters static options _filterOptions(search); // Searches for date by pattern _searchDate(search); // Searches for date by natural language prompt await _searchDateNLP(search); return _groupFromResults(options); } InlineActionsResult _groupFromResults([ List<InlineActionsMenuItem>? options, ]) => InlineActionsResult( title: LocaleKeys.inlineActions_reminder_groupTitle.tr(), results: options ?? [], startsWithKeywords: [ LocaleKeys.inlineActions_reminder_groupTitle.tr().toLowerCase(), LocaleKeys.inlineActions_reminder_shortKeyword.tr().toLowerCase(), ], ); void _filterOptions(String? search) { if (search == null || search.isEmpty) { options = _allOptions; return; } options = _allOptions .where( (option) => option.keywords != null && option.keywords!.isNotEmpty && option.keywords!.any( (keyword) => keyword.contains(search.toLowerCase()), ), ) .toList(); if (options.isEmpty && _keywords.any((k) => search.startsWith(k))) { _setOptions(); options = _allOptions; } } void _searchDate(String? search) { if (search == null || search.isEmpty) { return; } try { final date = DateFormat.yMd(_locale).parse(search); options.insert(0, _itemFromDate(date)); } catch (_) { return; } } Future<void> _searchDateNLP(String? search) async { if (search == null || search.isEmpty) { return; } final result = await DateService.queryDate(search); result.fold( (date) { // Only insert dates in the future if (DateTime.now().isBefore(date)) { options.insert(0, _itemFromDate(date)); } }, (_) {}, ); } Future<void> _insertReminderReference( EditorState editorState, DateTime date, int start, int end, ) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = editorState.getNodeAtPath(selection.end.path); final delta = node?.delta; if (node == null || delta == null) { return; } final viewId = context.read<DocumentBloc>().view.id; final reminder = _reminderFromDate(date, viewId, node); final transaction = editorState.transaction ..replaceText( node, start, end, '\$', attributes: { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.date.name, MentionBlockKeys.date: date.toIso8601String(), MentionBlockKeys.reminderId: reminder.id, MentionBlockKeys.reminderOption: ReminderOption.atTimeOfEvent.name, }, }, ); await editorState.apply(transaction); if (context.mounted) { context.read<ReminderBloc>().add(ReminderEvent.add(reminder: reminder)); } } void _setOptions() { final today = DateTime.now(); final tomorrow = today.add(const Duration(days: 1)); final oneWeek = today.add(const Duration(days: 7)); _allOptions = [ _itemFromDate( tomorrow, LocaleKeys.relativeDates_tomorrow.tr(), [DateFormat.yMd(_locale).format(tomorrow)], ), _itemFromDate( oneWeek, LocaleKeys.relativeDates_oneWeek.tr(), [DateFormat.yMd(_locale).format(oneWeek)], ), ]; } /// Sets Locale on each search to make sure /// keywords are localized void _setLocale() { final locale = context.locale.toLanguageTag(); if (locale != _locale) { _locale = locale; _setOptions(); } } InlineActionsMenuItem _itemFromDate( DateTime date, [ String? label, List<String>? keywords, ]) { final labelStr = label ?? DateFormat.yMd(_locale).format(date); return InlineActionsMenuItem( label: labelStr.capitalize(), keywords: [labelStr.toLowerCase(), ...?keywords], onSelected: (context, editorState, menuService, replace) => _insertReminderReference(editorState, date, replace.$1, replace.$2), ); } ReminderPB _reminderFromDate(DateTime date, String viewId, Node node) { return ReminderPB( id: nanoid(), objectId: viewId, title: LocaleKeys.reminderNotification_title.tr(), message: LocaleKeys.reminderNotification_message.tr(), meta: { ReminderMetaKeys.includeTime: false.toString(), ReminderMetaKeys.blockId: node.id, }, scheduledAt: Int64(date.millisecondsSinceEpoch ~/ 1000), isAck: date.isBefore(DateTime.now()), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/inline_page_reference.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/base/emoji/emoji_text.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/insert_page_command.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart'; import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart'; import 'package:appflowy/plugins/inline_actions/service_handler.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/view/view_ext.dart'; import 'package:appflowy/workspace/application/view/view_service.dart'; import 'package:appflowy/workspace/application/workspace/workspace_listener.dart'; import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/widget/dialog/styled_dialogs.dart'; import 'package:flowy_infra_ui/widget/error_page.dart'; class InlinePageReferenceService extends InlineActionsDelegate { InlinePageReferenceService({ required this.currentViewId, this.viewLayout, this.customTitle, this.insertPage = false, this.limitResults = 0, }) { init(); } final Completer _initCompleter = Completer<void>(); final String currentViewId; final ViewLayoutPB? viewLayout; final String? customTitle; /// Defaults to false, if set to true the Page /// will be inserted as a Reference /// When false, a link to the view will be inserted /// final bool insertPage; /// Defaults to 0 where there are no limits /// Anything above 0 will limit the page reference results /// to [limitResults]. /// final int limitResults; final ViewBackendService service = ViewBackendService(); List<InlineActionsMenuItem> _items = []; List<InlineActionsMenuItem> _filtered = []; UserProfilePB? _user; String? _workspaceId; WorkspaceListener? _listener; Future<void> init() async { _items = await _generatePageItems(currentViewId, viewLayout); _filtered = limitResults > 0 ? _items.take(limitResults).toList() : _items; await _initWorkspaceListener(); _initCompleter.complete(); } Future<void> _initWorkspaceListener() async { final snapshot = await Future.wait([ FolderEventGetCurrentWorkspaceSetting().send(), getIt<AuthService>().getUser(), ]); final (workspaceSettings, userProfile) = (snapshot.first, snapshot.last); _workspaceId = workspaceSettings.fold( (s) => (s as WorkspaceSettingPB).workspaceId, (e) => null, ); _user = userProfile.fold((s) => s as UserProfilePB, (e) => null); if (_user != null && _workspaceId != null) { _listener = WorkspaceListener( user: _user!, workspaceId: _workspaceId!, ); _listener!.start( appsChanged: (_) async { _items = await _generatePageItems(currentViewId, viewLayout); _filtered = limitResults > 0 ? _items.take(limitResults).toList() : _items; }, ); } } @override Future<InlineActionsResult> search([ String? search, ]) async { _filtered = await _filterItems(search); return InlineActionsResult( title: customTitle?.isNotEmpty == true ? customTitle! : LocaleKeys.inlineActions_pageReference.tr(), results: _filtered, ); } @override Future<void> dispose() async { await _listener?.stop(); } Future<List<InlineActionsMenuItem>> _filterItems(String? search) async { await _initCompleter.future; final items = (search == null || search.isEmpty) ? _items : _items.where( (item) => item.keywords != null && item.keywords!.isNotEmpty && item.keywords!.any( (keyword) => keyword.contains(search.toLowerCase()), ), ); return limitResults > 0 ? items.take(limitResults).toList() : items.toList(); } Future<List<InlineActionsMenuItem>> _generatePageItems( String currentViewId, ViewLayoutPB? viewLayout, ) async { late List<ViewPB> views; if (viewLayout != null) { views = await service.fetchViewsWithLayoutType(viewLayout); } else { views = await service.fetchViews(); } if (views.isEmpty) { return []; } final List<InlineActionsMenuItem> pages = []; views.sort((a, b) => b.createTime.compareTo(a.createTime)); for (final view in views) { if (view.id == currentViewId) { continue; } final pageSelectionMenuItem = InlineActionsMenuItem( keywords: [view.name.toLowerCase()], label: view.name, icon: (onSelected) => view.icon.value.isNotEmpty ? EmojiText( emoji: view.icon.value, fontSize: 12, textAlign: TextAlign.center, lineHeight: 1.3, ) : view.defaultIcon(), onSelected: (context, editorState, menuService, replace) => insertPage ? _onInsertPageRef(view, context, editorState, replace) : _onInsertLinkRef( view, context, editorState, menuService, replace, ), ); pages.add(pageSelectionMenuItem); } return pages; } Future<void> _onInsertPageRef( ViewPB view, BuildContext context, EditorState editorState, (int, int) replace, ) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = editorState.getNodeAtPath(selection.start.path); if (node != null) { // Delete search term if (replace.$2 > 0) { final transaction = editorState.transaction ..deleteText(node, replace.$1, replace.$2); await editorState.apply(transaction); } // Insert newline before inserting referenced database if (node.delta?.toPlainText().isNotEmpty == true) { await editorState.insertNewLine(); } } try { await editorState.insertReferencePage(view, view.layout); } on FlowyError catch (e) { if (context.mounted) { return Dialogs.show( context, child: FlowyErrorPage.message( e.msg, howToFix: LocaleKeys.errorDialog_howToFixFallback.tr(), ), ); } } } Future<void> _onInsertLinkRef( ViewPB view, BuildContext context, EditorState editorState, InlineActionsMenuService menuService, (int, int) replace, ) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = editorState.getNodeAtPath(selection.start.path); final delta = node?.delta; if (node == null || delta == null) { return; } // @page name -> $ // preload the page infos pageMemorizer[view.id] = view; final transaction = editorState.transaction ..replaceText( node, replace.$1, replace.$2, '\$', attributes: { MentionBlockKeys.mention: { MentionBlockKeys.type: MentionType.page.name, MentionBlockKeys.pageId: view.id, }, }, ); await editorState.apply(transaction); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/drag_handler.dart
import 'package:flutter/material.dart'; class DragHandle extends StatelessWidget { const DragHandle({ super.key, }); @override Widget build(BuildContext context) { return Container( height: 4, width: 40, margin: const EdgeInsets.symmetric(vertical: 6), decoration: BoxDecoration( color: Colors.grey.shade400, borderRadius: BorderRadius.circular(2), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/icon/icon_picker_page.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/plugins/base/icon/icon_picker.dart'; import 'package:easy_localization/easy_localization.dart'; class IconPickerPage extends StatelessWidget { const IconPickerPage({ super.key, this.title, required this.onSelected, }); final void Function(EmojiPickerResult) onSelected; final String? title; @override Widget build(BuildContext context) { return Scaffold( appBar: FlowyAppBar( titleText: title ?? LocaleKeys.titleBar_pageIcon.tr(), ), body: SafeArea( child: FlowyIconPicker(onSelected: onSelected), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/icon/icon_picker.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/base/emoji/emoji_picker.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/icon.pbenum.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/style_widget/hover.dart'; extension ToProto on FlowyIconType { ViewIconTypePB toProto() { switch (this) { case FlowyIconType.emoji: return ViewIconTypePB.Emoji; case FlowyIconType.icon: return ViewIconTypePB.Icon; case FlowyIconType.custom: return ViewIconTypePB.Url; } } } enum FlowyIconType { emoji, icon, custom; } class EmojiPickerResult { factory EmojiPickerResult.none() => const EmojiPickerResult(FlowyIconType.icon, ''); factory EmojiPickerResult.emoji(String emoji) => EmojiPickerResult(FlowyIconType.emoji, emoji); const EmojiPickerResult( this.type, this.emoji, ); final FlowyIconType type; final String emoji; } class FlowyIconPicker extends StatelessWidget { const FlowyIconPicker({ super.key, required this.onSelected, }); final void Function(EmojiPickerResult result) onSelected; @override Widget build(BuildContext context) { // ONLY supports emoji picker for now return DefaultTabController( length: 1, child: Column( mainAxisSize: MainAxisSize.min, children: [ Row( children: [ _buildTabs(context), const Spacer(), _RemoveIconButton( onTap: () => onSelected(EmojiPickerResult.none()), ), ], ), const Divider(height: 2), Expanded( child: TabBarView( children: [ FlowyEmojiPicker( emojiPerLine: _getEmojiPerLine(context), onEmojiSelected: (_, emoji) => onSelected(EmojiPickerResult.emoji(emoji)), ), ], ), ), ], ), ); } Widget _buildTabs(BuildContext context) { return Align( alignment: Alignment.centerLeft, child: TabBar( indicatorSize: TabBarIndicatorSize.label, isScrollable: true, overlayColor: MaterialStatePropertyAll( Theme.of(context).colorScheme.secondary, ), padding: EdgeInsets.zero, tabs: [ FlowyHover( style: const HoverStyle(borderRadius: BorderRadius.zero), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 12.0, vertical: 8.0, ), child: FlowyText(LocaleKeys.emoji_emojiTab.tr()), ), ), ], ), ); } int _getEmojiPerLine(BuildContext context) { if (PlatformExtension.isDesktopOrWeb) { return 9; } final width = MediaQuery.of(context).size.width; return width ~/ 46.0; // the size of the emoji } } class _RemoveIconButton extends StatelessWidget { const _RemoveIconButton({required this.onTap}); final VoidCallback onTap; @override Widget build(BuildContext context) { return SizedBox( height: 28, child: FlowyButton( onTap: onTap, useIntrinsicWidth: true, text: FlowyText.small( LocaleKeys.document_plugins_cover_removeIcon.tr(), ), leftIcon: const FlowySvg(FlowySvgs.delete_s), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_picker_header.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_emoji_mart/flutter_emoji_mart.dart'; class FlowyEmojiHeader extends StatelessWidget { const FlowyEmojiHeader({ super.key, required this.category, }); final Category category; @override Widget build(BuildContext context) { if (PlatformExtension.isDesktopOrWeb) { return Container( height: 22, padding: const EdgeInsets.symmetric(horizontal: 8.0), color: Theme.of(context).cardColor, child: FlowyText.regular(category.id), ); } else { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 40, width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 8.0), color: Theme.of(context).cardColor, child: Padding( padding: const EdgeInsets.only( top: 14.0, bottom: 4.0, ), child: FlowyText.regular(category.id), ), ), const Divider( height: 1, thickness: 1, ), ], ); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_picker_i18n.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_emoji_mart/flutter_emoji_mart.dart'; class FlowyEmojiPickerI18n extends EmojiPickerI18n { @override String get activity => LocaleKeys.emoji_categories_activities.tr(); @override String get flags => LocaleKeys.emoji_categories_flags.tr(); @override String get foods => LocaleKeys.emoji_categories_food.tr(); @override String get frequent => LocaleKeys.emoji_categories_frequentlyUsed.tr(); @override String get nature => LocaleKeys.emoji_categories_nature.tr(); @override String get objects => LocaleKeys.emoji_categories_objects.tr(); @override String get people => LocaleKeys.emoji_categories_smileys.tr(); @override String get places => LocaleKeys.emoji_categories_places.tr(); @override String get search => LocaleKeys.emoji_search.tr(); @override String get symbols => LocaleKeys.emoji_categories_symbols.tr(); @override String get searchHintText => LocaleKeys.emoji_search.tr(); @override String get searchNoResult => LocaleKeys.emoji_noEmojiFound.tr(); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_picker_screen.dart
import 'package:appflowy/plugins/base/icon/icon_picker.dart'; import 'package:appflowy/plugins/base/icon/icon_picker_page.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class MobileEmojiPickerScreen extends StatelessWidget { const MobileEmojiPickerScreen({super.key, this.title}); final String? title; static const routeName = '/emoji_picker'; static const pageTitle = 'title'; @override Widget build(BuildContext context) { return IconPickerPage( title: title, onSelected: (result) { context.pop<EmojiPickerResult>(result); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_text.dart
import 'dart:io'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; // used to prevent loading font from google fonts every time List<String>? _cachedFallbackFontFamily; // Some emojis are not supported by the default font on Android or Linux, fallback to noto color emoji class EmojiText extends StatelessWidget { const EmojiText({ super.key, required this.emoji, required this.fontSize, this.textAlign, this.lineHeight, }); final String emoji; final double fontSize; final TextAlign? textAlign; final double? lineHeight; @override Widget build(BuildContext context) { _loadFallbackFontFamily(); return FlowyText( emoji, fontSize: fontSize, textAlign: textAlign, fallbackFontFamily: _cachedFallbackFontFamily, lineHeight: lineHeight, ); } void _loadFallbackFontFamily() { if (Platform.isLinux || Platform.isAndroid) { final notoColorEmoji = GoogleFonts.notoColorEmoji().fontFamily; if (notoColorEmoji != null) { _cachedFallbackFontFamily = [notoColorEmoji]; } } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_picker.dart
import 'dart:io'; import 'package:appflowy/plugins/base/emoji/emoji_picker_header.dart'; import 'package:appflowy/plugins/base/emoji/emoji_search_bar.dart'; import 'package:appflowy/plugins/base/emoji/emoji_skin_tone.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_emoji_mart/flutter_emoji_mart.dart'; import 'package:google_fonts/google_fonts.dart'; // use a global value to store the selected emoji to prevent reloading every time. EmojiData? _cachedEmojiData; class FlowyEmojiPicker extends StatefulWidget { const FlowyEmojiPicker({ super.key, required this.onEmojiSelected, this.emojiPerLine = 9, }); final EmojiSelectedCallback onEmojiSelected; final int emojiPerLine; @override State<FlowyEmojiPicker> createState() => _FlowyEmojiPickerState(); } class _FlowyEmojiPickerState extends State<FlowyEmojiPicker> { EmojiData? emojiData; List<String>? fallbackFontFamily; @override void initState() { super.initState(); // load the emoji data from cache if it's available if (_cachedEmojiData != null) { emojiData = _cachedEmojiData; } else { EmojiData.builtIn().then( (value) { _cachedEmojiData = value; setState(() { emojiData = value; }); }, ); } if (Platform.isAndroid || Platform.isLinux) { final notoColorEmoji = GoogleFonts.notoColorEmoji().fontFamily; if (notoColorEmoji != null) { fallbackFontFamily = [notoColorEmoji]; } } } @override Widget build(BuildContext context) { if (emojiData == null) { return const Center( child: SizedBox.square( dimension: 24.0, child: CircularProgressIndicator( strokeWidth: 2.0, ), ), ); } return EmojiPicker( emojiData: emojiData!, configuration: EmojiPickerConfiguration( showTabs: false, defaultSkinTone: lastSelectedEmojiSkinTone ?? EmojiSkinTone.none, perLine: widget.emojiPerLine, ), onEmojiSelected: widget.onEmojiSelected, headerBuilder: (context, category) { return FlowyEmojiHeader( category: category, ); }, itemBuilder: (context, emojiId, emoji, callback) { return FlowyIconButton( iconPadding: const EdgeInsets.all(2.0), icon: FlowyText( emoji, fontSize: 28.0, fallbackFontFamily: fallbackFontFamily, ), onPressed: () => callback(emojiId, emoji), ); }, searchBarBuilder: (context, keyword, skinTone) { return FlowyEmojiSearchBar( emojiData: emojiData!, onKeywordChanged: (value) { keyword.value = value; }, onSkinToneChanged: (value) { skinTone.value = value; }, onRandomEmojiSelected: widget.onEmojiSelected, ); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_search_bar.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/base/emoji/emoji_skin_tone.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flutter/material.dart'; import 'package:flutter_emoji_mart/flutter_emoji_mart.dart'; typedef EmojiKeywordChangedCallback = void Function(String keyword); typedef EmojiSkinToneChanged = void Function(EmojiSkinTone skinTone); class FlowyEmojiSearchBar extends StatefulWidget { const FlowyEmojiSearchBar({ super.key, required this.emojiData, required this.onKeywordChanged, required this.onSkinToneChanged, required this.onRandomEmojiSelected, }); final EmojiData emojiData; final EmojiKeywordChangedCallback onKeywordChanged; final EmojiSkinToneChanged onSkinToneChanged; final EmojiSelectedCallback onRandomEmojiSelected; @override State<FlowyEmojiSearchBar> createState() => _FlowyEmojiSearchBarState(); } class _FlowyEmojiSearchBarState extends State<FlowyEmojiSearchBar> { final TextEditingController controller = TextEditingController(); @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric( vertical: 8.0, horizontal: PlatformExtension.isDesktopOrWeb ? 0.0 : 8.0, ), child: Row( children: [ Expanded( child: _SearchTextField( onKeywordChanged: widget.onKeywordChanged, ), ), const HSpace(6.0), _RandomEmojiButton( emojiData: widget.emojiData, onRandomEmojiSelected: widget.onRandomEmojiSelected, ), const HSpace(6.0), FlowyEmojiSkinToneSelector( onEmojiSkinToneChanged: widget.onSkinToneChanged, ), const HSpace(6.0), ], ), ); } } class _RandomEmojiButton extends StatelessWidget { const _RandomEmojiButton({ required this.emojiData, required this.onRandomEmojiSelected, }); final EmojiData emojiData; final EmojiSelectedCallback onRandomEmojiSelected; @override Widget build(BuildContext context) { return FlowyTooltip( message: LocaleKeys.emoji_random.tr(), child: FlowyButton( useIntrinsicWidth: true, text: const Icon( Icons.shuffle_rounded, ), onTap: () { final random = emojiData.random; onRandomEmojiSelected( random.$1, random.$2, ); }, ), ); } } class _SearchTextField extends StatefulWidget { const _SearchTextField({ required this.onKeywordChanged, }); final EmojiKeywordChangedCallback onKeywordChanged; @override State<_SearchTextField> createState() => _SearchTextFieldState(); } class _SearchTextFieldState extends State<_SearchTextField> { final TextEditingController controller = TextEditingController(); final FocusNode focusNode = FocusNode(); @override void dispose() { controller.dispose(); focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ConstrainedBox( constraints: const BoxConstraints( maxHeight: 32.0, ), child: FlowyTextField( focusNode: focusNode, hintText: LocaleKeys.emoji_search.tr(), controller: controller, onChanged: widget.onKeywordChanged, prefixIcon: const Padding( padding: EdgeInsets.only( left: 8.0, right: 4.0, ), child: FlowySvg( FlowySvgs.search_s, ), ), prefixIconConstraints: const BoxConstraints( maxHeight: 18.0, ), suffixIcon: Padding( padding: const EdgeInsets.all(4.0), child: FlowyButton( text: const FlowySvg( FlowySvgs.close_lg, ), margin: EdgeInsets.zero, useIntrinsicWidth: true, onTap: () { if (controller.text.isNotEmpty) { controller.clear(); widget.onKeywordChanged(''); } else { focusNode.unfocus(); } }, ), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/emoji/emoji_skin_tone.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flutter/material.dart'; import 'package:flutter_emoji_mart/flutter_emoji_mart.dart'; // use a temporary global value to store last selected skin tone EmojiSkinTone? lastSelectedEmojiSkinTone; @visibleForTesting ValueKey emojiSkinToneKey(String icon) { return ValueKey('emoji_skin_tone_$icon'); } class FlowyEmojiSkinToneSelector extends StatefulWidget { const FlowyEmojiSkinToneSelector({ super.key, required this.onEmojiSkinToneChanged, }); final EmojiSkinToneChanged onEmojiSkinToneChanged; @override State<FlowyEmojiSkinToneSelector> createState() => _FlowyEmojiSkinToneSelectorState(); } class _FlowyEmojiSkinToneSelectorState extends State<FlowyEmojiSkinToneSelector> { EmojiSkinTone skinTone = EmojiSkinTone.none; final controller = PopoverController(); @override Widget build(BuildContext context) { return AppFlowyPopover( direction: PopoverDirection.bottomWithCenterAligned, controller: controller, popupBuilder: (context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: EmojiSkinTone.values .map( (e) => _buildIconButton( e.icon, () { setState(() => lastSelectedEmojiSkinTone = e); widget.onEmojiSkinToneChanged(e); controller.close(); }, ), ) .toList(), ); }, child: FlowyTooltip( message: LocaleKeys.emoji_selectSkinTone.tr(), child: _buildIconButton( lastSelectedEmojiSkinTone?.icon ?? 'βœ‹', () => controller.show(), ), ), ); } Widget _buildIconButton(String icon, VoidCallback onPressed) { return FlowyIconButton( key: emojiSkinToneKey(icon), icon: Padding( // add a left padding to align the emoji center padding: const EdgeInsets.only( left: 3.0, ), child: FlowyText( icon, fontSize: 22.0, ), ), onPressed: onPressed, ); } } extension EmojiSkinToneIcon on EmojiSkinTone { String get icon { switch (this) { case EmojiSkinTone.none: return 'βœ‹'; case EmojiSkinTone.light: return 'βœ‹πŸ»'; case EmojiSkinTone.mediumLight: return 'βœ‹πŸΌ'; case EmojiSkinTone.medium: return 'βœ‹πŸ½'; case EmojiSkinTone.mediumDark: return 'βœ‹πŸΎ'; case EmojiSkinTone.dark: return 'βœ‹πŸΏ'; } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/color/color_picker.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.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'; class FlowyMobileColorPicker extends StatelessWidget { const FlowyMobileColorPicker({ super.key, required this.onSelectedColor, }); final void Function(FlowyColorOption? option) onSelectedColor; @override Widget build(BuildContext context) { const defaultColor = Colors.transparent; final colors = [ // reset to default background color FlowyColorOption( color: defaultColor, i18n: LocaleKeys.document_plugins_optionAction_defaultColor.tr(), id: optionActionColorDefaultColor, ), ...FlowyTint.values.map( (e) => FlowyColorOption( color: e.color(context), i18n: e.tintName(AppFlowyEditorL10n.current), id: e.id, ), ), ]; return ListView.separated( itemBuilder: (context, index) { final color = colors[index]; return SizedBox( height: 56, child: FlowyButton( useIntrinsicWidth: true, text: FlowyText( color.i18n, ), leftIcon: _ColorIcon( color: color.color, ), leftIconSize: const Size.square(36.0), iconPadding: 12.0, margin: const EdgeInsets.symmetric( horizontal: 12.0, vertical: 16.0, ), onTap: () => onSelectedColor(color), ), ); }, separatorBuilder: (_, __) => const Divider( height: 1, ), itemCount: colors.length, ); } } class _ColorIcon extends StatelessWidget { const _ColorIcon({required this.color}); final Color color; @override Widget build(BuildContext context) { return SizedBox.square( dimension: 24, child: DecoratedBox( decoration: BoxDecoration( color: color, shape: BoxShape.circle, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/base/color/color_picker_screen.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/plugins/base/color/color_picker.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class MobileColorPickerScreen extends StatelessWidget { const MobileColorPickerScreen({super.key, this.title}); final String? title; static const routeName = '/color_picker'; static const pageTitle = 'title'; @override Widget build(BuildContext context) { return Scaffold( appBar: FlowyAppBar( titleText: title ?? LocaleKeys.titleBar_pageIcon.tr(), ), body: SafeArea( child: FlowyMobileColorPicker( onSelectedColor: (option) => context.pop(option), ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/date/date_service.dart
import 'package:appflowy_backend/dispatch/dispatch.dart'; import 'package:appflowy_backend/protobuf/flowy-date/entities.pb.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_result/appflowy_result.dart'; class DateService { static Future<FlowyResult<DateTime, FlowyError>> queryDate( String search, ) async { final query = DateQueryPB.create()..query = search; final result = await DateEventQueryDate(query).send(); return result.fold( (s) { final date = DateTime.tryParse(s.date); if (date != null) { return FlowyResult.success(date); } return FlowyResult.failure( FlowyError(msg: 'Could not parse Date (NLP) from String'), ); }, (e) => FlowyResult.failure(e), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/desktop_runner_1.dart
import 'package:integration_test/integration_test.dart'; import 'desktop/document/document_test_runner.dart' as document_test_runner; import 'desktop/uncategorized/empty_test.dart' as first_test; import 'desktop/uncategorized/switch_folder_test.dart' as switch_folder_test; Future<void> main() async { await runIntegration1OnDesktop(); } Future<void> runIntegration1OnDesktop() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // This test must be run first, otherwise the CI will fail. first_test.main(); switch_folder_test.main(); document_test_runner.startTesting(); // DON'T add more tests here. This is the first test runner for desktop. }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/runner.dart
import 'dart:io'; import 'desktop_runner_1.dart'; import 'desktop_runner_2.dart'; import 'desktop_runner_3.dart'; import 'mobile_runner.dart'; /// The main task runner for all integration tests in AppFlowy. /// /// Having a single entrypoint for integration tests is necessary due to an /// [issue caused by switching files with integration testing](https://github.com/flutter/flutter/issues/101031). /// If flutter/flutter#101031 is resolved, this file can be removed completely. /// Once removed, the integration_test.yaml must be updated to exclude this as /// as the test target. Future<void> main() async { if (Platform.isLinux || Platform.isMacOS || Platform.isWindows) { await runIntegration1OnDesktop(); await runIntegration2OnDesktop(); await runIntegration3OnDesktop(); } else if (Platform.isIOS || Platform.isAndroid) { await runIntegrationOnMobile(); } else { throw Exception('Unsupported platform'); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/desktop_runner_2.dart
import 'package:integration_test/integration_test.dart'; import 'desktop/database/database_calendar_test.dart' as database_calendar_test; import 'desktop/database/database_cell_test.dart' as database_cell_test; import 'desktop/database/database_field_settings_test.dart' as database_field_settings_test; import 'desktop/database/database_field_test.dart' as database_field_test; import 'desktop/database/database_filter_test.dart' as database_filter_test; import 'desktop/database/database_row_page_test.dart' as database_row_page_test; import 'desktop/database/database_row_test.dart' as database_row_test; import 'desktop/database/database_setting_test.dart' as database_setting_test; import 'desktop/database/database_share_test.dart' as database_share_test; import 'desktop/database/database_sort_test.dart' as database_sort_test; import 'desktop/database/database_view_test.dart' as database_view_test; import 'desktop/uncategorized/empty_test.dart' as first_test; Future<void> main() async { await runIntegration2OnDesktop(); } Future<void> runIntegration2OnDesktop() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // This test must be run first, otherwise the CI will fail. first_test.main(); database_cell_test.main(); database_field_test.main(); database_field_settings_test.main(); database_share_test.main(); database_row_page_test.main(); database_row_test.main(); database_setting_test.main(); database_filter_test.main(); database_sort_test.main(); database_view_test.main(); database_calendar_test.main(); // DON'T add more tests here. This is the second test runner for desktop. }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/desktop_runner_3.dart
import 'package:integration_test/integration_test.dart'; import 'desktop/board/board_test_runner.dart' as board_test_runner; import 'desktop/settings/settings_runner.dart' as settings_test_runner; import 'desktop/sidebar/sidebar_test_runner.dart' as sidebar_test_runner; import 'desktop/uncategorized/appearance_settings_test.dart' as appearance_test_runner; import 'desktop/uncategorized/emoji_shortcut_test.dart' as emoji_shortcut_test; import 'desktop/uncategorized/empty_test.dart' as first_test; import 'desktop/uncategorized/hotkeys_test.dart' as hotkeys_test; import 'desktop/uncategorized/import_files_test.dart' as import_files_test; import 'desktop/uncategorized/share_markdown_test.dart' as share_markdown_test; import 'desktop/uncategorized/tabs_test.dart' as tabs_test; Future<void> main() async { await runIntegration3OnDesktop(); } Future<void> runIntegration3OnDesktop() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // This test must be run first, otherwise the CI will fail. first_test.main(); hotkeys_test.main(); emoji_shortcut_test.main(); hotkeys_test.main(); emoji_shortcut_test.main(); appearance_test_runner.main(); settings_test_runner.main(); share_markdown_test.main(); import_files_test.main(); sidebar_test_runner.startTesting(); board_test_runner.startTesting(); tabs_test.main(); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/mobile_runner.dart
import 'package:integration_test/integration_test.dart'; import 'mobile/sign_in/anonymous_sign_in_test.dart' as anonymous_sign_in_test; Future<void> runIntegrationOnMobile() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); anonymous_sign_in_test.main(); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/util.dart
export 'base.dart'; export 'common_operations.dart'; export 'settings.dart'; export 'data.dart'; export 'expectation.dart'; export 'editor_test_operations.dart'; export 'mock/mock_url_launcher.dart'; export 'ime.dart'; export 'auth_operation.dart';
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart
import 'dart:io'; import 'package:appflowy/plugins/database/widgets/field/field_editor.dart'; import 'package:appflowy/plugins/database/widgets/field/field_type_list.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/database/application/calculations/calculation_type_ext.dart'; import 'package:appflowy/plugins/database/board/presentation/board_page.dart'; import 'package:appflowy/plugins/database/board/presentation/widgets/board_column_header.dart'; import 'package:appflowy/plugins/database/calendar/application/calendar_bloc.dart'; import 'package:appflowy/plugins/database/calendar/presentation/calendar_day.dart'; import 'package:appflowy/plugins/database/calendar/presentation/calendar_event_card.dart'; import 'package:appflowy/plugins/database/calendar/presentation/calendar_event_editor.dart'; import 'package:appflowy/plugins/database/calendar/presentation/calendar_page.dart'; import 'package:appflowy/plugins/database/calendar/presentation/toolbar/calendar_layout_setting.dart'; import 'package:appflowy/plugins/database/grid/presentation/grid_page.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/calculations/calculate_cell.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/calculations/calculation_type_item.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/common/type_option_separator.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/checkbox.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/checklist/checklist.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/select_option/option_list.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/select_option/select_option.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/text.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/create_filter_list.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/disclosure_button.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_menu_item.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/footer/grid_footer.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/header/desktop_field_cell.dart'; import 'package:appflowy/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart'; import 'package:appflowy/plugins/database/widgets/field/type_option_editor/number.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/row/row.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/create_sort_list.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/order_panel.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_editor.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_menu.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/toolbar/filter_button.dart'; import 'package:appflowy/plugins/database/grid/presentation/widgets/toolbar/sort_button.dart'; import 'package:appflowy/plugins/database/tab_bar/desktop/tab_bar_add_button.dart'; import 'package:appflowy/plugins/database/tab_bar/desktop/tab_bar_header.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/checkbox.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/checklist.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/date.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/number.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/select_option.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/text.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/timestamp.dart'; import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/url.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_cell_editor.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_progress_bar.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/date_editor.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/extension.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/select_option_cell_editor.dart'; import 'package:appflowy/plugins/database/widgets/cell_editor/select_option_text_field.dart'; import 'package:appflowy/plugins/database/widgets/database_layout_ext.dart'; import 'package:appflowy/plugins/database/widgets/row/accessory/cell_accessory.dart'; import 'package:appflowy/plugins/database/widgets/row/row_action.dart'; import 'package:appflowy/plugins/database/widgets/row/row_banner.dart'; import 'package:appflowy/plugins/database/widgets/row/row_detail.dart'; import 'package:appflowy/plugins/database/widgets/row/row_document.dart'; import 'package:appflowy/plugins/database/widgets/row/row_property.dart'; import 'package:appflowy/plugins/database/widgets/setting/database_layout_selector.dart'; import 'package:appflowy/plugins/database/widgets/setting/database_setting_action.dart'; import 'package:appflowy/plugins/database/widgets/setting/database_settings_list.dart'; import 'package:appflowy/plugins/database/widgets/setting/setting_button.dart'; import 'package:appflowy/plugins/database/widgets/setting/setting_property_list.dart'; import 'package:appflowy/util/field_type_extension.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/clear_date_button.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_type_option_button.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/end_time_button.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart'; import 'package:appflowy/workspace/presentation/widgets/dialogs.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:appflowy/workspace/presentation/widgets/toggle/toggle.dart'; import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_board/appflowy_board.dart'; import 'package:calendar_view/calendar_view.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/style_widget/text_input.dart'; import 'package:flowy_infra_ui/widget/buttons/primary_button.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; // Non-exported member of the table_calendar library import 'package:table_calendar/src/widgets/cell_content.dart'; import 'package:table_calendar/table_calendar.dart'; import 'base.dart'; import 'common_operations.dart'; import 'expectation.dart'; import 'mock/mock_file_picker.dart'; extension AppFlowyDatabaseTest on WidgetTester { Future<void> openV020database() async { final context = await initializeAppFlowy(); await tapAnonymousSignInButton(); // expect to see a readme page expectToSeePageName(gettingStarted); await tapAddViewButton(); await tapImportButton(); final testFileNames = ['v020.afdb']; final paths = <String>[]; for (final fileName in testFileNames) { // Don't use the p.join to build the path that used in loadString. It // is not working on windows. final str = await rootBundle .loadString("assets/test/workspaces/database/$fileName"); // Write the content to the file. final path = p.join( context.applicationDataDirectory, fileName, ); paths.add(path); File(path).writeAsStringSync(str); } // mock get files mockPickFilePaths( paths: paths, ); await tapDatabaseRawDataButton(); await pumpAndSettle(); await openPage('v020', layout: ViewLayoutPB.Grid); } Future<void> hoverOnFirstRowOfGrid() async { final findRow = find.byType(GridRow); expect(findRow, findsWidgets); final firstRow = findRow.first; await hoverOnWidget(firstRow); } Future<void> editCell({ required int rowIndex, required FieldType fieldType, required String input, int cellIndex = 0, }) async { final cell = cellFinder(rowIndex, fieldType, cellIndex: cellIndex); expect(cell, findsOneWidget); await enterText(cell, input); await pumpAndSettle(); } Finder cellFinder(int rowIndex, FieldType fieldType, {int cellIndex = 0}) { final findRow = find.byType(GridRow, skipOffstage: false); final findCell = finderForFieldType(fieldType); return find .descendant( of: findRow.at(rowIndex), matching: findCell, skipOffstage: false, ) .at(cellIndex); } Future<void> tapCheckboxCellInGrid({ required int rowIndex, }) async { final cell = cellFinder(rowIndex, FieldType.Checkbox); final button = find.descendant( of: cell, matching: find.byType(FlowyIconButton), ); expect(cell, findsOneWidget); await tapButton(button); } Future<void> assertCheckboxCell({ required int rowIndex, required bool isSelected, }) async { final cell = cellFinder(rowIndex, FieldType.Checkbox); final finder = isSelected ? find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.check_filled_s, ) : find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.uncheck_s, ); expect( find.descendant( of: cell, matching: finder, ), findsOneWidget, ); } Future<void> tapCellInGrid({ required int rowIndex, required FieldType fieldType, }) async { final cell = cellFinder(rowIndex, fieldType); expect(cell, findsOneWidget); await tapButton(cell); } /// The [fieldName] must be unique in the grid. void assertCellContent({ required int rowIndex, required FieldType fieldType, required String content, int cellIndex = 0, }) { final findCell = cellFinder(rowIndex, fieldType, cellIndex: cellIndex); final findContent = find.descendant( of: findCell, matching: find.text(content), skipOffstage: false, ); expect(findContent, findsOneWidget); } Future<void> assertSingleSelectOption({ required int rowIndex, required String content, }) async { final findCell = cellFinder(rowIndex, FieldType.SingleSelect); if (content.isNotEmpty) { final finder = find.descendant( of: findCell, matching: find.byWidgetPredicate( (widget) => widget is SelectOptionTag && (widget.name == content || widget.option?.name == content), ), ); expect(finder, findsOneWidget); } } Future<void> assertMultiSelectOption({ required int rowIndex, required List<String> contents, }) async { final findCell = cellFinder(rowIndex, FieldType.MultiSelect); for (final content in contents) { if (content.isNotEmpty) { final finder = find.descendant( of: findCell, matching: find.byWidgetPredicate( (widget) => widget is SelectOptionTag && (widget.name == content || widget.option?.name == content), ), ); expect(finder, findsOneWidget); } } } /// null percent means no progress bar should be found void assertChecklistCellInGrid({ required int rowIndex, required double? percent, }) { final findCell = cellFinder(rowIndex, FieldType.Checklist); if (percent == null) { final finder = find.descendant( of: findCell, matching: find.byType(ChecklistProgressBar), ); expect(finder, findsNothing); } else { final finder = find.descendant( of: findCell, matching: find.byWidgetPredicate( (widget) => widget is ChecklistProgressBar && widget.percent == percent, ), ); expect(finder, findsOneWidget); } } Future<void> selectDay({ required int content, }) async { final findCalendar = find.byType(TableCalendar); final findDay = find.text(content.toString()); final finder = find.descendant( of: findCalendar, matching: findDay, ); // if the day is very near the beginning or the end of the month, // it may overlap with the same day in the next or previous month, // respectively because it was spilling over. This will lead to 2 // widgets being found and thus cannot be tapped correctly. if (content < 15) { // e.g., Jan 2 instead of Feb 2 await tapButton(finder.first); } else { // e.g. Jun 28 instead of May 28 await tapButton(finder.last); } } Future<void> toggleIncludeTime() async { final findDateEditor = find.byType(IncludeTimeButton); final findToggle = find.byType(Toggle); final finder = find.descendant( of: findDateEditor, matching: findToggle, ); await tapButton(finder); } Future<void> selectReminderOption(ReminderOption option) async { await tapButton(find.byType(ReminderSelector)); final finder = find.descendant( of: find.byType(FlowyButton), matching: find.textContaining(option.label), ); await tapButton(finder); } Future<bool> selectLastDateInPicker() async { final finder = find.byType(CellContent).last; final w = widget(finder) as CellContent; await tapButton(finder); return w.isToday; } Future<void> toggleDateRange() async { final findDateEditor = find.byType(EndTimeButton); final findToggle = find.byType(Toggle); final finder = find.descendant( of: findDateEditor, matching: findToggle, ); await tapButton(finder); } Future<void> tapChangeDateTimeFormatButton() async { await tapButton(find.byType(DateTypeOptionButton)); } Future<void> changeDateFormat() async { final findDateFormatButton = find.byType(DateFormatButton); await tapButton(findDateFormatButton); final findNewDateFormat = find.text("Day/Month/Year"); await tapButton(findNewDateFormat); } Future<void> changeTimeFormat() async { final findDateFormatButton = find.byType(TimeFormatButton); await tapButton(findDateFormatButton); final findNewDateFormat = find.text("12 hour"); await tapButton(findNewDateFormat); } Future<void> clearDate() async { final findDateEditor = find.byType(DateCellEditor); final findClearButton = find.byType(ClearDateButton); final finder = find.descendant( of: findDateEditor, matching: findClearButton, ); await tapButton(finder); } Future<void> tapSelectOptionCellInGrid({ required int rowIndex, required FieldType fieldType, }) async { assert( fieldType == FieldType.SingleSelect || fieldType == FieldType.MultiSelect, ); final findRow = find.byType(GridRow); final findCell = finderForFieldType(fieldType); final cell = find.descendant( of: findRow.at(rowIndex), matching: findCell, ); await tapButton(cell); } /// The [SelectOptionCellEditor] must be opened first. Future<void> createOption({ required String name, }) async { final findEditor = find.byType(SelectOptionCellEditor); expect(findEditor, findsOneWidget); final findTextField = find.byType(SelectOptionTextField); expect(findTextField, findsOneWidget); await enterText(findTextField, name); await pump(); await testTextInput.receiveAction(TextInputAction.done); await pumpAndSettle(); } Future<void> selectOption({ required String name, }) async { final option = find.byWidgetPredicate( (widget) => widget is SelectOptionTagCell && widget.option.name == name, ); await tapButton(option); } Future<void> findSelectOptionWithNameInGrid({ required int rowIndex, required String name, }) async { final findRow = find.byType(GridRow); final option = find.byWidgetPredicate( (widget) => widget is SelectOptionTag && (widget.name == name || widget.option?.name == name), ); final cell = find.descendant( of: findRow.at(rowIndex), matching: option, ); expect(cell, findsOneWidget); } Future<void> assertNumberOfSelectedOptionsInGrid({ required int rowIndex, required Matcher matcher, }) async { final findRow = find.byType(GridRow); final options = find.byWidgetPredicate( (widget) => widget is SelectOptionTag, ); final cell = find.descendant( of: findRow.at(rowIndex), matching: options, ); expect(cell, matcher); } Future<void> tapChecklistCellInGrid({required int rowIndex}) async { final findRow = find.byType(GridRow); final findCell = finderForFieldType(FieldType.Checklist); final cell = find.descendant( of: findRow.at(rowIndex), matching: findCell, ); await tapButton(cell); } void assertChecklistEditorVisible({required bool visible}) { final editor = find.byType(ChecklistCellEditor); if (visible) { expect(editor, findsOneWidget); } else { expect(editor, findsNothing); } } Future<void> createNewChecklistTask({ required String name, enter = false, button = false, }) async { assert(!(enter && button)); final textField = find.descendant( of: find.byType(NewTaskItem), matching: find.byType(TextField), ); await enterText(textField, name); await pumpAndSettle(); if (enter) { await testTextInput.receiveAction(TextInputAction.done); await pumpAndSettle(); } else { await tapButton( find.descendant( of: find.byType(NewTaskItem), matching: find.byType(FlowyTextButton), ), ); } } void assertChecklistTaskInEditor({ required int index, required String name, required bool isChecked, }) { final task = find.byType(ChecklistItem).at(index); final widget = this.widget<ChecklistItem>(task); assert( widget.task.data.name == name && widget.task.isSelected == isChecked, ); } Future<void> renameChecklistTask({ required int index, required String name, }) async { final textField = find .descendant( of: find.byType(ChecklistItem), matching: find.byType(TextField), ) .at(index); await enterText(textField, name); await testTextInput.receiveAction(TextInputAction.done); await pumpAndSettle(); } Future<void> checkChecklistTask({required int index}) async { final button = find.descendant( of: find.byType(ChecklistItem).at(index), matching: find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.uncheck_s, ), ); await tapButton(button); } Future<void> deleteChecklistTask({required int index}) async { final task = find.byType(ChecklistItem).at(index); await startGesture(getCenter(task), kind: PointerDeviceKind.mouse); await pumpAndSettle(); final button = find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.delete_s, ); await tapButton(button); } Future<void> openFirstRowDetailPage() async { await hoverOnFirstRowOfGrid(); final expandButton = find.byType(PrimaryCellAccessory); expect(expandButton, findsOneWidget); await tapButton(expandButton); } void assertRowDetailPageOpened() async { final findRowDetailPage = find.byType(RowDetailPage); expect(findRowDetailPage, findsOneWidget); } Future<void> dismissRowDetailPage() async { // use tap empty area instead of clicking ESC to dismiss the row detail page // sometimes, the ESC key is not working. await simulateKeyEvent(LogicalKeyboardKey.escape); await pumpAndSettle(); final findRowDetailPage = find.byType(RowDetailPage); if (findRowDetailPage.evaluate().isNotEmpty) { await tapAt(const Offset(0, 0)); await pumpAndSettle(); } } Future<void> editTitleInRowDetailPage(String title) async { final titleField = find.byType(EditableTextCell); await enterText(titleField, title); await pumpAndSettle(); } Future<void> hoverRowBanner() async { final banner = find.byType(RowBanner); expect(banner, findsOneWidget); await startGesture( getCenter(banner), kind: PointerDeviceKind.mouse, ); await pumpAndSettle(); } Future<void> openEmojiPicker() async { await tapButton(find.byType(AddEmojiButton)); } Future<void> tapDateCellInRowDetailPage() async { final findDateCell = find.byType(EditableDateCell); await tapButton(findDateCell); } Future<void> tapGridFieldWithNameInRowDetailPage(String name) async { final fields = find.byWidgetPredicate( (widget) => widget is FieldCellButton && widget.field.name == name, ); final field = find.descendant( of: find.byType(RowDetailPage), matching: fields, ); await tapButton(field); await pumpAndSettle(); } Future<void> duplicateRowInRowDetailPage() async { final duplicateButton = find.byType(RowDetailPageDuplicateButton); await tapButton(duplicateButton); } Future<void> deleteRowInRowDetailPage() async { final deleteButton = find.byType(RowDetailPageDeleteButton); await tapButton(deleteButton); } Future<TestGesture> hoverOnFieldInRowDetail({required int index}) async { final fieldButtons = find.byType(FieldCellButton); final button = find .descendant(of: find.byType(RowDetailPage), matching: fieldButtons) .at(index); return startGesture( getCenter(button), kind: PointerDeviceKind.mouse, ); } Future<void> reorderFieldInRowDetail({required double offset}) async { final thumb = find .byWidgetPredicate( (widget) => widget is ReorderableDragStartListener && widget.enabled, ) .first; await drag( thumb, Offset(0, offset), kind: PointerDeviceKind.mouse, ); await pumpAndSettle(); } void assertToggleShowHiddenFieldsVisibility(bool shown) { final button = find.byType(ToggleHiddenFieldsVisibilityButton); if (shown) { expect(button, findsOneWidget); } else { expect(button, findsNothing); } } Future<void> toggleShowHiddenFields() async { final button = find.byType(ToggleHiddenFieldsVisibilityButton); await tapButton(button); } Future<void> tapDeletePropertyInFieldEditor() async { final deleteButton = find.byWidgetPredicate( (widget) => widget is FieldActionCell && widget.action == FieldAction.delete, ); await tapButton(deleteButton); final confirmButton = find.descendant( of: find.byType(NavigatorAlertDialog), matching: find.byType(PrimaryTextButton), ); await tapButton(confirmButton); } Future<void> scrollGridByOffset(Offset offset) async { await drag(find.byType(GridPage), offset); await pumpAndSettle(); } Future<void> scrollRowDetailByOffset(Offset offset) async { await drag(find.byType(RowDetailPage), offset); await pumpAndSettle(); } Future<void> scrollToRight(Finder find) async { final size = getSize(find); await drag(find, Offset(-size.width, 0), warnIfMissed: false); await pumpAndSettle(const Duration(milliseconds: 500)); } Future<void> tapNewPropertyButton() async { await tapButtonWithName(LocaleKeys.grid_field_newProperty.tr()); await pumpAndSettle(); } Future<void> tapGridFieldWithName(String name) async { final field = find.byWidgetPredicate( (widget) => widget is FieldCellButton && widget.field.name == name, ); await tapButton(field); await pumpAndSettle(); } Future<void> changeFieldTypeOfFieldWithName( String name, FieldType type, ) async { await tapGridFieldWithName(name); await tapEditFieldButton(); await tapSwitchFieldTypeButton(); await selectFieldType(type); await dismissFieldEditor(); } Future<void> changeCalculateAtIndex(int index, CalculationType type) async { await tap(find.byType(CalculateCell).at(index)); await pumpAndSettle(); await tap( find.descendant( of: find.byType(CalculationTypeItem), matching: find.text(type.label), ), ); await pumpAndSettle(); } /// Should call [tapGridFieldWithName] first. Future<void> tapEditFieldButton() async { await tapButtonWithName(LocaleKeys.grid_field_editProperty.tr()); await pumpAndSettle(const Duration(milliseconds: 200)); } /// Should call [tapGridFieldWithName] first. Future<void> tapDeletePropertyButton() async { final field = find.byWidgetPredicate( (widget) => widget is FieldActionCell && widget.action == FieldAction.delete, ); await tapButton(field); } /// A SimpleDialog must be shown first, e.g. when deleting a field. Future<void> tapDialogOkButton() async { final field = find.byWidgetPredicate( (widget) => widget is PrimaryTextButton && widget.label == LocaleKeys.button_ok.tr(), ); await tapButton(field); } /// Should call [tapGridFieldWithName] first. Future<void> tapDuplicatePropertyButton() async { final field = find.byWidgetPredicate( (widget) => widget is FieldActionCell && widget.action == FieldAction.duplicate, ); await tapButton(field); } Future<void> tapInsertFieldButton({ required bool left, required String name, }) async { final field = find.byWidgetPredicate( (widget) => widget is FieldActionCell && (left && widget.action == FieldAction.insertLeft || !left && widget.action == FieldAction.insertRight), ); await tapButton(field); await renameField(name); } /// Should call [tapGridFieldWithName] first. Future<void> tapHidePropertyButton() async { final field = find.byWidgetPredicate( (widget) => widget is FieldActionCell && widget.action == FieldAction.toggleVisibility, ); await tapButton(field); } Future<void> tapHidePropertyButtonInFieldEditor() async { final button = find.byWidgetPredicate( (widget) => widget is FieldActionCell && widget.action == FieldAction.toggleVisibility, ); await tapButton(button); } Future<void> tapRowDetailPageRowActionButton() async { await tapButton(find.byType(RowActionButton)); } Future<void> tapRowDetailPageCreatePropertyButton() async { await tapButton(find.byType(CreateRowFieldButton)); } Future<void> tapRowDetailPageDeleteRowButton() async { await tapButton(find.byType(RowDetailPageDeleteButton)); } Future<void> tapRowDetailPageDuplicateRowButton() async { await tapButton(find.byType(RowDetailPageDuplicateButton)); } Future<void> tapSwitchFieldTypeButton() async { await tapButton(find.byType(SwitchFieldButton)); } Future<void> tapEscButton() async { await sendKeyEvent(LogicalKeyboardKey.escape); } /// Must call [tapSwitchFieldTypeButton] first. Future<void> selectFieldType(FieldType fieldType) async { final fieldTypeCell = find.byType(FieldTypeCell); final fieldTypeButton = find.descendant( of: fieldTypeCell, matching: find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == fieldType.i18n, ), ); await tapButton(fieldTypeButton); } // Use in edit mode of FieldEditor void expectEmptyTypeOptionEditor() { expect( find.descendant( of: find.byType(FieldTypeOptionEditor), matching: find.byType(TypeOptionSeparator), ), findsNothing, ); } /// Each field has its own cell, so we can find the corresponding cell by /// the field type after create a new field. Future<void> findCellByFieldType(FieldType fieldType) async { final finder = finderForFieldType(fieldType); expect(finder, findsWidgets); } Future<void> assertNumberOfFieldsInGridPage(int num) async { expect(find.byType(GridFieldCell), findsNWidgets(num)); } Future<void> assertNumberOfRowsInGridPage(int num) async { expect( find.byType(GridRow, skipOffstage: false), findsNWidgets(num), ); } Future<void> assertDocumentExistInRowDetailPage() async { expect(find.byType(RowDocument), findsOneWidget); } /// Check the field type of the [FieldCellButton] is the same as the name. Future<void> assertFieldTypeWithFieldName( String name, FieldType fieldType, ) async { final field = find.byWidgetPredicate( (widget) => widget is FieldCellButton && widget.field.fieldType == fieldType && widget.field.name == name, ); expect(field, findsOneWidget); } void assertFirstFieldInRowDetailByType(FieldType fieldType) { final firstField = find .descendant( of: find.byType(RowDetailPage), matching: find.byType(FieldCellButton), ) .first; final widget = this.widget<FieldCellButton>(firstField); expect(widget.field.fieldType, fieldType); } void findFieldWithName(String name) { final field = find.byWidgetPredicate( (widget) => widget is FieldCellButton && widget.field.name == name, ); expect(field, findsOneWidget); } void noFieldWithName(String name) { final field = find.byWidgetPredicate( (widget) => widget is FieldCellButton && widget.field.name == name, ); expect(field, findsNothing); } Future<void> renameField(String newName) async { final textField = find.byType(FieldNameTextField); expect(textField, findsOneWidget); await enterText(textField, newName); await pumpAndSettle(); } Future<void> dismissFieldEditor() async { await sendKeyEvent(LogicalKeyboardKey.escape); await pumpAndSettle(const Duration(milliseconds: 200)); } Future<void> findFieldEditor(dynamic matcher) async { final finder = find.byType(FieldEditor); expect(finder, matcher); } Future<void> findDateEditor(dynamic matcher) async { final finder = find.byType(DateCellEditor); expect(finder, matcher); } Future<void> findSelectOptionEditor(dynamic matcher) async { final finder = find.byType(SelectOptionCellEditor); expect(finder, matcher); } Future<void> dismissCellEditor() async { await sendKeyEvent(LogicalKeyboardKey.escape); await pumpAndSettle(); } Future<void> tapCreateRowButtonInGrid() async { await tapButton(find.byType(GridAddRowButton)); } Future<void> tapCreateRowButtonInRowMenuOfGrid() async { await tapButton(find.byType(InsertRowButton)); } Future<void> tapRowMenuButtonInGrid() async { await tapButton(find.byType(RowMenuButton)); } /// Should call [tapRowMenuButtonInGrid] first. Future<void> tapDeleteOnRowMenu() async { await tapButtonWithName(LocaleKeys.grid_row_delete.tr()); } Future<void> createField(FieldType fieldType, String name) async { await scrollToRight(find.byType(GridPage)); await tapNewPropertyButton(); await renameField(name); await tapSwitchFieldTypeButton(); await selectFieldType(fieldType); await dismissFieldEditor(); } Future<void> tapDatabaseSettingButton() async { await tapButton(find.byType(SettingButton)); } Future<void> tapDatabaseFilterButton() async { await tapButton(find.byType(FilterButton)); } Future<void> tapDatabaseSortButton() async { await tapButton(find.byType(SortButton)); } Future<void> tapCreateFilterByFieldType( FieldType fieldType, String title, ) async { final findFilter = find.byWidgetPredicate( (widget) => widget is GridFilterPropertyCell && widget.fieldInfo.fieldType == fieldType && widget.fieldInfo.name == title, ); await tapButton(findFilter); } Future<void> tapFilterButtonInGrid(String filterName) async { final findFilter = find.byType(FilterMenuItem); final button = find.descendant( of: findFilter, matching: find.text(filterName), ); await tapButton(button); } Future<void> tapCreateSortByFieldType( FieldType fieldType, String title, ) async { final findSort = find.byWidgetPredicate( (widget) => widget is GridSortPropertyCell && widget.fieldInfo.fieldType == fieldType && widget.fieldInfo.name == title, ); await tapButton(findSort); } // Must call [tapSortMenuInSettingBar] first. Future<void> tapCreateSortByFieldTypeInSortMenu( FieldType fieldType, String title, ) async { await tapButton(find.byType(DatabaseAddSortButton)); final findSort = find.byWidgetPredicate( (widget) => widget is GridSortPropertyCell && widget.fieldInfo.fieldType == fieldType && widget.fieldInfo.name == title, ); await tapButton(findSort); await pumpAndSettle(); } Future<void> tapSortMenuInSettingBar() async { await tapButton(find.byType(SortMenu)); await pumpAndSettle(); } /// Must call [tapSortMenuInSettingBar] first. Future<void> tapSortButtonByName(String name) async { final findSortItem = find.byWidgetPredicate( (widget) => widget is DatabaseSortItem && widget.sortInfo.fieldInfo.name == name, ); await tapButton(findSortItem); } /// Must call [tapSortMenuInSettingBar] first. Future<void> reorderSort( (FieldType, String) from, (FieldType, String) to, ) async { final fromSortItem = find.byWidgetPredicate( (widget) => widget is DatabaseSortItem && widget.sortInfo.fieldInfo.fieldType == from.$1 && widget.sortInfo.fieldInfo.name == from.$2, ); final toSortItem = find.byWidgetPredicate( (widget) => widget is DatabaseSortItem && widget.sortInfo.fieldInfo.fieldType == to.$1 && widget.sortInfo.fieldInfo.name == to.$2, ); final dragElement = find.descendant( of: fromSortItem, matching: find.byType(ReorderableDragStartListener), ); await drag( dragElement, getCenter(toSortItem) - getCenter(fromSortItem), ); await pumpAndSettle(const Duration(milliseconds: 200)); } /// Must call [tapSortButtonByName] first. Future<void> tapSortByDescending() async { await tapButton( find.descendant( of: find.byType(OrderPannelItem), matching: find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == LocaleKeys.grid_sort_descending.tr(), ), ), ); await sendKeyEvent(LogicalKeyboardKey.escape); await pumpAndSettle(); } /// Must call [tapSortMenuInSettingBar] first. Future<void> tapAllSortButton() async { await tapButton(find.byType(DeleteAllSortsButton)); } Future<void> scrollOptionFilterListByOffset(Offset offset) async { await drag(find.byType(SelectOptionFilterEditor), offset); await pumpAndSettle(); } Future<void> enterTextInTextFilter(String text) async { final findEditor = find.byType(TextFilterEditor); final findTextField = find.descendant( of: findEditor, matching: find.byType(FlowyTextField), ); await enterText(findTextField, text); await pumpAndSettle(const Duration(milliseconds: 300)); } Future<void> tapDisclosureButtonInFinder(Finder finder) async { final findDisclosure = find.descendant( of: finder, matching: find.byType(DisclosureButton), ); await tapButton(findDisclosure); } /// must call [tapDisclosureButtonInFinder] first. Future<void> tapDeleteFilterButtonInGrid() async { await tapButton(find.text(LocaleKeys.grid_settings_deleteFilter.tr())); } Future<void> tapCheckboxFilterButtonInGrid() async { await tapButton(find.byType(CheckboxFilterConditionList)); } Future<void> tapChecklistFilterButtonInGrid() async { await tapButton(find.byType(ChecklistFilterConditionList)); } /// The [SelectOptionFilterList] must show up first. Future<void> tapOptionFilterWithName(String name) async { final findCell = find.descendant( of: find.byType(SelectOptionFilterList), matching: find.byWidgetPredicate( (widget) => widget is SelectOptionFilterCell && widget.option.name == name, skipOffstage: false, ), skipOffstage: false, ); expect(findCell, findsOneWidget); await tapButton(findCell); } Future<void> tapCheckedButtonOnCheckboxFilter() async { final button = find.descendant( of: find.byType(HoverButton), matching: find.text(LocaleKeys.grid_checkboxFilter_isChecked.tr()), ); await tapButton(button); } Future<void> tapUnCheckedButtonOnCheckboxFilter() async { final button = find.descendant( of: find.byType(HoverButton), matching: find.text(LocaleKeys.grid_checkboxFilter_isUnchecked.tr()), ); await tapButton(button); } Future<void> tapCompletedButtonOnChecklistFilter() async { final button = find.descendant( of: find.byType(HoverButton), matching: find.text(LocaleKeys.grid_checklistFilter_isComplete.tr()), ); await tapButton(button); } Future<void> tapUnCompletedButtonOnChecklistFilter() async { final button = find.descendant( of: find.byType(HoverButton), matching: find.text(LocaleKeys.grid_checklistFilter_isIncomplted.tr()), ); await tapButton(button); } /// Should call [tapDatabaseSettingButton] first. Future<void> tapViewPropertiesButton() async { final findSettingItem = find.byType(DatabaseSettingsList); final findLayoutButton = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == DatabaseSettingAction.showProperties.title(), ); final button = find.descendant( of: findSettingItem, matching: findLayoutButton, ); await tapButton(button); } /// Should call [tapDatabaseSettingButton] first. Future<void> tapDatabaseLayoutButton() async { final findSettingItem = find.byType(DatabaseSettingsList); final findLayoutButton = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == DatabaseSettingAction.showLayout.title(), ); final button = find.descendant( of: findSettingItem, matching: findLayoutButton, ); await tapButton(button); } Future<void> tapCalendarLayoutSettingButton() async { final findSettingItem = find.byType(DatabaseSettingsList); final findLayoutButton = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == DatabaseSettingAction.showCalendarLayout.title(), ); final button = find.descendant( of: findSettingItem, matching: findLayoutButton, ); await tapButton(button); } Future<void> tapFirstDayOfWeek() async { await tapButton(find.byType(FirstDayOfWeek)); } Future<void> tapFirstDayOfWeekStartFromSunday() async { final finder = find.byWidgetPredicate( (widget) => widget is StartFromButton && widget.dayIndex == 0, ); await tapButton(finder); } Future<void> tapFirstDayOfWeekStartFromMonday() async { final finder = find.byWidgetPredicate( (widget) => widget is StartFromButton && widget.dayIndex == 1, ); await tapButton(finder); // Dismiss the popover overlay in cause of obscure the tapButton // in the next test case. await sendKeyEvent(LogicalKeyboardKey.escape); await pumpAndSettle(const Duration(milliseconds: 200)); } void assertFirstDayOfWeekStartFromMonday() { final finder = find.byWidgetPredicate( (widget) => widget is StartFromButton && widget.dayIndex == 1 && widget.isSelected == true, ); expect(finder, findsOneWidget); } void assertFirstDayOfWeekStartFromSunday() { final finder = find.byWidgetPredicate( (widget) => widget is StartFromButton && widget.dayIndex == 0 && widget.isSelected == true, ); expect(finder, findsOneWidget); } Future<void> scrollToToday() async { final todayCell = find.byWidgetPredicate( (widget) => widget is CalendarDayCard && widget.isToday, ); final scrollable = find .descendant( of: find.byType(MonthView<CalendarDayEvent>), matching: find.byWidgetPredicate( (widget) => widget is Scrollable && widget.axis == Axis.vertical, ), ) .first; await scrollUntilVisible( todayCell, 300, scrollable: scrollable, ); await pumpAndSettle(const Duration(milliseconds: 300)); } Future<void> hoverOnTodayCalendarCell({ Future<void> Function()? onHover, }) async { final todayCell = find.byWidgetPredicate( (widget) => widget is CalendarDayCard && widget.isToday, ); await hoverOnWidget(todayCell, onHover: onHover); } Future<void> tapAddCalendarEventButton() async { final findFlowyButton = find.byType(FlowyIconButton); final findNewEventButton = find.byType(NewEventButton); final button = find.descendant( of: findNewEventButton, matching: findFlowyButton, ); await tapButton(button); } /// Checks for a certain number of events. Parameters [date] and [title] can /// also be provided to restrict the scope of the search void assertNumberOfEventsInCalendar(int number, {String? title}) { Finder findEvents = find.byType(EventCard); if (title != null) { findEvents = find.descendant(of: findEvents, matching: find.text(title)); } expect(findEvents, findsNWidgets(number)); } void assertNumberOfEventsOnSpecificDay( int number, DateTime date, { String? title, }) { final findDayCell = find.byWidgetPredicate( (widget) => widget is CalendarDayCard && isSameDay( widget.date, date, ), ); Finder findEvents = find.descendant( of: findDayCell, matching: find.byType(EventCard), ); if (title != null) { findEvents = find.descendant(of: findEvents, matching: find.text(title)); } expect(findEvents, findsNWidgets(number)); } Future<void> doubleClickCalendarCell(DateTime date) async { final todayCell = find.byWidgetPredicate( (widget) => widget is CalendarDayCard && isSameDay(date, widget.date), ); final location = getTopLeft(todayCell).translate(10, 10); await doubleTapAt(location); } Future<void> openCalendarEvent({required int index, DateTime? date}) async { final findDayCell = find.byWidgetPredicate( (widget) => widget is CalendarDayCard && isSameDay(widget.date, date ?? DateTime.now()), ); final cards = find.descendant( of: findDayCell, matching: find.byType(EventCard), ); await tapButton(cards.at(index)); } void assertEventEditorOpen() { expect(find.byType(CalendarEventEditor), findsOneWidget); } Future<void> dismissEventEditor() async { await simulateKeyEvent(LogicalKeyboardKey.escape); } Future<void> editEventTitle(String title) async { final textField = find.descendant( of: find.byType(CalendarEventEditor), matching: find.byType(FlowyTextField), ); await enterText(textField, title); await pumpAndSettle(const Duration(milliseconds: 300)); } Future<void> openEventToRowDetailPage() async { final button = find.descendant( of: find.byType(CalendarEventEditor), matching: find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.full_view_s, ), ); await tapButton(button); } Future<void> deleteEventFromEventEditor() async { final button = find.descendant( of: find.byType(CalendarEventEditor), matching: find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.delete_s, ), ); await tapButton(button); } Future<void> dragDropRescheduleCalendarEvent() async { final findEventCard = find.byType(EventCard); await drag(findEventCard.first, const Offset(0, 300)); await pumpAndSettle(const Duration(microseconds: 300)); } Future<void> openUnscheduledEventsPopup() async { final button = find.byType(UnscheduledEventsButton); await tapButton(button); } void findUnscheduledPopup(Matcher matcher, int numUnscheduledEvents) { expect(find.byType(UnscheduleEventsList), matcher); if (matcher != findsNothing) { expect( find.byType(UnscheduledEventCell), findsNWidgets(numUnscheduledEvents), ); } } Future<void> clickUnscheduledEvent() async { final unscheduledEvent = find.byType(UnscheduledEventCell); await tapButton(unscheduledEvent); } Future<void> tapCreateLinkedDatabaseViewButton( DatabaseLayoutPB layoutType, ) async { final findAddButton = find.byType(AddDatabaseViewButton); await tapButton(findAddButton); final findCreateButton = find.byWidgetPredicate( (widget) => widget is TabBarAddButtonActionCell && widget.action == layoutType, ); await tapButton(findCreateButton); } void assertNumberOfGroups(int number) { final groups = find.byType(BoardColumnHeader, skipOffstage: false); expect(groups, findsNWidgets(number)); } Future<void> scrollBoardToEnd() async { final scrollable = find .descendant( of: find.byType(AppFlowyBoard), matching: find.byWidgetPredicate( (widget) => widget is Scrollable && widget.axis == Axis.horizontal, ), ) .first; await scrollUntilVisible( find.byType(BoardTrailing), 300, scrollable: scrollable, ); } Future<void> tapNewGroupButton() async { final button = find.descendant( of: find.byType(BoardTrailing), matching: find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.add_s, ), ); expect(button, findsOneWidget); await tapButton(button); } void assertNewGroupTextField(bool isVisible) { final textField = find.descendant( of: find.byType(BoardTrailing), matching: find.byType(TextField), ); if (isVisible) { expect(textField, findsOneWidget); } else { expect(textField, findsNothing); } } Future<void> enterNewGroupName(String name, {required bool submit}) async { final textField = find.descendant( of: find.byType(BoardTrailing), matching: find.byType(TextField), ); await enterText(textField, name); await pumpAndSettle(); if (submit) { await testTextInput.receiveAction(TextInputAction.done); await pumpAndSettle(); } } Future<void> clearNewGroupTextField() async { final textField = find.descendant( of: find.byType(BoardTrailing), matching: find.byType(TextField), ); await tapButton( find.descendant( of: textField, matching: find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.close_filled_m, ), ), ); final textFieldWidget = widget<TextField>(textField); assert( textFieldWidget.controller != null && textFieldWidget.controller!.text.isEmpty, ); } Future<void> tapTabBarLinkedViewByViewName(String name) async { final viewButton = findTabBarLinkViewByViewName(name); await tapButton(viewButton); } Finder findTabBarLinkViewByViewLayout(ViewLayoutPB layout) { return find.byWidgetPredicate( (widget) => widget is TabBarItemButton && widget.view.layout == layout, ); } Finder findTabBarLinkViewByViewName(String name) { return find.byWidgetPredicate( (widget) => widget is TabBarItemButton && widget.view.name == name, ); } Future<void> renameLinkedView(Finder linkedView, String name) async { await tap(linkedView, buttons: kSecondaryButton); await pumpAndSettle(); await tapButton( find.byWidgetPredicate( (widget) => widget is ActionCellWidget && widget.action == TabBarViewAction.rename, ), ); await enterText( find.descendant( of: find.byType(FlowyFormTextInput), matching: find.byType(TextFormField), ), name, ); final field = find.byWidgetPredicate( (widget) => widget is PrimaryTextButton && widget.label == LocaleKeys.button_ok.tr(), ); await tapButton(field); } Future<void> deleteDatebaseView(Finder linkedView) async { await tap(linkedView, buttons: kSecondaryButton); await pumpAndSettle(); await tapButton( find.byWidgetPredicate( (widget) => widget is ActionCellWidget && widget.action == TabBarViewAction.delete, ), ); final okButton = find.byWidgetPredicate( (widget) => widget is PrimaryTextButton && widget.label == LocaleKeys.button_ok.tr(), ); await tapButton(okButton); } void assertCurrentDatabaseTagIs(DatabaseLayoutPB layout) { switch (layout) { case DatabaseLayoutPB.Board: expect(find.byType(BoardPage), findsOneWidget); break; case DatabaseLayoutPB.Calendar: expect(find.byType(CalendarPage), findsOneWidget); break; case DatabaseLayoutPB.Grid: expect(find.byType(GridPage), findsOneWidget); break; default: throw Exception('Unknown database layout type: $layout'); } } Future<void> selectDatabaseLayoutType(DatabaseLayoutPB layout) async { final findLayoutCell = find.byType(DatabaseViewLayoutCell); final findText = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == layout.layoutName, ); final button = find.descendant( of: findLayoutCell, matching: findText, ); await tapButton(button); } Future<void> assertCurrentDatabaseLayoutType(DatabaseLayoutPB layout) async { expect(finderForDatabaseLayoutType(layout), findsOneWidget); } Future<void> tapDatabaseRawDataButton() async { await tapButtonWithName(LocaleKeys.importPanel_database.tr()); } // Use in edit mode of FieldEditor Future<void> changeNumberFieldFormat() async { final changeFormatButton = find.descendant( of: find.byType(FieldTypeOptionEditor), matching: find.text("Number"), ); await tapButton(changeFormatButton); await tapButton( find.byWidgetPredicate( (widget) => widget is NumberFormatCell && widget.format == NumberFormatPB.USD, ), ); } // Use in edit mode of FieldEditor Future<void> tapAddSelectOptionButton() async { await tapButtonWithName(LocaleKeys.grid_field_addSelectOption.tr()); } Future<void> tapViewTogglePropertyVisibilityButtonByName( String fieldName, ) async { final field = find.byWidgetPredicate( (widget) => widget is DatabasePropertyCell && widget.fieldInfo.name == fieldName, ); final toggleVisibilityButton = find.descendant(of: field, matching: find.byType(FlowyIconButton)); await tapButton(toggleVisibilityButton); } } Finder finderForDatabaseLayoutType(DatabaseLayoutPB layout) { switch (layout) { case DatabaseLayoutPB.Board: return find.byType(BoardPage); case DatabaseLayoutPB.Calendar: return find.byType(CalendarPage); case DatabaseLayoutPB.Grid: return find.byType(GridPage); default: throw Exception('Unknown database layout type: $layout'); } } Finder finderForFieldType(FieldType fieldType) { switch (fieldType) { case FieldType.Checkbox: return find.byType(EditableCheckboxCell, skipOffstage: false); case FieldType.DateTime: return find.byType(EditableDateCell, skipOffstage: false); case FieldType.LastEditedTime: return find.byWidgetPredicate( (widget) => widget is EditableTimestampCell && widget.fieldType == FieldType.LastEditedTime, skipOffstage: false, ); case FieldType.CreatedTime: return find.byWidgetPredicate( (widget) => widget is EditableTimestampCell && widget.fieldType == FieldType.CreatedTime, skipOffstage: false, ); case FieldType.SingleSelect: return find.byWidgetPredicate( (widget) => widget is EditableSelectOptionCell && widget.fieldType == FieldType.SingleSelect, skipOffstage: false, ); case FieldType.MultiSelect: return find.byWidgetPredicate( (widget) => widget is EditableSelectOptionCell && widget.fieldType == FieldType.MultiSelect, skipOffstage: false, ); case FieldType.Checklist: return find.byType(EditableChecklistCell, skipOffstage: false); case FieldType.Number: return find.byType(EditableNumberCell, skipOffstage: false); case FieldType.RichText: return find.byType(EditableTextCell, skipOffstage: false); case FieldType.URL: return find.byType(EditableURLCell, skipOffstage: false); default: throw Exception('Unknown field type: $fieldType'); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/auth_operation.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_supabase_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'base.dart'; import 'expectation.dart'; extension AppFlowyAuthTest on WidgetTester { Future<void> tapGoogleLoginInButton() async { await tapButton(find.byKey(const Key('signInWithGoogleButton'))); } Future<void> logout() async { await tapButton(find.byType(SettingLogoutButton)); expectToSeeText(LocaleKeys.button_ok.tr()); await tapButtonWithName(LocaleKeys.button_ok.tr()); } Future<void> tapSignInAsGuest() async { await tapButton(find.byType(SignInAnonymousButtonV2)); } void expectToSeeGoogleLoginButton() { expect(find.byKey(const Key('signInWithGoogleButton')), findsOneWidget); } void assertSwitchValue(Finder finder, bool value) { final Switch switchWidget = widget(finder); final isSwitched = switchWidget.value; assert(isSwitched == value); } void assertEnableEncryptSwitchValue(bool value) { assertSwitchValue( find.descendant( of: find.byType(EnableEncrypt), matching: find.byWidgetPredicate((widget) => widget is Switch), ), value, ); } void assertSupabaseEnableSyncSwitchValue(bool value) { assertSwitchValue( find.descendant( of: find.byType(SupabaseEnableSync), matching: find.byWidgetPredicate((widget) => widget is Switch), ), value, ); } void assertAppFlowyCloudEnableSyncSwitchValue(bool value) { assertSwitchValue( find.descendant( of: find.byType(AppFlowyCloudEnableSync), matching: find.byWidgetPredicate((widget) => widget is Switch), ), value, ); } Future<void> toggleEnableEncrypt() async { final finder = find.descendant( of: find.byType(EnableEncrypt), matching: find.byWidgetPredicate((widget) => widget is Switch), ); await tapButton(finder); } Future<void> toggleEnableSync(Type syncButton) async { final finder = find.descendant( of: find.byType(syncButton), matching: find.byWidgetPredicate((widget) => widget is Switch), ); await tapButton(finder); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/emoji.dart
import 'package:flutter_emoji_mart/flutter_emoji_mart.dart'; import 'package:flutter_test/flutter_test.dart'; import 'base.dart'; extension EmojiTestExtension on WidgetTester { Future<void> tapEmoji(String emoji) async { final emojiWidget = find.descendant( of: find.byType(EmojiPicker), matching: find.text(emoji), ); await tapButton(emojiWidget); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/workspace.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/base/icon/icon_picker.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/sidebar_workspace.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_actions.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_icon.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'base.dart'; extension AppFlowyWorkspace on WidgetTester { /// Open workspace menu Future<void> openWorkspaceMenu() async { final workspaceWrapper = find.byType(SidebarSwitchWorkspaceButton); expect(workspaceWrapper, findsOneWidget); await tapButton(workspaceWrapper); final workspaceMenu = find.byType(WorkspacesMenu); expect(workspaceMenu, findsOneWidget); } /// Open a workspace Future<void> openWorkspace(String name) async { final workspace = find.descendant( of: find.byType(WorkspaceMenuItem), matching: find.findTextInFlowyText(name), ); expect(workspace, findsOneWidget); await tapButton(workspace); } Future<void> changeWorkspaceName(String name) async { final moreButton = find.descendant( of: find.byType(WorkspaceMenuItem), matching: find.byType(WorkspaceMoreActionList), ); expect(moreButton, findsOneWidget); await tapButton(moreButton); await tapButton(find.findTextInFlowyText(LocaleKeys.button_rename.tr())); final input = find.byType(TextFormField); expect(input, findsOneWidget); await enterText(input, name); await tapButton(find.text(LocaleKeys.button_ok.tr())); } Future<void> changeWorkspaceIcon(String icon) async { final iconButton = find.descendant( of: find.byType(WorkspaceMenuItem), matching: find.byType(WorkspaceIcon), ); expect(iconButton, findsOneWidget); await tapButton(iconButton); final iconPicker = find.byType(FlowyIconPicker); expect(iconPicker, findsOneWidget); await tapButton(find.findTextInFlowyText(icon)); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/data.dart
import 'dart:io'; import 'package:appflowy/core/config/kv_keys.dart'; import 'package:archive/archive_io.dart'; import 'package:flutter/services.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; enum TestWorkspace { board("board"), emptyDocument("empty_document"), aiWorkSpace("ai_workspace"), coverImage("cover_image"); const TestWorkspace(this._name); final String _name; Future<File> get zip async { final Directory parent = await TestWorkspace._parent; final File out = File(p.join(parent.path, '$_name.zip')); if (await out.exists()) return out; await out.create(); final ByteData data = await rootBundle.load(_asset); await out.writeAsBytes(data.buffer.asUint8List()); return out; } Future<Directory> get root async { final Directory parent = await TestWorkspace._parent; return Directory(p.join(parent.path, _name)); } static Future<Directory> get _parent async { final Directory root = await getTemporaryDirectory(); if (await root.exists()) return root; await root.create(); return root; } String get _asset => 'assets/test/workspaces/$_name.zip'; } class TestWorkspaceService { const TestWorkspaceService(this.workspace); final TestWorkspace workspace; /// Instructs the application to read workspace data from the workspace found under this [TestWorkspace]'s path. Future<void> setUpAll() async { final root = await workspace.root; final path = root.path; SharedPreferences.setMockInitialValues( { KVKeys.pathLocation: path, }, ); } /// Workspaces that are checked into source are compressed. [TestWorkspaceService.setUp()] decompresses the file into an ephemeral directory that will be ignored by source control. Future<void> setUp() async { final inputStream = InputFileStream(await workspace.zip.then((value) => value.path)); final archive = ZipDecoder().decodeBuffer(inputStream); extractArchiveToDisk( archive, await TestWorkspace._parent.then((value) => value.path), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/ime.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; extension IME on WidgetTester { IMESimulator get ime => IMESimulator(this); } class IMESimulator { IMESimulator(this.tester) { client = findTextInputClient(); } final WidgetTester tester; late final TextInputClient client; Future<void> insertText(String text) async { for (final c in text.characters) { await insertCharacter(c); } } Future<void> insertCharacter(String character) async { final value = client.currentTextEditingValue; if (value == null) { assert(false); return; } final text = value.text .replaceRange(value.selection.start, value.selection.end, character); final textEditingValue = TextEditingValue( text: text, selection: TextSelection.collapsed( offset: value.selection.baseOffset + 1, ), ); client.updateEditingValue(textEditingValue); await tester.pumpAndSettle(); } TextInputClient findTextInputClient() { final finder = find.byType(KeyboardServiceWidget); final KeyboardServiceWidgetState state = tester.state(finder); return state.textInputService as TextInputClient; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/expectation.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/database/widgets/row/row_detail.dart'; import 'package:appflowy/plugins/document/presentation/banner.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/document_header_node_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart'; import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart'; import 'package:appflowy/workspace/presentation/home/home_stack.dart'; import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart'; import 'package:appflowy/workspace/presentation/notifications/widgets/notification_item.dart'; import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart'; import 'package:appflowy/workspace/presentation/widgets/view_title_bar.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_test/flutter_test.dart'; import 'util.dart'; // const String readme = 'Read me'; const String gettingStarted = 'Getting started'; extension Expectation on WidgetTester { /// Expect to see the home page and with a default read me page. Future<void> expectToSeeHomePageWithGetStartedPage() async { final finder = find.byType(HomeStack); await pumpUntilFound(finder); expect(finder, findsOneWidget); final docFinder = find.textContaining(gettingStarted); await pumpUntilFound(docFinder); } Future<void> expectToSeeHomePage() async { final finder = find.byType(HomeStack); await pumpUntilFound(finder); expect(finder, findsOneWidget); } /// Expect to see the page name on the home page. void expectToSeePageName( String name, { String? parentName, ViewLayoutPB layout = ViewLayoutPB.Document, ViewLayoutPB parentLayout = ViewLayoutPB.Document, }) { final pageName = findPageName( name, layout: layout, parentName: parentName, parentLayout: parentLayout, ); expect(pageName, findsOneWidget); } /// Expect not to see the page name on the home page. void expectNotToSeePageName( String name, { String? parentName, ViewLayoutPB layout = ViewLayoutPB.Document, ViewLayoutPB parentLayout = ViewLayoutPB.Document, }) { final pageName = findPageName( name, layout: layout, parentName: parentName, parentLayout: parentLayout, ); expect(pageName, findsNothing); } /// Expect to see the document banner. void expectToSeeDocumentBanner() { expect(find.byType(DocumentBanner), findsOneWidget); } /// Expect not to see the document banner. void expectNotToSeeDocumentBanner() { expect(find.byType(DocumentBanner), findsNothing); } /// Expect to the markdown file export success dialog. void expectToExportSuccess() { final exportSuccess = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == LocaleKeys.settings_files_exportFileSuccess.tr(), ); expect(exportSuccess, findsOneWidget); } /// Expect to see the add button and icon button in the cover toolbar void expectToSeePluginAddCoverAndIconButton() { final addCover = find.textContaining( LocaleKeys.document_plugins_cover_addCover.tr(), ); final addIcon = find.textContaining( LocaleKeys.document_plugins_cover_addIcon.tr(), ); expect(addCover, findsOneWidget); expect(addIcon, findsOneWidget); } /// Expect to see the document header toolbar empty void expectToSeeEmptyDocumentHeaderToolbar() { final addCover = find.textContaining( LocaleKeys.document_plugins_cover_addCover.tr(), ); final addIcon = find.textContaining( LocaleKeys.document_plugins_cover_addIcon.tr(), ); expect(addCover, findsNothing); expect(addIcon, findsNothing); } void expectToSeeDocumentIcon(String? emoji) { if (emoji == null) { final iconWidget = find.byType(EmojiIconWidget); expect(iconWidget, findsNothing); return; } final iconWidget = find.byWidgetPredicate( (widget) => widget is EmojiIconWidget && widget.emoji == emoji, ); expect(iconWidget, findsOneWidget); } void expectDocumentIconNotNull() { final iconWidget = find.byWidgetPredicate( (widget) => widget is EmojiIconWidget && widget.emoji.isNotEmpty, ); expect(iconWidget, findsOneWidget); } void expectToSeeDocumentCover(CoverType type) { final findCover = find.byWidgetPredicate( (widget) => widget is DocumentCover && widget.coverType == type, ); expect(findCover, findsOneWidget); } void expectToSeeNoDocumentCover() { final findCover = find.byType(DocumentCover); expect(findCover, findsNothing); } void expectChangeCoverAndDeleteButton() { final findChangeCover = find.text( LocaleKeys.document_plugins_cover_changeCover.tr(), ); final findRemoveIcon = find.byType(DeleteCoverButton); expect(findChangeCover, findsOneWidget); expect(findRemoveIcon, findsOneWidget); } /// Expect to see the user name on the home page void expectToSeeUserName(String name) { final userName = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == name, ); expect(userName, findsOneWidget); } /// Expect to see a text void expectToSeeText(String text) { Finder textWidget = find.textContaining(text, findRichText: true); if (textWidget.evaluate().isEmpty) { textWidget = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == text, ); } expect(textWidget, findsOneWidget); } /// Find if the page is favorite Finder findFavoritePageName( String name, { ViewLayoutPB layout = ViewLayoutPB.Document, String? parentName, ViewLayoutPB parentLayout = ViewLayoutPB.Document, }) { return find.byWidgetPredicate( (widget) => widget is SingleInnerViewItem && widget.view.isFavorite && widget.categoryType == FolderCategoryType.favorite && widget.view.name == name && widget.view.layout == layout, skipOffstage: false, ); } Finder findAllFavoritePages() { return find.byWidgetPredicate( (widget) => widget is SingleInnerViewItem && widget.view.isFavorite && widget.categoryType == FolderCategoryType.favorite, ); } Finder findPageName( String name, { ViewLayoutPB layout = ViewLayoutPB.Document, String? parentName, ViewLayoutPB parentLayout = ViewLayoutPB.Document, }) { if (parentName == null) { return find.byWidgetPredicate( (widget) => widget is SingleInnerViewItem && widget.view.name == name && widget.view.layout == layout, skipOffstage: false, ); } return find.descendant( of: find.byWidgetPredicate( (widget) => widget is InnerViewItem && widget.view.name == parentName && widget.view.layout == parentLayout, skipOffstage: false, ), matching: findPageName(name, layout: layout), ); } void expectViewHasIcon(String name, ViewLayoutPB layout, String emoji) { final pageName = findPageName( name, layout: layout, ); final icon = find.descendant( of: pageName, matching: find.text(emoji), ); expect(icon, findsOneWidget); } void expectViewTitleHasIcon(String name, ViewLayoutPB layout, String emoji) { final icon = find.descendant( of: find.byType(ViewTitleBar), matching: find.text(emoji), ); expect(icon, findsOneWidget); } void expectSelectedReminder(ReminderOption option) { final findSelectedText = find.descendant( of: find.byType(ReminderSelector), matching: find.text(option.label), ); expect(findSelectedText, findsOneWidget); } void expectNotificationItems(int amount) { final findItems = find.byType(NotificationItem); expect(findItems, findsNWidgets(amount)); } void expectToSeeRowDetailsPageDialog() { expect( find.descendant( of: find.byType(RowDetailPage), matching: find.byType(SimpleDialog), ), findsOneWidget, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/editor_test_operations.dart
import 'dart:async'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/base/emoji/emoji_picker.dart'; import 'package:appflowy/plugins/base/emoji/emoji_skin_tone.dart'; import 'package:appflowy/plugins/base/icon/icon_picker.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_add_button.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_button.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/cover_editor.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/document_header_node_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/embed_image_url_widget.dart'; import 'package:appflowy/plugins/inline_actions/widgets/inline_actions_handler.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_emoji_mart/flutter_emoji_mart.dart'; import 'package:flutter_test/flutter_test.dart'; import 'util.dart'; extension EditorWidgetTester on WidgetTester { EditorOperations get editor => EditorOperations(this); } class EditorOperations { const EditorOperations(this.tester); final WidgetTester tester; EditorState getCurrentEditorState() { return tester .widget<AppFlowyEditor>(find.byType(AppFlowyEditor)) .editorState; } /// Tap the line of editor at [index] Future<void> tapLineOfEditorAt(int index) async { final textBlocks = find.byType(AppFlowyRichText); index = index.clamp(0, textBlocks.evaluate().length - 1); await tester.tapAt(tester.getTopRight(textBlocks.at(index))); await tester.pumpAndSettle(); } /// Hover on cover plugin button above the document Future<void> hoverOnCoverToolbar() async { final coverToolbar = find.byType(DocumentHeaderToolbar); await tester.startGesture( tester.getBottomLeft(coverToolbar).translate(5, -5), kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); } /// Taps on the 'Add Icon' button in the cover toolbar Future<void> tapAddIconButton() async { await tester.tapButtonWithName( LocaleKeys.document_plugins_cover_addIcon.tr(), ); expect(find.byType(FlowyEmojiPicker), findsOneWidget); } Future<void> tapGettingStartedIcon() async { await tester.tapButton( find.descendant( of: find.byType(DocumentHeaderNodeWidget), matching: find.findTextInFlowyText('⭐️'), ), ); } /// Taps on the 'Skin tone' button /// /// Must call [tapAddIconButton] first. Future<void> changeEmojiSkinTone(EmojiSkinTone skinTone) async { await tester.tapButton( find.byTooltip(LocaleKeys.emoji_selectSkinTone.tr()), ); final skinToneButton = find.byKey(emojiSkinToneKey(skinTone.icon)); await tester.tapButton(skinToneButton); } /// Taps the 'Remove Icon' button in the cover toolbar and the icon popover Future<void> tapRemoveIconButton({bool isInPicker = false}) async { Finder button = find.text(LocaleKeys.document_plugins_cover_removeIcon.tr()); if (isInPicker) { button = find.descendant( of: find.byType(FlowyIconPicker), matching: button, ); } await tester.tapButton(button); } /// Requires that the document must already have an icon. This opens the icon /// picker Future<void> tapOnIconWidget() async { final iconWidget = find.byType(EmojiIconWidget); await tester.tapButton(iconWidget); } Future<void> tapOnAddCover() async { await tester.tapButtonWithName( LocaleKeys.document_plugins_cover_addCover.tr(), ); } Future<void> tapOnChangeCover() async { await tester.tapButtonWithName( LocaleKeys.document_plugins_cover_changeCover.tr(), ); } Future<void> switchSolidColorBackground() async { final findPurpleButton = find.byWidgetPredicate( (widget) => widget is ColorItem && widget.option.name == 'Purple', ); await tester.tapButton(findPurpleButton); } Future<void> addNetworkImageCover(String imageUrl) async { final embedLinkButton = find.findTextInFlowyText( LocaleKeys.document_imageBlock_embedLink_label.tr(), ); await tester.tapButton(embedLinkButton); final imageUrlTextField = find.descendant( of: find.byType(EmbedImageUrlWidget), matching: find.byType(TextField), ); await tester.enterText(imageUrlTextField, imageUrl); await tester.pumpAndSettle(); await tester.tapButton( find.descendant( of: find.byType(EmbedImageUrlWidget), matching: find.findTextInFlowyText( LocaleKeys.document_imageBlock_embedLink_label.tr(), ), ), ); } Future<void> switchNetworkImageCover(String imageUrl) async { final image = find.byWidgetPredicate( (widget) => widget is ImageGridItem, ); await tester.tapButton(image); } Future<void> tapOnRemoveCover() async { await tester.tapButton(find.byType(DeleteCoverButton)); } /// A cover must be present in the document to function properly since this /// catches all cover types collectively Future<void> hoverOnCover() async { final cover = find.byType(DocumentCover); await tester.startGesture( tester.getCenter(cover), kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); } Future<void> dismissCoverPicker() async { await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); } /// trigger the slash command (selection menu) Future<void> showSlashMenu() async { await tester.ime.insertCharacter('/'); } /// trigger the mention (@) command Future<void> showAtMenu() async { await tester.ime.insertCharacter('@'); } /// Tap the slash menu item with [name] /// /// Must call [showSlashMenu] first. Future<void> tapSlashMenuItemWithName(String name) async { final slashMenuItem = find.text(name, findRichText: true); await tester.tapButton(slashMenuItem); } /// Tap the at menu item with [name] /// /// Must call [showAtMenu] first. Future<void> tapAtMenuItemWithName(String name) async { final atMenuItem = find.descendant( of: find.byType(InlineActionsHandler), matching: find.text(name, findRichText: true), ); await tester.tapButton(atMenuItem); } /// Update the editor's selection Future<void> updateSelection(Selection selection) async { final editorState = getCurrentEditorState(); unawaited( editorState.updateSelectionWithReason( selection, reason: SelectionUpdateReason.uiEvent, ), ); await tester.pumpAndSettle(const Duration(milliseconds: 200)); } /// hover and click on the + button beside the block component. Future<void> hoverAndClickOptionAddButton( Path path, bool withModifiedKey, // alt on windows or linux, option on macos ) async { final optionAddButton = find.byWidgetPredicate( (widget) => widget is BlockComponentActionWrapper && widget.node.path.equals(path), ); await tester.hoverOnWidget( optionAddButton, onHover: () async { if (withModifiedKey) { await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); } await tester.tapButton( find.byWidgetPredicate( (widget) => widget is BlockAddButton && widget.blockComponentContext.node.path.equals(path), ), ); if (withModifiedKey) { await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); } }, ); } /// hover and click on the option menu button beside the block component. Future<void> hoverAndClickOptionMenuButton(Path path) async { final optionMenuButton = find.byWidgetPredicate( (widget) => widget is BlockComponentActionWrapper && widget.node.path.equals(path), ); await tester.hoverOnWidget( optionMenuButton, onHover: () async { await tester.tapButton( find.byWidgetPredicate( (widget) => widget is BlockOptionButton && widget.blockComponentContext.node.path.equals(path), ), ); }, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/base.dart
import 'dart:async'; import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/env/cloud_env_test.dart'; import 'package:appflowy/startup/entry_point.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/application/auth/supabase_mock_auth_service.dart'; import 'package:appflowy/user/presentation/presentation.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; class FlowyTestContext { FlowyTestContext({ required this.applicationDataDirectory, }); final String applicationDataDirectory; } extension AppFlowyTestBase on WidgetTester { Future<FlowyTestContext> initializeAppFlowy({ // use to append after the application data directory String? pathExtension, // use to specify the application data directory, if not specified, a temporary directory will be used. String? dataDirectory, Size windowSize = const Size(1600, 1200), AuthenticatorType? cloudType, String? email, }) async { if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) { // Set the window size await binding.setSurfaceSize(windowSize); } mockHotKeyManagerHandlers(); final applicationDataDirectory = dataDirectory ?? await mockApplicationDataStorage( pathExtension: pathExtension, ); await FlowyRunner.run( AppFlowyApplication(), IntegrationMode.integrationTest, rustEnvsBuilder: () { final rustEnvs = <String, String>{}; if (cloudType != null) { switch (cloudType) { case AuthenticatorType.local: break; case AuthenticatorType.supabase: break; case AuthenticatorType.appflowyCloudSelfHost: rustEnvs["GOTRUE_ADMIN_EMAIL"] = "[email protected]"; rustEnvs["GOTRUE_ADMIN_PASSWORD"] = "password"; break; default: throw Exception("not supported"); } } return rustEnvs; }, didInitGetItCallback: () { return Future( () async { if (cloudType != null) { switch (cloudType) { case AuthenticatorType.local: await useLocal(); break; case AuthenticatorType.supabase: await useTestSupabaseCloud(); getIt.unregister<AuthService>(); getIt.registerFactory<AuthService>( () => SupabaseMockAuthService(), ); break; case AuthenticatorType.appflowyCloudSelfHost: await useTestSelfHostedAppFlowyCloud(); getIt.unregister<AuthService>(); getIt.registerFactory<AuthService>( () => AppFlowyCloudMockAuthService(email: email), ); default: throw Exception("not supported"); } } }, ); }, ); await waitUntilSignInPageShow(); return FlowyTestContext( applicationDataDirectory: applicationDataDirectory, ); } void mockHotKeyManagerHandlers() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(const MethodChannel('hotkey_manager'), (MethodCall methodCall) async { if (methodCall.method == 'unregisterAll') { // do nothing } return; }); } Future<void> waitUntilSignInPageShow() async { if (isAuthEnabled) { final finder = find.byType(SignInAnonymousButtonV2); await pumpUntilFound(finder, timeout: const Duration(seconds: 30)); expect(finder, findsOneWidget); } else { final finder = find.byType(GoButton); await pumpUntilFound(finder); expect(finder, findsOneWidget); } } Future<void> waitForSeconds(int seconds) async { await Future.delayed(Duration(seconds: seconds), () {}); } Future<void> pumpUntilFound( Finder finder, { Duration timeout = const Duration(seconds: 10), Duration pumpInterval = const Duration( milliseconds: 50, ), // Interval between pumps }) async { bool timerDone = false; final timer = Timer(timeout, () => timerDone = true); while (!timerDone) { await pump(pumpInterval); // Pump with an interval if (any(finder)) { break; } } timer.cancel(); } Future<void> pumpUntilNotFound( Finder finder, { Duration timeout = const Duration(seconds: 10), Duration pumpInterval = const Duration( milliseconds: 50, ), // Interval between pumps }) async { bool timerDone = false; final timer = Timer(timeout, () => timerDone = true); while (!timerDone) { await pump(pumpInterval); // Pump with an interval if (!any(finder)) { break; } } timer.cancel(); } Future<void> tapButton( Finder finder, { int? pointer, int buttons = kPrimaryButton, bool warnIfMissed = false, int milliseconds = 500, }) async { await tap( finder, buttons: buttons, warnIfMissed: warnIfMissed, ); await pumpAndSettle( Duration(milliseconds: milliseconds), EnginePhase.sendSemanticsUpdate, const Duration(seconds: 5), ); } Future<void> tapButtonWithName( String tr, { int milliseconds = 500, }) async { Finder button = find.text( tr, findRichText: true, skipOffstage: false, ); if (button.evaluate().isEmpty) { button = find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == tr, ); } await tapButton( button, milliseconds: milliseconds, ); return; } Future<void> tapButtonWithTooltip( String tr, { int milliseconds = 500, }) async { final button = find.byTooltip(tr); await tapButton( button, milliseconds: milliseconds, ); return; } Future<void> doubleTapAt( Offset location, { int? pointer, int buttons = kPrimaryButton, int milliseconds = 500, }) async { await tapAt(location, pointer: pointer, buttons: buttons); await pump(kDoubleTapMinTime); await tapAt(location, pointer: pointer, buttons: buttons); await pumpAndSettle(Duration(milliseconds: milliseconds)); } Future<void> doubleTapButton( Finder finder, { int? pointer, int buttons = kPrimaryButton, bool warnIfMissed = true, int milliseconds = 500, }) async { await tap( finder, pointer: pointer, buttons: buttons, warnIfMissed: warnIfMissed, ); await pump(kDoubleTapMinTime); await tap( finder, buttons: buttons, pointer: pointer, warnIfMissed: warnIfMissed, ); await pumpAndSettle(Duration(milliseconds: milliseconds)); } Future<void> wait(int milliseconds) async { await pumpAndSettle(Duration(milliseconds: milliseconds)); return; } } extension AppFlowyFinderTestBase on CommonFinders { Finder findTextInFlowyText(String text) { return find.byWidgetPredicate( (widget) => widget is FlowyText && widget.text == text, ); } } Future<void> useLocal() async { await useLocalServer(); } Future<void> useTestSupabaseCloud() async { await useSupabaseCloud( url: TestEnv.supabaseUrl, anonKey: TestEnv.supabaseAnonKey, ); } Future<void> useTestSelfHostedAppFlowyCloud() async { await useSelfHostedAppFlowyCloudWithURL(TestEnv.afCloudUrl); } Future<String> mockApplicationDataStorage({ // use to append after the application data directory String? pathExtension, }) async { final dir = await getTemporaryDirectory(); // Use a random uuid to avoid conflict. String path = p.join(dir.path, 'appflowy_integration_test', uuid()); if (pathExtension != null && pathExtension.isNotEmpty) { path = '$path/$pathExtension'; } final directory = Directory(path); if (!directory.existsSync()) { await directory.create(recursive: true); } MockApplicationDataStorage.initialPath = directory.path; return directory.path; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/keyboard.dart
import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart' as flutter_test; class FlowyTestKeyboard { static Future<void> simulateKeyDownEvent( List<LogicalKeyboardKey> keys, { required flutter_test.WidgetTester tester, }) async { for (final LogicalKeyboardKey key in keys) { await flutter_test.simulateKeyDownEvent(key); await tester.pumpAndSettle(); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/settings.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/sidebar_setting.dart'; import 'package:appflowy/workspace/presentation/settings/settings_dialog.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/direction_setting.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_menu_element.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_test/flutter_test.dart'; import 'base.dart'; extension AppFlowySettings on WidgetTester { /// Open settings page Future<void> openSettings() async { final settingsButton = find.byType(UserSettingButton); expect(settingsButton, findsOneWidget); await tapButton(settingsButton); final settingsDialog = find.byType(SettingsDialog); expect(settingsDialog, findsOneWidget); return; } /// Open the page that insides the settings page Future<void> openSettingsPage(SettingsPage page) async { final button = find.byWidgetPredicate( (widget) => widget is SettingsMenuElement && widget.page == page, ); expect(button, findsOneWidget); await tapButton(button); return; } Future<void> expectNoSettingsPage(SettingsPage page) async { final button = find.byWidgetPredicate( (widget) => widget is SettingsMenuElement && widget.page == page, ); expect(button, findsNothing); return; } /// Restore the AppFlowy data storage location Future<void> restoreLocation() async { final button = find.byTooltip(LocaleKeys.settings_files_recoverLocationTooltips.tr()); expect(button, findsOneWidget); await tapButton(button); return; } Future<void> tapOpenFolderButton() async { final button = find.text(LocaleKeys.settings_files_open.tr()); expect(button, findsOneWidget); await tapButton(button); return; } Future<void> tapCustomLocationButton() async { final button = find.byTooltip( LocaleKeys.settings_files_changeLocationTooltips.tr(), ); expect(button, findsOneWidget); await tapButton(button); return; } /// Enter user name Future<void> enterUserName(String name) async { final uni = find.byType(UserNameInput); expect(uni, findsOneWidget); await tap(uni); await enterText(uni, name); await wait(300); // await testTextInput.receiveAction(TextInputAction.done); await pumpAndSettle(); } // go to settings page and toggle enable RTL toolbar items Future<void> toggleEnableRTLToolbarItems() async { await openSettings(); await openSettingsPage(SettingsPage.appearance); final switchButton = find.byKey(EnableRTLToolbarItemsSetting.enableRTLSwitchKey); expect(switchButton, findsOneWidget); await tapButton(switchButton); // tap anywhere to close the settings page await tapAt(Offset.zero); await pumpAndSettle(); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/dir.dart
import 'dart:io'; import 'package:path/path.dart' as p; import 'package:archive/archive.dart'; Future<void> deleteDirectoriesWithSameBaseNameAsPrefix( String path, ) async { final dir = Directory(path); final prefix = p.basename(dir.path); final parentDir = dir.parent; // Check if the directory exists if (!await parentDir.exists()) { // ignore: avoid_print print('Directory does not exist'); return; } // List all entities in the directory await for (final entity in parentDir.list()) { // Check if the entity is a directory and starts with the specified prefix if (entity is Directory && p.basename(entity.path).startsWith(prefix)) { try { await entity.delete(recursive: true); } catch (e) { // ignore: avoid_print print('Failed to delete directory: ${entity.path}, Error: $e'); } } } } Future<void> unzipFile(File zipFile, Directory targetDirectory) async { // Read the Zip file from disk. final bytes = zipFile.readAsBytesSync(); // Decode the Zip file final archive = ZipDecoder().decodeBytes(bytes); // Extract the contents of the Zip archive to disk. for (final file in archive) { final filename = file.name; if (file.isFile) { final data = file.content as List<int>; File(p.join(targetDirectory.path, filename)) ..createSync(recursive: true) ..writeAsBytesSync(data); } else { Directory(p.join(targetDirectory.path, filename)) .createSync(recursive: true); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/common_operations.dart
import 'dart:io'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:appflowy/core/config/kv.dart'; import 'package:appflowy/core/config/kv_keys.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/emoji_picker_button.dart'; import 'package:appflowy/plugins/document/presentation/share/share_button.dart'; import 'package:appflowy/shared/feature_flags.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/presentation/screens/screens.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/sidebar_new_page_button.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/sidebar_workspace.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart'; import 'package:appflowy/workspace/presentation/home/menu/view/draggable_view_item.dart'; import 'package:appflowy/workspace/presentation/home/menu/view/view_action_type.dart'; import 'package:appflowy/workspace/presentation/home/menu/view/view_add_button.dart'; import 'package:appflowy/workspace/presentation/home/menu/view/view_more_action_button.dart'; import 'package:appflowy/workspace/presentation/notifications/widgets/flowy_tab.dart'; import 'package:appflowy/workspace/presentation/notifications/widgets/notification_button.dart'; import 'package:appflowy/workspace/presentation/notifications/widgets/notification_tab_bar.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_language_view.dart'; import 'package:appflowy/workspace/presentation/widgets/view_title_bar.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/widget/buttons/primary_button.dart'; import 'package:flutter_test/flutter_test.dart'; import 'emoji.dart'; import 'util.dart'; extension CommonOperations on WidgetTester { /// Tap the GetStart button on the launch page. Future<void> tapAnonymousSignInButton() async { // local version final goButton = find.byType(GoButton); if (goButton.evaluate().isNotEmpty) { await tapButton(goButton); } else { // cloud version final anonymousButton = find.byType(SignInAnonymousButtonV2); await tapButton(anonymousButton); } if (Platform.isWindows) { await pumpAndSettle(const Duration(milliseconds: 200)); } } /// Tap the + button on the home page. Future<void> tapAddViewButton({ String name = gettingStarted, }) async { await hoverOnPageName( name, onHover: () async { final addButton = find.byType(ViewAddButton); await tapButton(addButton); }, ); } /// Tap the 'New Page' Button on the sidebar. Future<void> tapNewPageButton() async { final newPageButton = find.byType(SidebarNewPageButton); await tapButton(newPageButton); } /// Tap the create document button. /// /// Must call [tapAddViewButton] first. Future<void> tapCreateDocumentButton() async { await tapButtonWithName(LocaleKeys.document_menuName.tr()); } /// Tap the create grid button. /// /// Must call [tapAddViewButton] first. Future<void> tapCreateGridButton() async { await tapButtonWithName(LocaleKeys.grid_menuName.tr()); } /// Tap the create grid button. /// /// Must call [tapAddViewButton] first. Future<void> tapCreateCalendarButton() async { await tapButtonWithName(LocaleKeys.calendar_menuName.tr()); } /// Tap the import button. /// /// Must call [tapAddViewButton] first. Future<void> tapImportButton() async { await tapButtonWithName(LocaleKeys.moreAction_import.tr()); } /// Tap the import from text & markdown button. /// /// Must call [tapImportButton] first. Future<void> tapTextAndMarkdownButton() async { await tapButtonWithName(LocaleKeys.importPanel_textAndMarkdown.tr()); } /// Tap the LanguageSelectorOnWelcomePage widget on the launch page. Future<void> tapLanguageSelectorOnWelcomePage() async { final languageSelector = find.byType(LanguageSelectorOnWelcomePage); await tapButton(languageSelector); } /// Tap languageItem on LanguageItemsListView. /// /// [scrollDelta] is the distance to scroll the ListView. /// Default value is 100 /// /// If it is positive -> scroll down. /// /// If it is negative -> scroll up. Future<void> tapLanguageItem({ required String languageCode, String? countryCode, double? scrollDelta, }) async { final languageItemsListView = find.descendant( of: find.byType(ListView), matching: find.byType(Scrollable), ); final languageItem = find.byWidgetPredicate( (widget) => widget is LanguageItem && widget.locale.languageCode == languageCode && widget.locale.countryCode == countryCode, ); // scroll the ListView until zHCNLanguageItem shows on the screen. await scrollUntilVisible( languageItem, scrollDelta ?? 100, scrollable: languageItemsListView, // maxHeight of LanguageItemsListView maxScrolls: 400, ); try { await tapButton(languageItem); } on FlutterError catch (e) { Log.warn('tapLanguageItem error: $e'); } } /// Hover on the widget. Future<void> hoverOnWidget( Finder finder, { Offset? offset, Future<void> Function()? onHover, bool removePointer = true, }) async { try { final gesture = await createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: offset ?? getCenter(finder)); await pumpAndSettle(); await onHover?.call(); await gesture.removePointer(); } catch (err) { Log.error('hoverOnWidget error: $err'); } } /// Hover on the page name. Future<void> hoverOnPageName( String name, { ViewLayoutPB layout = ViewLayoutPB.Document, Future<void> Function()? onHover, bool useLast = true, }) async { final pageNames = findPageName(name, layout: layout); if (useLast) { await hoverOnWidget( pageNames.last, onHover: onHover, ); } else { await hoverOnWidget( pageNames.first, onHover: onHover, ); } } /// open the page with given name. Future<void> openPage( String name, { ViewLayoutPB layout = ViewLayoutPB.Document, }) async { final finder = findPageName(name, layout: layout); expect(finder, findsOneWidget); await tapButton(finder); } /// Tap the ... button beside the page name. /// /// Must call [hoverOnPageName] first. Future<void> tapPageOptionButton() async { final optionButton = find.byType(ViewMoreActionButton); await tapButton(optionButton); } /// Tap the delete page button. Future<void> tapDeletePageButton() async { await tapPageOptionButton(); await tapButtonWithName(ViewMoreActionType.delete.name); } /// Tap the rename page button. Future<void> tapRenamePageButton() async { await tapPageOptionButton(); await tapButtonWithName(ViewMoreActionType.rename.name); } /// Tap the favorite page button Future<void> tapFavoritePageButton() async { await tapPageOptionButton(); await tapButtonWithName(ViewMoreActionType.favorite.name); } /// Tap the unfavorite page button Future<void> tapUnfavoritePageButton() async { await tapPageOptionButton(); await tapButtonWithName(ViewMoreActionType.unFavorite.name); } /// Tap the Open in a new tab button Future<void> tapOpenInTabButton() async { await tapPageOptionButton(); await tapButtonWithName(ViewMoreActionType.openInNewTab.name); } /// Rename the page. Future<void> renamePage(String name) async { await tapRenamePageButton(); await enterText(find.byType(TextFormField), name); await tapOKButton(); } Future<void> tapOKButton() async { final okButton = find.byWidgetPredicate( (widget) => widget is PrimaryTextButton && widget.label == LocaleKeys.button_ok.tr(), ); await tapButton(okButton); } /// Tap the restore button. /// /// the restore button will show after the current page is deleted. Future<void> tapRestoreButton() async { final restoreButton = find.textContaining( LocaleKeys.deletePagePrompt_restore.tr(), ); await tapButton(restoreButton); } /// Tap the delete permanently button. /// /// the restore button will show after the current page is deleted. Future<void> tapDeletePermanentlyButton() async { final restoreButton = find.textContaining( LocaleKeys.deletePagePrompt_deletePermanent.tr(), ); await tapButton(restoreButton); } /// Tap the share button above the document page. Future<void> tapShareButton() async { final shareButton = find.byWidgetPredicate( (widget) => widget is DocumentShareButton, ); await tapButton(shareButton); } /// Tap the export markdown button /// /// Must call [tapShareButton] first. Future<void> tapMarkdownButton() async { final markdownButton = find.textContaining( LocaleKeys.shareAction_markdown.tr(), ); await tapButton(markdownButton); } Future<void> createNewPageWithNameUnderParent({ String? name, ViewLayoutPB layout = ViewLayoutPB.Document, String? parentName, bool openAfterCreated = true, }) async { // create a new page await tapAddViewButton(name: parentName ?? gettingStarted); await tapButtonWithName(layout.menuName); final settingsOrFailure = await getIt<KeyValueStorage>().getWithFormat( KVKeys.showRenameDialogWhenCreatingNewFile, (value) => bool.parse(value), ); final showRenameDialog = settingsOrFailure ?? false; if (showRenameDialog) { await tapOKButton(); } await pumpAndSettle(); // hover on it and change it's name if (name != null) { await hoverOnPageName( LocaleKeys.menuAppHeader_defaultNewPageName.tr(), layout: layout, onHover: () async { await renamePage(name); await pumpAndSettle(); }, ); await pumpAndSettle(); } // open the page after created if (openAfterCreated) { await openPage( // if the name is null, use the default name name ?? LocaleKeys.menuAppHeader_defaultNewPageName.tr(), layout: layout, ); await pumpAndSettle(); } } Future<void> createNewPage({ ViewLayoutPB layout = ViewLayoutPB.Document, bool openAfterCreated = true, }) async { await tapButton(find.byType(SidebarNewPageButton)); } Future<void> simulateKeyEvent( LogicalKeyboardKey key, { bool isControlPressed = false, bool isShiftPressed = false, bool isAltPressed = false, bool isMetaPressed = false, }) async { if (isControlPressed) { await simulateKeyDownEvent(LogicalKeyboardKey.control); } if (isShiftPressed) { await simulateKeyDownEvent(LogicalKeyboardKey.shift); } if (isAltPressed) { await simulateKeyDownEvent(LogicalKeyboardKey.alt); } if (isMetaPressed) { await simulateKeyDownEvent(LogicalKeyboardKey.meta); } await simulateKeyDownEvent(key); await simulateKeyUpEvent(key); if (isControlPressed) { await simulateKeyUpEvent(LogicalKeyboardKey.control); } if (isShiftPressed) { await simulateKeyUpEvent(LogicalKeyboardKey.shift); } if (isAltPressed) { await simulateKeyUpEvent(LogicalKeyboardKey.alt); } if (isMetaPressed) { await simulateKeyUpEvent(LogicalKeyboardKey.meta); } await pumpAndSettle(); } Future<void> openAppInNewTab(String name, ViewLayoutPB layout) async { await hoverOnPageName( name, onHover: () async { await tapOpenInTabButton(); await pumpAndSettle(); }, ); await pumpAndSettle(); } Future<void> favoriteViewByName( String name, { ViewLayoutPB layout = ViewLayoutPB.Document, }) async { await hoverOnPageName( name, layout: layout, onHover: () async { await tapFavoritePageButton(); await pumpAndSettle(); }, ); } Future<void> unfavoriteViewByName( String name, { ViewLayoutPB layout = ViewLayoutPB.Document, }) async { await hoverOnPageName( name, layout: layout, onHover: () async { await tapUnfavoritePageButton(); await pumpAndSettle(); }, ); } Future<void> movePageToOtherPage({ required String name, required String parentName, required ViewLayoutPB layout, required ViewLayoutPB parentLayout, DraggableHoverPosition position = DraggableHoverPosition.center, }) async { final from = findPageName(name, layout: layout); final to = findPageName(parentName, layout: parentLayout); final gesture = await startGesture(getCenter(from)); Offset offset = Offset.zero; switch (position) { case DraggableHoverPosition.center: offset = getCenter(to); break; case DraggableHoverPosition.top: offset = getTopLeft(to); break; case DraggableHoverPosition.bottom: offset = getBottomLeft(to); break; default: } await gesture.moveTo(offset, timeStamp: const Duration(milliseconds: 400)); await gesture.up(); await pumpAndSettle(); } // tap the button with [FlowySvgData] Future<void> tapButtonWithFlowySvgData(FlowySvgData svg) async { final button = find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg.path == svg.path, ); await tapButton(button); } // update the page icon in the sidebar Future<void> updatePageIconInSidebarByName({ required String name, required String parentName, required ViewLayoutPB layout, required String icon, }) async { final iconButton = find.descendant( of: findPageName( name, layout: layout, parentName: parentName, ), matching: find.byTooltip(LocaleKeys.document_plugins_cover_changeIcon.tr()), ); await tapButton(iconButton); await tapEmoji(icon); await pumpAndSettle(); } // update the page icon in the sidebar Future<void> updatePageIconInTitleBarByName({ required String name, required ViewLayoutPB layout, required String icon, }) async { await openPage( name, layout: layout, ); final title = find.descendant( of: find.byType(ViewTitleBar), matching: find.text(name), ); await tapButton(title); await tapButton(find.byType(EmojiPickerButton)); await tapEmoji(icon); await pumpAndSettle(); } Future<void> openNotificationHub({ int tabIndex = 0, }) async { final finder = find.descendant( of: find.byType(NotificationButton), matching: find.byWidgetPredicate( (widget) => widget is FlowySvg && widget.svg == FlowySvgs.clock_alarm_s, ), ); await tap(finder); await pumpAndSettle(); if (tabIndex == 1) { final tabFinder = find.descendant( of: find.byType(NotificationTabBar), matching: find.byType(FlowyTabItem).at(1), ); await tap(tabFinder); await pumpAndSettle(); } } Future<void> toggleCommandPalette() async { // Press CMD+P or CTRL+P to open the command palette await simulateKeyEvent( LogicalKeyboardKey.keyP, isControlPressed: !Platform.isMacOS, isMetaPressed: Platform.isMacOS, ); await pumpAndSettle(); } Future<void> openCollaborativeWorkspaceMenu() async { if (!FeatureFlag.collaborativeWorkspace.isOn) { throw UnsupportedError('Collaborative workspace is not enabled'); } final workspace = find.byType(SidebarWorkspace); expect(workspace, findsOneWidget); // click it await tapButton(workspace, milliseconds: 2000); } Future<void> closeCollaborativeWorkspaceMenu() async { if (!FeatureFlag.collaborativeWorkspace.isOn) { throw UnsupportedError('Collaborative workspace is not enabled'); } await tapAt(Offset.zero); await pumpAndSettle(); } Future<void> createCollaborativeWorkspace(String name) async { if (!FeatureFlag.collaborativeWorkspace.isOn) { throw UnsupportedError('Collaborative workspace is not enabled'); } await openCollaborativeWorkspaceMenu(); // expect to see the workspace list, and there should be only one workspace final workspacesMenu = find.byType(WorkspacesMenu); expect(workspacesMenu, findsOneWidget); // click the create button final createButton = find.byKey(createWorkspaceButtonKey); expect(createButton, findsOneWidget); await tapButton(createButton); // see the create workspace dialog final createWorkspaceDialog = find.byType(CreateWorkspaceDialog); expect(createWorkspaceDialog, findsOneWidget); // input the workspace name await enterText(find.byType(TextField), name); await tapButtonWithName(LocaleKeys.button_ok.tr()); } } extension ViewLayoutPBTest on ViewLayoutPB { String get menuName { switch (this) { case ViewLayoutPB.Grid: return LocaleKeys.grid_menuName.tr(); case ViewLayoutPB.Board: return LocaleKeys.board_menuName.tr(); case ViewLayoutPB.Document: return LocaleKeys.document_menuName.tr(); case ViewLayoutPB.Calendar: return LocaleKeys.calendar_menuName.tr(); default: throw UnsupportedError('Unsupported layout: $this'); } } String get referencedMenuName { switch (this) { case ViewLayoutPB.Grid: return LocaleKeys.document_plugins_referencedGrid.tr(); case ViewLayoutPB.Board: return LocaleKeys.document_plugins_referencedBoard.tr(); case ViewLayoutPB.Calendar: return LocaleKeys.document_plugins_referencedCalendar.tr(); default: throw UnsupportedError('Unsupported layout: $this'); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/mock/mock_file_picker.dart
import 'package:appflowy/startup/startup.dart'; import 'package:flowy_infra/file_picker/file_picker_service.dart'; class MockFilePicker implements FilePickerService { MockFilePicker({ this.mockPath = '', this.mockPaths = const [], }); final String mockPath; final List<String> mockPaths; @override Future<String?> getDirectoryPath({String? title}) { return Future.value(mockPath); } @override Future<String?> saveFile({ String? dialogTitle, String? fileName, String? initialDirectory, FileType type = FileType.any, List<String>? allowedExtensions, bool lockParentWindow = false, }) { return Future.value(mockPath); } @override Future<FilePickerResult?> pickFiles({ String? dialogTitle, String? initialDirectory, FileType type = FileType.any, List<String>? allowedExtensions, Function(FilePickerStatus p1)? onFileLoading, bool allowCompression = true, bool allowMultiple = false, bool withData = false, bool withReadStream = false, bool lockParentWindow = false, }) { final platformFiles = mockPaths.map((e) => PlatformFile(path: e, name: '', size: 0)).toList(); return Future.value( FilePickerResult( platformFiles, ), ); } } Future<void> mockGetDirectoryPath( String path, ) async { getIt.unregister<FilePickerService>(); getIt.registerFactory<FilePickerService>( () => MockFilePicker( mockPath: path, ), ); return; } Future<String> mockSaveFilePath( String path, ) async { getIt.unregister<FilePickerService>(); getIt.registerFactory<FilePickerService>( () => MockFilePicker( mockPath: path, ), ); return path; } List<String> mockPickFilePaths({required List<String> paths}) { getIt.unregister<FilePickerService>(); getIt.registerFactory<FilePickerService>( () => MockFilePicker( mockPaths: paths, ), ); return paths; }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/mock/mock_url_launcher.dart
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; class MockUrlLauncher extends Fake with MockPlatformInterfaceMixin implements UrlLauncherPlatform { String? url; PreferredLaunchMode? launchMode; bool? useSafariVC; bool? useWebView; bool? enableJavaScript; bool? enableDomStorage; bool? universalLinksOnly; Map<String, String>? headers; String? webOnlyWindowName; bool? response; bool closeWebViewCalled = false; bool canLaunchCalled = false; bool launchCalled = false; // ignore: use_setters_to_change_properties void setCanLaunchExpectations(String url) { this.url = url; } void setLaunchExpectations({ required String url, PreferredLaunchMode? launchMode, bool? useSafariVC, bool? useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, required String? webOnlyWindowName, }) { this.url = url; this.launchMode = launchMode; this.useSafariVC = useSafariVC; this.useWebView = useWebView; this.enableJavaScript = enableJavaScript; this.enableDomStorage = enableDomStorage; this.universalLinksOnly = universalLinksOnly; this.headers = headers; this.webOnlyWindowName = webOnlyWindowName; } // ignore: use_setters_to_change_properties void setResponse(bool response) { this.response = response; } @override LinkDelegate? get linkDelegate => null; @override Future<bool> canLaunch(String url) async { expect(url, this.url); canLaunchCalled = true; return response!; } @override Future<bool> launch( String url, { required bool useSafariVC, required bool useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, String? webOnlyWindowName, }) async { expect(url, this.url); expect(useSafariVC, this.useSafariVC); expect(useWebView, this.useWebView); expect(enableJavaScript, this.enableJavaScript); expect(enableDomStorage, this.enableDomStorage); expect(universalLinksOnly, this.universalLinksOnly); expect(headers, this.headers); expect(webOnlyWindowName, this.webOnlyWindowName); launchCalled = true; return response!; } @override Future<bool> launchUrl(String url, LaunchOptions options) async { expect(url, this.url); expect(options.mode, launchMode); expect(options.webViewConfiguration.enableJavaScript, enableJavaScript); expect(options.webViewConfiguration.enableDomStorage, enableDomStorage); expect(options.webViewConfiguration.headers, headers); expect(options.webOnlyWindowName, webOnlyWindowName); launchCalled = true; return response!; } @override Future<void> closeWebView() async { closeWebViewCalled = true; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/shared/mock/mock_openai_repository.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart'; import 'package:mocktail/mocktail.dart'; import 'dart:convert'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/text_completion.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart'; import 'package:http/http.dart' as http; import 'dart:async'; class MyMockClient extends Mock implements http.Client { @override Future<http.StreamedResponse> send(http.BaseRequest request) async { final requestType = request.method; final requestUri = request.url; if (requestType == 'POST' && requestUri == OpenAIRequestType.textCompletion.uri) { final responseHeaders = <String, String>{ 'content-type': 'text/event-stream', }; final responseBody = Stream.fromIterable([ utf8.encode( '{ "choices": [{"text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula ", "index": 0, "logprobs": null, "finish_reason": null}]}', ), utf8.encode('\n'), utf8.encode('[DONE]'), ]); // Return a mocked response with the expected data return http.StreamedResponse(responseBody, 200, headers: responseHeaders); } // Return an error response for any other request return http.StreamedResponse(const Stream.empty(), 404); } } class MockOpenAIRepository extends HttpOpenAIRepository { MockOpenAIRepository() : super(apiKey: 'dummyKey', client: MyMockClient()); @override Future<void> getStreamedCompletions({ required String prompt, required Future<void> Function() onStart, required Future<void> Function(TextCompletionResponse response) onProcess, required Future<void> Function() onEnd, required void Function(OpenAIError error) onError, String? suffix, int maxTokens = 2048, double temperature = 0.3, bool useAction = false, }) async { final request = http.Request('POST', OpenAIRequestType.textCompletion.uri); final response = await client.send(request); var previousSyntax = ''; if (response.statusCode == 200) { await for (final chunk in response.stream .transform(const Utf8Decoder()) .transform(const LineSplitter())) { await onStart(); final data = chunk.trim().split('data: '); if (data[0] != '[DONE]') { final response = TextCompletionResponse.fromJson( json.decode(data[0]), ); if (response.choices.isNotEmpty) { final text = response.choices.first.text; if (text == previousSyntax && text == '\n') { continue; } await onProcess(response); previousSyntax = response.choices.first.text; } } else { await onEnd(); } } } return; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/mobile
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/mobile/sign_in/anonymous_sign_in_test.dart
// ignore_for_file: unused_import import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/home/home.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path/path.dart' as p; import '../../shared/dir.dart'; import '../../shared/mock/mock_file_picker.dart'; import '../../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('anonymous sign in on mobile', () { testWidgets('anon user and then sign in', (tester) async { await tester.initializeAppFlowy(); // click the anonymousSignInButton final anonymousSignInButton = find.byType(SignInAnonymousButtonV2); expect(anonymousSignInButton, findsOneWidget); await tester.tapButton(anonymousSignInButton); // expect to see the home page expect(find.byType(MobileHomeScreen), findsOneWidget); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/mobile
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/mobile/home_page/create_new_page_test.dart
// ignore_for_file: unused_import import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/editor/mobile_editor_screen.dart'; import 'package:appflowy/mobile/presentation/home/home.dart'; import 'package:appflowy/mobile/presentation/home/section_folder/mobile_home_section_folder_header.dart'; import 'package:appflowy/plugins/document/document_page.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path/path.dart' as p; import '../../shared/dir.dart'; import '../../shared/mock/mock_file_picker.dart'; import '../../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('create new page', () { testWidgets('create document', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.local, ); // click the anonymousSignInButton final anonymousSignInButton = find.byType(SignInAnonymousButtonV2); expect(anonymousSignInButton, findsOneWidget); await tester.tapButton(anonymousSignInButton); // tap the create page button final createPageButton = find.byKey(mobileCreateNewPageButtonKey); await tester.tapButton(createPageButton); expect(find.byType(MobileDocumentScreen), findsOneWidget); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/supabase_auth_test.dart
import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_supabase_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import '../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('supabase auth', () { testWidgets('sign in with supabase', (tester) async { await tester.initializeAppFlowy(cloudType: AuthenticatorType.supabase); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); }); testWidgets('sign out with supabase', (tester) async { await tester.initializeAppFlowy(cloudType: AuthenticatorType.supabase); await tester.tapGoogleLoginInButton(); // Open the setting page and sign out await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); await tester.tapButton(find.byType(SettingLogoutButton)); tester.expectToSeeText(LocaleKeys.button_ok.tr()); await tester.tapButtonWithName(LocaleKeys.button_ok.tr()); // Go to the sign in page again await tester.pumpAndSettle(const Duration(seconds: 1)); tester.expectToSeeGoogleLoginButton(); }); testWidgets('sign in as anonymous', (tester) async { await tester.initializeAppFlowy(cloudType: AuthenticatorType.supabase); await tester.tapSignInAsGuest(); // should not see the sync setting page when sign in as anonymous await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); tester.expectToSeeGoogleLoginButton(); }); // testWidgets('enable encryption', (tester) async { // await tester.initializeAppFlowy(cloudType: CloudType.supabase); // await tester.tapGoogleLoginInButton(); // // Open the setting page and sign out // await tester.openSettings(); // await tester.openSettingsPage(SettingsPage.cloud); // // the switch should be off by default // tester.assertEnableEncryptSwitchValue(false); // await tester.toggleEnableEncrypt(); // // the switch should be on after toggling // tester.assertEnableEncryptSwitchValue(true); // // the switch can not be toggled back to off // await tester.toggleEnableEncrypt(); // tester.assertEnableEncryptSwitchValue(true); // }); testWidgets('enable sync', (tester) async { await tester.initializeAppFlowy(cloudType: AuthenticatorType.supabase); await tester.tapGoogleLoginInButton(); // Open the setting page and sign out await tester.openSettings(); await tester.openSettingsPage(SettingsPage.cloud); // the switch should be on by default tester.assertSupabaseEnableSyncSwitchValue(true); await tester.toggleEnableSync(SupabaseEnableSync); // the switch should be off tester.assertSupabaseEnableSyncSwitchValue(false); // the switch should be on after toggling await tester.toggleEnableSync(SupabaseEnableSync); tester.assertSupabaseEnableSyncSwitchValue(true); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/cloud_runner.dart
import 'anon_user_continue_test.dart' as anon_user_continue_test; import 'appflowy_cloud_auth_test.dart' as appflowy_cloud_auth_test; import 'empty_test.dart' as preset_af_cloud_env_test; // import 'document_sync_test.dart' as document_sync_test; import 'user_setting_sync_test.dart' as user_sync_test; import 'workspace/change_name_and_icon_test.dart' as change_workspace_name_and_icon_test; import 'workspace/collaborative_workspace_test.dart' as collaboration_workspace_test; Future<void> main() async { preset_af_cloud_env_test.main(); appflowy_cloud_auth_test.main(); // document_sync_test.main(); user_sync_test.main(); anon_user_continue_test.main(); // workspace collaboration_workspace_test.main(); change_workspace_name_and_icon_test.main(); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/document_sync_test.dart
// ignore_for_file: unused_import import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:integration_test/integration_test.dart'; import '../shared/dir.dart'; import '../shared/mock/mock_file_picker.dart'; import '../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); final email = '${uuid()}@appflowy.io'; const inputContent = 'Hello world, this is a test document'; // The test will create a new document called Sample, and sync it to the server. // Then the test will logout the user, and login with the same user. The data will // be synced from the server. group('appflowy cloud document', () { testWidgets('sync local docuemnt to server', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, email: email, ); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); // create a new document called Sample await tester.createNewPage(); // focus on the editor await tester.editor.tapLineOfEditorAt(0); await tester.ime.insertText(inputContent); expect(find.text(inputContent, findRichText: true), findsOneWidget); // TODO(nathan): remove the await // 6 seconds for data sync await tester.waitForSeconds(6); await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); await tester.logout(); }); testWidgets('sync doc from server', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, email: email, ); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePage(); // the latest document will be opened, so the content must be the inputContent await tester.pumpAndSettle(); expect(find.text(inputContent, findRichText: true), findsOneWidget); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/anon_user_continue_test.dart
// ignore_for_file: unused_import import 'dart:io'; import 'dart:ui'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path/path.dart' as p; import '../shared/dir.dart'; import '../shared/mock/mock_file_picker.dart'; import '../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('appflowy cloud', () { testWidgets('anon user and then sign in', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, ); tester.expectToSeeText(LocaleKeys.signIn_loginStartWithAnonymous.tr()); await tester.tapAnonymousSignInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); // reanme the name of the anon user await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); final userNameFinder = find.descendant( of: find.byType(SettingsUserView), matching: find.byType(UserNameInput), ); await tester.enterText(userNameFinder, 'local_user'); await tester.openSettingsPage(SettingsPage.user); await tester.pumpAndSettle(); // sign up with Google await tester.tapGoogleLoginInButton(); // sign out await tester.expectToSeeHomePage(); await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); await tester.logout(); await tester.pumpAndSettle(); // tap the continue as anonymous button await tester .tapButton(find.text(LocaleKeys.signIn_loginStartWithAnonymous.tr())); await tester.expectToSeeHomePage(); // New anon user name await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); final userNameInput = tester.widget(userNameFinder) as UserNameInput; expect(userNameInput.name, 'Me'); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/appflowy_cloud_auth_test.dart
// ignore_for_file: unused_import import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path/path.dart' as p; import '../shared/mock/mock_file_picker.dart'; import '../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('appflowy cloud auth', () { testWidgets('sign in', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, ); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); }); testWidgets('sign out', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, ); await tester.tapGoogleLoginInButton(); // Open the setting page and sign out await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); await tester.tapButton(find.byType(SettingLogoutButton)); tester.expectToSeeText(LocaleKeys.button_ok.tr()); await tester.tapButtonWithName(LocaleKeys.button_ok.tr()); // Go to the sign in page again await tester.pumpAndSettle(const Duration(seconds: 1)); tester.expectToSeeGoogleLoginButton(); }); testWidgets('sign in as anonymous', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, ); await tester.tapSignInAsGuest(); // should not see the sync setting page when sign in as anonymous await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); tester.expectToSeeGoogleLoginButton(); }); testWidgets('enable sync', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, ); await tester.tapGoogleLoginInButton(); // Open the setting page and sign out await tester.openSettings(); await tester.openSettingsPage(SettingsPage.cloud); // the switch should be on by default tester.assertAppFlowyCloudEnableSyncSwitchValue(true); await tester.toggleEnableSync(AppFlowyCloudEnableSync); // the switch should be off tester.assertAppFlowyCloudEnableSyncSwitchValue(false); // the switch should be on after toggling await tester.toggleEnableSync(AppFlowyCloudEnableSync); tester.assertAppFlowyCloudEnableSyncSwitchValue(true); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/empty_test.dart
import 'package:appflowy/env/cloud_env.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import '../shared/util.dart'; // This test is meaningless, just for preventing the CI from failing. void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('Empty', () { testWidgets('set appflowy cloud', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, ); }); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/user_setting_sync_test.dart
// ignore_for_file: unused_import import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy/workspace/presentation/widgets/user_avatar.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:integration_test/integration_test.dart'; import '../shared/database_test_op.dart'; import '../shared/dir.dart'; import '../shared/emoji.dart'; import '../shared/mock/mock_file_picker.dart'; import '../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); final email = '${uuid()}@appflowy.io'; const name = 'nathan'; group('appflowy cloud setting', () { testWidgets('sync user name and icon to server', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, email: email, ); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); // final userAvatarFinder = find.descendant( // of: find.byType(SettingsUserView), // matching: find.byType(UserAvatar), // ); // Open icon picker dialog and select emoji // await tester.tap(userAvatarFinder); // await tester.pumpAndSettle(); // await tester.tapEmoji('😁'); // await tester.pumpAndSettle(); // final UserAvatar userAvatar = // tester.widget(userAvatarFinder) as UserAvatar; // expect(userAvatar.iconUrl, '😁'); // enter user name final userNameFinder = find.descendant( of: find.byType(SettingsUserView), matching: find.byType(UserNameInput), ); await tester.enterText(userNameFinder, name); await tester.pumpAndSettle(); await tester.tapEscButton(); // wait 2 seconds for the sync to finish await tester.pumpAndSettle(const Duration(seconds: 2)); }); }); testWidgets('get user icon and name from server', (tester) async { await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, email: email, ); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); await tester.pumpAndSettle(); await tester.openSettings(); await tester.openSettingsPage(SettingsPage.user); // verify icon // final userAvatarFinder = find.descendant( // of: find.byType(SettingsUserView), // matching: find.byType(UserAvatar), // ); // final UserAvatar userAvatar = tester.widget(userAvatarFinder) as UserAvatar; // expect(userAvatar.iconUrl, '😁'); // verify name final userNameFinder = find.descendant( of: find.byType(SettingsUserView), matching: find.byType(UserNameInput), ); final UserNameInput userNameInput = tester.widget(userNameFinder) as UserNameInput; expect(userNameInput.name, name); }); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/integration_test/cloud/workspace/collaborative_workspace_test.dart
// ignore_for_file: unused_import import 'dart:io'; import 'package:appflowy/env/cloud_env.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart'; import 'package:appflowy/shared/feature_flags.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/sidebar_workspace.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_actions.dart'; import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart'; import 'package:appflowy/workspace/presentation/widgets/user_avatar.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path/path.dart' as p; import '../../shared/database_test_op.dart'; import '../../shared/dir.dart'; import '../../shared/emoji.dart'; import '../../shared/mock/mock_file_picker.dart'; import '../../shared/util.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); final email = '${uuid()}@appflowy.io'; group('collaborative workspace', () { // combine the create and delete workspace test to reduce the time testWidgets('create a new workspace, open it and then delete it', (tester) async { // only run the test when the feature flag is on if (!FeatureFlag.collaborativeWorkspace.isOn) { return; } await tester.initializeAppFlowy( cloudType: AuthenticatorType.appflowyCloudSelfHost, email: email, ); await tester.tapGoogleLoginInButton(); await tester.expectToSeeHomePageWithGetStartedPage(); const name = 'AppFlowy.IO'; // the workspace will be opened after created await tester.createCollaborativeWorkspace(name); final loading = find.byType(Loading); await tester.pumpUntilNotFound(loading); Finder success; // delete the newly created workspace await tester.openCollaborativeWorkspaceMenu(); final Finder items = find.byType(WorkspaceMenuItem); expect(items, findsNWidgets(2)); expect( tester.widget<WorkspaceMenuItem>(items.last).workspace.name, name, ); final secondWorkspace = find.byType(WorkspaceMenuItem).last; await tester.hoverOnWidget( secondWorkspace, onHover: () async { // click the more button final moreButton = find.byType(WorkspaceMoreActionList); expect(moreButton, findsOneWidget); await tester.tapButton(moreButton); // click the delete button final deleteButton = find.text(LocaleKeys.button_delete.tr()); expect(deleteButton, findsOneWidget); await tester.tapButton(deleteButton); // see the delete confirm dialog final confirm = find.text(LocaleKeys.workspace_deleteWorkspaceHintText.tr()); expect(confirm, findsOneWidget); await tester.tapButton(find.text(LocaleKeys.button_ok.tr())); // delete success success = find.text(LocaleKeys.workspace_createSuccess.tr()); await tester.pumpUntilFound(success); expect(success, findsOneWidget); await tester.pumpUntilNotFound(success); }, ); }); }); }
0