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/mobile_toolbar_v3/appflowy_mobile_toolbar_item.dart
import 'dart:async'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/appflowy_mobile_toolbar.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; // build the toolbar item, like Aa, +, image ... typedef AppFlowyMobileToolbarItemBuilder = Widget Function( BuildContext context, EditorState editorState, AppFlowyMobileToolbarWidgetService service, VoidCallback? onMenuCallback, VoidCallback? onActionCallback, ); // build the menu after clicking the toolbar item typedef AppFlowyMobileToolbarItemMenuBuilder = Widget Function( BuildContext context, EditorState editorState, AppFlowyMobileToolbarWidgetService service, ); class AppFlowyMobileToolbarItem { /// Tool bar item that implements attribute directly(without opening menu) const AppFlowyMobileToolbarItem({ required this.itemBuilder, this.menuBuilder, this.pilotAtCollapsedSelection = false, this.pilotAtExpandedSelection = false, }); final AppFlowyMobileToolbarItemBuilder itemBuilder; final AppFlowyMobileToolbarItemMenuBuilder? menuBuilder; final bool pilotAtCollapsedSelection; final bool pilotAtExpandedSelection; } class AppFlowyMobileToolbarIconItem extends StatefulWidget { const AppFlowyMobileToolbarIconItem({ super.key, this.icon, this.keepSelectedStatus = false, this.iconBuilder, this.isSelected, this.shouldListenToToggledStyle = false, this.enable, required this.onTap, required this.editorState, }); final FlowySvgData? icon; final bool keepSelectedStatus; final VoidCallback onTap; final WidgetBuilder? iconBuilder; final bool Function()? isSelected; final bool shouldListenToToggledStyle; final EditorState editorState; final bool Function()? enable; @override State<AppFlowyMobileToolbarIconItem> createState() => _AppFlowyMobileToolbarIconItemState(); } class _AppFlowyMobileToolbarIconItemState extends State<AppFlowyMobileToolbarIconItem> { bool isSelected = false; StreamSubscription? _subscription; @override void initState() { super.initState(); isSelected = widget.isSelected?.call() ?? false; if (widget.shouldListenToToggledStyle) { widget.editorState.toggledStyleNotifier.addListener(_rebuild); _subscription = widget.editorState.transactionStream.listen((_) { _rebuild(); }); } } @override void dispose() { if (widget.shouldListenToToggledStyle) { widget.editorState.toggledStyleNotifier.removeListener(_rebuild); _subscription?.cancel(); } super.dispose(); } @override void didUpdateWidget(covariant AppFlowyMobileToolbarIconItem oldWidget) { super.didUpdateWidget(oldWidget); if (widget.isSelected != null) { isSelected = widget.isSelected!.call(); } } @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); final enable = widget.enable?.call() ?? true; return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { widget.onTap(); _rebuild(); }, child: widget.iconBuilder?.call(context) ?? Container( width: 40, padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(9), color: isSelected ? theme.toolbarItemSelectedBackgroundColor : null, ), child: FlowySvg( widget.icon!, color: enable ? theme.toolbarItemIconColor : theme.toolbarItemIconDisabledColor, ), ), ), ); } void _rebuild() { if (!context.mounted) { return; } setState(() { isSelected = (widget.keepSelectedStatus && widget.isSelected == null) ? !isSelected : widget.isSelected?.call() ?? 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/mobile_toolbar_v3/add_block_toolbar_item.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/type_option_menu_item.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_placeholder.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_item/mobile_add_block_toolbar_item.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/startup/tasks/app_widget.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:go_router/go_router.dart'; final addBlockToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, service, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, icon: FlowySvgs.m_toolbar_add_m, onTap: () { final selection = editorState.selection; service.closeKeyboard(); // delay to wait the keyboard closed. Future.delayed(const Duration(milliseconds: 100), () async { unawaited( editorState.updateSelectionWithReason( selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDoNotAttachTextService: true, }, ), ); keepEditorFocusNotifier.increase(); final didAddBlock = await showAddBlockMenu( AppGlobals.rootNavKey.currentContext!, editorState: editorState, selection: selection!, ); if (didAddBlock != true) { unawaited( editorState.updateSelectionWithReason( selection, ), ); } }); }, ); }, ); Future<bool?> showAddBlockMenu( BuildContext context, { required EditorState editorState, required Selection selection, }) async { final theme = ToolbarColorExtension.of(context); return showMobileBottomSheet<bool>( context, showHeader: true, showDragHandle: true, showCloseButton: true, title: LocaleKeys.button_add.tr(), barrierColor: Colors.transparent, backgroundColor: theme.toolbarMenuBackgroundColor, elevation: 20, enableDraggableScrollable: true, builder: (context) { return Padding( padding: EdgeInsets.all(16 * context.scale), child: _AddBlockMenu( selection: selection, editorState: editorState, ), ); }, ); } class _AddBlockMenu extends StatelessWidget { const _AddBlockMenu({ required this.selection, required this.editorState, }); final Selection selection; final EditorState editorState; @override Widget build(BuildContext context) { return TypeOptionMenu<String>( values: buildTypeOptionMenuItemValues(context), scaleFactor: context.scale, ); } Future<void> _insertBlock(Node node) async { AppGlobals.rootNavKey.currentContext?.pop(true); Future.delayed(const Duration(milliseconds: 100), () { editorState.insertBlockAfterCurrentSelection( selection, node, ); }); } List<TypeOptionMenuItemValue<String>> buildTypeOptionMenuItemValues( BuildContext context, ) { final colorMap = _colorMap(context); return [ // heading 1 - 3 TypeOptionMenuItemValue( value: HeadingBlockKeys.type, backgroundColor: colorMap[HeadingBlockKeys.type]!, text: LocaleKeys.editor_heading1.tr(), icon: FlowySvgs.m_add_block_h1_s, onTap: (_, __) => _insertBlock(headingNode(level: 1)), ), TypeOptionMenuItemValue( value: HeadingBlockKeys.type, backgroundColor: colorMap[HeadingBlockKeys.type]!, text: LocaleKeys.editor_heading2.tr(), icon: FlowySvgs.m_add_block_h2_s, onTap: (_, __) => _insertBlock(headingNode(level: 2)), ), TypeOptionMenuItemValue( value: HeadingBlockKeys.type, backgroundColor: colorMap[HeadingBlockKeys.type]!, text: LocaleKeys.editor_heading3.tr(), icon: FlowySvgs.m_add_block_h3_s, onTap: (_, __) => _insertBlock(headingNode(level: 3)), ), // paragraph TypeOptionMenuItemValue( value: ParagraphBlockKeys.type, backgroundColor: colorMap[ParagraphBlockKeys.type]!, text: LocaleKeys.editor_text.tr(), icon: FlowySvgs.m_add_block_paragraph_s, onTap: (_, __) => _insertBlock(paragraphNode()), ), // checkbox TypeOptionMenuItemValue( value: TodoListBlockKeys.type, backgroundColor: colorMap[TodoListBlockKeys.type]!, text: LocaleKeys.editor_checkbox.tr(), icon: FlowySvgs.m_add_block_checkbox_s, onTap: (_, __) => _insertBlock(todoListNode(checked: false)), ), // quote TypeOptionMenuItemValue( value: QuoteBlockKeys.type, backgroundColor: colorMap[QuoteBlockKeys.type]!, text: LocaleKeys.editor_quote.tr(), icon: FlowySvgs.m_add_block_quote_s, onTap: (_, __) => _insertBlock(quoteNode()), ), // bulleted list, numbered list, toggle list TypeOptionMenuItemValue( value: BulletedListBlockKeys.type, backgroundColor: colorMap[BulletedListBlockKeys.type]!, text: LocaleKeys.editor_bulletedListShortForm.tr(), icon: FlowySvgs.m_add_block_bulleted_list_s, onTap: (_, __) => _insertBlock(bulletedListNode()), ), TypeOptionMenuItemValue( value: NumberedListBlockKeys.type, backgroundColor: colorMap[NumberedListBlockKeys.type]!, text: LocaleKeys.editor_numberedListShortForm.tr(), icon: FlowySvgs.m_add_block_numbered_list_s, onTap: (_, __) => _insertBlock(numberedListNode()), ), TypeOptionMenuItemValue( value: ToggleListBlockKeys.type, backgroundColor: colorMap[ToggleListBlockKeys.type]!, text: LocaleKeys.editor_toggleListShortForm.tr(), icon: FlowySvgs.m_add_block_toggle_s, onTap: (_, __) => _insertBlock(toggleListBlockNode()), ), // image TypeOptionMenuItemValue( value: ImageBlockKeys.type, backgroundColor: colorMap[ImageBlockKeys.type]!, text: LocaleKeys.editor_image.tr(), icon: FlowySvgs.m_add_block_image_s, onTap: (_, __) async { AppGlobals.rootNavKey.currentContext?.pop(true); Future.delayed(const Duration(milliseconds: 400), () async { final imagePlaceholderKey = GlobalKey<ImagePlaceholderState>(); await editorState.insertEmptyImageBlock(imagePlaceholderKey); }); }, ), // date TypeOptionMenuItemValue( value: ParagraphBlockKeys.type, backgroundColor: colorMap['date']!, text: LocaleKeys.editor_date.tr(), icon: FlowySvgs.m_add_block_date_s, onTap: (_, __) => _insertBlock(dateMentionNode()), ), // divider TypeOptionMenuItemValue( value: DividerBlockKeys.type, backgroundColor: colorMap[DividerBlockKeys.type]!, text: LocaleKeys.editor_divider.tr(), icon: FlowySvgs.m_add_block_divider_s, onTap: (_, __) { AppGlobals.rootNavKey.currentContext?.pop(true); Future.delayed(const Duration(milliseconds: 100), () { editorState.insertDivider(selection); }); }, ), // callout, code, math equation TypeOptionMenuItemValue( value: CalloutBlockKeys.type, backgroundColor: colorMap[CalloutBlockKeys.type]!, text: LocaleKeys.document_plugins_callout.tr(), icon: FlowySvgs.m_add_block_callout_s, onTap: (_, __) => _insertBlock(calloutNode()), ), TypeOptionMenuItemValue( value: CodeBlockKeys.type, backgroundColor: colorMap[CodeBlockKeys.type]!, text: LocaleKeys.editor_codeBlockShortForm.tr(), icon: FlowySvgs.m_add_block_code_s, onTap: (_, __) => _insertBlock(codeBlockNode()), ), TypeOptionMenuItemValue( value: MathEquationBlockKeys.type, backgroundColor: colorMap[MathEquationBlockKeys.type]!, text: LocaleKeys.editor_mathEquationShortForm.tr(), icon: FlowySvgs.m_add_block_formula_s, onTap: (_, __) { AppGlobals.rootNavKey.currentContext?.pop(true); Future.delayed(const Duration(milliseconds: 100), () { editorState.insertMathEquation(selection); }); }, ), ]; } Map<String, Color> _colorMap(BuildContext context) { final isDarkMode = Theme.of(context).brightness == Brightness.dark; if (isDarkMode) { return { HeadingBlockKeys.type: const Color(0xFF5465A1), ParagraphBlockKeys.type: const Color(0xFF5465A1), TodoListBlockKeys.type: const Color(0xFF4BB299), QuoteBlockKeys.type: const Color(0xFFBAAC74), BulletedListBlockKeys.type: const Color(0xFFA35F94), NumberedListBlockKeys.type: const Color(0xFFA35F94), ToggleListBlockKeys.type: const Color(0xFFA35F94), ImageBlockKeys.type: const Color(0xFFBAAC74), 'date': const Color(0xFF40AAB8), DividerBlockKeys.type: const Color(0xFF4BB299), CalloutBlockKeys.type: const Color(0xFF66599B), CodeBlockKeys.type: const Color(0xFF66599B), MathEquationBlockKeys.type: const Color(0xFF66599B), }; } return { HeadingBlockKeys.type: const Color(0xFFBECCFF), ParagraphBlockKeys.type: const Color(0xFFBECCFF), TodoListBlockKeys.type: const Color(0xFF98F4CD), QuoteBlockKeys.type: const Color(0xFFFDEDA7), BulletedListBlockKeys.type: const Color(0xFFFFB9EF), NumberedListBlockKeys.type: const Color(0xFFFFB9EF), ToggleListBlockKeys.type: const Color(0xFFFFB9EF), ImageBlockKeys.type: const Color(0xFFFDEDA7), 'date': const Color(0xFF91EAF5), DividerBlockKeys.type: const Color(0xFF98F4CD), CalloutBlockKeys.type: const Color(0xFFCABDFF), CodeBlockKeys.type: const Color(0xFFCABDFF), MathEquationBlockKeys.type: const Color(0xFFCABDFF), }; } } extension on EditorState { Future<void> insertBlockAfterCurrentSelection( Selection selection, Node node, ) async { final path = selection.end.path.next; final transaction = this.transaction; transaction.insertNode( path, node, ); transaction.afterSelection = Selection.collapsed( Position(path: path), ); transaction.selectionExtraInfo = {}; await 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/mobile_toolbar_v3/more_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; final moreToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, icon: FlowySvgs.m_toolbar_more_s, 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/mobile_toolbar_v3/appflowy_mobile_toolbar.dart
import 'dart:async'; import 'dart:io'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_close_keyboard_or_menu_button.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/appflowy_mobile_toolbar_item.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/keyboard_height_observer.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:scrollable_positioned_list/scrollable_positioned_list.dart'; abstract class AppFlowyMobileToolbarWidgetService { void closeItemMenu(); void closeKeyboard(); PropertyValueNotifier<bool> get showMenuNotifier; } class AppFlowyMobileToolbar extends StatefulWidget { const AppFlowyMobileToolbar({ super.key, this.toolbarHeight = 50.0, required this.editorState, required this.toolbarItemsBuilder, required this.child, }); final EditorState editorState; final double toolbarHeight; final List<AppFlowyMobileToolbarItem> Function( Selection? selection, ) toolbarItemsBuilder; final Widget child; @override State<AppFlowyMobileToolbar> createState() => _AppFlowyMobileToolbarState(); } class _AppFlowyMobileToolbarState extends State<AppFlowyMobileToolbar> { OverlayEntry? toolbarOverlay; final isKeyboardShow = ValueNotifier(false); @override void initState() { super.initState(); _insertKeyboardToolbar(); KeyboardHeightObserver.instance.addListener(_onKeyboardHeightChanged); } @override void dispose() { _removeKeyboardToolbar(); KeyboardHeightObserver.instance.removeListener(_onKeyboardHeightChanged); super.dispose(); } @override Widget build(BuildContext context) { return Column( children: [ Expanded( child: widget.child, ), // add a bottom offset to make sure the toolbar is above the keyboard ValueListenableBuilder( valueListenable: isKeyboardShow, builder: (context, isKeyboardShow, __) { return AnimatedContainer( duration: const Duration(milliseconds: 110), height: isKeyboardShow ? widget.toolbarHeight : 0, ); }, ), ], ); } void _onKeyboardHeightChanged(double height) { isKeyboardShow.value = height > 0; } void _removeKeyboardToolbar() { toolbarOverlay?.remove(); toolbarOverlay?.dispose(); toolbarOverlay = null; } void _insertKeyboardToolbar() { _removeKeyboardToolbar(); Widget child = ValueListenableBuilder<Selection?>( valueListenable: widget.editorState.selectionNotifier, builder: (_, Selection? selection, __) { // if the selection is null, hide the toolbar if (selection == null || widget.editorState.selectionExtraInfo?[ selectionExtraInfoDisableMobileToolbarKey] == true) { return const SizedBox.shrink(); } return RepaintBoundary( child: _MobileToolbar( editorState: widget.editorState, toolbarItems: widget.toolbarItemsBuilder(selection), toolbarHeight: widget.toolbarHeight, ), ); }, ); child = Stack( children: [ Positioned( left: 0, right: 0, bottom: 0, child: Material( child: child, ), ), ], ); final router = GoRouter.of(context); toolbarOverlay = OverlayEntry( builder: (context) { return Provider.value( value: router, child: child, ); }, ); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { Overlay.of(context, rootOverlay: true).insert(toolbarOverlay!); }); } } class _MobileToolbar extends StatefulWidget { const _MobileToolbar({ required this.editorState, required this.toolbarItems, required this.toolbarHeight, }); final EditorState editorState; final List<AppFlowyMobileToolbarItem> toolbarItems; final double toolbarHeight; @override State<_MobileToolbar> createState() => _MobileToolbarState(); } class _MobileToolbarState extends State<_MobileToolbar> implements AppFlowyMobileToolbarWidgetService { // used to control the toolbar menu items @override PropertyValueNotifier<bool> showMenuNotifier = PropertyValueNotifier(false); // when the users click the menu item, the keyboard will be hidden, // but in this case, we don't want to update the cached keyboard height. // This is because we want to keep the same height when the menu is shown. bool canUpdateCachedKeyboardHeight = true; ValueNotifier<double> cachedKeyboardHeight = ValueNotifier(0.0); // used to check if click the same item again int? selectedMenuIndex; Selection? currentSelection; bool closeKeyboardInitiative = false; final ScrollOffsetListener offsetListener = ScrollOffsetListener.create(); late final StreamSubscription offsetSubscription; ValueNotifier<double> toolbarOffset = ValueNotifier(0.0); @override void initState() { super.initState(); currentSelection = widget.editorState.selection; KeyboardHeightObserver.instance.addListener(_onKeyboardHeightChanged); offsetSubscription = offsetListener.changes.listen((event) { toolbarOffset.value += event; }); } @override void didUpdateWidget(covariant _MobileToolbar oldWidget) { super.didUpdateWidget(oldWidget); if (currentSelection != widget.editorState.selection) { currentSelection = widget.editorState.selection; closeItemMenu(); if (currentSelection != null) { _showKeyboard(); } } } @override void dispose() { showMenuNotifier.dispose(); cachedKeyboardHeight.dispose(); KeyboardHeightObserver.instance.removeListener(_onKeyboardHeightChanged); offsetSubscription.cancel(); toolbarOffset.dispose(); super.dispose(); } @override void reassemble() { super.reassemble(); canUpdateCachedKeyboardHeight = true; closeItemMenu(); _closeKeyboard(); } @override Widget build(BuildContext context) { // toolbar // - if the menu is shown, the toolbar will be pushed up by the height of the menu // - otherwise, add a spacer to push the toolbar up when the keyboard is shown return Column( children: [ const Divider( height: 0.5, color: Color(0xFFEDEDED), ), _buildToolbar(context), const Divider( height: 0.5, color: Color(0xFFEDEDED), ), _buildMenuOrSpacer(context), ], ); } @override void closeItemMenu() { showMenuNotifier.value = false; } @override void closeKeyboard() { _closeKeyboard(); } void showItemMenu() { showMenuNotifier.value = true; } void _onKeyboardHeightChanged(double height) { // if the keyboard is not closed initiative, we need to close the menu at same time if (!closeKeyboardInitiative && cachedKeyboardHeight.value != 0 && height == 0) { widget.editorState.selection = null; } // if the menu is shown and the height is not 0, we need to close the menu if (showMenuNotifier.value && height != 0) { closeItemMenu(); } if (canUpdateCachedKeyboardHeight) { cachedKeyboardHeight.value = height; } if (height == 0) { closeKeyboardInitiative = false; } } // toolbar list view and close keyboard/menu button Widget _buildToolbar(BuildContext context) { final theme = ToolbarColorExtension.of(context); return Container( height: widget.toolbarHeight, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: theme.toolbarBackgroundColor, boxShadow: const [ BoxShadow( color: Color(0x0F181818), blurRadius: 40, offset: Offset(0, -4), ), ], ), child: Row( mainAxisSize: MainAxisSize.min, children: [ // toolbar list view Expanded( child: _ToolbarItemListView( offsetListener: offsetListener, toolbarItems: widget.toolbarItems, editorState: widget.editorState, toolbarWidgetService: this, itemWithActionOnPressed: (_) { if (showMenuNotifier.value) { closeItemMenu(); _showKeyboard(); // update the cached keyboard height after the keyboard is shown Debounce.debounce('canUpdateCachedKeyboardHeight', const Duration(milliseconds: 500), () { canUpdateCachedKeyboardHeight = true; }); } }, itemWithMenuOnPressed: (index) { // click the same one if (selectedMenuIndex == index && showMenuNotifier.value) { // if the menu is shown, close it and show the keyboard closeItemMenu(); _showKeyboard(); // update the cached keyboard height after the keyboard is shown Debounce.debounce('canUpdateCachedKeyboardHeight', const Duration(milliseconds: 500), () { canUpdateCachedKeyboardHeight = true; }); } else { canUpdateCachedKeyboardHeight = false; selectedMenuIndex = index; showItemMenu(); closeKeyboardInitiative = true; _closeKeyboard(); } }, ), ), const Padding( padding: EdgeInsets.symmetric(vertical: 13.0), child: VerticalDivider( width: 1.0, thickness: 1.0, color: Color(0xFFD9D9D9), ), ), // close menu or close keyboard button CloseKeyboardOrMenuButton( onPressed: () { closeKeyboardInitiative = true; // close the keyboard and clear the selection // if the selection is null, the keyboard and the toolbar will be hidden automatically widget.editorState.selection = null; // sometimes, the keyboard is not closed after the selection is cleared if (Platform.isAndroid) { SystemChannels.textInput.invokeMethod('TextInput.hide'); } }, ), const HSpace(4.0), ], ), ); } // if there's no menu, we need to add a spacer to push the toolbar up when the keyboard is shown Widget _buildMenuOrSpacer(BuildContext context) { return ValueListenableBuilder( valueListenable: cachedKeyboardHeight, builder: (_, height, ___) { return AnimatedContainer( duration: const Duration(microseconds: 110), height: height, child: ValueListenableBuilder( valueListenable: showMenuNotifier, builder: (_, showingMenu, __) { return AnimatedContainer( duration: const Duration(microseconds: 110), height: height, child: (showingMenu && selectedMenuIndex != null) ? widget.toolbarItems[selectedMenuIndex!].menuBuilder?.call( context, widget.editorState, this, ) ?? const SizedBox.shrink() : const SizedBox.shrink(), ); }, ), ); }, ); } void _showKeyboard() { final selection = widget.editorState.selection; if (selection != null) { widget.editorState.service.keyboardService?.enableKeyBoard(selection); } } void _closeKeyboard() { widget.editorState.service.keyboardService?.closeKeyboard(); } } class _ToolbarItemListView extends StatefulWidget { const _ToolbarItemListView({ required this.offsetListener, required this.toolbarItems, required this.editorState, required this.toolbarWidgetService, required this.itemWithMenuOnPressed, required this.itemWithActionOnPressed, }); final Function(int index) itemWithMenuOnPressed; final Function(int index) itemWithActionOnPressed; final List<AppFlowyMobileToolbarItem> toolbarItems; final EditorState editorState; final AppFlowyMobileToolbarWidgetService toolbarWidgetService; final ScrollOffsetListener offsetListener; @override State<_ToolbarItemListView> createState() => _ToolbarItemListViewState(); } class _ToolbarItemListViewState extends State<_ToolbarItemListView> { final scrollController = ItemScrollController(); Selection? previousSelection; @override void initState() { super.initState(); widget.editorState.selectionNotifier .addListener(_debounceUpdatePilotPosition); previousSelection = widget.editorState.selection; } @override void dispose() { widget.editorState.selectionNotifier .removeListener(_debounceUpdatePilotPosition); super.dispose(); } @override Widget build(BuildContext context) { final children = [ const HSpace(8), ...widget.toolbarItems .mapIndexed( (index, element) => element.itemBuilder.call( context, widget.editorState, widget.toolbarWidgetService, element.menuBuilder != null ? () { widget.itemWithMenuOnPressed(index); } : null, element.menuBuilder == null ? () { widget.itemWithActionOnPressed(index); } : null, ), ) .map((e) => [e, const HSpace(10)]) .flattened, const HSpace(4), ]; return PageStorage( bucket: PageStorageBucket(), child: ScrollablePositionedList.builder( physics: const ClampingScrollPhysics(), scrollOffsetListener: widget.offsetListener, itemScrollController: scrollController, scrollDirection: Axis.horizontal, itemBuilder: (context, index) => children[index], itemCount: children.length, ), ); } void _debounceUpdatePilotPosition() { Debounce.debounce( 'updatePilotPosition', const Duration(milliseconds: 250), _updatePilotPosition, ); } void _updatePilotPosition() { final selection = widget.editorState.selection; if (selection == null) { return; } if (previousSelection != null && previousSelection!.isCollapsed == selection.isCollapsed) { return; } final toolbarItems = widget.toolbarItems; // use -0.4 to make sure the pilot is in the front of the toolbar item final alignment = selection.isCollapsed ? 0.0 : -0.4; final index = toolbarItems.indexWhere( (element) => selection.isCollapsed ? element.pilotAtCollapsedSelection : element.pilotAtExpandedSelection, ); if (index != -1) { scrollController.scrollTo( alignment: alignment, index: index, duration: const Duration( milliseconds: 250, ), ); } previousSelection = selection; } } // class _MyClipper extends CustomClipper<Rect> { // const _MyClipper({ // this.offset = 0, // }); // final double offset; // @override // Rect getClip(Size size) => Rect.fromLTWH(offset, 0, 64.0, 46.0); // @override // bool shouldReclip(CustomClipper<Rect> oldClipper) => 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/mobile_toolbar_v3/list_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; final todoListToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, keepSelectedStatus: true, isSelected: () => false, icon: FlowySvgs.m_toolbar_checkbox_m, onTap: () async { await editorState.convertBlockType( TodoListBlockKeys.type, extraAttributes: { TodoListBlockKeys.checked: false, }, ); }, ); }, ); final numberedListToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { final isSelected = editorState.isBlockTypeSelected(NumberedListBlockKeys.type); return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, keepSelectedStatus: true, isSelected: () => isSelected, icon: FlowySvgs.m_toolbar_numbered_list_m, onTap: () async { await editorState.convertBlockType( NumberedListBlockKeys.type, ); }, ); }, ); final bulletedListToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { final isSelected = editorState.isBlockTypeSelected(BulletedListBlockKeys.type); return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, keepSelectedStatus: true, isSelected: () => isSelected, icon: FlowySvgs.m_toolbar_bulleted_list_m, onTap: () async { await editorState.convertBlockType( BulletedListBlockKeys.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/mobile_toolbar_v3/toolbar_item_builder.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; final _listBlockTypes = [ BulletedListBlockKeys.type, NumberedListBlockKeys.type, TodoListBlockKeys.type, ]; final _defaultToolbarItems = [ addBlockToolbarItem, aaToolbarItem, todoListToolbarItem, bulletedListToolbarItem, numberedListToolbarItem, boldToolbarItem, italicToolbarItem, underlineToolbarItem, strikethroughToolbarItem, colorToolbarItem, undoToolbarItem, redoToolbarItem, ]; final _listToolbarItems = [ addBlockToolbarItem, aaToolbarItem, outdentToolbarItem, indentToolbarItem, todoListToolbarItem, bulletedListToolbarItem, numberedListToolbarItem, boldToolbarItem, italicToolbarItem, underlineToolbarItem, strikethroughToolbarItem, colorToolbarItem, undoToolbarItem, redoToolbarItem, ]; final _textToolbarItems = [ aaToolbarItem, boldToolbarItem, italicToolbarItem, underlineToolbarItem, strikethroughToolbarItem, colorToolbarItem, ]; /// Calculate the toolbar items based on the current selection. /// /// Default: /// Add, Aa, Todo List, Image, Bulleted List, Numbered List, B, I, U, S, Color, Undo, Redo /// /// Selecting text: /// Aa, B, I, U, S, Color /// /// Selecting a list: /// Add, Aa, Indent, Outdent, Bulleted List, Numbered List, Todo List B, I, U, S List<AppFlowyMobileToolbarItem> buildMobileToolbarItems( EditorState editorState, Selection? selection, ) { if (selection == null) { return []; } if (!selection.isCollapsed) { return _textToolbarItems; } final allSelectedAreListType = editorState .getSelectedNodes(selection: selection) .every((node) => _listBlockTypes.contains(node.type)); if (allSelectedAreListType) { return _listToolbarItems; } return _defaultToolbarItems; }
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/mobile_toolbar_v3/_get_selection_color.dart
import 'package:appflowy_editor/appflowy_editor.dart'; extension SelectionColor on EditorState { String? getSelectionColor(String key) { final selection = this.selection; if (selection == null) { return null; } String? color = toggledStyle[key]; if (color == null) { if (selection.isCollapsed && selection.startIndex != 0) { color = getDeltaAttributeValueInSelection<String>( key, selection.copyWith( start: selection.start.copyWith( offset: selection.startIndex - 1, ), ), ); } else { color = getDeltaAttributeValueInSelection<String>( key, ); } } return 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/mobile_toolbar_v3/biusc_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_color_list.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/widgets.dart'; final boldToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, isSelected: () => editorState.isTextDecorationSelected( AppFlowyRichTextKeys.bold, ) && editorState.toggledStyle[AppFlowyRichTextKeys.bold] != false, icon: FlowySvgs.m_toolbar_bold_m, onTap: () async => editorState.toggleAttribute( AppFlowyRichTextKeys.bold, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, }, ), ); }, ); final italicToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, isSelected: () => editorState.isTextDecorationSelected( AppFlowyRichTextKeys.italic, ), icon: FlowySvgs.m_toolbar_italic_m, onTap: () async => editorState.toggleAttribute( AppFlowyRichTextKeys.italic, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, }, ), ); }, ); final underlineToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, isSelected: () => editorState.isTextDecorationSelected( AppFlowyRichTextKeys.underline, ), icon: FlowySvgs.m_toolbar_underline_m, onTap: () async => editorState.toggleAttribute( AppFlowyRichTextKeys.underline, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, }, ), ); }, ); final strikethroughToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, isSelected: () => editorState.isTextDecorationSelected( AppFlowyRichTextKeys.strikethrough, ), icon: FlowySvgs.m_toolbar_strike_m, onTap: () async => editorState.toggleAttribute( AppFlowyRichTextKeys.strikethrough, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, }, ), ); }, ); final colorToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, service, __, onAction) { return AppFlowyMobileToolbarIconItem( editorState: editorState, shouldListenToToggledStyle: true, icon: FlowySvgs.m_aa_font_color_m, iconBuilder: (context) { String? getColor(String key) { final selection = editorState.selection; if (selection == null) { return null; } String? color = editorState.toggledStyle[key]; if (color == null) { if (selection.isCollapsed && selection.startIndex != 0) { color = editorState.getDeltaAttributeValueInSelection<String>( key, selection.copyWith( start: selection.start.copyWith( offset: selection.startIndex - 1, ), ), ); } else { color = editorState.getDeltaAttributeValueInSelection<String>( key, ); } } return color; } final textColor = getColor(AppFlowyRichTextKeys.textColor); final backgroundColor = getColor(AppFlowyRichTextKeys.backgroundColor); return Container( width: 40, padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(9), color: backgroundColor?.tryToColor(), ), child: FlowySvg( FlowySvgs.m_aa_font_color_m, color: textColor?.tryToColor(), ), ); }, onTap: () { service.closeKeyboard(); editorState.updateSelectionWithReason( editorState.selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDoNotAttachTextService: true, }, ); keepEditorFocusNotifier.increase(); showTextColorAndBackgroundColorPicker( context, editorState: editorState, selection: 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/mobile_toolbar_v3/undo_redo_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/widgets.dart'; final undoToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { final theme = ToolbarColorExtension.of(context); return AppFlowyMobileToolbarIconItem( editorState: editorState, iconBuilder: (context) { final canUndo = editorState.undoManager.undoStack.isNonEmpty; return Container( width: 40, padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(9), ), child: FlowySvg( FlowySvgs.m_toolbar_undo_m, color: canUndo ? theme.toolbarItemIconColor : theme.toolbarItemIconDisabledColor, ), ); }, onTap: () => undoCommand.execute(editorState), ); }, ); final redoToolbarItem = AppFlowyMobileToolbarItem( itemBuilder: (context, editorState, _, __, onAction) { final theme = ToolbarColorExtension.of(context); return AppFlowyMobileToolbarIconItem( editorState: editorState, iconBuilder: (context) { final canRedo = editorState.undoManager.redoStack.isNonEmpty; return Container( width: 40, padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(9), ), child: FlowySvg( FlowySvgs.m_toolbar_redo_m, color: canRedo ? theme.toolbarItemIconColor : theme.toolbarItemIconDisabledColor, ), ); }, onTap: () => redoCommand.execute(editorState), ); }, );
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_popup_menu.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class PopupMenu extends StatefulWidget { const PopupMenu({ super.key, required this.onSelected, required this.itemLength, required this.menuBuilder, required this.builder, }); final Widget Function(BuildContext context, Key key) builder; final int itemLength; final Widget Function( BuildContext context, List<GlobalKey> keys, int currentIndex, ) menuBuilder; final void Function(int index) onSelected; @override State<PopupMenu> createState() => _PopupMenuState(); } class _PopupMenuState extends State<PopupMenu> { final key = GlobalKey(); final indexNotifier = ValueNotifier(-1); late List<GlobalKey> itemKeys; OverlayEntry? popupMenuOverlayEntry; Rect get rect { final RenderBox renderBox = key.currentContext!.findRenderObject() as RenderBox; final size = renderBox.size; final offset = renderBox.localToGlobal(Offset.zero); return Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height); } @override void initState() { super.initState(); indexNotifier.value = widget.itemLength - 1; itemKeys = List.generate( widget.itemLength, (_) => GlobalKey(), ); indexNotifier.addListener(HapticFeedback.mediumImpact); } @override void dispose() { indexNotifier.removeListener(HapticFeedback.mediumImpact); indexNotifier.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, onLongPressStart: (details) { _showMenu(context); }, onLongPressMoveUpdate: (details) { _updateSelection(details); }, onLongPressCancel: () { _hideMenu(); }, onLongPressUp: () { if (indexNotifier.value != -1) { widget.onSelected(indexNotifier.value); } _hideMenu(); }, child: widget.builder(context, key), ); } void _showMenu(BuildContext context) { final theme = ToolbarColorExtension.of(context); _hideMenu(); indexNotifier.value = widget.itemLength - 1; popupMenuOverlayEntry ??= OverlayEntry( builder: (context) { final screenSize = MediaQuery.of(context).size; final right = screenSize.width - rect.right; final bottom = screenSize.height - rect.top + 16; return Positioned( right: right, bottom: bottom, child: ColoredBox( color: theme.toolbarMenuBackgroundColor, child: ValueListenableBuilder( valueListenable: indexNotifier, builder: (context, value, _) => widget.menuBuilder( context, itemKeys, value, ), ), ), ); }, ); Overlay.of(context).insert(popupMenuOverlayEntry!); } void _hideMenu() { indexNotifier.value = -1; popupMenuOverlayEntry?.remove(); popupMenuOverlayEntry = null; } void _updateSelection(LongPressMoveUpdateDetails details) { final dx = details.globalPosition.dx; for (var i = 0; i < itemKeys.length; i++) { final key = itemKeys[i]; final RenderBox renderBox = key.currentContext!.findRenderObject() as RenderBox; final size = renderBox.size; final offset = renderBox.localToGlobal(Offset.zero); final rect = Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height); // ignore the position overflow if ((i == 0 && dx < rect.left) || (i == itemKeys.length - 1 && dx > rect.right)) { indexNotifier.value = -1; break; } if (rect.left <= dx && dx <= rect.right) { indexNotifier.value = itemKeys.indexOf(key); break; } } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_align_items.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_menu_item.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_popup_menu.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/util.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; const _left = 'left'; const _center = 'center'; const _right = 'right'; class AlignItems extends StatelessWidget { AlignItems({ super.key, required this.editorState, }); final EditorState editorState; final List<(String, FlowySvgData)> _alignMenuItems = [ (_left, FlowySvgs.m_aa_align_left_m), (_center, FlowySvgs.m_aa_align_center_m), (_right, FlowySvgs.m_aa_align_right_m), ]; @override Widget build(BuildContext context) { final currentAlignItem = _getCurrentAlignItem(); final theme = ToolbarColorExtension.of(context); return PopupMenu( itemLength: _alignMenuItems.length, onSelected: (index) { editorState.alignBlock( _alignMenuItems[index].$1, selectionExtraInfo: { selectionExtraInfoDoNotAttachTextService: true, selectionExtraInfoDisableFloatingToolbar: true, }, ); }, menuBuilder: (context, keys, currentIndex) { final children = _alignMenuItems .mapIndexed( (index, e) => [ PopupMenuItemWrapper( key: keys[index], isSelected: currentIndex == index, icon: e.$2, ), if (index != 0 && index != _alignMenuItems.length - 1) const HSpace(12), ], ) .flattened .toList(); return PopupMenuWrapper( child: Row( mainAxisSize: MainAxisSize.min, children: children, ), ); }, builder: (context, key) => MobileToolbarMenuItemWrapper( key: key, size: const Size(82, 52), onTap: () async { await editorState.alignBlock( currentAlignItem.$1, selectionExtraInfo: { selectionExtraInfoDoNotAttachTextService: true, selectionExtraInfoDisableFloatingToolbar: true, }, ); }, icon: currentAlignItem.$2, isSelected: false, iconPadding: const EdgeInsets.symmetric( vertical: 14.0, ), showDownArrow: true, backgroundColor: theme.toolbarMenuItemBackgroundColor, ), ); } (String, FlowySvgData) _getCurrentAlignItem() { final align = _getCurrentBlockAlign(); if (align == _center) { return (_right, FlowySvgs.m_aa_align_right_s); } else if (align == _right) { return (_left, FlowySvgs.m_aa_align_left_s); } else { return (_center, FlowySvgs.m_aa_align_center_s); } } String _getCurrentBlockAlign() { final selection = editorState.selection; if (selection == null) { return _left; } final nodes = editorState.getNodesInSelection(selection); String? alignString; for (final node in nodes) { final align = node.attributes[blockComponentAlign]; if (alignString == null) { alignString = align; } else if (alignString != align) { return _left; } } return alignString ?? _left; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_indent_items.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; class IndentAndOutdentItems extends StatelessWidget { const IndentAndOutdentItems({ super.key, required this.service, required this.editorState, }); final EditorState editorState; final AppFlowyMobileToolbarWidgetService service; @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); return IntrinsicHeight( child: Row( children: [ MobileToolbarMenuItemWrapper( size: const Size(95, 52), icon: FlowySvgs.m_aa_outdent_m, enable: isOutdentable(editorState), isSelected: false, enableTopRightRadius: false, enableBottomRightRadius: false, iconPadding: const EdgeInsets.symmetric(vertical: 14.0), backgroundColor: theme.toolbarMenuItemBackgroundColor, onTap: () { service.closeItemMenu(); outdentCommand.execute(editorState); }, ), const ScaledVerticalDivider(), MobileToolbarMenuItemWrapper( size: const Size(95, 52), icon: FlowySvgs.m_aa_indent_m, enable: isIndentable(editorState), isSelected: false, enableTopLeftRadius: false, enableBottomLeftRadius: false, iconPadding: const EdgeInsets.symmetric(vertical: 14.0), backgroundColor: theme.toolbarMenuItemBackgroundColor, onTap: () { service.closeItemMenu(); indentCommand.execute(editorState); }, ), ], ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_block_items.dart
import 'dart:async'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_item/utils.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_menu_item.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_popup_menu.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class BlockItems extends StatelessWidget { BlockItems({ super.key, required this.service, required this.editorState, }); final EditorState editorState; final AppFlowyMobileToolbarWidgetService service; final List<(FlowySvgData, String)> _blockItems = [ (FlowySvgs.m_toolbar_bulleted_list_m, BulletedListBlockKeys.type), (FlowySvgs.m_toolbar_numbered_list_m, NumberedListBlockKeys.type), (FlowySvgs.m_aa_quote_m, QuoteBlockKeys.type), ]; @override Widget build(BuildContext context) { return IntrinsicHeight( child: Row( mainAxisSize: MainAxisSize.min, children: [ ..._blockItems .mapIndexed( (index, e) => [ _buildBlockItem( context, index, e.$1, e.$2, ), if (index != 0) const ScaledVerticalDivider(), ], ) .flattened, // this item is a special case, use link item here instead of block item _buildLinkItem(context), ], ), ); } Widget _buildBlockItem( BuildContext context, int index, FlowySvgData icon, String blockType, ) { final theme = ToolbarColorExtension.of(context); return MobileToolbarMenuItemWrapper( size: const Size(62, 54), enableTopLeftRadius: index == 0, enableBottomLeftRadius: index == 0, enableTopRightRadius: false, enableBottomRightRadius: false, onTap: () async { await _convert(blockType); }, backgroundColor: theme.toolbarMenuItemBackgroundColor, icon: icon, isSelected: editorState.isBlockTypeSelected(blockType), iconPadding: const EdgeInsets.symmetric( vertical: 14.0, ), ); } Widget _buildLinkItem(BuildContext context) { final theme = ToolbarColorExtension.of(context); final items = [ (AppFlowyRichTextKeys.code, FlowySvgs.m_aa_code_m), // (InlineMathEquationKeys.formula, FlowySvgs.m_aa_math_s), ]; return PopupMenu( itemLength: items.length, onSelected: (index) async { await editorState.toggleAttribute(items[index].$1); }, menuBuilder: (context, keys, currentIndex) { final children = items .mapIndexed( (index, e) => [ PopupMenuItemWrapper( key: keys[index], isSelected: currentIndex == index, icon: e.$2, ), if (index != 0 || index != items.length - 1) const HSpace(12), ], ) .flattened .toList(); return PopupMenuWrapper( child: Row( mainAxisSize: MainAxisSize.min, children: children, ), ); }, builder: (context, key) => MobileToolbarMenuItemWrapper( key: key, size: const Size(62, 54), enableTopLeftRadius: false, enableBottomLeftRadius: false, showDownArrow: true, onTap: _onLinkItemTap, backgroundColor: theme.toolbarMenuItemBackgroundColor, icon: FlowySvgs.m_toolbar_link_m, isSelected: false, iconPadding: const EdgeInsets.symmetric( vertical: 14.0, ), ), ); } void _onLinkItemTap() async { final selection = editorState.selection; if (selection == null) { return; } final nodes = editorState.getNodesInSelection(selection); // show edit link bottom sheet final context = nodes.firstOrNull?.context; if (context != null) { _closeKeyboard(selection); // keep the selection unawaited( editorState.updateSelectionWithReason( selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDoNotAttachTextService: true, selectionExtraInfoDisableFloatingToolbar: true, }, ), ); keepEditorFocusNotifier.increase(); final text = editorState .getTextInSelection( selection, ) .join(); final href = editorState.getDeltaAttributeValueInSelection<String>( AppFlowyRichTextKeys.href, selection, ); await showEditLinkBottomSheet( context, text, href, (context, newText, newHref) { editorState.updateTextAndHref( text, href, newText, newHref, selection: selection, ); context.pop(true); }, ); // re-open the keyboard again unawaited( editorState.updateSelectionWithReason( selection, extraInfo: {}, ), ); } } void _closeKeyboard(Selection selection) { editorState.updateSelectionWithReason( selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDoNotAttachTextService: true, }, ); editorState.service.keyboardService?.closeKeyboard(); } Future<void> _convert(String blockType) async { await editorState.convertBlockType( blockType, selectionExtraInfo: { selectionExtraInfoDoNotAttachTextService: true, selectionExtraInfoDisableFloatingToolbar: true, }, ); unawaited( editorState.updateSelectionWithReason( editorState.selection, extraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDoNotAttachTextService: true, }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_font_item.dart
import 'dart:async'; import 'package:appflowy/mobile/presentation/setting/font/font_picker_screen.dart'; import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/util/google_font_family_extension.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; class FontFamilyItem extends StatelessWidget { const FontFamilyItem({ super.key, required this.editorState, }); final EditorState editorState; @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); final fontFamily = _getCurrentSelectedFontFamilyName(); final systemFonFamily = context.read<DocumentAppearanceCubit>().state.fontFamily; return MobileToolbarMenuItemWrapper( size: const Size(144, 52), onTap: () async { final selection = editorState.selection; if (selection == null) { return; } // disable the floating toolbar unawaited( editorState.updateSelectionWithReason( selection, extraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDisableMobileToolbarKey: true, }, ), ); final newFont = await context .read<GoRouter>() .push<String>(FontPickerScreen.routeName); // if the selection is not collapsed, apply the font to the selection. if (newFont != null && !selection.isCollapsed) { if (newFont != fontFamily) { await editorState.formatDelta(selection, { AppFlowyRichTextKeys.fontFamily: GoogleFonts.getFont(newFont).fontFamily, }); } } // wait for the font picker screen to be dismissed. Future.delayed(const Duration(milliseconds: 250), () { // highlight the selected text again. editorState.updateSelectionWithReason( selection, extraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDisableMobileToolbarKey: false, }, ); // if the selection is collapsed, save the font for the next typing. if (newFont != null && selection.isCollapsed) { editorState.updateToggledStyle( AppFlowyRichTextKeys.fontFamily, GoogleFonts.getFont(newFont).fontFamily, ); } }); }, text: (fontFamily ?? systemFonFamily).parseFontFamilyName(), fontFamily: fontFamily ?? systemFonFamily, backgroundColor: theme.toolbarMenuItemBackgroundColor, isSelected: false, enable: true, showRightArrow: true, iconPadding: const EdgeInsets.only( top: 14.0, bottom: 14.0, left: 14.0, right: 12.0, ), textPadding: const EdgeInsets.only( right: 16.0, ), ); } String? _getCurrentSelectedFontFamilyName() { final toggleFontFamily = editorState.toggledStyle[AppFlowyRichTextKeys.fontFamily]; if (toggleFontFamily is String && toggleFontFamily.isNotEmpty) { return toggleFontFamily; } final selection = editorState.selection; if (selection != null && selection.isCollapsed && selection.startIndex != 0) { return editorState.getDeltaAttributeValueInSelection<String>( AppFlowyRichTextKeys.fontFamily, selection.copyWith( start: selection.start.copyWith( offset: selection.startIndex - 1, ), ), ); } return editorState.getDeltaAttributeValueInSelection<String>( AppFlowyRichTextKeys.fontFamily, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_color_list.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/_get_selection_color.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/size.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; const _count = 6; Future<void> showTextColorAndBackgroundColorPicker( BuildContext context, { required EditorState editorState, required Selection selection, }) async { final theme = ToolbarColorExtension.of(context); await showMobileBottomSheet( context, showHeader: true, showCloseButton: false, showDivider: true, showDragHandle: true, showDoneButton: true, barrierColor: Colors.transparent, backgroundColor: theme.toolbarMenuBackgroundColor, elevation: 20, title: LocaleKeys.grid_selectOption_colorPanelTitle.tr(), padding: const EdgeInsets.fromLTRB(10, 4, 10, 8), builder: (context) { return _TextColorAndBackgroundColor( editorState: editorState, selection: selection, ); }, ); Future.delayed(const Duration(milliseconds: 100), () { // highlight the selected text again. editorState.updateSelectionWithReason( selection, extraInfo: { selectionExtraInfoDisableFloatingToolbar: true, }, ); }); } class _TextColorAndBackgroundColor extends StatefulWidget { const _TextColorAndBackgroundColor({ required this.editorState, required this.selection, }); final EditorState editorState; final Selection selection; @override State<_TextColorAndBackgroundColor> createState() => _TextColorAndBackgroundColorState(); } class _TextColorAndBackgroundColorState extends State<_TextColorAndBackgroundColor> { @override Widget build(BuildContext context) { final String? selectedTextColor = widget.editorState.getSelectionColor(AppFlowyRichTextKeys.textColor); final String? selectedBackgroundColor = widget.editorState .getSelectionColor(AppFlowyRichTextKeys.backgroundColor); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only( top: 20, left: 6.0, ), child: FlowyText( LocaleKeys.editor_textColor.tr(), fontSize: 14.0, ), ), const VSpace(6.0), _TextColors( selectedColor: selectedTextColor?.tryToColor(), onSelectedColor: (textColor) async { final hex = textColor.alpha == 0 ? null : textColor.toHex(); final selection = widget.selection; if (selection.isCollapsed) { widget.editorState.updateToggledStyle( AppFlowyRichTextKeys.textColor, hex ?? '', ); } else { await widget.editorState.formatDelta( widget.selection, { AppFlowyRichTextKeys.textColor: hex, }, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDoNotAttachTextService: true, }, ); } setState(() {}); }, ), Padding( padding: const EdgeInsets.only( top: 18.0, left: 6.0, ), child: FlowyText( LocaleKeys.editor_backgroundColor.tr(), fontSize: 14.0, ), ), const VSpace(6.0), _BackgroundColors( selectedColor: selectedBackgroundColor?.tryToColor(), onSelectedColor: (backgroundColor) async { final hex = backgroundColor.alpha == 0 ? null : backgroundColor.toHex(); final selection = widget.selection; if (selection.isCollapsed) { widget.editorState.updateToggledStyle( AppFlowyRichTextKeys.backgroundColor, hex ?? '', ); } else { await widget.editorState.formatDelta( widget.selection, { AppFlowyRichTextKeys.backgroundColor: hex, }, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDoNotAttachTextService: true, }, ); } setState(() {}); }, ), ], ); } } class _BackgroundColors extends StatelessWidget { _BackgroundColors({ this.selectedColor, required this.onSelectedColor, }); final Color? selectedColor; final void Function(Color color) onSelectedColor; final colors = [ const Color(0x00FFFFFF), const Color(0xFFE8E0FF), const Color(0xFFFFE6FD), const Color(0xFFFFDAE6), const Color(0xFFFFEFE3), const Color(0xFFF5FFDC), const Color(0xFFDDFFD6), const Color(0xFFDEFFF1), const Color(0xFFE1FBFF), const Color(0xFFFFADAD), const Color(0xFFFFE088), const Color(0xFFA7DF4A), const Color(0xFFD4C0FF), const Color(0xFFFDB2FE), const Color(0xFFFFD18B), const Color(0xFFFFF176), const Color(0xFF71E6B4), const Color(0xFF80F1FF), ]; @override Widget build(BuildContext context) { return GridView.count( crossAxisCount: _count, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), children: colors.mapIndexed( (index, color) { return _BackgroundColorItem( color: color, isSelected: selectedColor == null ? index == 0 : selectedColor == color, onTap: () => onSelectedColor(color), ); }, ).toList(), ); } } class _BackgroundColorItem extends StatelessWidget { const _BackgroundColorItem({ required this.color, required this.isSelected, required this.onTap, }); final VoidCallback onTap; final Color color; final bool isSelected; @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); return GestureDetector( onTap: onTap, child: Container( margin: const EdgeInsets.all(6.0), decoration: BoxDecoration( color: color, borderRadius: Corners.s12Border, border: Border.all( width: isSelected ? 2.0 : 1.0, color: isSelected ? theme.toolbarMenuItemSelectedBackgroundColor : Theme.of(context).dividerColor, ), ), alignment: Alignment.center, child: isSelected ? const FlowySvg( FlowySvgs.m_blue_check_s, size: Size.square(28.0), blendMode: null, ) : null, ), ); } } class _TextColors extends StatelessWidget { _TextColors({ this.selectedColor, required this.onSelectedColor, }); final Color? selectedColor; final void Function(Color color) onSelectedColor; final colors = [ const Color(0x00FFFFFF), const Color(0xFFDB3636), const Color(0xFFEA8F06), const Color(0xFF18A166), const Color(0xFF205EEE), const Color(0xFFC619C9), ]; @override Widget build(BuildContext context) { return GridView.count( crossAxisCount: _count, shrinkWrap: true, padding: EdgeInsets.zero, physics: const NeverScrollableScrollPhysics(), children: colors.mapIndexed( (index, color) { return _TextColorItem( color: color, isSelected: selectedColor == null ? index == 0 : selectedColor == color, onTap: () => onSelectedColor(color), ); }, ).toList(), ); } } class _TextColorItem extends StatelessWidget { const _TextColorItem({ required this.color, required this.isSelected, required this.onTap, }); final VoidCallback onTap; final Color color; final bool isSelected; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( margin: const EdgeInsets.all(6.0), decoration: BoxDecoration( borderRadius: Corners.s12Border, border: Border.all( width: isSelected ? 2.0 : 1.0, color: isSelected ? const Color(0xff00C6F1) : Theme.of(context).dividerColor, ), ), alignment: Alignment.center, child: FlowyText( 'A', fontSize: 24, color: color.alpha == 0 ? null : color, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart
// workaround for toolbar theme color. import 'package:flutter/material.dart'; class ToolbarColorExtension extends ThemeExtension<ToolbarColorExtension> { factory ToolbarColorExtension.light() => const ToolbarColorExtension( toolbarBackgroundColor: Color(0xFFFFFFFF), toolbarItemIconColor: Color(0xFF1F2329), toolbarItemIconDisabledColor: Color(0xFF999BA0), toolbarItemIconSelectedColor: Color(0x1F232914), toolbarItemSelectedBackgroundColor: Color(0xFFF2F2F2), toolbarMenuBackgroundColor: Color(0xFFFFFFFF), toolbarMenuItemBackgroundColor: Color(0xFFF2F2F7), toolbarMenuItemSelectedBackgroundColor: Color(0xFF00BCF0), toolbarMenuIconColor: Color(0xFF1F2329), toolbarMenuIconDisabledColor: Color(0xFF999BA0), toolbarMenuIconSelectedColor: Color(0xFFFFFFFF), toolbarShadowColor: Color(0x2D000000), ); factory ToolbarColorExtension.dark() => const ToolbarColorExtension( toolbarBackgroundColor: Color(0xFF1F2329), toolbarItemIconColor: Color(0xFFF3F3F8), toolbarItemIconDisabledColor: Color(0xFF55565B), toolbarItemIconSelectedColor: Color(0xFF00BCF0), toolbarItemSelectedBackgroundColor: Color(0xFF3A3D43), toolbarMenuBackgroundColor: Color(0xFF23262B), toolbarMenuItemBackgroundColor: Color(0xFF2D3036), toolbarMenuItemSelectedBackgroundColor: Color(0xFF00BCF0), toolbarMenuIconColor: Color(0xFFF3F3F8), toolbarMenuIconDisabledColor: Color(0xFF55565B), toolbarMenuIconSelectedColor: Color(0xFF1F2329), toolbarShadowColor: Color.fromARGB(80, 112, 112, 112), ); factory ToolbarColorExtension.fromBrightness(Brightness brightness) => brightness == Brightness.light ? ToolbarColorExtension.light() : ToolbarColorExtension.dark(); const ToolbarColorExtension({ required this.toolbarBackgroundColor, required this.toolbarItemIconColor, required this.toolbarItemIconDisabledColor, required this.toolbarItemIconSelectedColor, required this.toolbarMenuBackgroundColor, required this.toolbarMenuItemBackgroundColor, required this.toolbarMenuItemSelectedBackgroundColor, required this.toolbarItemSelectedBackgroundColor, required this.toolbarMenuIconColor, required this.toolbarMenuIconDisabledColor, required this.toolbarMenuIconSelectedColor, required this.toolbarShadowColor, }); final Color toolbarBackgroundColor; final Color toolbarItemIconColor; final Color toolbarItemIconDisabledColor; final Color toolbarItemIconSelectedColor; final Color toolbarItemSelectedBackgroundColor; final Color toolbarMenuBackgroundColor; final Color toolbarMenuItemBackgroundColor; final Color toolbarMenuItemSelectedBackgroundColor; final Color toolbarMenuIconColor; final Color toolbarMenuIconDisabledColor; final Color toolbarMenuIconSelectedColor; final Color toolbarShadowColor; static ToolbarColorExtension of(BuildContext context) { return Theme.of(context).extension<ToolbarColorExtension>()!; } @override ToolbarColorExtension copyWith({ Color? toolbarBackgroundColor, Color? toolbarItemIconColor, Color? toolbarItemIconDisabledColor, Color? toolbarItemIconSelectedColor, Color? toolbarMenuBackgroundColor, Color? toolbarItemSelectedBackgroundColor, Color? toolbarMenuItemBackgroundColor, Color? toolbarMenuItemSelectedBackgroundColor, Color? toolbarMenuIconColor, Color? toolbarMenuIconDisabledColor, Color? toolbarMenuIconSelectedColor, Color? toolbarShadowColor, }) { return ToolbarColorExtension( toolbarBackgroundColor: toolbarBackgroundColor ?? this.toolbarBackgroundColor, toolbarItemIconColor: toolbarItemIconColor ?? this.toolbarItemIconColor, toolbarItemIconDisabledColor: toolbarItemIconDisabledColor ?? this.toolbarItemIconDisabledColor, toolbarItemIconSelectedColor: toolbarItemIconSelectedColor ?? this.toolbarItemIconSelectedColor, toolbarItemSelectedBackgroundColor: toolbarItemSelectedBackgroundColor ?? this.toolbarItemSelectedBackgroundColor, toolbarMenuBackgroundColor: toolbarMenuBackgroundColor ?? this.toolbarMenuBackgroundColor, toolbarMenuItemBackgroundColor: toolbarMenuItemBackgroundColor ?? this.toolbarMenuItemBackgroundColor, toolbarMenuItemSelectedBackgroundColor: toolbarMenuItemSelectedBackgroundColor ?? this.toolbarMenuItemSelectedBackgroundColor, toolbarMenuIconColor: toolbarMenuIconColor ?? this.toolbarMenuIconColor, toolbarMenuIconDisabledColor: toolbarMenuIconDisabledColor ?? this.toolbarMenuIconDisabledColor, toolbarMenuIconSelectedColor: toolbarMenuIconSelectedColor ?? this.toolbarMenuIconSelectedColor, toolbarShadowColor: toolbarShadowColor ?? this.toolbarShadowColor, ); } @override ToolbarColorExtension lerp(ToolbarColorExtension? other, double t) { if (other is! ToolbarColorExtension) { return this; } return ToolbarColorExtension( toolbarBackgroundColor: Color.lerp(toolbarBackgroundColor, other.toolbarBackgroundColor, t)!, toolbarItemIconColor: Color.lerp(toolbarItemIconColor, other.toolbarItemIconColor, t)!, toolbarItemIconDisabledColor: Color.lerp( toolbarItemIconDisabledColor, other.toolbarItemIconDisabledColor, t, )!, toolbarItemIconSelectedColor: Color.lerp( toolbarItemIconSelectedColor, other.toolbarItemIconSelectedColor, t, )!, toolbarItemSelectedBackgroundColor: Color.lerp( toolbarItemSelectedBackgroundColor, other.toolbarItemSelectedBackgroundColor, t, )!, toolbarMenuBackgroundColor: Color.lerp( toolbarMenuBackgroundColor, other.toolbarMenuBackgroundColor, t, )!, toolbarMenuItemBackgroundColor: Color.lerp( toolbarMenuItemBackgroundColor, other.toolbarMenuItemBackgroundColor, t, )!, toolbarMenuItemSelectedBackgroundColor: Color.lerp( toolbarMenuItemSelectedBackgroundColor, other.toolbarMenuItemSelectedBackgroundColor, t, )!, toolbarMenuIconColor: Color.lerp(toolbarMenuIconColor, other.toolbarMenuIconColor, t)!, toolbarMenuIconDisabledColor: Color.lerp( toolbarMenuIconDisabledColor, other.toolbarMenuIconDisabledColor, t, )!, toolbarMenuIconSelectedColor: Color.lerp( toolbarMenuIconSelectedColor, other.toolbarMenuIconSelectedColor, t, )!, toolbarShadowColor: Color.lerp(toolbarShadowColor, other.toolbarShadowColor, t)!, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_bius_items.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/util.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; class BIUSItems extends StatelessWidget { BIUSItems({ super.key, required this.editorState, }); final EditorState editorState; final List<(FlowySvgData, String)> _bius = [ (FlowySvgs.m_toolbar_bold_m, AppFlowyRichTextKeys.bold), (FlowySvgs.m_toolbar_italic_m, AppFlowyRichTextKeys.italic), (FlowySvgs.m_toolbar_underline_m, AppFlowyRichTextKeys.underline), (FlowySvgs.m_toolbar_strike_m, AppFlowyRichTextKeys.strikethrough), ]; @override Widget build(BuildContext context) { return IntrinsicHeight( child: Row( mainAxisSize: MainAxisSize.min, children: _bius .mapIndexed( (index, e) => [ _buildBIUSItem( context, index, e.$1, e.$2, ), if (index != 0 || index != _bius.length - 1) const ScaledVerticalDivider(), ], ) .flattened .toList(), ), ); } Widget _buildBIUSItem( BuildContext context, int index, FlowySvgData icon, String richTextKey, ) { final theme = ToolbarColorExtension.of(context); return StatefulBuilder( builder: (_, setState) => MobileToolbarMenuItemWrapper( size: const Size(62, 52), enableTopLeftRadius: index == 0, enableBottomLeftRadius: index == 0, enableTopRightRadius: index == _bius.length - 1, enableBottomRightRadius: index == _bius.length - 1, backgroundColor: theme.toolbarMenuItemBackgroundColor, onTap: () async { await editorState.toggleAttribute( richTextKey, selectionExtraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDoNotAttachTextService: true, }, ); // refresh the status setState(() {}); }, icon: icon, isSelected: editorState.isTextDecorationSelected(richTextKey) && editorState.toggledStyle[richTextKey] != false, iconPadding: const EdgeInsets.symmetric( vertical: 14.0, ), ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_color_item.dart
import 'dart:async'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/_get_selection_color.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_color_list.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; class ColorItem extends StatelessWidget { const ColorItem({ super.key, required this.editorState, required this.service, }); final EditorState editorState; final AppFlowyMobileToolbarWidgetService service; @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); final String? selectedTextColor = editorState.getSelectionColor(AppFlowyRichTextKeys.textColor); final String? selectedBackgroundColor = editorState.getSelectionColor(AppFlowyRichTextKeys.backgroundColor); return MobileToolbarMenuItemWrapper( size: const Size(82, 52), onTap: () async { service.closeKeyboard(); unawaited( editorState.updateSelectionWithReason( editorState.selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDoNotAttachTextService: true, }, ), ); keepEditorFocusNotifier.increase(); await showTextColorAndBackgroundColorPicker( context, editorState: editorState, selection: editorState.selection!, ); }, icon: FlowySvgs.m_aa_font_color_m, iconColor: selectedTextColor?.tryToColor(), backgroundColor: selectedBackgroundColor?.tryToColor() ?? theme.toolbarMenuItemBackgroundColor, selectedBackgroundColor: selectedBackgroundColor?.tryToColor(), isSelected: selectedBackgroundColor != null, showRightArrow: true, iconPadding: const EdgeInsets.only( top: 14.0, bottom: 14.0, right: 28.0, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_close_keyboard_or_menu_button.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class CloseKeyboardOrMenuButton extends StatelessWidget { const CloseKeyboardOrMenuButton({ super.key, required this.onPressed, }); final VoidCallback onPressed; @override Widget build(BuildContext context) { return SizedBox( width: 62, height: 42, child: FlowyButton( text: const FlowySvg( FlowySvgs.m_toolbar_keyboard_m, ), onTap: onPressed, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_heading_and_text_items.dart
import 'dart:async'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/util.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; class HeadingsAndTextItems extends StatelessWidget { const HeadingsAndTextItems({ super.key, required this.editorState, }); final EditorState editorState; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ _HeadingOrTextItem( icon: FlowySvgs.m_aa_h1_m, blockType: HeadingBlockKeys.type, editorState: editorState, level: 1, ), _HeadingOrTextItem( icon: FlowySvgs.m_aa_h2_m, blockType: HeadingBlockKeys.type, editorState: editorState, level: 2, ), _HeadingOrTextItem( icon: FlowySvgs.m_aa_h3_m, blockType: HeadingBlockKeys.type, editorState: editorState, level: 3, ), _HeadingOrTextItem( icon: FlowySvgs.m_aa_paragraph_m, blockType: ParagraphBlockKeys.type, editorState: editorState, ), ], ); } } class _HeadingOrTextItem extends StatelessWidget { const _HeadingOrTextItem({ required this.icon, required this.blockType, required this.editorState, this.level, }); final FlowySvgData icon; final String blockType; final EditorState editorState; final int? level; @override Widget build(BuildContext context) { final isSelected = editorState.isBlockTypeSelected( blockType, level: level, ); final padding = level != null ? EdgeInsets.symmetric( vertical: 14.0 - (3 - level!) * 3.0, ) : const EdgeInsets.symmetric( vertical: 16.0, ); return MobileToolbarMenuItemWrapper( size: const Size(76, 52), onTap: () async => _convert(isSelected), icon: icon, isSelected: isSelected, iconPadding: padding, ); } Future<void> _convert(bool isSelected) async { await editorState.convertBlockType( blockType, isSelected: isSelected, extraAttributes: level != null ? { HeadingBlockKeys.level: level!, } : null, selectionExtraInfo: { selectionExtraInfoDoNotAttachTextService: true, selectionExtraInfoDisableFloatingToolbar: true, }, ); unawaited( editorState.updateSelectionWithReason( editorState.selection, extraInfo: { selectionExtraInfoDisableFloatingToolbar: true, selectionExtraInfoDoNotAttachTextService: true, }, ), ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_menu_item.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart'; import 'package:flowy_svg/flowy_svg.dart'; import 'package:flutter/material.dart'; class PopupMenuItemWrapper extends StatelessWidget { const PopupMenuItemWrapper({ super.key, required this.isSelected, required this.icon, }); final bool isSelected; final FlowySvgData icon; @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); return Container( width: 62, height: 44, decoration: ShapeDecoration( color: isSelected ? theme.toolbarMenuItemSelectedBackgroundColor : null, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 9), child: FlowySvg( icon, color: isSelected ? theme.toolbarMenuIconSelectedColor : theme.toolbarMenuIconColor, ), ); } } class PopupMenuWrapper extends StatelessWidget { const PopupMenuWrapper({ super.key, required this.child, }); final Widget child; @override Widget build(BuildContext context) { final theme = ToolbarColorExtension.of(context); return Container( height: 64, padding: const EdgeInsets.symmetric( horizontal: 12, vertical: 10, ), decoration: ShapeDecoration( color: theme.toolbarMenuBackgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), shadows: [ BoxShadow( color: theme.toolbarShadowColor, blurRadius: 20, offset: const Offset(0, 10), ), ], ), child: 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/toggle/toggle_block_shortcut_event.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/toggle/toggle_block_component.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; const _greater = '>'; /// Convert '> ' to toggle list /// /// - support /// - desktop /// - mobile /// - web /// CharacterShortcutEvent formatGreaterToToggleList = CharacterShortcutEvent( key: 'format greater to quote', character: ' ', handler: (editorState) async => formatMarkdownSymbol( editorState, (node) => node.type != ToggleListBlockKeys.type, (_, text, __) => text == _greater, (_, node, delta) => [ toggleListBlockNode( delta: delta.compose(Delta()..delete(_greater.length)), ), ], ), ); /// Press enter key to insert child node inside the toggle list /// /// - support /// - desktop /// - mobile /// - web CharacterShortcutEvent insertChildNodeInsideToggleList = CharacterShortcutEvent( key: 'insert child node inside toggle list', character: '\n', handler: (editorState) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return false; } final node = editorState.getNodeAtPath(selection.start.path); final delta = node?.delta; if (node == null || node.type != ToggleListBlockKeys.type || delta == null) { return false; } final slicedDelta = delta.slice(selection.start.offset); final transaction = editorState.transaction; final collapsed = node.attributes[ToggleListBlockKeys.collapsed] as bool; if (collapsed) { // if the delta is empty, clear the format if (delta.isEmpty) { transaction ..insertNode( selection.start.path.next, paragraphNode(), ) ..deleteNode(node) ..afterSelection = Selection.collapsed( Position(path: selection.start.path), ); } else if (selection.startIndex == 0) { // insert a paragraph block above the current toggle list block transaction.insertNode(selection.start.path, paragraphNode()); transaction.afterSelection = Selection.collapsed( Position(path: selection.start.path.next), ); } else { // insert a toggle list block below the current toggle list block transaction ..deleteText(node, selection.startIndex, slicedDelta.length) ..insertNodes( selection.start.path.next, [ toggleListBlockNode(collapsed: true, delta: slicedDelta), paragraphNode(), ], ) ..afterSelection = Selection.collapsed( Position(path: selection.start.path.next), ); } } else { // insert a paragraph block inside the current toggle list block transaction ..deleteText(node, selection.startIndex, slicedDelta.length) ..insertNode( selection.start.path + [0], paragraphNode(delta: slicedDelta), ) ..afterSelection = Selection.collapsed( Position(path: selection.start.path + [0]), ); } await editorState.apply(transaction); return true; }, ); /// cmd/ctrl + enter to close or open the toggle list /// /// - support /// - desktop /// - web /// // toggle the todo list final CommandShortcutEvent toggleToggleListCommand = CommandShortcutEvent( key: 'toggle the toggle list', getDescription: () => AppFlowyEditorL10n.current.cmdToggleTodoList, command: 'ctrl+enter', macOSCommand: 'cmd+enter', handler: _toggleToggleListCommandHandler, ); CommandShortcutEventHandler _toggleToggleListCommandHandler = (editorState) { if (PlatformExtension.isMobile) { assert(false, 'enter key is not supported on mobile platform.'); return KeyEventResult.ignored; } final selection = editorState.selection; if (selection == null) { return KeyEventResult.ignored; } final nodes = editorState.getNodesInSelection(selection); if (nodes.isEmpty || nodes.length > 1) { return KeyEventResult.ignored; } final node = nodes.first; if (node.type != ToggleListBlockKeys.type) { return KeyEventResult.ignored; } final collapsed = node.attributes[ToggleListBlockKeys.collapsed] as bool; final transaction = editorState.transaction; transaction.updateNode(node, { ToggleListBlockKeys.collapsed: !collapsed, }); transaction.afterSelection = selection; editorState.apply(transaction); return KeyEventResult.handled; };
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/toggle/toggle_block_component.dart
import 'package:appflowy/generated/locale_keys.g.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'; class ToggleListBlockKeys { const ToggleListBlockKeys._(); static const String type = 'toggle_list'; /// The content of a code block. /// /// The value is a String. static const String delta = blockComponentDelta; static const String backgroundColor = blockComponentBackgroundColor; static const String textDirection = blockComponentTextDirection; /// The value is a bool. static const String collapsed = 'collapsed'; } Node toggleListBlockNode({ String? text, Delta? delta, bool collapsed = false, String? textDirection, Attributes? attributes, Iterable<Node>? children, }) { return Node( type: ToggleListBlockKeys.type, attributes: { ToggleListBlockKeys.collapsed: collapsed, ToggleListBlockKeys.delta: (delta ?? (Delta()..insert(text ?? ''))).toJson(), if (attributes != null) ...attributes, if (textDirection != null) ToggleListBlockKeys.textDirection: textDirection, }, children: children ?? [], ); } // defining the toggle list block menu item SelectionMenuItem toggleListBlockItem = SelectionMenuItem.node( getName: LocaleKeys.document_plugins_toggleList.tr, iconData: Icons.arrow_right, keywords: ['collapsed list', 'toggle list', 'list'], nodeBuilder: (editorState, _) => toggleListBlockNode(), replace: (_, node) => node.delta?.isEmpty ?? false, ); class ToggleListBlockComponentBuilder extends BlockComponentBuilder { ToggleListBlockComponentBuilder({ super.configuration, this.padding = const EdgeInsets.all(0), }); final EdgeInsets padding; @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return ToggleListBlockComponentWidget( key: node.key, node: node, configuration: configuration, padding: padding, showActions: showActions(node), actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), ); } @override bool validate(Node node) => node.delta != null; } class ToggleListBlockComponentWidget extends BlockComponentStatefulWidget { const ToggleListBlockComponentWidget({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), this.padding = const EdgeInsets.all(0), }); final EdgeInsets padding; @override State<ToggleListBlockComponentWidget> createState() => _ToggleListBlockComponentWidgetState(); } class _ToggleListBlockComponentWidgetState extends State<ToggleListBlockComponentWidget> with SelectableMixin, DefaultSelectableMixin, BlockComponentConfigurable, BlockComponentBackgroundColorMixin, NestedBlockComponentStatefulWidgetMixin, BlockComponentTextDirectionMixin, BlockComponentAlignMixin { // the key used to forward focus to the richtext child @override final forwardKey = GlobalKey(debugLabel: 'flowy_rich_text'); @override BlockComponentConfiguration get configuration => widget.configuration; @override GlobalKey<State<StatefulWidget>> get containerKey => node.key; @override GlobalKey<State<StatefulWidget>> blockComponentKey = GlobalKey( debugLabel: ToggleListBlockKeys.type, ); @override Node get node => widget.node; @override EdgeInsets get indentPadding => configuration.indentPadding( node, calculateTextDirection( layoutDirection: Directionality.maybeOf(context), ), ); bool get collapsed => node.attributes[ToggleListBlockKeys.collapsed] ?? false; @override Widget build(BuildContext context) { return collapsed ? buildComponent(context) : buildComponentWithChildren(context); } @override Widget buildComponent( BuildContext context, { bool withBackgroundColor = false, }) { final textDirection = calculateTextDirection( layoutDirection: Directionality.maybeOf(context), ); Widget child = Container( color: backgroundColor, width: double.infinity, alignment: alignment, child: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, textDirection: textDirection, children: [ // the emoji picker button for the note Container( constraints: const BoxConstraints(minWidth: 26, minHeight: 22), padding: const EdgeInsets.only(right: 4.0), child: AnimatedRotation( turns: collapsed ? 0.0 : 0.25, duration: const Duration(milliseconds: 200), child: FlowyIconButton( width: 18.0, icon: const Icon( Icons.arrow_right, size: 18.0, ), onPressed: onCollapsed, ), ), ), Flexible( child: AppFlowyRichText( key: forwardKey, delegate: this, node: widget.node, editorState: editorState, placeholderText: placeholderText, lineHeight: 1.5, textSpanDecorator: (textSpan) => textSpan.updateTextStyle( textStyle, ), placeholderTextSpanDecorator: (textSpan) => textSpan.updateTextStyle( placeholderTextStyle, ), textDirection: textDirection, textAlign: alignment?.toTextAlign, cursorColor: editorState.editorStyle.cursorColor, selectionColor: editorState.editorStyle.selectionColor, ), ), ], ), ); child = Padding( key: blockComponentKey, padding: padding, child: child, ); child = BlockSelectionContainer( node: node, delegate: this, listenable: editorState.selectionNotifier, blockColor: editorState.editorStyle.selectionColor, supportTypes: const [ BlockSelectionType.block, ], child: child, ); if (widget.showActions && widget.actionBuilder != null) { child = BlockComponentActionWrapper( node: node, actionBuilder: widget.actionBuilder!, child: child, ); } return child; } Future<void> onCollapsed() async { final transaction = editorState.transaction ..updateNode(node, { ToggleListBlockKeys.collapsed: !collapsed, }); 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/actions/option_action_button.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/option_action.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:flowy_infra_ui/widget/ignore_parent_gesture.dart'; import 'package:flutter/material.dart'; class OptionActionList extends StatelessWidget { const OptionActionList({ super.key, required this.blockComponentContext, required this.blockComponentState, required this.actions, required this.editorState, }); final BlockComponentContext blockComponentContext; final BlockComponentActionState blockComponentState; final List<OptionAction> actions; final EditorState editorState; @override Widget build(BuildContext context) { final popoverActions = actions.map((e) { if (e == OptionAction.divider) { return DividerOptionAction(); } else if (e == OptionAction.color) { return ColorOptionAction( editorState: editorState, ); } else if (e == OptionAction.depth) { return DepthOptionAction( editorState: editorState, ); } else { return OptionActionWrapper(e); } }).toList(); return PopoverActionList<PopoverAction>( popoverMutex: PopoverMutex(), direction: PopoverDirection.leftWithCenterAligned, actions: popoverActions, onPopupBuilder: () => blockComponentState.alwaysShowActions = true, onClosed: () { editorState.selectionType = null; editorState.selection = null; blockComponentState.alwaysShowActions = false; }, onSelected: (action, controller) { if (action is OptionActionWrapper) { _onSelectAction(action.inner); controller.close(); } }, buildChild: (controller) => OptionActionButton( onTap: () { controller.show(); // update selection _updateBlockSelection(); }, ), ); } void _updateBlockSelection() { final startNode = blockComponentContext.node; var endNode = startNode; while (endNode.children.isNotEmpty) { endNode = endNode.children.last; } final start = Position(path: startNode.path); final end = endNode.selectable?.end() ?? Position( path: endNode.path, offset: endNode.delta?.length ?? 0, ); editorState.selectionType = SelectionType.block; editorState.selection = Selection( start: start, end: end, ); } void _onSelectAction(OptionAction action) { final node = blockComponentContext.node; final transaction = editorState.transaction; switch (action) { case OptionAction.delete: transaction.deleteNode(node); break; case OptionAction.duplicate: transaction.insertNode( node.path.next, node.copyWith(), ); break; case OptionAction.turnInto: break; case OptionAction.moveUp: transaction.moveNode(node.path.previous, node); break; case OptionAction.moveDown: transaction.moveNode(node.path.next.next, node); break; case OptionAction.align: case OptionAction.color: case OptionAction.divider: case OptionAction.depth: throw UnimplementedError(); } editorState.apply(transaction); } } class OptionActionButton extends StatelessWidget { const OptionActionButton({ super.key, required this.onTap, }); final VoidCallback onTap; @override Widget build(BuildContext context) { return Align( child: MouseRegion( cursor: SystemMouseCursors.grab, child: IgnoreParentGestureWidget( child: GestureDetector( onTap: onTap, behavior: HitTestBehavior.deferToChild, child: FlowySvg( FlowySvgs.drag_element_s, size: const Size.square(24.0), color: Theme.of(context).iconTheme.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/actions/option_action.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/workspace/presentation/widgets/pop_up_action.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/theme_extension.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:styled_widget/styled_widget.dart'; const optionActionColorDefaultColor = 'appflowy_theme_default_color'; enum OptionAction { delete, duplicate, turnInto, moveUp, moveDown, /// callout background color color, divider, align, depth; FlowySvgData get svg { switch (this) { case OptionAction.delete: return FlowySvgs.delete_s; case OptionAction.duplicate: return FlowySvgs.copy_s; case OptionAction.turnInto: return const FlowySvgData('editor/turn_into'); case OptionAction.moveUp: return const FlowySvgData('editor/move_up'); case OptionAction.moveDown: return const FlowySvgData('editor/move_down'); case OptionAction.color: return const FlowySvgData('editor/color'); case OptionAction.divider: return const FlowySvgData('editor/divider'); case OptionAction.align: return FlowySvgs.m_aa_bulleted_list_s; case OptionAction.depth: return FlowySvgs.tag_s; } } String get description { switch (this) { case OptionAction.delete: return LocaleKeys.document_plugins_optionAction_delete.tr(); case OptionAction.duplicate: return LocaleKeys.document_plugins_optionAction_duplicate.tr(); case OptionAction.turnInto: return LocaleKeys.document_plugins_optionAction_turnInto.tr(); case OptionAction.moveUp: return LocaleKeys.document_plugins_optionAction_moveUp.tr(); case OptionAction.moveDown: return LocaleKeys.document_plugins_optionAction_moveDown.tr(); case OptionAction.color: return LocaleKeys.document_plugins_optionAction_color.tr(); case OptionAction.align: return LocaleKeys.document_plugins_optionAction_align.tr(); case OptionAction.depth: return LocaleKeys.document_plugins_optionAction_depth.tr(); case OptionAction.divider: throw UnsupportedError('Divider does not have description'); } } } enum OptionAlignType { left, center, right; static OptionAlignType fromString(String? value) { switch (value) { case 'left': return OptionAlignType.left; case 'center': return OptionAlignType.center; case 'right': return OptionAlignType.right; default: return OptionAlignType.center; } } FlowySvgData get svg { switch (this) { case OptionAlignType.left: return FlowySvgs.align_left_s; case OptionAlignType.center: return FlowySvgs.align_center_s; case OptionAlignType.right: return FlowySvgs.align_right_s; } } String get description { switch (this) { case OptionAlignType.left: return LocaleKeys.document_plugins_optionAction_left.tr(); case OptionAlignType.center: return LocaleKeys.document_plugins_optionAction_center.tr(); case OptionAlignType.right: return LocaleKeys.document_plugins_optionAction_right.tr(); } } } enum OptionDepthType { h1(1, 'H1'), h2(2, 'H2'), h3(3, 'H3'), h4(4, 'H4'), h5(5, 'H5'), h6(6, 'H6'); const OptionDepthType(this.level, this.description); final String description; final int level; static OptionDepthType fromLevel(int? level) { switch (level) { case 1: return OptionDepthType.h1; case 2: return OptionDepthType.h2; case 3: default: return OptionDepthType.h3; } } } class DividerOptionAction extends CustomActionCell { @override Widget buildWithContext(BuildContext context) { return const Divider( height: 1.0, thickness: 1.0, ); } } class AlignOptionAction extends PopoverActionCell { AlignOptionAction({ required this.editorState, }); final EditorState editorState; @override Widget? leftIcon(Color iconColor) { return FlowySvg( align.svg, size: const Size.square(12), ).padding(all: 2.0); } @override String get name { return LocaleKeys.document_plugins_optionAction_align.tr(); } @override PopoverActionCellBuilder get builder => (context, parentController, controller) { final selection = editorState.selection?.normalized; if (selection == null) { return const SizedBox.shrink(); } final node = editorState.getNodeAtPath(selection.start.path); if (node == null) { return const SizedBox.shrink(); } final children = buildAlignOptions(context, (align) async { await onAlignChanged(align); controller.close(); parentController.close(); }); return IntrinsicHeight( child: IntrinsicWidth( child: Column( children: children, ), ), ); }; List<Widget> buildAlignOptions( BuildContext context, void Function(OptionAlignType) onTap, ) { return OptionAlignType.values.map((e) => OptionAlignWrapper(e)).map((e) { final leftIcon = e.leftIcon(Theme.of(context).colorScheme.onSurface); final rightIcon = e.rightIcon(Theme.of(context).colorScheme.onSurface); return HoverButton( onTap: () => onTap(e.inner), itemHeight: ActionListSizes.itemHeight, leftIcon: leftIcon, name: e.name, rightIcon: rightIcon, ); }).toList(); } OptionAlignType get align { final selection = editorState.selection; if (selection == null) { return OptionAlignType.center; } final node = editorState.getNodeAtPath(selection.start.path); final align = node?.attributes['align']; return OptionAlignType.fromString(align); } Future<void> onAlignChanged(OptionAlignType align) async { if (align == this.align) { return; } final selection = editorState.selection; if (selection == null) { return; } final node = editorState.getNodeAtPath(selection.start.path); if (node == null) { return; } final transaction = editorState.transaction; transaction.updateNode(node, { 'align': align.name, }); await editorState.apply(transaction); } } class ColorOptionAction extends PopoverActionCell { ColorOptionAction({ required this.editorState, }); final EditorState editorState; @override Widget? leftIcon(Color iconColor) { return const FlowySvg( FlowySvgs.color_format_m, size: Size.square(12), ).padding(all: 2.0); } @override String get name => LocaleKeys.document_plugins_optionAction_color.tr(); @override Widget Function( BuildContext context, PopoverController parentController, PopoverController controller, ) get builder => (context, parentController, controller) { final selection = editorState.selection?.normalized; if (selection == null) { return const SizedBox.shrink(); } final node = editorState.getNodeAtPath(selection.start.path); if (node == null) { return const SizedBox.shrink(); } final bgColor = node.attributes[blockComponentBackgroundColor] as String?; final selectedColor = bgColor?.tryToColor(); // get default background color for callout block from themeExtension final defaultColor = node.type == CalloutBlockKeys.type ? AFThemeExtension.of(context).calloutBGColor : 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 FlowyColorPicker( colors: colors, selected: selectedColor, border: Border.all( color: Theme.of(context).colorScheme.onBackground, ), onTap: (option, index) async { final transaction = editorState.transaction; transaction.updateNode(node, { blockComponentBackgroundColor: option.id, }); await editorState.apply(transaction); controller.close(); parentController.close(); }, ); }; } class DepthOptionAction extends PopoverActionCell { DepthOptionAction({required this.editorState}); final EditorState editorState; @override Widget? leftIcon(Color iconColor) { return FlowySvg( OptionAction.depth.svg, size: const Size.square(12), ).padding(all: 2.0); } @override String get name => LocaleKeys.document_plugins_optionAction_depth.tr(); @override PopoverActionCellBuilder get builder => (context, parentController, controller) { final children = buildDepthOptions(context, (depth) async { await onDepthChanged(depth); controller.close(); parentController.close(); }); return SizedBox( width: 42, child: Column( mainAxisSize: MainAxisSize.min, children: children, ), ); }; List<Widget> buildDepthOptions( BuildContext context, Future<void> Function(OptionDepthType) onTap, ) { return OptionDepthType.values .map((e) => OptionDepthWrapper(e)) .map( (e) => HoverButton( onTap: () => onTap(e.inner), itemHeight: ActionListSizes.itemHeight, name: e.name, ), ) .toList(); } OptionDepthType depth(Node node) { final level = node.attributes[OutlineBlockKeys.depth]; return OptionDepthType.fromLevel(level); } Future<void> onDepthChanged(OptionDepthType depth) async { final selection = editorState.selection; final node = selection != null ? editorState.getNodeAtPath(selection.start.path) : null; if (node == null || depth == this.depth(node)) return; final transaction = editorState.transaction; transaction.updateNode( node, {OutlineBlockKeys.depth: depth.level}, ); await editorState.apply(transaction); } } class OptionDepthWrapper extends ActionCell { OptionDepthWrapper(this.inner); final OptionDepthType inner; @override String get name => inner.description; } class OptionActionWrapper extends ActionCell { OptionActionWrapper(this.inner); final OptionAction inner; @override Widget? leftIcon(Color iconColor) => FlowySvg(inner.svg); @override String get name => inner.description; } class OptionAlignWrapper extends ActionCell { OptionAlignWrapper(this.inner); final OptionAlignType inner; @override Widget? leftIcon(Color iconColor) => FlowySvg(inner.svg); @override String get name => inner.description; }
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/actions/block_action_button.dart
import 'dart:io'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flowy_infra_ui/widget/ignore_parent_gesture.dart'; import 'package:flutter/material.dart'; class BlockActionButton extends StatelessWidget { const BlockActionButton({ super.key, required this.svg, required this.richMessage, required this.onTap, }); final FlowySvgData svg; final InlineSpan richMessage; final VoidCallback onTap; @override Widget build(BuildContext context) { return Align( child: FlowyTooltip( preferBelow: false, richMessage: richMessage, child: MouseRegion( cursor: Platform.isWindows ? SystemMouseCursors.click : SystemMouseCursors.grab, child: IgnoreParentGestureWidget( child: GestureDetector( onTap: onTap, behavior: HitTestBehavior.deferToChild, child: FlowySvg( svg, size: const Size.square(18.0), color: Theme.of(context).iconTheme.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/actions/block_action_list.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:flutter/material.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/option_action.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; class BlockActionList extends StatelessWidget { const BlockActionList({ super.key, required this.blockComponentContext, required this.blockComponentState, required this.editorState, required this.actions, required this.showSlashMenu, }); final BlockComponentContext blockComponentContext; final BlockComponentActionState blockComponentState; final List<OptionAction> actions; final VoidCallback showSlashMenu; final EditorState editorState; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ BlockAddButton( blockComponentContext: blockComponentContext, blockComponentState: blockComponentState, editorState: editorState, showSlashMenu: showSlashMenu, ), const SizedBox(width: 4.0), BlockOptionButton( blockComponentContext: blockComponentContext, blockComponentState: blockComponentState, actions: actions, editorState: editorState, ), const SizedBox(width: 4.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/actions/block_action_option_button.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/actions/block_action_button.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/option_action.dart'; import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class BlockOptionButton extends StatelessWidget { const BlockOptionButton({ super.key, required this.blockComponentContext, required this.blockComponentState, required this.actions, required this.editorState, }); final BlockComponentContext blockComponentContext; final BlockComponentActionState blockComponentState; final List<OptionAction> actions; final EditorState editorState; @override Widget build(BuildContext context) { final popoverActions = actions.map((e) { switch (e) { case OptionAction.divider: return DividerOptionAction(); case OptionAction.color: return ColorOptionAction(editorState: editorState); case OptionAction.align: return AlignOptionAction(editorState: editorState); case OptionAction.depth: return DepthOptionAction(editorState: editorState); default: return OptionActionWrapper(e); } }).toList(); return PopoverActionList<PopoverAction>( popoverMutex: PopoverMutex(), direction: context.read<AppearanceSettingsCubit>().state.layoutDirection == LayoutDirection.rtlLayout ? PopoverDirection.rightWithCenterAligned : PopoverDirection.leftWithCenterAligned, actions: popoverActions, onPopupBuilder: () { keepEditorFocusNotifier.increase(); blockComponentState.alwaysShowActions = true; }, onClosed: () { WidgetsBinding.instance.addPostFrameCallback((timeStamp) { editorState.selectionType = null; editorState.selection = null; blockComponentState.alwaysShowActions = false; keepEditorFocusNotifier.decrease(); }); }, onSelected: (action, controller) { if (action is OptionActionWrapper) { _onSelectAction(action.inner); controller.close(); } }, buildChild: (controller) => _buildOptionButton(controller), ); } Widget _buildOptionButton(PopoverController controller) { return BlockActionButton( svg: FlowySvgs.drag_element_s, richMessage: TextSpan( children: [ TextSpan( // todo: customize the color to highlight the text. text: LocaleKeys.document_plugins_optionAction_click.tr(), ), TextSpan( text: LocaleKeys.document_plugins_optionAction_toOpenMenu.tr(), ), ], ), onTap: () { controller.show(); // update selection _updateBlockSelection(); }, ); } void _updateBlockSelection() { final startNode = blockComponentContext.node; var endNode = startNode; while (endNode.children.isNotEmpty) { endNode = endNode.children.last; } final start = Position(path: startNode.path); final end = endNode.selectable?.end() ?? Position( path: endNode.path, offset: endNode.delta?.length ?? 0, ); editorState.selectionType = SelectionType.block; editorState.selection = Selection( start: start, end: end, ); } void _onSelectAction(OptionAction action) { final node = blockComponentContext.node; final transaction = editorState.transaction; switch (action) { case OptionAction.delete: transaction.deleteNode(node); break; case OptionAction.duplicate: transaction.insertNode( node.path.next, node.copyWith(), ); break; case OptionAction.turnInto: break; case OptionAction.moveUp: transaction.moveNode(node.path.previous, node); break; case OptionAction.moveDown: transaction.moveNode(node.path.next.next, node); break; case OptionAction.align: case OptionAction.color: case OptionAction.divider: case OptionAction.depth: throw UnimplementedError(); } 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/actions/block_action_add_button.dart
import 'dart:io'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_button.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class BlockAddButton extends StatelessWidget { const BlockAddButton({ super.key, required this.blockComponentContext, required this.blockComponentState, required this.editorState, required this.showSlashMenu, }); final BlockComponentContext blockComponentContext; final BlockComponentActionState blockComponentState; final EditorState editorState; final VoidCallback showSlashMenu; @override Widget build(BuildContext context) { return BlockActionButton( svg: FlowySvgs.add_s, richMessage: TextSpan( children: [ TextSpan( text: LocaleKeys.blockActions_addBelowTooltip.tr(), ), const TextSpan(text: '\n'), TextSpan( text: Platform.isMacOS ? LocaleKeys.blockActions_addAboveMacCmd.tr() : LocaleKeys.blockActions_addAboveCmd.tr(), ), const TextSpan(text: ' '), TextSpan( text: LocaleKeys.blockActions_addAboveTooltip.tr(), ), ], ), onTap: () { final isAltPressed = HardwareKeyboard.instance.isAltPressed; final transaction = editorState.transaction; // If the current block is not an empty paragraph block, // then insert a new block above/below the current block. final node = blockComponentContext.node; if (node.type != ParagraphBlockKeys.type || (node.delta?.isNotEmpty ?? true)) { final path = isAltPressed ? node.path : node.path.next; transaction.insertNode(path, paragraphNode()); transaction.afterSelection = Selection.collapsed( Position(path: path), ); } else { transaction.afterSelection = Selection.collapsed( Position(path: node.path), ); } // show the slash menu. editorState.apply(transaction).then( (_) => WidgetsBinding.instance.addPostFrameCallback( (_) => showSlashMenu(), ), ); }, ); } }
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/actions/mobile_block_action_buttons.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet_block_action_widget.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:go_router/go_router.dart'; /// The ... button shows on the top right corner of a block. /// /// Default actions are: /// - delete /// - duplicate /// - insert above /// - insert below /// /// Only works on mobile. class MobileBlockActionButtons extends StatelessWidget { const MobileBlockActionButtons({ super.key, this.extendActionWidgets = const [], this.showThreeDots = true, required this.node, required this.editorState, required this.child, }); final Node node; final EditorState editorState; final List<Widget> extendActionWidgets; final Widget child; final bool showThreeDots; @override Widget build(BuildContext context) { if (!PlatformExtension.isMobile) { return child; } if (!showThreeDots) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => _showBottomSheet(context), child: child, ); } const padding = 10.0; return Stack( children: [ child, Positioned( top: padding, right: padding, child: FlowyIconButton( icon: const FlowySvg( FlowySvgs.three_dots_s, ), width: 20.0, onPressed: () => _showBottomSheet(context), ), ), ], ); } void _showBottomSheet(BuildContext context) { // close the keyboard editorState.updateSelectionWithReason(null, extraInfo: {}); showMobileBottomSheet( context, showHeader: true, showCloseButton: true, showDivider: true, showDragHandle: true, title: LocaleKeys.document_plugins_action.tr(), builder: (context) { return BlockActionBottomSheet( extendActionWidgets: extendActionWidgets, onAction: (action) async { context.pop(); final transaction = editorState.transaction; switch (action) { case BlockActionBottomSheetType.delete: transaction.deleteNode(node); break; case BlockActionBottomSheetType.duplicate: transaction.insertNode( node.path.next, node.copyWith(), ); break; case BlockActionBottomSheetType.insertAbove: case BlockActionBottomSheetType.insertBelow: final path = action == BlockActionBottomSheetType.insertAbove ? node.path : node.path.next; transaction ..insertNode( path, paragraphNode(), ) ..afterSelection = Selection.collapsed( Position( path: path, ), ); break; default: } if (transaction.operations.isNotEmpty) { 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/header/custom_cover_picker.dart
import 'dart:io'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/custom_cover_picker_bloc.dart'; import 'package: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/snap_bar.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/style_widget/text_field.dart'; import 'package:flowy_infra_ui/widget/rounded_button.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class CoverImagePicker extends StatefulWidget { const CoverImagePicker({ super.key, required this.onBackPressed, required this.onFileSubmit, }); final VoidCallback onBackPressed; final Function(List<String> paths) onFileSubmit; @override State<CoverImagePicker> createState() => _CoverImagePickerState(); } class _CoverImagePickerState extends State<CoverImagePicker> { @override Widget build(BuildContext context) { return BlocProvider( create: (context) => CoverImagePickerBloc() ..add(const CoverImagePickerEvent.initialEvent()), child: BlocListener<CoverImagePickerBloc, CoverImagePickerState>( listener: (context, state) { if (state is NetworkImagePicked) { state.successOrFail.fold( (s) {}, (e) => showSnapBar( context, LocaleKeys.document_plugins_cover_invalidImageUrl.tr(), ), ); } if (state is Done) { state.successOrFail.fold( (l) => widget.onFileSubmit(l), (r) => showSnapBar( context, LocaleKeys.document_plugins_cover_failedToAddImageToGallery .tr(), ), ); } }, child: BlocBuilder<CoverImagePickerBloc, CoverImagePickerState>( builder: (context, state) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ state is Loading ? const SizedBox( height: 180, child: Center( child: CircularProgressIndicator(), ), ) : CoverImagePreviewWidget(state: state), const VSpace(10), NetworkImageUrlInput( onAdd: (url) { context.read<CoverImagePickerBloc>().add(UrlSubmit(url)); }, ), const VSpace(10), ImagePickerActionButtons( onBackPressed: () { widget.onBackPressed(); }, onSave: () { context.read<CoverImagePickerBloc>().add( SaveToGallery(state), ); }, ), ], ); }, ), ), ); } } class NetworkImageUrlInput extends StatefulWidget { const NetworkImageUrlInput({super.key, required this.onAdd}); final void Function(String color) onAdd; @override State<NetworkImageUrlInput> createState() => _NetworkImageUrlInputState(); } class _NetworkImageUrlInputState extends State<NetworkImageUrlInput> { TextEditingController urlController = TextEditingController(); bool get buttonDisabled => urlController.text.isEmpty; @override void initState() { super.initState(); urlController.addListener(() => setState(() {})); } @override void dispose() { urlController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Row( children: [ Expanded( flex: 4, child: FlowyTextField( controller: urlController, hintText: LocaleKeys.document_plugins_cover_enterImageUrl.tr(), ), ), const SizedBox( width: 5, ), Expanded( child: RoundedTextButton( onPressed: () { urlController.text.isNotEmpty ? widget.onAdd(urlController.text) : null; }, hoverColor: Colors.transparent, fillColor: buttonDisabled ? Theme.of(context).disabledColor : Theme.of(context).colorScheme.primary, height: 36, title: LocaleKeys.document_plugins_cover_add.tr(), borderRadius: Corners.s8Border, ), ), ], ); } } class ImagePickerActionButtons extends StatelessWidget { const ImagePickerActionButtons({ super.key, required this.onBackPressed, required this.onSave, }); final VoidCallback onBackPressed; final VoidCallback onSave; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ FlowyTextButton( LocaleKeys.document_plugins_cover_back.tr(), hoverColor: Theme.of(context).colorScheme.secondaryContainer, fillColor: Colors.transparent, mainAxisAlignment: MainAxisAlignment.end, onPressed: () => onBackPressed(), ), FlowyTextButton( LocaleKeys.document_plugins_cover_saveToGallery.tr(), onPressed: () => onSave(), hoverColor: Theme.of(context).colorScheme.secondaryContainer, fillColor: Colors.transparent, mainAxisAlignment: MainAxisAlignment.end, fontColor: Theme.of(context).colorScheme.primary, ), ], ); } } class CoverImagePreviewWidget extends StatefulWidget { const CoverImagePreviewWidget({super.key, required this.state}); final dynamic state; @override State<CoverImagePreviewWidget> createState() => _CoverImagePreviewWidgetState(); } class _CoverImagePreviewWidgetState extends State<CoverImagePreviewWidget> { DecoratedBox _buildFilePickerWidget(BuildContext ctx) { return DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).cardColor, borderRadius: Corners.s6Border, border: Border.fromBorderSide( BorderSide( color: Theme.of(context).colorScheme.primary, ), ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const FlowySvg( FlowySvgs.add_s, size: Size(20, 20), ), const SizedBox( width: 3, ), FlowyText( LocaleKeys.document_plugins_cover_pasteImageUrl.tr(), ), ], ), const VSpace(10), FlowyText( LocaleKeys.document_plugins_cover_or.tr(), fontWeight: FontWeight.w300, ), const VSpace(10), FlowyButton( hoverColor: Theme.of(context).hoverColor, onTap: () { ctx.read<CoverImagePickerBloc>().add(const PickFileImage()); }, useIntrinsicWidth: true, leftIcon: const FlowySvg( FlowySvgs.document_s, size: Size(20, 20), ), text: FlowyText( LocaleKeys.document_plugins_cover_pickFromFiles.tr(), ), ), ], ), ); } Positioned _buildImageDeleteButton(BuildContext ctx) { return Positioned( right: 10, top: 10, child: InkWell( onTap: () { ctx.read<CoverImagePickerBloc>().add(const DeleteImage()); }, child: DecoratedBox( decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context).colorScheme.onPrimary, ), child: const FlowySvg( FlowySvgs.close_s, size: Size(20, 20), ), ), ), ); } @override Widget build(BuildContext context) { return Stack( children: [ Container( height: 180, alignment: Alignment.center, decoration: BoxDecoration( color: Theme.of(context).colorScheme.secondary, borderRadius: Corners.s6Border, image: widget.state is Initial ? null : widget.state is NetworkImagePicked ? widget.state.successOrFail.fold( (path) => DecorationImage( image: NetworkImage(path), fit: BoxFit.cover, ), (r) => null, ) : widget.state is FileImagePicked ? DecorationImage( image: FileImage(File(widget.state.path)), fit: BoxFit.cover, ) : null, ), child: (widget.state is Initial) ? _buildFilePickerWidget(context) : (widget.state is NetworkImagePicked) ? widget.state.successOrFail.fold( (l) => null, (r) => _buildFilePickerWidget( context, ), ) : null, ), (widget.state is FileImagePicked) ? _buildImageDeleteButton(context) : (widget.state is NetworkImagePicked) ? widget.state.successOrFail.fold( (l) => _buildImageDeleteButton(context), (r) => const SizedBox.shrink(), ) : 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/header/custom_cover_picker_bloc.dart
import 'dart:io'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/workspace/application/settings/prelude.dart'; import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/file_picker/file_picker_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:http/http.dart' as http; import 'package:path/path.dart' as p; import 'package:shared_preferences/shared_preferences.dart'; import 'cover_editor.dart'; part 'custom_cover_picker_bloc.freezed.dart'; class CoverImagePickerBloc extends Bloc<CoverImagePickerEvent, CoverImagePickerState> { CoverImagePickerBloc() : super(const CoverImagePickerState.initial()) { _dispatch(); } static const allowedExtensions = ['jpg', 'png', 'jpeg']; void _dispatch() { on<CoverImagePickerEvent>( (event, emit) async { await event.map( initialEvent: (InitialEvent initialEvent) { emit(const CoverImagePickerState.initial()); }, urlSubmit: (UrlSubmit urlSubmit) async { emit(const CoverImagePickerState.loading()); final validateImage = await _validateURL(urlSubmit.path); if (validateImage) { emit( CoverImagePickerState.networkImage( FlowyResult.success(urlSubmit.path), ), ); } else { emit( CoverImagePickerState.networkImage( FlowyResult.failure( FlowyError( msg: LocaleKeys.document_plugins_cover_couldNotFetchImage .tr(), ), ), ), ); } }, pickFileImage: (PickFileImage pickFileImage) async { final imagePickerResults = await _pickImages(); if (imagePickerResults != null) { emit(CoverImagePickerState.fileImage(imagePickerResults)); } else { emit(const CoverImagePickerState.initial()); } }, deleteImage: (DeleteImage deleteImage) { emit(const CoverImagePickerState.initial()); }, saveToGallery: (SaveToGallery saveToGallery) async { emit(const CoverImagePickerState.loading()); final saveImage = await _saveToGallery(saveToGallery.previousState); if (saveImage != null) { emit(CoverImagePickerState.done(FlowyResult.success(saveImage))); } else { emit( CoverImagePickerState.done( FlowyResult.failure( FlowyError( msg: LocaleKeys.document_plugins_cover_imageSavingFailed .tr(), ), ), ), ); emit(const CoverImagePickerState.initial()); } }, ); }, ); } Future<List<String>?>? _saveToGallery(CoverImagePickerState state) async { final SharedPreferences prefs = await SharedPreferences.getInstance(); final List<String> imagePaths = prefs.getStringList(kLocalImagesKey) ?? []; final directory = await _coverPath(); if (state is FileImagePicked) { try { final path = state.path; final newPath = p.join(directory, p.split(path).last); final newFile = await File(path).copy(newPath); imagePaths.add(newFile.path); } catch (e) { return null; } } else if (state is NetworkImagePicked) { try { final url = state.successOrFail.fold((path) => path, (r) => null); if (url != null) { final response = await http.get(Uri.parse(url)); final newPath = p.join(directory, _networkImageName(url)); final imageFile = File(newPath); await imageFile.create(); await imageFile.writeAsBytes(response.bodyBytes); imagePaths.add(imageFile.absolute.path); } else { return null; } } catch (e) { return null; } } await prefs.setStringList(kLocalImagesKey, imagePaths); return imagePaths; } Future<String?> _pickImages() async { final result = await getIt<FilePickerService>().pickFiles( dialogTitle: LocaleKeys.document_plugins_cover_addLocalImage.tr(), type: FileType.image, allowedExtensions: allowedExtensions, ); if (result != null && result.files.isNotEmpty) { return result.files.first.path; } return null; } Future<String> _coverPath() async { final directory = await getIt<ApplicationDataStorage>().getPath(); return Directory(p.join(directory, 'covers')) .create(recursive: true) .then((value) => value.path); } String _networkImageName(String url) { return 'IMG_${DateTime.now().millisecondsSinceEpoch.toString()}.${_getExtension( url, fromNetwork: true, )}'; } String? _getExtension( String path, { bool fromNetwork = false, }) { String? ext; if (!fromNetwork) { final extension = p.extension(path); if (extension.isEmpty) { return null; } ext = extension; } else { final uri = Uri.parse(path); final parameters = uri.queryParameters; if (path.contains('unsplash')) { final dl = parameters['dl']; if (dl != null) { ext = p.extension(dl); } } else { ext = p.extension(path); } } if (ext != null && ext.isNotEmpty) { ext = ext.substring(1); } if (allowedExtensions.contains(ext)) { return ext; } return null; } Future<bool> _validateURL(String path) async { final extension = _getExtension(path, fromNetwork: true); if (extension == null) { return false; } try { final response = await http.head(Uri.parse(path)); return response.statusCode == 200; } catch (e) { return false; } } } @freezed class CoverImagePickerEvent with _$CoverImagePickerEvent { const factory CoverImagePickerEvent.urlSubmit(String path) = UrlSubmit; const factory CoverImagePickerEvent.pickFileImage() = PickFileImage; const factory CoverImagePickerEvent.deleteImage() = DeleteImage; const factory CoverImagePickerEvent.saveToGallery( CoverImagePickerState previousState, ) = SaveToGallery; const factory CoverImagePickerEvent.initialEvent() = InitialEvent; } @freezed class CoverImagePickerState with _$CoverImagePickerState { const factory CoverImagePickerState.initial() = Initial; const factory CoverImagePickerState.loading() = Loading; const factory CoverImagePickerState.networkImage( FlowyResult<String, FlowyError> successOrFail, ) = NetworkImagePicked; const factory CoverImagePickerState.fileImage(String path) = FileImagePicked; const factory CoverImagePickerState.done( FlowyResult<List<String>, FlowyError> successOrFail, ) = Done; }
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/header/cover_editor.dart
import 'dart:io'; import 'dart:ui'; 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_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/size.dart'; import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra_ui/style_widget/button.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'; import 'package:flutter_bloc/flutter_bloc.dart'; const String kLocalImagesKey = 'local_images'; List<String> get builtInAssetImages => [ "assets/images/app_flowy_abstract_cover_1.jpg", "assets/images/app_flowy_abstract_cover_2.jpg", ]; class ChangeCoverPopover extends StatefulWidget { const ChangeCoverPopover({ super.key, required this.editorState, required this.node, required this.onCoverChanged, }); final EditorState editorState; final Node node; final Function( CoverType selectionType, String selection, ) onCoverChanged; @override State<ChangeCoverPopover> createState() => _ChangeCoverPopoverState(); } class _ChangeCoverPopoverState extends State<ChangeCoverPopover> { bool isAddingImage = false; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => ChangeCoverPopoverBloc( editorState: widget.editorState, node: widget.node, )..add(const ChangeCoverPopoverEvent.fetchPickedImagePaths()), child: BlocConsumer<ChangeCoverPopoverBloc, ChangeCoverPopoverState>( listener: (context, state) { if (state is Loaded && state.selectLatestImage) { widget.onCoverChanged( CoverType.file, state.imageNames.last, ); } }, builder: (context, state) { return Padding( padding: const EdgeInsets.all(12), child: SingleChildScrollView( child: isAddingImage ? CoverImagePicker( onBackPressed: () => setState(() { isAddingImage = false; }), onFileSubmit: (_) { context.read<ChangeCoverPopoverBloc>().add( const ChangeCoverPopoverEvent .fetchPickedImagePaths( selectLatestImage: true, ), ); setState(() => isAddingImage = false); }, ) : _buildCoverSelection(), ), ); }, ), ); } Widget _buildCoverSelection() { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FlowyText.semibold( LocaleKeys.document_plugins_cover_colors.tr(), color: Theme.of(context).colorScheme.tertiary, ), const VSpace(10), _buildColorPickerList(), const VSpace(10), _buildImageHeader(), const VSpace(10), _buildFileImagePicker(), const VSpace(10), FlowyText.semibold( LocaleKeys.document_plugins_cover_abstract.tr(), color: Theme.of(context).colorScheme.tertiary, ), const VSpace(10), _buildAbstractImagePicker(), ], ); } Widget _buildImageHeader() { return BlocBuilder<ChangeCoverPopoverBloc, ChangeCoverPopoverState>( builder: (context, state) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FlowyText.semibold( LocaleKeys.document_plugins_cover_images.tr(), color: Theme.of(context).colorScheme.tertiary, ), FlowyTextButton( fillColor: Theme.of(context).cardColor, hoverColor: Theme.of(context).colorScheme.secondaryContainer, LocaleKeys.document_plugins_cover_clearAll.tr(), fontColor: Theme.of(context).colorScheme.tertiary, onPressed: () async { final hasFileImageCover = CoverType.fromString( widget.node.attributes[DocumentHeaderBlockKeys.coverType], ) == CoverType.file; final changeCoverBloc = context.read<ChangeCoverPopoverBloc>(); if (hasFileImageCover) { await showDialog( context: context, builder: (context) { return DeleteImageAlertDialog( onSubmit: () { changeCoverBloc.add( const ChangeCoverPopoverEvent.clearAllImages(), ); Navigator.pop(context); }, ); }, ); } else { context .read<ChangeCoverPopoverBloc>() .add(const ChangeCoverPopoverEvent.clearAllImages()); } }, mainAxisAlignment: MainAxisAlignment.end, ), ], ); }, ); } Widget _buildAbstractImagePicker() { return GridView.builder( shrinkWrap: true, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 1 / 0.65, crossAxisSpacing: 7, mainAxisSpacing: 7, ), itemCount: builtInAssetImages.length, itemBuilder: (BuildContext ctx, index) { return InkWell( onTap: () { widget.onCoverChanged( CoverType.asset, builtInAssetImages[index], ); }, child: DecoratedBox( decoration: BoxDecoration( image: DecorationImage( image: AssetImage(builtInAssetImages[index]), fit: BoxFit.cover, ), borderRadius: Corners.s8Border, ), ), ); }, ); } Widget _buildColorPickerList() { final theme = Theme.of(context); return CoverColorPicker( pickerBackgroundColor: theme.cardColor, pickerItemHoverColor: theme.hoverColor, selectedBackgroundColorHex: widget.node.attributes[DocumentHeaderBlockKeys.coverType] == CoverType.color.toString() ? widget.node.attributes[DocumentHeaderBlockKeys.coverDetails] : 'ffffff', backgroundColorOptions: _generateBackgroundColorOptions(widget.editorState), onSubmittedBackgroundColorHex: (color) { widget.onCoverChanged(CoverType.color, color); setState(() {}); }, ); } Widget _buildFileImagePicker() { return BlocBuilder<ChangeCoverPopoverBloc, ChangeCoverPopoverState>( builder: (context, state) { if (state is Loaded) { final List<String> images = state.imageNames; return GridView.builder( shrinkWrap: true, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 1 / 0.65, crossAxisSpacing: 7, mainAxisSpacing: 7, ), itemCount: images.length + 1, itemBuilder: (BuildContext ctx, index) { if (index == 0) { return NewCustomCoverButton( onPressed: () => setState( () => isAddingImage = true, ), ); } return ImageGridItem( onImageSelect: () { widget.onCoverChanged( CoverType.file, images[index - 1], ); }, onImageDelete: () async { final changeCoverBloc = context.read<ChangeCoverPopoverBloc>(); final deletingCurrentCover = widget.node .attributes[DocumentHeaderBlockKeys.coverDetails] == images[index - 1]; if (deletingCurrentCover) { await showDialog( context: context, builder: (context) { return DeleteImageAlertDialog( onSubmit: () { changeCoverBloc.add( ChangeCoverPopoverEvent.deleteImage( images[index - 1], ), ); Navigator.pop(context); }, ); }, ); } else { changeCoverBloc.add(DeleteImage(images[index - 1])); } }, imagePath: images[index - 1], ); }, ); } return const SizedBox.shrink(); }, ); } List<ColorOption> _generateBackgroundColorOptions(EditorState editorState) { return FlowyTint.values .map( (t) => ColorOption( colorHex: t.color(context).toHex(), name: t.tintName(AppFlowyEditorL10n.current), ), ) .toList(); } } @visibleForTesting class NewCustomCoverButton extends StatelessWidget { const NewCustomCoverButton({super.key, required this.onPressed}); final VoidCallback onPressed; @override Widget build(BuildContext context) { return DecoratedBox( decoration: BoxDecoration( border: Border.all( color: Theme.of(context).colorScheme.primary, ), borderRadius: Corners.s8Border, ), child: FlowyIconButton( icon: Icon( Icons.add, color: Theme.of(context).colorScheme.primary, ), hoverColor: Theme.of(context).colorScheme.primary.withOpacity(0.15), onPressed: onPressed, ), ); } } class ColorOption { const ColorOption({ required this.colorHex, required this.name, }); final String colorHex; final String name; } class CoverColorPicker extends StatefulWidget { const CoverColorPicker({ super.key, this.selectedBackgroundColorHex, required this.pickerBackgroundColor, required this.backgroundColorOptions, required this.pickerItemHoverColor, required this.onSubmittedBackgroundColorHex, }); final String? selectedBackgroundColorHex; final Color pickerBackgroundColor; final List<ColorOption> backgroundColorOptions; final Color pickerItemHoverColor; final void Function(String color) onSubmittedBackgroundColorHex; @override State<CoverColorPicker> createState() => _CoverColorPickerState(); } class _CoverColorPickerState extends State<CoverColorPicker> { final scrollController = ScrollController(); @override void dispose() { scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( height: 30, alignment: Alignment.center, child: ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith( dragDevices: { PointerDeviceKind.touch, PointerDeviceKind.mouse, }, platform: TargetPlatform.windows, ), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: _buildColorItems( widget.backgroundColorOptions, widget.selectedBackgroundColorHex, ), ), ), ); } Widget _buildColorItems(List<ColorOption> options, String? selectedColor) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: options .map( (e) => ColorItem( option: e, isChecked: e.colorHex == selectedColor, hoverColor: widget.pickerItemHoverColor, onTap: widget.onSubmittedBackgroundColorHex, ), ) .toList(), ); } } class DeleteImageAlertDialog extends StatelessWidget { const DeleteImageAlertDialog({ super.key, required this.onSubmit, }); final Function() onSubmit; @override Widget build(BuildContext context) { return AlertDialog( title: FlowyText.semibold( "Image is used in cover", fontSize: 20, color: Theme.of(context).colorScheme.tertiary, ), content: Container( constraints: const BoxConstraints(minHeight: 100), padding: const EdgeInsets.symmetric( vertical: 20, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text(LocaleKeys.document_plugins_cover_coverRemoveAlert).tr(), const SizedBox( height: 4, ), const Text( LocaleKeys.document_plugins_cover_alertDialogConfirmation, ).tr(), ], ), ), contentPadding: const EdgeInsets.symmetric( vertical: 10.0, horizontal: 20.0, ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text(LocaleKeys.button_cancel).tr(), ), TextButton( onPressed: onSubmit, child: const Text(LocaleKeys.button_ok).tr(), ), ], ); } } class ImageGridItem extends StatefulWidget { const ImageGridItem({ super.key, required this.onImageSelect, required this.onImageDelete, required this.imagePath, }); final Function() onImageSelect; final Function() onImageDelete; final String imagePath; @override State<ImageGridItem> createState() => _ImageGridItemState(); } class _ImageGridItemState extends State<ImageGridItem> { bool showDeleteButton = false; @override Widget build(BuildContext context) { return MouseRegion( onEnter: (_) { setState(() { showDeleteButton = true; }); }, onExit: (_) { setState(() { showDeleteButton = false; }); }, child: Stack( children: [ InkWell( onTap: widget.onImageSelect, child: ClipRRect( borderRadius: Corners.s8Border, child: Image.file(File(widget.imagePath), fit: BoxFit.cover), ), ), if (showDeleteButton) Positioned( right: 2, top: 2, child: FlowyIconButton( fillColor: Theme.of(context).colorScheme.surface.withOpacity(0.8), hoverColor: Theme.of(context).colorScheme.surface.withOpacity(0.8), iconPadding: const EdgeInsets.all(5), width: 28, icon: FlowySvg( FlowySvgs.delete_s, color: Theme.of(context).colorScheme.tertiary, ), onPressed: widget.onImageDelete, ), ), ], ), ); } } @visibleForTesting class ColorItem extends StatelessWidget { const ColorItem({ super.key, required this.option, required this.isChecked, required this.hoverColor, required this.onTap, }); final ColorOption option; final bool isChecked; final Color hoverColor; final void Function(String) onTap; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(right: 10.0), child: InkWell( customBorder: const CircleBorder(), hoverColor: hoverColor, onTap: () => onTap(option.colorHex), child: SizedBox.square( dimension: 25, child: DecoratedBox( decoration: BoxDecoration( color: option.colorHex.tryToColor(), shape: BoxShape.circle, ), child: isChecked ? SizedBox.square( child: Container( margin: const EdgeInsets.all(1), decoration: BoxDecoration( border: Border.all( color: Theme.of(context).cardColor, width: 3.0, ), color: option.colorHex.tryToColor(), shape: BoxShape.circle, ), ), ) : 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/header/cover_editor_bloc.dart
import 'dart:async'; import 'dart:io'; 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_editor/appflowy_editor.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; part 'cover_editor_bloc.freezed.dart'; class ChangeCoverPopoverBloc extends Bloc<ChangeCoverPopoverEvent, ChangeCoverPopoverState> { ChangeCoverPopoverBloc({required this.editorState, required this.node}) : super(const ChangeCoverPopoverState.initial()) { SharedPreferences.getInstance().then((prefs) { _prefs = prefs; _initCompleter.complete(); }); _dispatch(); } final EditorState editorState; final Node node; final _initCompleter = Completer<void>(); late final SharedPreferences _prefs; void _dispatch() { on<ChangeCoverPopoverEvent>((event, emit) async { await event.map( fetchPickedImagePaths: (FetchPickedImagePaths fetchPickedImagePaths) async { final imageNames = await _getPreviouslyPickedImagePaths(); emit( ChangeCoverPopoverState.loaded( imageNames, selectLatestImage: fetchPickedImagePaths.selectLatestImage, ), ); }, deleteImage: (DeleteImage deleteImage) async { final currentState = state; final currentlySelectedImage = node.attributes[DocumentHeaderBlockKeys.coverDetails]; if (currentState is Loaded) { await _deleteImageInStorage(deleteImage.path); if (currentlySelectedImage == deleteImage.path) { _removeCoverImageFromNode(); } final updateImageList = currentState.imageNames .where((path) => path != deleteImage.path) .toList(); _updateImagePathsInStorage(updateImageList); emit(Loaded(updateImageList)); } }, clearAllImages: (ClearAllImages clearAllImages) async { final currentState = state; final currentlySelectedImage = node.attributes[DocumentHeaderBlockKeys.coverDetails]; if (currentState is Loaded) { for (final image in currentState.imageNames) { await _deleteImageInStorage(image); if (currentlySelectedImage == image) { _removeCoverImageFromNode(); } } _updateImagePathsInStorage([]); emit(const Loaded([])); } }, ); }); } Future<List<String>> _getPreviouslyPickedImagePaths() async { await _initCompleter.future; final imageNames = _prefs.getStringList(kLocalImagesKey) ?? []; if (imageNames.isEmpty) { return imageNames; } imageNames.removeWhere((name) => !File(name).existsSync()); unawaited(_prefs.setStringList(kLocalImagesKey, imageNames)); return imageNames; } void _updateImagePathsInStorage(List<String> imagePaths) async { await _initCompleter.future; await _prefs.setStringList(kLocalImagesKey, imagePaths); } Future<void> _deleteImageInStorage(String path) async { final imageFile = File(path); await imageFile.delete(); } void _removeCoverImageFromNode() { final transaction = editorState.transaction; transaction.updateNode(node, { DocumentHeaderBlockKeys.coverType: CoverType.none.toString(), DocumentHeaderBlockKeys.icon: node.attributes[DocumentHeaderBlockKeys.icon], }); editorState.apply(transaction); } } @freezed class ChangeCoverPopoverEvent with _$ChangeCoverPopoverEvent { const factory ChangeCoverPopoverEvent.fetchPickedImagePaths({ @Default(false) bool selectLatestImage, }) = FetchPickedImagePaths; const factory ChangeCoverPopoverEvent.deleteImage(String path) = DeleteImage; const factory ChangeCoverPopoverEvent.clearAllImages() = ClearAllImages; } @freezed class ChangeCoverPopoverState with _$ChangeCoverPopoverState { const factory ChangeCoverPopoverState.initial() = Initial; const factory ChangeCoverPopoverState.loading() = Loading; const factory ChangeCoverPopoverState.loaded( List<String> imageNames, { @Default(false) selectLatestImage, }) = Loaded; }
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/header/emoji_icon_widget.dart
import 'package:appflowy/plugins/base/emoji/emoji_text.dart'; import 'package:flutter/material.dart'; class EmojiIconWidget extends StatefulWidget { const EmojiIconWidget({ super.key, required this.emoji, this.emojiSize = 60, }); final String emoji; final double emojiSize; @override State<EmojiIconWidget> createState() => _EmojiIconWidgetState(); } class _EmojiIconWidgetState extends State<EmojiIconWidget> { bool hover = true; @override Widget build(BuildContext context) { return MouseRegion( onEnter: (_) => setHidden(false), onExit: (_) => setHidden(true), cursor: SystemMouseCursors.click, child: Container( decoration: BoxDecoration( color: !hover ? Theme.of(context).colorScheme.inverseSurface.withOpacity(0.5) : Colors.transparent, borderRadius: BorderRadius.circular(8), ), alignment: Alignment.center, child: EmojiText( emoji: widget.emoji, fontSize: widget.emojiSize, textAlign: TextAlign.center, ), ), ); } void setHidden(bool value) { if (hover == value) return; setState(() { hover = value; }); } }
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/header/document_header_node_widget.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/plugins/base/emoji/emoji_picker_screen.dart'; import 'package:appflowy/plugins/base/icon/icon_picker.dart'; import 'package:appflowy/plugins/document/application/document_bloc.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.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/plugins/document/presentation/editor_style.dart'; import 'package:appflowy/shared/appflowy_network_image.dart'; import 'package:appflowy/workspace/application/view/view_listener.dart'; import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide UploadImageMenu; 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/rounded_button.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:string_validator/string_validator.dart'; import 'cover_editor.dart'; const double kCoverHeight = 250.0; const double kIconHeight = 60.0; const double kToolbarHeight = 40.0; // with padding to the top class DocumentHeaderBlockKeys { const DocumentHeaderBlockKeys._(); static const String coverType = 'cover_selection_type'; static const String coverDetails = 'cover_selection'; static const String icon = 'selected_icon'; } enum CoverType { none, color, file, asset; static CoverType fromString(String? value) { if (value == null) { return CoverType.none; } return CoverType.values.firstWhere( (e) => e.toString() == value, orElse: () => CoverType.none, ); } } class DocumentHeaderNodeWidget extends StatefulWidget { const DocumentHeaderNodeWidget({ super.key, required this.node, required this.editorState, required this.onIconChanged, required this.view, }); final Node node; final EditorState editorState; final void Function(String icon) onIconChanged; final ViewPB view; @override State<DocumentHeaderNodeWidget> createState() => _DocumentHeaderNodeWidgetState(); } class _DocumentHeaderNodeWidgetState extends State<DocumentHeaderNodeWidget> { CoverType get coverType => CoverType.fromString( widget.node.attributes[DocumentHeaderBlockKeys.coverType], ); String? get coverDetails => widget.node.attributes[DocumentHeaderBlockKeys.coverDetails]; String? get icon => widget.node.attributes[DocumentHeaderBlockKeys.icon]; bool get hasIcon => viewIcon.isNotEmpty; bool get hasCover => coverType != CoverType.none; String viewIcon = ''; late final ViewListener viewListener; @override void initState() { super.initState(); final value = widget.view.icon.value; viewIcon = value.isNotEmpty ? value : icon ?? ''; widget.node.addListener(_reload); viewListener = ViewListener( viewId: widget.view.id, )..start( onViewUpdated: (p0) { setState(() { viewIcon = p0.icon.value; }); }, ); } @override void dispose() { viewListener.stop(); widget.node.removeListener(_reload); super.dispose(); } void _reload() => setState(() {}); @override Widget build(BuildContext context) { return Stack( children: [ SizedBox( height: _calculateOverallHeight(), child: DocumentHeaderToolbar( onIconOrCoverChanged: _saveIconOrCover, node: widget.node, editorState: widget.editorState, hasCover: hasCover, hasIcon: hasIcon, ), ), if (hasCover) DocumentCover( editorState: widget.editorState, node: widget.node, coverType: coverType, coverDetails: coverDetails, onChangeCover: (type, details) => _saveIconOrCover(cover: (type, details)), ), if (hasIcon) Positioned( left: PlatformExtension.isDesktopOrWeb ? 80 : 20, // if hasCover, there shouldn't be icons present so the icon can // be closer to the bottom. bottom: hasCover ? kToolbarHeight - kIconHeight / 2 : kToolbarHeight, child: DocumentIcon( editorState: widget.editorState, node: widget.node, icon: viewIcon, onChangeIcon: (icon) => _saveIconOrCover(icon: icon), ), ), ], ); } double _calculateOverallHeight() { switch ((hasIcon, hasCover)) { case (true, true): return kCoverHeight + kToolbarHeight; case (true, false): return 50 + kIconHeight + kToolbarHeight; case (false, true): return kCoverHeight + kToolbarHeight; case (false, false): return kToolbarHeight; } } void _saveIconOrCover({(CoverType, String?)? cover, String? icon}) async { final transaction = widget.editorState.transaction; final coverType = widget.node.attributes[DocumentHeaderBlockKeys.coverType]; final coverDetails = widget.node.attributes[DocumentHeaderBlockKeys.coverDetails]; final Map<String, dynamic> attributes = { DocumentHeaderBlockKeys.coverType: coverType, DocumentHeaderBlockKeys.coverDetails: coverDetails, DocumentHeaderBlockKeys.icon: widget.node.attributes[DocumentHeaderBlockKeys.icon], CustomImageBlockKeys.imageType: '1', }; if (cover != null) { attributes[DocumentHeaderBlockKeys.coverType] = cover.$1.toString(); attributes[DocumentHeaderBlockKeys.coverDetails] = cover.$2; } if (icon != null) { attributes[DocumentHeaderBlockKeys.icon] = icon; widget.onIconChanged(icon); } transaction.updateNode(widget.node, attributes); await widget.editorState.apply(transaction); } } @visibleForTesting class DocumentHeaderToolbar extends StatefulWidget { const DocumentHeaderToolbar({ super.key, required this.node, required this.editorState, required this.hasCover, required this.hasIcon, required this.onIconOrCoverChanged, }); final Node node; final EditorState editorState; final bool hasCover; final bool hasIcon; final void Function({(CoverType, String?)? cover, String? icon}) onIconOrCoverChanged; @override State<DocumentHeaderToolbar> createState() => _DocumentHeaderToolbarState(); } class _DocumentHeaderToolbarState extends State<DocumentHeaderToolbar> { bool isHidden = true; bool isPopoverOpen = false; final PopoverController _popoverController = PopoverController(); @override void initState() { super.initState(); isHidden = PlatformExtension.isDesktopOrWeb; } @override Widget build(BuildContext context) { Widget child = Container( alignment: Alignment.bottomLeft, width: double.infinity, padding: PlatformExtension.isDesktopOrWeb ? EdgeInsets.symmetric( horizontal: EditorStyleCustomizer.documentPadding.right, ) : EdgeInsets.symmetric( horizontal: EditorStyleCustomizer.documentPadding.left, ), child: SizedBox( height: 28, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: buildRowChildren(), ), ), ); if (PlatformExtension.isDesktopOrWeb) { child = MouseRegion( onEnter: (event) => setHidden(false), onExit: (event) { if (!isPopoverOpen) { setHidden(true); } }, opaque: false, child: child, ); } return child; } List<Widget> buildRowChildren() { if (isHidden || widget.hasCover && widget.hasIcon) { return []; } final List<Widget> children = []; if (!widget.hasCover) { children.add( FlowyButton( leftIconSize: const Size.square(18), onTap: () => widget.onIconOrCoverChanged( cover: PlatformExtension.isDesktopOrWeb ? (CoverType.asset, builtInAssetImages.first) : (CoverType.color, '0xffe8e0ff'), ), useIntrinsicWidth: true, leftIcon: const FlowySvg(FlowySvgs.image_s), text: FlowyText.small( LocaleKeys.document_plugins_cover_addCover.tr(), ), ), ); } if (widget.hasIcon) { children.add( FlowyButton( leftIconSize: const Size.square(18), onTap: () => widget.onIconOrCoverChanged(icon: ""), useIntrinsicWidth: true, leftIcon: const Icon( Icons.emoji_emotions_outlined, size: 18, ), text: FlowyText.small( LocaleKeys.document_plugins_cover_removeIcon.tr(), ), ), ); } else { Widget child = FlowyButton( leftIconSize: const Size.square(18), useIntrinsicWidth: true, leftIcon: const Icon( Icons.emoji_emotions_outlined, size: 18, ), text: FlowyText.small( LocaleKeys.document_plugins_cover_addIcon.tr(), ), onTap: PlatformExtension.isDesktop ? null : () async { final result = await context.push<EmojiPickerResult>( MobileEmojiPickerScreen.routeName, ); if (result != null) { widget.onIconOrCoverChanged(icon: result.emoji); } }, ); if (PlatformExtension.isDesktop) { child = AppFlowyPopover( onClose: () => isPopoverOpen = false, controller: _popoverController, offset: const Offset(0, 8), direction: PopoverDirection.bottomWithCenterAligned, constraints: BoxConstraints.loose(const Size(360, 380)), child: child, popupBuilder: (BuildContext popoverContext) { isPopoverOpen = true; return FlowyIconPicker( onSelected: (result) { widget.onIconOrCoverChanged(icon: result.emoji); _popoverController.close(); }, ); }, ); } children.add(child); } return children; } void setHidden(bool value) { if (isHidden == value) return; setState(() { isHidden = value; }); } } @visibleForTesting class DocumentCover extends StatefulWidget { const DocumentCover({ super.key, required this.node, required this.editorState, required this.coverType, this.coverDetails, required this.onChangeCover, }); final Node node; final EditorState editorState; final CoverType coverType; final String? coverDetails; final void Function(CoverType type, String? details) onChangeCover; @override State<DocumentCover> createState() => DocumentCoverState(); } class DocumentCoverState extends State<DocumentCover> { bool isOverlayButtonsHidden = true; bool isPopoverOpen = false; final PopoverController popoverController = PopoverController(); @override Widget build(BuildContext context) { return PlatformExtension.isDesktopOrWeb ? _buildDesktopCover() : _buildMobileCover(); } Widget _buildDesktopCover() { return SizedBox( height: kCoverHeight, child: MouseRegion( onEnter: (event) => setOverlayButtonsHidden(false), onExit: (event) => setOverlayButtonsHidden(isPopoverOpen ? false : true), child: Stack( children: [ SizedBox( height: double.infinity, width: double.infinity, child: _buildCoverImage(), ), if (!isOverlayButtonsHidden) _buildCoverOverlayButtons(context), ], ), ), ); } Widget _buildMobileCover() { return SizedBox( height: kCoverHeight, child: Stack( children: [ SizedBox( height: double.infinity, width: double.infinity, child: _buildCoverImage(), ), Positioned( bottom: 8, right: 12, child: Row( children: [ IntrinsicWidth( child: RoundedTextButton( fontSize: 14, onPressed: () { showMobileBottomSheet( context, showHeader: true, showDragHandle: true, showCloseButton: true, title: LocaleKeys.document_plugins_cover_changeCover.tr(), builder: (context) { return Padding( padding: const EdgeInsets.only(top: 8.0), child: ConstrainedBox( constraints: const BoxConstraints( maxHeight: 340, minHeight: 80, ), child: UploadImageMenu( limitMaximumImageSize: !_isLocalMode(), supportTypes: const [ UploadImageType.color, UploadImageType.local, UploadImageType.url, UploadImageType.unsplash, ], onSelectedLocalImage: (path) async { context.pop(); widget.onChangeCover(CoverType.file, path); }, onSelectedAIImage: (_) { throw UnimplementedError(); }, onSelectedNetworkImage: (url) async { context.pop(); widget.onChangeCover(CoverType.file, url); }, onSelectedColor: (color) { context.pop(); widget.onChangeCover(CoverType.color, color); }, ), ), ); }, ); }, fillColor: Theme.of(context) .colorScheme .onSurfaceVariant .withOpacity(0.5), height: 32, title: LocaleKeys.document_plugins_cover_changeCover.tr(), ), ), const HSpace(8.0), SizedBox.square( dimension: 32.0, child: DeleteCoverButton( onTap: () => widget.onChangeCover(CoverType.none, null), ), ), ], ), ), ], ), ); } Widget _buildCoverImage() { final detail = widget.coverDetails; if (detail == null) { return const SizedBox.shrink(); } switch (widget.coverType) { case CoverType.file: if (isURL(detail)) { final userProfilePB = context.read<DocumentBloc>().state.userProfilePB; return FlowyNetworkImage( url: detail, userProfilePB: userProfilePB, errorWidgetBuilder: (context, url, error) => const SizedBox.shrink(), ); } final imageFile = File(detail); if (!imageFile.existsSync()) { WidgetsBinding.instance.addPostFrameCallback((_) { widget.onChangeCover(CoverType.none, null); }); return const SizedBox.shrink(); } return Image.file( imageFile, fit: BoxFit.cover, ); case CoverType.asset: return Image.asset( widget.coverDetails!, fit: BoxFit.cover, ); case CoverType.color: final color = widget.coverDetails?.tryToColor() ?? Colors.white; return Container(color: color); case CoverType.none: return const SizedBox.shrink(); } } Widget _buildCoverOverlayButtons(BuildContext context) { return Positioned( bottom: 20, right: 50, child: Row( mainAxisSize: MainAxisSize.min, children: [ AppFlowyPopover( controller: popoverController, triggerActions: PopoverTriggerFlags.none, offset: const Offset(0, 8), direction: PopoverDirection.bottomWithCenterAligned, constraints: const BoxConstraints( maxWidth: 540, maxHeight: 360, minHeight: 80, ), margin: EdgeInsets.zero, onClose: () => isPopoverOpen = false, child: IntrinsicWidth( child: RoundedTextButton( height: 28.0, onPressed: () => popoverController.show(), hoverColor: Theme.of(context).colorScheme.surface, textColor: Theme.of(context).colorScheme.tertiary, fillColor: Theme.of(context).colorScheme.surface.withOpacity(0.5), title: LocaleKeys.document_plugins_cover_changeCover.tr(), ), ), popupBuilder: (BuildContext popoverContext) { isPopoverOpen = true; return UploadImageMenu( limitMaximumImageSize: !_isLocalMode(), supportTypes: const [ UploadImageType.color, UploadImageType.local, UploadImageType.url, UploadImageType.unsplash, ], onSelectedLocalImage: (path) { popoverController.close(); onCoverChanged(CoverType.file, path); }, onSelectedAIImage: (_) { throw UnimplementedError(); }, onSelectedNetworkImage: (url) { popoverController.close(); onCoverChanged(CoverType.file, url); }, onSelectedColor: (color) { popoverController.close(); onCoverChanged(CoverType.color, color); }, ); }, ), const HSpace(10), DeleteCoverButton( onTap: () => onCoverChanged(CoverType.none, null), ), ], ), ); } Future<void> onCoverChanged(CoverType type, String? details) async { if (type == CoverType.file && details != null && !isURL(details)) { if (_isLocalMode()) { details = await saveImageToLocalStorage(details); } else { // else we should save the image to cloud storage (details, _) = await saveImageToCloudStorage(details); } } widget.onChangeCover(type, details); } void setOverlayButtonsHidden(bool value) { if (isOverlayButtonsHidden == value) return; setState(() { isOverlayButtonsHidden = value; }); } bool _isLocalMode() { return context.read<DocumentBloc>().isLocalMode; } } @visibleForTesting class DeleteCoverButton extends StatelessWidget { const DeleteCoverButton({required this.onTap, super.key}); final VoidCallback onTap; @override Widget build(BuildContext context) { final fillColor = PlatformExtension.isDesktopOrWeb ? Theme.of(context).colorScheme.surface.withOpacity(0.5) : Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.5); final svgColor = PlatformExtension.isDesktopOrWeb ? Theme.of(context).colorScheme.tertiary : Theme.of(context).colorScheme.onPrimary; return FlowyIconButton( hoverColor: Theme.of(context).colorScheme.surface, fillColor: fillColor, iconPadding: const EdgeInsets.all(5), width: 28, icon: FlowySvg( FlowySvgs.delete_s, color: svgColor, ), onPressed: onTap, ); } } @visibleForTesting class DocumentIcon extends StatefulWidget { const DocumentIcon({ super.key, required this.node, required this.editorState, required this.icon, required this.onChangeIcon, }); final Node node; final EditorState editorState; final String icon; final void Function(String icon) onChangeIcon; @override State<DocumentIcon> createState() => _DocumentIconState(); } class _DocumentIconState extends State<DocumentIcon> { final PopoverController _popoverController = PopoverController(); @override Widget build(BuildContext context) { Widget child = EmojiIconWidget( emoji: widget.icon, ); if (PlatformExtension.isDesktopOrWeb) { child = AppFlowyPopover( direction: PopoverDirection.bottomWithCenterAligned, controller: _popoverController, offset: const Offset(0, 8), constraints: BoxConstraints.loose(const Size(360, 380)), child: child, popupBuilder: (BuildContext popoverContext) { return FlowyIconPicker( onSelected: (result) { widget.onChangeIcon(result.emoji); _popoverController.close(); }, ); }, ); } else { child = GestureDetector( child: child, onTap: () async { final result = await context.push<EmojiPickerResult>( MobileEmojiPickerScreen.routeName, ); if (result != null) { widget.onChangeIcon(result.emoji); } }, ); } 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/mobile_floating_toolbar/custom_mobile_floating_toolbar.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; List<ContextMenuButtonItem> buildMobileFloatingToolbarItems( EditorState editorState, Offset offset, Function closeToolbar, ) { // copy, paste, select, select all, cut final selection = editorState.selection; if (selection == null) { return []; } final toolbarItems = <ContextMenuButtonItem>[]; if (!selection.isCollapsed) { toolbarItems.add( ContextMenuButtonItem( label: LocaleKeys.editor_copy.tr(), onPressed: () { copyCommand.execute(editorState); closeToolbar(); }, ), ); } toolbarItems.add( ContextMenuButtonItem( label: LocaleKeys.editor_paste.tr(), onPressed: () { pasteCommand.execute(editorState); closeToolbar(); }, ), ); if (!selection.isCollapsed) { toolbarItems.add( ContextMenuButtonItem( label: LocaleKeys.editor_cut.tr(), onPressed: () { cutCommand.execute(editorState); closeToolbar(); }, ), ); } toolbarItems.add( ContextMenuButtonItem( label: LocaleKeys.editor_select.tr(), onPressed: () { editorState.selectWord(offset); closeToolbar(); }, ), ); toolbarItems.add( ContextMenuButtonItem( label: LocaleKeys.editor_selectAll.tr(), onPressed: () { selectAllCommand.execute(editorState); closeToolbar(); }, ), ); return toolbarItems; } extension on EditorState { void selectWord(Offset offset) { final node = service.selectionService.getNodeInOffset(offset); final selection = node?.selectable?.getWordBoundaryInOffset(offset); if (selection == null) { return; } updateSelectionWithReason(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/font/customize_font_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/font_family_setting.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; import 'package:appflowy_popover/appflowy_popover.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flutter/material.dart'; final customizeFontToolbarItem = ToolbarItem( id: 'editor.font', group: 4, isActive: onlyShowInTextType, builder: (context, editorState, highlightColor, _) { final selection = editorState.selection!; final popoverController = PopoverController(); return MouseRegion( cursor: SystemMouseCursors.click, child: FontFamilyDropDown( currentFontFamily: '', offset: const Offset(0, 12), popoverController: popoverController, onOpen: () => keepEditorFocusNotifier.increase(), onClose: () => keepEditorFocusNotifier.decrease(), showResetButton: true, onFontFamilyChanged: (fontFamily) async { popoverController.close(); try { await editorState.formatDelta(selection, { AppFlowyRichTextKeys.fontFamily: fontFamily, }); } catch (e) { Log.error('Failed to set font family: $e'); } }, onResetFont: () async => editorState.formatDelta(selection, { AppFlowyRichTextKeys.fontFamily: null, }), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: FlowyTooltip( message: LocaleKeys.document_plugins_fonts.tr(), child: const FlowySvg( FlowySvgs.font_family_s, size: Size.square(16.0), color: Colors.white, ), ), ), ), ); }, );
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/callout/callout_block_component.dart
import 'package:appflowy/generated/locale_keys.g.dart' show LocaleKeys; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart' show StringTranslateExtension; import 'package:easy_localization/easy_localization.dart' hide TextDirection; import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../base/emoji_picker_button.dart'; // defining the keys of the callout block's attributes for easy access class CalloutBlockKeys { const CalloutBlockKeys._(); static const String type = 'callout'; /// The content of a code block. /// /// The value is a String. static const String delta = 'delta'; /// The background color of a callout block. /// /// The value is a String. static const String backgroundColor = blockComponentBackgroundColor; /// The emoji icon of a callout block. /// /// The value is a String. static const String icon = 'icon'; } // The one is inserted through selection menu Node calloutNode({ Delta? delta, String emoji = '📌', Color? defaultColor, }) { final attributes = { CalloutBlockKeys.delta: (delta ?? Delta()).toJson(), CalloutBlockKeys.icon: emoji, CalloutBlockKeys.backgroundColor: defaultColor?.toHex(), }; return Node( type: CalloutBlockKeys.type, attributes: attributes, ); } // defining the callout block menu item in selection menu SelectionMenuItem calloutItem = SelectionMenuItem.node( getName: LocaleKeys.document_plugins_callout.tr, iconData: Icons.note, keywords: [CalloutBlockKeys.type], nodeBuilder: (editorState, context) => calloutNode(defaultColor: AFThemeExtension.of(context).calloutBGColor), replace: (_, node) => node.delta?.isEmpty ?? false, updateSelection: (_, path, __, ___) { return Selection.single(path: path, startOffset: 0); }, ); // building the callout block widget class CalloutBlockComponentBuilder extends BlockComponentBuilder { CalloutBlockComponentBuilder({ super.configuration, required this.defaultColor, }); final Color defaultColor; @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return CalloutBlockComponentWidget( key: node.key, node: node, defaultColor: defaultColor, configuration: configuration, showActions: showActions(node), actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), ); } // validate the data of the node, if the result is false, the node will be rendered as a placeholder @override bool validate(Node node) => node.delta != null && node.children.isEmpty && node.attributes[CalloutBlockKeys.icon] is String; } // the main widget for rendering the callout block class CalloutBlockComponentWidget extends BlockComponentStatefulWidget { const CalloutBlockComponentWidget({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), required this.defaultColor, }); final Color defaultColor; @override State<CalloutBlockComponentWidget> createState() => _CalloutBlockComponentWidgetState(); } class _CalloutBlockComponentWidgetState extends State<CalloutBlockComponentWidget> with SelectableMixin, DefaultSelectableMixin, BlockComponentConfigurable, BlockComponentTextDirectionMixin, BlockComponentAlignMixin, BlockComponentBackgroundColorMixin { // the key used to forward focus to the richtext child @override final forwardKey = GlobalKey(debugLabel: 'flowy_rich_text'); // the key used to identify this component @override GlobalKey<State<StatefulWidget>> get containerKey => widget.node.key; @override GlobalKey<State<StatefulWidget>> blockComponentKey = GlobalKey( debugLabel: CalloutBlockKeys.type, ); @override BlockComponentConfiguration get configuration => widget.configuration; @override Node get node => widget.node; @override Color get backgroundColor { final color = super.backgroundColor; if (color == Colors.transparent) { return AFThemeExtension.of(context).calloutBGColor; } return color; } // get the emoji of the note block from the node's attributes or default to '📌' String get emoji { final icon = node.attributes[CalloutBlockKeys.icon]; if (icon == null || icon.isEmpty) { return '📌'; } return icon; } // get access to the editor state via provider @override late final editorState = Provider.of<EditorState>(context, listen: false); // build the callout block widget @override Widget build(BuildContext context) { final textDirection = calculateTextDirection( layoutDirection: Directionality.maybeOf(context), ); Widget child = Container( decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(8.0)), color: backgroundColor, ), width: double.infinity, alignment: alignment, child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, textDirection: textDirection, children: [ // the emoji picker button for the note Padding( padding: const EdgeInsets.only( top: 8.0, left: 4.0, right: 4.0, ), child: EmojiPickerButton( key: ValueKey( emoji.toString(), ), // force to refresh the popover state title: '', emoji: emoji, onSubmitted: (emoji, controller) { setEmoji(emoji); controller?.close(); }, ), ), Flexible( child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: buildCalloutBlockComponent(context, textDirection), ), ), const HSpace(8.0), ], ), ); child = Padding( key: blockComponentKey, padding: padding, child: child, ); child = BlockSelectionContainer( node: node, delegate: this, listenable: editorState.selectionNotifier, blockColor: editorState.editorStyle.selectionColor, supportTypes: const [ BlockSelectionType.block, ], child: child, ); if (widget.showActions && widget.actionBuilder != null) { child = BlockComponentActionWrapper( node: widget.node, actionBuilder: widget.actionBuilder!, child: child, ); } return child; } // build the richtext child Widget buildCalloutBlockComponent( BuildContext context, TextDirection textDirection, ) { return Padding( padding: padding, child: AppFlowyRichText( key: forwardKey, delegate: this, node: widget.node, editorState: editorState, placeholderText: placeholderText, textSpanDecorator: (textSpan) => textSpan.updateTextStyle( textStyle, ), placeholderTextSpanDecorator: (textSpan) => textSpan.updateTextStyle( placeholderTextStyle, ), textDirection: textDirection, cursorColor: editorState.editorStyle.cursorColor, selectionColor: editorState.editorStyle.selectionColor, ), ); } // set the emoji of the note block Future<void> setEmoji(String emoji) async { final transaction = editorState.transaction ..updateNode(node, { CalloutBlockKeys.icon: emoji, }) ..afterSelection = Selection.collapsed( Position(path: node.path, offset: node.delta?.length ?? 0), ); 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/database/database_view_block_component.dart
import 'package:appflowy/plugins/database/widgets/database_view_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/built_in_page_widget.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class DatabaseBlockKeys { const DatabaseBlockKeys._(); static const String gridType = 'grid'; static const String boardType = 'board'; static const String calendarType = 'calendar'; static const String parentID = 'parent_id'; static const String viewID = 'view_id'; } class DatabaseViewBlockComponentBuilder extends BlockComponentBuilder { DatabaseViewBlockComponentBuilder({ super.configuration, }); @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return DatabaseBlockComponentWidget( 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[DatabaseBlockKeys.parentID] is String && node.attributes[DatabaseBlockKeys.viewID] is String; } class DatabaseBlockComponentWidget extends BlockComponentStatefulWidget { const DatabaseBlockComponentWidget({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), }); @override State<DatabaseBlockComponentWidget> createState() => _DatabaseBlockComponentWidgetState(); } class _DatabaseBlockComponentWidgetState extends State<DatabaseBlockComponentWidget> with BlockComponentConfigurable { @override Node get node => widget.node; @override BlockComponentConfiguration get configuration => widget.configuration; @override Widget build(BuildContext context) { final editorState = Provider.of<EditorState>(context, listen: false); Widget child = BuiltInPageWidget( node: widget.node, editorState: editorState, builder: (viewPB) { return DatabaseViewWidget( key: ValueKey(viewPB.id), view: viewPB, ); }, ); child = Padding( padding: padding, child: FocusScope( skipTraversal: true, onFocusChange: (value) { if (value) { context.read<EditorState>().selection = null; } }, child: child, ), ); if (widget.showActions && widget.actionBuilder != null) { child = BlockComponentActionWrapper( node: widget.node, actionBuilder: widget.actionBuilder!, 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/database/inline_database_menu_item.dart
import 'package:appflowy/generated/flowy_svgs.g.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/insert_page_command.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/selectable_svg_widget.dart'; import 'package:appflowy/workspace/application/view/view_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'; SelectionMenuItem inlineGridMenuItem(DocumentBloc documentBloc) => SelectionMenuItem( getName: LocaleKeys.document_slashMenu_grid_createANewGrid.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.grid_s, isSelected: onSelected, style: style, ), keywords: ['grid', 'database'], handler: (editorState, menuService, context) async { // create the view inside current page final parentViewId = documentBloc.view.id; final value = await ViewBackendService.createView( parentViewId: parentViewId, name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), layoutType: ViewLayoutPB.Grid, ); value.map((r) => editorState.insertInlinePage(parentViewId, r)); }, ); SelectionMenuItem inlineBoardMenuItem(DocumentBloc documentBloc) => SelectionMenuItem( getName: LocaleKeys.document_slashMenu_board_createANewBoard.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.board_s, isSelected: onSelected, style: style, ), keywords: ['board', 'kanban', 'database'], handler: (editorState, menuService, context) async { // create the view inside current page final parentViewId = documentBloc.view.id; final value = await ViewBackendService.createView( parentViewId: parentViewId, name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), layoutType: ViewLayoutPB.Board, ); value.map((r) => editorState.insertInlinePage(parentViewId, r)); }, ); SelectionMenuItem inlineCalendarMenuItem(DocumentBloc documentBloc) => SelectionMenuItem( getName: LocaleKeys.document_slashMenu_calendar_createANewCalendar.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.date_s, isSelected: onSelected, style: style, ), keywords: ['calendar', 'database'], handler: (editorState, menuService, context) async { // create the view inside current page final parentViewId = documentBloc.view.id; final value = await ViewBackendService.createView( parentViewId: parentViewId, name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(), layoutType: ViewLayoutPB.Calendar, ); value.map((r) => editorState.insertInlinePage(parentViewId, r)); }, );
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/database/referenced_database_menu_item.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/link_to_page_widget.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/selectable_svg_widget.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'; // Document Reference SelectionMenuItem referencedDocumentMenuItem = SelectionMenuItem( getName: LocaleKeys.document_plugins_referencedDocument.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.document_s, isSelected: onSelected, style: style, ), keywords: ['page', 'notes', 'referenced page', 'referenced document'], handler: (editorState, menuService, context) => showLinkToPageMenu(editorState, menuService, ViewLayoutPB.Document), ); // Database References SelectionMenuItem referencedGridMenuItem = SelectionMenuItem( getName: LocaleKeys.document_plugins_referencedGrid.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.grid_s, isSelected: onSelected, style: style, ), keywords: ['referenced', 'grid', 'database'], handler: (editorState, menuService, context) => showLinkToPageMenu(editorState, menuService, ViewLayoutPB.Grid), ); SelectionMenuItem referencedBoardMenuItem = SelectionMenuItem( getName: LocaleKeys.document_plugins_referencedBoard.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.board_s, isSelected: onSelected, style: style, ), keywords: ['referenced', 'board', 'kanban'], handler: (editorState, menuService, context) => showLinkToPageMenu(editorState, menuService, ViewLayoutPB.Board), ); SelectionMenuItem referencedCalendarMenuItem = SelectionMenuItem( getName: LocaleKeys.document_plugins_referencedCalendar.tr, icon: (editorState, onSelected, style) => SelectableSvgWidget( data: FlowySvgs.date_s, isSelected: onSelected, style: style, ), keywords: ['referenced', 'calendar', 'database'], handler: (editorState, menuService, context) => showLinkToPageMenu(editorState, menuService, ViewLayoutPB.Calendar), );
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/parsers/document_markdown_parsers.dart
export 'callout_node_parser.dart'; export 'custom_image_node_parser.dart'; export 'math_equation_node_parser.dart'; export 'toggle_list_node_parser.dart';
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/parsers/markdown_parsers.dart
export 'callout_node_parser.dart'; export 'math_equation_node_parser.dart'; export 'toggle_list_node_parser.dart';
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/parsers/math_equation_node_parser.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; class MathEquationNodeParser extends NodeParser { const MathEquationNodeParser(); @override String get id => MathEquationBlockKeys.type; @override String transform(Node node, DocumentMarkdownEncoder? encoder) { return '\$\$${node.attributes[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/parsers/callout_node_parser.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; class CalloutNodeParser extends NodeParser { const CalloutNodeParser(); @override String get id => CalloutBlockKeys.type; @override String transform(Node node, DocumentMarkdownEncoder? encoder) { assert(node.children.isEmpty); final icon = node.attributes[CalloutBlockKeys.icon]; final delta = node.delta ?? Delta() ..insert(''); final String markdown = DeltaMarkdownEncoder() .convert(delta) .split('\n') .map((e) => '> $e') .join('\n'); return ''' > $icon $markdown '''; } }
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/parsers/custom_image_node_parser.dart
import 'package:appflowy_editor/appflowy_editor.dart'; class CustomImageNodeParser extends NodeParser { const CustomImageNodeParser(); @override String get id => ImageBlockKeys.type; @override String transform(Node node, DocumentMarkdownEncoder? encoder) { assert(node.children.isEmpty); final url = node.attributes[ImageBlockKeys.url]; assert(url != null); return '![]($url)\n'; } }
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/parsers/toggle_list_node_parser.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; enum ToggleListExportStyle { github, markdown, } class ToggleListNodeParser extends NodeParser { const ToggleListNodeParser({ this.exportStyle = ToggleListExportStyle.markdown, }); final ToggleListExportStyle exportStyle; @override String get id => ToggleListBlockKeys.type; @override String transform(Node node, DocumentMarkdownEncoder? encoder) { final delta = node.delta ?? Delta() ..insert(''); String markdown = DeltaMarkdownEncoder().convert(delta); final details = encoder?.convertNodes( node.children, withIndent: true, ); switch (exportStyle) { case ToggleListExportStyle.github: return '''<details> <summary>$markdown</summary> $details </details> '''; case ToggleListExportStyle.markdown: markdown = '- $markdown\n'; if (details != null && details.isNotEmpty) { markdown += details; } return markdown; } } }
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/code_block/code_block_language_selector.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/selectable_item_list_menu.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/string_extension.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/code_block/code_language_screen.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.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:go_router/go_router.dart'; CodeBlockLanguagePickerBuilder codeBlockLanguagePickerBuilder = ( editorState, supportedLanguages, onLanguageSelected, { selectedLanguage, onMenuClose, onMenuOpen, }) => _CodeBlockLanguageSelector( editorState: editorState, language: selectedLanguage, supportedLanguages: supportedLanguages, onLanguageSelected: onLanguageSelected, onMenuClose: onMenuClose, onMenuOpen: onMenuOpen, ); class _CodeBlockLanguageSelector extends StatefulWidget { const _CodeBlockLanguageSelector({ required this.editorState, required this.supportedLanguages, this.language, required this.onLanguageSelected, this.onMenuOpen, this.onMenuClose, }); final EditorState editorState; final List<String> supportedLanguages; final String? language; final void Function(String) onLanguageSelected; final VoidCallback? onMenuOpen; final VoidCallback? onMenuClose; @override State<_CodeBlockLanguageSelector> createState() => _CodeBlockLanguageSelectorState(); } class _CodeBlockLanguageSelectorState extends State<_CodeBlockLanguageSelector> { final controller = PopoverController(); @override void dispose() { controller.close(); super.dispose(); } @override Widget build(BuildContext context) { Widget child = Row( children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 4.0), child: FlowyTextButton( widget.language?.capitalize() ?? LocaleKeys.document_codeBlock_language_auto.tr(), constraints: const BoxConstraints(minWidth: 50), fontColor: Theme.of(context).colorScheme.onBackground, padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 4), fillColor: Colors.transparent, hoverColor: Theme.of(context).colorScheme.secondaryContainer, onPressed: () async { if (PlatformExtension.isMobile) { final language = await context .push<String>(MobileCodeLanguagePickerScreen.routeName); if (language != null) { widget.onLanguageSelected(language); } } }, ), ), ], ); if (PlatformExtension.isDesktopOrWeb) { child = AppFlowyPopover( controller: controller, direction: PopoverDirection.bottomWithLeftAligned, onOpen: widget.onMenuOpen, constraints: const BoxConstraints(maxHeight: 300, maxWidth: 200), onClose: widget.onMenuClose, popupBuilder: (_) => _LanguageSelectionPopover( editorState: widget.editorState, language: widget.language, supportedLanguages: widget.supportedLanguages, onLanguageSelected: (language) { widget.onLanguageSelected(language); controller.close(); }, ), child: child, ); } return child; } } class _LanguageSelectionPopover extends StatefulWidget { const _LanguageSelectionPopover({ required this.editorState, required this.language, required this.supportedLanguages, required this.onLanguageSelected, }); final EditorState editorState; final String? language; final List<String> supportedLanguages; final void Function(String) onLanguageSelected; @override State<_LanguageSelectionPopover> createState() => _LanguageSelectionPopoverState(); } class _LanguageSelectionPopoverState extends State<_LanguageSelectionPopover> { final searchController = TextEditingController(); final focusNode = FocusNode(); late List<String> filteredLanguages = widget.supportedLanguages.map((e) => e.capitalize()).toList(); late int selectedIndex = widget.supportedLanguages.indexOf(widget.language ?? ''); @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback( // This is a workaround because longer taps might break the // focus, this might be an issue with the Flutter framework. (_) => Future.delayed( const Duration(milliseconds: 100), () => focusNode.requestFocus(), ), ); } @override void dispose() { focusNode.dispose(); searchController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ FlowyTextField( focusNode: focusNode, autoFocus: false, controller: searchController, hintText: LocaleKeys.document_codeBlock_searchLanguageHint.tr(), onChanged: (_) => setState(() { filteredLanguages = widget.supportedLanguages .where((e) => e.contains(searchController.text.toLowerCase())) .map((e) => e.capitalize()) .toList(); selectedIndex = widget.supportedLanguages.indexOf(widget.language ?? ''); }), ), const VSpace(8), Flexible( child: SelectableItemListMenu( shrinkWrap: true, items: filteredLanguages, selectedIndex: selectedIndex, onSelected: (index) => widget.onLanguageSelected(filteredLanguages[index]), ), ), ], ); } }
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/code_block/code_block_copy_button.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/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:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/theme_extension.dart'; import 'package:flowy_infra_ui/style_widget/icon_button.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; CodeBlockCopyBuilder codeBlockCopyBuilder = (_, node) => _CopyButton(node: node); class _CopyButton extends StatelessWidget { const _CopyButton({required this.node}); final Node node; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(4), child: FlowyTooltip( message: LocaleKeys.document_codeBlock_copyTooltip.tr(), child: FlowyIconButton( onPressed: () async { await getIt<ClipboardService>().setData( ClipboardServiceData( plainText: node.delta?.toPlainText(), ), ); if (context.mounted) { showSnackBarMessage( context, LocaleKeys.document_codeBlock_codeCopiedSnackbar.tr(), ); } }, hoverColor: Theme.of(context).colorScheme.secondaryContainer, icon: FlowySvg( FlowySvgs.copy_s, color: AFThemeExtension.of(context).textColor, ), ), ), ); } }
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/code_block/code_language_screen.dart
import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/string_extension.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:go_router/go_router.dart'; class MobileCodeLanguagePickerScreen extends StatelessWidget { const MobileCodeLanguagePickerScreen({super.key}); static const routeName = '/code_language_picker'; @override Widget build(BuildContext context) { return Scaffold( appBar: FlowyAppBar( titleText: LocaleKeys.titleBar_language.tr(), ), body: SafeArea( child: ListView.separated( itemBuilder: (context, index) { final language = defaultCodeBlockSupportedLanguages[index]; return SizedBox( height: 48, child: FlowyTextButton( language.capitalize(), padding: const EdgeInsets.symmetric( horizontal: 16.0, vertical: 4.0, ), onPressed: () => context.pop(language), ), ); }, separatorBuilder: (_, __) => const Divider(), itemCount: defaultCodeBlockSupportedLanguages.length, ), ), ); } }
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/background_color/theme_background_color.dart
import 'package:flowy_infra/theme_extension.dart'; // DON'T MODIFY THIS KEY BECAUSE IT'S SAVED IN THE DATABASE! // Used for the block component background color const themeBackgroundColors = { 'appflowy_them_color_tint1': FlowyTint.tint1, 'appflowy_them_color_tint2': FlowyTint.tint2, 'appflowy_them_color_tint3': FlowyTint.tint3, 'appflowy_them_color_tint4': FlowyTint.tint4, 'appflowy_them_color_tint5': FlowyTint.tint5, 'appflowy_them_color_tint6': FlowyTint.tint6, 'appflowy_them_color_tint7': FlowyTint.tint7, 'appflowy_them_color_tint8': FlowyTint.tint8, 'appflowy_them_color_tint9': FlowyTint.tint9, };
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/extensions/flowy_tint_extension.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flowy_infra/theme_extension.dart'; import 'package:flutter/material.dart'; extension FlowyTintExtension on FlowyTint { String tintName( AppFlowyEditorLocalizations l10n, { ThemeMode? themeMode, String? theme, }) { switch (this) { case FlowyTint.tint1: return l10n.lightLightTint1; case FlowyTint.tint2: return l10n.lightLightTint2; case FlowyTint.tint3: return l10n.lightLightTint3; case FlowyTint.tint4: return l10n.lightLightTint4; case FlowyTint.tint5: return l10n.lightLightTint5; case FlowyTint.tint6: return l10n.lightLightTint6; case FlowyTint.tint7: return l10n.lightLightTint7; case FlowyTint.tint8: return l10n.lightLightTint8; case FlowyTint.tint9: return l10n.lightLightTint9; } } }
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/mobile_toolbar_item/mobile_text_decoration_item_v2.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_item/utils.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; final customTextDecorationMobileToolbarItem = MobileToolbarItem.withMenu( itemIconBuilder: (_, __, ___) => const FlowySvg( FlowySvgs.text_s, size: Size.square(24), ), itemMenuBuilder: (_, editorState, service) { final selection = editorState.selection; if (selection == null) { return const SizedBox.shrink(); } return _TextDecorationMenu( editorState, selection, service, ); }, ); class _TextDecorationMenu extends StatefulWidget { const _TextDecorationMenu( this.editorState, this.selection, this.service, ); final EditorState editorState; final Selection selection; final MobileToolbarWidgetService service; @override State<_TextDecorationMenu> createState() => _TextDecorationMenuState(); } class _TextDecorationMenuState extends State<_TextDecorationMenu> { EditorState get editorState => widget.editorState; final textDecorations = [ // BIUS TextDecorationUnit( icon: AFMobileIcons.bold, label: AppFlowyEditorL10n.current.bold, name: AppFlowyRichTextKeys.bold, ), TextDecorationUnit( icon: AFMobileIcons.italic, label: AppFlowyEditorL10n.current.italic, name: AppFlowyRichTextKeys.italic, ), TextDecorationUnit( icon: AFMobileIcons.underline, label: AppFlowyEditorL10n.current.underline, name: AppFlowyRichTextKeys.underline, ), TextDecorationUnit( icon: AFMobileIcons.strikethrough, label: AppFlowyEditorL10n.current.strikethrough, name: AppFlowyRichTextKeys.strikethrough, ), // Code TextDecorationUnit( icon: AFMobileIcons.code, label: AppFlowyEditorL10n.current.embedCode, name: AppFlowyRichTextKeys.code, ), // link TextDecorationUnit( icon: AFMobileIcons.link, label: AppFlowyEditorL10n.current.link, name: AppFlowyRichTextKeys.href, ), ]; @override void dispose() { widget.editorState.selectionExtraInfo = null; super.dispose(); } @override Widget build(BuildContext context) { final children = textDecorations .map((currentDecoration) { // Check current decoration is active or not final selection = widget.selection; // only show edit link bottom sheet when selection is not collapsed if (selection.isCollapsed && currentDecoration.name == AppFlowyRichTextKeys.href) { return null; } final nodes = editorState.getNodesInSelection(selection); final bool isSelected; if (selection.isCollapsed) { isSelected = editorState.toggledStyle.containsKey( currentDecoration.name, ); } else { isSelected = nodes.allSatisfyInSelection(selection, (delta) { return delta.everyAttributes( (attributes) => attributes[currentDecoration.name] == true, ); }); } return MobileToolbarItemMenuBtn( icon: AFMobileIcon( afMobileIcons: currentDecoration.icon, color: MobileToolbarTheme.of(context).iconColor, ), label: FlowyText(currentDecoration.label), isSelected: isSelected, onPressed: () { if (currentDecoration.name == AppFlowyRichTextKeys.href) { if (selection.isCollapsed) { return; } _closeKeyboard(); // show edit link bottom sheet final context = nodes.firstOrNull?.context; if (context != null) { final text = editorState .getTextInSelection( widget.selection, ) .join(); final href = editorState.getDeltaAttributeValueInSelection<String>( AppFlowyRichTextKeys.href, widget.selection, ); showEditLinkBottomSheet( context, text, href, (context, newText, newHref) { _updateTextAndHref(text, href, newText, newHref); context.pop(); }, ); } } else { setState(() { editorState.toggleAttribute(currentDecoration.name); }); } }, ); }) .nonNulls .toList(); return GridView.count( shrinkWrap: true, padding: EdgeInsets.zero, crossAxisCount: 2, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 4, children: children, ); } void _closeKeyboard() { editorState.updateSelectionWithReason( widget.selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, }, ); editorState.service.keyboardService?.closeKeyboard(); } void _updateTextAndHref( String prevText, String? prevHref, String text, String href, ) async { final selection = widget.selection; if (!selection.isSingle) { return; } final node = editorState.getNodeAtPath(selection.start.path); if (node == null) { return; } final transaction = editorState.transaction; if (prevText != text) { transaction.replaceText( node, selection.startIndex, selection.length, text, ); } // if the text is empty, it means the user wants to remove the text if (text.isNotEmpty && prevHref != href) { transaction.formatText(node, selection.startIndex, text.length, { AppFlowyRichTextKeys.href: href.isEmpty ? null : href, }); } 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/mobile_toolbar_item/mobile_block_settings_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet_block_action_widget.dart'; import 'package:appflowy/plugins/base/color/color_picker_screen.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:go_router/go_router.dart'; final mobileBlockSettingsToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, editorState, __) { return onlyShowInSingleSelectionAndTextType(editorState) ? const FlowySvg(FlowySvgs.three_dots_s) : null; }, actionHandler: (_, editorState) async { // show the settings page final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final node = editorState.getNodeAtPath(selection.start.path); final context = node?.context; if (node == null || context == null) { return; } await _showBlockActionSheet( context, editorState, node, selection, ); }, ); Future<void> _showBlockActionSheet( BuildContext context, EditorState editorState, Node node, Selection selection, ) async { final result = await showMobileBottomSheet<bool>( context, showDragHandle: true, showCloseButton: true, showHeader: true, padding: const EdgeInsets.fromLTRB(16, 8, 16, 32), title: LocaleKeys.document_plugins_action.tr(), builder: (context) { return BlockActionBottomSheet( extendActionWidgets: [ Row( children: [ Expanded( child: BottomSheetActionWidget( svg: FlowySvgs.m_color_m, text: LocaleKeys.document_plugins_optionAction_color.tr(), onTap: () async { final option = await context.push<FlowyColorOption?>( Uri( path: MobileColorPickerScreen.routeName, queryParameters: { MobileColorPickerScreen.pageTitle: LocaleKeys .document_plugins_optionAction_color .tr(), }, ).toString(), ); if (option != null) { final transaction = editorState.transaction; transaction.updateNode(node, { blockComponentBackgroundColor: option.id, }); await editorState.apply(transaction); } if (context.mounted) { context.pop(true); } }, ), ), // more options ... ], ), ], onAction: (action) async { context.pop(true); final transaction = editorState.transaction; switch (action) { case BlockActionBottomSheetType.delete: transaction.deleteNode(node); break; case BlockActionBottomSheetType.duplicate: transaction.insertNode( node.path.next, node.copyWith(), ); break; case BlockActionBottomSheetType.insertAbove: case BlockActionBottomSheetType.insertBelow: final path = action == BlockActionBottomSheetType.insertAbove ? node.path : node.path.next; transaction ..insertNode( path, paragraphNode(), ) ..afterSelection = Selection.collapsed( Position( path: path, ), ); break; default: } if (transaction.operations.isNotEmpty) { await editorState.apply(transaction); } }, ); }, ); if (result != true) { // restore the selection editorState.selection = 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/mobile_toolbar_item/mobile_convert_block_toolbar_item.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/document/presentation/editor_plugins/mobile_toolbar_item/mobile_blocks_menu.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:easy_localization/easy_localization.dart'; // convert the current block to other block types // only show in single selection and text type final mobileConvertBlockToolbarItem = MobileToolbarItem.withMenu( itemIconBuilder: (_, editorState, ___) { if (!onlyShowInSingleSelectionAndTextType(editorState)) { return null; } return const FlowySvg( FlowySvgs.convert_s, size: Size.square(22), ); }, itemMenuBuilder: (_, editorState, service) { final selection = editorState.selection; if (selection == null) { return null; } return BlocksMenu( items: _convertToBlockMenuItems, editorState: editorState, service: service, ); }, ); final _convertToBlockMenuItems = [ // paragraph BlockMenuItem( blockType: ParagraphBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_text_decoration_m), label: LocaleKeys.editor_text.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( ParagraphBlockKeys.type, selection: selection, ), ), // to-do list BlockMenuItem( blockType: TodoListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_checkbox_m), label: LocaleKeys.editor_checkbox.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( TodoListBlockKeys.type, selection: selection, extraAttributes: { TodoListBlockKeys.checked: false, }, ), ), // heading 1 - 3 BlockMenuItem( blockType: HeadingBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_h1_m), label: LocaleKeys.editor_heading1.tr(), isSelected: (editorState, selection) => _isHeadingSelected( editorState, selection, 1, ), onTap: (editorState, selection, _) { final isSelected = _isHeadingSelected( editorState, selection, 1, ); editorState.convertBlockType( HeadingBlockKeys.type, selection: selection, isSelected: isSelected, extraAttributes: { HeadingBlockKeys.level: 1, }, ); }, ), BlockMenuItem( blockType: HeadingBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_h2_m), label: LocaleKeys.editor_heading2.tr(), isSelected: (editorState, selection) => _isHeadingSelected( editorState, selection, 2, ), onTap: (editorState, selection, _) { final isSelected = _isHeadingSelected( editorState, selection, 2, ); editorState.convertBlockType( HeadingBlockKeys.type, selection: selection, isSelected: isSelected, extraAttributes: { HeadingBlockKeys.level: 2, }, ); }, ), BlockMenuItem( blockType: HeadingBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_h3_m), label: LocaleKeys.editor_heading3.tr(), isSelected: (editorState, selection) => _isHeadingSelected( editorState, selection, 3, ), onTap: (editorState, selection, _) { final isSelected = _isHeadingSelected( editorState, selection, 3, ); editorState.convertBlockType( HeadingBlockKeys.type, selection: selection, isSelected: isSelected, extraAttributes: { HeadingBlockKeys.level: 3, }, ); }, ), // bulleted list BlockMenuItem( blockType: BulletedListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_bulleted_list_m), label: LocaleKeys.editor_bulletedList.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( BulletedListBlockKeys.type, selection: selection, ), ), // numbered list BlockMenuItem( blockType: NumberedListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_numbered_list_m), label: LocaleKeys.editor_numberedList.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( NumberedListBlockKeys.type, selection: selection, ), ), // toggle list BlockMenuItem( blockType: ToggleListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_toggle_list_m), label: LocaleKeys.document_plugins_toggleList.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( selection: selection, ToggleListBlockKeys.type, ), ), // quote BlockMenuItem( blockType: QuoteBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_quote_m), label: LocaleKeys.editor_quote.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( selection: selection, QuoteBlockKeys.type, ), ), // callout BlockMenuItem( blockType: CalloutBlockKeys.type, // FIXME: update icon icon: const Icon(Icons.note_rounded), label: LocaleKeys.document_plugins_callout.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( CalloutBlockKeys.type, selection: selection, extraAttributes: { CalloutBlockKeys.icon: '📌', }, ), ), // code BlockMenuItem( blockType: CodeBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_code_m), label: LocaleKeys.document_selectionMenu_codeBlock.tr(), onTap: (editorState, selection, _) => editorState.convertBlockType( CodeBlockKeys.type, selection: selection, ), ), ]; bool _isHeadingSelected( EditorState editorState, Selection selection, int level, ) { final node = editorState.getNodeAtPath(selection.start.path); final type = node?.type; if (node == null || type == null) { return false; } return type == HeadingBlockKeys.type && node.attributes[HeadingBlockKeys.level] == level; }
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/mobile_toolbar_item/mobile_align_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.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'; final mobileAlignToolbarItem = MobileToolbarItem.withMenu( itemIconBuilder: (_, editorState, __) { return onlyShowInTextType(editorState) ? const FlowySvg( FlowySvgs.toolbar_align_center_s, size: Size.square(32), ) : null; }, itemMenuBuilder: (_, editorState, ___) { final selection = editorState.selection; if (selection == null) { return null; } return _MobileAlignMenu( editorState: editorState, selection: selection, ); }, ); class _MobileAlignMenu extends StatelessWidget { const _MobileAlignMenu({ required this.editorState, required this.selection, }); final Selection selection; final EditorState editorState; @override Widget build(BuildContext context) { return GridView.count( padding: EdgeInsets.zero, crossAxisCount: 3, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 3, shrinkWrap: true, children: [ _buildAlignmentButton( context, 'left', LocaleKeys.document_plugins_optionAction_left.tr(), ), _buildAlignmentButton( context, 'center', LocaleKeys.document_plugins_optionAction_center.tr(), ), _buildAlignmentButton( context, 'right', LocaleKeys.document_plugins_optionAction_right.tr(), ), ], ); } Widget _buildAlignmentButton( BuildContext context, String alignment, String label, ) { final nodes = editorState.getNodesInSelection(selection); if (nodes.isEmpty) { const SizedBox.shrink(); } bool isSatisfyCondition(bool Function(Object? value) test) { return nodes.every( (n) => test(n.attributes[blockComponentAlign]), ); } final data = switch (alignment) { 'left' => FlowySvgs.toolbar_align_left_s, 'center' => FlowySvgs.toolbar_align_center_s, 'right' => FlowySvgs.toolbar_align_right_s, _ => throw UnimplementedError(), }; final isSelected = isSatisfyCondition((value) => value == alignment); return MobileToolbarItemMenuBtn( icon: FlowySvg(data, size: const Size.square(28)), label: FlowyText(label), isSelected: isSelected, onPressed: () async { await editorState.updateNode( selection, (node) => node.copyWith( attributes: { ...node.attributes, blockComponentAlign: alignment, }, ), ); }, ); } }
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/mobile_toolbar_item/mobile_block_settings_screen.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/base/app_bar_actions.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; enum MobileBlockActionType { delete, duplicate, insertAbove, insertBelow, color; static List<MobileBlockActionType> get standard => [ MobileBlockActionType.delete, MobileBlockActionType.duplicate, MobileBlockActionType.insertAbove, MobileBlockActionType.insertBelow, ]; static MobileBlockActionType fromActionString(String actionString) { return MobileBlockActionType.values.firstWhere( (e) => e.actionString == actionString, orElse: () => throw Exception('Unknown action string: $actionString'), ); } String get actionString => toString(); FlowySvgData get icon { return switch (this) { MobileBlockActionType.delete => FlowySvgs.m_delete_m, MobileBlockActionType.duplicate => FlowySvgs.m_duplicate_m, MobileBlockActionType.insertAbove => FlowySvgs.arrow_up_s, MobileBlockActionType.insertBelow => FlowySvgs.arrow_down_s, MobileBlockActionType.color => FlowySvgs.m_color_m, }; } String get i18n { return switch (this) { MobileBlockActionType.delete => LocaleKeys.button_delete.tr(), MobileBlockActionType.duplicate => LocaleKeys.button_duplicate.tr(), MobileBlockActionType.insertAbove => LocaleKeys.button_insertAbove.tr(), MobileBlockActionType.insertBelow => LocaleKeys.button_insertBelow.tr(), MobileBlockActionType.color => LocaleKeys.document_plugins_optionAction_color.tr(), }; } } class MobileBlockSettingsScreen extends StatelessWidget { const MobileBlockSettingsScreen({super.key, required this.actions}); final List<MobileBlockActionType> actions; static const routeName = '/block_settings'; // the action string comes from the enum MobileBlockActionType // example: MobileBlockActionType.delete.actionString, MobileBlockActionType.duplicate.actionString, etc. static const supportedActions = 'actions'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( titleSpacing: 0, title: FlowyText.semibold( LocaleKeys.titleBar_actions.tr(), fontSize: 14.0, ), leading: const AppBarBackButton(), ), body: SafeArea( child: ListView.separated( itemCount: actions.length, itemBuilder: (context, index) { final action = actions[index]; return FlowyButton( text: Padding( padding: const EdgeInsets.symmetric( horizontal: 12.0, vertical: 18.0, ), child: FlowyText(action.i18n), ), leftIcon: FlowySvg(action.icon), leftIconSize: const Size.square(24), onTap: () {}, ); }, separatorBuilder: (context, index) => const Divider( height: 1.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/mobile_toolbar_item/mobile_text_decoration_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_item/utils.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; final customTextDecorationMobileToolbarItem = MobileToolbarItem.withMenu( itemIconBuilder: (_, __, ___) => const FlowySvg( FlowySvgs.text_s, size: Size.square(24), ), itemMenuBuilder: (_, editorState, service) { final selection = editorState.selection; if (selection == null) { return const SizedBox.shrink(); } return _TextDecorationMenu( editorState, selection, service, ); }, ); class _TextDecorationMenu extends StatefulWidget { const _TextDecorationMenu( this.editorState, this.selection, this.service, ); final EditorState editorState; final Selection selection; final MobileToolbarWidgetService service; @override State<_TextDecorationMenu> createState() => _TextDecorationMenuState(); } class _TextDecorationMenuState extends State<_TextDecorationMenu> { EditorState get editorState => widget.editorState; final textDecorations = [ // BIUS TextDecorationUnit( icon: AFMobileIcons.bold, label: AppFlowyEditorL10n.current.bold, name: AppFlowyRichTextKeys.bold, ), TextDecorationUnit( icon: AFMobileIcons.italic, label: AppFlowyEditorL10n.current.italic, name: AppFlowyRichTextKeys.italic, ), TextDecorationUnit( icon: AFMobileIcons.underline, label: AppFlowyEditorL10n.current.underline, name: AppFlowyRichTextKeys.underline, ), TextDecorationUnit( icon: AFMobileIcons.strikethrough, label: AppFlowyEditorL10n.current.strikethrough, name: AppFlowyRichTextKeys.strikethrough, ), // Code TextDecorationUnit( icon: AFMobileIcons.code, label: AppFlowyEditorL10n.current.embedCode, name: AppFlowyRichTextKeys.code, ), // link TextDecorationUnit( icon: AFMobileIcons.link, label: AppFlowyEditorL10n.current.link, name: AppFlowyRichTextKeys.href, ), ]; @override void dispose() { widget.editorState.selectionExtraInfo = null; super.dispose(); } @override Widget build(BuildContext context) { final children = textDecorations .map((currentDecoration) { // Check current decoration is active or not final selection = widget.selection; // only show edit link bottom sheet when selection is not collapsed if (selection.isCollapsed && currentDecoration.name == AppFlowyRichTextKeys.href) { return null; } final nodes = editorState.getNodesInSelection(selection); final bool isSelected; if (selection.isCollapsed) { isSelected = editorState.toggledStyle.containsKey( currentDecoration.name, ); } else { isSelected = nodes.allSatisfyInSelection(selection, (delta) { return delta.everyAttributes( (attributes) => attributes[currentDecoration.name] == true, ); }); } return MobileToolbarItemMenuBtn( icon: AFMobileIcon( afMobileIcons: currentDecoration.icon, color: MobileToolbarTheme.of(context).iconColor, ), label: FlowyText(currentDecoration.label), isSelected: isSelected, onPressed: () { if (currentDecoration.name == AppFlowyRichTextKeys.href) { if (selection.isCollapsed) { return; } _closeKeyboard(); // show edit link bottom sheet final context = nodes.firstOrNull?.context; if (context != null) { final text = editorState .getTextInSelection( widget.selection, ) .join(); final href = editorState.getDeltaAttributeValueInSelection<String>( AppFlowyRichTextKeys.href, widget.selection, ); showEditLinkBottomSheet( context, text, href, (context, newText, newHref) { _updateTextAndHref(text, href, newText, newHref); context.pop(); }, ); } } else { setState(() { editorState.toggleAttribute(currentDecoration.name); }); } }, ); }) .nonNulls .toList(); return GridView.count( shrinkWrap: true, padding: EdgeInsets.zero, crossAxisCount: 2, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 4, children: children, ); } void _closeKeyboard() { editorState.updateSelectionWithReason( widget.selection, extraInfo: { selectionExtraInfoDisableMobileToolbarKey: true, }, ); editorState.service.keyboardService?.closeKeyboard(); } void _updateTextAndHref( String prevText, String? prevHref, String text, String href, ) async { final selection = widget.selection; if (!selection.isSingle) { return; } final node = editorState.getNodeAtPath(selection.start.path); if (node == null) { return; } final transaction = editorState.transaction; if (prevText != text) { transaction.replaceText( node, selection.startIndex, selection.length, text, ); } // if the text is empty, it means the user wants to remove the text if (text.isNotEmpty && prevHref != href) { transaction.formatText(node, selection.startIndex, text.length, { AppFlowyRichTextKeys.href: href.isEmpty ? null : href, }); } 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/mobile_toolbar_item/mobile_indent_toolbar_item.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; final mobileIndentToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, editorState, __) { return onlyShowInTextType(editorState) ? const Icon(Icons.format_indent_increase_rounded) : null; }, actionHandler: (_, editorState) { indentCommand.execute(editorState); }, ); final mobileOutdentToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, editorState, __) { return onlyShowInTextType(editorState) ? const Icon(Icons.format_indent_decrease_rounded) : null; }, actionHandler: (_, editorState) { outdentCommand.execute(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/mobile_toolbar_item/mobile_blocks_menu.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flutter/material.dart'; class BlockMenuItem { const BlockMenuItem({ required this.blockType, required this.icon, required this.label, required this.onTap, this.isSelected, }); // block type final String blockType; final Widget icon; final String label; // callback final void Function( EditorState editorState, Selection selection, // used to control the open or close the menu MobileToolbarWidgetService service, ) onTap; final bool Function( EditorState editorState, Selection selection, )? isSelected; } class BlocksMenu extends StatelessWidget { const BlocksMenu({ super.key, required this.editorState, required this.items, required this.service, }); final EditorState editorState; final List<BlockMenuItem> items; final MobileToolbarWidgetService service; @override Widget build(BuildContext context) { return GridView.count( crossAxisCount: 2, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 4, padding: const EdgeInsets.only( bottom: 36.0, ), shrinkWrap: true, children: items.map((item) { final selection = editorState.selection; if (selection == null) { return const SizedBox.shrink(); } bool isSelected = false; if (item.isSelected != null) { isSelected = item.isSelected!(editorState, selection); } else { isSelected = _isSelected(editorState, selection, item.blockType); } return MobileToolbarItemMenuBtn( icon: item.icon, label: FlowyText(item.label), isSelected: isSelected, onPressed: () async { item.onTap(editorState, selection, service); }, ); }).toList(), ); } bool _isSelected( EditorState editorState, Selection selection, String blockType, ) { final node = editorState.getNodeAtPath(selection.start.path); final type = node?.type; if (node == null || type == null) { return false; } return type == blockType; } }
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/mobile_toolbar_item/mobile_add_block_toolbar_item.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/document/presentation/editor_plugins/mobile_toolbar_item/mobile_blocks_menu.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:easy_localization/easy_localization.dart'; // convert the current block to other block types // only show in single selection and text type final mobileAddBlockToolbarItem = MobileToolbarItem.withMenu( itemIconBuilder: (_, editorState, ___) { if (!onlyShowInSingleSelectionAndTextType(editorState)) { return null; } return const FlowySvg( FlowySvgs.add_m, size: Size.square(48), ); }, itemMenuBuilder: (_, editorState, service) { final selection = editorState.selection; if (selection == null) { return null; } return BlocksMenu( items: _addBlockMenuItems, editorState: editorState, service: service, ); }, ); final _addBlockMenuItems = [ // paragraph BlockMenuItem( blockType: ParagraphBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_text_decoration_m), label: LocaleKeys.editor_text.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, paragraphNode(), ); }, ), // to-do list BlockMenuItem( blockType: TodoListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_checkbox_m), label: LocaleKeys.editor_checkbox.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, todoListNode(checked: false), ); }, ), // heading 1 - 3 BlockMenuItem( blockType: HeadingBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_h1_m), label: LocaleKeys.editor_heading1.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, headingNode(level: 1), ); }, ), BlockMenuItem( blockType: HeadingBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_h2_m), label: LocaleKeys.editor_heading2.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, headingNode(level: 2), ); }, ), BlockMenuItem( blockType: HeadingBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_h3_m), label: LocaleKeys.editor_heading3.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, headingNode(level: 3), ); }, ), // bulleted list BlockMenuItem( blockType: BulletedListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_bulleted_list_m), label: LocaleKeys.editor_bulletedList.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, bulletedListNode(), ); }, ), // numbered list BlockMenuItem( blockType: NumberedListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_numbered_list_m), label: LocaleKeys.editor_numberedList.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, numberedListNode(), ); }, ), // toggle list BlockMenuItem( blockType: ToggleListBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_toggle_list_m), label: LocaleKeys.document_plugins_toggleList.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, toggleListBlockNode(), ); }, ), // quote BlockMenuItem( blockType: QuoteBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_quote_m), label: LocaleKeys.editor_quote.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, quoteNode(), ); }, ), // callout BlockMenuItem( blockType: CalloutBlockKeys.type, icon: const Icon(Icons.note_rounded), label: LocaleKeys.document_plugins_callout.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, calloutNode(), ); }, ), // code BlockMenuItem( blockType: CodeBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_code_m), label: LocaleKeys.document_selectionMenu_codeBlock.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertBlockOrReplaceCurrentBlock( selection, codeBlockNode(), ); }, ), // divider BlockMenuItem( blockType: DividerBlockKeys.type, icon: const FlowySvg(FlowySvgs.m_divider_m), label: LocaleKeys.editor_divider.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertDivider(selection); }, ), // math equation BlockMenuItem( blockType: MathEquationBlockKeys.type, icon: const FlowySvg( FlowySvgs.math_lg, size: Size.square(22), ), label: LocaleKeys.document_plugins_mathEquation_name.tr(), isSelected: _unSelectable, onTap: (editorState, selection, service) async { service.closeItemMenu(); await editorState.insertMathEquation(selection); }, ), ]; bool _unSelectable( EditorState editorState, Selection selection, ) { return false; } extension EditorStateAddBlock on EditorState { Future<void> insertBlockOrReplaceCurrentBlock( Selection selection, Node insertedNode, ) async { // If the current block is not an empty paragraph block, // then insert a new block below the current block. final node = getNodeAtPath(selection.start.path); if (node == null) { return; } final transaction = this.transaction; if (node.type != ParagraphBlockKeys.type || (node.delta?.isNotEmpty ?? true)) { final path = node.path.next; // insert the block below the current empty paragraph block transaction ..insertNode(path, insertedNode) ..afterSelection = Selection.collapsed( Position(path: path), ); } else { final path = node.path; // replace the current empty paragraph block with the inserted block transaction ..insertNode(path, insertedNode) ..deleteNode(node) ..afterSelection = Selection.collapsed( Position(path: path), ) ..selectionExtraInfo = null; } await apply(transaction); service.keyboardService?.enableKeyBoard(selection); } Future<void> insertMathEquation( Selection selection, ) async { final path = selection.start.path; final node = getNodeAtPath(path); final delta = node?.delta; if (node == null || delta == null) { return; } final transaction = this.transaction; final insertedNode = mathEquationNode(); if (delta.isEmpty) { transaction ..insertNode(path, insertedNode) ..deleteNode(node); } else { transaction.insertNode( path.next, insertedNode, ); } await apply(transaction); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { final mathEquationState = getNodeAtPath(path)?.key.currentState; if (mathEquationState != null && mathEquationState is MathEquationBlockComponentWidgetState) { mathEquationState.showEditingDialog(); } }); } Future<void> insertDivider(Selection selection) async { // same as the [handler] of [dividerMenuItem] in Desktop final path = selection.end.path; final node = getNodeAtPath(path); final delta = node?.delta; if (node == null || delta == null) { return; } final insertedPath = delta.isEmpty ? path : path.next; final transaction = this.transaction; transaction.insertNode(insertedPath, dividerNode()); // only insert a new paragraph node when the next node is not a paragraph node // and its delta is not empty. final next = node.next; if (next == null || next.type != ParagraphBlockKeys.type || next.delta?.isNotEmpty == true) { transaction.insertNode( insertedPath, paragraphNode(), ); } transaction.selectionExtraInfo = {}; transaction.afterSelection = Selection.collapsed( Position(path: insertedPath.next), ); await 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/mobile_toolbar_item/utils.dart
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart'; import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet_edit_link_widget.dart'; import 'package:flutter/material.dart'; Future<T?> showEditLinkBottomSheet<T>( BuildContext context, String text, String? href, void Function(BuildContext context, String text, String href) onEdit, ) { return showMobileBottomSheet( context, showHeader: false, showCloseButton: false, showDragHandle: true, padding: const EdgeInsets.symmetric(horizontal: 16), builder: (context) { return MobileBottomSheetEditLinkWidget( text: text, href: href, onEdit: (text, href) => onEdit(context, text, href), ); }, ); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_item
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_item/undo_redo/undo_mobile_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; final undoMobileToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, __, ___) => const FlowySvg( FlowySvgs.m_undo_m, ), actionHandler: (_, editorState) async { editorState.undoManager.undo(); }, );
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_item
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mobile_toolbar_item/undo_redo/redo_mobile_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; final redoMobileToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, __, ___) => const FlowySvg( FlowySvgs.m_redo_m, ), actionHandler: (_, editorState) async { editorState.undoManager.redo(); }, );
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/block_menu/block_menu_button.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/widget/flowy_tooltip.dart'; import 'package:flutter/material.dart'; class MenuBlockButton extends StatelessWidget { const MenuBlockButton({ super.key, required this.tooltip, required this.iconData, this.onTap, }); final VoidCallback? onTap; final String tooltip; final FlowySvgData iconData; @override Widget build(BuildContext context) { return FlowyButton( useIntrinsicWidth: true, onTap: onTap, text: FlowyTooltip( message: tooltip, child: FlowySvg( iconData, size: const Size.square(16), ), ), ); } }
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/migration/editor_migration.dart
import 'dart:convert'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:collection/collection.dart'; class EditorMigration { // AppFlowy 0.1.x -> 0.2 // // The cover node has been deprecated, and use page/attributes/cover instead. // cover node -> page/attributes/cover // // mark the textNode deprecated. use paragraph node instead. // text node -> paragraph node // delta -> attributes/delta // // mark the subtype deprecated. use type instead. // for example, text/checkbox -> checkbox_list // // some attribute keys. // ... static Document migrateDocument(String json) { final map = jsonDecode(json); assert(map['document'] != null); final documentV0 = Map<String, Object>.from(map['document'] as Map); final rootV0 = NodeV0.fromJson(documentV0); final root = migrateNode(rootV0); return Document(root: root); } static Node migrateNode(NodeV0 nodeV0) { Node? node; final children = nodeV0.children.map((e) => migrateNode(e)).toList(); final id = nodeV0.id; if (id == 'editor') { final coverNode = children.firstWhereOrNull( (element) => element.id == 'cover', ); if (coverNode != null) { node = pageNode( children: children, attributes: coverNode.attributes, ); } else { node = pageNode(children: children); } } else if (id == 'callout') { final emoji = nodeV0.attributes['emoji'] ?? '📌'; final delta = nodeV0.children.whereType<TextNodeV0>().fold(Delta(), (p, e) { final delta = migrateDelta(e.delta); final textInserts = delta.whereType<TextInsert>(); for (final element in textInserts) { p.add(element); } return p..insert('\n'); }); node = calloutNode( emoji: emoji, delta: delta, ); } else if (id == 'divider') { // divider -> divider node = dividerNode(); } else if (id == 'math_equation') { // math_equation -> math_equation final formula = nodeV0.attributes['math_equation'] ?? ''; node = mathEquationNode(formula: formula); } else if (nodeV0 is TextNodeV0) { final delta = migrateDelta(nodeV0.delta); final deltaJson = delta.toJson(); final attributes = {'delta': deltaJson}; if (id == 'text') { // text -> paragraph node = paragraphNode( attributes: attributes, children: children, ); } else if (nodeV0.id == 'text/heading') { // text/heading -> heading final heading = nodeV0.attributes.heading?.replaceAll('h', ''); final level = int.tryParse(heading ?? '') ?? 1; node = headingNode( level: level, attributes: attributes, ); } else if (id == 'text/checkbox') { // text/checkbox -> todo_list final checked = nodeV0.attributes.check; node = todoListNode( checked: checked, attributes: attributes, children: children, ); } else if (id == 'text/quote') { // text/quote -> quote node = quoteNode(attributes: attributes); } else if (id == 'text/number-list') { // text/number-list -> numbered_list node = numberedListNode( attributes: attributes, children: children, ); } else if (id == 'text/bulleted-list') { // text/bulleted-list -> bulleted_list node = bulletedListNode( attributes: attributes, children: children, ); } else if (id == 'text/code_block') { // text/code_block -> code final language = nodeV0.attributes['language']; node = codeBlockNode(delta: delta, language: language); } } else if (id == 'cover') { node = paragraphNode(); } return node ?? paragraphNode(text: jsonEncode(nodeV0.toJson())); } // migrate the attributes. // backgroundColor -> highlightColor // color -> textColor static Delta migrateDelta(Delta delta) { final textInserts = delta .whereType<TextInsert>() .map( (e) => TextInsert( e.text, attributes: migrateAttributes(e.attributes), ), ) .toList(growable: false); return Delta(operations: textInserts.toList()); } static Attributes? migrateAttributes(Attributes? attributes) { if (attributes == null) { return null; } const backgroundColor = 'backgroundColor'; if (attributes.containsKey(backgroundColor)) { attributes[AppFlowyRichTextKeys.backgroundColor] = attributes[backgroundColor]; attributes.remove(backgroundColor); } const color = 'color'; if (attributes.containsKey(color)) { attributes[AppFlowyRichTextKeys.textColor] = attributes[color]; attributes.remove(color); } return attributes; } }
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/copy_and_paste/custom_cut_command.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/editor_state_paste_node_extension.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; /// cut. /// /// - support /// - desktop /// - web /// - mobile /// final CommandShortcutEvent customCutCommand = CommandShortcutEvent( key: 'cut the selected content', getDescription: () => AppFlowyEditorL10n.current.cmdCutSelection, command: 'ctrl+x', macOSCommand: 'cmd+x', handler: _cutCommandHandler, ); CommandShortcutEventHandler _cutCommandHandler = (editorState) { customCopyCommand.execute(editorState); editorState.deleteSelectionIfNeeded(); return KeyEventResult.handled; };
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/copy_and_paste/custom_copy_command.dart
import 'dart:convert'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; /// Copy. /// /// - support /// - desktop /// - web /// - mobile /// final CommandShortcutEvent customCopyCommand = CommandShortcutEvent( key: 'copy the selected content', getDescription: () => AppFlowyEditorL10n.current.cmdCopySelection, command: 'ctrl+c', macOSCommand: 'cmd+c', handler: _copyCommandHandler, ); CommandShortcutEventHandler _copyCommandHandler = (editorState) { final selection = editorState.selection?.normalized; if (selection == null || selection.isCollapsed) { return KeyEventResult.ignored; } // plain text. final text = editorState.getTextInSelection(selection).join('\n'); final nodes = editorState.getSelectedNodes(selection: selection); final document = Document.blank()..insert([0], nodes); // in app json final inAppJson = jsonEncode(document.toJson()); // html final html = documentToHTML(document); () async { await getIt<ClipboardService>().setData( ClipboardServiceData( plainText: text, html: html, inAppJson: inAppJson, ), ); }(); return KeyEventResult.handled; };
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/copy_and_paste/clipboard_service.dart
import 'dart:async'; import 'dart:convert'; import 'package:appflowy_backend/log.dart'; import 'package:flutter/foundation.dart'; import 'package:super_clipboard/super_clipboard.dart'; /// Used for in-app copy and paste without losing the format. /// /// It's a Json string representing the copied editor nodes. final inAppJsonFormat = CustomValueFormat<String>( applicationId: 'io.appflowy.InAppJsonType', onDecode: (value, platformType) async { if (value is PlatformDataProvider) { final data = await value.getData(platformType); if (data is List<int>) { return utf8.decode(data, allowMalformed: true); } if (data is String) { return Uri.decodeFull(data); } } return null; }, onEncode: (value, platformType) => utf8.encode(value), ); class ClipboardServiceData { const ClipboardServiceData({ this.plainText, this.html, this.image, this.inAppJson, }); final String? plainText; final String? html; final (String, Uint8List?)? image; final String? inAppJson; } class ClipboardService { Future<void> setData(ClipboardServiceData data) async { final plainText = data.plainText; final html = data.html; final inAppJson = data.inAppJson; final image = data.image; final item = DataWriterItem(); if (plainText != null) { item.add(Formats.plainText(plainText)); } if (html != null) { item.add(Formats.htmlText(html)); } if (inAppJson != null) { item.add(inAppJsonFormat(inAppJson)); } if (image != null && image.$2?.isNotEmpty == true) { switch (image.$1) { case 'png': item.add(Formats.png(image.$2!)); break; case 'jpeg': item.add(Formats.jpeg(image.$2!)); break; case 'gif': item.add(Formats.gif(image.$2!)); break; default: throw Exception('unsupported image format: ${image.$1}'); } } await SystemClipboard.instance?.write([item]); } Future<void> setPlainText(String text) async { await SystemClipboard.instance?.write([ DataWriterItem()..add(Formats.plainText(text)), ]); } Future<ClipboardServiceData> getData() async { final reader = await SystemClipboard.instance?.read(); if (reader == null) { return const ClipboardServiceData(); } for (final item in reader.items) { final availableFormats = await item.rawReader!.getAvailableFormats(); Log.debug( 'availableFormats: $availableFormats', ); } final plainText = await reader.readValue(Formats.plainText); final html = await reader.readValue(Formats.htmlText); final inAppJson = await reader.readValue(inAppJsonFormat); (String, Uint8List?)? image; if (reader.canProvide(Formats.png)) { image = ('png', await reader.readFile(Formats.png)); } else if (reader.canProvide(Formats.jpeg)) { image = ('jpeg', await reader.readFile(Formats.jpeg)); } else if (reader.canProvide(Formats.gif)) { image = ('gif', await reader.readFile(Formats.gif)); } return ClipboardServiceData( plainText: plainText, html: html, image: image, inAppJson: inAppJson, ); } } extension on DataReader { Future<Uint8List?>? readFile(FileFormat format) { final c = Completer<Uint8List?>(); final progress = getFile( format, (file) async { try { final all = await file.readAll(); c.complete(all); } catch (e) { c.completeError(e); } }, onError: (e) { c.completeError(e); }, ); if (progress == null) { c.complete(null); } return c.future; } }
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/copy_and_paste/paste_from_image.dart
import 'dart:io'; import 'dart:typed_data'; 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/image/image_util.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; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra/uuid.dart'; import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; extension PasteFromImage on EditorState { static final supportedImageFormats = [ 'png', 'jpeg', 'gif', ]; Future<bool> pasteImage(String format, Uint8List imageBytes) async { if (!supportedImageFormats.contains(format)) { return false; } final context = document.root.context; if (context == null) { return false; } final isLocalMode = context.read<DocumentBloc>().isLocalMode; 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, 'tmp_${uuid()}.$format', ); await File(copyToPath).writeAsBytes(imageBytes); final String? path; if (context.mounted) { showSnackBarMessage( context, LocaleKeys.document_imageBlock_imageIsUploading.tr(), ); } if (isLocalMode) { path = await saveImageToLocalStorage(copyToPath); } else { final result = await saveImageToCloudStorage(copyToPath); final errorMessage = result.$2; if (errorMessage != null && context.mounted) { showSnackBarMessage( context, errorMessage, ); return false; } path = result.$1; } if (path != null) { await insertImageNode(path); } await File(copyToPath).delete(); return true; } catch (e) { Log.error('cannot copy image file', e); if (context.mounted) { showSnackBarMessage( context, LocaleKeys.document_imageBlock_error_invalidImage.tr(), ); } } 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/copy_and_paste/paste_from_html.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/editor_state_paste_node_extension.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; extension PasteFromHtml on EditorState { Future<bool> pasteHtml(String html) async { final nodes = htmlToDocument(html).root.children.toList(); // remove the front and back empty line while (nodes.isNotEmpty && nodes.first.delta?.isEmpty == true) { nodes.removeAt(0); } while (nodes.isNotEmpty && nodes.last.delta?.isEmpty == true) { nodes.removeLast(); } // if there's no nodes being converted successfully, return false if (nodes.isEmpty) { return false; } if (nodes.length == 1) { await pasteSingleLineNode(nodes.first); } else { await pasteMultiLineNodes(nodes.toList()); } 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/copy_and_paste/custom_paste_command.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/editor_state_paste_node_extension.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_html.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_image.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_in_app_json.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_plain_text.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; import 'package:flutter/material.dart'; import 'package:string_validator/string_validator.dart'; /// Paste. /// /// - support /// - desktop /// - web /// - mobile /// final CommandShortcutEvent customPasteCommand = CommandShortcutEvent( key: 'paste the content', getDescription: () => AppFlowyEditorL10n.current.cmdPasteContent, command: 'ctrl+v', macOSCommand: 'cmd+v', handler: _pasteCommandHandler, ); CommandShortcutEventHandler _pasteCommandHandler = (editorState) { final selection = editorState.selection; if (selection == null) { return KeyEventResult.ignored; } // because the event handler is not async, so we need to use wrap the async function here () async { // dispatch the paste event final data = await getIt<ClipboardService>().getData(); final inAppJson = data.inAppJson; final html = data.html; final plainText = data.plainText; final image = data.image; // paste as link preview final result = await _pasteAsLinkPreview(editorState, plainText); if (result) { return; } // Order: // 1. in app json format // 2. html // 3. image // 4. plain text // try to paste the content in order, if any of them is failed, then try the next one if (inAppJson != null && inAppJson.isNotEmpty) { await editorState.deleteSelectionIfNeeded(); final result = await editorState.pasteInAppJson(inAppJson); if (result) { return; } } if (html != null && html.isNotEmpty) { await editorState.deleteSelectionIfNeeded(); final result = await editorState.pasteHtml(html); if (result) { return; } } if (image != null && image.$2?.isNotEmpty == true) { await editorState.deleteSelectionIfNeeded(); final result = await editorState.pasteImage(image.$1, image.$2!); if (result) { return; } } if (plainText != null && plainText.isNotEmpty) { await editorState.pastePlainText(plainText); } }(); return KeyEventResult.handled; }; Future<bool> _pasteAsLinkPreview( EditorState editorState, String? text, ) async { if (text == null || !isURL(text)) { return false; } final selection = editorState.selection; if (selection == null || !selection.isCollapsed || selection.startIndex != 0) { return false; } final node = editorState.getNodeAtPath(selection.start.path); if (node == null || node.type != ParagraphBlockKeys.type || node.delta?.toPlainText().isNotEmpty == true) { return false; } final transaction = editorState.transaction; transaction.insertNode( selection.start.path, linkPreviewNode(url: text), ); await editorState.apply(transaction); 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/copy_and_paste/paste_from_plain_text.dart
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/editor_state_paste_node_extension.dart'; import 'package:appflowy/shared/patterns/common_patterns.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; extension PasteFromPlainText on EditorState { Future<void> pastePlainText(String plainText) async { if (await pasteHtmlIfAvailable(plainText)) { return; } await deleteSelectionIfNeeded(); final nodes = plainText .split('\n') .map( (e) => e ..replaceAll(r'\r', '') ..trimRight(), ) .map((e) { // parse the url content final Attributes attributes = {}; if (hrefRegex.hasMatch(e)) { attributes[AppFlowyRichTextKeys.href] = e; } return Delta()..insert(e, attributes: attributes); }) .map((e) => paragraphNode(delta: e)) .toList(); if (nodes.isEmpty) { return; } if (nodes.length == 1) { await pasteSingleLineNode(nodes.first); } else { await pasteMultiLineNodes(nodes.toList()); } } Future<bool> pasteHtmlIfAvailable(String plainText) async { final selection = this.selection; if (selection == null || !selection.isSingle || selection.isCollapsed || !hrefRegex.hasMatch(plainText)) { return false; } final node = getNodeAtPath(selection.start.path); if (node == null) { return false; } final transaction = this.transaction; transaction.formatText(node, selection.startIndex, selection.length, { AppFlowyRichTextKeys.href: plainText, }); await apply(transaction); 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/copy_and_paste/editor_state_paste_node_extension.dart
import 'package:appflowy_editor/appflowy_editor.dart'; extension PasteNodes on EditorState { Future<void> pasteSingleLineNode(Node insertedNode) async { final selection = await deleteSelectionIfNeeded(); if (selection == null) { return; } final node = getNodeAtPath(selection.start.path); final delta = node?.delta; if (node == null || delta == null) { return; } final transaction = this.transaction; final insertedDelta = insertedNode.delta; // if the node is empty and its type is paragprah, replace it with the inserted node. if (delta.isEmpty && node.type == ParagraphBlockKeys.type) { transaction.insertNode( selection.end.path.next, insertedNode, ); transaction.deleteNode(node); final path = calculatePath(selection.end.path, [insertedNode]); final offset = calculateLength([insertedNode]); transaction.afterSelection = Selection.collapsed( Position( path: path, offset: offset, ), ); } else if (insertedDelta != null) { // if the node is not empty, insert the delta from inserted node after the selection. transaction.insertTextDelta(node, selection.endIndex, insertedDelta); } await apply(transaction); } Future<void> pasteMultiLineNodes(List<Node> nodes) async { assert(nodes.length > 1); final selection = await deleteSelectionIfNeeded(); if (selection == null) { return; } final node = getNodeAtPath(selection.start.path); final delta = node?.delta; if (node == null || delta == null) { return; } final transaction = this.transaction; final lastNodeLength = calculateLength(nodes); // merge the current selected node delta into the nodes. if (delta.isNotEmpty) { nodes.first.insertDelta( delta.slice(0, selection.startIndex), insertAfter: false, ); nodes.last.insertDelta( delta.slice(selection.endIndex), ); } if (delta.isEmpty && node.type != ParagraphBlockKeys.type) { nodes[0] = nodes.first.copyWith( type: node.type, attributes: { ...node.attributes, ...nodes.first.attributes, }, ); } for (final child in node.children) { nodes.last.insert(child); } transaction.insertNodes(selection.end.path, nodes); // delete the current node. transaction.deleteNode(node); final path = calculatePath(selection.start.path, nodes); transaction.afterSelection = Selection.collapsed( Position( path: path, offset: lastNodeLength, ), ); await apply(transaction); } // delete the selection if it's not collapsed. Future<Selection?> deleteSelectionIfNeeded() async { final selection = this.selection; if (selection == null) { return null; } // delete the selection first. if (!selection.isCollapsed) { await deleteSelection(selection); } // fetch selection again.selection = editorState.selection; assert(this.selection?.isCollapsed == true); return this.selection; } Path calculatePath(Path start, List<Node> nodes) { var path = start; for (var i = 0; i < nodes.length; i++) { path = path.next; } path = path.previous; if (nodes.last.children.isNotEmpty) { return [ ...path, ...calculatePath([0], nodes.last.children.toList()), ]; } return path; } int calculateLength(List<Node> nodes) { if (nodes.last.children.isNotEmpty) { return calculateLength(nodes.last.children.toList()); } return nodes.last.delta?.length ?? 0; } } extension on Node { void insertDelta(Delta delta, {bool insertAfter = true}) { assert(delta.every((element) => element is TextInsert)); if (this.delta == null) { updateAttributes({ blockComponentDelta: delta.toJson(), }); } else if (insertAfter) { updateAttributes( { blockComponentDelta: this .delta! .compose( Delta() ..retain(this.delta!.length) ..addAll(delta), ) .toJson(), }, ); } else { updateAttributes( { blockComponentDelta: delta .compose( Delta() ..retain(delta.length) ..addAll(this.delta!), ) .toJson(), }, ); } } }
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/copy_and_paste/paste_from_in_app_json.dart
import 'dart:convert'; import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/editor_state_paste_node_extension.dart'; import 'package:appflowy_backend/log.dart'; import 'package:appflowy_editor/appflowy_editor.dart' hide Log; extension PasteFromInAppJson on EditorState { Future<bool> pasteInAppJson(String inAppJson) async { try { final nodes = Document.fromJson(jsonDecode(inAppJson)).root.children; if (nodes.isEmpty) { return false; } if (nodes.length == 1) { await pasteSingleLineNode(nodes.first); } else { await pasteMultiLineNodes(nodes.toList()); } return true; } catch (e) { Log.error( 'Failed to paste in app json: $inAppJson, error: $e', ); } 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/stability_ai/stability_ai_client.dart
import 'dart:async'; import 'dart:convert'; import 'package:appflowy/plugins/document/presentation/editor_plugins/stability_ai/stability_ai_error.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:http/http.dart' as http; enum StabilityAIRequestType { imageGenerations; Uri get uri { switch (this) { case StabilityAIRequestType.imageGenerations: return Uri.parse( 'https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image', ); } } } abstract class StabilityAIRepository { /// Generate image from Stability AI /// /// [prompt] is the prompt text /// [n] is the number of images to generate /// /// the return value is a list of base64 encoded images Future<FlowyResult<List<String>, StabilityAIRequestError>> generateImage({ required String prompt, int n = 1, }); } class HttpStabilityAIRepository implements StabilityAIRepository { const HttpStabilityAIRepository({ required this.client, required this.apiKey, }); final http.Client client; final String apiKey; Map<String, String> get headers => { 'Authorization': 'Bearer $apiKey', 'Content-Type': 'application/json', }; @override Future<FlowyResult<List<String>, StabilityAIRequestError>> generateImage({ required String prompt, int n = 1, }) async { final parameters = { 'text_prompts': [ { 'text': prompt, } ], 'samples': n, }; try { final response = await client.post( StabilityAIRequestType.imageGenerations.uri, headers: headers, body: json.encode(parameters), ); final data = json.decode( utf8.decode(response.bodyBytes), ); if (response.statusCode == 200) { final artifacts = data['artifacts'] as List; final base64Images = artifacts .map( (e) => e['base64'].toString(), ) .toList(); return FlowyResult.success(base64Images); } else { return FlowyResult.failure( StabilityAIRequestError( data['message'].toString(), ), ); } } catch (error) { return FlowyResult.failure( StabilityAIRequestError( error.toString(), ), ); } } }
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/stability_ai/stability_ai_error.dart
class StabilityAIRequestError { StabilityAIRequestError(this.message); final String message; @override String toString() { return 'StabilityAIRequestError{message: $message}'; } }
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/link_preview/link_preview_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/block_menu/block_menu_button.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.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/services.dart'; import 'package:provider/provider.dart'; class LinkPreviewMenu extends StatefulWidget { const LinkPreviewMenu({ super.key, required this.node, required this.state, }); final Node node; final LinkPreviewBlockComponentState state; @override State<LinkPreviewMenu> createState() => _LinkPreviewMenuState(); } class _LinkPreviewMenuState extends State<LinkPreviewMenu> { @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), MenuBlockButton( tooltip: LocaleKeys.document_plugins_urlPreview_convertToLink.tr(), iconData: FlowySvgs.m_aa_link_s, onTap: () => convertUrlPreviewNodeToLink( context.read<EditorState>(), widget.node, ), ), const HSpace(4), MenuBlockButton( tooltip: LocaleKeys.editor_copyLink.tr(), iconData: FlowySvgs.copy_s, onTap: copyImageLink, ), const _Divider(), MenuBlockButton( tooltip: LocaleKeys.button_delete.tr(), iconData: FlowySvgs.delete_s, onTap: deleteLinkPreviewNode, ), const HSpace(4), ], ), ); } void copyImageLink() { final url = widget.node.attributes[ImageBlockKeys.url]; if (url != null) { Clipboard.setData(ClipboardData(text: url)); showSnackBarMessage( context, LocaleKeys.document_plugins_urlPreview_copiedToPasteBoard.tr(), ); } } Future<void> deleteLinkPreviewNode() 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 _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/link_preview/link_preview_cache.dart
import 'dart:convert'; import 'package:appflowy/core/config/kv.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; class LinkPreviewDataCache implements LinkPreviewDataCacheInterface { @override Future<LinkPreviewData?> get(String url) async { final option = await getIt<KeyValueStorage>().getWithFormat<LinkPreviewData?>( url, (value) => LinkPreviewData.fromJson(jsonDecode(value)), ); return option; } @override Future<void> set(String url, LinkPreviewData data) async { await getIt<KeyValueStorage>().set( url, jsonEncode(data.toJson()), ); } }
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/link_preview/shared.dart
import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart'; void convertUrlPreviewNodeToLink(EditorState editorState, Node node) { assert(node.type == LinkPreviewBlockKeys.type); final url = node.attributes[ImageBlockKeys.url]; final transaction = editorState.transaction; transaction ..insertNode(node.path, paragraphNode(text: url)) ..deleteNode(node); transaction.afterSelection = Selection.collapsed( Position( path: node.path, offset: url.length, ), ); 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/link_preview/custom_link_preview.dart
import 'package:flutter/material.dart'; import 'package:appflowy/core/helpers/url_launcher.dart'; import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/mobile/presentation/widgets/widgets.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/mobile_block_action_buttons.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart'; import 'package:appflowy/shared/appflowy_network_image.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:go_router/go_router.dart'; import 'package:provider/provider.dart'; class CustomLinkPreviewWidget extends StatelessWidget { const CustomLinkPreviewWidget({ super.key, required this.node, required this.url, this.title, this.description, this.imageUrl, }); final Node node; final String? title; final String? description; final String? imageUrl; final String url; @override Widget build(BuildContext context) { final documentFontSize = context .read<EditorState>() .editorStyle .textStyleConfiguration .text .fontSize ?? 16.0; final (fontSize, width) = PlatformExtension.isDesktopOrWeb ? (documentFontSize, 180.0) : (documentFontSize - 2, 120.0); final Widget child = Container( clipBehavior: Clip.hardEdge, decoration: BoxDecoration( border: Border.all( color: Theme.of(context).colorScheme.onSurface, ), borderRadius: BorderRadius.circular( 6.0, ), ), child: IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (imageUrl != null) ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(6.0), bottomLeft: Radius.circular(6.0), ), child: FlowyNetworkImage( url: imageUrl!, width: width, ), ), Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (title != null) Padding( padding: const EdgeInsets.only( bottom: 4.0, right: 10.0, ), child: FlowyText.medium( title!, maxLines: 2, overflow: TextOverflow.ellipsis, fontSize: fontSize, ), ), if (description != null) Padding( padding: const EdgeInsets.only(bottom: 4.0), child: FlowyText( description!, maxLines: 2, overflow: TextOverflow.ellipsis, fontSize: fontSize - 4, ), ), FlowyText( url.toString(), overflow: TextOverflow.ellipsis, maxLines: 2, color: Theme.of(context).hintColor, fontSize: fontSize - 4, ), ], ), ), ), ], ), ), ); if (PlatformExtension.isDesktopOrWeb) { return InkWell( onTap: () => afLaunchUrlString(url), child: child, ); } return MobileBlockActionButtons( node: node, editorState: context.read<EditorState>(), extendActionWidgets: _buildExtendActionWidgets(context), child: child, ); } // only used on mobile platform List<Widget> _buildExtendActionWidgets(BuildContext context) { return [ FlowyOptionTile.text( showTopBorder: false, text: LocaleKeys.document_plugins_urlPreview_convertToLink.tr(), leftIcon: const FlowySvg( FlowySvgs.m_aa_link_s, size: Size.square(20), ), onTap: () { context.pop(); convertUrlPreviewNodeToLink( context.read<EditorState>(), node, ); }, ), ]; } }
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/find_and_replace/find_and_replace_menu.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_infra_ui/flowy_infra_ui.dart' hide WidgetBuilder; import 'package:flowy_infra_ui/style_widget/text_input.dart'; import 'package:flutter/material.dart'; class FindAndReplaceMenuWidget extends StatefulWidget { const FindAndReplaceMenuWidget({ super.key, required this.onDismiss, required this.editorState, }); final EditorState editorState; final VoidCallback onDismiss; @override State<FindAndReplaceMenuWidget> createState() => _FindAndReplaceMenuWidgetState(); } class _FindAndReplaceMenuWidgetState extends State<FindAndReplaceMenuWidget> { bool showReplaceMenu = false; late SearchServiceV3 searchService = SearchServiceV3( editorState: widget.editorState, ); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: FindMenu( onDismiss: widget.onDismiss, editorState: widget.editorState, searchService: searchService, onShowReplace: (value) => setState( () => showReplaceMenu = value, ), ), ), showReplaceMenu ? Padding( padding: const EdgeInsets.only( bottom: 8.0, ), child: ReplaceMenu( editorState: widget.editorState, searchService: searchService, ), ) : const SizedBox.shrink(), ], ); } } class FindMenu extends StatefulWidget { const FindMenu({ super.key, required this.onDismiss, required this.editorState, required this.searchService, required this.onShowReplace, }); final EditorState editorState; final VoidCallback onDismiss; final SearchServiceV3 searchService; final void Function(bool value) onShowReplace; @override State<FindMenu> createState() => _FindMenuState(); } class _FindMenuState extends State<FindMenu> { late final FocusNode findTextFieldFocusNode; final findTextEditingController = TextEditingController(); String queriedPattern = ''; bool showReplaceMenu = false; bool caseSensitive = false; @override void initState() { super.initState(); widget.searchService.matchWrappers.addListener(_setState); widget.searchService.currentSelectedIndex.addListener(_setState); findTextEditingController.addListener(_searchPattern); WidgetsBinding.instance.addPostFrameCallback((_) { findTextFieldFocusNode.requestFocus(); }); } @override void dispose() { widget.searchService.matchWrappers.removeListener(_setState); widget.searchService.currentSelectedIndex.removeListener(_setState); widget.searchService.dispose(); findTextEditingController.removeListener(_searchPattern); findTextEditingController.dispose(); findTextFieldFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // the selectedIndex from searchService is 0-based final selectedIndex = widget.searchService.selectedIndex + 1; final matches = widget.searchService.matchWrappers.value; return Row( children: [ const HSpace(4.0), // expand/collapse button _FindAndReplaceIcon( icon: showReplaceMenu ? FlowySvgs.drop_menu_show_s : FlowySvgs.drop_menu_hide_s, tooltipText: '', onPressed: () { widget.onShowReplace(!showReplaceMenu); setState( () => showReplaceMenu = !showReplaceMenu, ); }, ), const HSpace(4.0), // find text input SizedBox( width: 150, height: 30, child: FlowyFormTextInput( onFocusCreated: (focusNode) { findTextFieldFocusNode = focusNode; }, onEditingComplete: () { widget.searchService.navigateToMatch(); // after update selection or navigate to match, the editor // will request focus, here's a workaround to request the // focus back to the findTextField Future.delayed(const Duration(milliseconds: 50), () { FocusScope.of(context).requestFocus( findTextFieldFocusNode, ); }); }, controller: findTextEditingController, hintText: LocaleKeys.findAndReplace_find.tr(), textAlign: TextAlign.left, ), ), // the count of matches Container( constraints: const BoxConstraints(minWidth: 80), padding: const EdgeInsets.symmetric(horizontal: 8.0), alignment: Alignment.centerLeft, child: FlowyText( matches.isEmpty ? LocaleKeys.findAndReplace_noResult.tr() : '$selectedIndex of ${matches.length}', ), ), const HSpace(4.0), // case sensitive button _FindAndReplaceIcon( icon: FlowySvgs.text_s, tooltipText: LocaleKeys.findAndReplace_caseSensitive.tr(), onPressed: () => setState(() { caseSensitive = !caseSensitive; widget.searchService.caseSensitive = caseSensitive; }), isSelected: caseSensitive, ), const HSpace(4.0), // previous match button _FindAndReplaceIcon( onPressed: () => widget.searchService.navigateToMatch(moveUp: true), icon: FlowySvgs.arrow_up_s, tooltipText: LocaleKeys.findAndReplace_previousMatch.tr(), ), const HSpace(4.0), // next match button _FindAndReplaceIcon( onPressed: () => widget.searchService.navigateToMatch(), icon: FlowySvgs.arrow_down_s, tooltipText: LocaleKeys.findAndReplace_nextMatch.tr(), ), const HSpace(4.0), _FindAndReplaceIcon( onPressed: widget.onDismiss, icon: FlowySvgs.close_s, tooltipText: LocaleKeys.findAndReplace_close.tr(), ), const HSpace(4.0), ], ); } void _searchPattern() { if (findTextEditingController.text.isEmpty) { return; } widget.searchService.findAndHighlight(findTextEditingController.text); setState(() => queriedPattern = findTextEditingController.text); } void _setState() { setState(() {}); } } class ReplaceMenu extends StatefulWidget { const ReplaceMenu({ super.key, required this.editorState, required this.searchService, this.localizations, }); final EditorState editorState; /// The localizations of the find and replace menu final FindReplaceLocalizations? localizations; final SearchServiceV3 searchService; @override State<ReplaceMenu> createState() => _ReplaceMenuState(); } class _ReplaceMenuState extends State<ReplaceMenu> { late final FocusNode replaceTextFieldFocusNode; final replaceTextEditingController = TextEditingController(); @override void dispose() { replaceTextEditingController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Row( children: [ // placeholder for aligning the replace menu const HSpace(30), SizedBox( width: 150, height: 30, child: FlowyFormTextInput( onFocusCreated: (focusNode) { replaceTextFieldFocusNode = focusNode; }, onEditingComplete: () { widget.searchService.navigateToMatch(); // after update selection or navigate to match, the editor // will request focus, here's a workaround to request the // focus back to the findTextField Future.delayed(const Duration(milliseconds: 50), () { FocusScope.of(context).requestFocus( replaceTextFieldFocusNode, ); }); }, controller: replaceTextEditingController, hintText: LocaleKeys.findAndReplace_replace.tr(), textAlign: TextAlign.left, ), ), const HSpace(4.0), _FindAndReplaceIcon( onPressed: _replaceSelectedWord, iconBuilder: (_) => const Icon( Icons.find_replace_outlined, size: 16, ), tooltipText: LocaleKeys.findAndReplace_replace.tr(), ), const HSpace(4.0), _FindAndReplaceIcon( iconBuilder: (_) => const Icon( Icons.change_circle_outlined, size: 16, ), tooltipText: LocaleKeys.findAndReplace_replaceAll.tr(), onPressed: () => widget.searchService.replaceAllMatches( replaceTextEditingController.text, ), ), ], ); } void _replaceSelectedWord() { widget.searchService.replaceSelectedWord(replaceTextEditingController.text); } } class _FindAndReplaceIcon extends StatelessWidget { const _FindAndReplaceIcon({ required this.onPressed, required this.tooltipText, this.icon, this.iconBuilder, this.isSelected, }); final VoidCallback onPressed; final FlowySvgData? icon; final WidgetBuilder? iconBuilder; final String tooltipText; final bool? isSelected; @override Widget build(BuildContext context) { return FlowyIconButton( width: 24, height: 24, onPressed: onPressed, icon: iconBuilder?.call(context) ?? (icon != null ? FlowySvg(icon!) : const Placeholder()), tooltipText: tooltipText, isSelected: isSelected, iconColorOnHover: Theme.of(context).colorScheme.onSecondary, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/discard_dialog.dart
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; class DiscardDialog extends StatelessWidget { const DiscardDialog({ super.key, required this.onConfirm, required this.onCancel, }); final VoidCallback onConfirm; final VoidCallback onCancel; @override Widget build(BuildContext context) { return NavigatorOkCancelDialog( message: LocaleKeys.document_plugins_discardResponse.tr(), okTitle: LocaleKeys.button_discard.tr(), cancelTitle: LocaleKeys.button_cancel.tr(), onOkPressed: onConfirm, onCancelPressed: onCancel, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; enum SmartEditAction { summarize, fixSpelling, improveWriting, makeItLonger; String get toInstruction { switch (this) { case SmartEditAction.summarize: return 'Tl;dr'; case SmartEditAction.fixSpelling: return 'Correct this to standard English:'; case SmartEditAction.improveWriting: return 'Rewrite this in your own words:'; case SmartEditAction.makeItLonger: return 'Make this text longer:'; } } String prompt(String input) { switch (this) { case SmartEditAction.summarize: return '$input\n\nTl;dr'; case SmartEditAction.fixSpelling: return 'Correct this to standard English:\n\n$input'; case SmartEditAction.improveWriting: return 'Rewrite this:\n\n$input'; case SmartEditAction.makeItLonger: return 'Make this text longer:\n\n$input'; } } static SmartEditAction from(int index) { switch (index) { case 0: return SmartEditAction.summarize; case 1: return SmartEditAction.fixSpelling; case 2: return SmartEditAction.improveWriting; case 3: return SmartEditAction.makeItLonger; } return SmartEditAction.fixSpelling; } String get name { switch (this) { case SmartEditAction.summarize: return LocaleKeys.document_plugins_smartEditSummarize.tr(); case SmartEditAction.fixSpelling: return LocaleKeys.document_plugins_smartEditFixSpelling.tr(); case SmartEditAction.improveWriting: return LocaleKeys.document_plugins_smartEditImproveWriting.tr(); case SmartEditAction.makeItLonger: return LocaleKeys.document_plugins_smartEditMakeLonger.tr(); } } } class SmartEditActionWrapper extends ActionCell { SmartEditActionWrapper(this.inner); final SmartEditAction inner; Widget? icon(Color iconColor) => null; @override String get name { return inner.name; } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart
import 'package:flutter/material.dart'; class Loading { Loading(this.context); BuildContext? loadingContext; final BuildContext context; Future<void> start() async => showDialog<void>( context: context, barrierDismissible: false, builder: (BuildContext context) { loadingContext = context; return const SimpleDialog( elevation: 0.0, backgroundColor: Colors.transparent, // can change this to your preferred color children: [ Center( child: CircularProgressIndicator(), ), ], ); }, ); Future<void> stop() async { if (loadingContext != null) { Navigator.of(loadingContext!).pop(); loadingContext = null; } } } class BarrierDialog { BarrierDialog(this.context); late BuildContext loadingContext; final BuildContext context; Future<void> show() async => showDialog<void>( context: context, barrierDismissible: false, barrierColor: Colors.transparent, builder: (BuildContext context) { loadingContext = context; return const SizedBox.shrink(); }, ); Future<void> dismiss() async => Navigator.of(loadingContext).pop(); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_toolbar_item.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy/user/application/user_service.dart'; import 'package:appflowy/workspace/presentation/home/toast.dart'; import 'package:appflowy/workspace/presentation/widgets/pop_up_action.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/style_widget/icon_button.dart'; import 'package:flutter/material.dart'; final ToolbarItem smartEditItem = ToolbarItem( id: 'appflowy.editor.smart_edit', group: 0, isActive: onlyShowInSingleSelectionAndTextType, builder: (context, editorState, _, __) => SmartEditActionList( editorState: editorState, ), ); class SmartEditActionList extends StatefulWidget { const SmartEditActionList({ super.key, required this.editorState, }); final EditorState editorState; @override State<SmartEditActionList> createState() => _SmartEditActionListState(); } class _SmartEditActionListState extends State<SmartEditActionList> { bool isOpenAIEnabled = false; @override void initState() { super.initState(); UserBackendService.getCurrentUserProfile().then((value) { setState(() { isOpenAIEnabled = value.fold( (s) => s.openaiKey.isNotEmpty, (_) => false, ); }); }); } @override Widget build(BuildContext context) { return PopoverActionList<SmartEditActionWrapper>( direction: PopoverDirection.bottomWithLeftAligned, actions: SmartEditAction.values .map((action) => SmartEditActionWrapper(action)) .toList(), onClosed: () => keepEditorFocusNotifier.decrease(), buildChild: (controller) { keepEditorFocusNotifier.increase(); return FlowyIconButton( hoverColor: Colors.transparent, tooltipText: isOpenAIEnabled ? LocaleKeys.document_plugins_smartEdit.tr() : LocaleKeys.document_plugins_smartEditDisabled.tr(), preferBelow: false, icon: const Icon( Icons.lightbulb_outline, size: 15, color: Colors.white, ), onPressed: () { if (isOpenAIEnabled) { controller.show(); } else { showSnackBarMessage( context, LocaleKeys.document_plugins_smartEditDisabled.tr(), showCancel: true, ); } }, ); }, onSelected: (action, controller) { controller.close(); _insertSmartEditNode(action); }, ); } Future<void> _insertSmartEditNode( SmartEditActionWrapper actionWrapper, ) async { final selection = widget.editorState.selection?.normalized; if (selection == null) { return; } final input = widget.editorState.getTextInSelection(selection); while (input.last.isEmpty) { input.removeLast(); } final transaction = widget.editorState.transaction; transaction.insertNode( selection.normalized.end.path.next, smartEditNode( action: actionWrapper.inner, content: input.join('\n\n'), ), ); await widget.editorState.apply( transaction, options: const ApplyOptions( recordUndo: false, ), withUpdateSelection: false, ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/auto_completion_node_widget.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/build_context_extension.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/base/text_robot.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/util/learn_more_action.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/discard_dialog.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart'; import 'package:appflowy/user/application/user_service.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/style_widget/button.dart'; import 'package:flowy_infra_ui/style_widget/text.dart'; import 'package:flowy_infra_ui/style_widget/text_field.dart'; import 'package:flowy_infra_ui/widget/buttons/primary_button.dart'; import 'package:flowy_infra_ui/widget/buttons/secondary_button.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:provider/provider.dart'; class AutoCompletionBlockKeys { const AutoCompletionBlockKeys._(); static const String type = 'auto_completion'; static const String prompt = 'prompt'; static const String startSelection = 'start_selection'; static const String generationCount = 'generation_count'; } Node autoCompletionNode({ String prompt = '', required Selection start, }) { return Node( type: AutoCompletionBlockKeys.type, attributes: { AutoCompletionBlockKeys.prompt: prompt, AutoCompletionBlockKeys.startSelection: start.toJson(), AutoCompletionBlockKeys.generationCount: 0, }, ); } SelectionMenuItem autoGeneratorMenuItem = SelectionMenuItem.node( getName: LocaleKeys.document_plugins_autoGeneratorMenuItemName.tr, iconData: Icons.generating_tokens, keywords: ['ai', 'openai' 'writer', 'autogenerator'], nodeBuilder: (editorState, _) { final node = autoCompletionNode(start: editorState.selection!); return node; }, replace: (_, node) => false, ); class AutoCompletionBlockComponentBuilder extends BlockComponentBuilder { AutoCompletionBlockComponentBuilder(); @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return AutoCompletionBlockComponent( key: node.key, node: node, showActions: showActions(node), actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), ); } @override bool validate(Node node) { return node.children.isEmpty && node.attributes[AutoCompletionBlockKeys.prompt] is String && node.attributes[AutoCompletionBlockKeys.startSelection] is Map; } } class AutoCompletionBlockComponent extends BlockComponentStatefulWidget { const AutoCompletionBlockComponent({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), }); @override State<AutoCompletionBlockComponent> createState() => _AutoCompletionBlockComponentState(); } class _AutoCompletionBlockComponentState extends State<AutoCompletionBlockComponent> { final controller = TextEditingController(); final textFieldFocusNode = FocusNode(); late final editorState = context.read<EditorState>(); late final SelectionGestureInterceptor interceptor; String get prompt => widget.node.attributes[AutoCompletionBlockKeys.prompt]; int get generationCount => widget.node.attributes[AutoCompletionBlockKeys.generationCount] ?? 0; Selection? get startSelection { final selection = widget.node.attributes[AutoCompletionBlockKeys.startSelection]; if (selection != null) { return Selection.fromJson(selection); } return null; } @override void initState() { super.initState(); _subscribeSelectionGesture(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { editorState.selection = null; textFieldFocusNode.requestFocus(); }); } @override void dispose() { _onExit(); _unsubscribeSelectionGesture(); controller.dispose(); textFieldFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Card( elevation: 5, color: Theme.of(context).colorScheme.surface, child: Container( margin: const EdgeInsets.all(10), child: Column( mainAxisSize: MainAxisSize.min, children: [ const AutoCompletionHeader(), const Space(0, 10), if (prompt.isEmpty && generationCount < 1) ...[ _buildInputWidget(context), const Space(0, 10), AutoCompletionInputFooter( onGenerate: _onGenerate, onExit: _onExit, ), ] else ...[ AutoCompletionFooter( onKeep: _onExit, onRewrite: _onRewrite, onDiscard: _onDiscard, ), ], ], ), ), ); } Widget _buildInputWidget(BuildContext context) { return FlowyTextField( hintText: LocaleKeys.document_plugins_autoGeneratorHintText.tr(), controller: controller, maxLines: 5, focusNode: textFieldFocusNode, autoFocus: false, hintTextConstraints: const BoxConstraints(), ); } Future<void> _onExit() async { final transaction = editorState.transaction..deleteNode(widget.node); await editorState.apply( transaction, options: const ApplyOptions( recordUndo: false, ), ); } Future<void> _onGenerate() async { final loading = Loading(context); await loading.start(); await _updateEditingText(); final userProfile = await UserBackendService.getCurrentUserProfile() .then((value) => value.toNullable()); if (userProfile == null) { await loading.stop(); if (mounted) { showSnackBarMessage( context, LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(), showCancel: true, ); } return; } final textRobot = TextRobot(editorState: editorState); BarrierDialog? barrierDialog; final openAIRepository = HttpOpenAIRepository( client: http.Client(), apiKey: userProfile.openaiKey, ); await openAIRepository.getStreamedCompletions( prompt: controller.text, onStart: () async { await loading.stop(); if (mounted) { barrierDialog = BarrierDialog(context); await barrierDialog?.show(); await _makeSurePreviousNodeIsEmptyParagraphNode(); } }, onProcess: (response) async { if (response.choices.isNotEmpty) { final text = response.choices.first.text; await textRobot.autoInsertText( text, delay: Duration.zero, ); } }, onEnd: () async { await barrierDialog?.dismiss(); }, onError: (error) async { await loading.stop(); if (mounted) { showSnackBarMessage( context, error.message, showCancel: true, ); } }, ); await _updateGenerationCount(); } Future<void> _onDiscard() async { final selection = startSelection; if (selection != null) { final start = selection.start.path; final end = widget.node.previous?.path; if (end != null) { final transaction = editorState.transaction; transaction.deleteNodesAtPath( start, end.last - start.last + 1, ); await editorState.apply(transaction); await _makeSurePreviousNodeIsEmptyParagraphNode(); } } return _onExit(); } Future<void> _onRewrite() async { final previousOutput = _getPreviousOutput(); if (previousOutput == null) { return; } final loading = Loading(context); await loading.start(); // clear previous response final selection = startSelection; if (selection != null) { final start = selection.start.path; final end = widget.node.previous?.path; if (end != null) { final transaction = editorState.transaction; transaction.deleteNodesAtPath( start, end.last - start.last + 1, ); await editorState.apply(transaction); } } // generate new response final userProfile = await UserBackendService.getCurrentUserProfile() .then((value) => value.toNullable()); if (userProfile == null) { await loading.stop(); if (mounted) { showSnackBarMessage( context, LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(), showCancel: true, ); } return; } final textRobot = TextRobot(editorState: editorState); final openAIRepository = HttpOpenAIRepository( client: http.Client(), apiKey: userProfile.openaiKey, ); await openAIRepository.getStreamedCompletions( prompt: _rewritePrompt(previousOutput), onStart: () async { await loading.stop(); await _makeSurePreviousNodeIsEmptyParagraphNode(); }, onProcess: (response) async { if (response.choices.isNotEmpty) { final text = response.choices.first.text; await textRobot.autoInsertText( text, delay: Duration.zero, ); } }, onEnd: () async {}, onError: (error) async { await loading.stop(); if (mounted) { showSnackBarMessage( context, error.message, showCancel: true, ); } }, ); await _updateGenerationCount(); } String? _getPreviousOutput() { final startSelection = this.startSelection; if (startSelection != null) { final end = widget.node.previous?.path; if (end != null) { final result = editorState .getNodesInSelection( startSelection.copyWith(end: Position(path: end)), ) .fold( '', (previousValue, element) { final delta = element.delta; if (delta != null) { return "$previousValue\n${delta.toPlainText()}"; } else { return previousValue; } }, ); return result.trim(); } } return null; } Future<void> _updateEditingText() async { final transaction = editorState.transaction; transaction.updateNode( widget.node, { AutoCompletionBlockKeys.prompt: controller.text, }, ); await editorState.apply(transaction); } Future<void> _updateGenerationCount() async { final transaction = editorState.transaction; transaction.updateNode( widget.node, { AutoCompletionBlockKeys.generationCount: generationCount + 1, }, ); await editorState.apply(transaction); } String _rewritePrompt(String previousOutput) { return 'I am not satisfied with your previous response ($previousOutput) to the query ($prompt). Please provide an alternative response.'; } Future<void> _makeSurePreviousNodeIsEmptyParagraphNode() async { // make sure the previous node is a empty paragraph node without any styles. final transaction = editorState.transaction; final previous = widget.node.previous; final Selection selection; if (previous == null || previous.type != ParagraphBlockKeys.type || (previous.delta?.toPlainText().isNotEmpty ?? false)) { selection = Selection.single( path: widget.node.path, startOffset: 0, ); transaction.insertNode( widget.node.path, paragraphNode(), ); } else { selection = Selection.single( path: previous.path, startOffset: 0, ); } transaction.updateNode(widget.node, { AutoCompletionBlockKeys.startSelection: selection.toJson(), }); transaction.afterSelection = selection; await editorState.apply(transaction); } void _subscribeSelectionGesture() { interceptor = SelectionGestureInterceptor( key: AutoCompletionBlockKeys.type, canTap: (details) { if (!context.isOffsetInside(details.globalPosition)) { if (prompt.isNotEmpty || controller.text.isNotEmpty) { // show dialog showDialog( context: context, builder: (context) { return DiscardDialog( onConfirm: () => _onDiscard(), onCancel: () {}, ); }, ); } else if (controller.text.isEmpty) { _onExit(); } } editorState.service.keyboardService?.disable(); return false; }, ); editorState.service.selectionService.registerGestureInterceptor( interceptor, ); } void _unsubscribeSelectionGesture() { editorState.service.selectionService.unregisterGestureInterceptor( AutoCompletionBlockKeys.type, ); } } class AutoCompletionHeader extends StatelessWidget { const AutoCompletionHeader({ super.key, }); @override Widget build(BuildContext context) { return Row( children: [ FlowyText.medium( LocaleKeys.document_plugins_autoGeneratorTitleName.tr(), fontSize: 14, ), const Spacer(), FlowyButton( useIntrinsicWidth: true, text: FlowyText.regular( LocaleKeys.document_plugins_autoGeneratorLearnMore.tr(), ), onTap: () async { await openLearnMorePage(); }, ), ], ); } } class AutoCompletionInputFooter extends StatelessWidget { const AutoCompletionInputFooter({ super.key, required this.onGenerate, required this.onExit, }); final VoidCallback onGenerate; final VoidCallback onExit; @override Widget build(BuildContext context) { return Row( children: [ PrimaryTextButton( LocaleKeys.button_generate.tr(), onPressed: onGenerate, ), const Space(10, 0), SecondaryTextButton( LocaleKeys.button_cancel.tr(), onPressed: onExit, ), Expanded( child: Container( alignment: Alignment.centerRight, child: FlowyText.regular( LocaleKeys.document_plugins_warning.tr(), color: Theme.of(context).hintColor, overflow: TextOverflow.ellipsis, ), ), ), ], ); } } class AutoCompletionFooter extends StatelessWidget { const AutoCompletionFooter({ super.key, required this.onKeep, required this.onRewrite, required this.onDiscard, }); final VoidCallback onKeep; final VoidCallback onRewrite; final VoidCallback onDiscard; @override Widget build(BuildContext context) { return Row( children: [ PrimaryTextButton( LocaleKeys.button_keep.tr(), onPressed: onKeep, ), const Space(10, 0), SecondaryTextButton( LocaleKeys.document_plugins_autoGeneratorRewrite.tr(), onPressed: onRewrite, ), const Space(10, 0), SecondaryTextButton( LocaleKeys.button_discard.tr(), onPressed: onDiscard, ), ], ); } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart
import 'dart:async'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/util/learn_more_action.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/discard_dialog.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart'; import 'package:appflowy/startup/startup.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:flowy_infra_ui/flowy_infra_ui.dart'; import 'package:flowy_infra_ui/style_widget/decoration.dart'; import 'package:flutter/material.dart'; import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:http/http.dart' as http; import 'package:provider/provider.dart'; class SmartEditBlockKeys { const SmartEditBlockKeys._(); static const type = 'smart_edit'; /// The instruction of the smart edit. /// /// It is a [SmartEditAction] value. static const action = 'action'; /// The input of the smart edit. static const content = 'content'; } Node smartEditNode({ required SmartEditAction action, required String content, }) { return Node( type: SmartEditBlockKeys.type, attributes: { SmartEditBlockKeys.action: action.index, SmartEditBlockKeys.content: content, }, ); } class SmartEditBlockComponentBuilder extends BlockComponentBuilder { SmartEditBlockComponentBuilder(); @override BlockComponentWidget build(BlockComponentContext blockComponentContext) { final node = blockComponentContext.node; return SmartEditBlockComponentWidget( key: node.key, node: node, showActions: showActions(node), actionBuilder: (context, state) => actionBuilder( blockComponentContext, state, ), ); } @override bool validate(Node node) => node.attributes[SmartEditBlockKeys.action] is int && node.attributes[SmartEditBlockKeys.content] is String; } class SmartEditBlockComponentWidget extends BlockComponentStatefulWidget { const SmartEditBlockComponentWidget({ super.key, required super.node, super.showActions, super.actionBuilder, super.configuration = const BlockComponentConfiguration(), }); @override State<SmartEditBlockComponentWidget> createState() => _SmartEditBlockComponentWidgetState(); } class _SmartEditBlockComponentWidgetState extends State<SmartEditBlockComponentWidget> { final popoverController = PopoverController(); final key = GlobalKey(debugLabel: 'smart_edit_input'); late final editorState = context.read<EditorState>(); @override void initState() { super.initState(); // todo: don't use a popover to show the content of the smart edit. WidgetsBinding.instance.addPostFrameCallback((timeStamp) { popoverController.show(); }); } @override void reassemble() { super.reassemble(); final transaction = editorState.transaction..deleteNode(widget.node); editorState.apply(transaction); } @override Widget build(BuildContext context) { final width = _getEditorWidth(); return AppFlowyPopover( controller: popoverController, direction: PopoverDirection.bottomWithLeftAligned, triggerActions: PopoverTriggerFlags.none, margin: EdgeInsets.zero, constraints: BoxConstraints(maxWidth: width), decoration: FlowyDecoration.decoration( Colors.transparent, Colors.transparent, ), child: const SizedBox( width: double.infinity, ), canClose: () async { final completer = Completer<bool>(); final state = key.currentState as _SmartEditInputWidgetState; if (state.result.isEmpty) { completer.complete(true); } else { await showDialog( context: context, builder: (context) { return DiscardDialog( onConfirm: () => completer.complete(true), onCancel: () => completer.complete(false), ); }, ); } return completer.future; }, onClose: () { final transaction = editorState.transaction..deleteNode(widget.node); editorState.apply(transaction); }, popupBuilder: (BuildContext popoverContext) { return SmartEditInputWidget( key: key, node: widget.node, editorState: editorState, ); }, ); } double _getEditorWidth() { var width = double.infinity; final editorSize = editorState.renderBox?.size; final padding = editorState.editorStyle.padding; if (editorSize != null) { width = editorSize.width - padding.left - padding.right; } return width; } } class SmartEditInputWidget extends StatefulWidget { const SmartEditInputWidget({ required super.key, required this.node, required this.editorState, }); final Node node; final EditorState editorState; @override State<SmartEditInputWidget> createState() => _SmartEditInputWidgetState(); } class _SmartEditInputWidgetState extends State<SmartEditInputWidget> { final focusNode = FocusNode(); final client = http.Client(); SmartEditAction get action => SmartEditAction.from( widget.node.attributes[SmartEditBlockKeys.action], ); String get content => widget.node.attributes[SmartEditBlockKeys.content]; EditorState get editorState => widget.editorState; bool loading = true; String result = ''; @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { editorState.service.keyboardService?.disable(); // editorState.selection = null; }); focusNode.requestFocus(); _requestCompletions(); } @override void dispose() { client.close(); focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Card( elevation: 5, color: Theme.of(context).colorScheme.surface, child: Container( margin: const EdgeInsets.all(10), child: _buildSmartEditPanel(context), ), ); } Widget _buildSmartEditPanel(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildHeaderWidget(context), const Space(0, 10), _buildResultWidget(context), const Space(0, 10), _buildInputFooterWidget(context), ], ); } Widget _buildHeaderWidget(BuildContext context) { return Row( children: [ FlowyText.medium( '${LocaleKeys.document_plugins_openAI.tr()}: ${action.name}', fontSize: 14, ), const Spacer(), FlowyButton( useIntrinsicWidth: true, text: FlowyText.regular( LocaleKeys.document_plugins_autoGeneratorLearnMore.tr(), ), onTap: () async { await openLearnMorePage(); }, ), ], ); } Widget _buildResultWidget(BuildContext context) { final loadingWidget = Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: SizedBox.fromSize( size: const Size.square(14), child: const CircularProgressIndicator(), ), ); if (result.isEmpty || loading) { return loadingWidget; } return Flexible( child: Text( result, ), ); } Widget _buildInputFooterWidget(BuildContext context) { return Row( children: [ FlowyRichTextButton( TextSpan( children: [ TextSpan( text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(), style: Theme.of(context).textTheme.bodyMedium, ), ], ), onPressed: () => _requestCompletions(rewrite: true), ), const Space(10, 0), FlowyRichTextButton( TextSpan( children: [ TextSpan( text: LocaleKeys.button_replace.tr(), style: Theme.of(context).textTheme.bodyMedium, ), ], ), onPressed: () async { await _onReplace(); await _onExit(); }, ), const Space(10, 0), FlowyRichTextButton( TextSpan( children: [ TextSpan( text: LocaleKeys.button_insertBelow.tr(), style: Theme.of(context).textTheme.bodyMedium, ), ], ), onPressed: () async { await _onInsertBelow(); await _onExit(); }, ), const Space(10, 0), FlowyRichTextButton( TextSpan( children: [ TextSpan( text: LocaleKeys.button_cancel.tr(), style: Theme.of(context).textTheme.bodyMedium, ), ], ), onPressed: () async => _onExit(), ), const Spacer(), Expanded( child: Container( alignment: Alignment.centerRight, child: FlowyText.regular( LocaleKeys.document_plugins_warning.tr(), color: Theme.of(context).hintColor, overflow: TextOverflow.ellipsis, ), ), ), ], ); } Future<void> _onReplace() async { final selection = editorState.selection?.normalized; if (selection == null) { return; } final nodes = editorState.getNodesInSelection(selection); if (nodes.isEmpty || !nodes.every((element) => element.delta != null)) { return; } final replaceTexts = result.split('\n') ..removeWhere((element) => element.isEmpty); final transaction = editorState.transaction; transaction.replaceTexts( nodes, selection, replaceTexts, ); await editorState.apply(transaction); int endOffset = replaceTexts.last.length; if (replaceTexts.length == 1) { endOffset += selection.start.offset; } editorState.selection = Selection( start: selection.start, end: Position( path: [selection.start.path.first + replaceTexts.length - 1], offset: endOffset, ), ); } Future<void> _onInsertBelow() async { final selection = editorState.selection?.normalized; if (selection == null) { return; } final insertedText = result.split('\n') ..removeWhere((element) => element.isEmpty); final transaction = editorState.transaction; transaction.insertNodes( selection.end.path.next, insertedText.map( (e) => paragraphNode( text: e, ), ), ); transaction.afterSelection = Selection( start: Position(path: selection.end.path.next), end: Position( path: [selection.end.path.next.first + insertedText.length], ), ); await editorState.apply(transaction); } Future<void> _onExit() async { final transaction = editorState.transaction..deleteNode(widget.node); return editorState.apply( transaction, options: const ApplyOptions( recordUndo: false, ), ); } Future<void> _requestCompletions({bool rewrite = false}) async { if (rewrite) { setState(() { loading = true; result = ""; }); } final openAIRepository = await getIt.getAsync<OpenAIRepository>(); var lines = content.split('\n\n'); if (action == SmartEditAction.summarize) { lines = [lines.join('\n')]; } for (var i = 0; i < lines.length; i++) { final element = lines[i]; await openAIRepository.getStreamedCompletions( useAction: true, prompt: action.prompt(element), onStart: () async { setState(() { loading = false; }); }, onProcess: (response) async { setState(() { if (response.choices.first.text != '\n') { result += response.choices.first.text; } }); }, onEnd: () async { setState(() { if (i != lines.length - 1) { result += '\n'; } }); }, onError: (error) async { showSnackBarMessage( context, error.message, showCancel: true, ); await _onExit(); }, ); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/service/text_completion.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'text_completion.freezed.dart'; part 'text_completion.g.dart'; @freezed class TextCompletionChoice with _$TextCompletionChoice { factory TextCompletionChoice({ required String text, required int index, // ignore: invalid_annotation_target @JsonKey(name: 'finish_reason') String? finishReason, }) = _TextCompletionChoice; factory TextCompletionChoice.fromJson(Map<String, Object?> json) => _$TextCompletionChoiceFromJson(json); } @freezed class TextCompletionResponse with _$TextCompletionResponse { const factory TextCompletionResponse({ required List<TextCompletionChoice> choices, }) = _TextCompletionResponse; factory TextCompletionResponse.fromJson(Map<String, Object?> json) => _$TextCompletionResponseFromJson(json); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/service/error.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'error.freezed.dart'; part 'error.g.dart'; @freezed class OpenAIError with _$OpenAIError { const factory OpenAIError({ String? code, required String message, }) = _OpenAIError; factory OpenAIError.fromJson(Map<String, Object?> json) => _$OpenAIErrorFromJson(json); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/service/openai_client.dart
import 'dart:async'; import 'dart:convert'; import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/text_edit.dart'; import 'package:appflowy_result/appflowy_result.dart'; import 'package:http/http.dart' as http; import 'error.dart'; import 'text_completion.dart'; enum OpenAIRequestType { textCompletion, textEdit, imageGenerations; Uri get uri { switch (this) { case OpenAIRequestType.textCompletion: return Uri.parse('https://api.openai.com/v1/completions'); case OpenAIRequestType.textEdit: return Uri.parse('https://api.openai.com/v1/v1/chat/completions'); case OpenAIRequestType.imageGenerations: return Uri.parse('https://api.openai.com/v1/images/generations'); } } } abstract class OpenAIRepository { /// Get completions from GPT-3 /// /// [prompt] is the prompt text /// [suffix] is the suffix text /// [maxTokens] is the maximum number of tokens to generate /// [temperature] is the temperature of the model /// Future<FlowyResult<TextCompletionResponse, OpenAIError>> getCompletions({ required String prompt, String? suffix, int maxTokens = 2048, double temperature = .3, }); 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, }); /// Get edits from GPT-3 /// /// [input] is the input text /// [instruction] is the instruction text /// [temperature] is the temperature of the model /// Future<FlowyResult<TextEditResponse, OpenAIError>> getEdits({ required String input, required String instruction, double temperature = 0.3, }); /// Generate image from GPT-3 /// /// [prompt] is the prompt text /// [n] is the number of images to generate /// /// the result is a list of urls Future<FlowyResult<List<String>, OpenAIError>> generateImage({ required String prompt, int n = 1, }); } class HttpOpenAIRepository implements OpenAIRepository { const HttpOpenAIRepository({ required this.client, required this.apiKey, }); final http.Client client; final String apiKey; Map<String, String> get headers => { 'Authorization': 'Bearer $apiKey', 'Content-Type': 'application/json', }; @override Future<FlowyResult<TextCompletionResponse, OpenAIError>> getCompletions({ required String prompt, String? suffix, int maxTokens = 2048, double temperature = 0.3, }) async { final parameters = { 'model': 'gpt-3.5-turbo-instruct', 'prompt': prompt, 'suffix': suffix, 'max_tokens': maxTokens, 'temperature': temperature, 'stream': false, }; final response = await client.post( OpenAIRequestType.textCompletion.uri, headers: headers, body: json.encode(parameters), ); if (response.statusCode == 200) { return FlowyResult.success( TextCompletionResponse.fromJson( json.decode( utf8.decode(response.bodyBytes), ), ), ); } else { return FlowyResult.failure( OpenAIError.fromJson(json.decode(response.body)['error']), ); } } @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 parameters = { 'model': 'gpt-3.5-turbo-instruct', 'prompt': prompt, 'suffix': suffix, 'max_tokens': maxTokens, 'temperature': temperature, 'stream': true, }; final request = http.Request('POST', OpenAIRequestType.textCompletion.uri); request.headers.addAll(headers); request.body = jsonEncode(parameters); final response = await client.send(request); // NEED TO REFACTOR. // WHY OPENAI USE TWO LINES TO INDICATE THE START OF THE STREAMING RESPONSE? // AND WHY OPENAI USE [DONE] TO INDICATE THE END OF THE STREAMING RESPONSE? int syntax = 0; var previousSyntax = ''; if (response.statusCode == 200) { await for (final chunk in response.stream .transform(const Utf8Decoder()) .transform(const LineSplitter())) { syntax += 1; if (!useAction) { if (syntax == 3) { await onStart(); continue; } else if (syntax < 3) { continue; } } else { if (syntax == 2) { await onStart(); continue; } else if (syntax < 2) { continue; } } final data = chunk.trim().split('data: '); if (data.length > 1) { if (data[1] != '[DONE]') { final response = TextCompletionResponse.fromJson( json.decode(data[1]), ); 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(); } } } } else { final body = await response.stream.bytesToString(); onError( OpenAIError.fromJson(json.decode(body)['error']), ); } return; } @override Future<FlowyResult<TextEditResponse, OpenAIError>> getEdits({ required String input, required String instruction, double temperature = 0.3, int n = 1, }) async { final parameters = { 'model': 'gpt-4', 'input': input, 'instruction': instruction, 'temperature': temperature, 'n': n, }; final response = await client.post( OpenAIRequestType.textEdit.uri, headers: headers, body: json.encode(parameters), ); if (response.statusCode == 200) { return FlowyResult.success( TextEditResponse.fromJson( json.decode( utf8.decode(response.bodyBytes), ), ), ); } else { return FlowyResult.failure( OpenAIError.fromJson(json.decode(response.body)['error']), ); } } @override Future<FlowyResult<List<String>, OpenAIError>> generateImage({ required String prompt, int n = 1, }) async { final parameters = { 'prompt': prompt, 'n': n, 'size': '512x512', }; try { final response = await client.post( OpenAIRequestType.imageGenerations.uri, headers: headers, body: json.encode(parameters), ); if (response.statusCode == 200) { final data = json.decode( utf8.decode(response.bodyBytes), )['data'] as List; final urls = data .map((e) => e.values) .expand((e) => e) .map((e) => e.toString()) .toList(); return FlowyResult.success(urls); } else { return FlowyResult.failure( OpenAIError.fromJson(json.decode(response.body)['error']), ); } } catch (error) { return FlowyResult.failure(OpenAIError(message: error.toString())); } } }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/service/text_edit.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'text_edit.freezed.dart'; part 'text_edit.g.dart'; @freezed class TextEditChoice with _$TextEditChoice { factory TextEditChoice({ required String text, required int index, }) = _TextEditChoice; factory TextEditChoice.fromJson(Map<String, Object?> json) => _$TextEditChoiceFromJson(json); } @freezed class TextEditResponse with _$TextEditResponse { const factory TextEditResponse({ required List<TextEditChoice> choices, }) = _TextEditResponse; factory TextEditResponse.fromJson(Map<String, Object?> json) => _$TextEditResponseFromJson(json); }
0
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/util/learn_more_action.dart
import 'package:appflowy/core/helpers/url_launcher.dart'; const String learnMoreUrl = 'https://docs.appflowy.io/docs/appflowy/product/appflowy-x-openai'; Future<void> openLearnMorePage() async { await afLaunchUrlString(learnMoreUrl); }
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/i18n/editor_i18n.dart
import 'package:appflowy/generated/locale_keys.g.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; class EditorI18n extends AppFlowyEditorL10n { // static AppFlowyEditorLocalizations current = EditorI18n(); EditorI18n(); @override String get bold { return LocaleKeys.editor_bold.tr(); } /// `Bulleted List` @override String get bulletedList { return LocaleKeys.editor_bulletedList.tr(); } /// `Checkbox` @override String get checkbox { return LocaleKeys.editor_checkbox.tr(); } /// `Embed Code` @override String get embedCode { return LocaleKeys.editor_embedCode.tr(); } /// `H1` @override String get heading1 { return LocaleKeys.editor_heading1.tr(); } /// `H2` @override String get heading2 { return LocaleKeys.editor_heading2.tr(); } /// `H3` @override String get heading3 { return LocaleKeys.editor_heading3.tr(); } /// `Highlight` @override String get highlight { return LocaleKeys.editor_highlight.tr(); } /// `Color` @override String get color { return LocaleKeys.editor_color.tr(); } /// `Image` @override String get image { return LocaleKeys.editor_image.tr(); } /// `Italic` @override String get italic { return LocaleKeys.editor_italic.tr(); } /// `Link` @override String get link { return LocaleKeys.editor_link.tr(); } /// `Numbered List` @override String get numberedList { return LocaleKeys.editor_numberedList.tr(); } /// `Quote` @override String get quote { return LocaleKeys.editor_quote.tr(); } /// `Strikethrough` @override String get strikethrough { return LocaleKeys.editor_strikethrough.tr(); } /// `Text` @override String get text { return LocaleKeys.editor_text.tr(); } /// `Underline` @override String get underline { return LocaleKeys.editor_underline.tr(); } /// `Default` @override String get fontColorDefault { return LocaleKeys.editor_fontColorDefault.tr(); } /// `Gray` @override String get fontColorGray { return LocaleKeys.editor_fontColorGray.tr(); } /// `Brown` @override String get fontColorBrown { return LocaleKeys.editor_fontColorBrown.tr(); } /// `Orange` @override String get fontColorOrange { return LocaleKeys.editor_fontColorOrange.tr(); } /// `Yellow` @override String get fontColorYellow { return LocaleKeys.editor_fontColorYellow.tr(); } /// `Green` @override String get fontColorGreen { return LocaleKeys.editor_fontColorGreen.tr(); } /// `Blue` @override String get fontColorBlue { return LocaleKeys.editor_fontColorBlue.tr(); } /// `Purple` @override String get fontColorPurple { return LocaleKeys.editor_fontColorPurple.tr(); } /// `Pink` @override String get fontColorPink { return LocaleKeys.editor_fontColorPink.tr(); } /// `Red` @override String get fontColorRed { return LocaleKeys.editor_fontColorRed.tr(); } /// `Default background` @override String get backgroundColorDefault { return LocaleKeys.editor_backgroundColorDefault.tr(); } /// `Gray background` @override String get backgroundColorGray { return LocaleKeys.editor_backgroundColorGray.tr(); } /// `Brown background` @override String get backgroundColorBrown { return LocaleKeys.editor_backgroundColorBrown.tr(); } /// `Orange background` @override String get backgroundColorOrange { return LocaleKeys.editor_backgroundColorOrange.tr(); } /// `Yellow background` @override String get backgroundColorYellow { return LocaleKeys.editor_backgroundColorYellow.tr(); } /// `Green background` @override String get backgroundColorGreen { return LocaleKeys.editor_backgroundColorGreen.tr(); } /// `Blue background` @override String get backgroundColorBlue { return LocaleKeys.editor_backgroundColorBlue.tr(); } /// `Purple background` @override String get backgroundColorPurple { return LocaleKeys.editor_backgroundColorPurple.tr(); } /// `Pink background` @override String get backgroundColorPink { return LocaleKeys.editor_backgroundColorPink.tr(); } /// `Red background` @override String get backgroundColorRed { return LocaleKeys.editor_backgroundColorRed.tr(); } /// `Done` @override String get done { return LocaleKeys.editor_done.tr(); } /// `Cancel` @override String get cancel { return LocaleKeys.editor_cancel.tr(); } /// `Tint 1` @override String get tint1 { return LocaleKeys.editor_tint1.tr(); } /// `Tint 2` @override String get tint2 { return LocaleKeys.editor_tint2.tr(); } /// `Tint 3` @override String get tint3 { return LocaleKeys.editor_tint3.tr(); } /// `Tint 4` @override String get tint4 { return LocaleKeys.editor_tint4.tr(); } /// `Tint 5` @override String get tint5 { return LocaleKeys.editor_tint5.tr(); } /// `Tint 6` @override String get tint6 { return LocaleKeys.editor_tint6.tr(); } /// `Tint 7` @override String get tint7 { return LocaleKeys.editor_tint7.tr(); } /// `Tint 8` @override String get tint8 { return LocaleKeys.editor_tint8.tr(); } /// `Tint 9` @override String get tint9 { return LocaleKeys.editor_tint9.tr(); } /// `Purple` @override String get lightLightTint1 { return LocaleKeys.editor_lightLightTint1.tr(); } /// `Pink` @override String get lightLightTint2 { return LocaleKeys.editor_lightLightTint2.tr(); } /// `Light Pink` @override String get lightLightTint3 { return LocaleKeys.editor_lightLightTint3.tr(); } /// `Orange` @override String get lightLightTint4 { return LocaleKeys.editor_lightLightTint4.tr(); } /// `Yellow` @override String get lightLightTint5 { return LocaleKeys.editor_lightLightTint5.tr(); } /// `Lime` @override String get lightLightTint6 { return LocaleKeys.editor_lightLightTint6.tr(); } /// `Green` @override String get lightLightTint7 { return LocaleKeys.editor_lightLightTint7.tr(); } /// `Aqua` @override String get lightLightTint8 { return LocaleKeys.editor_lightLightTint8.tr(); } /// `Blue` @override String get lightLightTint9 { return LocaleKeys.editor_lightLightTint9.tr(); } /// `URL` @override String get urlHint { return LocaleKeys.editor_urlHint.tr(); } /// `Heading 1` @override String get mobileHeading1 { return LocaleKeys.editor_mobileHeading1.tr(); } /// `Heading 2` @override String get mobileHeading2 { return LocaleKeys.editor_mobileHeading2.tr(); } /// `Heading 3` @override String get mobileHeading3 { return LocaleKeys.editor_mobileHeading3.tr(); } /// `Text Color` @override String get textColor { return LocaleKeys.editor_textColor.tr(); } /// `Background Color` @override String get backgroundColor { return LocaleKeys.editor_backgroundColor.tr(); } /// `Add your link` @override String get addYourLink { return LocaleKeys.editor_addYourLink.tr(); } /// `Open link` @override String get openLink { return LocaleKeys.editor_openLink.tr(); } /// `Copy link` @override String get copyLink { return LocaleKeys.editor_copyLink.tr(); } /// `Remove link` @override String get removeLink { return LocaleKeys.editor_removeLink.tr(); } /// `Edit link` @override String get editLink { return LocaleKeys.editor_editLink.tr(); } /// `Text` @override String get linkText { return LocaleKeys.editor_linkText.tr(); } /// `Please enter text` @override String get linkTextHint { return LocaleKeys.editor_linkTextHint.tr(); } /// `Please enter URL` @override String get linkAddressHint { return LocaleKeys.editor_linkAddressHint.tr(); } /// `Highlight color` @override String get highlightColor { return LocaleKeys.editor_highlightColor.tr(); } /// `Clear highlight color` @override String get clearHighlightColor { return LocaleKeys.editor_clearHighlightColor.tr(); } /// `Custom color` @override String get customColor { return LocaleKeys.editor_customColor.tr(); } /// `Hex value` @override String get hexValue { return LocaleKeys.editor_hexValue.tr(); } /// `Opacity` @override String get opacity { return LocaleKeys.editor_opacity.tr(); } /// `Reset to default color` @override String get resetToDefaultColor { return LocaleKeys.editor_resetToDefaultColor.tr(); } /// `LTR` @override String get ltr { return LocaleKeys.editor_ltr.tr(); } /// `RTL` @override String get rtl { return LocaleKeys.editor_rtl.tr(); } /// `Auto` @override String get auto { return LocaleKeys.editor_auto.tr(); } /// `Cut` @override String get cut { return LocaleKeys.editor_cut.tr(); } /// `Copy` @override String get copy { return LocaleKeys.editor_copy.tr(); } /// `Paste` @override String get paste { return LocaleKeys.editor_paste.tr(); } /// `Find` @override String get find { return LocaleKeys.editor_find.tr(); } /// `Previous match` @override String get previousMatch { return LocaleKeys.editor_previousMatch.tr(); } /// `Next match` @override String get nextMatch { return LocaleKeys.editor_nextMatch.tr(); } /// `Close` @override String get closeFind { return LocaleKeys.editor_closeFind.tr(); } /// `Replace` @override String get replace { return LocaleKeys.editor_replace.tr(); } /// `Replace all` @override String get replaceAll { return LocaleKeys.editor_replaceAll.tr(); } /// `Regex` @override String get regex { return LocaleKeys.editor_regex.tr(); } /// `Case sensitive` @override String get caseSensitive { return LocaleKeys.editor_caseSensitive.tr(); } /// `Upload Image` @override String get uploadImage { return LocaleKeys.editor_uploadImage.tr(); } /// `URL Image` @override String get urlImage { return LocaleKeys.editor_urlImage.tr(); } /// `Incorrect Link` @override String get incorrectLink { return LocaleKeys.editor_incorrectLink.tr(); } /// `Upload` @override String get upload { return LocaleKeys.editor_upload.tr(); } /// `Choose an image` @override String get chooseImage { return LocaleKeys.editor_chooseImage.tr(); } /// `Loading` @override String get loading { return LocaleKeys.editor_loading.tr(); } /// `Could not load the image` @override String get imageLoadFailed { return LocaleKeys.editor_imageLoadFailed.tr(); } /// `Divider` @override String get divider { return LocaleKeys.editor_divider.tr(); } /// `Table` @override String get table { return LocaleKeys.editor_table.tr(); } /// `Add before` @override String get colAddBefore { return LocaleKeys.editor_colAddBefore.tr(); } /// `Add before` @override String get rowAddBefore { return LocaleKeys.editor_rowAddBefore.tr(); } /// `Add after` @override String get colAddAfter { return LocaleKeys.editor_colAddAfter.tr(); } /// `Add after` @override String get rowAddAfter { return LocaleKeys.editor_rowAddAfter.tr(); } /// `Remove` @override String get colRemove { return LocaleKeys.editor_colRemove.tr(); } /// `Remove` @override String get rowRemove { return LocaleKeys.editor_rowRemove.tr(); } /// `Duplicate` @override String get colDuplicate { return LocaleKeys.editor_colDuplicate.tr(); } /// `Duplicate` @override String get rowDuplicate { return LocaleKeys.editor_rowDuplicate.tr(); } /// `Clear Content` @override String get colClear { return LocaleKeys.editor_colClear.tr(); } /// `Clear Content` @override String get rowClear { return LocaleKeys.editor_rowClear.tr(); } /// `Enter a / to insert a block, or start typing` @override String get slashPlaceHolder { return LocaleKeys.editor_slashPlaceHolder.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/inline_math_equation/inline_math_equation_toolbar_item.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_editor/appflowy_editor.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; final ToolbarItem inlineMathEquationItem = ToolbarItem( id: 'editor.inline_math_equation', group: 2, isActive: onlyShowInSingleSelectionAndTextType, builder: (context, editorState, highlightColor, _) { final selection = editorState.selection!; final nodes = editorState.getNodesInSelection(selection); final isHighlight = nodes.allSatisfyInSelection(selection, (delta) { return delta.everyAttributes( (attributes) => attributes[InlineMathEquationKeys.formula] != null, ); }); return SVGIconItemWidget( iconBuilder: (_) => FlowySvg( FlowySvgs.math_lg, size: const Size.square(16), color: isHighlight ? highlightColor : Colors.white, ), isHighlight: isHighlight, highlightColor: highlightColor, tooltip: LocaleKeys.document_plugins_createInlineMathEquation.tr(), onPressed: () 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; } final transaction = editorState.transaction; if (isHighlight) { final formula = delta .slice(selection.startIndex, selection.endIndex) .whereType<TextInsert>() .firstOrNull ?.attributes?[InlineMathEquationKeys.formula]; assert(formula != null); if (formula == null) { return; } // clear the format transaction.replaceText( node, selection.startIndex, selection.length, formula, attributes: {}, ); } else { final text = editorState.getTextInSelection(selection).join(); transaction.replaceText( node, selection.startIndex, selection.length, '\$', attributes: { InlineMathEquationKeys.formula: text, }, ); } 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/inline_math_equation/inline_math_equation.dart
import 'package:appflowy/generated/locale_keys.g.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/style_widget/text_input.dart'; import 'package:flutter/material.dart'; import 'package:flutter_math_fork/flutter_math.dart'; import 'package:provider/provider.dart'; class InlineMathEquationKeys { const InlineMathEquationKeys._(); static const formula = 'formula'; } class InlineMathEquation extends StatefulWidget { const InlineMathEquation({ super.key, required this.formula, required this.node, required this.index, this.textStyle, }); final Node node; final int index; final String formula; final TextStyle? textStyle; @override State<InlineMathEquation> createState() => _InlineMathEquationState(); } class _InlineMathEquationState extends State<InlineMathEquation> { final popoverController = PopoverController(); @override Widget build(BuildContext context) { final theme = Theme.of(context); return _IgnoreParentPointer( child: AppFlowyPopover( controller: popoverController, direction: PopoverDirection.bottomWithLeftAligned, popupBuilder: (_) { return MathInputTextField( initialText: widget.formula, onSubmit: (value) async { popoverController.close(); if (value == widget.formula) { return; } final editorState = context.read<EditorState>(); final transaction = editorState.transaction ..formatText(widget.node, widget.index, 1, { InlineMathEquationKeys.formula: value, }); await editorState.apply(transaction); }, ); }, offset: const Offset(0, 10), child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: MouseRegion( cursor: SystemMouseCursors.click, child: Row( mainAxisSize: MainAxisSize.min, children: [ const HSpace(2), Math.tex( widget.formula, options: MathOptions( style: MathStyle.text, mathFontOptions: const FontOptions( fontShape: FontStyle.italic, ), fontSize: 14.0, color: widget.textStyle?.color ?? theme.colorScheme.onBackground, ), ), const HSpace(2), ], ), ), ), ), ); } } class MathInputTextField extends StatefulWidget { const MathInputTextField({ super.key, required this.initialText, required this.onSubmit, }); final String initialText; final void Function(String value) onSubmit; @override State<MathInputTextField> createState() => _MathInputTextFieldState(); } class _MathInputTextFieldState extends State<MathInputTextField> { late final TextEditingController textEditingController; @override void initState() { super.initState(); textEditingController = TextEditingController( text: widget.initialText, ); textEditingController.selection = TextSelection( baseOffset: 0, extentOffset: widget.initialText.length, ); } @override void dispose() { textEditingController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SizedBox( width: 240, child: Row( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: FlowyFormTextInput( autoFocus: true, textAlign: TextAlign.left, controller: textEditingController, contentPadding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 4.0, ), onEditingComplete: () => widget.onSubmit(textEditingController.text), ), ), const HSpace(4.0), FlowyButton( text: FlowyText(LocaleKeys.button_done.tr()), useIntrinsicWidth: true, onTap: () => widget.onSubmit(textEditingController.text), ), ], ), ); } } class _IgnoreParentPointer extends StatelessWidget { const _IgnoreParentPointer({ required this.child, }); final Widget child; @override Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () {}, onTapDown: (_) {}, onDoubleTap: () {}, onLongPress: () {}, child: 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/align_toolbar_item/align_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/generated/locale_keys.g.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/flowy_tooltip.dart'; import 'package:flutter/material.dart'; const String leftAlignmentKey = 'left'; const String centerAlignmentKey = 'center'; const String rightAlignmentKey = 'right'; final alignToolbarItem = ToolbarItem( id: 'editor.align', group: 4, isActive: onlyShowInTextType, builder: (context, editorState, highlightColor, _) { final selection = editorState.selection!; final nodes = editorState.getNodesInSelection(selection); bool isSatisfyCondition(bool Function(Object? value) test) { return nodes.every( (n) => test(n.attributes[blockComponentAlign]), ); } bool isHighlight = false; FlowySvgData data = FlowySvgs.toolbar_align_left_s; if (isSatisfyCondition((value) => value == leftAlignmentKey)) { isHighlight = true; data = FlowySvgs.toolbar_align_left_s; } else if (isSatisfyCondition((value) => value == centerAlignmentKey)) { isHighlight = true; data = FlowySvgs.toolbar_align_center_s; } else if (isSatisfyCondition((value) => value == rightAlignmentKey)) { isHighlight = true; data = FlowySvgs.toolbar_align_right_s; } final child = FlowySvg( data, size: const Size.square(16), color: isHighlight ? highlightColor : Colors.white, ); return MouseRegion( cursor: SystemMouseCursors.click, child: FlowyTooltip( message: LocaleKeys.document_plugins_optionAction_align.tr(), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: _AlignmentButtons( child: child, onAlignChanged: (align) async { await editorState.updateNode( selection, (node) => node.copyWith( attributes: { ...node.attributes, blockComponentAlign: align, }, ), ); }, ), ), ), ); }, ); class _AlignmentButtons extends StatefulWidget { const _AlignmentButtons({ required this.child, required this.onAlignChanged, }); final Widget child; final Function(String align) onAlignChanged; @override State<_AlignmentButtons> createState() => _AlignmentButtonsState(); } class _AlignmentButtonsState extends State<_AlignmentButtons> { @override Widget build(BuildContext context) { return AppFlowyPopover( windowPadding: const EdgeInsets.all(0), margin: const EdgeInsets.all(4), direction: PopoverDirection.bottomWithCenterAligned, offset: const Offset(0, 10), decoration: BoxDecoration( color: Theme.of(context).colorScheme.onTertiary, borderRadius: const BorderRadius.all(Radius.circular(4)), ), popupBuilder: (_) { keepEditorFocusNotifier.increase(); return _AlignButtons(onAlignChanged: widget.onAlignChanged); }, onClose: () { keepEditorFocusNotifier.decrease(); }, child: widget.child, ); } } 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), _AlignButton( icon: FlowySvgs.toolbar_align_left_s, tooltips: LocaleKeys.document_plugins_optionAction_left.tr(), onTap: () => onAlignChanged(leftAlignmentKey), ), const _Divider(), _AlignButton( icon: FlowySvgs.toolbar_align_center_s, tooltips: LocaleKeys.document_plugins_optionAction_center.tr(), onTap: () => onAlignChanged(centerAlignmentKey), ), const _Divider(), _AlignButton( icon: FlowySvgs.toolbar_align_right_s, tooltips: LocaleKeys.document_plugins_optionAction_right.tr(), onTap: () => onAlignChanged(rightAlignmentKey), ), const HSpace(4), ], ), ); } } class _AlignButton extends StatelessWidget { const _AlignButton({ required this.icon, required this.tooltips, required this.onTap, }); final FlowySvgData icon; final String tooltips; final VoidCallback onTap; @override Widget build(BuildContext context) { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: onTap, child: FlowyTooltip( message: tooltips, child: FlowySvg( icon, size: const Size.square(16), color: Colors.white, ), ), ), ); } } 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/align_toolbar_item/custom_text_align_command.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:flutter/material.dart'; final List<CommandShortcutEvent> customTextAlignCommands = [ customTextLeftAlignCommand, customTextCenterAlignCommand, customTextRightAlignCommand, ]; /// Windows / Linux : ctrl + shift + l /// macOS : ctrl + shift + l /// Allows the user to align text to the left /// /// - support /// - desktop /// - web /// final CommandShortcutEvent customTextLeftAlignCommand = CommandShortcutEvent( key: 'Align text to the left', command: 'ctrl+shift+l', getDescription: LocaleKeys.settings_shortcuts_commands_textAlignLeft.tr, handler: (editorState) => _textAlignHandler(editorState, leftAlignmentKey), ); /// Windows / Linux : ctrl + shift + e /// macOS : ctrl + shift + e /// Allows the user to align text to the center /// /// - support /// - desktop /// - web /// final CommandShortcutEvent customTextCenterAlignCommand = CommandShortcutEvent( key: 'Align text to the center', command: 'ctrl+shift+e', getDescription: LocaleKeys.settings_shortcuts_commands_textAlignCenter.tr, handler: (editorState) => _textAlignHandler(editorState, centerAlignmentKey), ); /// Windows / Linux : ctrl + shift + r /// macOS : ctrl + shift + r /// Allows the user to align text to the right /// /// - support /// - desktop /// - web /// final CommandShortcutEvent customTextRightAlignCommand = CommandShortcutEvent( key: 'Align text to the right', command: 'ctrl+shift+r', getDescription: LocaleKeys.settings_shortcuts_commands_textAlignRight.tr, handler: (editorState) => _textAlignHandler(editorState, rightAlignmentKey), ); KeyEventResult _textAlignHandler(EditorState editorState, String align) { final Selection? selection = editorState.selection; if (selection == null) { return KeyEventResult.ignored; } editorState.updateNode( selection, (node) => node.copyWith( attributes: { ...node.attributes, blockComponentAlign: align, }, ), ); return KeyEventResult.handled; }
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/mobile_math_equation_toolbar_item.dart
import 'package:appflowy/generated/flowy_svgs.g.dart'; import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; final mathEquationMobileToolbarItem = MobileToolbarItem.action( itemIconBuilder: (_, __, ___) => const SizedBox( width: 22, child: FlowySvg(FlowySvgs.math_lg), ), actionHandler: (_, editorState) async { final selection = editorState.selection; if (selection == null || !selection.isCollapsed) { return; } final path = selection.start.path; final node = editorState.getNodeAtPath(path); final delta = node?.delta; if (node == null || delta == null) { return; } final transaction = editorState.transaction; final insertedNode = mathEquationNode(); if (delta.isEmpty) { transaction ..insertNode(path, insertedNode) ..deleteNode(node); } else { transaction.insertNode( path.next, insertedNode, ); } await editorState.apply(transaction); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { final mathEquationState = editorState.getNodeAtPath(path)?.key.currentState; if (mathEquationState != null && mathEquationState is MathEquationBlockComponentWidgetState) { mathEquationState.showEditingDialog(); } }); }, );
0