Skip to content

Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.

feat: copy link to block (#6523)

Lucas37a2fb17b543
diff --git a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_copy_link_to_block_test.dart b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_copy_link_to_block_test.dart
new file mode 100644
index 0000000000..ba31bbe074
--- /dev/null
+++ b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_copy_link_to_block_test.dart
@@ -0,0 +1,174 @@
+import 'package:appflowy/env/cloud_env.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+
+import '../../../shared/constants.dart';
+import '../../../shared/util.dart';
+
+void main() {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ // copy link to block
+ group('copy link to block:', () {
+ testWidgets('copy link to check if the clipboard has the correct content',
+ (tester) async {
+ await tester.initializeAppFlowy(
+ cloudType: AuthenticatorType.appflowyCloudSelfHost,
+ );
+ await tester.tapGoogleLoginInButton();
+ await tester.expectToSeeHomePageWithGetStartedPage();
+
+ // open getting started page
+ await tester.openPage(Constants.gettingStartedPageName);
+ await tester.editor.copyLinkToBlock([0]);
+ await tester.pumpAndSettle(Durations.short1);
+
+ // check the clipboard
+ final content = await Clipboard.getData(Clipboard.kTextPlain);
+ expect(
+ content?.text,
+ matches(
+ r'^https:\/\/appflowy\.com\/app\/[a-f0-9-]{36}\/[a-f0-9-]{36}\?blockId=[A-Za-z0-9_-]+$',
+ ),
+ );
+ });
+
+ testWidgets('copy link to block(another page) and paste it in doc',
+ (tester) async {
+ await tester.initializeAppFlowy(
+ cloudType: AuthenticatorType.appflowyCloudSelfHost,
+ );
+ await tester.tapGoogleLoginInButton();
+ await tester.expectToSeeHomePageWithGetStartedPage();
+
+ // open getting started page
+ await tester.openPage(Constants.gettingStartedPageName);
+ await tester.editor.copyLinkToBlock([0]);
+
+ // create a new page and paste it
+ const pageName = 'copy link to block';
+ await tester.createNewPageInSpace(
+ spaceName: Constants.generalSpaceName,
+ layout: ViewLayoutPB.Document,
+ pageName: pageName,
+ );
+
+ // paste the link to the new page
+ await tester.editor.tapLineOfEditorAt(0);
+ await tester.editor.paste();
+ await tester.pumpAndSettle();
+
+ // check the content of the block
+ final node = tester.editor.getNodeAtPath([0]);
+ final delta = node.delta!;
+ final insert = (delta.first as TextInsert).text;
+ final attributes = delta.first.attributes;
+ expect(insert, MentionBlockKeys.mentionChar);
+ final mention =
+ attributes?[MentionBlockKeys.mention] as Map<String, dynamic>;
+ expect(mention[MentionBlockKeys.type], MentionType.page.name);
+ expect(mention[MentionBlockKeys.blockId], isNotNull);
+ expect(mention[MentionBlockKeys.pageId], isNotNull);
+ expect(
+ find.descendant(
+ of: find.byType(AppFlowyEditor),
+ matching: find.textContaining(
+ Constants.gettingStartedPageName,
+ findRichText: true,
+ ),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: find.byType(AppFlowyEditor),
+ matching: find.textContaining(
+ // the pasted block content is 'Welcome to AppFlowy'
+ 'Welcome to AppFlowy',
+ findRichText: true,
+ ),
+ ),
+ findsOneWidget,
+ );
+
+ // tap the mention block to jump to the page
+ await tester.tapButton(find.byType(MentionPageBlock));
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('copy link to block(same page) and paste it in doc',
+ (tester) async {
+ await tester.initializeAppFlowy(
+ cloudType: AuthenticatorType.appflowyCloudSelfHost,
+ );
+ await tester.tapGoogleLoginInButton();
+ await tester.expectToSeeHomePageWithGetStartedPage();
+
+ // create a new page and paste it
+ const pageName = 'copy link to block';
+ await tester.createNewPageInSpace(
+ spaceName: Constants.generalSpaceName,
+ layout: ViewLayoutPB.Document,
+ pageName: pageName,
+ );
+
+ // copy the link to block from the first line
+ const inputText = 'Hello World';
+ await tester.editor.tapLineOfEditorAt(0);
+ await tester.ime.insertText(inputText);
+ await tester.ime.insertCharacter('\n');
+ await tester.pumpAndSettle();
+ await tester.editor.copyLinkToBlock([0]);
+
+ // paste the link to the second line
+ await tester.editor.tapLineOfEditorAt(1);
+ await tester.editor.paste();
+ await tester.pumpAndSettle();
+
+ // check the content of the block
+ final node = tester.editor.getNodeAtPath([1]);
+ final delta = node.delta!;
+ final insert = (delta.first as TextInsert).text;
+ final attributes = delta.first.attributes;
+ expect(insert, MentionBlockKeys.mentionChar);
+ final mention =
+ attributes?[MentionBlockKeys.mention] as Map<String, dynamic>;
+ expect(mention[MentionBlockKeys.type], MentionType.page.name);
+ expect(mention[MentionBlockKeys.blockId], isNotNull);
+ expect(mention[MentionBlockKeys.pageId], isNotNull);
+ expect(
+ find.descendant(
+ of: find.byType(AppFlowyEditor),
+ matching: find.textContaining(
+ inputText,
+ findRichText: true,
+ ),
+ ),
+ findsNWidgets(2),
+ );
+
+ // edit the pasted block
+ await tester.editor.tapLineOfEditorAt(0);
+ await tester.ime.insertText('!');
+ await tester.pumpAndSettle();
+
+ // check the content of the block
+ expect(
+ find.descendant(
+ of: find.byType(AppFlowyEditor),
+ matching: find.textContaining(
+ '$inputText!',
+ findRichText: true,
+ ),
+ ),
+ findsNWidgets(2),
+ );
+ });
+ });
+}
diff --git a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_option_actions_test.dart b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_option_actions_test.dart
index 31580c330a..0289fbe176 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_option_actions_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_option_actions_test.dart
@@ -68,38 +68,6 @@ void main() {
expect(afterMoveBlock.delta, beforeMoveBlock.delta);
});
- // Copy link to block feature is disable temporarily, enable this test when the feature is ready.
- // testWidgets('copy block link', (tester) async {
- // await tester.initializeAppFlowy(
- // cloudType: AuthenticatorType.appflowyCloudSelfHost,
- // );
- // await tester.tapGoogleLoginInButton();
- // await tester.expectToSeeHomePageWithGetStartedPage();
-
- // // open getting started page
- // await tester.openPage(Constants.gettingStartedPageName);
-
- // // hover and click on the option menu button beside the block component.
- // await tester.editor.hoverAndClickOptionMenuButton([0]);
-
- // // click the copy link to block option
- // await tester.tap(
- // find.findTextInFlowyText(
- // LocaleKeys.document_plugins_optionAction_copyLinkToBlock.tr(),
- // ),
- // );
- // await tester.pumpAndSettle(Durations.short1);
-
- // // check the clipboard
- // final content = await Clipboard.getData(Clipboard.kTextPlain);
- // expect(
- // content?.text,
- // matches(
- // r'^https:\/\/appflowy\.com\/app\/[a-f0-9-]{36}\/[a-f0-9-]{36}\?blockId=[A-Za-z0-9_-]+$',
- // ),
- // );
- // });
-
testWidgets('hover on the block and delete it', (tester) async {
await tester.initializeAppFlowy(
cloudType: AuthenticatorType.appflowyCloudSelfHost,
diff --git a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_test_runner.dart b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_test_runner.dart
index 336e824b37..3a9af560ce 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_test_runner.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_test_runner.dart
@@ -1,9 +1,12 @@
import 'package:integration_test/integration_test.dart';
+import 'document_copy_link_to_block_test.dart'
+ as document_copy_link_to_block_test;
import 'document_option_actions_test.dart' as document_option_actions_test;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
document_option_actions_test.main();
+ document_copy_link_to_block_test.main();
}
diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_test_runner_2.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_test_runner_2.dart
index f4af09c61f..3a0a3d5adf 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/document/document_test_runner_2.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_test_runner_2.dart
@@ -1,8 +1,9 @@
import 'package:integration_test/integration_test.dart';
import 'document_app_lifecycle_test.dart' as document_app_lifecycle_test;
-import 'document_title_test.dart' as document_title_test;
import 'document_deletion_test.dart' as document_deletion_test;
+import 'document_option_action_test.dart' as document_option_action_test;
+import 'document_title_test.dart' as document_title_test;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
@@ -13,4 +14,5 @@ void main() {
// document_sub_page_test.main();
document_app_lifecycle_test.main();
document_deletion_test.main();
+ document_option_action_test.main();
}
diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_with_inline_page_test.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_with_inline_page_test.dart
index 45613fe97f..2a552c0d22 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/document/document_with_inline_page_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_with_inline_page_test.dart
@@ -1,5 +1,5 @@
+import 'package:appflowy/plugins/database/grid/presentation/grid_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart';
-import 'package:appflowy/shared/flowy_error_page.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:flowy_infra/uuid.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -92,7 +92,7 @@ void main() {
);
expect(finder, findsOneWidget);
await tester.tapButton(finder);
- expect(find.byType(AppFlowyErrorPage), findsOneWidget);
+ expect(find.byType(GridPage), findsOneWidget);
});
});
}
diff --git a/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart b/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart
index 3b38ed04a1..1ea750fd11 100644
--- a/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart
+++ b/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart
@@ -73,6 +73,20 @@ class EditorOperations {
expect(find.byType(FlowyEmojiPicker), findsOneWidget);
}
+ Future<void> paste() async {
+ if (UniversalPlatform.isMacOS) {
+ await tester.simulateKeyEvent(
+ LogicalKeyboardKey.keyV,
+ isMetaPressed: true,
+ );
+ } else {
+ await tester.simulateKeyEvent(
+ LogicalKeyboardKey.keyV,
+ isControlPressed: true,
+ );
+ }
+ }
+
Future<void> tapGettingStartedIcon() async {
await tester.tapButton(
find.descendant(
@@ -293,6 +307,16 @@ class EditorOperations {
await tester.pumpUntilFound(find.byType(TurnIntoOptionMenu));
}
+ /// copy link to block
+ Future<void> copyLinkToBlock(Path path) async {
+ await hoverAndClickOptionMenuButton(path);
+ await tester.tapButton(
+ find.findTextInFlowyText(
+ LocaleKeys.document_plugins_optionAction_copyLinkToBlock.tr(),
+ ),
+ );
+ }
+
Future<void> openDepthMenu(Path path) async {
await hoverAndClickOptionMenuButton(path);
await tester.tapButton(
diff --git a/frontend/appflowy_flutter/lib/mobile/presentation/notifications/widgets/shared.dart b/frontend/appflowy_flutter/lib/mobile/presentation/notifications/widgets/shared.dart
index 4f1a7d2db0..ee7581bdb0 100644
--- a/frontend/appflowy_flutter/lib/mobile/presentation/notifications/widgets/shared.dart
+++ b/frontend/appflowy_flutter/lib/mobile/presentation/notifications/widgets/shared.dart
@@ -258,7 +258,7 @@ class NotificationDocumentContent extends StatelessWidget {
),
);
- final blockBuilders = getEditorBuilderMap(
+ final blockBuilders = buildBlockComponentBuilders(
context: context,
editorState: editorState,
styleCustomizer: styleCustomizer,
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart
index e5359161b4..f8669ffa09 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart
@@ -108,7 +108,7 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
cursorColor: Colors.transparent,
cursorWidth: 0,
);
- final blockBuilders = getEditorBuilderMap(
+ final blockBuilders = buildBlockComponentBuilders(
context: context,
editorState: editorState,
styleCustomizer: styleCustomizer,
diff --git a/frontend/appflowy_flutter/lib/plugins/document/application/document_service.dart b/frontend/appflowy_flutter/lib/plugins/document/application/document_service.dart
index 57b86ce2d4..f520e20d02 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/application/document_service.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/application/document_service.dart
@@ -1,4 +1,6 @@
+import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
+import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
@@ -36,6 +38,41 @@ class DocumentService {
return result;
}
+ Future<FlowyResult<(DocumentDataPB, BlockPB, Node), FlowyError>>
+ getDocumentNode({
+ required String documentId,
+ required String blockId,
+ }) async {
+ final documentResult = await getDocument(documentId: documentId);
+ final document = documentResult.fold((l) => l, (f) => null);
+ if (document == null) {
+ Log.error('unable to get the document for page $documentId');
+ return FlowyResult.failure(FlowyError(msg: 'Document not found'));
+ }
+
+ final blockResult = await getBlockFromDocument(
+ document: document,
+ blockId: blockId,
+ );
+ final block = blockResult.fold((l) => l, (f) => null);
+ if (block == null) {
+ Log.error(
+ 'unable to get the block $blockId from the document $documentId',
+ );
+ return FlowyResult.failure(FlowyError(msg: 'Block not found'));
+ }
+
+ final node = document.buildNode(blockId);
+ if (node == null) {
+ Log.error(
+ 'unable to get the node for block $blockId in document $documentId',
+ );
+ return FlowyResult.failure(FlowyError(msg: 'Node not found'));
+ }
+
+ return FlowyResult.success((document, block, node));
+ }
+
Future<FlowyResult<BlockPB, FlowyError>> getBlockFromDocument({
required DocumentDataPB document,
required String blockId,
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart
index 6263a57f2f..0b5626767f 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart
@@ -18,49 +18,17 @@ import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:universal_platform/universal_platform.dart';
-enum EditorOptionActionType {
- turnInto,
- color,
- align,
- depth;
-
- Set<String> get supportTypes {
- switch (this) {
- case EditorOptionActionType.turnInto:
- return {
- ParagraphBlockKeys.type,
- HeadingBlockKeys.type,
- QuoteBlockKeys.type,
- CalloutBlockKeys.type,
- BulletedListBlockKeys.type,
- NumberedListBlockKeys.type,
- TodoListBlockKeys.type,
- };
- case EditorOptionActionType.color:
- return {
- ParagraphBlockKeys.type,
- HeadingBlockKeys.type,
- BulletedListBlockKeys.type,
- NumberedListBlockKeys.type,
- QuoteBlockKeys.type,
- TodoListBlockKeys.type,
- CalloutBlockKeys.type,
- OutlineBlockKeys.type,
- ToggleListBlockKeys.type,
- };
- case EditorOptionActionType.align:
- return {
- ImageBlockKeys.type,
- };
- case EditorOptionActionType.depth:
- return {
- OutlineBlockKeys.type,
- };
- }
- }
-}
-
-Map<String, BlockComponentBuilder> getEditorBuilderMap({
+/// Build the block component builders.
+///
+/// Every block type should have a corresponding builder in the map.
+/// Otherwise, the errorBlockComponentBuilder will be rendered.
+///
+/// Additional, you can define the block render options in the builder
+/// - customize the block option actions. (... button and + button)
+/// - customize the block component configuration. (padding, placeholder, etc.)
+/// - customize the block icon. (bulleted list, numbered list, todo list)
+/// - customize the hover menu. (show the menu at the top-right corner of the block)
+Map<String, BlockComponentBuilder> buildBlockComponentBuilders({
required BuildContext context,
required EditorState editorState,
required EditorStyleCustomizer styleCustomizer,
@@ -70,18 +38,32 @@ Map<String, BlockComponentBuilder> getEditorBuilderMap({
String Function(Node)? placeholderText,
EdgeInsets? customHeadingPadding,
}) {
- final standardActions = [
- OptionAction.delete,
- OptionAction.duplicate,
- // Copy link to block feature is disable temporarily, enable this test when the feature is ready.
- // filter out the copy link to block option if in local mode
- // if (context.read<DocumentBloc?>()?.isLocalMode != true)
- // OptionAction.copyLinkToBlock,
- ];
+ final configuration = _buildDefaultConfiguration(context);
+ final builders = _buildBlockComponentBuilderMap(
+ context,
+ configuration: configuration,
+ editorState: editorState,
+ styleCustomizer: styleCustomizer,
+ showParagraphPlaceholder: showParagraphPlaceholder,
+ placeholderText: placeholderText,
+ );
- final calloutBGColor = AFThemeExtension.of(context).calloutBGColor;
+ // customize the action builder. actually, we can customize them in their own builder. Put them here just for convenience.
+ if (editable) {
+ _customBlockOptionActions(
+ context,
+ builders: builders,
+ editorState: editorState,
+ styleCustomizer: styleCustomizer,
+ slashMenuItems: slashMenuItems,
+ );
+ }
+
+ return builders;
+}
+
+BlockComponentConfiguration _buildDefaultConfiguration(BuildContext context) {
final configuration = BlockComponentConfiguration(
- // use EdgeInsets.zero to remove the default padding.
padding: (_) {
if (UniversalPlatform.isMobile) {
final pageStyle = context.read<DocumentPageStyleBloc>().state;
@@ -96,218 +78,201 @@ Map<String, BlockComponentBuilder> getEditorBuilderMap({
? const EdgeInsets.only(left: 26.0)
: const EdgeInsets.only(right: 26.0),
);
+ return configuration;
+}
+
+/// Build the option actions for the block component.
+///
+/// Notes: different block type may have different option actions.
+/// All the block types have the delete and duplicate options.
+List<OptionAction> _buildOptionActions(BuildContext context, String type) {
+ final standardActions = [
+ OptionAction.delete,
+ OptionAction.duplicate,
+ ];
+
+ // filter out the copy link to block option if in local mode
+ if (context.read<DocumentBloc?>()?.isLocalMode != true) {
+ standardActions.add(OptionAction.copyLinkToBlock);
+ }
+ if (EditorOptionActionType.turnInto.supportTypes.contains(type)) {
+ standardActions.add(OptionAction.turnInto);
+ }
+
+ if (EditorOptionActionType.color.supportTypes.contains(type)) {
+ standardActions.addAll([OptionAction.divider, OptionAction.color]);
+ }
+
+ if (EditorOptionActionType.align.supportTypes.contains(type)) {
+ standardActions.addAll([OptionAction.divider, OptionAction.align]);
+ }
+
+ if (EditorOptionActionType.depth.supportTypes.contains(type)) {
+ standardActions.addAll([OptionAction.divider, OptionAction.depth]);
+ }
+
+ return standardActions;
+}
+
+void _customBlockOptionActions(
+ BuildContext context, {
+ required Map<String, BlockComponentBuilder> builders,
+ required EditorState editorState,
+ required EditorStyleCustomizer styleCustomizer,
+ List<SelectionMenuItem>? slashMenuItems,
+}) {
+ for (final entry in builders.entries) {
+ if (entry.key == PageBlockKeys.type) {
+ continue;
+ }
+ final builder = entry.value;
+ final actions = _buildOptionActions(context, entry.key);
+
+ if (UniversalPlatform.isDesktop) {
+ builder.showActions =
+ (node) => node.parent?.type != TableCellBlockKeys.type;
+
+ builder.actionBuilder = (context, state) {
+ final top = builder.configuration.padding(context.node).top;
+ final padding = context.node.type == HeadingBlockKeys.type
+ ? EdgeInsets.only(top: top + 8.0)
+ : EdgeInsets.only(top: top + 2.0);
+ return Padding(
+ padding: padding,
+ child: BlockActionList(
+ blockComponentContext: context,
+ blockComponentState: state,
+ editorState: editorState,
+ blockComponentBuilder: builders,
+ actions: actions,
+ showSlashMenu: slashMenuItems != null
+ ? () => customSlashCommand(
+ slashMenuItems,
+ shouldInsertSlash: false,
+ style: styleCustomizer.selectionMenuStyleBuilder(),
+ ).handler.call(editorState)
+ : () {},
+ ),
+ );
+ };
+ }
+ }
+}
+
+Map<String, BlockComponentBuilder> _buildBlockComponentBuilderMap(
+ BuildContext context, {
+ required BlockComponentConfiguration configuration,
+ required EditorState editorState,
+ required EditorStyleCustomizer styleCustomizer,
+ ShowPlaceholder? showParagraphPlaceholder,
+ String Function(Node)? placeholderText,
+ EdgeInsets? customHeadingPadding,
+}) {
final customBlockComponentBuilderMap = {
PageBlockKeys.type: PageBlockComponentBuilder(),
- ParagraphBlockKeys.type: ParagraphBlockComponentBuilder(
- configuration: configuration.copyWith(placeholderText: placeholderText),
- showPlaceholder: showParagraphPlaceholder,
+ ParagraphBlockKeys.type: _buildParagraphBlockComponentBuilder(
+ context,
+ configuration,
+ showParagraphPlaceholder,
+ placeholderText,
),
- TodoListBlockKeys.type: TodoListBlockComponentBuilder(
- configuration: configuration.copyWith(
- placeholderText: (_) => LocaleKeys.blockPlaceholders_todoList.tr(),
- ),
- iconBuilder: (_, node, onCheck) =>
- TodoListIcon(node: node, onCheck: onCheck),
- toggleChildrenTriggers: [
- LogicalKeyboardKey.shift,
- LogicalKeyboardKey.shiftLeft,
- LogicalKeyboardKey.shiftRight,
- ],
- ),
- BulletedListBlockKeys.type: BulletedListBlockComponentBuilder(
- configuration: configuration.copyWith(
- placeholderText: (_) => LocaleKeys.blockPlaceholders_bulletList.tr(),
- ),
- iconBuilder: (_, node) => BulletedListIcon(node: node),
+ TodoListBlockKeys.type: _buildTodoListBlockComponentBuilder(
+ context,
+ configuration,
),
- NumberedListBlockKeys.type: NumberedListBlockComponentBuilder(
- configuration: configuration.copyWith(
- placeholderText: (_) => LocaleKeys.blockPlaceholders_numberList.tr(),
- ),
- iconBuilder: (_, node, textDirection) =>
- NumberedListIcon(node: node, textDirection: textDirection),
+ BulletedListBlockKeys.type: _buildBulletedListBlockComponentBuilder(
+ context,
+ configuration,
),
- QuoteBlockKeys.type: QuoteBlockComponentBuilder(
- configuration: configuration.copyWith(
- placeholderText: (_) => LocaleKeys.blockPlaceholders_quote.tr(),
- ),
+ NumberedListBlockKeys.type: _buildNumberedListBlockComponentBuilder(
+ context,
+ configuration,
),
- HeadingBlockKeys.type: HeadingBlockComponentBuilder(
- configuration: configuration.copyWith(
- padding: (node) {
- if (customHeadingPadding != null) {
- return customHeadingPadding;
- }
-
- if (UniversalPlatform.isMobile) {
- final pageStyle = context.read<DocumentPageStyleBloc>().state;
- final factor = pageStyle.fontLayout.factor;
- final headingPaddings = pageStyle.lineHeightLayout.headingPaddings
- .map((e) => e * factor);
- int level = node.attributes[HeadingBlockKeys.level] ?? 6;
- level = level.clamp(1, 6);
- return EdgeInsets.only(top: headingPaddings.elementAt(level - 1));
- }
-
- return const EdgeInsets.only(top: 12.0, bottom: 4.0);
- },
- placeholderText: (node) {
- int level = node.attributes[HeadingBlockKeys.level] ?? 6;
- level = level.clamp(1, 6);
- return LocaleKeys.blockPlaceholders_heading.tr(
- args: [level.toString()],
- );
- },
- ),
- textStyleBuilder: (level) => styleCustomizer.headingStyleBuilder(level),
+ QuoteBlockKeys.type: _buildQuoteBlockComponentBuilder(
+ context,
+ configuration,
),
- ImageBlockKeys.type: CustomImageBlockComponentBuilder(
- configuration: configuration,
- showMenu: true,
- menuBuilder: (node, state) => Positioned(
- top: 10,
- right: 10,
- child: ImageMenu(node: node, state: state),
- ),
+ HeadingBlockKeys.type: _buildHeadingBlockComponentBuilder(
+ context,
+ configuration,
+ styleCustomizer,
+ customHeadingPadding,
),
- MultiImageBlockKeys.type: MultiImageBlockComponentBuilder(
- configuration: configuration,
- showMenu: true,
- menuBuilder: (
- Node node,
- MultiImageBlockComponentState state,
- ValueNotifier<int> indexNotifier,
- VoidCallback onImageDeleted,
- ) =>
- Positioned(
- top: 10,
- right: 10,
- child: MultiImageMenu(
- node: node,
- state: state,
- indexNotifier: indexNotifier,
- isLocalMode: context.read<DocumentBloc>().isLocalMode,
- onImageDeleted: onImageDeleted,
- ),
- ),
+ ImageBlockKeys.type: _buildCustomImageBlockComponentBuilder(
+ context,
+ configuration,
),
- TableBlockKeys.type: TableBlockComponentBuilder(
- menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
- TableMenu(
- node: node,
- editorState: editorState,
- position: position,
- dir: dir,
- onBuild: onBuild,
- onClose: onClose,
- ),
+ MultiImageBlockKeys.type: _buildMultiImageBlockComponentBuilder(
+ context,
+ configuration,
),
- TableCellBlockKeys.type: TableCellBlockComponentBuilder(
- colorBuilder: (context, node) {
- final String colorString =
- node.attributes[TableCellBlockKeys.colBackgroundColor] ??
- node.attributes[TableCellBlockKeys.rowBackgroundColor] ??
- '';
- if (colorString.isEmpty) {
- return null;
- }
- return buildEditorCustomizedColor(context, node, colorString);
- },
- menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
- TableMenu(
- node: node,
- editorState: editorState,
- position: position,
- dir: dir,
- onBuild: onBuild,
- onClose: onClose,
- ),
+ TableBlockKeys.type: _buildTableBlockComponentBuilder(
+ context,
+ configuration,
),
- DatabaseBlockKeys.gridType: DatabaseViewBlockComponentBuilder(
- configuration: configuration.copyWith(
- padding: (_) => const EdgeInsets.symmetric(vertical: 10),
- ),
+ TableCellBlockKeys.type: _buildTableCellBlockComponentBuilder(
+ context,
+ configuration,
),
- DatabaseBlockKeys.boardType: DatabaseViewBlockComponentBuilder(
- configuration: configuration.copyWith(
- padding: (_) => const EdgeInsets.symmetric(vertical: 10),
- ),
+ DatabaseBlockKeys.gridType: _buildDatabaseViewBlockComponentBuilder(
+ context,
+ configuration,
),
- DatabaseBlockKeys.calendarType: DatabaseViewBlockComponentBuilder(
- configuration: configuration.copyWith(
- padding: (_) => const EdgeInsets.symmetric(vertical: 10),
- ),
+ DatabaseBlockKeys.boardType: _buildDatabaseViewBlockComponentBuilder(
+ context,
+ configuration,
),
- CalloutBlockKeys.type: CalloutBlockComponentBuilder(
- configuration: configuration.copyWith(
- padding: (node) => const EdgeInsets.symmetric(vertical: 10),
- ),
- inlinePadding: const EdgeInsets.symmetric(vertical: 8.0),
- defaultColor: calloutBGColor,
+ DatabaseBlockKeys.calendarType: _buildDatabaseViewBlockComponentBuilder(
+ context,
+ configuration,
),
- DividerBlockKeys.type: DividerBlockComponentBuilder(
- configuration: configuration,
- height: 28.0,
- wrapper: (_, node, child) => MobileBlockActionButtons(
- showThreeDots: false,
- node: node,
- editorState: editorState,
- child: child,
- ),
+ CalloutBlockKeys.type: _buildCalloutBlockComponentBuilder(
+ context,
+ configuration,
),
- MathEquationBlockKeys.type: MathEquationBlockComponentBuilder(
- configuration: configuration,
+ DividerBlockKeys.type: _buildDividerBlockComponentBuilder(
+ context,
+ configuration,
+ editorState,
),
- CodeBlockKeys.type: CodeBlockComponentBuilder(
- configuration: configuration.copyWith(
- textStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
- placeholderTextStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
- ),
- styleBuilder: () => CodeBlockStyle(
- backgroundColor: AFThemeExtension.of(context).calloutBGColor,
- foregroundColor: AFThemeExtension.of(context).textColor.withAlpha(155),
- ),
- padding: const EdgeInsets.only(left: 20, right: 30, bottom: 34),
- languagePickerBuilder: codeBlockLanguagePickerBuilder,
- copyButtonBuilder: codeBlockCopyBuilder,
- showLineNumbers: false,
- ),
- AutoCompletionBlockKeys.type: AutoCompletionBlockComponentBuilder(),
- SmartEditBlockKeys.type: SmartEditBlockComponentBuilder(),
- ToggleListBlockKeys.type: ToggleListBlockComponentBuilder(
- configuration: configuration,
+ MathEquationBlockKeys.type: _buildMathEquationBlockComponentBuilder(
+ context,
+ configuration,
),
- OutlineBlockKeys.type: OutlineBlockComponentBuilder(
- configuration: configuration.copyWith(
- placeholderTextStyle: (_) =>
- styleCustomizer.outlineBlockPlaceholderStyleBuilder(),
- padding: (_) => const EdgeInsets.only(top: 12.0, bottom: 4.0),
- ),
+ CodeBlockKeys.type: _buildCodeBlockComponentBuilder(
+ context,
+ configuration,
+ styleCustomizer,
),
- LinkPreviewBlockKeys.type: LinkPreviewBlockComponentBuilder(
- configuration: configuration.copyWith(
- padding: (_) => const EdgeInsets.symmetric(vertical: 10),
- ),
- cache: LinkPreviewDataCache(),
- showMenu: true,
- menuBuilder: (context, node, state) => Positioned(
- top: 10,
- right: 0,
- child: LinkPreviewMenu(node: node, state: state),
- ),
- builder: (_, node, url, title, description, imageUrl) =>
- CustomLinkPreviewWidget(
- node: node,
- url: url,
- title: title,
- description: description,
- imageUrl: imageUrl,
- ),
+ AutoCompletionBlockKeys.type: _buildAutoCompletionBlockComponentBuilder(
+ context,
+ configuration,
),
- FileBlockKeys.type: FileBlockComponentBuilder(configuration: configuration),
- SubPageBlockKeys.type: SubPageBlockComponentBuilder(
- configuration: configuration,
+ SmartEditBlockKeys.type: _buildSmartEditBlockComponentBuilder(
+ context,
+ configuration,
+ ),
+ ToggleListBlockKeys.type: _buildToggleListBlockComponentBuilder(
+ context,
+ configuration,
+ ),
+ OutlineBlockKeys.type: _buildOutlineBlockComponentBuilder(
+ context,
+ configuration,
+ styleCustomizer,
+ ),
+ LinkPreviewBlockKeys.type: _buildLinkPreviewBlockComponentBuilder(
+ context,
+ configuration,
+ ),
+ FileBlockKeys.type: _buildFileBlockComponentBuilder(
+ context,
+ configuration,
+ ),
+ SubPageBlockKeys.type: _buildSubPageBlockComponentBuilder(
+ context,
+ configuration,
),
errorBlockComponentBuilderKey: ErrorBlockComponentBuilder(
configuration: configuration,
@@ -319,61 +284,347 @@ Map<String, BlockComponentBuilder> getEditorBuilderMap({
...customBlockComponentBuilderMap,
};
- if (editable) {
- // customize the action builder. actually, we can customize them in their own builder. Put them here just for convenience.
- for (final entry in builders.entries) {
- if (entry.key == PageBlockKeys.type) {
- continue;
- }
- final builder = entry.value;
-
- final colorAction = [OptionAction.divider, OptionAction.color];
- final alignAction = [OptionAction.divider, OptionAction.align];
- final depthAction = [OptionAction.depth];
- final turnIntoAction = [OptionAction.turnInto];
-
- final List<OptionAction> actions = [
- ...standardActions,
- if (EditorOptionActionType.turnInto.supportTypes.contains(entry.key))
- ...turnIntoAction,
- if (EditorOptionActionType.color.supportTypes.contains(entry.key))
- ...colorAction,
- if (EditorOptionActionType.align.supportTypes.contains(entry.key))
- ...alignAction,
- if (EditorOptionActionType.depth.supportTypes.contains(entry.key))
- ...depthAction,
- ];
-
- if (UniversalPlatform.isDesktop) {
- builder.showActions =
- (node) => node.parent?.type != TableCellBlockKeys.type;
-
- builder.actionBuilder = (context, state) {
- final top = builder.configuration.padding(context.node).top;
- final padding = context.node.type == HeadingBlockKeys.type
- ? EdgeInsets.only(top: top + 8.0)
- : EdgeInsets.only(top: top + 2.0);
- return Padding(
- padding: padding,
- child: BlockActionList(
- blockComponentContext: context,
- blockComponentState: state,
- editorState: editorState,
- blockComponentBuilder: builders,
- actions: actions,
- showSlashMenu: slashMenuItems != null
- ? () => customSlashCommand(
- slashMenuItems,
- shouldInsertSlash: false,
- style: styleCustomizer.selectionMenuStyleBuilder(),
- ).handler.call(editorState)
- : () {},
- ),
- );
- };
+ return builders;
+}
+
+ParagraphBlockComponentBuilder _buildParagraphBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+ ShowPlaceholder? showParagraphPlaceholder,
+ String Function(Node)? placeholderText,
+) {
+ return ParagraphBlockComponentBuilder(
+ configuration: configuration.copyWith(placeholderText: placeholderText),
+ showPlaceholder: showParagraphPlaceholder,
+ );
+}
+
+TodoListBlockComponentBuilder _buildTodoListBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return TodoListBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ placeholderText: (_) => LocaleKeys.blockPlaceholders_todoList.tr(),
+ ),
+ iconBuilder: (_, node, onCheck) => TodoListIcon(
+ node: node,
+ onCheck: onCheck,
+ ),
+ toggleChildrenTriggers: [
+ LogicalKeyboardKey.shift,
+ LogicalKeyboardKey.shiftLeft,
+ LogicalKeyboardKey.shiftRight,
+ ],
+ );
+}
+
+BulletedListBlockComponentBuilder _buildBulletedListBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return BulletedListBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ placeholderText: (_) => LocaleKeys.blockPlaceholders_bulletList.tr(),
+ ),
+ iconBuilder: (_, node) => BulletedListIcon(node: node),
+ );
+}
+
+NumberedListBlockComponentBuilder _buildNumberedListBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return NumberedListBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ placeholderText: (_) => LocaleKeys.blockPlaceholders_numberList.tr(),
+ ),
+ iconBuilder: (_, node, textDirection) => NumberedListIcon(
+ node: node,
+ textDirection: textDirection,
+ ),
+ );
+}
+
+QuoteBlockComponentBuilder _buildQuoteBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return QuoteBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ placeholderText: (_) => LocaleKeys.blockPlaceholders_quote.tr(),
+ ),
+ );
+}
+
+HeadingBlockComponentBuilder _buildHeadingBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+ EditorStyleCustomizer styleCustomizer,
+ EdgeInsets? customHeadingPadding,
+) {
+ return HeadingBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ padding: (node) {
+ if (customHeadingPadding != null) {
+ return customHeadingPadding;
+ }
+
+ if (UniversalPlatform.isMobile) {
+ final pageStyle = context.read<DocumentPageStyleBloc>().state;
+ final factor = pageStyle.fontLayout.factor;
+ final headingPaddings =
+ pageStyle.lineHeightLayout.headingPaddings.map((e) => e * factor);
+ int level = node.attributes[HeadingBlockKeys.level] ?? 6;
+ level = level.clamp(1, 6);
+ return EdgeInsets.only(top: headingPaddings.elementAt(level - 1));
+ }
+
+ return const EdgeInsets.only(top: 12.0, bottom: 4.0);
+ },
+ placeholderText: (node) {
+ int level = node.attributes[HeadingBlockKeys.level] ?? 6;
+ level = level.clamp(1, 6);
+ return LocaleKeys.blockPlaceholders_heading.tr(
+ args: [level.toString()],
+ );
+ },
+ ),
+ textStyleBuilder: (level) => styleCustomizer.headingStyleBuilder(level),
+ );
+}
+
+CustomImageBlockComponentBuilder _buildCustomImageBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return CustomImageBlockComponentBuilder(
+ configuration: configuration,
+ showMenu: true,
+ menuBuilder: (node, state) => Positioned(
+ top: 10,
+ right: 10,
+ child: ImageMenu(node: node, state: state),
+ ),
+ );
+}
+
+MultiImageBlockComponentBuilder _buildMultiImageBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return MultiImageBlockComponentBuilder(
+ configuration: configuration,
+ showMenu: true,
+ menuBuilder: (
+ Node node,
+ MultiImageBlockComponentState state,
+ ValueNotifier<int> indexNotifier,
+ VoidCallback onImageDeleted,
+ ) =>
+ Positioned(
+ top: 10,
+ right: 10,
+ child: MultiImageMenu(
+ node: node,
+ state: state,
+ indexNotifier: indexNotifier,
+ isLocalMode: context.read<DocumentBloc>().isLocalMode,
+ onImageDeleted: onImageDeleted,
+ ),
+ ),
+ );
+}
+
+TableBlockComponentBuilder _buildTableBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return TableBlockComponentBuilder(
+ menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
+ TableMenu(
+ node: node,
+ editorState: editorState,
+ position: position,
+ dir: dir,
+ onBuild: onBuild,
+ onClose: onClose,
+ ),
+ );
+}
+
+TableCellBlockComponentBuilder _buildTableCellBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return TableCellBlockComponentBuilder(
+ colorBuilder: (context, node) {
+ final String colorString =
+ node.attributes[TableCellBlockKeys.colBackgroundColor] ??
+ node.attributes[TableCellBlockKeys.rowBackgroundColor] ??
+ '';
+ if (colorString.isEmpty) {
+ return null;
}
- }
- }
+ return buildEditorCustomizedColor(context, node, colorString);
+ },
+ menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
+ TableMenu(
+ node: node,
+ editorState: editorState,
+ position: position,
+ dir: dir,
+ onBuild: onBuild,
+ onClose: onClose,
+ ),
+ );
+}
- return builders;
+DatabaseViewBlockComponentBuilder _buildDatabaseViewBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return DatabaseViewBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ padding: (_) => const EdgeInsets.symmetric(vertical: 10),
+ ),
+ );
+}
+
+CalloutBlockComponentBuilder _buildCalloutBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ final calloutBGColor = AFThemeExtension.of(context).calloutBGColor;
+ return CalloutBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ padding: (node) => const EdgeInsets.symmetric(vertical: 10),
+ ),
+ inlinePadding: const EdgeInsets.symmetric(vertical: 8.0),
+ defaultColor: calloutBGColor,
+ );
+}
+
+DividerBlockComponentBuilder _buildDividerBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+ EditorState editorState,
+) {
+ return DividerBlockComponentBuilder(
+ configuration: configuration,
+ height: 28.0,
+ wrapper: (_, node, child) => MobileBlockActionButtons(
+ showThreeDots: false,
+ node: node,
+ editorState: editorState,
+ child: child,
+ ),
+ );
+}
+
+MathEquationBlockComponentBuilder _buildMathEquationBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return MathEquationBlockComponentBuilder(
+ configuration: configuration,
+ );
+}
+
+CodeBlockComponentBuilder _buildCodeBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+ EditorStyleCustomizer styleCustomizer,
+) {
+ return CodeBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ textStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
+ placeholderTextStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
+ ),
+ styleBuilder: () => CodeBlockStyle(
+ backgroundColor: AFThemeExtension.of(context).calloutBGColor,
+ foregroundColor: AFThemeExtension.of(context).textColor.withAlpha(155),
+ ),
+ padding: const EdgeInsets.only(left: 20, right: 30, bottom: 34),
+ languagePickerBuilder: codeBlockLanguagePickerBuilder,
+ copyButtonBuilder: codeBlockCopyBuilder,
+ showLineNumbers: false,
+ );
+}
+
+AutoCompletionBlockComponentBuilder _buildAutoCompletionBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return AutoCompletionBlockComponentBuilder();
+}
+
+SmartEditBlockComponentBuilder _buildSmartEditBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return SmartEditBlockComponentBuilder();
+}
+
+ToggleListBlockComponentBuilder _buildToggleListBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return ToggleListBlockComponentBuilder(
+ configuration: configuration,
+ );
+}
+
+OutlineBlockComponentBuilder _buildOutlineBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+ EditorStyleCustomizer styleCustomizer,
+) {
+ return OutlineBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ placeholderTextStyle: (_) =>
+ styleCustomizer.outlineBlockPlaceholderStyleBuilder(),
+ padding: (_) => const EdgeInsets.only(top: 12.0, bottom: 4.0),
+ ),
+ );
+}
+
+LinkPreviewBlockComponentBuilder _buildLinkPreviewBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return LinkPreviewBlockComponentBuilder(
+ configuration: configuration.copyWith(
+ padding: (_) => const EdgeInsets.symmetric(vertical: 10),
+ ),
+ cache: LinkPreviewDataCache(),
+ showMenu: true,
+ menuBuilder: (context, node, state) => Positioned(
+ top: 10,
+ right: 0,
+ child: LinkPreviewMenu(node: node, state: state),
+ ),
+ builder: (_, node, url, title, description, imageUrl) =>
+ CustomLinkPreviewWidget(
+ node: node,
+ url: url,
+ title: title,
+ description: description,
+ imageUrl: imageUrl,
+ ),
+ );
+}
+
+FileBlockComponentBuilder _buildFileBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return FileBlockComponentBuilder(configuration: configuration);
+}
+
+SubPageBlockComponentBuilder _buildSubPageBlockComponentBuilder(
+ BuildContext context,
+ BlockComponentConfiguration configuration,
+) {
+ return SubPageBlockComponentBuilder(configuration: configuration);
}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
index 1617597131..10b48cb29e 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
@@ -281,7 +281,7 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
// setup the theme
editorStyle: styleCustomizer.style(),
// customize the block builders
- blockComponentBuilders: getEditorBuilderMap(
+ blockComponentBuilders: buildBlockComponentBuilders(
slashMenuItems: slashMenuItems,
context: context,
editorState: widget.editorState,
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart
index 2bcb3ae430..cddeb7f2d0 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart
@@ -145,7 +145,11 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
}
Future<void> _copyLinkToBlock(Node node) async {
- final viewId = getIt<DocumentBloc>().documentId;
+ final context = editorState.document.root.context;
+ final viewId = context?.read<DocumentBloc>().documentId;
+ if (viewId == null) {
+ return;
+ }
final workspace = await FolderEventReadCurrentWorkspace().send();
final workspaceId = workspace.fold(
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/option_actions.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/option_actions.dart
index 08e2a51fa9..8aa2807548 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/option_actions.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/option_actions.dart
@@ -1,5 +1,8 @@
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' hide TextDirection;
import 'package:easy_localization/easy_localization.dart';
export 'align_option_action.dart';
@@ -8,6 +11,48 @@ export 'depth_option_action.dart';
export 'divider_option_action.dart';
export 'turn_into_option_action.dart';
+enum EditorOptionActionType {
+ turnInto,
+ color,
+ align,
+ depth;
+
+ Set<String> get supportTypes {
+ switch (this) {
+ case EditorOptionActionType.turnInto:
+ return {
+ ParagraphBlockKeys.type,
+ HeadingBlockKeys.type,
+ QuoteBlockKeys.type,
+ CalloutBlockKeys.type,
+ BulletedListBlockKeys.type,
+ NumberedListBlockKeys.type,
+ TodoListBlockKeys.type,
+ };
+ case EditorOptionActionType.color:
+ return {
+ ParagraphBlockKeys.type,
+ HeadingBlockKeys.type,
+ BulletedListBlockKeys.type,
+ NumberedListBlockKeys.type,
+ QuoteBlockKeys.type,
+ TodoListBlockKeys.type,
+ CalloutBlockKeys.type,
+ OutlineBlockKeys.type,
+ ToggleListBlockKeys.type,
+ };
+ case EditorOptionActionType.align:
+ return {
+ ImageBlockKeys.type,
+ };
+ case EditorOptionActionType.depth:
+ return {
+ OutlineBlockKeys.type,
+ };
+ }
+ }
+}
+
enum OptionAction {
delete,
duplicate,
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/turn_into_option_action.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/turn_into_option_action.dart
index b213a5ac02..60ccbea800 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/turn_into_option_action.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/option/turn_into_option_action.dart
@@ -1,6 +1,5 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
-import 'package:appflowy/plugins/document/presentation/editor_configuration.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_paste_command.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_paste_command.dart
index b5237c81c0..31b2d7392d 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_paste_command.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_paste_command.dart
@@ -1,8 +1,7 @@
-import 'package:flutter/material.dart';
-
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_notification.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/paste_from_block_link.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';
@@ -12,6 +11,7 @@ import 'package:appflowy/util/default_extensions.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
+import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:string_validator/string_validator.dart';
@@ -51,6 +51,11 @@ CommandShortcutEventHandler _pasteCommandHandler = (editorState) {
Log.info('paste command: plainText: ${plainText?.length}');
Log.info('paste command: image: ${image?.$2?.length}');
+ if (await editorState.pasteAppFlowySharePageLink(plainText)) {
+ Log.info('Pasted block link');
+ return;
+ }
+
// paste as link preview
if (await _pasteAsLinkPreview(editorState, plainText)) {
Log.info('Pasted as link preview');
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_block_link.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_block_link.dart
new file mode 100644
index 0000000000..fbd9914c1d
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_block_link.dart
@@ -0,0 +1,58 @@
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
+import 'package:appflowy/shared/patterns/common_patterns.dart';
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+
+extension PasteFromBlockLink on EditorState {
+ Future<bool> pasteAppFlowySharePageLink(String? sharePageLink) async {
+ if (sharePageLink == null || sharePageLink.isEmpty) {
+ return false;
+ }
+
+ // Check if the link matches the appflowy block link format
+ final match = appflowySharePageLinkRegex.firstMatch(sharePageLink);
+
+ if (match == null) {
+ return false;
+ }
+
+ final workspaceId = match.group(1);
+ final pageId = match.group(2);
+ final blockId = match.group(3);
+
+ if (workspaceId == null || pageId == null) {
+ Log.error(
+ 'Failed to extract information from block link: $sharePageLink',
+ );
+ return false;
+ }
+
+ final selection = this.selection;
+ if (selection == null) {
+ return false;
+ }
+
+ final node = getNodesInSelection(selection).firstOrNull;
+ if (node == null) {
+ return false;
+ }
+
+ // todo: if the current link is not from current workspace.
+ final transaction = this.transaction;
+ transaction.insertText(
+ node,
+ selection.startIndex,
+ MentionBlockKeys.mentionChar,
+ attributes: {
+ MentionBlockKeys.mention: {
+ MentionBlockKeys.type: MentionType.page.name,
+ MentionBlockKeys.blockId: blockId,
+ MentionBlockKeys.pageId: pageId,
+ },
+ },
+ );
+ await apply(transaction);
+
+ return true;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/delta/text_delta_extension.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/delta/text_delta_extension.dart
new file mode 100644
index 0000000000..5beba66c32
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/delta/text_delta_extension.dart
@@ -0,0 +1,46 @@
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+
+typedef MentionPageNameGetter = Future<String> Function(String pageId);
+
+extension TextDeltaExtension on Delta {
+ /// Convert the delta to a text string.
+ ///
+ /// Unlike the [toPlainText], this method will keep the mention text
+ /// such as mentioned page name, mentioned block content.
+ ///
+ /// If the mentioned page or mentioned block not found, it will downgrade to
+ /// the default plain text.
+ Future<String> toText({
+ required MentionPageNameGetter getMentionPageName,
+ }) async {
+ final defaultPlainText = toPlainText();
+
+ String text = '';
+ final ops = iterator;
+ while (ops.moveNext()) {
+ final op = ops.current;
+ final attributes = op.attributes;
+ if (op is TextInsert) {
+ // if the text is '\$', it means the block text is empty,
+ // the real data is in the attributes
+ if (op.text == MentionBlockKeys.mentionChar) {
+ final mention = attributes?[MentionBlockKeys.mention];
+ final mentionPageId = mention?[MentionBlockKeys.pageId];
+ if (mentionPageId != null) {
+ text += await getMentionPageName(mentionPageId);
+ continue;
+ }
+ }
+
+ text += op.text;
+ } else {
+ // if the delta contains other types of operations,
+ // return the default plain text
+ return defaultPlainText;
+ }
+ }
+
+ return text;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/inline_math_equation/inline_math_equation_toolbar_item.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/inline_math_equation/inline_math_equation_toolbar_item.dart
index a66a9ee317..0311d57c08 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/inline_math_equation/inline_math_equation_toolbar_item.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/inline_math_equation/inline_math_equation_toolbar_item.dart
@@ -1,5 +1,6 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
@@ -63,7 +64,7 @@ final ToolbarItem inlineMathEquationItem = ToolbarItem(
node,
selection.startIndex,
selection.length,
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
InlineMathEquationKeys.formula: text,
},
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
index 620bbc4d10..7240030947 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
@@ -1,10 +1,9 @@
-import 'package:flutter/material.dart';
-
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
enum MentionType {
@@ -26,7 +25,7 @@ Node dateMentionNode() {
delta: Delta(
operations: [
TextInsert(
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
@@ -46,11 +45,14 @@ class MentionBlockKeys {
static const mention = 'mention';
static const type = 'type'; // MentionType, String
static const pageId = 'page_id';
+ static const blockId = 'block_id';
// Related to Reminder and Date blocks
static const date = 'date'; // Start Date
static const includeTime = 'include_time';
static const reminderOption = 'reminder_option';
+
+ static const mentionChar = '\$';
}
class MentionBlock extends StatelessWidget {
@@ -78,11 +80,13 @@ class MentionBlock extends StatelessWidget {
if (pageId == null) {
return const SizedBox.shrink();
}
+ final String? blockId = mention[MentionBlockKeys.blockId] as String?;
return MentionPageBlock(
key: ValueKey(pageId),
editorState: editorState,
pageId: pageId,
+ blockId: blockId,
node: node,
textStyle: textStyle,
index: index,
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_bloc.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_bloc.dart
new file mode 100644
index 0000000000..0c198124dc
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_bloc.dart
@@ -0,0 +1,245 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
+import 'package:appflowy/plugins/document/application/document_listener.dart';
+import 'package:appflowy/plugins/document/application/document_service.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/delta/text_delta_extension.dart';
+import 'package:appflowy/workspace/application/view/prelude.dart';
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+import 'package:freezed_annotation/freezed_annotation.dart';
+
+part 'mention_page_bloc.freezed.dart';
+
+typedef MentionPageStatus = (ViewPB? view, bool isInTrash, bool isDeleted);
+
+/// Observer the mentioned page status
+/// Including:
+/// - if view is changed, title, icon
+/// - if view is in trash
+/// - if view is deleted
+/// if the block id is not null
+/// - if block content is changed
+/// - if the block is deleted
+class MentionPageBloc extends Bloc<MentionPageEvent, MentionPageState> {
+ MentionPageBloc({
+ required this.pageId,
+ this.blockId,
+ }) : super(MentionPageState.initial()) {
+ on<MentionPageEvent>((event, emit) async {
+ await event.when(
+ initial: () async {
+ final (view, isInTrash, isDeleted) =
+ await ViewBackendService.getMentionPageStatus(
+ pageId,
+ );
+ final blockContent = await _getBlockContent();
+ emit(
+ state.copyWith(
+ view: view,
+ blockContent: blockContent ?? '',
+ isLoading: false,
+ isInTrash: isInTrash,
+ isDeleted: isDeleted,
+ ),
+ );
+
+ if (view != null) {
+ _startListeningView();
+ _startListeningDocument();
+ }
+ },
+ didUpdateBlockContent: (content) {
+ emit(
+ state.copyWith(
+ blockContent: content,
+ ),
+ );
+ },
+ didUpdateViewStatus: (mentionPageStatus) {
+ emit(
+ state.copyWith(
+ view: mentionPageStatus.$1,
+ isInTrash: mentionPageStatus.$2,
+ isDeleted: mentionPageStatus.$3,
+ ),
+ );
+ },
+ );
+ });
+ }
+
+ @override
+ Future<void> close() {
+ _viewListener?.stop();
+ _documentListener?.stop();
+ return super.close();
+ }
+
+ final String pageId;
+ final String? blockId;
+
+ final _documentService = DocumentService();
+ ViewListener? _viewListener;
+ DocumentListener? _documentListener;
+ BlockPB? _block;
+ String? _blockTextId;
+ Delta? _initialDelta;
+
+ void _startListeningView() {
+ _viewListener = ViewListener(viewId: pageId)
+ ..start(
+ onViewUpdated: (view) {
+ add(
+ MentionPageEvent.didUpdateViewStatus(
+ (view, false, false),
+ ),
+ );
+ },
+ onViewMoveToTrash: (view) {
+ add(
+ MentionPageEvent.didUpdateViewStatus(
+ (state.view, true, false),
+ ),
+ );
+ },
+ onViewDeleted: (view) {
+ add(
+ MentionPageEvent.didUpdateViewStatus(
+ (state.view, false, true),
+ ),
+ );
+ },
+ );
+ }
+
+ Future<String?> _getBlockContent() async {
+ if (blockId == null) {
+ return null;
+ }
+
+ final documentNodeResult = await _documentService.getDocumentNode(
+ documentId: pageId,
+ blockId: blockId!,
+ );
+ final documentNode = documentNodeResult.fold((l) => l, (f) => null);
+ if (documentNode == null) {
+ Log.error(
+ 'unable to get the document node for block $blockId in page $pageId',
+ );
+ return null;
+ }
+
+ final block = documentNode.$2;
+ final node = documentNode.$3;
+
+ _blockTextId = (node.externalValues as ExternalValues?)?.externalId;
+ _initialDelta = node.delta;
+ _block = block;
+
+ return _convertDeltaToText(_initialDelta);
+ }
+
+ void _startListeningDocument() {
+ // only observe the block content if the block id is not null
+ if (blockId == null ||
+ _blockTextId == null ||
+ _initialDelta == null ||
+ _block == null) {
+ return;
+ }
+
+ _documentListener = DocumentListener(id: pageId)
+ ..start(
+ onDocEventUpdate: (docEvent) {
+ for (final block in docEvent.events) {
+ for (final event in block.event) {
+ if (event.id == _blockTextId) {
+ if (event.command == DeltaTypePB.Updated) {
+ _updateBlockContent(event.value);
+ } else if (event.command == DeltaTypePB.Removed) {
+ add(const MentionPageEvent.didUpdateBlockContent(''));
+ }
+ }
+ }
+ }
+ },
+ );
+ }
+
+ Future<void> _updateBlockContent(String deltaJson) async {
+ if (_initialDelta == null || _block == null) {
+ return;
+ }
+
+ try {
+ final incremental = Delta.fromJson(jsonDecode(deltaJson));
+ final delta = _initialDelta!.compose(incremental);
+ final content = await _convertDeltaToText(delta);
+ add(MentionPageEvent.didUpdateBlockContent(content));
+ _initialDelta = delta;
+ } catch (e) {
+ Log.error('failed to update block content: $e');
+ }
+ }
+
+ Future<String> _convertDeltaToText(Delta? delta) async {
+ if (delta == null) {
+ return _initialDelta?.toPlainText() ?? '';
+ }
+
+ return delta.toText(
+ getMentionPageName: (mentionedPageId) async {
+ if (mentionedPageId == pageId) {
+ // if the mention page is the current page, return the view name
+ return state.view?.name ?? '';
+ } else {
+ // if the mention page is not the current page, return the mention page name
+ final viewResult = await ViewBackendService.getView(mentionedPageId);
+ final name = viewResult.fold((l) => l.name, (f) => '');
+ return name;
+ }
+ },
+ );
+ }
+}
+
+@freezed
+class MentionPageEvent with _$MentionPageEvent {
+ const factory MentionPageEvent.initial() = _Initial;
+ const factory MentionPageEvent.didUpdateBlockContent(
+ String content,
+ ) = _DidUpdateBlockContent;
+ const factory MentionPageEvent.didUpdateViewStatus(MentionPageStatus status) =
+ _DidUpdateViewStatus;
+}
+
+@freezed
+class MentionPageState with _$MentionPageState {
+ const factory MentionPageState({
+ required bool isLoading,
+ required bool isInTrash,
+ required bool isDeleted,
+ // non-null case:
+ // - page is found
+ // - page is in trash
+ // null case:
+ // - page is deleted
+ required ViewPB? view,
+ // the plain text content of the block
+ // it doesn't contain any formatting
+ required String blockContent,
+ }) = _MentionPageState;
+
+ factory MentionPageState.initial() => const MentionPageState(
+ isLoading: true,
+ isInTrash: false,
+ isDeleted: false,
+ blockContent: '',
+ view: null,
+ );
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart
index a9d4467124..28e8dc5856 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart
@@ -1,17 +1,15 @@
-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/application/mobile_router.dart';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mobile_page_selector_sheet.dart';
import 'package:appflowy/plugins/trash/application/trash_service.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/view/prelude.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
-import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
show Delta, EditorState, Node, TextInsert, TextTransaction, paragraphNode;
@@ -19,8 +17,8 @@ import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
+import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
-import 'package:provider/provider.dart';
import 'package:universal_platform/universal_platform.dart';
final pageMemorizer = <String, ViewPB?>{};
@@ -30,7 +28,7 @@ Node pageMentionNode(String viewId) {
delta: Delta(
operations: [
TextInsert(
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
@@ -48,6 +46,7 @@ class MentionPageBlock extends StatefulWidget {
super.key,
required this.editorState,
required this.pageId,
+ required this.blockId,
required this.node,
required this.textStyle,
required this.index,
@@ -55,6 +54,7 @@ class MentionPageBlock extends StatefulWidget {
final EditorState editorState;
final String pageId;
+ final String? blockId;
final Node node;
final TextStyle? textStyle;
@@ -67,71 +67,55 @@ class MentionPageBlock extends StatefulWidget {
class _MentionPageBlockState extends State<MentionPageBlock> {
late final EditorState editorState;
- late final ViewListener viewListener = ViewListener(viewId: widget.pageId);
- late Future<ViewPB?> viewPBFuture;
@override
void initState() {
super.initState();
editorState = context.read<EditorState>();
- viewPBFuture = fetchView(widget.pageId);
- viewListener.start(
- onViewUpdated: (p0) {
- pageMemorizer[p0.id] = p0;
- viewPBFuture = fetchView(widget.pageId);
- editorState.reload();
- },
- );
- }
-
- @override
- void dispose() {
- viewListener.stop();
- super.dispose();
}
@override
Widget build(BuildContext context) {
- return FutureBuilder<ViewPB?>(
- initialData: pageMemorizer[widget.pageId],
- future: viewPBFuture,
- builder: (context, state) {
- final view = state.data;
- // memorize the result
- pageMemorizer[widget.pageId] = view;
-
- if (view == null) {
- return _NoAccessMentionPageBlock(
- textStyle: widget.textStyle,
- );
- }
-
- if (UniversalPlatform.isMobile) {
- return _MobileMentionPageBlock(
- view: view,
- textStyle: widget.textStyle,
- handleTap: handleTap,
- handleDoubleTap: handleDoubleTap,
- );
- } else {
- return _DesktopMentionPageBlock(
- view: view,
- textStyle: widget.textStyle,
- handleTap: handleTap,
- );
- }
- },
+ return BlocProvider(
+ create: (context) => MentionPageBloc(
+ pageId: widget.pageId,
+ blockId: widget.blockId,
+ )..add(const MentionPageEvent.initial()),
+ child: BlocBuilder<MentionPageBloc, MentionPageState>(
+ builder: (context, state) {
+ final view = state.view;
+ if (state.isLoading) {
+ return const SizedBox.shrink();
+ }
+
+ if (state.isDeleted || view == null) {
+ return _NoAccessMentionPageBlock(
+ textStyle: widget.textStyle,
+ );
+ }
+
+ if (UniversalPlatform.isMobile) {
+ return _MobileMentionPageBlock(
+ view: view,
+ textStyle: widget.textStyle,
+ handleTap: () => handleTap(view),
+ handleDoubleTap: handleDoubleTap,
+ );
+ } else {
+ return _DesktopMentionPageBlock(
+ view: view,
+ content: state.blockContent,
+ textStyle: widget.textStyle,
+ handleTap: () => handleTap(view),
+ );
+ }
+ },
+ ),
);
}
- Future<void> handleTap() async {
- final view = await fetchView(widget.pageId);
- if (view == null) {
- Log.error('Page(${widget.pageId}) not found');
- return;
- }
-
+ Future<void> handleTap(ViewPB view) async {
if (UniversalPlatform.isMobile && mounted) {
await context.pushView(view);
} else {
@@ -207,34 +191,39 @@ class _MentionPageBlockContent extends StatelessWidget {
const _MentionPageBlockContent({
required this.view,
required this.textStyle,
+ this.content,
});
final ViewPB view;
final TextStyle? textStyle;
+ final String? content;
@override
Widget build(BuildContext context) {
+ final text = _getDisplayText(context, view, content);
final emojiSize = textStyle?.fontSize ?? 12.0;
final iconSize = textStyle?.fontSize ?? 16.0;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
- const HSpace(4),
- view.icon.value.isNotEmpty
- ? FlowyText.emoji(
- view.icon.value,
- fontSize: emojiSize,
- lineHeight: textStyle?.height,
- optimizeEmojiAlign: true,
- )
- : FlowySvg(
- view.layout.icon,
- size: Size.square(iconSize + 2.0),
- ),
+ if (_shouldDisplayViewName(context, view.id, content)) ...[
+ const HSpace(4),
+ view.icon.value.isNotEmpty
+ ? FlowyText.emoji(
+ view.icon.value,
+ fontSize: emojiSize,
+ lineHeight: textStyle?.height,
+ optimizeEmojiAlign: true,
+ )
+ : FlowySvg(
+ view.layout.icon,
+ size: Size.square(iconSize + 2.0),
+ ),
+ ],
const HSpace(2),
FlowyText(
- view.name,
+ text,
decoration: TextDecoration.underline,
fontSize: textStyle?.fontSize,
fontWeight: textStyle?.fontWeight,
@@ -244,6 +233,49 @@ class _MentionPageBlockContent extends StatelessWidget {
],
);
}
+
+ String _getDisplayText(
+ BuildContext context,
+ ViewPB view,
+ String? blockContent,
+ ) {
+ final shouldDisplayViewName = _shouldDisplayViewName(
+ context,
+ view.id,
+ blockContent,
+ );
+
+ if (blockContent == null || blockContent.isEmpty) {
+ return shouldDisplayViewName ? view.name : '';
+ }
+
+ return shouldDisplayViewName
+ ? '${view.name} - $blockContent'
+ : blockContent;
+ }
+
+ // display the view name or not
+ // if the block is from the same doc,
+ // 1. block content is not empty, display the **block content only**.
+ // 2. block content is empty, display the **view name**.
+ // if the block is from another doc,
+ // 1. block content is not empty, display the **view name and block content**.
+ // 2. block content is empty, display the **view name**.
+ bool _shouldDisplayViewName(
+ BuildContext context,
+ String viewId,
+ String? blockContent,
+ ) {
+ if (_isSameDocument(context, viewId)) {
+ return blockContent == null || blockContent.isEmpty;
+ }
+ return true;
+ }
+
+ bool _isSameDocument(BuildContext context, String viewId) {
+ final currentViewId = context.read<DocumentBloc?>()?.documentId;
+ return viewId == currentViewId;
+ }
}
class _NoAccessMentionPageBlock extends StatelessWidget {
@@ -302,10 +334,12 @@ class _DesktopMentionPageBlock extends StatelessWidget {
required this.view,
required this.textStyle,
required this.handleTap,
+ required this.content,
});
final TextStyle? textStyle;
final ViewPB view;
+ final String? content;
final VoidCallback handleTap;
@override
@@ -319,6 +353,7 @@ class _DesktopMentionPageBlock extends StatelessWidget {
cursor: SystemMouseCursors.click,
child: _MentionPageBlockContent(
view: view,
+ content: content,
textStyle: textStyle,
),
),
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/slash_menu_items.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/slash_menu_items.dart
index 1a53c63ca2..b13c7fe282 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/slash_menu_items.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/slash_menu_items.dart
@@ -34,7 +34,7 @@ Future<void> insertDateReference(EditorState editorState) async {
node,
selection.start.offset,
0,
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
diff --git a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/date_reference.dart b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/date_reference.dart
index 6f3bf087a8..904e10d362 100644
--- a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/date_reference.dart
+++ b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/date_reference.dart
@@ -1,5 +1,3 @@
-import 'package:flutter/material.dart';
-
import 'package:appflowy/date/date_service.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/string_extension.dart';
@@ -8,6 +6,7 @@ import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart';
import 'package:appflowy/plugins/inline_actions/service_handler.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
+import 'package:flutter/material.dart';
final _keywords = [
LocaleKeys.inlineActions_date.tr().toLowerCase(),
@@ -122,7 +121,7 @@ class DateReferenceService extends InlineActionsDelegate {
node,
start,
end,
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
diff --git a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/inline_page_reference.dart b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/inline_page_reference.dart
index da7ce92106..7d20ac32a4 100644
--- a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/inline_page_reference.dart
+++ b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/inline_page_reference.dart
@@ -211,7 +211,7 @@ class InlinePageReferenceService extends InlineActionsDelegate {
node,
replace.$1,
replace.$2,
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
diff --git a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/reminder_reference.dart b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/reminder_reference.dart
index c46c3a453d..372cc78698 100644
--- a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/reminder_reference.dart
+++ b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/reminder_reference.dart
@@ -147,7 +147,7 @@ class ReminderReferenceService extends InlineActionsDelegate {
node,
start,
end,
- '\$',
+ MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
diff --git a/frontend/appflowy_flutter/lib/shared/patterns/common_patterns.dart b/frontend/appflowy_flutter/lib/shared/patterns/common_patterns.dart
index fb9cd9f226..b459e04f0f 100644
--- a/frontend/appflowy_flutter/lib/shared/patterns/common_patterns.dart
+++ b/frontend/appflowy_flutter/lib/shared/patterns/common_patterns.dart
@@ -35,3 +35,7 @@ final camelCaseRegex = RegExp(_camelCasePattern);
const _macOSVolumesPattern = '^/Volumes/[^/]+';
final macOSVolumesRegex = RegExp(_macOSVolumesPattern);
+
+const _appflowySharePageLinkPattern =
+ r'^https://appflowy\.com/app/([^/]+)/([^?]+)(?:\?blockId=(.+))?$';
+final appflowySharePageLinkRegex = RegExp(_appflowySharePageLinkPattern);
diff --git a/frontend/appflowy_flutter/lib/workspace/application/view/view_service.dart b/frontend/appflowy_flutter/lib/workspace/application/view/view_service.dart
index ea5756d780..a8665135b1 100644
--- a/frontend/appflowy_flutter/lib/workspace/application/view/view_service.dart
+++ b/frontend/appflowy_flutter/lib/workspace/application/view/view_service.dart
@@ -1,9 +1,12 @@
import 'dart:async';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_bloc.dart';
+import 'package:appflowy/plugins/trash/application/trash_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
+import 'package:collection/collection.dart';
class ViewBackendService {
static Future<FlowyResult<ViewPB, FlowyError>> createView({
@@ -259,6 +262,33 @@ class ViewBackendService {
return FolderEventGetView(payload).send();
}
+ static Future<MentionPageStatus> getMentionPageStatus(String pageId) async {
+ final view = await ViewBackendService.getView(pageId).then(
+ (value) => value.toNullable(),
+ );
+
+ // found the page
+ if (view != null) {
+ return (view, false, false);
+ }
+
+ // if the view is not found, try to fetch from trash
+ final trashViews = await TrashService().readTrash();
+ final trash = trashViews.fold(
+ (l) => l.items.firstWhereOrNull((element) => element.id == pageId),
+ (r) => null,
+ );
+ if (trash != null) {
+ final trashView = ViewPB()
+ ..id = trash.id
+ ..name = trash.name;
+ return (trashView, true, false);
+ }
+
+ // the page was deleted
+ return (null, false, true);
+ }
+
static Future<FlowyResult<RepeatedViewPB, FlowyError>> getViewAncestors(
String viewId,
) async {
diff --git a/frontend/appflowy_flutter/test/unit_test/document/turn_into/turn_into_test.dart b/frontend/appflowy_flutter/test/unit_test/document/turn_into/turn_into_test.dart
index 9383bb1cb7..f944a62470 100644
--- a/frontend/appflowy_flutter/test/unit_test/document/turn_into/turn_into_test.dart
+++ b/frontend/appflowy_flutter/test/unit_test/document/turn_into/turn_into_test.dart
@@ -1,4 +1,3 @@
-import 'package:appflowy/plugins/document/presentation/editor_configuration.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_backend/log.dart';