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: allow user scroll during generation (#7559)

Richard Shiue566e7b2f40b1
diff --git a/frontend/appflowy_flutter/lib/plugins/document/document_page.dart b/frontend/appflowy_flutter/lib/plugins/document/document_page.dart
index 46ef2ca7f2..8716bb7ae2 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/document_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/document_page.dart
@@ -5,6 +5,7 @@ import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/presentation/banner.dart';
import 'package:appflowy/plugins/document/presentation/editor_drop_handler.dart';
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
+import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/cover/document_immersive_cover.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/shared_context/shared_context.dart';
@@ -55,8 +56,6 @@ class _DocumentPageState extends State<DocumentPage>
Selection? initialSelection;
late final documentBloc = DocumentBloc(documentId: widget.view.id)
..add(const DocumentEvent.initial());
- late final viewBloc = ViewBloc(view: widget.view)
- ..add(const ViewEvent.initial());
@override
void initState() {
@@ -68,7 +67,6 @@ class _DocumentPageState extends State<DocumentPage>
void dispose() {
WidgetsBinding.instance.removeObserver(this);
documentBloc.close();
- viewBloc.close();
super.dispose();
}
@@ -93,7 +91,11 @@ class _DocumentPageState extends State<DocumentPage>
value: ViewLockStatusBloc(view: widget.view)
..add(ViewLockStatusEvent.initial()),
),
- BlocProvider.value(value: viewBloc),
+ BlocProvider(
+ create: (context) =>
+ ViewBloc(view: widget.view)..add(const ViewEvent.initial()),
+ lazy: false,
+ ),
],
child: BlocConsumer<ViewLockStatusBloc, ViewLockStatusState>(
listenWhen: (prev, curr) => curr.isLocked != prev.isLocked,
@@ -126,14 +128,20 @@ class _DocumentPageState extends State<DocumentPage>
return const SizedBox.shrink();
}
- return BlocListener<ViewLockStatusBloc, ViewLockStatusState>(
- listener: (context, state) {
- editorState.editable = !state.isLocked;
- },
- child:
- BlocListener<ActionNavigationBloc, ActionNavigationState>(
- listenWhen: (_, curr) => curr.action != null,
- listener: onNotificationAction,
+ return MultiBlocListener(
+ listeners: [
+ BlocListener<ViewLockStatusBloc, ViewLockStatusState>(
+ listener: (context, state) =>
+ editorState.editable = !state.isLocked,
+ ),
+ BlocListener<ActionNavigationBloc, ActionNavigationState>(
+ listenWhen: (_, curr) => curr.action != null,
+ listener: onNotificationAction,
+ ),
+ ],
+ child: AiWriterScrollWrapper(
+ viewId: widget.view.id,
+ editorState: editorState,
child: buildEditorPage(context, state),
),
);
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart
index aee2e2cb50..c1b533ccca 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart
@@ -2,11 +2,8 @@ import 'package:appflowy/ai/ai.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
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/application/prelude.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:appflowy/workspace/application/view/view_bloc.dart';
-import 'package:appflowy/workspace/presentation/home/menu/sidebar/space/shared_widget.dart';
-import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/colorscheme/default_colorscheme.dart';
@@ -19,7 +16,6 @@ import 'operations/ai_writer_cubit.dart';
import 'operations/ai_writer_entities.dart';
import 'operations/ai_writer_node_extension.dart';
import 'suggestion_action_bar.dart';
-import 'widgets/ai_writer_gesture_detector.dart';
class AiWriterBlockKeys {
const AiWriterBlockKeys._();
@@ -98,18 +94,11 @@ class AiWriterBlockComponent extends BlockComponentStatefulWidget {
}
class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
- final key = GlobalKey();
final textController = TextEditingController();
final overlayController = OverlayPortalController();
final layerLink = LayerLink();
late final editorState = context.read<EditorState>();
- late final aiWriterCubit = AiWriterCubit(
- documentId: context.read<DocumentBloc>().documentId,
- editorState: editorState,
- getAiWriterNode: () => widget.node,
- initialCommand: widget.node.aiWriterCommand,
- );
@override
void initState() {
@@ -118,7 +107,7 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
WidgetsBinding.instance.addPostFrameCallback((_) {
overlayController.show();
if (!widget.node.isAiWriterInitialized) {
- aiWriterCubit.init();
+ context.read<AiWriterCubit>().register(widget.node);
}
});
}
@@ -126,7 +115,6 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
@override
void dispose() {
textController.dispose();
- aiWriterCubit.close();
super.dispose();
}
@@ -136,85 +124,42 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
return const SizedBox.shrink();
}
- return MultiBlocProvider(
- providers: [
- BlocProvider.value(
- value: aiWriterCubit,
- ),
- BlocProvider(
- create: (_) => AIPromptInputBloc(
- predefinedFormat: null,
- ),
- ),
- ],
+ return BlocProvider(
+ create: (_) => AIPromptInputBloc(
+ predefinedFormat: null,
+ ),
child: LayoutBuilder(
builder: (context, constraints) {
- return BlocListener<AiWriterCubit, AiWriterState>(
- listener: (context, state) {
- if (state is FailedContinueWritingAiWriterState) {
- showConfirmDialog(
- context: context,
- title: LocaleKeys.ai_continueWritingEmptyDocumentTitle.tr(),
- description: LocaleKeys
- .ai_continueWritingEmptyDocumentDescription
- .tr(),
- onConfirm: state.onConfirm,
- );
- } else if (state is DiscardResponseAiWriterState) {
- showConfirmDialog(
- context: context,
- title: LocaleKeys.button_discard.tr(),
- description: LocaleKeys.document_plugins_discardResponse.tr(),
- confirmLabel: LocaleKeys.button_discard.tr(),
- style: ConfirmPopupStyle.cancelAndOk,
- onConfirm: state.onDiscard,
- onCancel: () {},
- );
- }
- },
- child: OverlayPortal(
- controller: overlayController,
- overlayChildBuilder: (context) {
- return Stack(
- children: [
- BlocBuilder<AiWriterCubit, AiWriterState>(
- builder: (context, state) {
- return AiWriterGestureDetector(
- behavior: state is GeneratingAiWriterState
- ? HitTestBehavior.opaque
- : HitTestBehavior.translucent,
- onPointerEvent: onTapOutside,
- );
- },
+ return OverlayPortal(
+ controller: overlayController,
+ overlayChildBuilder: (context) {
+ return Center(
+ child: CompositedTransformFollower(
+ link: layerLink,
+ showWhenUnlinked: false,
+ child: Container(
+ padding: const EdgeInsets.only(
+ left: 40.0,
+ bottom: 16.0,
),
- CompositedTransformFollower(
- link: layerLink,
- showWhenUnlinked: false,
- child: Container(
- padding: const EdgeInsets.only(
- left: 40.0,
- bottom: 16.0,
- ),
- width: constraints.maxWidth,
- child: OverlayContent(
- editorState: editorState,
- node: widget.node,
- ),
- ),
+ width: constraints.maxWidth,
+ child: OverlayContent(
+ editorState: editorState,
+ node: widget.node,
),
- ],
- );
- },
- child: CompositedTransformTarget(
- link: layerLink,
- child: BlocBuilder<AiWriterCubit, AiWriterState>(
- builder: (context, state) {
- return SizedBox(
- key: key,
- width: double.infinity,
- );
- },
+ ),
),
+ );
+ },
+ child: CompositedTransformTarget(
+ link: layerLink,
+ child: BlocBuilder<AiWriterCubit, AiWriterState>(
+ builder: (context, state) {
+ return SizedBox(
+ width: double.infinity,
+ height: 1.0,
+ );
+ },
),
),
);
@@ -222,26 +167,6 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
),
);
}
-
- void onTapOutside() {
- if (aiWriterCubit.hasUnusedResponse()) {
- showConfirmDialog(
- context: context,
- title: LocaleKeys.button_discard.tr(),
- description: LocaleKeys.document_plugins_discardResponse.tr(),
- confirmLabel: LocaleKeys.button_discard.tr(),
- style: ConfirmPopupStyle.cancelAndOk,
- onConfirm: () => aiWriterCubit
- ..stopStream()
- ..exit(),
- onCancel: () {},
- );
- } else {
- aiWriterCubit
- ..stopStream()
- ..exit();
- }
- }
}
class OverlayContent extends StatelessWidget {
@@ -258,6 +183,9 @@ class OverlayContent extends StatelessWidget {
Widget build(BuildContext context) {
return BlocBuilder<AiWriterCubit, AiWriterState>(
builder: (context, state) {
+ if (state is IdleAiWriterState) {
+ return const SizedBox.shrink();
+ }
final selection = node.aiWriterSelection;
final showSuggestionPopup =
state is ReadyAiWriterState && !state.isFirstRun;
@@ -337,7 +265,9 @@ class OverlayContent extends StatelessWidget {
alignment:
AlignmentDirectional.centerStart,
child: FlowyText(
- state.command.i18n,
+ (state as RegisteredAiWriter)
+ .command
+ .i18n,
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF666D76),
@@ -421,7 +351,9 @@ class OverlayContent extends StatelessWidget {
context.read<AiWriterCubit>().runCommand(
command,
- showPredefinedFormats ? predefinedFormat : null,
+ predefinedFormat:
+ showPredefinedFormats ? predefinedFormat : null,
+ isFirstRun: false,
);
},
),
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dart
index c82b39e241..c503042339 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dart
@@ -4,7 +4,26 @@ import 'package:appflowy_editor/appflowy_editor.dart';
import '../ai_writer_block_component.dart';
import 'ai_writer_entities.dart';
-Future<void> removeAiWriterNode(EditorState editorState, Node node) async {
+Future<void> setAiWriterNodeIsInitialized(
+ EditorState editorState,
+ Node node,
+) async {
+ final transaction = editorState.transaction
+ ..updateNode(node, {
+ AiWriterBlockKeys.isInitialized: true,
+ })
+ ..afterSelection = null;
+
+ await editorState.apply(
+ transaction,
+ options: const ApplyOptions(recordUndo: false),
+ );
+}
+
+Future<void> removeAiWriterNode(
+ EditorState editorState,
+ Node node,
+) async {
final transaction = editorState.transaction..deleteNode(node);
await editorState.apply(
transaction,
@@ -88,10 +107,6 @@ Position ensurePreviousNodeIsEmptyParagraph(
position = Position(path: previous.path);
}
- transaction.updateNode(aiWriterNode, {
- AiWriterBlockKeys.isInitialized: true,
- });
-
return position;
}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart
index 376757b1a7..133b0b5562 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart
@@ -10,7 +10,6 @@ import 'package:appflowy_result/appflowy_result.dart';
import 'package:bloc/bloc.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
-import 'package:flutter/services.dart';
import '../../base/markdown_text_robot.dart';
import 'ai_writer_block_operations.dart';
@@ -21,28 +20,24 @@ class AiWriterCubit extends Cubit<AiWriterState> {
AiWriterCubit({
required this.documentId,
required this.editorState,
- required this.getAiWriterNode,
- required this.initialCommand,
+ this.onCreateNode,
+ this.onRemoveNode,
+ this.onAppendToDocument,
AppFlowyAIService? aiService,
}) : _aiService = aiService ?? AppFlowyAIService(),
_textRobot = MarkdownTextRobot(editorState: editorState),
selectedSourcesNotifier = ValueNotifier([documentId]),
- super(
- ReadyAiWriterState(
- initialCommand,
- isFirstRun: true,
- ),
- ) {
- HardwareKeyboard.instance.addHandler(_cancelShortcutHandler);
- editorState.service.keyboardService?.disableShortcuts();
- }
+ super(IdleAiWriterState());
final String documentId;
final EditorState editorState;
- final Node Function() getAiWriterNode;
- final AiWriterCommand initialCommand;
final AppFlowyAIService _aiService;
final MarkdownTextRobot _textRobot;
+ final void Function()? onCreateNode;
+ final void Function()? onRemoveNode;
+ final void Function()? onAppendToDocument;
+
+ Node? aiWriterNode;
final List<AiWriterRecord> records = [];
final ValueNotifier<List<String>> selectedSourcesNotifier;
@@ -52,85 +47,58 @@ class AiWriterCubit extends Cubit<AiWriterState> {
@override
Future<void> close() async {
selectedSourcesNotifier.dispose();
- HardwareKeyboard.instance.removeHandler(_cancelShortcutHandler);
- editorState.service.keyboardService?.enableShortcuts();
await super.close();
}
- void init() {
- runCommand(initialCommand, null, isImmediateRun: true);
- }
+ void register(Node node) async {
+ aiWriterNode = node;
+ onCreateNode?.call();
- void submit(
- String prompt,
- PredefinedFormat? format,
- ) async {
- final command = AiWriterCommand.userQuestion;
- final node = getAiWriterNode();
+ await setAiWriterNodeIsInitialized(editorState, node);
- _previousPrompt = (prompt, format);
+ final command = node.aiWriterCommand;
+ if (command == AiWriterCommand.userQuestion) {
+ emit(ReadyAiWriterState(AiWriterCommand.userQuestion, isFirstRun: true));
+ } else {
+ runCommand(command, isFirstRun: true);
+ }
+ }
- final stream = await _aiService.streamCompletion(
- objectId: documentId,
- text: prompt,
- format: format,
- sourceIds: selectedSourcesNotifier.value,
- completionType: command.toCompletionType(),
- history: records,
- onStart: () async {
- final transaction = editorState.transaction;
- final position =
- ensurePreviousNodeIsEmptyParagraph(editorState, node, transaction);
- transaction.afterSelection = null;
- await editorState.apply(
- transaction,
- options: ApplyOptions(
- inMemoryUpdate: true,
- recordUndo: false,
- ),
- );
- _textRobot.start(position: position);
- records.add(
- AiWriterRecord.user(content: prompt),
- );
- },
- onProcess: (text) async {
- await _textRobot.appendMarkdownText(
- text,
- attributes: ApplySuggestionFormatType.replace.attributes,
- );
- },
- onEnd: () async {
- await _textRobot.stop(
- attributes: ApplySuggestionFormatType.replace.attributes,
- );
- emit(ReadyAiWriterState(command, isFirstRun: false));
- records.add(
- AiWriterRecord.ai(content: _textRobot.markdownText),
- );
- },
- onError: (error) async {
- emit(ErrorAiWriterState(state.command, error: error));
- records.add(
- AiWriterRecord.ai(content: _textRobot.markdownText),
- );
- },
- );
+ Future<void> exit() async {
+ await _textRobot.discard();
+ _textRobot.reset();
+ onRemoveNode?.call();
+ emit(IdleAiWriterState());
- if (stream != null) {
- emit(
- GeneratingAiWriterState(
- command,
- taskId: stream.$1,
+ if (aiWriterNode != null) {
+ final selection = aiWriterNode!.aiWriterSelection;
+ if (selection == null) {
+ return;
+ }
+ final transaction = editorState.transaction;
+ formatSelection(
+ editorState,
+ selection,
+ transaction,
+ ApplySuggestionFormatType.clear,
+ );
+ await editorState.apply(
+ transaction,
+ options: const ApplyOptions(
+ inMemoryUpdate: true,
+ recordUndo: false,
),
+ withUpdateSelection: false,
);
+ await removeAiWriterNode(editorState, aiWriterNode!);
+ aiWriterNode = null;
}
}
void runCommand(
- AiWriterCommand command,
- PredefinedFormat? predefinedFormat, {
- bool isImmediateRun = false,
+ AiWriterCommand command, {
+ required bool isFirstRun,
+ PredefinedFormat? predefinedFormat,
bool isRetry = false,
}) async {
switch (command) {
@@ -138,7 +106,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
await _startContinueWriting(
command,
predefinedFormat,
- isImmediateRun: isImmediateRun,
+ isImmediateRun: isFirstRun,
);
break;
case AiWriterCommand.fixSpellingAndGrammar:
@@ -158,96 +126,79 @@ class AiWriterCubit extends Cubit<AiWriterState> {
}
}
- void stopStream() async {
- if (state is! GeneratingAiWriterState) {
- return;
- }
- await _textRobot.stop(
- attributes: ApplySuggestionFormatType.replace.attributes,
- );
- final generatingState = state as GeneratingAiWriterState;
- await AIEventStopCompleteText(
- CompleteTextTaskPB(
- taskId: generatingState.taskId,
- ),
- ).send();
- emit(
- ReadyAiWriterState(
- state.command,
- isFirstRun: false,
- markdownText: generatingState.markdownText,
- ),
- );
- }
+ Future<void> stopStream() async {
+ if (state is GeneratingAiWriterState) {
+ final generatingState = state as GeneratingAiWriterState;
- void exit() async {
- await _textRobot.discard();
- final selection = getAiWriterNode().aiWriterSelection;
- if (selection == null) {
- return;
+ await _textRobot.stop(
+ attributes: ApplySuggestionFormatType.replace.attributes,
+ );
+
+ await AIEventStopCompleteText(
+ CompleteTextTaskPB(
+ taskId: generatingState.taskId,
+ ),
+ ).send();
+
+ emit(
+ ReadyAiWriterState(
+ generatingState.command,
+ isFirstRun: false,
+ markdownText: generatingState.markdownText,
+ ),
+ );
}
- final transaction = editorState.transaction;
- formatSelection(
- editorState,
- selection,
- transaction,
- ApplySuggestionFormatType.clear,
- );
- await editorState.apply(
- transaction,
- options: const ApplyOptions(
- inMemoryUpdate: true,
- recordUndo: false,
- ),
- withUpdateSelection: false,
- );
- await removeAiWriterNode(editorState, getAiWriterNode());
}
void runResponseAction(
SuggestionAction action, [
PredefinedFormat? predefinedFormat,
]) async {
+ if (aiWriterNode == null) {
+ return;
+ }
+
+ if (state is! RegisteredAiWriter) {
+ return;
+ }
+
+ final command = (state as RegisteredAiWriter).command;
+
if (action case SuggestionAction.rewrite || SuggestionAction.tryAgain) {
await _textRobot.discard();
_textRobot.reset();
- runCommand(state.command, predefinedFormat, isRetry: true);
+ runCommand(
+ command,
+ predefinedFormat: predefinedFormat,
+ isRetry: true,
+ isFirstRun: false,
+ );
return;
}
- final selection = getAiWriterNode().aiWriterSelection;
+ final selection = aiWriterNode!.aiWriterSelection;
if (selection == null) {
return;
}
if (action case SuggestionAction.discard || SuggestionAction.close) {
- await _textRobot.discard();
+ await exit();
+ return;
+ }
- final transaction = editorState.transaction;
- formatSelection(
- editorState,
- selection,
- transaction,
- ApplySuggestionFormatType.clear,
- );
+ if (action case SuggestionAction.accept) {
+ await _textRobot.persist();
+ final nodes = editorState.getNodesInSelection(selection);
+ final transaction = editorState.transaction..deleteNodes(nodes);
await editorState.apply(
transaction,
options: const ApplyOptions(recordUndo: false),
+ withUpdateSelection: false,
);
}
- if (action case SuggestionAction.accept || SuggestionAction.keep) {
+ if (action case SuggestionAction.keep) {
await _textRobot.persist();
-
- if (acceptReplacesOriginal) {
- final nodes = editorState.getNodesInSelection(selection);
- final transaction = editorState.transaction..deleteNodes(nodes);
- await editorState.apply(
- transaction,
- options: const ApplyOptions(recordUndo: false),
- withUpdateSelection: false,
- );
- }
}
if (action case SuggestionAction.insertBelow) {
@@ -256,7 +207,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
final transaction = editorState.transaction;
final position = ensurePreviousNodeIsEmptyParagraph(
editorState,
- getAiWriterNode(),
+ aiWriterNode!,
transaction,
);
transaction.afterSelection = null;
@@ -266,6 +217,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
inMemoryUpdate: true,
recordUndo: false,
),
+ withUpdateSelection: false,
);
_textRobot.start(position: position);
await _textRobot.persist(markdownText: readyState.markdownText);
@@ -287,7 +239,9 @@ class AiWriterCubit extends Cubit<AiWriterState> {
);
}
- await removeAiWriterNode(editorState, getAiWriterNode());
+ await removeAiWriterNode(editorState, aiWriterNode!);
+ aiWriterNode = null;
+ emit(IdleAiWriterState());
}
bool hasUnusedResponse() {
@@ -302,14 +256,87 @@ class AiWriterCubit extends Cubit<AiWriterState> {
};
}
+ void submit(
+ String prompt,
+ PredefinedFormat? format,
+ ) async {
+ if (aiWriterNode == null) {
+ return;
+ }
+ final command = AiWriterCommand.userQuestion;
+ _previousPrompt = (prompt, format);
+
+ final stream = await _aiService.streamCompletion(
+ objectId: documentId,
+ text: prompt,
+ format: format,
+ history: records,
+ sourceIds: selectedSourcesNotifier.value,
+ completionType: command.toCompletionType(),
+ onStart: () async {
+ final transaction = editorState.transaction;
+ final position = ensurePreviousNodeIsEmptyParagraph(
+ editorState,
+ aiWriterNode!,
+ transaction,
+ );
+ await editorState.apply(
+ transaction,
+ options: ApplyOptions(
+ inMemoryUpdate: true,
+ recordUndo: false,
+ ),
+ withUpdateSelection: false,
+ );
+ _textRobot.start(position: position);
+ records.add(
+ AiWriterRecord.user(content: prompt),
+ );
+ },
+ onProcess: (text) async {
+ await _textRobot.appendMarkdownText(
+ text,
+ updateSelection: false,
+ attributes: ApplySuggestionFormatType.replace.attributes,
+ );
+ onAppendToDocument?.call();
+ },
+ onEnd: () async {
+ await _textRobot.stop(
+ attributes: ApplySuggestionFormatType.replace.attributes,
+ );
+ emit(ReadyAiWriterState(command, isFirstRun: false));
+ records.add(
+ AiWriterRecord.ai(content: _textRobot.markdownText),
+ );
+ },
+ onError: (error) async {
+ emit(ErrorAiWriterState(command, error: error));
+ records.add(
+ AiWriterRecord.ai(content: _textRobot.markdownText),
+ );
+ },
+ );
+
+ if (stream != null) {
+ emit(
+ GeneratingAiWriterState(
+ command,
+ taskId: stream.$1,
+ ),
+ );
+ }
+ }
+
Future<void> _startContinueWriting(
AiWriterCommand command,
PredefinedFormat? predefinedFormat, {
required bool isImmediateRun,
}) async {
- final node = getAiWriterNode();
-
- final cursorPosition = getAiWriterNode().aiWriterSelection?.start;
+ if (aiWriterNode == null) {
+ return;
+ }
+ final cursorPosition = aiWriterNode?.aiWriterSelection?.start;
if (cursorPosition == null) {
return;
}
@@ -320,28 +347,25 @@ class AiWriterCubit extends Cubit<AiWriterState> {
String text = (await editorState.getMarkdownInSelection(selection)).trim();
if (text.isEmpty) {
- if (state is! ReadyAiWriterState) {
- return;
- }
final view = await ViewBackendService.getView(documentId).toNullable();
if (view == null ||
view.name.isEmpty ||
view.name == LocaleKeys.menuAppHeader_defaultNewPageName.tr()) {
- final readyState = state as ReadyAiWriterState;
+ final stateCopy = state;
emit(
- FailedContinueWritingAiWriterState(
+ DocumentContentEmptyAiWriterState(
command,
onConfirm: () {
if (isImmediateRun) {
- removeAiWriterNode(editorState, node);
+ removeAiWriterNode(editorState, aiWriterNode!);
}
},
),
);
- emit(readyState);
+ emit(stateCopy);
return;
} else {
- text += view.name;
+ text = view.name;
}
}
@@ -352,8 +376,11 @@ class AiWriterCubit extends Cubit<AiWriterState> {
history: records,
onStart: () async {
final transaction = editorState.transaction;
- final position =
- ensurePreviousNodeIsEmptyParagraph(editorState, node, transaction);
+ final position = ensurePreviousNodeIsEmptyParagraph(
+ editorState,
+ aiWriterNode!,
+ transaction,
+ );
transaction.afterSelection = null;
await editorState.apply(
transaction,
@@ -361,14 +388,17 @@ class AiWriterCubit extends Cubit<AiWriterState> {
inMemoryUpdate: true,
recordUndo: false,
),
+ withUpdateSelection: false,
);
_textRobot.start(position: position);
},
onProcess: (text) async {
await _textRobot.appendMarkdownText(
text,
+ updateSelection: false,
attributes: ApplySuggestionFormatType.replace.attributes,
);
+ onAppendToDocument?.call();
},
onEnd: () async {
if (state case GeneratingAiWriterState _) {
@@ -399,8 +429,10 @@ class AiWriterCubit extends Cubit<AiWriterState> {
AiWriterCommand command,
PredefinedFormat? predefinedFormat,
) async {
- final node = getAiWriterNode();
- final selection = node.aiWriterSelection;
+ if (aiWriterNode == null) {
+ return;
+ }
+ final selection = aiWriterNode?.aiWriterSelection;
if (selection == null) {
return;
}
@@ -420,8 +452,11 @@ class AiWriterCubit extends Cubit<AiWriterState> {
transaction,
ApplySuggestionFormatType.original,
);
- final position =
- ensurePreviousNodeIsEmptyParagraph(editorState, node, transaction);
+ final position = ensurePreviousNodeIsEmptyParagraph(
+ editorState,
+ aiWriterNode!,
+ transaction,
+ );
transaction.afterSelection = null;
await editorState.apply(
transaction,
@@ -429,14 +464,17 @@ class AiWriterCubit extends Cubit<AiWriterState> {
inMemoryUpdate: true,
recordUndo: false,
),
+ withUpdateSelection: false,
);
_textRobot.start(position: position);
},
onProcess: (text) async {
await _textRobot.appendMarkdownText(
text,
+ updateSelection: false,
attributes: ApplySuggestionFormatType.replace.attributes,
);
+ onAppendToDocument?.call();
},
onEnd: () async {
if (state is GeneratingAiWriterState) {
@@ -472,8 +510,10 @@ class AiWriterCubit extends Cubit<AiWriterState> {
AiWriterCommand command,
PredefinedFormat? predefinedFormat,
) async {
- final node = getAiWriterNode();
- final selection = node.aiWriterSelection;
+ if (aiWriterNode == null) {
+ return;
+ }
+ final selection = aiWriterNode?.aiWriterSelection;
if (selection == null) {
return;
}
@@ -524,101 +564,71 @@ class AiWriterCubit extends Cubit<AiWriterState> {
);
}
}
+}
- bool _cancelShortcutHandler(KeyEvent event) {
- if (event is! KeyUpEvent) {
- return false;
- }
-
- switch (event.logicalKey) {
- case LogicalKeyboardKey.escape:
- if (state case GeneratingAiWriterState _) {
- stopStream();
- } else if (hasUnusedResponse()) {
- final saveState = state;
- emit(
- FailedContinueWritingAiWriterState(
- state.command,
- onConfirm: () {
- stopStream();
- exit();
- },
- ),
- );
- emit(saveState);
- } else {
- stopStream();
- exit();
- }
- return true;
- case LogicalKeyboardKey.keyC
- when HardwareKeyboard.instance.logicalKeysPressed
- .contains(LogicalKeyboardKey.controlLeft):
- if (state case GeneratingAiWriterState _) {
- stopStream();
- }
- return true;
- default:
- break;
- }
-
- return false;
- }
+mixin RegisteredAiWriter {
+ AiWriterCommand get command;
}
sealed class AiWriterState {
- const AiWriterState(this.command);
+ const AiWriterState();
+}
- final AiWriterCommand command;
+class IdleAiWriterState extends AiWriterState {
+ const IdleAiWriterState();
}
-class ReadyAiWriterState extends AiWriterState {
+class ReadyAiWriterState extends AiWriterState with RegisteredAiWriter {
const ReadyAiWriterState(
- super.command, {
+ this.command, {
required this.isFirstRun,
this.markdownText = '',
});
+ @override
+ final AiWriterCommand command;
+
final bool isFirstRun;
final String markdownText;
}
-class GeneratingAiWriterState extends AiWriterState {
+class GeneratingAiWriterState extends AiWriterState with RegisteredAiWriter {
const GeneratingAiWriterState(
- super.command, {
+ this.command, {
required this.taskId,
this.progress = '',
this.markdownText = '',
});
+ @override
+ final AiWriterCommand command;
+
final String taskId;
final String progress;
final String markdownText;
}
-class ErrorAiWriterState extends AiWriterState {
+class ErrorAiWriterState extends AiWriterState with RegisteredAiWriter {
const ErrorAiWriterState(
- super.command, {
+ this.command, {
required this.error,
});
+ @override
+ final AiWriterCommand command;
+
final AIError error;
}
-class FailedContinueWritingAiWriterState extends AiWriterState {
- const FailedContinueWritingAiWriterState(
- super.command, {
+class DocumentContentEmptyAiWriterState extends AiWriterState
+ with RegisteredAiWriter {
+ const DocumentContentEmptyAiWriterState(
+ this.command, {
required this.onConfirm,
});
- final void Function() onConfirm;
-}
-
-class DiscardResponseAiWriterState extends AiWriterState {
- const DiscardResponseAiWriterState(
- super.command, {
- required this.onDiscard,
- });
+ @override
+ final AiWriterCommand command;
- final void Function() onDiscard;
+ final void Function() onConfirm;
}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_gesture_detector.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_gesture_detector.dart
index 84f785335b..8a691acdfc 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_gesture_detector.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_gesture_detector.dart
@@ -21,7 +21,10 @@ class AiWriterGestureDetector extends StatelessWidget {
TapGestureRecognizer:
GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(),
- (instance) => instance..onTapDown = (_) => onPointerEvent(),
+ (instance) => instance
+ ..onTapDown = ((_) => onPointerEvent())
+ ..onSecondaryTapDown = ((_) => onPointerEvent())
+ ..onTertiaryTapDown = ((_) => onPointerEvent()),
),
ImmediateMultiDragGestureRecognizer:
GestureRecognizerFactoryWithHandlers<
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart
new file mode 100644
index 0000000000..4c04baf557
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart
@@ -0,0 +1,223 @@
+import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:appflowy/util/throttle.dart';
+import 'package:appflowy/workspace/presentation/home/menu/sidebar/space/shared_widget.dart';
+import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
+import 'package:appflowy_editor/appflowy_editor.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+
+import '../operations/ai_writer_cubit.dart';
+import 'ai_writer_gesture_detector.dart';
+
+class AiWriterScrollWrapper extends StatefulWidget {
+ const AiWriterScrollWrapper({
+ super.key,
+ required this.viewId,
+ required this.editorState,
+ required this.child,
+ });
+
+ final String viewId;
+ final EditorState editorState;
+ final Widget child;
+
+ @override
+ State<AiWriterScrollWrapper> createState() => _AiWriterScrollWrapperState();
+}
+
+class _AiWriterScrollWrapperState extends State<AiWriterScrollWrapper> {
+ final overlayController = OverlayPortalController();
+ late final throttler = Throttler();
+ late final aiWriterCubit = AiWriterCubit(
+ documentId: widget.viewId,
+ editorState: widget.editorState,
+ onCreateNode: () {
+ aiWriterRegistered = true;
+ widget.editorState.service.keyboardService?.disableShortcuts();
+ HardwareKeyboard.instance.addHandler(cancelShortcutHandler);
+ },
+ onRemoveNode: () {
+ aiWriterRegistered = false;
+ HardwareKeyboard.instance.removeHandler(cancelShortcutHandler);
+ widget.editorState.service.keyboardService?.enableShortcuts();
+ },
+ onAppendToDocument: onAppendToDocument,
+ );
+
+ bool userHasScrolled = false;
+ bool aiWriterRegistered = false;
+
+ @override
+ void initState() {
+ super.initState();
+ overlayController.show();
+ }
+
+ @override
+ void dispose() {
+ aiWriterCubit.close();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return BlocProvider.value(
+ value: aiWriterCubit,
+ child: NotificationListener<ScrollNotification>(
+ onNotification: handleScrollNotification,
+ child: MultiBlocListener(
+ listeners: [
+ BlocListener<AiWriterCubit, AiWriterState>(
+ listener: (context, state) {
+ if (state is DocumentContentEmptyAiWriterState) {
+ showConfirmDialog(
+ context: context,
+ title: LocaleKeys.ai_continueWritingEmptyDocumentTitle.tr(),
+ description: LocaleKeys
+ .ai_continueWritingEmptyDocumentDescription
+ .tr(),
+ onConfirm: state.onConfirm,
+ );
+ }
+ },
+ ),
+ BlocListener<AiWriterCubit, AiWriterState>(
+ listenWhen: (previous, current) =>
+ previous is GeneratingAiWriterState &&
+ current is ReadyAiWriterState,
+ listener: (context, state) {
+ widget.editorState.updateSelectionWithReason(null);
+ },
+ ),
+ ],
+ child: OverlayPortal(
+ controller: overlayController,
+ overlayChildBuilder: (context) {
+ return BlocBuilder<AiWriterCubit, AiWriterState>(
+ builder: (context, state) {
+ return AiWriterGestureDetector(
+ behavior: state is RegisteredAiWriter
+ ? HitTestBehavior.translucent
+ : HitTestBehavior.deferToChild,
+ onPointerEvent: () => onTapOutside(context),
+ );
+ },
+ );
+ },
+ child: widget.child,
+ ),
+ ),
+ ),
+ );
+ }
+
+ bool handleScrollNotification(ScrollNotification notification) {
+ if (!aiWriterRegistered) {
+ return false;
+ }
+
+ if (notification is UserScrollNotification) {
+ debounceResetUserHasScrolled();
+ userHasScrolled = true;
+ throttler.cancel();
+ }
+
+ return false;
+ }
+
+ void debounceResetUserHasScrolled() {
+ Debounce.debounce(
+ 'user_has_scrolled',
+ const Duration(seconds: 3),
+ () => userHasScrolled = false,
+ );
+ }
+
+ void onTapOutside(BuildContext context) {
+ final aiWriterCubit = context.read<AiWriterCubit>();
+
+ if (aiWriterCubit.hasUnusedResponse()) {
+ showConfirmDialog(
+ context: context,
+ title: LocaleKeys.button_discard.tr(),
+ description: LocaleKeys.document_plugins_discardResponse.tr(),
+ confirmLabel: LocaleKeys.button_discard.tr(),
+ style: ConfirmPopupStyle.cancelAndOk,
+ onConfirm: () {
+ Future(() async {
+ await aiWriterCubit.stopStream();
+ await aiWriterCubit.exit();
+ });
+ },
+ onCancel: () {},
+ );
+ } else {
+ Future(() async {
+ await aiWriterCubit.stopStream();
+ await aiWriterCubit.exit();
+ });
+ }
+ }
+
+ bool cancelShortcutHandler(KeyEvent event) {
+ if (event is! KeyUpEvent) {
+ return false;
+ }
+
+ switch (event.logicalKey) {
+ case LogicalKeyboardKey.escape:
+ if (aiWriterCubit.state case GeneratingAiWriterState _) {
+ aiWriterCubit.stopStream();
+ } else if (aiWriterCubit.hasUnusedResponse()) {
+ showConfirmDialog(
+ context: context,
+ title: LocaleKeys.button_discard.tr(),
+ description: LocaleKeys.document_plugins_discardResponse.tr(),
+ confirmLabel: LocaleKeys.button_discard.tr(),
+ style: ConfirmPopupStyle.cancelAndOk,
+ onConfirm: () {
+ Future(() async {
+ await aiWriterCubit.stopStream();
+ await aiWriterCubit.exit();
+ });
+ },
+ onCancel: () {},
+ );
+ } else {
+ Future(() async {
+ await aiWriterCubit.stopStream();
+ await aiWriterCubit.exit();
+ });
+ }
+ return true;
+ case LogicalKeyboardKey.keyC
+ when HardwareKeyboard.instance.logicalKeysPressed
+ .contains(LogicalKeyboardKey.controlLeft):
+ if (aiWriterCubit.state case GeneratingAiWriterState _) {
+ aiWriterCubit.stopStream();
+ }
+ return true;
+ default:
+ break;
+ }
+
+ return false;
+ }
+
+ void onAppendToDocument() {
+ if (!aiWriterRegistered || userHasScrolled) {
+ return;
+ }
+
+ throttler.call(() {
+ if (aiWriterCubit.aiWriterNode != null) {
+ final path = aiWriterCubit.aiWriterNode!.path;
+ widget.editorState.updateSelectionWithReason(
+ Selection.collapsed(Position(path: path)),
+ );
+ }
+ });
+ }
+}
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
index 58c4deb1b1..1904b10934 100644
--- 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
@@ -70,6 +70,7 @@ class MarkdownTextRobot {
/// The text will be inserted into the document but only in memory
Future<void> appendMarkdownText(
String text, {
+ bool updateSelection = true,
Map<String, dynamic>? attributes,
}) async {
_markdownText += text;
@@ -77,6 +78,7 @@ class MarkdownTextRobot {
await _lock.synchronized(() async {
await _refresh(
inMemoryUpdate: true,
+ updateSelection: updateSelection,
attributes: attributes,
);
});
@@ -95,7 +97,6 @@ class MarkdownTextRobot {
await _lock.synchronized(() async {
await _refresh(
inMemoryUpdate: true,
- updateSelection: false,
attributes: attributes,
);
});
@@ -155,7 +156,7 @@ class MarkdownTextRobot {
Future<void> _refresh({
required bool inMemoryUpdate,
- bool updateSelection = true,
+ bool updateSelection = false,
Map<String, dynamic>? attributes,
}) async {
final position = _insertPosition;
@@ -203,10 +204,6 @@ class MarkdownTextRobot {
offset: lastDelta.length,
),
);
-
- if (!updateSelection) {
- insertTransaction.afterSelection = null;
- }
}
await editorState.apply(
@@ -215,6 +212,7 @@ class MarkdownTextRobot {
inMemoryUpdate: inMemoryUpdate,
recordUndo: !inMemoryUpdate,
),
+ withUpdateSelection: updateSelection,
);
_insertedNodes = newNodes;
diff --git a/frontend/appflowy_flutter/lib/util/throttle.dart b/frontend/appflowy_flutter/lib/util/throttle.dart
index c8c6dcf0ca..0aaa9f2d3a 100644
--- a/frontend/appflowy_flutter/lib/util/throttle.dart
+++ b/frontend/appflowy_flutter/lib/util/throttle.dart
@@ -16,6 +16,10 @@ class Throttler {
});
}
+ void cancel() {
+ _timer?.cancel();
+ }
+
void dispose() {
_timer?.cancel();
_timer = null;
diff --git a/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dart
index aab5de8169..2abd4ffb97 100644
--- a/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dart
+++ b/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dart
@@ -162,20 +162,22 @@ void main() {
);
final editorState = EditorState(document: document)
..selection = selection;
- final command = AiWriterCommand.explain;
- final node = aiWriterNode(
- command: command,
- selection: selection,
- );
return AiWriterCubit(
documentId: '',
- getAiWriterNode: () => node,
editorState: editorState,
- initialCommand: command,
aiService: _MockAIRepository(),
);
},
- act: (bloc) => bloc.init(),
+ act: (bloc) => bloc.register(
+ aiWriterNode(
+ command: AiWriterCommand.explain,
+ selection: Selection(
+ start: Position(path: [0]),
+ end: Position(path: [2], offset: text3.length),
+ ),
+ ),
+ ),
+ wait: Duration(seconds: 1),
expect: () => [
isA<GeneratingAiWriterState>()
.having((s) => s.markdownText, 'result', isEmpty),
@@ -216,19 +218,22 @@ void main() {
);
final editorState = EditorState(document: document)
..selection = selection;
- final node = aiWriterNode(
- command: AiWriterCommand.explain,
- selection: selection,
- );
return AiWriterCubit(
documentId: '',
- getAiWriterNode: () => node,
editorState: editorState,
- initialCommand: AiWriterCommand.explain,
aiService: _MockErrorRepository(),
);
},
- act: (bloc) => bloc.init(),
+ act: (bloc) => bloc.register(
+ aiWriterNode(
+ command: AiWriterCommand.explain,
+ selection: Selection(
+ start: Position(path: [0]),
+ end: Position(path: [2], offset: text3.length),
+ ),
+ ),
+ ),
+ wait: Duration(seconds: 1),
expect: () => [
isA<GeneratingAiWriterState>()
.having((s) => s.markdownText, 'result', isEmpty),
@@ -264,12 +269,10 @@ void main() {
final aiNode = editorState.getNodeAtPath([3])!;
final bloc = AiWriterCubit(
documentId: '',
- getAiWriterNode: () => aiNode,
editorState: editorState,
- initialCommand: AiWriterCommand.improveWriting,
aiService: _MockAIRepository(),
);
- bloc.init();
+ bloc.register(aiNode);
await blocResponseFuture();
bloc.runResponseAction(SuggestionAction.accept);
await blocResponseFuture();
@@ -314,12 +317,10 @@ void main() {
final aiNode = editorState.getNodeAtPath([3])!;
final bloc = AiWriterCubit(
documentId: '',
- getAiWriterNode: () => aiNode,
editorState: editorState,
- initialCommand: AiWriterCommand.improveWriting,
aiService: _MockAIRepository(),
);
- bloc.init();
+ bloc.register(aiNode);
await blocResponseFuture();
bloc.runResponseAction(SuggestionAction.discard);
await blocResponseFuture();
@@ -355,12 +356,10 @@ void main() {
final aiNode = editorState.getNodeAtPath([3])!;
final bloc = AiWriterCubit(
documentId: '',
- getAiWriterNode: () => aiNode,
editorState: editorState,
- initialCommand: AiWriterCommand.improveWriting,
aiService: _MockAIRepositoryLess(),
);
- bloc.init();
+ bloc.register(aiNode);
await blocResponseFuture();
bloc.runResponseAction(SuggestionAction.accept);
await blocResponseFuture();
@@ -394,12 +393,10 @@ void main() {
final aiNode = editorState.getNodeAtPath([3])!;
final bloc = AiWriterCubit(
documentId: '',
- getAiWriterNode: () => aiNode,
editorState: editorState,
- initialCommand: AiWriterCommand.improveWriting,
aiService: _MockAIRepositoryMore(),
);
- bloc.init();
+ bloc.register(aiNode);
await blocResponseFuture();
bloc.runResponseAction(SuggestionAction.accept);
await blocResponseFuture();