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.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
feat: inline sub page mention (#6567)
Mathias Mogensen068500df849b
diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dartnew file mode 100644index 0000000000..51942a96f6--- /dev/null+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dart@@ -0,0 +1,378 @@+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/mention/mention_page_block.dart';+import 'package:appflowy/workspace/presentation/home/menu/view/view_action_type.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flutter/services.dart';++import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import '../../shared/keyboard.dart';+import '../../shared/util.dart';+import '../board/board_hide_groups_test.dart';++const _firstDocName = "Inline Sub Page Mention";+const _createdPageName = "hi world";++// Test cases that are covered in this file:+// - [x] Insert sub page mention from action menu (+)+// - [x] Delete sub page mention from editor+// - [x] Delete page from sidebar+// - [x] Delete page from sidebar and then trash+// - [x] Undo delete sub page mention+// - [x] Cut+paste in same document+// - [x] Cut+paste in different document+// - [x] Cut+paste in same document and then paste again in same document+// - [x] Turn paragraph with sub page mention into a heading+// - [x] Turn heading with sub page mention into a paragraph+// - [x] Duplicate a Block containing two sub page mentions++void main() {+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ group('document inline sub-page mention tests:', () {+ testWidgets('Insert (& delete) a sub page mention from action menu',+ (tester) async {+ await tester.initializeAppFlowy();+ await tester.tapAnonymousSignInButton();+ await tester.createOpenRenameDocumentUnderParent(name: _firstDocName);++ await tester.insertInlineSubPageFromPlusMenu();++ await tester.expandOrCollapsePage(+ pageName: _firstDocName,+ layout: ViewLayoutPB.Document,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ // Delete from editor+ await tester.editor.updateSelection(+ Selection.collapsed(Position(path: [0], offset: 1)),+ );++ await tester.simulateKeyEvent(LogicalKeyboardKey.backspace);+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNothing);+ expect(find.byType(MentionSubPageBlock), findsNothing);++ // Undo+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyZ,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);++ // Move to trash (delete from sidebar)+ await tester.rightClickOnPageName(_createdPageName);+ await tester.tapButtonWithName(ViewMoreActionType.delete.name);+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsOneWidget);+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(+ find.text(LocaleKeys.document_mention_trashHint.tr()),+ findsOneWidget,+ );++ // Delete from trash+ await tester.tapTrashButton();+ await tester.pumpAndSettle();++ await tester.tap(find.text(LocaleKeys.trash_deleteAll.tr()));+ await tester.pumpAndSettle();++ await tester.tap(find.text(LocaleKeys.button_delete.tr()));+ await tester.pumpAndSettle();++ await tester.openPage(_firstDocName);+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNothing);+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(+ find.text(LocaleKeys.document_mention_deletedPage.tr()),+ findsOneWidget,+ );+ });++ testWidgets(+ 'Cut+paste in same document and cut+paste in different document',+ (tester) async {+ await tester.initializeAppFlowy();+ await tester.tapAnonymousSignInButton();+ await tester.createOpenRenameDocumentUnderParent(name: _firstDocName);++ await tester.insertInlineSubPageFromPlusMenu();++ await tester.expandOrCollapsePage(+ pageName: _firstDocName,+ layout: ViewLayoutPB.Document,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ // Cut from editor+ await tester.editor.updateSelection(+ Selection.collapsed(Position(path: [0], offset: 1)),+ );+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyX,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNothing);+ expect(find.byType(MentionSubPageBlock), findsNothing);++ // Paste in same document+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyV,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ // Cut again+ await tester.editor.updateSelection(+ Selection.collapsed(Position(path: [0], offset: 1)),+ );+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyX,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ // Create another document+ const anotherDocName = "Another Document";+ await tester.createOpenRenameDocumentUnderParent(+ name: anotherDocName,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNothing);+ expect(find.byType(MentionSubPageBlock), findsNothing);++ await tester.editor.tapLineOfEditorAt(0);+ await tester.pumpAndSettle();++ // Paste in document+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyV,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpUntilFound(find.byType(MentionSubPageBlock));+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsOneWidget);++ await tester.expandOrCollapsePage(+ pageName: anotherDocName,+ layout: ViewLayoutPB.Document,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);+ });+ testWidgets(+ 'Cut+paste in same docuemnt and then paste again in same document',+ (tester) async {+ await tester.initializeAppFlowy();+ await tester.tapAnonymousSignInButton();+ await tester.createOpenRenameDocumentUnderParent(name: _firstDocName);++ await tester.insertInlineSubPageFromPlusMenu();++ await tester.expandOrCollapsePage(+ pageName: _firstDocName,+ layout: ViewLayoutPB.Document,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ // Cut from editor+ await tester.editor.updateSelection(+ Selection.collapsed(Position(path: [0], offset: 1)),+ );+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyX,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNothing);+ expect(find.byType(MentionSubPageBlock), findsNothing);++ // Paste in same document+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyV,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ // Paste again+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyV,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle(const Duration(seconds: 2));++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsNWidgets(2));+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsNWidgets(2));+ expect(find.text('$_createdPageName (copy)'), findsNWidgets(2));+ });++ testWidgets('Turn into w/ sub page mentions', (tester) async {+ await tester.initializeAppFlowy();+ await tester.tapAnonymousSignInButton();+ await tester.createOpenRenameDocumentUnderParent(name: _firstDocName);++ await tester.insertInlineSubPageFromPlusMenu();++ await tester.expandOrCollapsePage(+ pageName: _firstDocName,+ layout: ViewLayoutPB.Document,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ final headingText = LocaleKeys.document_slashMenu_name_heading1.tr();+ final paragraphText = LocaleKeys.document_slashMenu_name_text.tr();++ // Turn into heading+ await tester.editor.openTurnIntoMenu([0]);+ await tester.tapButton(find.findTextInFlowyText(headingText));+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);++ // Turn into paragraph+ await tester.editor.openTurnIntoMenu([0]);+ await tester.tapButton(find.findTextInFlowyText(paragraphText));+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsNWidgets(2));+ expect(find.byType(MentionSubPageBlock), findsOneWidget);+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsOneWidget);+ });++ testWidgets('Duplicate a block containing two sub page mentions',+ (tester) async {+ await tester.initializeAppFlowy();+ await tester.tapAnonymousSignInButton();+ await tester.createOpenRenameDocumentUnderParent(name: _firstDocName);++ await tester.insertInlineSubPageFromPlusMenu();++ // Copy paste it+ await tester.editor.updateSelection(+ Selection(+ start: Position(path: [0]),+ end: Position(path: [0], offset: 1),+ ),+ );+ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyC,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ await tester.editor.updateSelection(+ Selection.collapsed(Position(path: [0], offset: 1)),+ );++ await tester.simulateKeyEvent(+ LogicalKeyboardKey.keyV,+ isControlPressed: Platform.isLinux || Platform.isWindows,+ isMetaPressed: Platform.isMacOS,+ );+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsOneWidget);+ expect(find.text("$_createdPageName (copy)"), findsOneWidget);+ expect(find.byType(MentionSubPageBlock), findsNWidgets(2));+ expect(find.byFlowySvg(FlowySvgs.child_page_s), findsNWidgets(2));++ // Duplicate node from block action menu+ await tester.editor.hoverAndClickOptionMenuButton([0]);+ await tester.tapButtonWithName(LocaleKeys.button_duplicate.tr());+ await tester.pumpAndSettle();++ expect(find.text(_createdPageName), findsOneWidget);+ expect(find.text("$_createdPageName (copy)"), findsNWidgets(2));+ expect(find.text("$_createdPageName (copy) (copy)"), findsOneWidget);+ });+ });+}++extension _InlineSubPageTestHelper on WidgetTester {+ Future<void> insertInlineSubPageFromPlusMenu() async {+ await editor.tapLineOfEditorAt(0);++ await editor.showPlusMenu();++ // Workaround to allow typing a document name+ await FlowyTestKeyboard.simulateKeyDownEvent(+ tester: this,+ withKeyUp: true,+ [+ LogicalKeyboardKey.keyH,+ LogicalKeyboardKey.keyI,+ LogicalKeyboardKey.space,+ LogicalKeyboardKey.keyW,+ LogicalKeyboardKey.keyO,+ LogicalKeyboardKey.keyR,+ LogicalKeyboardKey.keyL,+ LogicalKeyboardKey.keyD,+ ],+ );++ await FlowyTestKeyboard.simulateKeyDownEvent(+ tester: this,+ withKeyUp: true,+ [LogicalKeyboardKey.enter],+ );+ await pumpUntilFound(find.byType(MentionSubPageBlock));+ }+}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.dartindex fc295709dd..2178b8346e 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@@ -6,6 +6,7 @@ import 'document_option_action_test.dart' as document_option_action_test;import 'document_title_test.dart' as document_title_test;import 'document_with_date_reminder_test.dart'as document_with_date_reminder_test;+import 'document_inline_sub_page_test.dart' as document_inline_sub_page_test;void main() {IntegrationTestWidgetsFlutterBinding.ensureInitialized();@@ -18,4 +19,5 @@ void main() {document_with_date_reminder_test.main();document_deletion_test.main();document_option_action_test.main();+ document_inline_sub_page_test.main();}diff --git a/frontend/appflowy_flutter/integration_test/shared/common_operations.dart b/frontend/appflowy_flutter/integration_test/shared/common_operations.dartindex bb99d10f77..3f8fb870f5 100644--- a/frontend/appflowy_flutter/integration_test/shared/common_operations.dart+++ b/frontend/appflowy_flutter/integration_test/shared/common_operations.dart@@ -8,6 +8,7 @@ import 'package:appflowy/mobile/presentation/presentation.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/base/emoji_picker_button.dart';import 'package:appflowy/plugins/shared/share/share_button.dart';import 'package:appflowy/shared/feature_flags.dart';+import 'package:appflowy/shared/text_field/text_filed_with_metric_lines.dart';import 'package:appflowy/startup/startup.dart';import 'package:appflowy/user/presentation/screens/screens.dart';import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart';@@ -186,6 +187,16 @@ extension CommonOperations on WidgetTester {}}+ /// Right click on the page name.+ Future<void> rightClickOnPageName(+ String name, {+ ViewLayoutPB layout = ViewLayoutPB.Document,+ }) async {+ final page = findPageName(name, layout: layout);+ await tap(page, buttons: kSecondaryMouseButton);+ await pumpAndSettle();+ }+/// open the page with given name.Future<void> openPage(String name, {@@ -354,6 +365,32 @@ extension CommonOperations on WidgetTester {}}+ Future<void> createOpenRenameDocumentUnderParent({+ required String name,+ String? parentName,+ }) async {+ // create a new page+ await tapAddViewButton(name: parentName ?? gettingStarted);+ await tapButtonWithName(ViewLayoutPB.Document.menuName);+ final settingsOrFailure = await getIt<KeyValueStorage>().getWithFormat(+ KVKeys.showRenameDialogWhenCreatingNewFile,+ (value) => bool.parse(value),+ );+ final showRenameDialog = settingsOrFailure ?? false;+ if (showRenameDialog) {+ await tapOKButton();+ }+ await pumpAndSettle();++ // open the page after created+ await openPage(ViewLayoutPB.Document.defaultName);+ await pumpAndSettle();++ // Enter new name in the document title+ await enterText(find.byType(TextFieldWithMetricLines), name);+ await pumpAndSettle();+ }+/// Create a new page in the spaceFuture<void> createNewPageInSpace({required String spaceName,diff --git a/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart b/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dartindex de27a264af..491ac9432c 100644--- a/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart+++ b/frontend/appflowy_flutter/integration_test/shared/document_test_operations.dart@@ -197,6 +197,11 @@ class EditorOperations {await tester.ime.insertCharacter('@');}+ /// trigger the plus action menu (+) command+ Future<void> showPlusMenu() async {+ await tester.ime.insertCharacter('+');+ }+/// Tap the slash menu item with [name]////// Must call [showSlashMenu] first.diff --git a/frontend/appflowy_flutter/lib/plugins/document/document_page.dart b/frontend/appflowy_flutter/lib/plugins/document/document_page.dartindex 40c8235cf2..aa73148fc8 100644--- a/frontend/appflowy_flutter/lib/plugins/document/document_page.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/document_page.dart@@ -1,15 +1,13 @@-import 'dart:async';-import 'package:appflowy/mobile/application/page_style/document_page_style_bloc.dart';import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';import 'package:appflowy/plugins/document/application/document_bloc.dart';import 'package:appflowy/plugins/document/presentation/banner.dart';import 'package:appflowy/plugins/document/presentation/editor_drop_handler.dart';-import 'package:appflowy/plugins/document/presentation/editor_notification.dart';import 'package:appflowy/plugins/document/presentation/editor_page.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/cover/document_immersive_cover.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/shared_context/shared_context.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_service.dart';import 'package:appflowy/plugins/document/presentation/editor_style.dart';import 'package:appflowy/shared/flowy_error_page.dart';import 'package:appflowy/startup/startup.dart';@@ -50,25 +48,16 @@ class _DocumentPageState extends State<DocumentPage>late final documentBloc = DocumentBloc(documentId: widget.view.id)..add(const DocumentEvent.initial());- StreamSubscription<(TransactionTime, Transaction)>? transactionSubscription;-- bool isUndoRedo = false;- bool isPaste = false;- bool isDraggingNode = false;-@overridevoid initState() {super.initState();WidgetsBinding.instance.addObserver(this);- EditorNotification.addListener(onEditorNotification);}@overridevoid dispose() {- EditorNotification.removeListener(onEditorNotification);WidgetsBinding.instance.removeObserver(this);documentBloc.close();- transactionSubscription?.cancel();super.dispose();}@@ -109,8 +98,6 @@ class _DocumentPageState extends State<DocumentPage>return const SizedBox.shrink();}- editorState.transactionStream.listen(onEditorTransaction);-return BlocListener<ActionNavigationBloc, ActionNavigationState>(listenWhen: (_, curr) => curr.action != null,listener: onNotificationAction,@@ -170,11 +157,15 @@ class _DocumentPageState extends State<DocumentPage>return Provider(create: (_) => SharedEditorContext(),- child: Column(- children: [- if (state.isDeleted) buildBanner(context),- Expanded(child: child),- ],+ child: EditorTransactionService(+ viewId: widget.view.id,+ editorState: state.editorState!,+ child: Column(+ children: [+ if (state.isDeleted) buildBanner(context),+ Expanded(child: child),+ ],+ ),),);}@@ -217,33 +208,6 @@ class _DocumentPageState extends State<DocumentPage>);}- void onEditorNotification(EditorNotificationType type) {- final editorState = this.editorState;- if (editorState == null) {- return;- }-- if ([EditorNotificationType.undo, EditorNotificationType.redo]- .contains(type)) {- isUndoRedo = true;- } else if (type == EditorNotificationType.paste) {- isPaste = true;- } else if (type == EditorNotificationType.dragStart) {- isDraggingNode = true;- } else if (type == EditorNotificationType.dragEnd) {- isDraggingNode = false;- }-- if (type == EditorNotificationType.undo) {- undoCommand.execute(editorState);- } else if (type == EditorNotificationType.redo) {- redoCommand.execute(editorState);- } else if (type == EditorNotificationType.exitEditing &&- editorState.selection != null) {- editorState.selection = null;- }- }-void onNotificationAction(BuildContext context,ActionNavigationState state,@@ -325,88 +289,6 @@ class _DocumentPageState extends State<DocumentPage>return false;}- List<Node> collectMatchingNodes(Node node, String type) {- final List<Node> matchingNodes = [];- if (node.type == type) {- matchingNodes.add(node);- }-- for (final child in node.children) {- matchingNodes.addAll(collectMatchingNodes(child, type));- }-- return matchingNodes;- }-- void onEditorTransaction((TransactionTime, Transaction) event) {- if (editorState == null || event.$1 == TransactionTime.before) {- return;- }-- final Map<String, List<Node>> addedNodes = {- for (final handler in SharedEditorContext.transactionHandlers)- handler.blockType: [],- };- final Map<String, List<Node>> removedNodes = {- for (final handler in SharedEditorContext.transactionHandlers)- handler.blockType: [],- };-- final transactionHandlerTypes = SharedEditorContext.transactionHandlers- .map((h) => h.blockType)- .toList();-- // Collect all matching nodes in a performant way for each handler type.- for (final op in event.$2.operations) {- if (op is InsertOperation) {- for (final n in op.nodes) {- for (final handlerType in transactionHandlerTypes) {- if (n.type == handlerType) {- addedNodes[handlerType]!- .addAll(collectMatchingNodes(n, handlerType));- }- }- }- } else if (op is DeleteOperation) {- for (final n in op.nodes) {- for (final handlerType in transactionHandlerTypes) {- if (n.type == handlerType) {- removedNodes[handlerType]!- .addAll(collectMatchingNodes(n, handlerType));- }- }- }- }- }-- if (removedNodes.isEmpty && addedNodes.isEmpty) {- return;- }-- for (final handler in SharedEditorContext.transactionHandlers) {- final added = addedNodes[handler.blockType] ?? [];- final removed = removedNodes[handler.blockType] ?? [];-- if (added.isEmpty && removed.isEmpty) {- continue;- }-- handler.onTransaction(- context,- editorState!,- added,- removed,- isUndoRedo: isUndoRedo,- isPaste: isPaste,- isDraggingNode: isDraggingNode,- parentViewId: widget.view.id,- );-- isUndoRedo = false;- isPaste = false;- }- }-Selection? _calculateInitialSelection(EditorState editorState) {if (widget.initialSelection != null) {return widget.initialSelection;diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dartindex 13a4388c1f..83a9775068 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart@@ -6,10 +6,12 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/backgroundimport 'package:appflowy/plugins/document/presentation/editor_plugins/i18n/editor_i18n.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';import 'package:appflowy/plugins/document/presentation/editor_style.dart';+import 'package:appflowy/plugins/inline_actions/handlers/child_page.dart';import 'package:appflowy/plugins/inline_actions/handlers/date_reference.dart';import 'package:appflowy/plugins/inline_actions/handlers/inline_page_reference.dart';import 'package:appflowy/plugins/inline_actions/handlers/reminder_reference.dart';import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart';+import 'package:appflowy/shared/feature_flags.dart';import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';import 'package:appflowy/workspace/application/settings/shortcuts/settings_shortcuts_service.dart';import 'package:appflowy/workspace/application/view_info/view_info_bloc.dart';@@ -64,6 +66,8 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>late final InlineActionsService inlineActionsService = InlineActionsService(context: context,handlers: [+ if (FeatureFlag.inlineSubPageMention.isOn)+ InlineChildPageService(currentViewId: documentBloc.documentId),InlinePageReferenceService(currentViewId: documentBloc.documentId),DateReferenceService(context),ReminderReferenceService(context),@@ -276,10 +280,12 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>context.read<AppearanceSettingsCubit>().state.enableRtlToolbarItems,);+ final isViewDeleted = context.read<DocumentBloc>().state.isDeleted;final editor = Directionality(textDirection: textDirection,child: AppFlowyEditor(editorState: widget.editorState,+ editable: !isViewDeleted,editorScrollController: editorScrollController,// setup the auto focus parametersautoFocus: widget.autoFocus ?? autoFocus,@@ -317,6 +323,10 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>),);+ if (isViewDeleted) {+ return editor;+ }+final editorState = widget.editorState;if (UniversalPlatform.isMobile) {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.dartindex 263d750e7a..c047ff6f70 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@@ -1,10 +1,9 @@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/plugins.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/sub_page/sub_page_block_component.dart';import 'package:appflowy/plugins/shared/share/constants.dart';import 'package:appflowy/startup/startup.dart';-import 'package:appflowy/workspace/application/view/prelude.dart';import 'package:appflowy_backend/dispatch/dispatch.dart';import 'package:appflowy_backend/log.dart';import 'package:appflowy_editor/appflowy_editor.dart';@@ -29,6 +28,8 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {break;case OptionAction.duplicate:await _duplicateBlock(transaction, node);+ EditorNotification.paste().post();+break;case OptionAction.moveUp:transaction.moveNode(node.path.previous, node);@@ -64,18 +65,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {Log.error('Block type $type is not valid');}- Node newNode = _copyBlock(node);-- if (node.type == SubPageBlockKeys.type) {- final viewId = await _handleDuplicateSubPage(node);- if (viewId == null) {- return;- }-- newNode = newNode.copyWith(attributes: {SubPageBlockKeys.viewId: viewId});- }-- transaction.insertNode(node.path.next, newNode);+ transaction.insertNode(node.path.next, _copyBlock(node));}Node _copyBlock(Node node) {@@ -175,35 +165,6 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {emit(BlockActionOptionState()); // Emit a new state to trigger UI update}- Future<String?> _handleDuplicateSubPage(Node node) async {- final viewId = node.attributes[SubPageBlockKeys.viewId];- if (viewId == null) {- return null;- }-- final view = (await ViewBackendService.getView(viewId)).toNullable();- if (view == null) {- return null;- }-- final result = await ViewBackendService.duplicate(- view: view,- openAfterDuplicate: false,- includeChildren: true,- parentViewId: view.parentViewId,- syncAfterDuplicate: true,- );-- return result.fold(- (view) => view.id,- (error) {- Log.error(error);- emit(BlockActionOptionState()); // Emit a new state to trigger UI update- return null;- },- );- }-Future<bool> turnIntoBlock(String type,Node node, {diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/page_reference_commands.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/page_reference_commands.dartindex 032aa3f653..e42bb3a2bf 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/page_reference_commands.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/page_reference_commands.dart@@ -1,7 +1,9 @@+import 'package:appflowy/plugins/inline_actions/handlers/child_page.dart';import 'package:appflowy/plugins/inline_actions/handlers/inline_page_reference.dart';import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart';import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart';import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart';+import 'package:appflowy/shared/feature_flags.dart';import 'package:appflowy_editor/appflowy_editor.dart';import 'package:flutter/material.dart';import 'package:universal_platform/universal_platform.dart';@@ -87,6 +89,8 @@ Future<bool> inlinePageReferenceCommandHandler(final service = InlineActionsService(context: context,handlers: [+ if (FeatureFlag.inlineSubPageMention.isOn)+ InlineChildPageService(currentViewId: currentViewId),InlinePageReferenceService(currentViewId: currentViewId,limitResults: 10,diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_cut_command.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_cut_command.dartindex 2d62ea4d3f..b5d20a3ec0 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_cut_command.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/custom_cut_command.dart@@ -1,7 +1,9 @@import 'package:flutter/material.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';+import 'package:appflowy/shared/clipboard_state.dart';import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:provider/provider.dart';/// cut.///@@ -24,6 +26,13 @@ CommandShortcutEventHandler _cutCommandHandler = (editorState) {return KeyEventResult.ignored;}+ final context = editorState.document.root.context;+ if (context == null || !context.mounted) {+ return KeyEventResult.ignored;+ }++ context.read<ClipboardState>().didCut();+handleCopyCommand(editorState, isCut: true);if (!selection.isCollapsed) {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.dartindex 31b2d7392d..38fd8dee63 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@@ -6,6 +6,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_pimport '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/shared/clipboard_state.dart';import 'package:appflowy/startup/startup.dart';import 'package:appflowy/util/default_extensions.dart';import 'package:appflowy_backend/log.dart';@@ -29,95 +30,96 @@ final CommandShortcutEvent customPasteCommand = CommandShortcutEvent();CommandShortcutEventHandler _pasteCommandHandler = (editorState) {+ doPaste(editorState).then((_) {+ final context = editorState.document.root.context;+ if (context != null && context.mounted) {+ context.read<ClipboardState>().didPaste();+ }+ });++ return KeyEventResult.handled;+};++Future<void> doPaste(EditorState editorState) async {final selection = editorState.selection;if (selection == null) {- return KeyEventResult.ignored;+ return;}- // because the event handler is not async, so we need to use wrap the async function here- () async {- EditorNotification.paste().post();-- // 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;-- // dump the length of the data here, don't log the data itself for privacy concerns- Log.info('paste command: inAppJson: ${inAppJson?.length}');- Log.info('paste command: html: ${html?.length}');- 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;- }+ EditorNotification.paste().post();- // paste as link preview- if (await _pasteAsLinkPreview(editorState, plainText)) {- Log.info('Pasted as link preview');- return;- }+ // 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;++ // dump the length of the data here, don't log the data itself for privacy concerns+ Log.info('paste command: inAppJson: ${inAppJson?.length}');+ Log.info('paste command: html: ${html?.length}');+ Log.info('paste command: plainText: ${plainText?.length}');+ Log.info('paste command: image: ${image?.$2?.length}');++ if (await editorState.pasteAppFlowySharePageLink(plainText)) {+ return Log.info('Pasted block link');+ }- // 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) {- if (await editorState.pasteInAppJson(inAppJson)) {- Log.info('Pasted in app json');- return;- }+ // paste as link preview+ if (await _pasteAsLinkPreview(editorState, plainText)) {+ return Log.info('Pasted as link preview');+ }++ // 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) {+ if (await editorState.pasteInAppJson(inAppJson)) {+ return Log.info('Pasted in app json');}+ }- // if the image data is not null, we should handle it first- // because the image URL in the HTML may not be reachable due to permission issues- // For example, when pasting an image from Slack, the image URL provided is not public.- if (image != null && image.$2?.isNotEmpty == true) {- final documentBloc =- editorState.document.root.context?.read<DocumentBloc>();- final documentId = documentBloc?.documentId;- if (documentId == null || documentId.isEmpty) {- return;- }- await editorState.deleteSelectionIfNeeded();- final result = await editorState.pasteImage(- image.$1,- image.$2!,- documentId,- selection: selection,- );- if (result) {- Log.info('Pasted image');- return;- }+ // if the image data is not null, we should handle it first+ // because the image URL in the HTML may not be reachable due to permission issues+ // For example, when pasting an image from Slack, the image URL provided is not public.+ if (image != null && image.$2?.isNotEmpty == true) {+ final documentBloc =+ editorState.document.root.context?.read<DocumentBloc>();+ final documentId = documentBloc?.documentId;+ if (documentId == null || documentId.isEmpty) {+ return;}- if (html != null && html.isNotEmpty) {- await editorState.deleteSelectionIfNeeded();- if (await editorState.pasteHtml(html)) {- Log.info('Pasted html');- return;- }+ await editorState.deleteSelectionIfNeeded();+ final result = await editorState.pasteImage(+ image.$1,+ image.$2!,+ documentId,+ selection: selection,+ );+ if (result) {+ return Log.info('Pasted image');}+ }- if (plainText != null && plainText.isNotEmpty) {- Log.info('Pasted plain text');- await editorState.pastePlainText(plainText);- return;+ if (html != null && html.isNotEmpty) {+ await editorState.deleteSelectionIfNeeded();+ if (await editorState.pasteHtml(html)) {+ return Log.info('Pasted html');}+ }- Log.info('unable to parse the clipboard content');- }();+ if (plainText != null && plainText.isNotEmpty) {+ await editorState.pastePlainText(plainText);+ return Log.info('Pasted plain text');+ }- return KeyEventResult.handled;-};+ return Log.info('unable to parse the clipboard content');+}Future<bool> _pasteAsLinkPreview(EditorState editorState,diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/header/cover_title.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/header/cover_title.dartindex bbb58b532c..d533dd5343 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/header/cover_title.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/header/cover_title.dart@@ -124,6 +124,7 @@ class _InnerCoverTitleState extends State<_InnerCoverTitle> {),child: TextFieldWithMetricLines(controller: titleTextController,+ enabled: editorState.editable,focusNode: titleFocusNode,style: fontStyle,onLineCountChange: (count) => lineCount = count,diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/child_page_transaction_handler.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/child_page_transaction_handler.dartnew file mode 100644index 0000000000..b2a47bae37--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/child_page_transaction_handler.dart@@ -0,0 +1,230 @@+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/transaction_handler/editor_transaction_handler.dart';+import 'package:appflowy/plugins/trash/application/trash_service.dart';+import 'package:appflowy/shared/clipboard_state.dart';+import 'package:appflowy/workspace/application/view/view_service.dart';+import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';+import 'package:appflowy_backend/log.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flowy_infra_ui/style_widget/snap_bar.dart';+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';++/// The data used to handle transactions for mentions.+///+/// [Node] is the block node.+/// [Map] is the data of the mention block.+/// [int] is the index of the mention block in the list of deltas (after transaction apply).+///+typedef MentionBlockData = (Node, Map<String, dynamic>, int);++const _pasteIdentifier = 'child_page_transaction';++class ChildPageTransactionHandler+ extends EditorTransactionHandler<MentionBlockData> {+ ChildPageTransactionHandler()+ : super(type: MentionBlockKeys.mention, livesInDelta: true);++ @override+ Future<void> onTransaction(+ BuildContext context,+ EditorState editorState,+ List<MentionBlockData> added,+ List<MentionBlockData> removed, {+ bool isCut = false,+ bool isUndoRedo = false,+ bool isPaste = false,+ bool isDraggingNode = false,+ String? parentViewId,+ }) async {+ if (isDraggingNode) {+ return;+ }++ // Remove the mentions that were both added and removed in the same transaction.+ // These were just moved around.+ final moved = <MentionBlockData>[];+ for (final mention in added) {+ if (removed.any((r) => r.$2 == mention.$2)) {+ moved.add(mention);+ }+ }++ for (final mention in removed) {+ if (!context.mounted || moved.any((m) => m.$2 == mention.$2)) {+ return;+ }++ if (mention.$2[MentionBlockKeys.type] != MentionType.childPage.name) {+ continue;+ }++ await _handleDeletion(context, mention);+ }++ if (isPaste || isUndoRedo) {+ if (context.mounted) {+ context.read<ClipboardState>().startHandlingPaste(_pasteIdentifier);+ }++ for (final mention in added) {+ if (!context.mounted || moved.any((m) => m.$2 == mention.$2)) {+ return;+ }++ if (mention.$2[MentionBlockKeys.type] != MentionType.childPage.name) {+ continue;+ }++ await _handleAddition(+ context,+ editorState,+ mention,+ isPaste,+ parentViewId,+ isCut,+ );+ }++ if (context.mounted) {+ context.read<ClipboardState>().endHandlingPaste(_pasteIdentifier);+ }+ }+ }++ Future<void> _handleDeletion(+ BuildContext context,+ MentionBlockData data,+ ) async {+ final viewId = data.$2[MentionBlockKeys.pageId];++ final result = await ViewBackendService.deleteView(viewId: viewId);+ result.fold(+ (_) {},+ (error) {+ Log.error(error);+ if (context.mounted) {+ showToastNotification(+ context,+ message: LocaleKeys.document_plugins_subPage_errors_failedDeletePage+ .tr(),+ );+ }+ },+ );+ }++ Future<void> _handleAddition(+ BuildContext context,+ EditorState editorState,+ MentionBlockData data,+ bool isPaste,+ String? parentViewId,+ bool isCut,+ ) async {+ if (parentViewId == null) {+ return;+ }++ final viewId = data.$2[MentionBlockKeys.pageId];+ if (isPaste && !isCut) {+ _handlePasteFromCopy(+ context,+ editorState,+ data.$1,+ data.$3,+ viewId,+ parentViewId,+ );+ } else {+ _handlePasteFromCut(viewId, parentViewId);+ }+ }++ void _handlePasteFromCut(String viewId, String parentViewId) async {+ // Attempt to restore from Trash just in case+ await TrashService.putback(viewId);++ final view = (await ViewBackendService.getView(viewId)).toNullable();+ if (view == null) {+ return Log.error('View not found: $viewId');+ }++ if (view.parentViewId == parentViewId) {+ return;+ }++ await ViewBackendService.moveViewV2(+ viewId: viewId,+ newParentId: parentViewId,+ prevViewId: null,+ );+ }++ void _handlePasteFromCopy(+ BuildContext context,+ EditorState editorState,+ Node node,+ int index,+ String viewId,+ String parentViewId,+ ) async {+ final view = (await ViewBackendService.getView(viewId)).toNullable();+ if (view == null) {+ return Log.error('View not found: $viewId');+ }++ final duplicatedViewOrFailure = await ViewBackendService.duplicate(+ view: view,+ openAfterDuplicate: false,+ includeChildren: true,+ syncAfterDuplicate: true,+ parentViewId: parentViewId,+ );++ await duplicatedViewOrFailure.fold(+ (newView) async {+ final newMentionAttributes = {+ MentionBlockKeys.mention: {+ MentionBlockKeys.type: MentionType.childPage.name,+ MentionBlockKeys.pageId: newView.id,+ },+ };++ // The index is the index of the delta, to get the index of the mention character+ // in all the text, we need to calculate it based on the deltas before the current delta.+ int mentionIndex = 0;+ for (final (i, delta) in node.delta!.indexed) {+ if (i >= index) {+ break;+ }++ mentionIndex += delta.length;+ }++ final transaction = editorState.transaction;+ transaction.formatText(+ node,+ mentionIndex,+ MentionBlockKeys.mentionChar.length,+ newMentionAttributes,+ );+ await editorState.apply(+ transaction,+ options: const ApplyOptions(recordUndo: false),+ );+ },+ (error) {+ Log.error(error);+ if (context.mounted) {+ showSnapBar(+ context,+ LocaleKeys.document_plugins_subPage_errors_failedDuplicatePage.tr(),+ );+ }+ },+ );+ }+}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.dartindex 7240030947..d8c6354273 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@@ -9,11 +9,13 @@ import 'package:provider/provider.dart';enum MentionType {page,reminder,- date;+ date,+ childPage;static MentionType fromString(String value) => switch (value) {'page' => page,'date' => date,+ 'childPage' => childPage,// Backwards compatibility'reminder' => date,_ => throw UnimplementedError(),@@ -91,6 +93,21 @@ class MentionBlock extends StatelessWidget {textStyle: textStyle,index: index,);+ case MentionType.childPage:+ final String? pageId = mention[MentionBlockKeys.pageId] as String?;+ if (pageId == null) {+ return const SizedBox.shrink();+ }++ return MentionSubPageBlock(+ key: ValueKey(pageId),+ editorState: editorState,+ pageId: pageId,+ node: node,+ textStyle: textStyle,+ index: index,+ );+case MentionType.date:final String date = mention[MentionBlockKeys.date];final reminderOption = ReminderOption.values.firstWhereOrNull(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.dartindex 0c198124dc..28a698dde2 100644--- 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@@ -5,11 +5,13 @@ import 'package:appflowy/plugins/document/application/document_data_pb_extensionimport '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/plugins/trash/application/prelude.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-document/entities.pb.dart';import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:flutter/foundation.dart';import 'package:flutter_bloc/flutter_bloc.dart';import 'package:freezed_annotation/freezed_annotation.dart';@@ -17,74 +19,83 @@ 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 deletedclass 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,- ),- );- },- );- });+ bool isSubPage = false,+ }) : _isSubPage = isSubPage,+ super(MentionPageState.initial()) {+ on<MentionPageEvent>(+ (event, emit) async {+ await event.when(+ initial: () async {+ final (view, isInTrash, isDeleted) =+ await ViewBackendService.getMentionPageStatus(pageId);++ String? blockContent;+ if (!_isSubPage) {+ blockContent = await _getBlockContent();+ }++ emit(+ state.copyWith(+ view: view,+ isLoading: false,+ isInTrash: isInTrash,+ isDeleted: isDeleted,+ blockContent: blockContent ?? '',+ ),+ );++ if (view != null) {+ _startListeningView();+ _startListeningTrash();++ if (!_isSubPage) {+ _startListeningDocument();+ }+ }+ },+ didUpdateViewStatus: (view, isDeleted) async {+ emit(+ state.copyWith(+ view: view,+ isDeleted: isDeleted ?? state.isDeleted,+ ),+ );+ },+ didUpdateTrashStatus: (isInTrash) async =>+ emit(state.copyWith(isInTrash: isInTrash)),+ didUpdateBlockContent: (content) {+ emit(+ state.copyWith(+ blockContent: content,+ ),+ );+ },+ );+ },+ );}@overrideFuture<void> close() {_viewListener?.stop();+ _trashListener?.close();_documentListener?.stop();return super.close();}+ final _documentService = DocumentService();+final String pageId;final String? blockId;+ final bool _isSubPage;- final _documentService = DocumentService();ViewListener? _viewListener;+ TrashListener? _trashListener;+DocumentListener? _documentListener;BlockPB? _block;String? _blockTextId;@@ -93,30 +104,47 @@ class MentionPageBloc extends Bloc<MentionPageEvent, MentionPageState> {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),- ),- );+ onViewUpdated: (view) => add(+ MentionPageEvent.didUpdateViewStatus(view: view, isDeleted: false),+ ),+ onViewDeleted: (_) =>+ add(const MentionPageEvent.didUpdateViewStatus(isDeleted: true)),+ );+ }++ void _startListeningTrash() {+ _trashListener = TrashListener()+ ..start(+ trashUpdated: (trashOrFailed) {+ final trash = trashOrFailed.toNullable();+ if (trash != null) {+ final isInTrash = trash.any((t) => t.id == pageId);+ add(MentionPageEvent.didUpdateTrashStatus(isInTrash: isInTrash));+ }},);}+ 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;+ }+ },+ );+ }+Future<String?> _getBlockContent() async {if (blockId == null) {return null;@@ -186,36 +214,21 @@ class MentionPageBloc extends Bloc<MentionPageEvent, MentionPageState> {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;- }- },- );- }}@freezedclass MentionPageEvent with _$MentionPageEvent {const factory MentionPageEvent.initial() = _Initial;+ const factory MentionPageEvent.didUpdateViewStatus({+ @Default(null) ViewPB? view,+ @Default(null) bool? isDeleted,+ }) = _DidUpdateViewStatus;+ const factory MentionPageEvent.didUpdateTrashStatus({+ required bool isInTrash,+ }) = _DidUpdateTrashStatus;const factory MentionPageEvent.didUpdateBlockContent(String content,) = _DidUpdateBlockContent;- const factory MentionPageEvent.didUpdateViewStatus(MentionPageStatus status) =- _DidUpdateViewStatus;}@freezed@@ -233,13 +246,13 @@ class MentionPageState with _$MentionPageState {// the plain text content of the block// it doesn't contain any formattingrequired String blockContent,- }) = _MentionPageState;+ }) = _MentionSubPageState;factory MentionPageState.initial() => const MentionPageState(isLoading: true,isInTrash: false,isDeleted: false,- blockContent: '',view: null,+ blockContent: '',);}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.dartindex 180c3e4db3..0c599cc5f2 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@@ -6,27 +6,30 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/meimport '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/shared/clipboard_state.dart';import 'package:appflowy/startup/startup.dart';import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart';import 'package:appflowy/workspace/application/action_navigation/navigation_action.dart';import 'package:appflowy/workspace/application/view/prelude.dart';-import 'package:appflowy/workspace/application/view/view_ext.dart';+import 'package:appflowy/workspace/presentation/home/menu/menu_shared_state.dart';import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';import 'package:appflowy_editor/appflowy_editor.dart'show+ ApplyOptions,Delta,EditorState,Node,- TextInsert,- TextTransaction,- paragraphNode,NodeIterator,Path,- Selection,Position,- SelectionType;+ Selection,+ SelectionType,+ TextInsert,+ TextTransaction,+ paragraphNode;import 'package:collection/collection.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:flowy_infra_ui/style_widget/hover.dart';import 'package:flutter/material.dart';@@ -78,19 +81,10 @@ class MentionPageBlock extends StatefulWidget {}class _MentionPageBlockState extends State<MentionPageBlock> {- late final EditorState editorState;-- @override- void initState() {- super.initState();-- editorState = context.read<EditorState>();- }-@overrideWidget build(BuildContext context) {return BlocProvider(- create: (context) => MentionPageBloc(+ create: (_) => MentionPageBloc(pageId: widget.pageId,blockId: widget.blockId,)..add(const MentionPageEvent.initial()),@@ -112,15 +106,32 @@ class _MentionPageBlockState extends State<MentionPageBlock> {view: view,content: state.blockContent,textStyle: widget.textStyle,- handleTap: () => handleTap(view),- handleDoubleTap: handleDoubleTap,+ handleTap: () => _handleTap(+ context,+ widget.editorState,+ view,+ blockId: widget.blockId,+ ),+ handleDoubleTap: () => _handleDoubleTap(+ context,+ widget.editorState,+ view.id,+ widget.node,+ widget.index,+ ),);} else {return _DesktopMentionPageBlock(view: view,content: state.blockContent,textStyle: widget.textStyle,- handleTap: () => handleTap(view),+ showTrashHint: state.isInTrash,+ handleTap: () => _handleTap(+ context,+ widget.editorState,+ view,+ blockId: widget.blockId,+ ),);}},@@ -128,71 +139,96 @@ class _MentionPageBlockState extends State<MentionPageBlock> {);}- Future<void> handleTap(ViewPB view) async {- final blockId = widget.blockId;- final currentViewId = context.read<DocumentBloc>().documentId;- if (currentViewId == widget.pageId && blockId != null) {- // same page- final path = _findNodePathByBlockId(editorState, blockId);- if (path != null) {- editorState.scrollService?.jumpTo(path.first);- await editorState.updateSelectionWithReason(- Selection.collapsed(Position(path: path)),- customSelectionType: SelectionType.block,- );- }- return;- }-- if (UniversalPlatform.isMobile) {- if (mounted && currentViewId != widget.pageId) {- await context.pushView(view);- }- } else {- final action = NavigationAction(- objectId: view.id,- arguments: {- ActionArgumentKeys.view: view,- ActionArgumentKeys.blockId: blockId,- },- );- getIt<ActionNavigationBloc>().add(- ActionNavigationEvent.performAction(- action: action,- ),- );- }+ void updateSelection() {+ WidgetsBinding.instance.addPostFrameCallback(+ (_) => widget.editorState+ .updateSelectionWithReason(widget.editorState.selection),+ );}+}- Future<void> handleDoubleTap() async {- if (!UniversalPlatform.isMobile) {- return;- }+class MentionSubPageBlock extends StatefulWidget {+ const MentionSubPageBlock({+ super.key,+ required this.editorState,+ required this.pageId,+ required this.node,+ required this.textStyle,+ required this.index,+ });- final currentViewId = context.read<DocumentBloc>().documentId;- final viewId = await showPageSelectorSheet(- context,- currentViewId: currentViewId,- selectedViewId: widget.pageId,- );+ final EditorState editorState;+ final String pageId;+ final Node node;+ final TextStyle? textStyle;- if (viewId != null) {- // Update this nodes pageId- final transaction = widget.editorState.transaction- ..formatText(- widget.node,- widget.index,- 1,- {- MentionBlockKeys.mention: {- MentionBlockKeys.type: MentionType.page.name,- MentionBlockKeys.pageId: viewId,- },- },- );+ // Used to update the block+ final int index;- await widget.editorState.apply(transaction, withUpdateSelection: false);- }+ @override+ State<MentionSubPageBlock> createState() => _MentionSubPageBlockState();+}++class _MentionSubPageBlockState extends State<MentionSubPageBlock> {+ late bool isHandlingPaste = context.read<ClipboardState>().isHandlingPaste;++ @override+ Widget build(BuildContext context) {+ return BlocProvider(+ create: (_) => MentionPageBloc(pageId: widget.pageId, isSubPage: true)+ ..add(const MentionPageEvent.initial()),+ child: BlocConsumer<MentionPageBloc, MentionPageState>(+ listener: (context, state) async {+ if (state.view != null) {+ final currentViewId = getIt<MenuSharedState>().latestOpenView?.id;+ if (currentViewId == null) {+ return;+ }++ if (state.view!.parentViewId != currentViewId) {+ turnIntoPageRef();+ }+ }+ },+ builder: (context, state) {+ final view = state.view;+ if (state.isLoading || isHandlingPaste) {+ return const SizedBox.shrink();+ }++ if (state.isDeleted || view == null) {+ return _DeletedPageBlock(textStyle: widget.textStyle);+ }++ if (UniversalPlatform.isMobile) {+ return _MobileMentionPageBlock(+ view: view,+ showTrashHint: state.isInTrash,+ textStyle: widget.textStyle,+ handleTap: () => _handleTap(context, widget.editorState, view),+ isChildPage: true,+ content: '',+ handleDoubleTap: () => _handleDoubleTap(+ context,+ widget.editorState,+ view.id,+ widget.node,+ widget.index,+ ),+ );+ } else {+ return _DesktopMentionPageBlock(+ view: view,+ showTrashHint: state.isInTrash,+ content: null,+ textStyle: widget.textStyle,+ isChildPage: true,+ handleTap: () => _handleTap(context, widget.editorState, view),+ );+ }+ },+ ),+ );}Future<ViewPB?> fetchView(String pageId) async {@@ -218,32 +254,131 @@ class _MentionPageBlockState extends State<MentionPageBlock> {}void updateSelection() {- WidgetsBinding.instance.addPostFrameCallback((timeStamp) {- editorState.updateSelectionWithReason(- editorState.selection,+ WidgetsBinding.instance.addPostFrameCallback(+ (_) => widget.editorState+ .updateSelectionWithReason(widget.editorState.selection),+ );+ }++ void turnIntoPageRef() {+ final transaction = widget.editorState.transaction+ ..formatText(+ widget.node,+ widget.index,+ MentionBlockKeys.mentionChar.length,+ {+ MentionBlockKeys.mention: {+ MentionBlockKeys.type: MentionType.page.name,+ MentionBlockKeys.pageId: widget.pageId,+ },+ },);- });++ widget.editorState.apply(+ transaction,+ withUpdateSelection: false,+ options: const ApplyOptions(+ recordUndo: false,+ ),+ );+ }+}++Path? _findNodePathByBlockId(EditorState editorState, String blockId) {+ final document = editorState.document;+ final startNode = document.root.children.firstOrNull;+ if (startNode == null) {+ return null;}- Path? _findNodePathByBlockId(EditorState editorState, String blockId) {- final document = editorState.document;- final startNode = document.root.children.firstOrNull;- if (startNode == null) {- return null;+ final nodeIterator = NodeIterator(+ document: document,+ startNode: startNode,+ );+ while (nodeIterator.moveNext()) {+ final node = nodeIterator.current;+ if (node.id == blockId) {+ return node.path;}+ }- final nodeIterator = NodeIterator(- document: document,- startNode: startNode,- );- while (nodeIterator.moveNext()) {- final node = nodeIterator.current;- if (node.id == blockId) {- return node.path;- }+ return null;+}++Future<void> _handleTap(+ BuildContext context,+ EditorState editorState,+ ViewPB view, {+ String? blockId,+}) async {+ final currentViewId = context.read<DocumentBloc>().documentId;+ if (currentViewId == view.id && blockId != null) {+ // same page+ final path = _findNodePathByBlockId(editorState, blockId);+ if (path != null) {+ editorState.scrollService?.jumpTo(path.first);+ await editorState.updateSelectionWithReason(+ Selection.collapsed(Position(path: path)),+ customSelectionType: SelectionType.block,+ );}+ return;+ }- return null;+ if (UniversalPlatform.isMobile) {+ if (context.mounted && currentViewId != view.id) {+ await context.pushView(view);+ }+ } else {+ final action = NavigationAction(+ objectId: view.id,+ arguments: {+ ActionArgumentKeys.view: view,+ ActionArgumentKeys.blockId: blockId,+ },+ );+ getIt<ActionNavigationBloc>().add(+ ActionNavigationEvent.performAction(+ action: action,+ ),+ );+ }+}++Future<void> _handleDoubleTap(+ BuildContext context,+ EditorState editorState,+ String viewId,+ Node node,+ int index,+) async {+ if (!UniversalPlatform.isMobile) {+ return;+ }++ final currentViewId = context.read<DocumentBloc>().documentId;+ final newViewId = await showPageSelectorSheet(+ context,+ currentViewId: currentViewId,+ selectedViewId: viewId,+ );++ if (newViewId != null) {+ // Update this nodes pageId+ final transaction = editorState.transaction+ ..formatText(+ node,+ index,+ 1,+ {+ MentionBlockKeys.mention: {+ MentionBlockKeys.type: MentionType.page.name,+ MentionBlockKeys.pageId: newViewId,+ },+ },+ );++ await editorState.apply(transaction, withUpdateSelection: false);}}@@ -252,11 +387,15 @@ class _MentionPageBlockContent extends StatelessWidget {required this.view,required this.textStyle,this.content,+ this.showTrashHint = false,+ this.isChildPage = false,});final ViewPB view;final TextStyle? textStyle;final String? content;+ final bool showTrashHint;+ final bool isChildPage;@overrideWidget build(BuildContext context) {@@ -265,7 +404,7 @@ class _MentionPageBlockContent extends StatelessWidget {return Row(mainAxisSize: MainAxisSize.min,children: [- ..._buildPrefixIcons(context, view, content),+ ..._buildPrefixIcons(context, view, content, isChildPage),const HSpace(2),Flexible(child: FlowyText(@@ -278,6 +417,17 @@ class _MentionPageBlockContent extends StatelessWidget {overflow: TextOverflow.ellipsis,),),+ if (showTrashHint) ...[+ FlowyText(+ LocaleKeys.document_mention_trashHint.tr(),+ fontSize: textStyle?.fontSize,+ fontWeight: textStyle?.fontWeight,+ lineHeight: textStyle?.height,+ color: Theme.of(context).disabledColor,+ decoration: TextDecoration.underline,+ decorationColor: AFThemeExtension.of(context).textColor,+ ),+ ],const HSpace(4),],);@@ -287,6 +437,7 @@ class _MentionPageBlockContent extends StatelessWidget {BuildContext context,ViewPB view,String? content,+ bool isChildPage,) {final isSameDocument = _isSameDocument(context, view.id);final shouldDisplayViewName = _shouldDisplayViewName(@@ -319,7 +470,7 @@ class _MentionPageBlockContent extends StatelessWidget {optimizeEmojiAlign: true,): FlowySvg(- view.layout.icon,+ isChildPage ? FlowySvgs.child_page_s : FlowySvgs.link_to_page_s,size: Size.square(iconSize + 2.0),),];@@ -373,9 +524,7 @@ class _MentionPageBlockContent extends StatelessWidget {}class _NoAccessMentionPageBlock extends StatelessWidget {- const _NoAccessMentionPageBlock({- required this.textStyle,- });+ const _NoAccessMentionPageBlock({required this.textStyle});final TextStyle? textStyle;@@ -396,6 +545,28 @@ class _NoAccessMentionPageBlock extends StatelessWidget {}}+class _DeletedPageBlock extends StatelessWidget {+ const _DeletedPageBlock({required this.textStyle});++ final TextStyle? textStyle;++ @override+ Widget build(BuildContext context) {+ return FlowyHover(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 4),+ child: FlowyText(+ LocaleKeys.document_mention_deletedPage.tr(),+ color: Theme.of(context).disabledColor,+ decoration: TextDecoration.underline,+ fontSize: textStyle?.fontSize,+ fontWeight: textStyle?.fontWeight,+ ),+ ),+ );+ }+}+class _MobileMentionPageBlock extends StatelessWidget {const _MobileMentionPageBlock({required this.view,@@ -403,6 +574,8 @@ class _MobileMentionPageBlock extends StatelessWidget {required this.textStyle,required this.handleTap,required this.handleDoubleTap,+ this.showTrashHint = false,+ this.isChildPage = false,});final TextStyle? textStyle;@@ -410,6 +583,8 @@ class _MobileMentionPageBlock extends StatelessWidget {final String content;final VoidCallback handleTap;final VoidCallback handleDoubleTap;+ final bool showTrashHint;+ final bool isChildPage;@overrideWidget build(BuildContext context) {@@ -421,6 +596,8 @@ class _MobileMentionPageBlock extends StatelessWidget {view: view,content: content,textStyle: textStyle,+ showTrashHint: showTrashHint,+ isChildPage: isChildPage,),);}@@ -432,12 +609,16 @@ class _DesktopMentionPageBlock extends StatelessWidget {required this.textStyle,required this.handleTap,required this.content,+ this.showTrashHint = false,+ this.isChildPage = false,});final TextStyle? textStyle;final ViewPB view;final String? content;final VoidCallback handleTap;+ final bool showTrashHint;+ final bool isChildPage;@overrideWidget build(BuildContext context) {@@ -450,6 +631,8 @@ class _DesktopMentionPageBlock extends StatelessWidget {view: view,content: content,textStyle: textStyle,+ showTrashHint: showTrashHint,+ isChildPage: isChildPage,),),);diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/shared_context/shared_context.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/shared_context/shared_context.dartindex f68b9bd363..9eefb79051 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/shared_context/shared_context.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/shared_context/shared_context.dart@@ -1,20 +1,13 @@import 'package:flutter/widgets.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/block_transaction_handler/block_transaction_handler.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/sub_page/block_transaction_handler.dart';--final _transactionHandlers = [SubPageBlockTransactionHandler()];-/// Shared context for the editor plugins.////// For example, the backspace command requires the focus node of the cover title./// so we need to use the shared context to get the focus node.+///class SharedEditorContext {SharedEditorContext();- static List<BlockTransactionHandler> get transactionHandlers =>- _transactionHandlers;-// The focus node of the cover title.// It's null when the cover title is not focused.FocusNode? coverTitleFocusNode;diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/sub_page/sub_page_transaction_handler.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/sub_page/sub_page_transaction_handler.dartnew file mode 100644index 0000000000..ed51b7d629--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/sub_page/sub_page_transaction_handler.dart@@ -0,0 +1,245 @@+import 'package:flutter/widgets.dart';++import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/sub_page/sub_page_block_component.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/transaction_handler/block_transaction_handler.dart';+import 'package:appflowy/plugins/trash/application/trash_service.dart';+import 'package:appflowy/workspace/application/view/view_service.dart';+import 'package:appflowy_backend/log.dart';+import 'package:appflowy_backend/protobuf/flowy-folder/view.pbenum.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flowy_infra_ui/style_widget/snap_bar.dart';++class SubPageTransactionHandler extends BlockTransactionHandler {+ SubPageTransactionHandler() : super(type: SubPageBlockKeys.type);++ final List<String> _beingCreated = [];++ @override+ Future<void> onTransaction(+ BuildContext context,+ EditorState editorState,+ List<Node> added,+ List<Node> removed, {+ bool isCut = false,+ bool isUndoRedo = false,+ bool isPaste = false,+ bool isDraggingNode = false,+ String? parentViewId,+ }) async {+ if (isDraggingNode) {+ return;+ }++ for (final node in removed) {+ if (!context.mounted) return;+ await _subPageDeleted(context, node);+ }++ for (final node in added) {+ if (!context.mounted) return;+ await _subPageAdded(+ context,+ editorState,+ node,+ isCut: isCut,+ isPaste: isPaste,+ parentViewId: parentViewId,+ );+ }+ }++ Future<void> _subPageDeleted(+ BuildContext context,+ Node node,+ ) async {+ if (node.type != type) {+ return;+ }++ final view = node.attributes[SubPageBlockKeys.viewId];+ if (view == null) {+ return;+ }++ final result = await ViewBackendService.deleteView(viewId: view);+ result.fold(+ (_) {},+ (error) {+ Log.error(error);+ if (context.mounted) {+ showSnapBar(+ context,+ LocaleKeys.document_plugins_subPage_errors_failedDeletePage.tr(),+ );+ }+ },+ );+ }++ Future<void> _subPageAdded(+ BuildContext context,+ EditorState editorState,+ Node node, {+ bool isCut = false,+ bool isPaste = false,+ String? parentViewId,+ }) async {+ if (node.type != type || _beingCreated.contains(node.id)) {+ return;+ }++ final viewId = node.attributes[SubPageBlockKeys.viewId];+ if (viewId == null && parentViewId != null) {+ _beingCreated.add(node.id);++ // This is a new Node, we need to create the view+ final viewOrResult = await ViewBackendService.createView(+ layoutType: ViewLayoutPB.Document,+ parentViewId: parentViewId,+ name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(),+ );++ await viewOrResult.fold(+ (view) async {+ final transaction = editorState.transaction+ ..updateNode(node, {SubPageBlockKeys.viewId: view.id});+ await editorState.apply(+ transaction,+ withUpdateSelection: false,+ options: const ApplyOptions(recordUndo: false),+ );+ editorState.reload();+ },+ (error) async {+ Log.error(error);+ showSnapBar(+ context,+ LocaleKeys.document_plugins_subPage_errors_failedCreatePage.tr(),+ );++ // Remove the node because it failed+ final transaction = editorState.transaction..deleteNode(node);+ await editorState.apply(+ transaction,+ withUpdateSelection: false,+ options: const ApplyOptions(recordUndo: false),+ );+ },+ );++ _beingCreated.remove(node.id);+ } else if (isPaste) {+ // final wasCut = node.attributes[SubPageBlockKeys.wasCut];++ if (isCut && parentViewId != null) {+ // Just in case, we try to put back from trash before moving+ await TrashService.putback(viewId);++ final viewOrResult = await ViewBackendService.moveViewV2(+ viewId: viewId,+ newParentId: parentViewId,+ prevViewId: null,+ );++ viewOrResult.fold(+ (_) {},+ (error) {+ Log.error(error);+ showSnapBar(+ context,+ LocaleKeys.document_plugins_subPage_errors_failedMovePage.tr(),+ );+ },+ );+ } else {+ final viewId = node.attributes[SubPageBlockKeys.viewId];+ if (viewId == null) {+ return;+ }++ final viewOrResult = await ViewBackendService.getView(viewId);+ return viewOrResult.fold(+ (view) async {+ final duplicatedViewOrResult = await ViewBackendService.duplicate(+ view: view,+ openAfterDuplicate: false,+ includeChildren: true,+ syncAfterDuplicate: true,+ parentViewId: parentViewId,+ );++ return duplicatedViewOrResult.fold(+ (view) async {+ final transaction = editorState.transaction+ ..updateNode(node, {+ SubPageBlockKeys.viewId: view.id,+ SubPageBlockKeys.wasCut: false,+ SubPageBlockKeys.wasCopied: false,+ });+ await editorState.apply(+ transaction,+ withUpdateSelection: false,+ options: const ApplyOptions(recordUndo: false),+ );+ editorState.reload();+ },+ (error) {+ Log.error(error);+ if (context.mounted) {+ showSnapBar(+ context,+ LocaleKeys+ .document_plugins_subPage_errors_failedDuplicatePage+ .tr(),+ );+ }+ },+ );+ },+ (error) async {+ Log.error(error);++ final transaction = editorState.transaction..deleteNode(node);+ await editorState.apply(+ transaction,+ withUpdateSelection: false,+ options: const ApplyOptions(recordUndo: false),+ );+ editorState.reload();+ if (context.mounted) {+ showSnapBar(+ context,+ LocaleKeys+ .document_plugins_subPage_errors_failedDuplicateFindView+ .tr(),+ );+ }+ },+ );+ }+ } else {+ // Try to restore from trash, and move to parent view+ await TrashService.putback(viewId);++ // Check if View needs to be moved+ if (parentViewId != null) {+ final view = (await ViewBackendService.getView(viewId)).toNullable();+ if (view == null) {+ return Log.error('View not found: $viewId');+ }++ if (view.parentViewId == parentViewId) {+ return;+ }++ await ViewBackendService.moveViewV2(+ viewId: viewId,+ newParentId: parentViewId,+ prevViewId: null,+ );+ }+ }+ }+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/block_transaction_handler.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/block_transaction_handler.dartnew file mode 100644index 0000000000..34b0bdc8f9--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/block_transaction_handler.dart@@ -0,0 +1,13 @@+import 'package:appflowy/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_handler.dart';+import 'package:appflowy_editor/appflowy_editor.dart';++/// A handler for transactions that involve a Block Component.+///+/// This is a subclass of [EditorTransactionHandler] that is used for block components.+/// Specifically this transaction handler only needs to concern itself with changes to+/// a [Node], and doesn't care about text deltas.+///+abstract class BlockTransactionHandler extends EditorTransactionHandler<Node> {+ const BlockTransactionHandler({required super.type})+ : super(livesInDelta: false);+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_handler.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_handler.dartnew file mode 100644index 0000000000..f7517e7fca--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_handler.dart@@ -0,0 +1,37 @@+import 'package:flutter/material.dart';++import 'package:appflowy_editor/appflowy_editor.dart';++/// A handler for transactions that involve a Block Component.+/// The [T] type is the type of data that this transaction handler takes.+///+/// In case of a block component, the [T] type should be a [Node].+/// In case of a mention component, the [T] type should be a [Map].+///+abstract class EditorTransactionHandler<T> {+ const EditorTransactionHandler({+ required this.type,+ this.livesInDelta = false,+ });++ /// The type of the block/mention that this handler is built for.+ /// It's used to determine whether to call any of the handlers on certain transactions.+ ///+ final String type;++ /// If the block is a "mention" type, it lives inside the [Delta] of a [Node].+ ///+ final bool livesInDelta;++ Future<void> onTransaction(+ BuildContext context,+ EditorState editorState,+ List<T> added,+ List<T> removed, {+ bool isCut = false,+ bool isUndoRedo = false,+ bool isPaste = false,+ bool isDraggingNode = false,+ String? parentViewId,+ });+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_service.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_service.dartnew file mode 100644index 0000000000..986b08f0c1--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_service.dart@@ -0,0 +1,306 @@+import 'dart:async';++import 'package:appflowy/plugins/document/presentation/editor_notification.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/child_page_transaction_handler.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/sub_page/sub_page_transaction_handler.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_handler.dart';+import 'package:appflowy/shared/clipboard_state.dart';+import 'package:appflowy/shared/feature_flags.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:flutter/material.dart';+import 'package:flutter_bloc/flutter_bloc.dart';++final _transactionHandlers = <EditorTransactionHandler>[+ if (FeatureFlag.inlineSubPageMention.isOn) ...[+ SubPageTransactionHandler(),+ ChildPageTransactionHandler(),+ ],+];++/// Handles delegating transactions to appropriate handlers.+///+/// Such as the [ChildPageTransactionHandler] for inline child pages.+///+class EditorTransactionService extends StatefulWidget {+ const EditorTransactionService({+ super.key,+ required this.viewId,+ required this.editorState,+ required this.child,+ });++ final String viewId;+ final EditorState editorState;+ final Widget child;++ @override+ State<EditorTransactionService> createState() =>+ _EditorTransactionServiceState();+}++class _EditorTransactionServiceState extends State<EditorTransactionService> {+ StreamSubscription<(TransactionTime, Transaction)>? transactionSubscription;++ bool isUndoRedo = false;+ bool isPaste = false;+ bool isDraggingNode = false;++ @override+ void initState() {+ super.initState();+ transactionSubscription =+ widget.editorState.transactionStream.listen(onEditorTransaction);+ EditorNotification.addListener(onEditorNotification);+ }++ @override+ void dispose() {+ EditorNotification.removeListener(onEditorNotification);+ transactionSubscription?.cancel();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ return widget.child;+ }++ void onEditorNotification(EditorNotificationType type) {+ if ([EditorNotificationType.undo, EditorNotificationType.redo]+ .contains(type)) {+ isUndoRedo = true;+ } else if (type == EditorNotificationType.paste) {+ isPaste = true;+ } else if (type == EditorNotificationType.dragStart) {+ isDraggingNode = true;+ } else if (type == EditorNotificationType.dragEnd) {+ isDraggingNode = false;+ }++ if (type == EditorNotificationType.undo) {+ undoCommand.execute(widget.editorState);+ } else if (type == EditorNotificationType.redo) {+ redoCommand.execute(widget.editorState);+ } else if (type == EditorNotificationType.exitEditing &&+ widget.editorState.selection != null) {+ widget.editorState.selection = null;+ }+ }++ /// Collects all nodes of a certain type, including those that are nested.+ ///+ List<Node> collectMatchingNodes(+ Node node,+ String type, {+ bool livesInDelta = false,+ }) {+ final List<Node> matchingNodes = [];+ if (node.type == type) {+ matchingNodes.add(node);+ }++ if (livesInDelta && node.attributes[blockComponentDelta] != null) {+ final deltas = node.attributes[blockComponentDelta];+ if (deltas is List) {+ for (final delta in deltas) {+ if (delta['attributes'] != null &&+ delta['attributes'][type] != null) {+ matchingNodes.add(node);+ }+ }+ }+ }++ for (final child in node.children) {+ matchingNodes.addAll(+ collectMatchingNodes(+ child,+ type,+ livesInDelta: livesInDelta,+ ),+ );+ }++ return matchingNodes;+ }++ void onEditorTransaction((TransactionTime, Transaction) event) {+ if (event.$1 == TransactionTime.before) {+ return;+ }++ final Map<String, dynamic> added = {+ for (final handler in _transactionHandlers)+ handler.type: handler.livesInDelta ? <MentionBlockData>[] : [],+ };+ final Map<String, dynamic> removed = {+ for (final handler in _transactionHandlers)+ handler.type: handler.livesInDelta ? <MentionBlockData>[] : [],+ };++ for (final op in event.$2.operations) {+ if (op is InsertOperation) {+ for (final n in op.nodes) {+ for (final handler in _transactionHandlers) {+ if (handler.livesInDelta) {+ added[handler.type]!+ .addAll(extractMentionsForType(n, handler.type));+ } else {+ added[handler.type]!+ .addAll(collectMatchingNodes(n, handler.type));+ }+ }+ }+ } else if (op is DeleteOperation) {+ for (final n in op.nodes) {+ for (final handler in _transactionHandlers) {+ if (handler.livesInDelta) {+ removed[handler.type]!.addAll(+ extractMentionsForType(n, handler.type, false),+ );+ } else {+ removed[handler.type]!+ .addAll(collectMatchingNodes(n, handler.type));+ }+ }+ }+ } else if (op is UpdateOperation) {+ final node = widget.editorState.getNodeAtPath(op.path);+ if (node == null) {+ continue;+ }++ if (op.attributes[blockComponentDelta] is! List ||+ op.oldAttributes[blockComponentDelta] is! List) {+ continue;+ }++ final deltaBefore =+ Delta.fromJson(op.oldAttributes[blockComponentDelta]);+ final deltaAfter = Delta.fromJson(op.attributes[blockComponentDelta]);++ final (add, del) = diffDeltas(deltaBefore, deltaAfter);++ for (final handler in _transactionHandlers) {+ if (!handler.livesInDelta) {+ continue;+ }++ if (add.isNotEmpty) {+ final mentionBlockDatas =+ getMentionBlockData(handler.type, node, add);++ added[handler.type]!.addAll(mentionBlockDatas);+ }++ if (del.isNotEmpty) {+ final mentionBlockDatas = getMentionBlockData(+ handler.type,+ node,+ del,+ );++ removed[handler.type]!.addAll(mentionBlockDatas);+ }+ }+ }+ }++ for (final handler in _transactionHandlers) {+ final additions = added[handler.type] ?? [];+ final removals = removed[handler.type] ?? [];++ if (additions.isEmpty && removals.isEmpty) {+ continue;+ }++ handler.onTransaction(+ context,+ widget.editorState,+ additions,+ removals,+ isCut: context.read<ClipboardState>().isCut,+ isUndoRedo: isUndoRedo,+ isPaste: isPaste,+ isDraggingNode: isDraggingNode,+ parentViewId: widget.viewId,+ );+ }++ isUndoRedo = false;+ isPaste = false;+ }++ /// Takes an iterable of [TextInsert] and returns a list of [MentionBlockData].+ /// This is used to extract mentions from a list of text inserts, of a certain type.+ List<MentionBlockData> getMentionBlockData(+ String type,+ Node node,+ Iterable<TextInsert> textInserts,+ ) {+ // Additions contain all the text inserts that were added in this+ // transaction, we only care about the ones that fit the handlers type.++ // Filter out the text inserts where the attribute for the handler type is present.+ final relevantTextInserts =+ textInserts.where((ti) => ti.attributes?[type] != null);++ // Map it to a list of MentionBlockData.+ final mentionBlockDatas = relevantTextInserts.map<MentionBlockData>((ti) {+ // For some text inserts (mostly additions), we might need to modify them after the transaction,+ // so we pass the index of the delta to the handler.+ final index = node.delta?.toList().indexOf(ti) ?? -1;+ return (node, ti.attributes![type], index);+ }).toList();++ return mentionBlockDatas;+ }++ List<MentionBlockData> extractMentionsForType(+ Node node,+ String mentionType, [+ bool includeIndex = true,+ ]) {+ final changes = <MentionBlockData>[];++ final nodesWithDelta = collectMatchingNodes(+ node,+ mentionType,+ livesInDelta: true,+ );++ for (final paragraphNode in nodesWithDelta) {+ final textInserts = paragraphNode.attributes[blockComponentDelta];+ if (textInserts == null || textInserts is! List || textInserts.isEmpty) {+ continue;+ }++ for (final (index, textInsert) in textInserts.indexed) {+ if (textInsert['attributes'] != null &&+ textInsert['attributes'][mentionType] != null) {+ changes.add(+ (+ paragraphNode,+ textInsert['attributes'][mentionType],+ includeIndex ? index : -1,+ ),+ );+ }+ }+ }++ return changes;+ }++ (Iterable<TextInsert>, Iterable<TextInsert>) diffDeltas(+ Delta before,+ Delta after,+ ) {+ final diff = before.diff(after);+ final inverted = diff.invert(before);+ final del = inverted.whereType<TextInsert>();+ final add = diff.whereType<TextInsert>();++ return (add, del);+ }+}diff --git a/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/child_page.dart b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/child_page.dartnew file mode 100644index 0000000000..d29a1f86bf--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/inline_actions/handlers/child_page.dart@@ -0,0 +1,84 @@+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/mention/mention_page_block.dart';+import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart';+import 'package:appflowy/plugins/inline_actions/inline_actions_result.dart';+import 'package:appflowy/plugins/inline_actions/service_handler.dart';+import 'package:appflowy/workspace/application/view/prelude.dart';+import 'package:appflowy_backend/log.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';+import 'package:flutter/material.dart';++class InlineChildPageService extends InlineActionsDelegate {+ InlineChildPageService({required this.currentViewId});++ final String currentViewId;++ @override+ Future<InlineActionsResult> search(String? search) async {+ final List<InlineActionsMenuItem> results = [];+ if (search != null && search.isNotEmpty) {+ results.add(+ InlineActionsMenuItem(+ label: LocaleKeys.inlineActions_createPage.tr(args: [search]),+ icon: (_) => const FlowySvg(FlowySvgs.add_s),+ onSelected: (context, editorState, service, replacement) =>+ _onSelected(context, editorState, service, replacement, search),+ ),+ );+ }++ return InlineActionsResult(results: results);+ }++ Future<void> _onSelected(+ BuildContext context,+ EditorState editorState,+ InlineActionsMenuService service,+ (int, int) replacement,+ String? search,+ ) 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 view = (await ViewBackendService.createView(+ layoutType: ViewLayoutPB.Document,+ parentViewId: currentViewId,+ name: search!,+ ))+ .toNullable();++ if (view == null) {+ return Log.error('Failed to create view');+ }++ // preload the page info+ pageMemorizer[view.id] = view;+ final transaction = editorState.transaction+ ..replaceText(+ node,+ replacement.$1,+ replacement.$2,+ MentionBlockKeys.mentionChar,+ attributes: {+ MentionBlockKeys.mention: {+ MentionBlockKeys.type: MentionType.childPage.name,+ MentionBlockKeys.pageId: view.id,+ },+ },+ );++ await editorState.apply(transaction);+ }+}diff --git a/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_result.dart b/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_result.dartindex c1f1a9e237..8da9647084 100644--- a/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_result.dart+++ b/frontend/appflowy_flutter/lib/plugins/inline_actions/inline_actions_result.dart@@ -25,7 +25,7 @@ class InlineActionsMenuItem {class InlineActionsResult {InlineActionsResult({- required this.title,+ this.title,required this.results,this.startsWithKeywords,});@@ -33,7 +33,9 @@ class InlineActionsResult {/// Localized title to be displayed above the results/// of the current group.///- final String title;+ /// If null, no title will be displayed.+ ///+ final String? title;/// List of results that will be displayed for this group/// made up of [SelectionMenuItem]s.diff --git a/frontend/appflowy_flutter/lib/plugins/inline_actions/widgets/inline_actions_menu_group.dart b/frontend/appflowy_flutter/lib/plugins/inline_actions/widgets/inline_actions_menu_group.dartindex 8e72415309..6179d3d18b 100644--- a/frontend/appflowy_flutter/lib/plugins/inline_actions/widgets/inline_actions_menu_group.dart+++ b/frontend/appflowy_flutter/lib/plugins/inline_actions/widgets/inline_actions_menu_group.dart@@ -41,8 +41,10 @@ class InlineActionsGroup extends StatelessWidget {child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- FlowyText.medium(result.title, color: style.groupTextColor),- const SizedBox(height: 4),+ if (result.title != null) ...[+ FlowyText.medium(result.title!, color: style.groupTextColor),+ const SizedBox(height: 4),+ ],...result.results.mapIndexed((index, item) => InlineActionsWidget(item: item,@@ -101,6 +103,7 @@ class _InlineActionsWidgetState extends State<InlineActionsWidget> {text: FlowyText.regular(widget.item.label,figmaLineHeight: 18,+ overflow: TextOverflow.ellipsis,),onTap: _onPressed,),diff --git a/frontend/appflowy_flutter/lib/shared/clipboard_state.dart b/frontend/appflowy_flutter/lib/shared/clipboard_state.dartnew file mode 100644index 0000000000..dfee65e420--- /dev/null+++ b/frontend/appflowy_flutter/lib/shared/clipboard_state.dart@@ -0,0 +1,46 @@+import 'package:flutter/foundation.dart';++/// Class to hold the state of the Clipboard.+///+/// Essentially for document in-app json paste, we need to be able+/// to differentiate between a cut-paste and a copy-paste.+///+/// When a cut-pase has occurred, the next paste operation should be+/// seen as a copy-paste.+///+class ClipboardState {+ ClipboardState();++ bool _isCut = false;++ bool get isCut => _isCut;++ final ValueNotifier<bool> isHandlingPasteNotifier = ValueNotifier(false);+ bool get isHandlingPaste => isHandlingPasteNotifier.value;++ final Set<String> _handlingPasteIds = {};++ void dispose() {+ isHandlingPasteNotifier.dispose();+ }++ void didCut() {+ _isCut = true;+ }++ void didPaste() {+ _isCut = false;+ }++ void startHandlingPaste(String id) {+ _handlingPasteIds.add(id);+ isHandlingPasteNotifier.value = true;+ }++ void endHandlingPaste(String id) {+ _handlingPasteIds.remove(id);+ if (_handlingPasteIds.isEmpty) {+ isHandlingPasteNotifier.value = false;+ }+ }+}diff --git a/frontend/appflowy_flutter/lib/shared/feature_flags.dart b/frontend/appflowy_flutter/lib/shared/feature_flags.dartindex bc87836659..7ea66076df 100644--- a/frontend/appflowy_flutter/lib/shared/feature_flags.dart+++ b/frontend/appflowy_flutter/lib/shared/feature_flags.dart@@ -38,6 +38,9 @@ enum FeatureFlag {// used for space designspaceDesign,+ // used for the inline sub-page mention+ inlineSubPageMention,+// used for ignore the conflicted feature flagunknown;@@ -102,6 +105,7 @@ enum FeatureFlag {// release this feature in version 0.5.4FeatureFlag.syncDatabase,FeatureFlag.syncDocument,+ FeatureFlag.inlineSubPageMention,].contains(this)) {return true;}@@ -116,6 +120,7 @@ enum FeatureFlag {case FeatureFlag.syncDocument:case FeatureFlag.syncDatabase:case FeatureFlag.spaceDesign:+ case FeatureFlag.inlineSubPageMention:return true;case FeatureFlag.collaborativeWorkspace:case FeatureFlag.membersSettings:@@ -140,6 +145,8 @@ enum FeatureFlag {return 'if it\'s on, plan and billing pages will be available in Settings';case FeatureFlag.spaceDesign:return 'if it\'s on, the space design feature will be available';+ case FeatureFlag.inlineSubPageMention:+ return 'if it\'s on, the inline sub-page mention feature will be available';case FeatureFlag.unknown:return '';}diff --git a/frontend/appflowy_flutter/lib/shared/text_field/text_filed_with_metric_lines.dart b/frontend/appflowy_flutter/lib/shared/text_field/text_filed_with_metric_lines.dartindex 97ada3b032..b8db272a4b 100644--- a/frontend/appflowy_flutter/lib/shared/text_field/text_filed_with_metric_lines.dart+++ b/frontend/appflowy_flutter/lib/shared/text_field/text_filed_with_metric_lines.dart@@ -9,6 +9,7 @@ class TextFieldWithMetricLines extends StatefulWidget {this.style,this.decoration,this.onLineCountChange,+ this.enabled = true,});final TextEditingController? controller;@@ -17,6 +18,7 @@ class TextFieldWithMetricLines extends StatefulWidget {final TextStyle? style;final InputDecoration? decoration;final void Function(int count)? onLineCountChange;+ final bool enabled;@overrideState<TextFieldWithMetricLines> createState() =>@@ -49,6 +51,7 @@ class _TextFieldWithMetricLinesState extends State<TextFieldWithMetricLines> {Widget build(BuildContext context) {return TextField(key: key,+ enabled: widget.enabled,controller: widget.controller,focusNode: widget.focusNode,maxLines: widget.maxLines,diff --git a/frontend/appflowy_flutter/lib/startup/tasks/app_widget.dart b/frontend/appflowy_flutter/lib/startup/tasks/app_widget.dartindex 3877fa515d..957c281d8a 100644--- a/frontend/appflowy_flutter/lib/startup/tasks/app_widget.dart+++ b/frontend/appflowy_flutter/lib/startup/tasks/app_widget.dart@@ -1,7 +1,11 @@import 'dart:io';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:appflowy/mobile/application/mobile_router.dart';import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';+import 'package:appflowy/shared/clipboard_state.dart';import 'package:appflowy/shared/feature_flags.dart';import 'package:appflowy/shared/icon_emoji_picker/icon_picker.dart';import 'package:appflowy/startup/startup.dart';@@ -22,10 +26,9 @@ import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';import 'package:easy_localization/easy_localization.dart';import 'package:flowy_infra/theme.dart';import 'package:flowy_infra_ui/flowy_infra_ui.dart';-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';import 'package:flutter_bloc/flutter_bloc.dart';import 'package:go_router/go_router.dart';+import 'package:provider/provider.dart';import 'package:toastification/toastification.dart';import 'package:universal_platform/universal_platform.dart';@@ -209,32 +212,36 @@ class _ApplicationWidgetState extends State<ApplicationWidget> {child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>(builder: (context, state) {_setSystemOverlayStyle(state);- return ToastificationWrapper(- child: MaterialApp.router(- builder: (context, child) => MediaQuery(- // use the 1.0 as the textScaleFactor to avoid the text size- // affected by the system setting.- data: MediaQuery.of(context).copyWith(- textScaler: TextScaler.linear(state.textScaleFactor),- ),- child: overlayManagerBuilder(- context,- !UniversalPlatform.isMobile && FeatureFlag.search.isOn- ? CommandPalette(- notifier: _commandPaletteNotifier,- child: child,- )- : child,+ return Provider(+ create: (_) => ClipboardState(),+ dispose: (_, state) => state.dispose(),+ child: ToastificationWrapper(+ child: MaterialApp.router(+ builder: (context, child) => MediaQuery(+ // use the 1.0 as the textScaleFactor to avoid the text size+ // affected by the system setting.+ data: MediaQuery.of(context).copyWith(+ textScaler: TextScaler.linear(state.textScaleFactor),+ ),+ child: overlayManagerBuilder(+ context,+ !UniversalPlatform.isMobile && FeatureFlag.search.isOn+ ? CommandPalette(+ notifier: _commandPaletteNotifier,+ child: child,+ )+ : child,+ ),),+ debugShowCheckedModeBanner: false,+ theme: state.lightTheme,+ darkTheme: state.darkTheme,+ themeMode: state.themeMode,+ localizationsDelegates: context.localizationDelegates,+ supportedLocales: context.supportedLocales,+ locale: state.locale,+ routerConfig: routerConfig,),- debugShowCheckedModeBanner: false,- theme: state.lightTheme,- darkTheme: state.darkTheme,- themeMode: state.themeMode,- localizationsDelegates: context.localizationDelegates,- supportedLocales: context.supportedLocales,- locale: state.locale,- routerConfig: routerConfig,),);},diff --git a/frontend/appflowy_flutter/lib/workspace/application/view/view_ext.dart b/frontend/appflowy_flutter/lib/workspace/application/view/view_ext.dartindex 09231f882f..4d02811063 100644--- a/frontend/appflowy_flutter/lib/workspace/application/view/view_ext.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/view/view_ext.dart@@ -284,6 +284,12 @@ extension ViewLayoutExtension on ViewLayoutPB {_ => throw Exception('Unknown layout type'),};+ FlowySvgData mentionIcon({bool isChildPage = false}) => switch (this) {+ ViewLayoutPB.Document =>+ isChildPage ? FlowySvgs.child_page_s : FlowySvgs.link_to_page_s,+ _ => icon,+ };+bool get isDocumentView => switch (this) {ViewLayoutPB.Document => true,ViewLayoutPB.Chat ||diff --git a/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text.dart b/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text.dartindex c02a5b1cfd..76e9eefbc2 100644--- a/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text.dart+++ b/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text.dart@@ -13,6 +13,7 @@ class FlowyText extends StatelessWidget {final int? maxLines;final Color? color;final TextDecoration? decoration;+ final Color? decorationColor;final double? decorationThickness;final bool selectable;final String? fontFamily;@@ -39,6 +40,7 @@ class FlowyText extends StatelessWidget {this.color,this.maxLines = 1,this.decoration,+ this.decorationColor,this.selectable = false,this.fontFamily,this.fallbackFontFamily,@@ -60,6 +62,7 @@ class FlowyText extends StatelessWidget {this.textAlign,this.maxLines = 1,this.decoration,+ this.decorationColor,this.selectable = false,this.fontFamily,this.fallbackFontFamily,@@ -82,6 +85,7 @@ class FlowyText extends StatelessWidget {this.textAlign,this.maxLines = 1,this.decoration,+ this.decorationColor,this.selectable = false,this.fontFamily,this.fallbackFontFamily,@@ -103,6 +107,7 @@ class FlowyText extends StatelessWidget {this.textAlign,this.maxLines = 1,this.decoration,+ this.decorationColor,this.selectable = false,this.fontFamily,this.fallbackFontFamily,@@ -124,6 +129,7 @@ class FlowyText extends StatelessWidget {this.textAlign,this.maxLines = 1,this.decoration,+ this.decorationColor,this.selectable = false,this.fontFamily,this.fallbackFontFamily,@@ -146,6 +152,7 @@ class FlowyText extends StatelessWidget {this.textAlign = TextAlign.center,this.maxLines = 1,this.decoration,+ this.decorationColor,this.selectable = false,this.lineHeight,this.withTooltip = false,@@ -194,6 +201,7 @@ class FlowyText extends StatelessWidget {fontWeight: fontWeight,color: color,decoration: decoration,+ decorationColor: decorationColor,decorationThickness: decorationThickness,fontFamily: fontFamily,fontFamilyFallback: fallbackFontFamily,diff --git a/frontend/appflowy_flutter/pubspec.lock b/frontend/appflowy_flutter/pubspec.lockindex 16bf375bce..ec03c15748 100644--- a/frontend/appflowy_flutter/pubspec.lock+++ b/frontend/appflowy_flutter/pubspec.lock@@ -1535,10 +1535,10 @@ packages:dependency: transitivedescription:name: platform- sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65"+ sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec"url: "https://pub.dev"source: hosted- version: "3.1.5"+ version: "3.1.4"plugin_platform_interface:dependency: "direct dev"description:@@ -1933,10 +1933,10 @@ packages:dependency: transitivedescription:name: string_scanner- sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3"+ sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"url: "https://pub.dev"source: hosted- version: "1.3.0"+ version: "1.2.0"string_validator:dependency: "direct main"description:@@ -2238,10 +2238,10 @@ packages:dependency: transitivedescription:name: vm_service- sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d"+ sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec"url: "https://pub.dev"source: hosted- version: "14.2.5"+ version: "14.2.1"watcher:dependency: transitivedescription:diff --git a/frontend/resources/flowy_icons/16x/child_page.svg b/frontend/resources/flowy_icons/16x/child_page.svgnew file mode 100644index 0000000000..40861287d4--- /dev/null+++ b/frontend/resources/flowy_icons/16x/child_page.svg@@ -0,0 +1,4 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M13.6668 6.74406V10.0173C13.6668 13.2906 12.5335 14.5999 9.70016 14.5999H6.30016C3.46683 14.5999 2.3335 13.2906 2.3335 10.0173V6.0894C2.3335 2.81614 3.46683 1.50684 6.30016 1.50684H9.1335" stroke="#171717" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M13.6168 6.66559H11.3502C9.65016 6.66559 9.0835 6.00738 9.0835 4.03274V1.68617C9.0835 1.58764 9.20598 1.54218 9.27027 1.61685L13.6168 6.66559Z" stroke="#171717" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/link_to_page.svg b/frontend/resources/flowy_icons/16x/link_to_page.svgnew file mode 100644index 0000000000..7968a5b367--- /dev/null+++ b/frontend/resources/flowy_icons/16x/link_to_page.svg@@ -0,0 +1,12 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<g clip-path="url(#clip0_315_1360)">+<path d="M1 10.3867L3.31601 8.07071C3.35506 8.03166 3.35506 7.96834 3.31601 7.92929L1 5.61328" stroke="#171717" stroke-linecap="round"/>+<path d="M15.2441 6.92362V9.72927C15.2441 12.5349 14.2726 13.6572 11.8441 13.6572H8.92978C6.50121 13.6572 5.52979 12.5349 5.52979 9.72927V6.36249C5.52979 3.55683 6.50121 2.43457 8.92978 2.43457H11.3584" stroke="#171717" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M15.2011 6.85622H13.2583C11.8011 6.85622 11.3154 6.29204 11.3154 4.5995V2.62904C11.3154 2.53051 11.4379 2.48505 11.5022 2.55972L15.2011 6.85622Z" stroke="#171717" stroke-linecap="round" stroke-linejoin="round"/>+</g>+<defs>+<clipPath id="clip0_315_1360">+<rect width="16" height="16" fill="white"/>+</clipPath>+</defs>+</svg>diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.jsonindex c464f27721..35c75c504f 100644--- a/frontend/resources/translations/en.json+++ b/frontend/resources/translations/en.json@@ -1884,7 +1884,9 @@},"deleted": "Deleted","deletedContent": "This content does not exist or has been deleted",- "noAccess": "No Access"+ "noAccess": "No Access",+ "deletedPage": "Deleted page",+ "trashHint": " - in trash"},"toolbar": {"resetToDefaultFont": "Reset to default"@@ -2083,7 +2085,8 @@"reminder": {"groupTitle": "Reminder","shortKeyword": "remind"- }+ },+ "createPage": "Create \"{}\" sub-page"},"datePicker": {"dateTimeFormatTooltip": "Change the date and time format in settings",