Skip to content

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

feat: support markdown syntax in ai writer block (#6864)

Lucas068ac0e992d8
diff --git a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart
index a207a31021..32737a23d1 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart
@@ -33,7 +33,7 @@ void main() {
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_aiWriter.tr(),
);
- expect(find.byType(AutoCompletionBlockComponent), findsOneWidget);
+ expect(find.byType(AIWriterBlockComponent), findsOneWidget);
// switch to another page
await tester.openPage(Constants.gettingStartedPageName);
@@ -41,7 +41,7 @@ void main() {
await tester.openPage(pageName);
// expect the ai writer block is not in the document
- expect(find.byType(AutoCompletionBlockComponent), findsNothing);
+ expect(find.byType(AIWriterBlockComponent), findsNothing);
});
});
}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart b/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart
index 5617f80f25..736c9b7fa6 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart
@@ -4,7 +4,7 @@ import 'dart:convert';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/application/document_service.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
@@ -176,7 +176,7 @@ extension on InsertOperation {
Path currentPath = path;
final List<BlockActionWrapper> actions = [];
for (final node in nodes) {
- if (node.type == SmartEditBlockKeys.type) {
+ if (node.type == AskAIBlockKeys.type) {
continue;
}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart
index 193dedb63f..e164afa635 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart
@@ -252,11 +252,11 @@ Map<String, BlockComponentBuilder> _buildBlockComponentBuilderMap(
configuration,
styleCustomizer,
),
- AutoCompletionBlockKeys.type: _buildAutoCompletionBlockComponentBuilder(
+ AIWriterBlockKeys.type: _buildAIWriterBlockComponentBuilder(
context,
configuration,
),
- SmartEditBlockKeys.type: _buildSmartEditBlockComponentBuilder(
+ AskAIBlockKeys.type: _buildAskAIBlockComponentBuilder(
context,
configuration,
),
@@ -553,18 +553,18 @@ CodeBlockComponentBuilder _buildCodeBlockComponentBuilder(
);
}
-AutoCompletionBlockComponentBuilder _buildAutoCompletionBlockComponentBuilder(
+AIWriterBlockComponentBuilder _buildAIWriterBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
- return AutoCompletionBlockComponentBuilder();
+ return AIWriterBlockComponentBuilder();
}
-SmartEditBlockComponentBuilder _buildSmartEditBlockComponentBuilder(
+AskAIBlockComponentBuilder _buildAskAIBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
- return SmartEditBlockComponentBuilder();
+ return AskAIBlockComponentBuilder();
}
ToggleListBlockComponentBuilder _buildToggleListBlockComponentBuilder(
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
index bbdbd56446..6d9aa8d1e5 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
@@ -79,7 +79,7 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
];
final List<ToolbarItem> toolbarItems = [
- smartEditItem..isActive = onlyShowInTextType,
+ askAIItem..isActive = onlyShowInTextType,
paragraphItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
headingsToolbarItem
..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart
new file mode 100644
index 0000000000..d83b91d130
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart
@@ -0,0 +1,136 @@
+import 'dart:convert';
+
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+import 'package:flutter/foundation.dart';
+import 'package:synchronized/synchronized.dart';
+
+class MarkdownTextRobot {
+ MarkdownTextRobot({
+ required this.editorState,
+ this.enableDebug = false,
+ });
+
+ final EditorState editorState;
+ final bool enableDebug;
+
+ final Lock lock = Lock();
+
+ // The selection before the text robot is ready.
+ Selection? _startSelection;
+
+ // The markdown text to be inserted.
+ String _markdownText = '';
+
+ // Only for debug. Enable by [enableDebug].
+ @visibleForTesting
+ final List<String> debugMarkdownTexts = [];
+
+ // The nodes inserted in the previous refresh.
+ Iterable<Node> _previousInsertedNodes = [];
+
+ /// Start the text robot.
+ ///
+ /// Must call this function before using the text robot.
+ void start() {
+ _startSelection = editorState.selection;
+
+ if (enableDebug) {
+ Log.info(
+ 'MarkdownTextRobot prepare, current selection: $_startSelection',
+ );
+ }
+ }
+
+ /// Append the markdown text to the text robot.
+ ///
+ /// The text will be inserted into document but not persisted until the text
+ /// robot is stopped.
+ Future<void> appendMarkdownText(String text) async {
+ _markdownText += text;
+
+ await lock.synchronized(() async {
+ await _refresh();
+ });
+
+ if (enableDebug) {
+ debugMarkdownTexts.add(text);
+ Log.info('debug markdown texts: ${jsonEncode(debugMarkdownTexts)}');
+ }
+ }
+
+ /// Stop the text robot.
+ ///
+ /// The text will be persisted into document.
+ Future<void> stop() async {
+ // persist the markdown text
+ await lock.synchronized(() async {
+ await _refresh(inMemoryUpdate: false);
+ });
+
+ _markdownText = '';
+
+ if (enableDebug) {
+ Log.info(
+ 'debug markdown texts: ${jsonEncode(debugMarkdownTexts)}',
+ );
+ debugMarkdownTexts.clear();
+ }
+ }
+
+ /// Refreshes the editor state with the current markdown text by:
+ ///
+ /// 1. Converting markdown to document nodes
+ /// 2. Replacing previously inserted nodes with new nodes
+ /// 3. Updating selection position
+ Future<void> _refresh({bool inMemoryUpdate = true}) async {
+ final start = _startSelection?.start;
+ if (start == null) {
+ return;
+ }
+
+ final transaction = editorState.transaction;
+
+ // Convert markdown and deep copy nodes
+ final nodes = markdownToDocument(_markdownText).root.children.map(
+ (node) => node.copyWith(),
+ ); // deep copy the nodes to avoid the linked entities being changed.
+
+ // Insert new nodes at selection start
+ transaction.insertNodes(start.path, nodes);
+
+ // Remove previously inserted nodes if they exist
+ if (_previousInsertedNodes.isNotEmpty) {
+ // fallback to the calculated position if the selection is null.
+ final end = editorState.selection?.end ??
+ Position(
+ path: start.path.nextNPath(_previousInsertedNodes.length - 1),
+ );
+ final deletedNodes = editorState.getNodesInSelection(
+ Selection(start: start, end: end),
+ );
+ transaction.deleteNodes(deletedNodes);
+ }
+
+ // Update selection to end of inserted content if it contains text
+ final lastDelta = nodes.lastOrNull?.delta;
+ if (lastDelta != null) {
+ transaction.afterSelection = Selection.collapsed(
+ Position(
+ path: start.path.nextNPath(nodes.length - 1),
+ offset: lastDelta.length,
+ ),
+ );
+ }
+
+ await editorState.apply(
+ transaction,
+ options: ApplyOptions(
+ inMemoryUpdate: inMemoryUpdate,
+ recordUndo: false,
+ ),
+ );
+
+ _previousInsertedNodes = nodes;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/util/ask_ai_node_extension.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/util/ask_ai_node_extension.dart
new file mode 100644
index 0000000000..9d696d7cfe
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/util/ask_ai_node_extension.dart
@@ -0,0 +1,67 @@
+import 'package:appflowy_editor/appflowy_editor.dart';
+
+extension AskAINodeExtension on EditorState {
+ String getMarkdownInSelection(Selection? selection) {
+ selection ??= this.selection?.normalized;
+ if (selection == null || selection.isCollapsed) {
+ return '';
+ }
+
+ // if the selected nodes are not entirely selected, slice the nodes
+ final slicedNodes = <Node>[];
+ final nodes = getNodesInSelection(selection);
+
+ for (final node in nodes) {
+ final delta = node.delta;
+ if (delta == null) {
+ continue;
+ }
+
+ final slicedDelta = delta.slice(
+ node == nodes.first ? selection.startIndex : 0,
+ node == nodes.last ? selection.endIndex : delta.length,
+ );
+
+ final copiedNode = node.copyWith(
+ attributes: {
+ ...node.attributes,
+ blockComponentDelta: slicedDelta.toJson(),
+ },
+ );
+
+ slicedNodes.add(copiedNode);
+ }
+
+ final markdown = documentToMarkdown(
+ Document.blank()..insert([0], slicedNodes),
+ );
+
+ return markdown;
+ }
+
+ List<String> getPlainTextInSelection(Selection? selection) {
+ selection ??= this.selection?.normalized;
+ if (selection == null || selection.isCollapsed) {
+ return [];
+ }
+
+ final res = <String>[];
+ if (selection.isCollapsed) {
+ return res;
+ }
+
+ final nodes = getNodesInSelection(selection);
+
+ for (final node in nodes) {
+ final delta = node.delta;
+ if (delta == null) {
+ continue;
+ }
+ final startIndex = node == nodes.first ? selection.startIndex : 0;
+ final endIndex = node == nodes.last ? selection.endIndex : delta.length;
+ res.add(delta.slice(startIndex, endIndex).toPlainText());
+ }
+
+ return res;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_component.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_component.dart
new file mode 100644
index 0000000000..49d58d9a61
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_component.dart
@@ -0,0 +1,370 @@
+import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:appflowy/plugins/document/application/prelude.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/base/build_context_extension.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_operations.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_widgets.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/discard_dialog.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart';
+import 'package:appflowy/user/application/ai_service.dart';
+import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flowy_infra_ui/flowy_infra_ui.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:universal_platform/universal_platform.dart';
+
+import 'ai_limit_dialog.dart';
+
+class AIWriterBlockKeys {
+ const AIWriterBlockKeys._();
+
+ static const String type = 'ai_writer';
+ static const String prompt = 'prompt';
+ static const String startSelection = 'start_selection';
+ static const String generationCount = 'generation_count';
+
+ static String getRewritePrompt(String previousOutput, String prompt) {
+ return 'I am not satisfied with your previous response ($previousOutput) to the query ($prompt). Please provide an alternative response.';
+ }
+}
+
+Node aiWriterNode({
+ String prompt = '',
+ required Selection start,
+}) {
+ return Node(
+ type: AIWriterBlockKeys.type,
+ attributes: {
+ AIWriterBlockKeys.prompt: prompt,
+ AIWriterBlockKeys.startSelection: start.toJson(),
+ AIWriterBlockKeys.generationCount: 0,
+ },
+ );
+}
+
+class AIWriterBlockComponentBuilder extends BlockComponentBuilder {
+ AIWriterBlockComponentBuilder();
+
+ @override
+ BlockComponentWidget build(BlockComponentContext blockComponentContext) {
+ final node = blockComponentContext.node;
+ return AIWriterBlockComponent(
+ key: node.key,
+ node: node,
+ showActions: showActions(node),
+ actionBuilder: (context, state) => actionBuilder(
+ blockComponentContext,
+ state,
+ ),
+ );
+ }
+
+ @override
+ BlockComponentValidate get validate => (node) =>
+ node.children.isEmpty &&
+ node.attributes[AIWriterBlockKeys.prompt] is String &&
+ node.attributes[AIWriterBlockKeys.startSelection] is Map;
+}
+
+class AIWriterBlockComponent extends BlockComponentStatefulWidget {
+ const AIWriterBlockComponent({
+ super.key,
+ required super.node,
+ super.showActions,
+ super.actionBuilder,
+ super.configuration = const BlockComponentConfiguration(),
+ });
+
+ @override
+ State<AIWriterBlockComponent> createState() => _AIWriterBlockComponentState();
+}
+
+class _AIWriterBlockComponentState extends State<AIWriterBlockComponent> {
+ final controller = TextEditingController();
+ final textFieldFocusNode = FocusNode();
+
+ late final editorState = context.read<EditorState>();
+ late final SelectionGestureInterceptor interceptor;
+ late final AIWriterBlockOperations aiWriterOperations =
+ AIWriterBlockOperations(
+ editorState: editorState,
+ aiWriterNode: widget.node,
+ );
+
+ String get prompt => widget.node.attributes[AIWriterBlockKeys.prompt];
+ int get generationCount =>
+ widget.node.attributes[AIWriterBlockKeys.generationCount] ?? 0;
+ Selection? get startSelection {
+ final selection = widget.node.attributes[AIWriterBlockKeys.startSelection];
+ if (selection != null) {
+ return Selection.fromJson(selection);
+ }
+ return null;
+ }
+
+ @override
+ void initState() {
+ super.initState();
+
+ _subscribeSelectionGesture();
+ WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
+ editorState.selection = null;
+ textFieldFocusNode.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ _onExit();
+ _unsubscribeSelectionGesture();
+ controller.dispose();
+ textFieldFocusNode.dispose();
+
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (UniversalPlatform.isMobile) {
+ return const SizedBox.shrink();
+ }
+
+ final child = Card(
+ elevation: 5,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(10),
+ ),
+ color: Theme.of(context).colorScheme.surface,
+ child: Container(
+ margin: const EdgeInsets.all(10),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const AIWriterBlockHeader(),
+ const Space(0, 10),
+ if (prompt.isEmpty && generationCount < 1) ...[
+ _buildInputWidget(context),
+ const Space(0, 10),
+ AIWriterBlockInputField(
+ onGenerate: _onGenerate,
+ onExit: _onExit,
+ ),
+ ] else ...[
+ AIWriterBlockFooter(
+ onKeep: _onExit,
+ onRewrite: _onRewrite,
+ onDiscard: _onDiscard,
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+
+ return Padding(
+ padding: const EdgeInsets.only(left: 40),
+ child: child,
+ );
+ }
+
+ Widget _buildInputWidget(BuildContext context) {
+ return FlowyTextField(
+ hintText: LocaleKeys.document_plugins_autoGeneratorHintText.tr(),
+ controller: controller,
+ maxLines: 5,
+ focusNode: textFieldFocusNode,
+ autoFocus: false,
+ hintTextConstraints: const BoxConstraints(),
+ );
+ }
+
+ Future<void> _onExit() async {
+ await aiWriterOperations.removeAIWriterNode(widget.node);
+ }
+
+ Future<void> _onGenerate() async {
+ await aiWriterOperations.updatePromptText(controller.text);
+
+ if (!_isAIWriterEnabled) {
+ Log.error('AI Writer is not enabled');
+ return;
+ }
+
+ final markdownTextRobot = MarkdownTextRobot(
+ editorState: editorState,
+ );
+
+ BarrierDialog? barrierDialog;
+
+ final aiRepository = AppFlowyAIService();
+ await aiRepository.streamCompletion(
+ text: controller.text,
+ completionType: CompletionTypePB.ContinueWriting,
+ onStart: () async {
+ if (mounted) {
+ barrierDialog = BarrierDialog(context);
+ barrierDialog?.show();
+ await aiWriterOperations.ensurePreviousNodeIsEmptyParagraphNode();
+ markdownTextRobot.start();
+ }
+ },
+ onProcess: (text) async {
+ await markdownTextRobot.appendMarkdownText(text);
+ },
+ onEnd: () async {
+ barrierDialog?.dismiss();
+ await markdownTextRobot.stop();
+ },
+ onError: (error) async {
+ barrierDialog?.dismiss();
+ _showAIWriterError(error);
+ },
+ );
+
+ await aiWriterOperations.updateGenerationCount(generationCount + 1);
+ }
+
+ Future<void> _onDiscard() async {
+ await aiWriterOperations.discardCurrentResponse(
+ aiWriterNode: widget.node,
+ selection: startSelection,
+ );
+ return _onExit();
+ }
+
+ Future<void> _onRewrite() async {
+ final previousOutput = _getPreviousOutput();
+ if (previousOutput == null) {
+ return;
+ }
+
+ // discard the current response
+ await aiWriterOperations.discardCurrentResponse(
+ aiWriterNode: widget.node,
+ selection: startSelection,
+ );
+
+ if (!_isAIWriterEnabled) {
+ return;
+ }
+
+ final markdownTextRobot = MarkdownTextRobot(
+ editorState: editorState,
+ );
+ final aiService = AppFlowyAIService();
+ await aiService.streamCompletion(
+ text: AIWriterBlockKeys.getRewritePrompt(previousOutput, prompt),
+ completionType: CompletionTypePB.ContinueWriting,
+ onStart: () async {
+ await aiWriterOperations.ensurePreviousNodeIsEmptyParagraphNode();
+
+ markdownTextRobot.start();
+ },
+ onProcess: (text) async {
+ await markdownTextRobot.appendMarkdownText(text);
+ },
+ onEnd: () async {
+ await markdownTextRobot.stop();
+ },
+ onError: (error) {
+ _showAIWriterError(error);
+ },
+ );
+
+ await aiWriterOperations.updateGenerationCount(generationCount + 1);
+ }
+
+ String? _getPreviousOutput() {
+ final startSelection = this.startSelection;
+ if (startSelection != null) {
+ final end = widget.node.previous?.path;
+
+ if (end != null) {
+ final result = editorState
+ .getNodesInSelection(
+ startSelection.copyWith(end: Position(path: end)),
+ )
+ .fold(
+ '',
+ (previousValue, element) {
+ final delta = element.delta;
+ if (delta != null) {
+ return "$previousValue\n${delta.toPlainText()}";
+ } else {
+ return previousValue;
+ }
+ },
+ );
+ return result.trim();
+ }
+ }
+ return null;
+ }
+
+ void _subscribeSelectionGesture() {
+ interceptor = SelectionGestureInterceptor(
+ key: AIWriterBlockKeys.type,
+ canTap: (details) {
+ if (!context.isOffsetInside(details.globalPosition)) {
+ if (prompt.isNotEmpty || controller.text.isNotEmpty) {
+ // show dialog
+ showDialog(
+ context: context,
+ builder: (_) => DiscardDialog(
+ onConfirm: _onDiscard,
+ onCancel: () {},
+ ),
+ );
+ } else if (controller.text.isEmpty) {
+ _onExit();
+ }
+ }
+ editorState.service.keyboardService?.disable();
+ return false;
+ },
+ );
+ editorState.service.selectionService.registerGestureInterceptor(
+ interceptor,
+ );
+ }
+
+ void _unsubscribeSelectionGesture() {
+ editorState.service.selectionService.unregisterGestureInterceptor(
+ AIWriterBlockKeys.type,
+ );
+ }
+
+ void _showAIWriterError(AIError error) {
+ if (mounted) {
+ if (error.isLimitExceeded) {
+ showAILimitDialog(context, error.message);
+ } else {
+ showToastNotification(
+ context,
+ message: error.message,
+ type: ToastificationType.error,
+ );
+ }
+ }
+ }
+
+ bool get _isAIWriterEnabled {
+ final userProfile = context.read<DocumentBloc>().state.userProfilePB;
+ final isAIWriterEnabled = userProfile != null;
+
+ if (!isAIWriterEnabled) {
+ showToastNotification(
+ context,
+ message: LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(),
+ type: ToastificationType.error,
+ );
+ }
+
+ return isAIWriterEnabled;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_operations.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_operations.dart
new file mode 100644
index 0000000000..08e242574f
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_operations.dart
@@ -0,0 +1,112 @@
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_component.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+
+/// Notes: All the operation related to the AI writer block will be applied
+/// in memory.
+class AIWriterBlockOperations {
+ AIWriterBlockOperations({
+ required this.editorState,
+ required this.aiWriterNode,
+ }) : assert(aiWriterNode.type == AIWriterBlockKeys.type);
+
+ final EditorState editorState;
+ final Node aiWriterNode;
+
+ /// Update the prompt text in the node.
+ Future<void> updatePromptText(String prompt) async {
+ final transaction = editorState.transaction;
+ transaction.updateNode(
+ aiWriterNode,
+ {AIWriterBlockKeys.prompt: prompt},
+ );
+ await editorState.apply(
+ transaction,
+ options: const ApplyOptions(
+ inMemoryUpdate: true,
+ recordUndo: false,
+ ),
+ );
+ }
+
+ /// Update the generation count in the node.
+ Future<void> updateGenerationCount(int count) async {
+ final transaction = editorState.transaction;
+ transaction.updateNode(
+ aiWriterNode,
+ {AIWriterBlockKeys.generationCount: count},
+ );
+ await editorState.apply(
+ transaction,
+ options: const ApplyOptions(inMemoryUpdate: true),
+ );
+ }
+
+ /// Ensure the previous node is a empty paragraph node without any styles.
+ Future<void> ensurePreviousNodeIsEmptyParagraphNode() async {
+ final previous = aiWriterNode.previous;
+ final Selection selection;
+
+ // 1. previous node is null or
+ // 2. previous node is not a paragraph node or
+ // 3. previous node is a paragraph node but not empty
+ final isNotEmptyParagraphNode = previous == null ||
+ previous.type != ParagraphBlockKeys.type ||
+ (previous.delta?.toPlainText().isNotEmpty ?? false);
+
+ if (isNotEmptyParagraphNode) {
+ final path = aiWriterNode.path;
+ final transaction = editorState.transaction;
+ selection = Selection.collapsed(Position(path: path));
+ transaction
+ ..insertNode(
+ path,
+ paragraphNode(),
+ )
+ ..afterSelection = selection;
+ await editorState.apply(transaction);
+ } else {
+ selection = Selection.collapsed(Position(path: previous.path));
+ }
+
+ final transaction = editorState.transaction;
+ transaction.updateNode(aiWriterNode, {
+ AIWriterBlockKeys.startSelection: selection.toJson(),
+ });
+ transaction.afterSelection = selection;
+ await editorState.apply(
+ transaction,
+ options: const ApplyOptions(inMemoryUpdate: true),
+ );
+ }
+
+ /// Discard the current response and delete the previous node.
+ Future<void> discardCurrentResponse({
+ required Node aiWriterNode,
+ Selection? selection,
+ }) async {
+ if (selection != null) {
+ final start = selection.start.path;
+ final end = aiWriterNode.previous?.path;
+ if (end != null) {
+ final transaction = editorState.transaction;
+ transaction.deleteNodesAtPath(
+ start,
+ end.last - start.last + 1,
+ );
+ await editorState.apply(transaction);
+ await ensurePreviousNodeIsEmptyParagraphNode();
+ }
+ }
+ }
+
+ /// Remove the ai writer node from the editor.
+ Future<void> removeAIWriterNode(Node aiWriterNode) async {
+ final transaction = editorState.transaction;
+ transaction.deleteNode(aiWriterNode);
+ await editorState.apply(
+ transaction,
+ options: const ApplyOptions(inMemoryUpdate: true, recordUndo: false),
+ withUpdateSelection: false,
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_widgets.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_widgets.dart
new file mode 100644
index 0000000000..b6681ed7fd
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_widgets.dart
@@ -0,0 +1,104 @@
+import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flowy_infra_ui/flowy_infra_ui.dart';
+import 'package:flutter/material.dart';
+
+class AIWriterBlockHeader extends StatelessWidget {
+ const AIWriterBlockHeader({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return FlowyText.medium(
+ LocaleKeys.document_plugins_autoGeneratorTitleName.tr(),
+ fontSize: 14,
+ );
+ }
+}
+
+class AIWriterBlockInputField extends StatelessWidget {
+ const AIWriterBlockInputField({
+ super.key,
+ required this.onGenerate,
+ required this.onExit,
+ });
+
+ final VoidCallback onGenerate;
+ final VoidCallback onExit;
+
+ @override
+ Widget build(BuildContext context) {
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ PrimaryRoundedButton(
+ text: LocaleKeys.button_generate.tr(),
+ margin: const EdgeInsets.symmetric(
+ horizontal: 16.0,
+ vertical: 10.0,
+ ),
+ radius: 8.0,
+ onTap: onGenerate,
+ ),
+ const Space(10, 0),
+ OutlinedRoundedButton(
+ text: LocaleKeys.button_cancel.tr(),
+ margin: const EdgeInsets.symmetric(
+ horizontal: 16.0,
+ vertical: 10.0,
+ ),
+ onTap: onExit,
+ ),
+ Flexible(
+ child: Container(
+ alignment: Alignment.centerRight,
+ child: FlowyText.regular(
+ LocaleKeys.document_plugins_warning.tr(),
+ color: Theme.of(context).hintColor,
+ overflow: TextOverflow.ellipsis,
+ fontSize: 12,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class AIWriterBlockFooter extends StatelessWidget {
+ const AIWriterBlockFooter({
+ super.key,
+ required this.onKeep,
+ required this.onRewrite,
+ required this.onDiscard,
+ });
+
+ final VoidCallback onKeep;
+ final VoidCallback onRewrite;
+ final VoidCallback onDiscard;
+
+ @override
+ Widget build(BuildContext context) {
+ return Row(
+ children: [
+ PrimaryRoundedButton(
+ text: LocaleKeys.button_keep.tr(),
+ margin: const EdgeInsets.symmetric(
+ horizontal: 16.0,
+ vertical: 9.0,
+ ),
+ onTap: onKeep,
+ ),
+ const HSpace(10),
+ OutlinedRoundedButton(
+ text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),
+ onTap: onRewrite,
+ ),
+ const HSpace(10),
+ OutlinedRoundedButton(
+ text: LocaleKeys.button_discard.tr(),
+ onTap: onDiscard,
+ ),
+ ],
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart
similarity index 59%
rename from frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart
rename to frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart
index 70affa002a..d47c26d655 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart
@@ -1,9 +1,9 @@
-import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
-import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:easy_localization/easy_localization.dart';
+import 'package:flutter/material.dart';
-enum SmartEditAction {
+enum AskAIAction {
summarize,
fixSpelling,
improveWriting,
@@ -11,62 +11,62 @@ enum SmartEditAction {
String get toInstruction {
switch (this) {
- case SmartEditAction.summarize:
+ case AskAIAction.summarize:
return 'Tl;dr';
- case SmartEditAction.fixSpelling:
+ case AskAIAction.fixSpelling:
return 'Correct this to standard English:';
- case SmartEditAction.improveWriting:
+ case AskAIAction.improveWriting:
return 'Rewrite this in your own words:';
- case SmartEditAction.makeItLonger:
+ case AskAIAction.makeItLonger:
return 'Make this text longer:';
}
}
String prompt(String input) {
switch (this) {
- case SmartEditAction.summarize:
+ case AskAIAction.summarize:
return '$input\n\nTl;dr';
- case SmartEditAction.fixSpelling:
+ case AskAIAction.fixSpelling:
return 'Correct this to standard English:\n\n$input';
- case SmartEditAction.improveWriting:
+ case AskAIAction.improveWriting:
return 'Rewrite this:\n\n$input';
- case SmartEditAction.makeItLonger:
+ case AskAIAction.makeItLonger:
return 'Make this text longer:\n\n$input';
}
}
- static SmartEditAction from(int index) {
+ static AskAIAction from(int index) {
switch (index) {
case 0:
- return SmartEditAction.summarize;
+ return AskAIAction.summarize;
case 1:
- return SmartEditAction.fixSpelling;
+ return AskAIAction.fixSpelling;
case 2:
- return SmartEditAction.improveWriting;
+ return AskAIAction.improveWriting;
case 3:
- return SmartEditAction.makeItLonger;
+ return AskAIAction.makeItLonger;
}
- return SmartEditAction.fixSpelling;
+ return AskAIAction.fixSpelling;
}
String get name {
switch (this) {
- case SmartEditAction.summarize:
+ case AskAIAction.summarize:
return LocaleKeys.document_plugins_smartEditSummarize.tr();
- case SmartEditAction.fixSpelling:
+ case AskAIAction.fixSpelling:
return LocaleKeys.document_plugins_smartEditFixSpelling.tr();
- case SmartEditAction.improveWriting:
+ case AskAIAction.improveWriting:
return LocaleKeys.document_plugins_smartEditImproveWriting.tr();
- case SmartEditAction.makeItLonger:
+ case AskAIAction.makeItLonger:
return LocaleKeys.document_plugins_smartEditMakeLonger.tr();
}
}
}
-class SmartEditActionWrapper extends ActionCell {
- SmartEditActionWrapper(this.inner);
+class AskAIActionWrapper extends ActionCell {
+ AskAIActionWrapper(this.inner);
- final SmartEditAction inner;
+ final AskAIAction inner;
Widget? icon(Color iconColor) => null;
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart
similarity index 65%
rename from frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart
rename to frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart
index bf78c1e4eb..24e864f6b8 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart
@@ -2,27 +2,33 @@ import 'dart:async';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/user/application/ai_service.dart';
import 'package:appflowy_backend/log.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';
-part 'smart_edit_bloc.freezed.dart';
+part 'ask_ai_action_bloc.freezed.dart';
-class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
- SmartEditBloc({
+enum AskAIReplacementType {
+ markdown,
+ plainText,
+}
+
+const _defaultReplacementType = AskAIReplacementType.markdown;
+
+class AskAIActionBloc extends Bloc<AskAIEvent, AskAIState> {
+ AskAIActionBloc({
required this.node,
required this.editorState,
required this.action,
this.enableLogging = true,
}) : super(
- SmartEditState.initial(action),
+ AskAIState.initial(action),
) {
- on<SmartEditEvent>((event, emit) async {
+ on<AskAIEvent>((event, emit) async {
await event.when(
initial: (aiRepositoryProvider) async {
aiRepository = await aiRepositoryProvider;
@@ -61,7 +67,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
final Node node;
final EditorState editorState;
- final SmartEditAction action;
+ final AskAIAction action;
final bool enableLogging;
// used to wait for the aiRepository to be initialized
final aiRepositoryCompleter = Completer();
@@ -75,14 +81,14 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
await aiRepositoryCompleter.future;
if (rewrite) {
- add(const SmartEditEvent.update('', true, null));
+ add(const AskAIEvent.update('', true, null));
}
if (enableLogging) {
Log.info('[smart_edit] request completions');
}
- final content = node.attributes[SmartEditBlockKeys.content] as String;
+ final content = node.attributes[AskAIBlockKeys.content] as String;
await aiRepository.streamCompletion(
text: content,
completionType: completionTypeFromInt(state.action),
@@ -93,7 +99,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (enableLogging) {
Log.info('[smart_edit] start generating');
}
- add(const SmartEditEvent.update('', true, null));
+ add(const AskAIEvent.update('', true, null));
},
onProcess: (text) async {
if (isCanceled) {
@@ -104,7 +110,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
Log.debug('[smart_edit] onProcess: $text');
}
final newResult = state.result + text;
- add(SmartEditEvent.update(newResult, false, null));
+ add(AskAIEvent.update(newResult, false, null));
},
onEnd: () async {
if (isCanceled) {
@@ -113,7 +119,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (enableLogging) {
Log.info('[smart_edit] end generating');
}
- add(SmartEditEvent.update('${state.result}\n', false, null));
+ add(AskAIEvent.update('${state.result}\n', false, null));
},
onError: (error) async {
if (isCanceled) {
@@ -122,7 +128,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (enableLogging) {
Log.info('[smart_edit] onError: $error');
}
- add(SmartEditEvent.update('', false, error));
+ add(AskAIEvent.update('', false, error));
await _exit();
await _clearSelection();
},
@@ -135,35 +141,70 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (selection == null) {
return;
}
- // return if the result is empty
- final result = state.result.trim();
- if (result.isEmpty) {
- return;
- }
- final insertedText = result.split('\n')
- ..removeWhere((element) => element.isEmpty);
+ final nodes = markdownToDocument(state.result)
+ .root
+ .children
+ .map((e) => e.copyWith())
+ .toList();
+ final insertedPath = selection.end.path.next;
final transaction = editorState.transaction;
- // todo: keep the style of the current node
transaction.insertNodes(
- selection.end.path.next,
- insertedText.map(
- (e) => paragraphNode(
- text: e,
- ),
+ insertedPath,
+ nodes,
+ );
+ final lastDeltaLength = nodes.lastOrNull?.delta?.length ?? 0;
+ transaction.afterSelection = Selection(
+ start: Position(path: insertedPath),
+ end: Position(
+ path: insertedPath.nextNPath(nodes.length - 1),
+ offset: lastDeltaLength,
),
);
- final start = Position(path: selection.end.path.next);
- final end = Position(
- path: [selection.end.path.next.first + insertedText.length],
+ await editorState.apply(transaction);
+ }
+
+ Future<void> _replace() async {
+ switch (_defaultReplacementType) {
+ case AskAIReplacementType.markdown:
+ await _replaceWithMarkdown();
+ case AskAIReplacementType.plainText:
+ await _replaceWithPlainText();
+ }
+ }
+
+ Future<void> _replaceWithMarkdown() async {
+ final selection = editorState.selection?.normalized;
+ if (selection == null) {
+ return;
+ }
+
+ final nodes = markdownToDocument(state.result)
+ .root
+ .children
+ .map((e) => e.copyWith())
+ .toList();
+ if (nodes.isEmpty) {
+ return;
+ }
+
+ final nodesInSelection = editorState.getNodesInSelection(selection);
+ final transaction = editorState.transaction;
+ transaction.insertNodes(
+ selection.start.path,
+ nodes,
);
+ transaction.deleteNodes(nodesInSelection);
transaction.afterSelection = Selection(
- start: start,
- end: end,
+ start: selection.start,
+ end: Position(
+ path: selection.start.path.nextNPath(nodes.length - 1),
+ offset: nodes.lastOrNull?.delta?.length ?? 0,
+ ),
);
await editorState.apply(transaction);
}
- Future<void> _replace() async {
+ Future<void> _replaceWithPlainText() async {
final result = state.result.trim();
if (result.isEmpty) {
return;
@@ -222,16 +263,16 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
}
@freezed
-class SmartEditEvent with _$SmartEditEvent {
- const factory SmartEditEvent.initial(
+class AskAIEvent with _$AskAIEvent {
+ const factory AskAIEvent.initial(
Future<AIRepository> aiRepositoryProvider,
) = _Initial;
- const factory SmartEditEvent.started() = _Started;
- const factory SmartEditEvent.rewrite() = _Rewrite;
- const factory SmartEditEvent.replace() = _Replace;
- const factory SmartEditEvent.insertBelow() = _InsertBelow;
- const factory SmartEditEvent.cancel() = _Cancel;
- const factory SmartEditEvent.update(
+ const factory AskAIEvent.started() = _Started;
+ const factory AskAIEvent.rewrite() = _Rewrite;
+ const factory AskAIEvent.replace() = _Replace;
+ const factory AskAIEvent.insertBelow() = _InsertBelow;
+ const factory AskAIEvent.cancel() = _Cancel;
+ const factory AskAIEvent.update(
String result,
bool isLoading,
AIError? error,
@@ -239,15 +280,15 @@ class SmartEditEvent with _$SmartEditEvent {
}
@freezed
-class SmartEditState with _$SmartEditState {
- const factory SmartEditState({
+class AskAIState with _$AskAIState {
+ const factory AskAIState({
required bool loading,
required String result,
- required SmartEditAction action,
+ required AskAIAction action,
@Default(null) AIError? requestError,
- }) = _SmartEditState;
+ }) = _AskAIState;
- factory SmartEditState.initial(SmartEditAction action) => SmartEditState(
+ factory AskAIState.initial(AskAIAction action) => AskAIState(
loading: true,
action: action,
result: '',
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart
similarity index 50%
rename from frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart
rename to frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart
index 9f7d3a5199..7babb48ba5 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart
@@ -4,8 +4,9 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_limit_dialog.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_widgets.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -15,14 +16,14 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:universal_platform/universal_platform.dart';
-class SmartEditBlockKeys {
- const SmartEditBlockKeys._();
+class AskAIBlockKeys {
+ const AskAIBlockKeys._();
- static const type = 'smart_edit';
+ static const type = 'ask_ai';
/// The instruction of the smart edit.
///
- /// It is a [SmartEditAction] value.
+ /// It is a [AskAIAction] value.
static const action = 'action';
/// The input of the smart edit.
@@ -31,26 +32,26 @@ class SmartEditBlockKeys {
static const content = 'content';
}
-Node smartEditNode({
- required SmartEditAction action,
+Node askAINode({
+ required AskAIAction action,
required String content,
}) {
return Node(
- type: SmartEditBlockKeys.type,
+ type: AskAIBlockKeys.type,
attributes: {
- SmartEditBlockKeys.action: action.index,
- SmartEditBlockKeys.content: content,
+ AskAIBlockKeys.action: action.index,
+ AskAIBlockKeys.content: content,
},
);
}
-class SmartEditBlockComponentBuilder extends BlockComponentBuilder {
- SmartEditBlockComponentBuilder();
+class AskAIBlockComponentBuilder extends BlockComponentBuilder {
+ AskAIBlockComponentBuilder();
@override
BlockComponentWidget build(BlockComponentContext blockComponentContext) {
final node = blockComponentContext.node;
- return SmartEditBlockComponentWidget(
+ return AskAIBlockComponentWidget(
key: node.key,
node: node,
showActions: showActions(node),
@@ -63,12 +64,12 @@ class SmartEditBlockComponentBuilder extends BlockComponentBuilder {
@override
BlockComponentValidate get validate => (node) =>
- node.attributes[SmartEditBlockKeys.action] is int &&
- node.attributes[SmartEditBlockKeys.content] is String;
+ node.attributes[AskAIBlockKeys.action] is int &&
+ node.attributes[AskAIBlockKeys.content] is String;
}
-class SmartEditBlockComponentWidget extends BlockComponentStatefulWidget {
- const SmartEditBlockComponentWidget({
+class AskAIBlockComponentWidget extends BlockComponentStatefulWidget {
+ const AskAIBlockComponentWidget({
super.key,
required super.node,
super.showActions,
@@ -77,18 +78,17 @@ class SmartEditBlockComponentWidget extends BlockComponentStatefulWidget {
});
@override
- State<SmartEditBlockComponentWidget> createState() =>
- _SmartEditBlockComponentWidgetState();
+ State<AskAIBlockComponentWidget> createState() =>
+ _AskAIBlockComponentWidgetState();
}
-class _SmartEditBlockComponentWidgetState
- extends State<SmartEditBlockComponentWidget> {
+class _AskAIBlockComponentWidgetState extends State<AskAIBlockComponentWidget> {
final popoverController = PopoverController();
late final editorState = context.read<EditorState>();
- late final action = SmartEditAction
- .values[widget.node.attributes[SmartEditBlockKeys.action] as int];
- late SmartEditBloc smartEditBloc;
+ late final action =
+ AskAIAction.values[widget.node.attributes[AskAIBlockKeys.action] as int];
+ late AskAIActionBloc askAIBloc;
@override
void initState() {
@@ -98,16 +98,16 @@ class _SmartEditBlockComponentWidgetState
popoverController.show();
});
- smartEditBloc = SmartEditBloc(
+ askAIBloc = AskAIActionBloc(
node: widget.node,
editorState: editorState,
action: action,
- )..add(SmartEditEvent.initial(getIt.getAsync<AIRepository>()));
+ )..add(AskAIEvent.initial(getIt.getAsync<AIRepository>()));
}
@override
void dispose() {
- smartEditBloc.close();
+ askAIBloc.close();
super.dispose();
}
@@ -128,8 +128,8 @@ class _SmartEditBlockComponentWidgetState
final width = _getEditorWidth();
return BlocProvider.value(
- value: smartEditBloc,
- child: BlocListener<SmartEditBloc, SmartEditState>(
+ value: askAIBloc,
+ child: BlocListener<AskAIActionBloc, AskAIState>(
listener: _onListen,
child: AppFlowyPopover(
controller: popoverController,
@@ -141,7 +141,7 @@ class _SmartEditBlockComponentWidgetState
constraints: BoxConstraints(maxWidth: width),
canClose: () async {
final completer = Completer<bool>();
- final state = smartEditBloc.state;
+ final state = askAIBloc.state;
if (state.result.isEmpty) {
completer.complete(true);
} else {
@@ -160,8 +160,8 @@ class _SmartEditBlockComponentWidgetState
popupBuilder: (BuildContext popoverContext) {
return BlocProvider.value(
// request the result when opening the popover
- value: smartEditBloc..add(const SmartEditEvent.started()),
- child: const SmartEditInputContent(),
+ value: askAIBloc..add(const AskAIEvent.started()),
+ child: const AskAiInputContent(),
);
},
child: const SizedBox(
@@ -191,7 +191,7 @@ class _SmartEditBlockComponentWidgetState
editorState.apply(transaction);
}
- void _onListen(BuildContext context, SmartEditState state) {
+ void _onListen(BuildContext context, AskAIState state) {
final error = state.requestError;
if (error != null) {
if (error.isLimitExceeded) {
@@ -206,110 +206,3 @@ class _SmartEditBlockComponentWidgetState
}
}
}
-
-class SmartEditInputContent extends StatelessWidget {
- const SmartEditInputContent({super.key});
-
- @override
- Widget build(BuildContext context) {
- return BlocBuilder<SmartEditBloc, SmartEditState>(
- builder: (context, state) {
- return Card(
- elevation: 5,
- color: Theme.of(context).colorScheme.surface,
- margin: EdgeInsets.zero,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(10),
- ),
- child: Container(
- margin: const EdgeInsets.all(16),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- FlowyText.medium(
- state.action.name,
- fontSize: 14,
- ),
- const VSpace(16),
- state.loading
- ? _buildLoadingWidget(context)
- : _buildResultWidget(context, state),
- const VSpace(16),
- const _SmartEditFooterWidget(),
- ],
- ),
- ),
- );
- },
- );
- }
-
- Widget _buildResultWidget(BuildContext context, SmartEditState state) {
- // todo: replace it with appflowy_editor
- return Flexible(
- child: FlowyText.regular(
- state.result,
- maxLines: null,
- ),
- );
- }
-
- Widget _buildLoadingWidget(BuildContext context) {
- return const Padding(
- padding: EdgeInsets.symmetric(horizontal: 4.0),
- child: SizedBox.square(
- dimension: 14,
- child: CircularProgressIndicator(
- strokeWidth: 2.0,
- ),
- ),
- );
- }
-}
-
-class _SmartEditFooterWidget extends StatelessWidget {
- const _SmartEditFooterWidget();
-
- @override
- Widget build(BuildContext context) {
- return Row(
- children: [
- OutlinedRoundedButton(
- text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),
- onTap: () =>
- context.read<SmartEditBloc>().add(const SmartEditEvent.rewrite()),
- ),
- const HSpace(10),
- OutlinedRoundedButton(
- text: LocaleKeys.button_replace.tr(),
- onTap: () =>
- context.read<SmartEditBloc>().add(const SmartEditEvent.replace()),
- ),
- const HSpace(10),
- OutlinedRoundedButton(
- text: LocaleKeys.button_insertBelow.tr(),
- onTap: () => context
- .read<SmartEditBloc>()
- .add(const SmartEditEvent.insertBelow()),
- ),
- const HSpace(10),
- OutlinedRoundedButton(
- text: LocaleKeys.button_cancel.tr(),
- onTap: () =>
- context.read<SmartEditBloc>().add(const SmartEditEvent.cancel()),
- ),
- Expanded(
- child: Container(
- alignment: Alignment.centerRight,
- child: Text(
- LocaleKeys.document_plugins_warning.tr(),
- style: TextStyle(color: Theme.of(context).hintColor),
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ),
- ],
- );
- }
-}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_widgets.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_widgets.dart
new file mode 100644
index 0000000000..5c70f774ed
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_widgets.dart
@@ -0,0 +1,112 @@
+import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/message/ai_markdown_text.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flowy_infra_ui/flowy_infra_ui.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+
+class AskAiInputContent extends StatelessWidget {
+ const AskAiInputContent({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return BlocBuilder<AskAIActionBloc, AskAIState>(
+ builder: (context, state) {
+ return Card(
+ elevation: 5,
+ color: Theme.of(context).colorScheme.surface,
+ margin: EdgeInsets.zero,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Container(
+ margin: const EdgeInsets.all(16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ FlowyText.medium(
+ state.action.name,
+ fontSize: 14,
+ ),
+ const VSpace(16),
+ state.loading
+ ? _buildLoadingWidget(context)
+ : _buildResultWidget(context, state),
+ const VSpace(16),
+ const AskAIFooter(),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildResultWidget(BuildContext context, AskAIState state) {
+ return Flexible(
+ child: AIMarkdownText(
+ markdown: state.result,
+ ),
+ );
+ }
+
+ Widget _buildLoadingWidget(BuildContext context) {
+ return const Padding(
+ padding: EdgeInsets.symmetric(horizontal: 4.0),
+ child: SizedBox.square(
+ dimension: 14,
+ child: CircularProgressIndicator(
+ strokeWidth: 2.0,
+ ),
+ ),
+ );
+ }
+}
+
+class AskAIFooter extends StatelessWidget {
+ const AskAIFooter({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return Row(
+ children: [
+ OutlinedRoundedButton(
+ text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),
+ onTap: () =>
+ context.read<AskAIActionBloc>().add(const AskAIEvent.rewrite()),
+ ),
+ const HSpace(10),
+ OutlinedRoundedButton(
+ text: LocaleKeys.button_replace.tr(),
+ onTap: () =>
+ context.read<AskAIActionBloc>().add(const AskAIEvent.replace()),
+ ),
+ const HSpace(10),
+ OutlinedRoundedButton(
+ text: LocaleKeys.button_insertBelow.tr(),
+ onTap: () => context
+ .read<AskAIActionBloc>()
+ .add(const AskAIEvent.insertBelow()),
+ ),
+ const HSpace(10),
+ OutlinedRoundedButton(
+ text: LocaleKeys.button_cancel.tr(),
+ onTap: () =>
+ context.read<AskAIActionBloc>().add(const AskAIEvent.cancel()),
+ ),
+ Expanded(
+ child: Container(
+ alignment: Alignment.centerRight,
+ child: Text(
+ LocaleKeys.document_plugins_warning.tr(),
+ style: TextStyle(color: Theme.of(context).hintColor),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_toolbar_item.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_toolbar_item.dart
similarity index 65%
rename from frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_toolbar_item.dart
rename to frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_toolbar_item.dart
index c37458c25d..232b5872a6 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_toolbar_item.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_toolbar_item.dart
@@ -1,8 +1,9 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/util/ask_ai_node_extension.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -11,20 +12,20 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
-const _kSmartEditToolbarItemId = 'appflowy.editor.smart_edit';
+const _kAskAIToolbarItemId = 'appflowy.editor.ask_ai';
-final ToolbarItem smartEditItem = ToolbarItem(
- id: _kSmartEditToolbarItemId,
+final ToolbarItem askAIItem = ToolbarItem(
+ id: _kAskAIToolbarItemId,
group: 0,
isActive: onlyShowInSingleSelectionAndTextType,
- builder: (context, editorState, _, __, tooltipBuilder) => SmartEditActionList(
+ builder: (context, editorState, _, __, tooltipBuilder) => AskAIActionList(
editorState: editorState,
tooltipBuilder: tooltipBuilder,
),
);
-class SmartEditActionList extends StatefulWidget {
- const SmartEditActionList({
+class AskAIActionList extends StatefulWidget {
+ const AskAIActionList({
super.key,
required this.editorState,
this.tooltipBuilder,
@@ -34,25 +35,28 @@ class SmartEditActionList extends StatefulWidget {
final ToolbarTooltipBuilder? tooltipBuilder;
@override
- State<SmartEditActionList> createState() => _SmartEditActionListState();
+ State<AskAIActionList> createState() => _AskAIActionListState();
}
-class _SmartEditActionListState extends State<SmartEditActionList> {
+class _AskAIActionListState extends State<AskAIActionList> {
bool isAIEnabled = true;
+ EditorState get editorState => widget.editorState;
+
@override
void initState() {
super.initState();
+
isAIEnabled = _isAIEnabled();
}
@override
Widget build(BuildContext context) {
- return PopoverActionList<SmartEditActionWrapper>(
+ return PopoverActionList<AskAIActionWrapper>(
offset: const Offset(-5, 5),
direction: PopoverDirection.bottomWithLeftAligned,
- actions: SmartEditAction.values
- .map((action) => SmartEditActionWrapper(action))
+ actions: AskAIAction.values
+ .map((action) => AskAIActionWrapper(action))
.toList(),
onClosed: () => keepEditorFocusNotifier.decrease(),
buildChild: (controller) {
@@ -88,7 +92,7 @@ class _SmartEditActionListState extends State<SmartEditActionList> {
if (widget.tooltipBuilder != null) {
return widget.tooltipBuilder!(
context,
- _kSmartEditToolbarItemId,
+ _kAskAIToolbarItemId,
isAIEnabled
? LocaleKeys.document_plugins_smartEdit.tr()
: LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),
@@ -100,59 +104,39 @@ class _SmartEditActionListState extends State<SmartEditActionList> {
},
onSelected: (action, controller) {
controller.close();
- _insertSmartEditNode(action);
+ _insertAskAINode(action);
},
);
}
- Future<void> _insertSmartEditNode(
- SmartEditActionWrapper actionWrapper,
+ Future<void> _insertAskAINode(
+ AskAIActionWrapper actionWrapper,
) async {
- final selection = widget.editorState.selection?.normalized;
+ final selection = editorState.selection?.normalized;
if (selection == null) {
return;
}
- // support multiple paragraphs
- final input = _getTextInSelection(selection);
+ final markdown = editorState.getMarkdownInSelection(selection);
- final transaction = widget.editorState.transaction;
+ final transaction = editorState.transaction;
transaction.insertNode(
selection.normalized.end.path.next,
- smartEditNode(
+ askAINode(
action: actionWrapper.inner,
- content: input.join('\n\n'),
+ content: markdown,
),
);
- await widget.editorState.apply(
+ await editorState.apply(
transaction,
options: const ApplyOptions(
recordUndo: false,
+ inMemoryUpdate: true,
),
withUpdateSelection: false,
);
}
- List<String> _getTextInSelection(
- Selection selection,
- ) {
- final res = <String>[];
- if (selection.isCollapsed) {
- return res;
- }
- final nodes = widget.editorState.getNodesInSelection(selection);
- for (final node in nodes) {
- final delta = node.delta;
- if (delta == null) {
- continue;
- }
- final startIndex = node == nodes.first ? selection.startIndex : 0;
- final endIndex = node == nodes.last ? selection.endIndex : delta.length;
- res.add(delta.slice(startIndex, endIndex).toPlainText());
- }
- return res;
- }
-
bool _isAIEnabled() {
final documentContext = widget.editorState.document.root.context;
if (documentContext == null) {
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/auto_completion_node_widget.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/auto_completion_node_widget.dart
deleted file mode 100644
index b297a93c46..0000000000
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/auto_completion_node_widget.dart
+++ /dev/null
@@ -1,566 +0,0 @@
-import 'package:appflowy/generated/flowy_svgs.g.dart';
-import 'package:appflowy/generated/locale_keys.g.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/base/build_context_extension.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/base/selectable_svg_widget.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/base/text_robot.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/discard_dialog.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart';
-import 'package:appflowy/user/application/ai_service.dart';
-import 'package:appflowy/user/application/user_service.dart';
-import 'package:appflowy/workspace/presentation/home/toast.dart';
-import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
-import 'package:appflowy_editor/appflowy_editor.dart';
-import 'package:easy_localization/easy_localization.dart';
-import 'package:flowy_infra_ui/flowy_infra_ui.dart';
-import 'package:flutter/material.dart';
-import 'package:provider/provider.dart';
-import 'package:universal_platform/universal_platform.dart';
-
-import 'ai_limit_dialog.dart';
-
-class AutoCompletionBlockKeys {
- const AutoCompletionBlockKeys._();
-
- static const String type = 'auto_completion';
- static const String prompt = 'prompt';
- static const String startSelection = 'start_selection';
- static const String generationCount = 'generation_count';
-}
-
-Node autoCompletionNode({
- String prompt = '',
- required Selection start,
-}) {
- return Node(
- type: AutoCompletionBlockKeys.type,
- attributes: {
- AutoCompletionBlockKeys.prompt: prompt,
- AutoCompletionBlockKeys.startSelection: start.toJson(),
- AutoCompletionBlockKeys.generationCount: 0,
- },
- );
-}
-
-SelectionMenuItem autoGeneratorMenuItem = SelectionMenuItem.node(
- getName: LocaleKeys.document_plugins_autoGeneratorMenuItemName.tr,
- iconBuilder: (editorState, onSelected, style) => SelectableSvgWidget(
- data: FlowySvgs.menu_item_ai_writer_s,
- isSelected: onSelected,
- style: style,
- ),
- keywords: ['ai', 'openai', 'writer', 'ai writer', 'autogenerator'],
- nodeBuilder: (editorState, _) {
- final node = autoCompletionNode(start: editorState.selection!);
- return node;
- },
- replace: (_, node) => false,
-);
-
-class AutoCompletionBlockComponentBuilder extends BlockComponentBuilder {
- AutoCompletionBlockComponentBuilder();
-
- @override
- BlockComponentWidget build(BlockComponentContext blockComponentContext) {
- final node = blockComponentContext.node;
- return AutoCompletionBlockComponent(
- key: node.key,
- node: node,
- showActions: showActions(node),
- actionBuilder: (context, state) => actionBuilder(
- blockComponentContext,
- state,
- ),
- );
- }
-
- @override
- BlockComponentValidate get validate => (node) =>
- node.children.isEmpty &&
- node.attributes[AutoCompletionBlockKeys.prompt] is String &&
- node.attributes[AutoCompletionBlockKeys.startSelection] is Map;
-}
-
-class AutoCompletionBlockComponent extends BlockComponentStatefulWidget {
- const AutoCompletionBlockComponent({
- super.key,
- required super.node,
- super.showActions,
- super.actionBuilder,
- super.configuration = const BlockComponentConfiguration(),
- });
-
- @override
- State<AutoCompletionBlockComponent> createState() =>
- _AutoCompletionBlockComponentState();
-}
-
-class _AutoCompletionBlockComponentState
- extends State<AutoCompletionBlockComponent> {
- final controller = TextEditingController();
- final textFieldFocusNode = FocusNode();
-
- late final editorState = context.read<EditorState>();
- late final SelectionGestureInterceptor interceptor;
-
- String get prompt => widget.node.attributes[AutoCompletionBlockKeys.prompt];
- int get generationCount =>
- widget.node.attributes[AutoCompletionBlockKeys.generationCount] ?? 0;
- Selection? get startSelection {
- final selection =
- widget.node.attributes[AutoCompletionBlockKeys.startSelection];
- if (selection != null) {
- return Selection.fromJson(selection);
- }
- return null;
- }
-
- @override
- void initState() {
- super.initState();
-
- _subscribeSelectionGesture();
- WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
- editorState.selection = null;
- textFieldFocusNode.requestFocus();
- });
- }
-
- @override
- void dispose() {
- _onExit();
- _unsubscribeSelectionGesture();
- controller.dispose();
- textFieldFocusNode.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- if (UniversalPlatform.isMobile) {
- return const SizedBox.shrink();
- }
-
- final child = Card(
- elevation: 5,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(10),
- ),
- color: Theme.of(context).colorScheme.surface,
- child: Container(
- margin: const EdgeInsets.all(10),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- const AutoCompletionHeader(),
- const Space(0, 10),
- if (prompt.isEmpty && generationCount < 1) ...[
- _buildInputWidget(context),
- const Space(0, 10),
- AutoCompletionInputFooter(
- onGenerate: _onGenerate,
- onExit: _onExit,
- ),
- ] else ...[
- AutoCompletionFooter(
- onKeep: _onExit,
- onRewrite: _onRewrite,
- onDiscard: _onDiscard,
- ),
- ],
- ],
- ),
- ),
- );
-
- return Padding(
- padding: const EdgeInsets.only(left: 40),
- child: child,
- );
- }
-
- Widget _buildInputWidget(BuildContext context) {
- return FlowyTextField(
- hintText: LocaleKeys.document_plugins_autoGeneratorHintText.tr(),
- controller: controller,
- maxLines: 5,
- focusNode: textFieldFocusNode,
- autoFocus: false,
- hintTextConstraints: const BoxConstraints(),
- );
- }
-
- Future<void> _onExit() async {
- final transaction = editorState.transaction..deleteNode(widget.node);
- await editorState.apply(
- transaction,
- options: const ApplyOptions(recordUndo: false, inMemoryUpdate: true),
- withUpdateSelection: false,
- );
- }
-
- Future<void> _onGenerate() async {
- await _updateEditingText();
-
- final userProfile = await UserBackendService.getCurrentUserProfile()
- .then((value) => value.toNullable());
- if (userProfile == null) {
- if (mounted) {
- showSnackBarMessage(
- context,
- LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(),
- showCancel: true,
- );
- }
- return;
- }
-
- final textRobot = TextRobot(editorState: editorState);
- BarrierDialog? barrierDialog;
- final aiRepository = AppFlowyAIService();
- await aiRepository.streamCompletion(
- text: controller.text,
- completionType: CompletionTypePB.ContinueWriting,
- onStart: () async {
- if (mounted) {
- barrierDialog = BarrierDialog(context);
- barrierDialog?.show();
- await _makeSurePreviousNodeIsEmptyParagraphNode();
- }
- },
- onProcess: (text) async {
- await textRobot.autoInsertTextSync(
- text,
- separator: r'\n\n',
- inputType: TextRobotInputType.sentence,
- delay: Duration.zero,
- );
- },
- onEnd: () async {
- barrierDialog?.dismiss();
- },
- onError: (error) async {
- barrierDialog?.dismiss();
- if (mounted) {
- if (error.isLimitExceeded) {
- showAILimitDialog(context, error.message);
- await _onDiscard();
- } else {
- showSnackBarMessage(
- context,
- error.message,
- showCancel: true,
- );
- }
- }
- },
- );
- await _updateGenerationCount();
- }
-
- Future<void> _onDiscard() async {
- final selection = startSelection;
- if (selection != null) {
- final start = selection.start.path;
- final end = widget.node.previous?.path;
- if (end != null) {
- final transaction = editorState.transaction;
- transaction.deleteNodesAtPath(
- start,
- end.last - start.last + 1,
- );
- await editorState.apply(transaction);
- await _makeSurePreviousNodeIsEmptyParagraphNode();
- }
- }
- return _onExit();
- }
-
- Future<void> _onRewrite() async {
- final previousOutput = _getPreviousOutput();
- if (previousOutput == null) {
- return;
- }
-
- // clear previous response
- final selection = startSelection;
- if (selection != null) {
- final start = selection.start.path;
- final end = widget.node.previous?.path;
- if (end != null) {
- final transaction = editorState.transaction;
- transaction.deleteNodesAtPath(
- start,
- end.last - start.last + 1,
- );
- await editorState.apply(transaction);
- }
- }
- // generate new response
- final userProfile = await UserBackendService.getCurrentUserProfile()
- .then((value) => value.toNullable());
- if (userProfile == null) {
- if (mounted) {
- showSnackBarMessage(
- context,
- LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(),
- showCancel: true,
- );
- }
- return;
- }
- final textRobot = TextRobot(editorState: editorState);
- final aiService = AppFlowyAIService();
- await aiService.streamCompletion(
- text: _rewritePrompt(previousOutput),
- completionType: CompletionTypePB.ContinueWriting,
- onStart: () async {
- await _makeSurePreviousNodeIsEmptyParagraphNode();
- },
- onProcess: (text) async {
- await textRobot.autoInsertTextSync(
- text,
- inputType: TextRobotInputType.sentence,
- separator: r'\n\n',
- delay: Duration.zero,
- );
- },
- onEnd: () async {},
- onError: (error) async {
- if (mounted) {
- if (error.isLimitExceeded) {
- showAILimitDialog(context, error.message);
- } else {
- showSnackBarMessage(
- context,
- error.message,
- showCancel: true,
- );
- }
- }
- },
- );
- await _updateGenerationCount();
- }
-
- String? _getPreviousOutput() {
- final startSelection = this.startSelection;
- if (startSelection != null) {
- final end = widget.node.previous?.path;
-
- if (end != null) {
- final result = editorState
- .getNodesInSelection(
- startSelection.copyWith(end: Position(path: end)),
- )
- .fold(
- '',
- (previousValue, element) {
- final delta = element.delta;
- if (delta != null) {
- return "$previousValue\n${delta.toPlainText()}";
- } else {
- return previousValue;
- }
- },
- );
- return result.trim();
- }
- }
- return null;
- }
-
- Future<void> _updateEditingText() async {
- final transaction = editorState.transaction;
- transaction.updateNode(
- widget.node,
- {
- AutoCompletionBlockKeys.prompt: controller.text,
- },
- );
- await editorState.apply(transaction);
- }
-
- Future<void> _updateGenerationCount() async {
- final transaction = editorState.transaction;
- transaction.updateNode(
- widget.node,
- {
- AutoCompletionBlockKeys.generationCount: generationCount + 1,
- },
- );
- await editorState.apply(transaction);
- }
-
- String _rewritePrompt(String previousOutput) {
- return 'I am not satisfied with your previous response ($previousOutput) to the query ($prompt). Please provide an alternative response.';
- }
-
- Future<void> _makeSurePreviousNodeIsEmptyParagraphNode() async {
- // make sure the previous node is a empty paragraph node without any styles.
-
- final previous = widget.node.previous;
- final Selection selection;
- if (previous == null ||
- previous.type != ParagraphBlockKeys.type ||
- (previous.delta?.toPlainText().isNotEmpty ?? false)) {
- final transaction = editorState.transaction;
- selection = Selection.single(
- path: widget.node.path,
- startOffset: 0,
- );
- transaction.insertNode(
- widget.node.path,
- paragraphNode(),
- );
- await editorState.apply(transaction);
- } else {
- selection = Selection.single(
- path: previous.path,
- startOffset: 0,
- );
- }
- final transaction = editorState.transaction;
- transaction.updateNode(widget.node, {
- AutoCompletionBlockKeys.startSelection: selection.toJson(),
- });
- transaction.afterSelection = selection;
- await editorState.apply(
- transaction,
- options: const ApplyOptions(inMemoryUpdate: true),
- );
- }
-
- void _subscribeSelectionGesture() {
- interceptor = SelectionGestureInterceptor(
- key: AutoCompletionBlockKeys.type,
- canTap: (details) {
- if (!context.isOffsetInside(details.globalPosition)) {
- if (prompt.isNotEmpty || controller.text.isNotEmpty) {
- // show dialog
- showDialog(
- context: context,
- builder: (_) => DiscardDialog(
- onConfirm: _onDiscard,
- onCancel: () {},
- ),
- );
- } else if (controller.text.isEmpty) {
- _onExit();
- }
- }
- editorState.service.keyboardService?.disable();
- return false;
- },
- );
- editorState.service.selectionService.registerGestureInterceptor(
- interceptor,
- );
- }
-
- void _unsubscribeSelectionGesture() {
- editorState.service.selectionService.unregisterGestureInterceptor(
- AutoCompletionBlockKeys.type,
- );
- }
-}
-
-class AutoCompletionHeader extends StatelessWidget {
- const AutoCompletionHeader({super.key});
-
- @override
- Widget build(BuildContext context) {
- return FlowyText.medium(
- LocaleKeys.document_plugins_autoGeneratorTitleName.tr(),
- fontSize: 14,
- );
- }
-}
-
-class AutoCompletionInputFooter extends StatelessWidget {
- const AutoCompletionInputFooter({
- super.key,
- required this.onGenerate,
- required this.onExit,
- });
-
- final VoidCallback onGenerate;
- final VoidCallback onExit;
-
- @override
- Widget build(BuildContext context) {
- return Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- PrimaryRoundedButton(
- text: LocaleKeys.button_generate.tr(),
- margin: const EdgeInsets.symmetric(
- horizontal: 16.0,
- vertical: 10.0,
- ),
- radius: 8.0,
- onTap: onGenerate,
- ),
- const Space(10, 0),
- OutlinedRoundedButton(
- text: LocaleKeys.button_cancel.tr(),
- margin: const EdgeInsets.symmetric(
- horizontal: 16.0,
- vertical: 10.0,
- ),
- onTap: onExit,
- ),
- Flexible(
- child: Container(
- alignment: Alignment.centerRight,
- child: FlowyText.regular(
- LocaleKeys.document_plugins_warning.tr(),
- color: Theme.of(context).hintColor,
- overflow: TextOverflow.ellipsis,
- fontSize: 12,
- ),
- ),
- ),
- ],
- );
- }
-}
-
-class AutoCompletionFooter extends StatelessWidget {
- const AutoCompletionFooter({
- super.key,
- required this.onKeep,
- required this.onRewrite,
- required this.onDiscard,
- });
-
- final VoidCallback onKeep;
- final VoidCallback onRewrite;
- final VoidCallback onDiscard;
-
- @override
- Widget build(BuildContext context) {
- return Row(
- children: [
- PrimaryRoundedButton(
- text: LocaleKeys.button_keep.tr(),
- margin: const EdgeInsets.symmetric(
- horizontal: 16.0,
- vertical: 9.0,
- ),
- onTap: onKeep,
- ),
- const HSpace(10),
- OutlinedRoundedButton(
- text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),
- onTap: onRewrite,
- ),
- const HSpace(10),
- OutlinedRoundedButton(
- text: LocaleKeys.button_discard.tr(),
- onTap: onDiscard,
- ),
- ],
- );
- }
-}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart
index 56e34975cb..af50b15f63 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart
@@ -24,9 +24,11 @@ export 'header/cover_editor_bloc.dart';
export 'header/custom_cover_picker.dart';
export 'header/document_cover_widget.dart';
export 'heading/heading_toolbar_item.dart';
+export 'image/custom_image_block_component/custom_image_block_component.dart';
export 'image/custom_image_block_component/image_menu.dart';
export 'image/image_selection_menu.dart';
export 'image/mobile_image_toolbar_item.dart';
+export 'image/multi_image_block_component/multi_image_block_component.dart';
export 'image/multi_image_block_component/multi_image_menu.dart';
export 'inline_math_equation/inline_math_equation.dart';
export 'inline_math_equation/inline_math_equation_toolbar_item.dart';
@@ -36,6 +38,7 @@ export 'link_preview/link_preview_cache.dart';
export 'link_preview/link_preview_menu.dart';
export 'math_equation/math_equation_block_component.dart';
export 'math_equation/mobile_math_equation_toolbar_item.dart';
+export 'mention/mention_block.dart';
export 'mobile_floating_toolbar/custom_mobile_floating_toolbar.dart';
export 'mobile_toolbar_v3/aa_toolbar_item.dart';
export 'mobile_toolbar_v3/add_block_toolbar_item.dart';
@@ -49,21 +52,18 @@ export 'mobile_toolbar_v3/toolbar_item_builder.dart';
export 'mobile_toolbar_v3/undo_redo_toolbar_item.dart';
export 'mobile_toolbar_v3/util.dart';
export 'numbered_list/numbered_list_icon.dart';
-export 'openai/widgets/auto_completion_node_widget.dart';
-export 'openai/widgets/smart_edit_node_widget.dart';
-export 'openai/widgets/smart_edit_toolbar_item.dart';
+export 'openai/widgets/ai_writer_block_component.dart';
+export 'openai/widgets/ask_ai_block_component.dart';
+export 'openai/widgets/ask_ai_toolbar_item.dart';
export 'outline/outline_block_component.dart';
export 'parsers/markdown_parsers.dart';
export 'quote/quote_block_shortcuts.dart';
export 'shortcuts/character_shortcuts.dart';
export 'shortcuts/command_shortcuts.dart';
export 'slash_menu/slash_menu_items.dart';
+export 'sub_page/sub_page_block_component.dart';
export 'table/table_menu.dart';
export 'table/table_option_action.dart';
export 'todo_list/todo_list_icon.dart';
export 'toggle/toggle_block_component.dart';
export 'toggle/toggle_block_shortcuts.dart';
-export 'sub_page/sub_page_block_component.dart';
-export 'mention/mention_block.dart';
-export 'image/custom_image_block_component/custom_image_block_component.dart';
-export 'image/multi_image_block_component/multi_image_block_component.dart';
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items.dart
index a06d3abb37..3d022b0de6 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items.dart
@@ -560,7 +560,7 @@ SelectionMenuItem aiWriterSlashMenuItem = SelectionMenuItem(
if (node == null || delta == null) {
return;
}
- final newNode = autoCompletionNode(start: selection);
+ final newNode = aiWriterNode(start: selection);
final transaction = editorState.transaction;
//default insert after
diff --git a/frontend/appflowy_flutter/lib/user/application/ai_service.dart b/frontend/appflowy_flutter/lib/user/application/ai_service.dart
index 175cb6f1fe..e4100cec59 100644
--- a/frontend/appflowy_flutter/lib/user/application/ai_service.dart
+++ b/frontend/appflowy_flutter/lib/user/application/ai_service.dart
@@ -6,7 +6,7 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/text_completion.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
@@ -64,15 +64,15 @@ class AppFlowyAIService implements AIRepository {
}
}
-CompletionTypePB completionTypeFromInt(SmartEditAction action) {
+CompletionTypePB completionTypeFromInt(AskAIAction action) {
switch (action) {
- case SmartEditAction.summarize:
+ case AskAIAction.summarize:
return CompletionTypePB.MakeShorter;
- case SmartEditAction.fixSpelling:
+ case AskAIAction.fixSpelling:
return CompletionTypePB.SpellingAndGrammar;
- case SmartEditAction.improveWriting:
+ case AskAIAction.improveWriting:
return CompletionTypePB.ImproveWriting;
- case SmartEditAction.makeItLonger:
+ case AskAIAction.makeItLonger:
return CompletionTypePB.MakeLonger;
}
}
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/settings_billing_view.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/settings_billing_view.dart
index e77dbaa7e0..0c57c9e158 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/settings_billing_view.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/settings_billing_view.dart
@@ -1,7 +1,5 @@
import 'dart:io';
-import 'package:flutter/material.dart';
-
import 'package:appflowy/shared/flowy_error_page.dart';
import 'package:appflowy/util/int64_extension.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
@@ -23,6 +21,7 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
+import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../generated/locale_keys.g.dart';
diff --git a/frontend/appflowy_flutter/test/bloc_test/smart_edit_test/smart_editor_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/ask_ai_test/ask_ai_action_bloc_test.dart
similarity index 81%
rename from frontend/appflowy_flutter/test/bloc_test/smart_edit_test/smart_editor_bloc_test.dart
rename to frontend/appflowy_flutter/test/bloc_test/ask_ai_test/ask_ai_action_bloc_test.dart
index 717cc7c141..8c6f798656 100644
--- a/frontend/appflowy_flutter/test/bloc_test/smart_edit_test/smart_editor_bloc_test.dart
+++ b/frontend/appflowy_flutter/test/bloc_test/ask_ai_test/ask_ai_action_bloc_test.dart
@@ -1,7 +1,7 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -89,13 +89,13 @@ class _MockErrorRepository extends Mock implements AIRepository {
}
void main() {
- group('SmartEditorBloc: ', () {
+ group('AskAIActionBloc: ', () {
const text1 = '1. Select text to style using the toolbar menu.';
const text2 = '2. Discover more styling options in Aa.';
const text3 =
'3. AppFlowy empowers you to beautifully and effortlessly style your content.';
- blocTest<SmartEditBloc, SmartEditState>(
+ blocTest<AskAIActionBloc, AskAIState>(
'send request before the bloc is initialized',
build: () {
final document = Document(
@@ -113,34 +113,34 @@ void main() {
end: Position(path: [2], offset: text3.length),
);
- final node = smartEditNode(
- action: SmartEditAction.makeItLonger,
+ final node = askAINode(
+ action: AskAIAction.makeItLonger,
content: [text1, text2, text3].join('\n'),
);
- return SmartEditBloc(
+ return AskAIActionBloc(
node: node,
editorState: editorState,
- action: SmartEditAction.makeItLonger,
+ action: AskAIAction.makeItLonger,
enableLogging: false,
);
},
act: (bloc) {
- bloc.add(SmartEditEvent.initial(Future.value(_MockAIRepository())));
- bloc.add(const SmartEditEvent.rewrite());
+ bloc.add(AskAIEvent.initial(Future.value(_MockAIRepository())));
+ bloc.add(const AskAIEvent.rewrite());
},
expect: () => [
- isA<SmartEditState>()
+ isA<AskAIState>()
.having((s) => s.loading, 'loading', true)
.having((s) => s.result, 'result', isEmpty),
- isA<SmartEditState>()
+ isA<AskAIState>()
.having((s) => s.loading, 'loading', false)
.having((s) => s.result, 'result', isNotEmpty)
.having((s) => s.result, 'result', contains('UPDATED:')),
- isA<SmartEditState>().having((s) => s.loading, 'loading', false),
+ isA<AskAIState>().having((s) => s.loading, 'loading', false),
],
);
- blocTest<SmartEditBloc, SmartEditState>(
+ blocTest<AskAIActionBloc, AskAIState>(
'exceed the ai response limit',
build: () {
const text1 = '1. Select text to style using the toolbar menu.';
@@ -162,26 +162,26 @@ void main() {
end: Position(path: [2], offset: text3.length),
);
- final node = smartEditNode(
- action: SmartEditAction.makeItLonger,
+ final node = askAINode(
+ action: AskAIAction.makeItLonger,
content: [text1, text2, text3].join('\n'),
);
- return SmartEditBloc(
+ return AskAIActionBloc(
node: node,
editorState: editorState,
- action: SmartEditAction.makeItLonger,
+ action: AskAIAction.makeItLonger,
enableLogging: false,
);
},
act: (bloc) {
- bloc.add(SmartEditEvent.initial(Future.value(_MockErrorRepository())));
- bloc.add(const SmartEditEvent.rewrite());
+ bloc.add(AskAIEvent.initial(Future.value(_MockErrorRepository())));
+ bloc.add(const AskAIEvent.rewrite());
},
expect: () => [
- isA<SmartEditState>()
+ isA<AskAIState>()
.having((s) => s.loading, 'loading', true)
.having((s) => s.result, 'result', isEmpty),
- isA<SmartEditState>()
+ isA<AskAIState>()
.having((s) => s.requestError, 'requestError', isNotNull)
.having(
(s) => s.requestError?.code,
@@ -208,21 +208,21 @@ void main() {
end: Position(path: [2], offset: text3.length),
);
- final node = smartEditNode(
- action: SmartEditAction.makeItLonger,
+ final node = askAINode(
+ action: AskAIAction.makeItLonger,
content: [text1, text2, text3].join('\n\n'),
);
- final bloc = SmartEditBloc(
+ final bloc = AskAIActionBloc(
node: node,
editorState: editorState,
- action: SmartEditAction.summarize,
+ action: AskAIAction.summarize,
enableLogging: false,
);
- bloc.add(SmartEditEvent.initial(Future.value(_MockAIRepository())));
+ bloc.add(AskAIEvent.initial(Future.value(_MockAIRepository())));
await blocResponseFuture();
- bloc.add(const SmartEditEvent.started());
+ bloc.add(const AskAIEvent.started());
await blocResponseFuture();
- bloc.add(const SmartEditEvent.replace());
+ bloc.add(const AskAIEvent.replace());
await blocResponseFuture();
expect(editorState.document.root.children.length, 3);
expect(
@@ -255,21 +255,21 @@ void main() {
end: Position(path: [2], offset: text3.length),
);
- final node = smartEditNode(
- action: SmartEditAction.makeItLonger,
+ final node = askAINode(
+ action: AskAIAction.makeItLonger,
content: [text1, text2, text3].join('\n'),
);
- final bloc = SmartEditBloc(
+ final bloc = AskAIActionBloc(
node: node,
editorState: editorState,
- action: SmartEditAction.summarize,
+ action: AskAIAction.summarize,
enableLogging: false,
);
- bloc.add(SmartEditEvent.initial(Future.value(_MockAIRepositoryLess())));
+ bloc.add(AskAIEvent.initial(Future.value(_MockAIRepositoryLess())));
await blocResponseFuture();
- bloc.add(const SmartEditEvent.started());
+ bloc.add(const AskAIEvent.started());
await blocResponseFuture();
- bloc.add(const SmartEditEvent.replace());
+ bloc.add(const AskAIEvent.replace());
await blocResponseFuture();
expect(editorState.document.root.children.length, 1);
expect(
@@ -294,21 +294,21 @@ void main() {
end: Position(path: [2], offset: text3.length),
);
- final node = smartEditNode(
- action: SmartEditAction.makeItLonger,
+ final node = askAINode(
+ action: AskAIAction.makeItLonger,
content: [text1, text2, text3].join('\n'),
);
- final bloc = SmartEditBloc(
+ final bloc = AskAIActionBloc(
node: node,
editorState: editorState,
- action: SmartEditAction.summarize,
+ action: AskAIAction.summarize,
enableLogging: false,
);
- bloc.add(SmartEditEvent.initial(Future.value(_MockAIRepositoryMore())));
+ bloc.add(AskAIEvent.initial(Future.value(_MockAIRepositoryMore())));
await blocResponseFuture();
- bloc.add(const SmartEditEvent.started());
+ bloc.add(const AskAIEvent.started());
await blocResponseFuture();
- bloc.add(const SmartEditEvent.replace());
+ bloc.add(const AskAIEvent.replace());
await blocResponseFuture();
expect(editorState.document.root.children.length, 10);
for (var i = 0; i < 10; i++) {
diff --git a/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dart b/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dart
new file mode 100644
index 0000000000..c732be720c
--- /dev/null
+++ b/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dart
@@ -0,0 +1,374 @@
+import 'package:appflowy/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart';
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ group('markdown text robot:', () {
+ setUpAll(() {
+ Log.shared.disableLog = true;
+ });
+
+ tearDownAll(() {
+ Log.shared.disableLog = false;
+ });
+
+ Future<void> testLiveRefresh(
+ List<String> texts, {
+ required void Function(EditorState) expect,
+ }) async {
+ final editorState = EditorState.blank();
+ editorState.selection = Selection.collapsed(Position(path: [0]));
+ final markdownTextRobot = MarkdownTextRobot(
+ editorState: editorState,
+ );
+ markdownTextRobot.start();
+ for (final text in texts) {
+ await markdownTextRobot.appendMarkdownText(text);
+ // mock the delay of the text robot
+ await Future.delayed(const Duration(milliseconds: 10));
+ }
+ await markdownTextRobot.stop();
+
+ expect(editorState);
+ }
+
+ test('parse markdown text (1)', () async {
+ final editorState = EditorState.blank();
+ editorState.selection = Selection.collapsed(Position(path: [0]));
+ final markdownTextRobot = MarkdownTextRobot(
+ editorState: editorState,
+ );
+
+ markdownTextRobot.start();
+ await markdownTextRobot.appendMarkdownText(_sample1);
+ await markdownTextRobot.stop();
+
+ final nodes = editorState.document.root.children;
+ // 4 from the sample, 1 from the original empty paragraph node
+ expect(nodes.length, 5);
+
+ final n1 = nodes[0];
+ expect(n1.delta!.toPlainText(), 'The Curious Cat');
+ expect(n1.type, HeadingBlockKeys.type);
+
+ final n2 = nodes[1];
+ expect(n2.type, ParagraphBlockKeys.type);
+ expect(n2.delta!.toJson(), [
+ {'insert': 'Once upon a time in a '},
+ {
+ 'insert': 'quiet village',
+ 'attributes': {'bold': true},
+ },
+ {'insert': ', there lived a curious cat named '},
+ {
+ 'insert': 'Whiskers',
+ 'attributes': {'italic': true},
+ },
+ {'insert': '. Unlike other cats, Whiskers had a passion for '},
+ {
+ 'insert': 'exploration',
+ 'attributes': {'bold': true},
+ },
+ {
+ 'insert':
+ '. Every day, he\'d wander through the village, discovering hidden spots and making new friends with the local animals.',
+ },
+ ]);
+
+ final n3 = nodes[2];
+ expect(n3.type, ParagraphBlockKeys.type);
+ expect(n3.delta!.toJson(), [
+ {'insert': 'One sunny morning, Whiskers stumbled upon a mysterious '},
+ {
+ 'insert': 'wooden box',
+ 'attributes': {'bold': true},
+ },
+ {'insert': ' behind the old barn. It was covered in '},
+ {
+ 'insert': 'vines and dust',
+ 'attributes': {'italic': true},
+ },
+ {
+ 'insert':
+ '. Intrigued, he nudged it open with his paw and found a collection of ancient maps. These maps led to secret trails around the village.',
+ },
+ ]);
+
+ final n4 = nodes[3];
+ expect(n4.type, ParagraphBlockKeys.type);
+ expect(n4.delta!.toJson(), [
+ {
+ 'insert':
+ 'Whiskers became the village\'s hero, guiding everyone on exciting adventures.',
+ },
+ ]);
+ });
+
+ // Live refresh - Partial sample
+ // ## The Decision
+ // - Aria found an ancient map in her grandmother's attic.
+ // - The map hinted at a mystical place known as the Enchanted Forest.
+ // - Legends spoke of the forest as a realm where dreams came to life.
+ test('live refresh (2)', () async {
+ await testLiveRefresh(
+ _liveRefreshSample2,
+ expect: (editorState) {
+ final nodes = editorState.document.root.children;
+ expect(nodes.length, 5);
+
+ final n1 = nodes[0];
+ expect(n1.type, HeadingBlockKeys.type);
+ expect(n1.delta!.toPlainText(), 'The Decision');
+
+ final n2 = nodes[1];
+ expect(n2.type, BulletedListBlockKeys.type);
+ expect(
+ n2.delta!.toPlainText(),
+ 'Aria found an ancient map in her grandmother\'s attic.',
+ );
+
+ final n3 = nodes[2];
+ expect(n3.type, BulletedListBlockKeys.type);
+ expect(
+ n3.delta!.toPlainText(),
+ 'The map hinted at a mystical place known as the Enchanted Forest.',
+ );
+
+ final n4 = nodes[3];
+ expect(n4.type, BulletedListBlockKeys.type);
+ expect(
+ n4.delta!.toPlainText(),
+ 'Legends spoke of the forest as a realm where dreams came to life.',
+ );
+ },
+ );
+ });
+
+ // Partial sample
+ // ## The Preparation
+ // Before embarking on her journey, Aria prepared meticulously:
+ // 1. Gather Supplies
+ // - A sturdy backpack
+ // - A compass and a map
+ // - Provisions for the week
+ // 2. Seek Guidance
+ // - Visited the village elder for advice
+ // - Listened to tales of past adventurers
+ // 3. Sharpen Skills
+ // - Practiced archery and swordsmanship
+ // - Enhanced survival skills
+ test('live refresh (3)', () async {
+ await testLiveRefresh(
+ _liveRefreshSample3,
+ expect: (editorState) {
+ final nodes = editorState.document.root.children;
+ expect(nodes.length, 6);
+
+ final n1 = nodes[0];
+ expect(n1.type, HeadingBlockKeys.type);
+ expect(n1.delta!.toPlainText(), 'The Preparation');
+
+ final n2 = nodes[1];
+ expect(n2.type, ParagraphBlockKeys.type);
+ expect(
+ n2.delta!.toPlainText(),
+ 'Before embarking on her journey, Aria prepared meticulously:',
+ );
+
+ final n3 = nodes[2];
+ expect(n3.type, NumberedListBlockKeys.type);
+ expect(
+ n3.delta!.toPlainText(),
+ 'Gather Supplies',
+ );
+
+ final n3c1 = n3.children[0];
+ expect(n3c1.type, BulletedListBlockKeys.type);
+ expect(n3c1.delta!.toPlainText(), 'A sturdy backpack');
+
+ final n3c2 = n3.children[1];
+ expect(n3c2.type, BulletedListBlockKeys.type);
+ expect(n3c2.delta!.toPlainText(), 'A compass and a map');
+
+ final n3c3 = n3.children[2];
+ expect(n3c3.type, BulletedListBlockKeys.type);
+ expect(n3c3.delta!.toPlainText(), 'Provisions for the week');
+
+ final n4 = nodes[3];
+ expect(n4.type, NumberedListBlockKeys.type);
+ expect(n4.delta!.toPlainText(), 'Seek Guidance');
+
+ final n4c1 = n4.children[0];
+ expect(n4c1.type, BulletedListBlockKeys.type);
+ expect(
+ n4c1.delta!.toPlainText(),
+ 'Visited the village elder for advice',
+ );
+
+ final n4c2 = n4.children[1];
+ expect(n4c2.type, BulletedListBlockKeys.type);
+ expect(
+ n4c2.delta!.toPlainText(),
+ 'Listened to tales of past adventurers',
+ );
+
+ final n5 = nodes[4];
+ expect(n5.type, NumberedListBlockKeys.type);
+ expect(
+ n5.delta!.toPlainText(),
+ 'Sharpen Skills',
+ );
+
+ final n5c1 = n5.children[0];
+ expect(n5c1.type, BulletedListBlockKeys.type);
+ expect(
+ n5c1.delta!.toPlainText(),
+ 'Practiced archery and swordsmanship',
+ );
+
+ final n5c2 = n5.children[1];
+ expect(n5c2.type, BulletedListBlockKeys.type);
+ expect(
+ n5c2.delta!.toPlainText(),
+ 'Enhanced survival skills',
+ );
+ },
+ );
+ });
+ });
+}
+
+const _sample1 = '''# The Curious Cat
+
+Once upon a time in a **quiet village**, there lived a curious cat named *Whiskers*. Unlike other cats, Whiskers had a passion for **exploration**. Every day, he'd wander through the village, discovering hidden spots and making new friends with the local animals.
+
+One sunny morning, Whiskers stumbled upon a mysterious **wooden box** behind the old barn. It was covered in _vines and dust_. Intrigued, he nudged it open with his paw and found a collection of ancient maps. These maps led to secret trails around the village.
+
+Whiskers became the village's hero, guiding everyone on exciting adventures.''';
+
+const _liveRefreshSample2 = [
+ "##",
+ " The",
+ " Decision",
+ "\n\n",
+ "-",
+ " Ar",
+ "ia",
+ " found",
+ " an",
+ " ancient map",
+ " in her grandmother",
+ "'s attic",
+ ".\n",
+ "-",
+ " The map",
+ " hinted at",
+ " a",
+ " mystical",
+ " place",
+ " known",
+ " as",
+ " the",
+ " En",
+ "ch",
+ "anted",
+ " Forest",
+ ".\n",
+ "-",
+ " Legends",
+ " spoke",
+ " of",
+ " the",
+ " forest",
+ " as",
+ " a realm",
+ " where dreams",
+ " came",
+ " to",
+ " life",
+ ".\n\n",
+];
+
+const _liveRefreshSample3 = [
+ "##",
+ " The",
+ " Preparation\n\n",
+ "Before",
+ " embarking",
+ " on",
+ " her",
+ " journey",
+ ", Aria prepared",
+ " meticulously:\n\n",
+ "1",
+ ".",
+ " **",
+ "Gather",
+ " Supplies**",
+ " \n",
+ " ",
+ " -",
+ " A",
+ " sturdy",
+ " backpack",
+ "\n",
+ " ",
+ " -",
+ " A",
+ " compass",
+ " and",
+ " a map",
+ "\n ",
+ " -",
+ " Pro",
+ "visions",
+ " for",
+ " the",
+ " week",
+ "\n\n",
+ "2",
+ ".",
+ " **",
+ "Seek",
+ " Guidance",
+ "**",
+ " \n",
+ " ",
+ " -",
+ " Vis",
+ "ited",
+ " the",
+ " village",
+ " elder for advice",
+ "\n",
+ " -",
+ " List",
+ "ened",
+ " to",
+ " tales",
+ " of past",
+ " advent",
+ "urers",
+ "\n\n",
+ "3",
+ ".",
+ " **",
+ "Shar",
+ "pen",
+ " Skills",
+ "**",
+ " \n",
+ " ",
+ " -",
+ " Pract",
+ "iced",
+ " arch",
+ "ery",
+ " and",
+ " swordsmanship",
+ "\n ",
+ " -",
+ " Enhanced",
+ " survival skills",
+];