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.

refacotr: ai chat page folder strcture (#7879)

Lucas926a5b31bb03
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/ai_chat_prelude.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/ai_chat_prelude.dart
new file mode 100644
index 0000000000..5275c643c2
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/ai_chat_prelude.dart
@@ -0,0 +1,15 @@
+export 'ai_model_switch_listener.dart';
+export 'chat_ai_message_bloc.dart';
+export 'chat_bloc.dart';
+export 'chat_edit_document_service.dart';
+export 'chat_entity.dart';
+export 'chat_input_control_cubit.dart';
+export 'chat_input_file_bloc.dart';
+export 'chat_member_bloc.dart';
+export 'chat_message_listener.dart';
+export 'chat_message_service.dart';
+export 'chat_message_stream.dart';
+export 'chat_notification.dart';
+export 'chat_select_message_bloc.dart';
+export 'chat_select_sources_cubit.dart';
+export 'chat_user_message_bloc.dart';
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
index a22a3f182f..733ee7b034 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
@@ -1,39 +1,15 @@
-import 'dart:io';
-
import 'package:appflowy/ai/ai.dart';
-import 'package:appflowy/plugins/ai_chat/presentation/chat_message_selector_banner.dart';
-import 'package:appflowy/workspace/application/view/view_service.dart';
-import 'package:appflowy/workspace/presentation/home/home_stack.dart';
-import 'package:appflowy_backend/log.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_page/chat_content_page.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
-import 'package:appflowy_result/appflowy_result.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
-import 'package:flutter_chat_core/flutter_chat_core.dart';
-import 'package:flutter_chat_ui/flutter_chat_ui.dart'
- hide ChatAnimatedListReversed;
-import 'package:string_validator/string_validator.dart';
-import 'package:universal_platform/universal_platform.dart';
-import 'package:url_launcher/url_launcher.dart';
import 'application/chat_bloc.dart';
import 'application/chat_entity.dart';
import 'application/chat_member_bloc.dart';
-import 'application/chat_select_message_bloc.dart';
-import 'application/chat_message_stream.dart';
-import 'presentation/animated_chat_list.dart';
-import 'presentation/chat_input/mobile_chat_input.dart';
-import 'presentation/chat_related_question.dart';
-import 'presentation/chat_welcome_page.dart';
-import 'presentation/layout_define.dart';
-import 'presentation/message/ai_text_message.dart';
-import 'presentation/message/error_text_message.dart';
-import 'presentation/message/message_util.dart';
-import 'presentation/message/user_text_message.dart';
-import 'presentation/scroll_to_bottom.dart';
class AIChatPage extends StatelessWidget {
const AIChatPage({
@@ -49,15 +25,6 @@ class AIChatPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
- // if (userProfile.authenticator != AuthTypePB.Server) {
- // return Center(
- // child: FlowyText(
- // LocaleKeys.chat_unsupportedCloudPrompt.tr(),
- // fontSize: 20,
- // ),
- // );
- // }
-
return MultiBlocProvider(
providers: [
/// [ChatBloc] is used to handle chat messages including send/receive message
@@ -111,7 +78,7 @@ class AIChatPage extends StatelessWidget {
return KeyEventResult.ignored;
},
- child: _ChatContentPage(
+ child: ChatContentPage(
view: view,
userProfile: userProfile,
),
@@ -122,371 +89,3 @@ class AIChatPage extends StatelessWidget {
);
}
}
-
-class _ChatContentPage extends StatelessWidget {
- const _ChatContentPage({
- required this.view,
- required this.userProfile,
- });
-
- final UserProfilePB userProfile;
- final ViewPB view;
-
- @override
- Widget build(BuildContext context) {
- return BlocBuilder<ChatBloc, ChatState>(
- builder: (context, state) {
- return switch (state.loadingState) {
- LoadChatMessageStatus.ready => Column(
- children: [
- ChatMessageSelectorBanner(
- view: view,
- allMessages: context.read<ChatBloc>().chatController.messages,
- ),
- Expanded(
- child: Align(
- alignment: Alignment.topCenter,
- child: _wrapConstraints(
- SelectionArea(
- child: ScrollConfiguration(
- behavior: ScrollConfiguration.of(context)
- .copyWith(scrollbars: false),
- child: Chat(
- chatController:
- context.read<ChatBloc>().chatController,
- user: User(id: userProfile.id.toString()),
- darkTheme:
- ChatTheme.fromThemeData(Theme.of(context)),
- theme: ChatTheme.fromThemeData(Theme.of(context)),
- builders: Builders(
- inputBuilder: (_) => const SizedBox.shrink(),
- textMessageBuilder: _buildTextMessage,
- chatMessageBuilder: _buildChatMessage,
- scrollToBottomBuilder: _buildScrollToBottom,
- chatAnimatedListBuilder: _buildChatAnimatedList,
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- _wrapConstraints(
- _Input(view: view),
- ),
- ],
- ),
- _ => const Center(child: CircularProgressIndicator.adaptive()),
- };
- },
- );
- }
-
- Widget _wrapConstraints(Widget child) {
- return Container(
- constraints: const BoxConstraints(maxWidth: 784),
- margin: UniversalPlatform.isDesktop
- ? const EdgeInsets.symmetric(horizontal: 60.0)
- : null,
- child: child,
- );
- }
-
- Widget _buildTextMessage(
- BuildContext context,
- TextMessage message,
- ) {
- final messageType = onetimeMessageTypeFromMeta(
- message.metadata,
- );
-
- if (messageType == OnetimeShotType.error) {
- return ChatErrorMessageWidget(
- errorMessage: message.metadata?[errorMessageTextKey] ?? "",
- );
- }
-
- if (messageType == OnetimeShotType.relatedQuestion) {
- return RelatedQuestionList(
- relatedQuestions: message.metadata!['questions'],
- onQuestionSelected: (question) {
- final bloc = context.read<AIPromptInputBloc>();
- final showPredefinedFormats = bloc.state.showPredefinedFormats;
- final predefinedFormat = bloc.state.predefinedFormat;
-
- context.read<ChatBloc>().add(
- ChatEvent.sendMessage(
- message: question,
- format: showPredefinedFormats ? predefinedFormat : null,
- ),
- );
- },
- );
- }
-
- if (message.author.id == userProfile.id.toString() ||
- isOtherUserMessage(message)) {
- return ChatUserMessageWidget(
- user: message.author,
- message: message,
- );
- }
-
- final stream = message.metadata?["$AnswerStream"];
- final questionId = message.metadata?[messageQuestionIdKey];
- final refSourceJsonString =
- message.metadata?[messageRefSourceJsonStringKey] as String?;
-
- return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
- selector: (state) => state.isSelectingMessages,
- builder: (context, isSelectingMessages) {
- return BlocBuilder<ChatBloc, ChatState>(
- builder: (context, state) {
- final chatController = context.read<ChatBloc>().chatController;
- final messages = chatController.messages
- .where((e) => onetimeMessageTypeFromMeta(e.metadata) == null);
- final isLastMessage =
- messages.isEmpty ? false : messages.last.id == message.id;
- return ChatAIMessageWidget(
- user: message.author,
- messageUserId: message.id,
- message: message,
- stream: stream is AnswerStream ? stream : null,
- questionId: questionId,
- chatId: view.id,
- refSourceJsonString: refSourceJsonString,
- isStreaming:
- state.promptResponseState != PromptResponseState.ready,
- isLastMessage: isLastMessage,
- isSelectingMessages: isSelectingMessages,
- onSelectedMetadata: (metadata) =>
- _onSelectMetadata(context, metadata),
- onRegenerate: () => context
- .read<ChatBloc>()
- .add(ChatEvent.regenerateAnswer(message.id, null, null)),
- onChangeFormat: (format) => context
- .read<ChatBloc>()
- .add(ChatEvent.regenerateAnswer(message.id, format, null)),
- onChangeModel: (model) => context
- .read<ChatBloc>()
- .add(ChatEvent.regenerateAnswer(message.id, null, model)),
- onStopStream: () => context.read<ChatBloc>().add(
- const ChatEvent.stopStream(),
- ),
- );
- },
- );
- },
- );
- }
-
- Widget _buildChatMessage(
- BuildContext context,
- Message message,
- Animation<double> animation,
- Widget child,
- ) {
- return ChatMessage(
- message: message,
- animation: animation,
- padding: const EdgeInsets.symmetric(vertical: 18.0),
- receivedMessageScaleAnimationAlignment: Alignment.center,
- child: child,
- );
- }
-
- Widget _buildScrollToBottom(
- BuildContext context,
- Animation<double> animation,
- VoidCallback onPressed,
- ) {
- return CustomScrollToBottom(
- animation: animation,
- onPressed: onPressed,
- );
- }
-
- Widget _buildChatAnimatedList(
- BuildContext context,
- ScrollController scrollController,
- ChatItem itemBuilder,
- ) {
- final bloc = context.read<ChatBloc>();
-
- if (bloc.chatController.messages.isEmpty) {
- return ChatWelcomePage(
- userProfile: userProfile,
- onSelectedQuestion: (question) {
- final aiPromptInputBloc = context.read<AIPromptInputBloc>();
- final showPredefinedFormats =
- aiPromptInputBloc.state.showPredefinedFormats;
- final predefinedFormat = aiPromptInputBloc.state.predefinedFormat;
- bloc.add(
- ChatEvent.sendMessage(
- message: question,
- format: showPredefinedFormats ? predefinedFormat : null,
- ),
- );
- },
- );
- }
-
- context
- .read<ChatSelectMessageBloc>()
- .add(ChatSelectMessageEvent.enableStartSelectingMessages());
-
- return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
- selector: (state) => state.isSelectingMessages,
- builder: (context, isSelectingMessages) {
- return ChatAnimatedListReversed(
- scrollController: scrollController,
- itemBuilder: itemBuilder,
- bottomPadding: isSelectingMessages
- ? 48.0 + DesktopAIChatSizes.messageActionBarIconSize
- : 8.0,
- onLoadPreviousMessages: () {
- bloc.add(const ChatEvent.loadPreviousMessages());
- },
- );
- },
- );
- }
-
- void _onSelectMetadata(
- BuildContext context,
- ChatMessageRefSource metadata,
- ) async {
- // When the source of metatdata is appflowy, which means it is a appflowy page
- if (metadata.source == "appflowy") {
- final sidebarView =
- await ViewBackendService.getView(metadata.id).toNullable();
- if (context.mounted) {
- openPageFromMessage(context, sidebarView);
- }
- return;
- }
-
- if (metadata.source == "web") {
- if (isURL(metadata.name)) {
- late Uri uri;
- try {
- uri = Uri.parse(metadata.name);
- // `Uri` identifies `localhost` as a scheme
- if (!uri.hasScheme || uri.scheme == 'localhost') {
- uri = Uri.parse("http://${metadata.name}");
- await InternetAddress.lookup(uri.host);
- }
- await launchUrl(uri);
- } catch (err) {
- Log.error("failed to open url $err");
- }
- }
- return;
- }
- }
-}
-
-class _Input extends StatefulWidget {
- const _Input({
- required this.view,
- });
-
- final ViewPB view;
-
- @override
- State<_Input> createState() => _InputState();
-}
-
-class _InputState extends State<_Input> {
- final textController = AiPromptInputTextEditingController();
-
- @override
- void dispose() {
- textController.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
- selector: (state) => state.isSelectingMessages,
- builder: (context, isSelectingMessages) {
- return AnimatedSwitcher(
- duration: const Duration(milliseconds: 150),
- transitionBuilder: (child, animation) {
- return NonClippingSizeTransition(
- sizeFactor: animation,
- axisAlignment: -1,
- child: child,
- );
- },
- child: isSelectingMessages
- ? const SizedBox.shrink()
- : Padding(
- padding: AIChatUILayout.safeAreaInsets(context),
- child: BlocSelector<ChatBloc, ChatState, bool>(
- selector: (state) {
- return state.promptResponseState ==
- PromptResponseState.ready;
- },
- builder: (context, canSendMessage) {
- final chatBloc = context.read<ChatBloc>();
-
- return UniversalPlatform.isDesktop
- ? DesktopPromptInput(
- isStreaming: !canSendMessage,
- textController: textController,
- onStopStreaming: () {
- chatBloc.add(const ChatEvent.stopStream());
- },
- onSubmitted: (text, format, metadata) {
- chatBloc.add(
- ChatEvent.sendMessage(
- message: text,
- format: format,
- metadata: metadata,
- ),
- );
- },
- selectedSourcesNotifier:
- chatBloc.selectedSourcesNotifier,
- onUpdateSelectedSources: (ids) {
- chatBloc.add(
- ChatEvent.updateSelectedSources(
- selectedSourcesIds: ids,
- ),
- );
- },
- )
- : MobileChatInput(
- isStreaming: !canSendMessage,
- onStopStreaming: () {
- chatBloc.add(const ChatEvent.stopStream());
- },
- onSubmitted: (text, format, metadata) {
- chatBloc.add(
- ChatEvent.sendMessage(
- message: text,
- format: format,
- metadata: metadata,
- ),
- );
- },
- selectedSourcesNotifier:
- chatBloc.selectedSourcesNotifier,
- onUpdateSelectedSources: (ids) {
- chatBloc.add(
- ChatEvent.updateSelectedSources(
- selectedSourcesIds: ids,
- ),
- );
- },
- );
- },
- ),
- ),
- );
- },
- );
- }
-}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list.dart
index 9b7aadf4a4..d24055d581 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list.dart
@@ -11,8 +11,8 @@ import 'package:flutter_chat_ui/src/scroll_to_bottom.dart';
import 'package:flutter_chat_ui/src/utils/message_list_diff.dart';
import 'package:provider/provider.dart';
-class ChatAnimatedListReversed extends StatefulWidget {
- const ChatAnimatedListReversed({
+class ChatAnimatedList extends StatefulWidget {
+ const ChatAnimatedList({
super.key,
required this.scrollController,
required this.itemBuilder,
@@ -22,6 +22,7 @@ class ChatAnimatedListReversed extends StatefulWidget {
this.scrollToBottomAppearanceDelay = const Duration(milliseconds: 250),
this.bottomPadding = 8,
this.onLoadPreviousMessages,
+ this.scrollBottomPadding = 440,
});
final ScrollController scrollController;
@@ -32,16 +33,19 @@ class ChatAnimatedListReversed extends StatefulWidget {
final Duration scrollToBottomAppearanceDelay;
final double? bottomPadding;
final VoidCallback? onLoadPreviousMessages;
+ final double scrollBottomPadding;
@override
- ChatAnimatedListReversedState createState() =>
- ChatAnimatedListReversedState();
+ ChatAnimatedListState createState() => ChatAnimatedListState();
}
-class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
+class ChatAnimatedListState extends State<ChatAnimatedList>
with SingleTickerProviderStateMixin {
final GlobalKey<SliverAnimatedListState> _listKey = GlobalKey();
- late ChatController _chatController;
+ late final ChatController _chatController = Provider.of<ChatController>(
+ context,
+ listen: false,
+ );
late List<Message> _oldList;
late StreamSubscription<ChatOperation> _operationsSubscription;
@@ -51,12 +55,12 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
bool _userHasScrolled = false;
bool _isScrollingToBottom = false;
- String _lastInsertedMessageId = '';
+ // String _lastInsertedMessageId = '';
@override
void initState() {
super.initState();
- _chatController = Provider.of<ChatController>(context, listen: false);
+
// TODO: Add assert for messages having same id
_oldList = List.from(_chatController.messages);
_operationsSubscription = _chatController.operationsStream.listen((event) {
@@ -109,12 +113,14 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
vsync: this,
duration: const Duration(milliseconds: 300),
);
+
_scrollToBottomAnimation = CurvedAnimation(
parent: _scrollToBottomController,
curve: Curves.easeInOut,
);
widget.scrollController.addListener(_handleLoadPreviousMessages);
+
WidgetsBinding.instance.addPostFrameCallback((_) {
_handleLoadPreviousMessages();
});
@@ -132,6 +138,7 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
@override
Widget build(BuildContext context) {
final builders = context.watch<Builders>();
+ final height = MediaQuery.of(context).size.height;
return NotificationListener<Notification>(
onNotification: (notification) {
@@ -142,7 +149,7 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
} else {
// When user overscolls to the bottom or stays idle at the bottom, set `_userHasScrolled` to false
if (notification.metrics.pixels ==
- notification.metrics.minScrollExtent) {
+ notification.metrics.maxScrollExtent) {
_userHasScrolled = false;
}
}
@@ -158,8 +165,8 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
child: Stack(
children: [
CustomScrollView(
- reverse: true,
controller: widget.scrollController,
+ physics: ClampingScrollPhysics(),
slivers: <Widget>[
SliverPadding(
padding: EdgeInsets.only(
@@ -174,15 +181,22 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
int index,
Animation<double> animation,
) {
- final message = _chatController.messages[
- max(_chatController.messages.length - 1 - index, 0)];
- return widget.itemBuilder(
+ final message = _chatController.messages[index];
+ final child = widget.itemBuilder(
context,
animation,
message,
);
+ return RepaintBoundary(
+ child: child,
+ );
},
),
+ SliverPadding(
+ padding: EdgeInsets.only(
+ bottom: max(0, height - widget.scrollBottomPadding),
+ ),
+ ),
],
),
builders.scrollToBottomBuilder?.call(
@@ -199,53 +213,62 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
);
}
- void _subsequentScrollToEnd(Message data) async {
- final user = Provider.of<User>(context, listen: false);
-
- // We only want to scroll to the bottom if user has not scrolled up
- // or if the message is sent by the current user.
- if (data.id == _lastInsertedMessageId &&
- widget.scrollController.offset >
- widget.scrollController.position.minScrollExtent &&
- (user.id == data.author.id && _userHasScrolled)) {
- if (widget.scrollToEndAnimationDuration == Duration.zero) {
- widget.scrollController
- .jumpTo(widget.scrollController.position.minScrollExtent);
- } else {
- await widget.scrollController.animateTo(
- widget.scrollController.position.minScrollExtent,
- duration: widget.scrollToEndAnimationDuration,
- curve: Curves.linearToEaseOut,
- );
- }
-
- if (!widget.scrollController.hasClients || !mounted) return;
-
- // Because of the issue I have opened here https://github.com/flutter/flutter/issues/129768
- // we need an additional jump to the end. Sometimes Flutter
- // will not scroll to the very end. Sometimes it will not scroll to the
- // very end even with this, so this is something that needs to be
- // addressed by the Flutter team.
- //
- // Additionally here we have a check for the message id, because
- // if new message arrives in the meantime it will trigger another
- // scroll to the end animation, making this logic redundant.
- if (data.id == _lastInsertedMessageId &&
- widget.scrollController.offset >
- widget.scrollController.position.minScrollExtent &&
- (user.id == data.author.id && _userHasScrolled)) {
- widget.scrollController
- .jumpTo(widget.scrollController.position.minScrollExtent);
- }
- }
- }
-
- void _scrollToEnd(Message data) {
+ // void _subsequentScrollToEnd(Message data) async {
+ // final user = Provider.of<User>(context, listen: false);
+
+ // // We only want to scroll to the bottom if user has not scrolled up
+ // // or if the message is sent by the current user.
+ // if (data.id == _lastInsertedMessageId &&
+ // widget.scrollController.offset <
+ // widget.scrollController.position.maxScrollExtent &&
+ // (user.id != data.author.id && !_userHasScrolled)) {
+ // if (widget.scrollToEndAnimationDuration == Duration.zero) {
+ // widget.scrollController
+ // .jumpTo(widget.scrollController.position.maxScrollExtent);
+ // } else {
+ // await widget.scrollController.animateTo(
+ // widget.scrollController.position.maxScrollExtent,
+ // duration: widget.scrollToEndAnimationDuration,
+ // curve: Curves.linearToEaseOut,
+ // );
+ // }
+
+ // if (!widget.scrollController.hasClients || !mounted) return;
+
+ // // Because of the issue I have opened here https://github.com/flutter/flutter/issues/129768
+ // // we need an additional jump to the end. Sometimes Flutter
+ // // will not scroll to the very end. Sometimes it will not scroll to the
+ // // very end even with this, so this is something that needs to be
+ // // addressed by the Flutter team.
+ // //
+ // // Additionally here we have a check for the message id, because
+ // // if new message arrives in the meantime it will trigger another
+ // // scroll to the end animation, making this logic redundant.
+ // if (data.id == _lastInsertedMessageId &&
+ // widget.scrollController.offset <
+ // widget.scrollController.position.maxScrollExtent &&
+ // (user.id == data.author.id && _userHasScrolled)) {
+ // widget.scrollController
+ // .jumpTo(widget.scrollController.position.maxScrollExtent);
+ // }
+ // }
+ // }
+
+ void _scrollToTop(Message data) {
WidgetsBinding.instance.addPostFrameCallback(
(_) {
if (!widget.scrollController.hasClients || !mounted) return;
- _subsequentScrollToEnd(data);
+ final user = Provider.of<User>(context, listen: false);
+ final lastMessage = _chatController.messages.last;
+ if (lastMessage.author.id == user.id) {
+ // scroll the current message to the top
+ widget.scrollController.animateTo(
+ widget.scrollController.position.maxScrollExtent,
+ duration: Durations.medium4,
+ curve: Curves.linearToEaseOut,
+ );
+ }
},
);
}
@@ -257,12 +280,16 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!widget.scrollController.hasClients || !mounted) return;
+ final height = MediaQuery.of(context).size.height;
+ final paddingHeight = height - widget.scrollBottomPadding;
+ final offset =
+ widget.scrollController.position.maxScrollExtent - paddingHeight;
+
if (widget.scrollToEndAnimationDuration == Duration.zero) {
- widget.scrollController
- .jumpTo(widget.scrollController.position.minScrollExtent);
+ widget.scrollController.jumpTo(offset);
} else {
await widget.scrollController.animateTo(
- widget.scrollController.position.minScrollExtent,
+ offset,
duration: widget.scrollToEndAnimationDuration,
curve: Curves.linearToEaseOut,
);
@@ -270,13 +297,6 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
if (!widget.scrollController.hasClients || !mounted) return;
- if (widget.scrollController.offset <
- widget.scrollController.position.minScrollExtent) {
- widget.scrollController.jumpTo(
- widget.scrollController.position.minScrollExtent,
- );
- }
-
_isScrollingToBottom = false;
});
}
@@ -286,9 +306,11 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
return;
}
+ final paddingHeight =
+ MediaQuery.of(context).size.height - widget.scrollBottomPadding;
_scrollToBottomShowTimer?.cancel();
- if (widget.scrollController.offset >
- widget.scrollController.position.minScrollExtent) {
+ if (widget.scrollController.offset <
+ widget.scrollController.position.maxScrollExtent - paddingHeight) {
_scrollToBottomShowTimer =
Timer(widget.scrollToBottomAppearanceDelay, () {
if (mounted) {
@@ -312,8 +334,8 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
// animation is triggered.
if (position == 0 &&
_userHasScrolled &&
- widget.scrollController.offset >
- widget.scrollController.position.minScrollExtent) {
+ widget.scrollController.offset <
+ widget.scrollController.position.maxScrollExtent) {
_userHasScrolled = false;
}
@@ -323,10 +345,11 @@ class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
);
// Used later to trigger scroll to end only for the last inserted message.
- _lastInsertedMessageId = data.id;
+ // _lastInsertedMessageId = data.id;
if (position == _oldList.length) {
- _scrollToEnd(data);
+ _scrollToTop(data);
+ // _scrollToEnd(data);
}
}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list_reversed.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list_reversed.dart
new file mode 100644
index 0000000000..b425192c3e
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/animated_chat_list_reversed.dart
@@ -0,0 +1,375 @@
+// ignore_for_file: implementation_imports
+
+import 'dart:async';
+import 'dart:math';
+
+import 'package:diffutil_dart/diffutil.dart' as diffutil;
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_chat_core/flutter_chat_core.dart';
+import 'package:flutter_chat_ui/src/scroll_to_bottom.dart';
+import 'package:flutter_chat_ui/src/utils/message_list_diff.dart';
+import 'package:provider/provider.dart';
+
+class ChatAnimatedListReversed extends StatefulWidget {
+ const ChatAnimatedListReversed({
+ super.key,
+ required this.scrollController,
+ required this.itemBuilder,
+ this.insertAnimationDuration = const Duration(milliseconds: 250),
+ this.removeAnimationDuration = const Duration(milliseconds: 250),
+ this.scrollToEndAnimationDuration = const Duration(milliseconds: 250),
+ this.scrollToBottomAppearanceDelay = const Duration(milliseconds: 250),
+ this.bottomPadding = 8,
+ this.onLoadPreviousMessages,
+ });
+
+ final ScrollController scrollController;
+ final ChatItem itemBuilder;
+ final Duration insertAnimationDuration;
+ final Duration removeAnimationDuration;
+ final Duration scrollToEndAnimationDuration;
+ final Duration scrollToBottomAppearanceDelay;
+ final double? bottomPadding;
+ final VoidCallback? onLoadPreviousMessages;
+
+ @override
+ ChatAnimatedListReversedState createState() =>
+ ChatAnimatedListReversedState();
+}
+
+class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
+ with SingleTickerProviderStateMixin {
+ final GlobalKey<SliverAnimatedListState> _listKey = GlobalKey();
+ late final ChatController _chatController = Provider.of<ChatController>(
+ context,
+ listen: false,
+ );
+ late List<Message> _oldList;
+ late StreamSubscription<ChatOperation> _operationsSubscription;
+
+ late final AnimationController _scrollToBottomController;
+ late final Animation<double> _scrollToBottomAnimation;
+ Timer? _scrollToBottomShowTimer;
+
+ bool _userHasScrolled = false;
+ bool _isScrollingToBottom = false;
+ String _lastInsertedMessageId = '';
+
+ @override
+ void initState() {
+ super.initState();
+
+ // TODO: Add assert for messages having same id
+ _oldList = List.from(_chatController.messages);
+ _operationsSubscription = _chatController.operationsStream.listen((event) {
+ switch (event.type) {
+ case ChatOperationType.insert:
+ assert(
+ event.index != null,
+ 'Index must be provided when inserting a message.',
+ );
+ assert(
+ event.message != null,
+ 'Message must be provided when inserting a message.',
+ );
+ _onInserted(event.index!, event.message!);
+ _oldList = List.from(_chatController.messages);
+ break;
+ case ChatOperationType.remove:
+ assert(
+ event.index != null,
+ 'Index must be provided when removing a message.',
+ );
+ assert(
+ event.message != null,
+ 'Message must be provided when removing a message.',
+ );
+ _onRemoved(event.index!, event.message!);
+ _oldList = List.from(_chatController.messages);
+ break;
+ case ChatOperationType.set:
+ final newList = _chatController.messages;
+
+ final updates = diffutil
+ .calculateDiff<Message>(
+ MessageListDiff(_oldList, newList),
+ )
+ .getUpdatesWithData();
+
+ for (var i = updates.length - 1; i >= 0; i--) {
+ _onDiffUpdate(updates.elementAt(i));
+ }
+
+ _oldList = List.from(newList);
+ break;
+ default:
+ break;
+ }
+ });
+
+ _scrollToBottomController = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 300),
+ );
+
+ _scrollToBottomAnimation = CurvedAnimation(
+ parent: _scrollToBottomController,
+ curve: Curves.easeInOut,
+ );
+
+ widget.scrollController.addListener(_handleLoadPreviousMessages);
+
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _handleLoadPreviousMessages();
+ });
+ }
+
+ @override
+ void dispose() {
+ super.dispose();
+ _scrollToBottomShowTimer?.cancel();
+ _scrollToBottomController.dispose();
+ _operationsSubscription.cancel();
+ widget.scrollController.removeListener(_handleLoadPreviousMessages);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final builders = context.watch<Builders>();
+
+ return NotificationListener<Notification>(
+ onNotification: (notification) {
+ if (notification is UserScrollNotification) {
+ // When user scrolls up, save it to `_userHasScrolled`
+ if (notification.direction == ScrollDirection.reverse) {
+ _userHasScrolled = true;
+ } else {
+ // When user overscolls to the bottom or stays idle at the bottom, set `_userHasScrolled` to false
+ if (notification.metrics.pixels ==
+ notification.metrics.minScrollExtent) {
+ _userHasScrolled = false;
+ }
+ }
+ }
+
+ if (notification is ScrollUpdateNotification) {
+ _handleToggleScrollToBottom();
+ }
+
+ // Allow other listeners to get the notification
+ return false;
+ },
+ child: Stack(
+ children: [
+ CustomScrollView(
+ reverse: true,
+ controller: widget.scrollController,
+ slivers: <Widget>[
+ SliverPadding(
+ padding: EdgeInsets.only(
+ top: widget.bottomPadding ?? 0,
+ ),
+ ),
+ SliverAnimatedList(
+ key: _listKey,
+ initialItemCount: _chatController.messages.length,
+ itemBuilder: (
+ BuildContext context,
+ int index,
+ Animation<double> animation,
+ ) {
+ final message = _chatController.messages[
+ max(_chatController.messages.length - 1 - index, 0)];
+ return widget.itemBuilder(
+ context,
+ animation,
+ message,
+ );
+ },
+ ),
+ ],
+ ),
+ builders.scrollToBottomBuilder?.call(
+ context,
+ _scrollToBottomAnimation,
+ _handleScrollToBottom,
+ ) ??
+ ScrollToBottom(
+ animation: _scrollToBottomAnimation,
+ onPressed: _handleScrollToBottom,
+ ),
+ ],
+ ),
+ );
+ }
+
+ void _subsequentScrollToEnd(Message data) async {
+ final user = Provider.of<User>(context, listen: false);
+
+ // We only want to scroll to the bottom if user has not scrolled up
+ // or if the message is sent by the current user.
+ if (data.id == _lastInsertedMessageId &&
+ widget.scrollController.offset >
+ widget.scrollController.position.minScrollExtent &&
+ (user.id == data.author.id && _userHasScrolled)) {
+ if (widget.scrollToEndAnimationDuration == Duration.zero) {
+ widget.scrollController
+ .jumpTo(widget.scrollController.position.minScrollExtent);
+ } else {
+ await widget.scrollController.animateTo(
+ widget.scrollController.position.minScrollExtent,
+ duration: widget.scrollToEndAnimationDuration,
+ curve: Curves.linearToEaseOut,
+ );
+ }
+
+ if (!widget.scrollController.hasClients || !mounted) return;
+
+ // Because of the issue I have opened here https://github.com/flutter/flutter/issues/129768
+ // we need an additional jump to the end. Sometimes Flutter
+ // will not scroll to the very end. Sometimes it will not scroll to the
+ // very end even with this, so this is something that needs to be
+ // addressed by the Flutter team.
+ //
+ // Additionally here we have a check for the message id, because
+ // if new message arrives in the meantime it will trigger another
+ // scroll to the end animation, making this logic redundant.
+ if (data.id == _lastInsertedMessageId &&
+ widget.scrollController.offset >
+ widget.scrollController.position.minScrollExtent &&
+ (user.id == data.author.id && _userHasScrolled)) {
+ widget.scrollController
+ .jumpTo(widget.scrollController.position.minScrollExtent);
+ }
+ }
+ }
+
+ void _scrollToEnd(Message data) {
+ WidgetsBinding.instance.addPostFrameCallback(
+ (_) {
+ if (!widget.scrollController.hasClients || !mounted) return;
+
+ _subsequentScrollToEnd(data);
+ },
+ );
+ }
+
+ void _handleScrollToBottom() {
+ _isScrollingToBottom = true;
+ _scrollToBottomController.reverse();
+
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
+ if (!widget.scrollController.hasClients || !mounted) return;
+
+ if (widget.scrollToEndAnimationDuration == Duration.zero) {
+ widget.scrollController
+ .jumpTo(widget.scrollController.position.minScrollExtent);
+ } else {
+ await widget.scrollController.animateTo(
+ widget.scrollController.position.minScrollExtent,
+ duration: widget.scrollToEndAnimationDuration,
+ curve: Curves.linearToEaseOut,
+ );
+ }
+
+ if (!widget.scrollController.hasClients || !mounted) return;
+
+ if (widget.scrollController.offset <
+ widget.scrollController.position.minScrollExtent) {
+ widget.scrollController.jumpTo(
+ widget.scrollController.position.minScrollExtent,
+ );
+ }
+
+ _isScrollingToBottom = false;
+ });
+ }
+
+ void _handleToggleScrollToBottom() {
+ if (_isScrollingToBottom) {
+ return;
+ }
+
+ _scrollToBottomShowTimer?.cancel();
+ if (widget.scrollController.offset >
+ widget.scrollController.position.minScrollExtent) {
+ _scrollToBottomShowTimer =
+ Timer(widget.scrollToBottomAppearanceDelay, () {
+ if (mounted) {
+ _scrollToBottomController.forward();
+ }
+ });
+ } else {
+ if (_scrollToBottomController.status != AnimationStatus.completed) {
+ _scrollToBottomController.stop();
+ }
+ _scrollToBottomController.reverse();
+ }
+ }
+
+ void _onInserted(final int position, final Message data) {
+ // There is a scroll notification listener the controls the
+ // `_userHasScrolled` variable.
+ //
+ // If for some reason `_userHasScrolled` is true and the user is not at the
+ // bottom of the list, set `_userHasScrolled` to false so that the scroll
+ // animation is triggered.
+ if (position == 0 &&
+ _userHasScrolled &&
+ widget.scrollController.offset >
+ widget.scrollController.position.minScrollExtent) {
+ _userHasScrolled = false;
+ }
+
+ _listKey.currentState!.insertItem(
+ 0,
+ duration: widget.insertAnimationDuration,
+ );
+
+ // Used later to trigger scroll to end only for the last inserted message.
+ _lastInsertedMessageId = data.id;
+
+ if (position == _oldList.length) {
+ _scrollToEnd(data);
+ }
+ }
+
+ void _onRemoved(final int position, final Message data) {
+ final visualPosition = max(_oldList.length - position - 1, 0);
+ _listKey.currentState!.removeItem(
+ visualPosition,
+ (context, animation) => widget.itemBuilder(
+ context,
+ animation,
+ data,
+ isRemoved: true,
+ ),
+ duration: widget.removeAnimationDuration,
+ );
+ }
+
+ void _onChanged(int position, Message oldData, Message newData) {
+ _onRemoved(position, oldData);
+ _listKey.currentState!.insertItem(
+ max(_oldList.length - position - 1, 0),
+ duration: widget.insertAnimationDuration,
+ );
+ }
+
+ void _onDiffUpdate(diffutil.DataDiffUpdate<Message> update) {
+ update.when<void>(
+ insert: (pos, data) => _onInserted(max(_oldList.length - pos, 0), data),
+ remove: (pos, data) => _onRemoved(pos, data),
+ change: (pos, oldData, newData) => _onChanged(pos, oldData, newData),
+ move: (_, __, ___) => throw UnimplementedError('unused'),
+ );
+ }
+
+ void _handleLoadPreviousMessages() {
+ if (widget.scrollController.offset >=
+ widget.scrollController.position.maxScrollExtent) {
+ widget.onLoadPreviousMessages?.call();
+ }
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_animation_list_widget.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_animation_list_widget.dart
new file mode 100644
index 0000000000..3ffae41e1f
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_animation_list_widget.dart
@@ -0,0 +1,89 @@
+import 'package:appflowy/ai/ai.dart';
+import 'package:appflowy/plugins/ai_chat/application/ai_chat_prelude.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/animated_chat_list.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/animated_chat_list_reversed.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_welcome_page.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/layout_define.dart';
+import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+import 'package:flutter_chat_core/flutter_chat_core.dart';
+
+class ChatAnimationListWidget extends StatefulWidget {
+ const ChatAnimationListWidget({
+ super.key,
+ required this.userProfile,
+ required this.scrollController,
+ required this.itemBuilder,
+ this.enableReversedList = false,
+ });
+
+ final UserProfilePB userProfile;
+ final ScrollController scrollController;
+ final ChatItem itemBuilder;
+ final bool enableReversedList;
+
+ @override
+ State<ChatAnimationListWidget> createState() =>
+ _ChatAnimationListWidgetState();
+}
+
+class _ChatAnimationListWidgetState extends State<ChatAnimationListWidget> {
+ @override
+ Widget build(BuildContext context) {
+ final bloc = context.read<ChatBloc>();
+
+ // this logic is quite weird, why don't we just get the message from the state?
+ if (bloc.chatController.messages.isEmpty) {
+ return ChatWelcomePage(
+ userProfile: widget.userProfile,
+ onSelectedQuestion: (question) {
+ final aiPromptInputBloc = context.read<AIPromptInputBloc>();
+ final showPredefinedFormats =
+ aiPromptInputBloc.state.showPredefinedFormats;
+ final predefinedFormat = aiPromptInputBloc.state.predefinedFormat;
+ bloc.add(
+ ChatEvent.sendMessage(
+ message: question,
+ format: showPredefinedFormats ? predefinedFormat : null,
+ ),
+ );
+ },
+ );
+ }
+
+ // don't call this in the build method
+ context
+ .read<ChatSelectMessageBloc>()
+ .add(ChatSelectMessageEvent.enableStartSelectingMessages());
+
+ // final bool reversed = false;
+
+ return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
+ selector: (state) => state.isSelectingMessages,
+ builder: (context, isSelectingMessages) {
+ return widget.enableReversedList
+ ? ChatAnimatedListReversed(
+ scrollController: widget.scrollController,
+ itemBuilder: widget.itemBuilder,
+ bottomPadding: isSelectingMessages
+ ? 48.0 + DesktopAIChatSizes.messageActionBarIconSize
+ : 8.0,
+ onLoadPreviousMessages: () {
+ bloc.add(const ChatEvent.loadPreviousMessages());
+ },
+ )
+ : ChatAnimatedList(
+ scrollController: widget.scrollController,
+ itemBuilder: widget.itemBuilder,
+ bottomPadding: isSelectingMessages
+ ? 48.0 + DesktopAIChatSizes.messageActionBarIconSize
+ : 8.0,
+ onLoadPreviousMessages: () {
+ bloc.add(const ChatEvent.loadPreviousMessages());
+ },
+ );
+ },
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_content_page.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_content_page.dart
new file mode 100644
index 0000000000..f98535a9ff
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_content_page.dart
@@ -0,0 +1,33 @@
+import 'package:appflowy/plugins/ai_chat/application/ai_chat_prelude.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_page/load_chat_message_status_ready.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
+import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+
+class ChatContentPage extends StatelessWidget {
+ const ChatContentPage({
+ super.key,
+ required this.view,
+ required this.userProfile,
+ });
+
+ final UserProfilePB userProfile;
+ final ViewPB view;
+
+ @override
+ Widget build(BuildContext context) {
+ return BlocBuilder<ChatBloc, ChatState>(
+ builder: (context, state) {
+ return switch (state.loadingState) {
+ LoadChatMessageStatus.ready => LoadChatMessageStatusReady(
+ view: view,
+ userProfile: userProfile,
+ chatController: context.read<ChatBloc>().chatController,
+ ),
+ _ => const Center(child: CircularProgressIndicator.adaptive()),
+ };
+ },
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_footer.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_footer.dart
new file mode 100644
index 0000000000..7035006fc0
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_footer.dart
@@ -0,0 +1,137 @@
+import 'package:appflowy/ai/ai.dart';
+import 'package:appflowy/plugins/ai_chat/application/ai_chat_prelude.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_input/mobile_chat_input.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/layout_define.dart';
+import 'package:appflowy/workspace/presentation/home/home_stack.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+import 'package:universal_platform/universal_platform.dart';
+
+class ChatFooter extends StatefulWidget {
+ const ChatFooter({
+ super.key,
+ required this.view,
+ });
+
+ final ViewPB view;
+
+ @override
+ State<ChatFooter> createState() => _ChatFooterState();
+}
+
+class _ChatFooterState extends State<ChatFooter> {
+ final textController = AiPromptInputTextEditingController();
+
+ @override
+ void dispose() {
+ textController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
+ selector: (state) => state.isSelectingMessages,
+ builder: (context, isSelectingMessages) {
+ return AnimatedSwitcher(
+ duration: const Duration(milliseconds: 150),
+ transitionBuilder: (child, animation) {
+ return NonClippingSizeTransition(
+ sizeFactor: animation,
+ axisAlignment: -1,
+ child: child,
+ );
+ },
+ child: isSelectingMessages
+ ? const SizedBox.shrink()
+ : Padding(
+ padding: AIChatUILayout.safeAreaInsets(context),
+ child: BlocSelector<ChatBloc, ChatState, bool>(
+ selector: (state) {
+ return state.promptResponseState ==
+ PromptResponseState.ready;
+ },
+ builder: (context, canSendMessage) {
+ final chatBloc = context.read<ChatBloc>();
+
+ return UniversalPlatform.isDesktop
+ ? _buildDesktopInput(
+ context,
+ chatBloc,
+ canSendMessage,
+ )
+ : _buildMobileInput(
+ context,
+ chatBloc,
+ canSendMessage,
+ );
+ },
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildDesktopInput(
+ BuildContext context,
+ ChatBloc chatBloc,
+ bool canSendMessage,
+ ) {
+ return DesktopPromptInput(
+ isStreaming: !canSendMessage,
+ textController: textController,
+ onStopStreaming: () {
+ chatBloc.add(const ChatEvent.stopStream());
+ },
+ onSubmitted: (text, format, metadata) {
+ chatBloc.add(
+ ChatEvent.sendMessage(
+ message: text,
+ format: format,
+ metadata: metadata,
+ ),
+ );
+ },
+ selectedSourcesNotifier: chatBloc.selectedSourcesNotifier,
+ onUpdateSelectedSources: (ids) {
+ chatBloc.add(
+ ChatEvent.updateSelectedSources(
+ selectedSourcesIds: ids,
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildMobileInput(
+ BuildContext context,
+ ChatBloc chatBloc,
+ bool canSendMessage,
+ ) {
+ return MobileChatInput(
+ isStreaming: !canSendMessage,
+ onStopStreaming: () {
+ chatBloc.add(const ChatEvent.stopStream());
+ },
+ onSubmitted: (text, format, metadata) {
+ chatBloc.add(
+ ChatEvent.sendMessage(
+ message: text,
+ format: format,
+ metadata: metadata,
+ ),
+ );
+ },
+ selectedSourcesNotifier: chatBloc.selectedSourcesNotifier,
+ onUpdateSelectedSources: (ids) {
+ chatBloc.add(
+ ChatEvent.updateSelectedSources(
+ selectedSourcesIds: ids,
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_message_widget.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/chat_message_widget.dart
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/load_chat_message_status_ready.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/load_chat_message_status_ready.dart
new file mode 100644
index 0000000000..85cac94d6b
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/load_chat_message_status_ready.dart
@@ -0,0 +1,117 @@
+import 'package:appflowy/plugins/ai_chat/presentation/chat_message_selector_banner.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_page/chat_animation_list_widget.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_page/chat_footer.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_page/text_message_widget.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/scroll_to_bottom.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
+import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_chat_core/flutter_chat_core.dart';
+import 'package:flutter_chat_ui/flutter_chat_ui.dart';
+import 'package:universal_platform/universal_platform.dart';
+
+class LoadChatMessageStatusReady extends StatelessWidget {
+ const LoadChatMessageStatusReady({
+ super.key,
+ required this.view,
+ required this.userProfile,
+ required this.chatController,
+ });
+
+ final ViewPB view;
+ final UserProfilePB userProfile;
+ final ChatController chatController;
+
+ @override
+ Widget build(BuildContext context) {
+ return Column(
+ children: [
+ // Chat header, banner
+ _buildHeader(context),
+ // Chat body, a list of messages
+ _buildBody(context),
+ // Chat footer, a text input field with toolbar, send button, etc.
+ _buildFooter(context),
+ ],
+ );
+ }
+
+ Widget _buildHeader(BuildContext context) {
+ return ChatMessageSelectorBanner(
+ view: view,
+ allMessages: chatController.messages,
+ );
+ }
+
+ Widget _buildBody(BuildContext context) {
+ return Expanded(
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: _wrapConstraints(
+ SelectionArea(
+ child: ScrollConfiguration(
+ behavior: ScrollConfiguration.of(context).copyWith(
+ scrollbars: false,
+ ),
+ child: Chat(
+ chatController: chatController,
+ user: User(id: userProfile.id.toString()),
+ darkTheme: ChatTheme.fromThemeData(Theme.of(context)),
+ theme: ChatTheme.fromThemeData(Theme.of(context)),
+ builders: Builders(
+ // we have a custom input builder, so we don't need the default one
+ inputBuilder: (_) => const SizedBox.shrink(),
+ textMessageBuilder: (context, message) => TextMessageWidget(
+ message: message,
+ userProfile: userProfile,
+ view: view,
+ ),
+ chatMessageBuilder: (context, message, animation, child) =>
+ ChatMessage(
+ message: message,
+ animation: animation,
+ padding: const EdgeInsets.symmetric(vertical: 18.0),
+ receivedMessageScaleAnimationAlignment: Alignment.center,
+ child: child,
+ ),
+ scrollToBottomBuilder: (context, animation, onPressed) =>
+ CustomScrollToBottom(
+ animation: animation,
+ onPressed: onPressed,
+ ),
+ chatAnimatedListBuilder: (
+ context,
+ scrollController,
+ itemBuilder,
+ ) =>
+ ChatAnimationListWidget(
+ userProfile: userProfile,
+ scrollController: scrollController,
+ itemBuilder: itemBuilder,
+ enableReversedList: true,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildFooter(BuildContext context) {
+ return _wrapConstraints(
+ ChatFooter(view: view),
+ );
+ }
+
+ Widget _wrapConstraints(Widget child) {
+ return Container(
+ constraints: const BoxConstraints(maxWidth: 784),
+ margin: UniversalPlatform.isDesktop
+ ? const EdgeInsets.symmetric(horizontal: 60.0)
+ : null,
+ child: child,
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/text_message_widget.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/text_message_widget.dart
new file mode 100644
index 0000000000..26995b7861
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_page/text_message_widget.dart
@@ -0,0 +1,154 @@
+import 'dart:io';
+
+import 'package:appflowy/ai/ai.dart';
+import 'package:appflowy/plugins/ai_chat/application/ai_chat_prelude.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/chat_related_question.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/message/ai_text_message.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/message/error_text_message.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/message/message_util.dart';
+import 'package:appflowy/plugins/ai_chat/presentation/message/user_text_message.dart';
+import 'package:appflowy/workspace/application/view/view_service.dart';
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
+import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
+import 'package:appflowy_result/appflowy_result.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+import 'package:flutter_chat_core/flutter_chat_core.dart';
+import 'package:string_validator/string_validator.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+class TextMessageWidget extends StatelessWidget {
+ const TextMessageWidget({
+ super.key,
+ required this.message,
+ required this.userProfile,
+ required this.view,
+ this.enableAnimation = true,
+ });
+
+ final TextMessage message;
+ final UserProfilePB userProfile;
+ final ViewPB view;
+ final bool enableAnimation;
+
+ @override
+ Widget build(BuildContext context) {
+ final messageType = onetimeMessageTypeFromMeta(
+ message.metadata,
+ );
+
+ if (messageType == OnetimeShotType.error) {
+ return ChatErrorMessageWidget(
+ errorMessage: message.metadata?[errorMessageTextKey] ?? "",
+ );
+ }
+
+ if (messageType == OnetimeShotType.relatedQuestion) {
+ return RelatedQuestionList(
+ relatedQuestions: message.metadata!['questions'],
+ onQuestionSelected: (question) {
+ final bloc = context.read<AIPromptInputBloc>();
+ final showPredefinedFormats = bloc.state.showPredefinedFormats;
+ final predefinedFormat = bloc.state.predefinedFormat;
+
+ context.read<ChatBloc>().add(
+ ChatEvent.sendMessage(
+ message: question,
+ format: showPredefinedFormats ? predefinedFormat : null,
+ ),
+ );
+ },
+ );
+ }
+
+ if (message.author.id == userProfile.id.toString() ||
+ isOtherUserMessage(message)) {
+ return ChatUserMessageWidget(
+ user: message.author,
+ message: message,
+ );
+ }
+
+ final stream = message.metadata?["$AnswerStream"];
+ final questionId = message.metadata?[messageQuestionIdKey];
+ final refSourceJsonString =
+ message.metadata?[messageRefSourceJsonStringKey] as String?;
+
+ return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
+ selector: (state) => state.isSelectingMessages,
+ builder: (context, isSelectingMessages) {
+ return BlocBuilder<ChatBloc, ChatState>(
+ builder: (context, state) {
+ final chatController = context.read<ChatBloc>().chatController;
+ final messages = chatController.messages
+ .where((e) => onetimeMessageTypeFromMeta(e.metadata) == null);
+ final isLastMessage =
+ messages.isEmpty ? false : messages.last.id == message.id;
+ return ChatAIMessageWidget(
+ user: message.author,
+ messageUserId: message.id,
+ message: message,
+ stream: stream is AnswerStream ? stream : null,
+ questionId: questionId,
+ chatId: view.id,
+ refSourceJsonString: refSourceJsonString,
+ isStreaming:
+ state.promptResponseState != PromptResponseState.ready,
+ isLastMessage: isLastMessage,
+ isSelectingMessages: isSelectingMessages,
+ enableAnimation: enableAnimation,
+ onSelectedMetadata: (metadata) =>
+ _onSelectMetadata(context, metadata),
+ onRegenerate: () => context
+ .read<ChatBloc>()
+ .add(ChatEvent.regenerateAnswer(message.id, null, null)),
+ onChangeFormat: (format) => context
+ .read<ChatBloc>()
+ .add(ChatEvent.regenerateAnswer(message.id, format, null)),
+ onChangeModel: (model) => context
+ .read<ChatBloc>()
+ .add(ChatEvent.regenerateAnswer(message.id, null, model)),
+ onStopStream: () => context.read<ChatBloc>().add(
+ const ChatEvent.stopStream(),
+ ),
+ );
+ },
+ );
+ },
+ );
+ }
+
+ void _onSelectMetadata(
+ BuildContext context,
+ ChatMessageRefSource metadata,
+ ) async {
+ // When the source of metatdata is appflowy, which means it is a appflowy page
+ if (metadata.source == "appflowy") {
+ final sidebarView =
+ await ViewBackendService.getView(metadata.id).toNullable();
+ if (context.mounted) {
+ openPageFromMessage(context, sidebarView);
+ }
+ return;
+ }
+
+ if (metadata.source == "web") {
+ if (isURL(metadata.name)) {
+ late Uri uri;
+ try {
+ uri = Uri.parse(metadata.name);
+ // `Uri` identifies `localhost` as a scheme
+ if (!uri.hasScheme || uri.scheme == 'localhost') {
+ uri = Uri.parse("http://${metadata.name}");
+ await InternetAddress.lookup(uri.host);
+ }
+ await launchUrl(uri);
+ } catch (err) {
+ Log.error("failed to open url $err");
+ }
+ }
+ return;
+ }
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart
index 1e7d428263..41d5846ed0 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_markdown_text.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/application/page_style/document_page_style_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_configuration.dart';
@@ -17,16 +19,21 @@ class AIMarkdownText extends StatelessWidget {
const AIMarkdownText({
super.key,
required this.markdown,
+ this.withAnimation = false,
});
final String markdown;
+ final bool withAnimation;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => DocumentPageStyleBloc(view: ViewPB())
..add(const DocumentPageStyleEvent.initial()),
- child: _AppFlowyEditorMarkdown(markdown: markdown),
+ child: _AppFlowyEditorMarkdown(
+ markdown: markdown,
+ withAnimation: withAnimation,
+ ),
);
}
}
@@ -34,19 +41,28 @@ class AIMarkdownText extends StatelessWidget {
class _AppFlowyEditorMarkdown extends StatefulWidget {
const _AppFlowyEditorMarkdown({
required this.markdown,
+ this.withAnimation = false,
});
// the text should be the markdown format
final String markdown;
+ /// Whether to animate the text.
+ final bool withAnimation;
+
@override
State<_AppFlowyEditorMarkdown> createState() =>
_AppFlowyEditorMarkdownState();
}
-class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
+class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown>
+ with TickerProviderStateMixin {
late EditorState editorState;
late EditorScrollController scrollController;
+ late Timer markdownOutputTimer;
+ int offset = 0;
+
+ final Map<String, (AnimationController, Animation<double>)> _animations = {};
@override
void initState() {
@@ -57,13 +73,46 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
editorState: editorState,
shrinkWrap: true,
);
+
+ if (widget.withAnimation) {
+ markdownOutputTimer =
+ Timer.periodic(const Duration(milliseconds: 60), (timer) {
+ if (offset >= widget.markdown.length || !widget.withAnimation) {
+ return;
+ }
+
+ final markdown = widget.markdown.substring(0, offset);
+ offset += 30;
+
+ final editorState = _parseMarkdown(
+ markdown,
+ previousDocument: this.editorState.document,
+ );
+ final lastCurrentNode = editorState.document.last;
+ final lastPreviousNode = this.editorState.document.last;
+ if (lastCurrentNode?.id != lastPreviousNode?.id ||
+ lastCurrentNode?.type != lastPreviousNode?.type ||
+ lastCurrentNode?.delta?.toPlainText() !=
+ lastPreviousNode?.delta?.toPlainText()) {
+ setState(() {
+ this.editorState.dispose();
+ this.editorState = editorState;
+ scrollController.dispose();
+ scrollController = EditorScrollController(
+ editorState: editorState,
+ shrinkWrap: true,
+ );
+ });
+ }
+ });
+ }
}
@override
void didUpdateWidget(covariant _AppFlowyEditorMarkdown oldWidget) {
super.didUpdateWidget(oldWidget);
- if (oldWidget.markdown != widget.markdown) {
+ if (oldWidget.markdown != widget.markdown && !widget.withAnimation) {
final editorState = _parseMarkdown(
widget.markdown.trim(),
previousDocument: this.editorState.document,
@@ -83,6 +132,13 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
scrollController.dispose();
editorState.dispose();
+ if (widget.withAnimation) {
+ markdownOutputTimer.cancel();
+ for (final controller in _animations.values.map((e) => e.$1)) {
+ controller.dispose();
+ }
+ }
+
super.dispose();
}
@@ -120,6 +176,33 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
commandShortcutEvents: [customCopyCommand],
disableAutoScroll: true,
editorState: editorState,
+ blockWrapper: (
+ context, {
+ required Node node,
+ required Widget child,
+ }) {
+ if (!widget.withAnimation) {
+ return child;
+ }
+
+ if (!_animations.containsKey(node.id)) {
+ final controller = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 1600),
+ );
+ final fade = Tween<double>(
+ begin: 0,
+ end: 1,
+ ).animate(controller);
+ _animations[node.id] = (controller, fade);
+ controller.forward();
+ }
+ final (controller, fade) = _animations[node.id]!;
+ return _AnimatedWrapper(
+ fade: fade,
+ child: child,
+ );
+ },
contextMenuItems: [
[
ContextMenuItem(
@@ -161,3 +244,39 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
return editorState;
}
}
+
+class _AnimatedWrapper extends StatelessWidget {
+ const _AnimatedWrapper({
+ required this.fade,
+ required this.child,
+ });
+
+ final Animation<double> fade;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ return AnimatedBuilder(
+ animation: fade,
+ builder: (context, childWidget) {
+ return ShaderMask(
+ shaderCallback: (Rect bounds) {
+ return LinearGradient(
+ stops: [fade.value, fade.value],
+ colors: const [
+ Colors.white,
+ Colors.transparent,
+ ],
+ ).createShader(bounds);
+ },
+ blendMode: BlendMode.dstIn,
+ child: Opacity(
+ opacity: fade.value,
+ child: childWidget,
+ ),
+ );
+ },
+ child: child,
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart
index 03f0d61ebc..e9aacb55b1 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart
@@ -23,9 +23,9 @@ import 'package:go_router/go_router.dart';
import 'package:universal_platform/universal_platform.dart';
import '../layout_define.dart';
+import 'ai_change_format_bottom_sheet.dart';
import 'ai_change_model_bottom_sheet.dart';
import 'ai_message_action_bar.dart';
-import 'ai_change_format_bottom_sheet.dart';
import 'message_util.dart';
/// Wraps an AI response message with the avatar and actions. On desktop,
@@ -132,7 +132,7 @@ class ChatAIBottomInlineActions extends StatelessWidget {
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
),
- const VSpace(32.0),
+ const VSpace(16.0),
],
);
}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart
index 380767105f..8779e875d4 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart
@@ -41,6 +41,7 @@ class ChatAIMessageWidget extends StatelessWidget {
this.isLastMessage = false,
this.isStreaming = false,
this.isSelectingMessages = false,
+ this.enableAnimation = true,
});
final User user;
@@ -59,6 +60,7 @@ class ChatAIMessageWidget extends StatelessWidget {
final bool isStreaming;
final bool isLastMessage;
final bool isSelectingMessages;
+ final bool enableAnimation;
@override
Widget build(BuildContext context) {
@@ -96,41 +98,27 @@ class ChatAIMessageWidget extends StatelessWidget {
),
ready: () {
return state.text.isEmpty
- ? ChatAIMessageBubble(
+ ? _LoadingMessage(
message: message,
- showActions: false,
- child: Padding(
- padding: const EdgeInsets.only(top: 8.0),
- child: AILoadingIndicator(text: loadingText),
- ),
+ loadingText: loadingText,
)
- : ChatAIMessageBubble(
+ : _NonEmptyMessage(
+ user: user,
+ messageUserId: messageUserId,
message: message,
- isLastMessage: isLastMessage,
- showActions: stream == null &&
- state.text.isNotEmpty &&
- !isStreaming,
- isSelectingMessages: isSelectingMessages,
+ stream: stream,
+ questionId: questionId,
+ chatId: chatId,
+ refSourceJsonString: refSourceJsonString,
+ onStopStream: onStopStream,
+ onSelectedMetadata: onSelectedMetadata,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- AIMarkdownText(
- markdown: state.text,
- ),
- if (state.sources.isNotEmpty)
- SelectionContainer.disabled(
- child: AIMessageMetadata(
- sources: state.sources,
- onSelectedMetadata: onSelectedMetadata,
- ),
- ),
- if (state.sources.isNotEmpty && !isLastMessage)
- const VSpace(8.0),
- ],
- ),
+ isLastMessage: isLastMessage,
+ isStreaming: isStreaming,
+ isSelectingMessages: isSelectingMessages,
+ enableAnimation: enableAnimation,
);
},
onError: (error) {
@@ -171,3 +159,96 @@ class ChatAIMessageWidget extends StatelessWidget {
);
}
}
+
+class _LoadingMessage extends StatelessWidget {
+ const _LoadingMessage({
+ required this.message,
+ required this.loadingText,
+ });
+
+ final Message message;
+ final String loadingText;
+
+ @override
+ Widget build(BuildContext context) {
+ return ChatAIMessageBubble(
+ message: message,
+ showActions: false,
+ child: Padding(
+ padding: const EdgeInsets.only(top: 8.0),
+ child: AILoadingIndicator(text: loadingText),
+ ),
+ );
+ }
+}
+
+class _NonEmptyMessage extends StatelessWidget {
+ const _NonEmptyMessage({
+ required this.user,
+ required this.messageUserId,
+ required this.message,
+ required this.stream,
+ required this.questionId,
+ required this.chatId,
+ required this.refSourceJsonString,
+ required this.onStopStream,
+ this.onSelectedMetadata,
+ this.onRegenerate,
+ this.onChangeFormat,
+ this.onChangeModel,
+ this.isLastMessage = false,
+ this.isStreaming = false,
+ this.isSelectingMessages = false,
+ this.enableAnimation = true,
+ });
+
+ final User user;
+ final String messageUserId;
+
+ final Message message;
+ final AnswerStream? stream;
+ final Int64? questionId;
+ final String chatId;
+ final String? refSourceJsonString;
+ final ValueChanged<ChatMessageRefSource>? onSelectedMetadata;
+ final VoidCallback? onRegenerate;
+ final VoidCallback onStopStream;
+ final ValueChanged<PredefinedFormat>? onChangeFormat;
+ final ValueChanged<AIModelPB>? onChangeModel;
+ final bool isStreaming;
+ final bool isLastMessage;
+ final bool isSelectingMessages;
+ final bool enableAnimation;
+
+ @override
+ Widget build(BuildContext context) {
+ final state = context.read<ChatAIMessageBloc>().state;
+ final showActions = stream == null && state.text.isNotEmpty && !isStreaming;
+ return ChatAIMessageBubble(
+ message: message,
+ isLastMessage: isLastMessage,
+ showActions: showActions,
+ isSelectingMessages: isSelectingMessages,
+ onRegenerate: onRegenerate,
+ onChangeFormat: onChangeFormat,
+ onChangeModel: onChangeModel,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ AIMarkdownText(
+ markdown: state.text,
+ withAnimation: enableAnimation && stream != null,
+ ),
+ if (state.sources.isNotEmpty)
+ SelectionContainer.disabled(
+ child: AIMessageMetadata(
+ sources: state.sources,
+ onSelectedMetadata: onSelectedMetadata,
+ ),
+ ),
+ if (state.sources.isNotEmpty && !isLastMessage) const VSpace(8.0),
+ ],
+ ),
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/page_block/custom_page_block_component.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/page_block/custom_page_block_component.dart
index 731ba4c7cd..1bcd4228a9 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/page_block/custom_page_block_component.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/page_block/custom_page_block_component.dart
@@ -15,6 +15,7 @@ class CustomPageBlockComponentBuilder extends BlockComponentBuilder {
node: blockComponentContext.node,
header: blockComponentContext.header,
footer: blockComponentContext.footer,
+ wrapper: blockComponentContext.wrapper,
);
}
}
@@ -29,10 +30,12 @@ class CustomPageBlockComponent extends BlockComponentStatelessWidget {
super.configuration = const BlockComponentConfiguration(),
this.header,
this.footer,
+ this.wrapper,
});
final Widget? header;
final Widget? footer;
+ final BlockComponentWrapper? wrapper;
@override
Widget build(BuildContext context) {
@@ -52,14 +55,20 @@ class CustomPageBlockComponent extends BlockComponentStatelessWidget {
children: [
if (header != null) header!,
...items.map(
- (e) => Container(
- constraints: BoxConstraints(
- maxWidth:
- editorState.editorStyle.maxWidth ?? double.infinity,
- ),
- padding: editorState.editorStyle.padding,
- child: editorState.renderer.build(context, e),
- ),
+ (e) {
+ Widget child = editorState.renderer.build(context, e);
+ if (wrapper != null) {
+ child = wrapper!(context, node: e, child: child);
+ }
+ return Container(
+ constraints: BoxConstraints(
+ maxWidth:
+ editorState.editorStyle.maxWidth ?? double.infinity,
+ ),
+ padding: editorState.editorStyle.padding,
+ child: child,
+ );
+ },
),
if (footer != null) footer!,
],
@@ -92,6 +101,11 @@ class CustomPageBlockComponent extends BlockComponentStatelessWidget {
final childNode = items[index - (header != null ? 1 : 0)];
final isOverflowType = overflowTypes.contains(childNode.type);
+ Widget child = editorState.renderer.build(context, childNode);
+ if (wrapper != null) {
+ child = wrapper!(context, node: childNode, child: child);
+ }
+
final item = Container(
constraints: BoxConstraints(
maxWidth: editorState.editorStyle.maxWidth ?? double.infinity,
@@ -99,10 +113,7 @@ class CustomPageBlockComponent extends BlockComponentStatelessWidget {
padding: isOverflowType
? EdgeInsets.zero
: editorState.editorStyle.padding,
- child: editorState.renderer.build(
- context,
- childNode,
- ),
+ child: child,
);
return isOverflowType ? item : Center(child: item);
diff --git a/frontend/appflowy_flutter/pubspec.lock b/frontend/appflowy_flutter/pubspec.lock
index d396a37be6..e7060698cb 100644
--- a/frontend/appflowy_flutter/pubspec.lock
+++ b/frontend/appflowy_flutter/pubspec.lock
@@ -98,8 +98,8 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: e56746a
- resolved-ref: e56746ac65681fb002ff169be3de15ae4f5aad60
+ ref: "4e8cf75"
+ resolved-ref: "4e8cf75df69589e142492749160acb1b8d9dca0e"
url: "https://github.com/AppFlowy-IO/appflowy-editor.git"
source: git
version: "5.2.0"
diff --git a/frontend/appflowy_flutter/pubspec.yaml b/frontend/appflowy_flutter/pubspec.yaml
index 9c90559b49..ecb9854c11 100644
--- a/frontend/appflowy_flutter/pubspec.yaml
+++ b/frontend/appflowy_flutter/pubspec.yaml
@@ -185,7 +185,7 @@ dependency_overrides:
appflowy_editor:
git:
url: https://github.com/AppFlowy-IO/appflowy-editor.git
- ref: "e56746a"
+ ref: "4e8cf75"
appflowy_editor_plugins:
git: