Compare commits

...
Author SHA1 Message Date
Nathan 89647ae683 chore: logs for windows 2025-03-31 00:15:59 +08:00
Nathan.fooo c87d9ab74f Merge pull request #7652 from AppFlowy-IO/show_not_ready
chore: display message when using ai writer with local ai, but local ai  is disabled
2025-03-30 22:16:05 +08:00
Nathan e3a0806eee chore: clippy 2025-03-30 20:53:27 +08:00
Nathan b63c4dfe21 chore: show local ai disable 2025-03-30 20:12:20 +08:00
Nathan 2277d7d234 chore: show local ai disable 2025-03-30 15:15:59 +08:00
Nathan f76ce2be14 chore: show not ready state when using ai writer with local ai 2025-03-30 12:06:08 +08:00
Nathan.fooo 3c74208ab9 Merge pull request #7650 from AppFlowy-IO/display_plugin_version
chore: show plugin version
2025-03-30 12:05:25 +08:00
Nathan 5ae3f42313 chore: fix windows build 2025-03-30 11:28:29 +08:00
Nathan af5c4bfe76 chore: show plugin version 2025-03-30 10:48:26 +08:00
Nathan.fooo 9c25769d8e Merge pull request #7649 from AppFlowy-IO/revert-7643-chore/improve-local-ai-setting-page
Revert "chore: improve local ai settings page"
2025-03-30 09:54:26 +08:00
Nathan.fooo 12a4bf67f6 Revert "feat: improve local ai settings page UI (#7643)"
This reverts commit 3a879b0186.
2025-03-30 09:54:08 +08:00
Nathan 34a858e948 chore: show plugin version 2025-03-30 09:02:06 +08:00
Richard Shiue 3a879b0186 feat: improve local ai settings page UI (#7643)
* chore: improve local ai settings page

* chore: improve local ai settings page

* chore: simplify state and improve ui
2025-03-29 21:56:05 +08:00
Nathan.fooo dbe72b32b2 Merge pull request #7646 from AppFlowy-IO/show_lai_resource
chore: bump lai
2025-03-29 19:58:08 +08:00
Nathan 917aa60c98 chore: bump lai 2025-03-29 15:32:45 +08:00
Nathan.fooo 84e0f5e6ff Merge pull request #7595 from AppFlowy-IO/mcp_protocol
chore: implement MCP client
2025-03-29 09:10:05 +08:00
Nathan 7b89d76cea chore: clippy 2025-03-28 23:31:00 +08:00
Nathan fbf031b06d chore: bump local ai 2025-03-28 23:00:27 +08:00
Nathan 671e855b0e Merge branch 'main' into mcp_protocol 2025-03-28 16:27:19 +08:00
Nathan 8aa32ca3fa chore: disable mcp 2025-03-28 16:27:16 +08:00
Richard Shiue 07c767c4fa fix: ai writer ux issues (#7640)
* chore: fix local ai font weight

* chore: adjust auto response format copy

* fix: escape shortcut

* chore: more action button icon size
2025-03-28 11:23:29 +08:00
Nathan.fooo 4ce0782a05 Merge pull request #7638 from AppFlowy-IO/ai_model_desc
Ai model desc
2025-03-27 22:07:00 +08:00
Nathan 7456c65799 chore: clippy 2025-03-27 20:54:48 +08:00
Nathan 8cf31b8afc chore: bump client api 2025-03-27 20:51:29 +08:00
Nathan ff70595a15 chore: display ai model desc and fix flashing when select model 2025-03-27 20:03:07 +08:00
Nathan f6f19a0a07 chore: display ai model desc on setting page 2025-03-27 19:17:52 +08:00
Richard Shiue b83b964678 chore: add model description UI 2025-03-27 18:01:45 +08:00
Nathan f574b6b9c2 chore: update default name 2025-03-27 17:10:35 +08:00
Nathan 7ee29dcbc5 chore: return model desc 2025-03-27 17:09:01 +08:00
Nathan d348361889 chore: return desc of ai model 2025-03-27 16:31:18 +08:00
Richard Shiue 07a78b4ad7 chore: adjust default model name (#7634) 2025-03-27 14:26:45 +08:00
Morn a26ebbccc1 fix: toolbar launch review issues (#7631)
* fix: keep the turn into menu within six-dot same as toolbar

* fix: change some icon color within toolbar

* fix: improve toolbar

* chore: update editor dependency

* fix: update editor dependency
2025-03-27 14:19:51 +08:00
Nathan ccb020e885 chore: bump lai 2025-03-27 14:19:27 +08:00
Lucas 76cb23e233 feat: add bloc observer (#7633)
* chore: bump version 0.8.8

* feat: add bloc observer

* chore: update comment

* chore: update comment
2025-03-27 14:17:47 +08:00
Morn 4686e13390 feat: add animation for floating toolbar (#7623) 2025-03-27 13:28:35 +08:00
Nathan.fooo 584f762e11 Merge pull request #7617 from richardshiue/chore/improve-model-selection-ui
feat: regenerate message with different model
2025-03-27 12:54:26 +08:00
Richard Shiue 8528811992 chore: remove ai model class 2025-03-27 12:02:58 +08:00
Richard Shiue 9147f64b65 chore: adjust suggestion action button position (#7632) 2025-03-27 11:10:23 +08:00
Richard Shiue f7f2e71ee1 chore: adjust popover shadows (#7630) 2025-03-27 10:05:26 +08:00
Richard Shiue f9e1dcca6c chore: code nit 2025-03-27 00:15:48 +08:00
Richard Shiue e11388491f chore: emit ready state faster 2025-03-27 00:15:48 +08:00
Richard Shiue eb0cff36c9 chore: improve ai model selection ui 2025-03-27 00:15:48 +08:00
Nathan ac8141ab15 Merge branch 'main' into mcp_protocol 2025-03-26 16:18:46 +08:00
Richard Shiue b3b13e550d chore: adjust popover shadows (#7626) 2025-03-26 14:29:11 +08:00
Nathan.fooo ba1767e312 Merge pull request #7628 from AppFlowy-IO/local_ai_global_config
chore: implement local ai config
2025-03-26 14:29:02 +08:00
Nathan 10048dadec Merge branch 'main' into local_ai_global_config 2025-03-26 14:21:12 +08:00
Nathan 815bb11cde chore: implement local ai config 2025-03-26 14:19:57 +08:00
Lucas 7372f5583c chore: bump version 0.8.8 (#7627) 2025-03-26 13:56:24 +08:00
LucasandRichard Shiue 9115e208ac fix: numbered list generated by ai should keep the same index as the input (#7622)
Co-authored-by: Richard Shiue <71320345+richardshiue@users.noreply.github.com>
2025-03-26 13:31:32 +08:00
Morn 24bb1b58a0 feat: support use ":" keyword to create emojis (#7582)
* feat: add ability to use : keyword to create emojis(#2797)

* fix: emoji position error

* chore: add integration test

* chore: dismiss emoji picker while starting searching with space
2025-03-26 13:24:16 +08:00
Ametero cfca70ae14 chore: update translations with Fink 🐦 (#7584) 2025-03-26 13:23:25 +08:00
Morn 1db6da7024 fix: undo not working for toggle heading (#7598) 2025-03-26 13:22:47 +08:00
Richard Shiue c212c568e9 chore: bump editor ref (#7621) 2025-03-26 11:00:41 +08:00
Richard Shiue 1d437fb81e chore: adjust ai writer popover content area (#7618) 2025-03-25 23:44:00 +08:00
Richard Shiue 5a0478ad56 fix(mobile): settings page crashes (#7616) 2025-03-25 23:00:28 +08:00
Richard Shiue 039c191d1f fix: ai text insertion (#7615)
* fix: dont scroll to ai writer node if path not found

* chore: rename text robot clear method and add reset

* fix: insert position is off if using ai writer multiple times

* chore: reorganize code

* fix: undo not working after accept
2025-03-25 22:41:35 +08:00
Richard Shiue eb4b015de8 chore: bump editor plugin ref (#7610) 2025-03-25 20:37:15 +08:00
Khor Shu Heng 5269bfbf8e Merge pull request #7609 from ixicut/fix-ukrainian-translation-7603
fix: correct translation inconsistencies
2025-03-25 18:05:30 +08:00
ixicut ed44c20281 fix: correct translation inconsistencies 2025-03-25 11:19:11 +02:00
Nathan.fooo 878323a299 Merge pull request #7606 from AppFlowy-IO/fix_exceptions
chore: fix incorrect local ai state
2025-03-25 13:59:49 +08:00
Nathan 0dc2363962 chore: fix incorrect local ai state 2025-03-25 13:05:18 +08:00
Richard Shiue 72d660f1ac fix: number cell update flashes with old content (#7605) 2025-03-25 11:07:46 +08:00
Nathan.fooo 46532a861f Merge pull request #7602 from AppFlowy-IO/remove_default_model
chore: remove default model name
2025-03-24 22:37:23 +08:00
Nathan 4c39908748 chore: separate model 2025-03-24 22:21:44 +08:00
Nathan 35081fd311 chore: remove default model name 2025-03-24 21:59:42 +08:00
Richard Shiue 7463e4e3eb fix: pass response format in ai writer (#7599) 2025-03-24 16:50:16 +08:00
Nathan 66ce786726 chore: add client 2025-03-24 16:38:37 +08:00
Richard Shiue 682a50da53 chore: replace ai response every time (#7597) 2025-03-24 14:15:20 +08:00
Nathan d372abd5a1 Merge branch 'main' into mcp_protocol 2025-03-24 13:56:56 +08:00
Richard Shiue dfb5a6629f chore: pass ai writer context (#7596)
* chore: pass ai writer context

* chore: maintain selection after starting ai writer

* chore: improve ui of additional comments

* chore: revert podfile.lock changes

* chore: code readability

* chore: revert podfile.lock changes

* fix: accept shouldn't try to unformat
2025-03-24 13:27:31 +08:00
Nathan.fooo bb72f7e70a Merge pull request #7590 from AppFlowy-IO/support_switch_model
chore: support switch ai model in chat/ AI writer
2025-03-24 12:40:43 +08:00
Nathan 37085042f8 chore: clippy 2025-03-24 12:40:29 +08:00
Nathan 2cbcb320fe chore: add timeout 2025-03-24 12:11:12 +08:00
Nathan 949556e2fa chore: remove tauri feature 2025-03-24 12:03:42 +08:00
Nathan 08d1d3602e chore: implement MCP client 2025-03-24 10:44:20 +08:00
Morn 910c45e457 chore: change some mobile slash menu icons (#7579) 2025-03-24 09:55:58 +08:00
Morn 6f031d0c7e feat: revamp toolbar link (#7578)
* feat: revamp toolbar link

* fix: some review issues

* chore: add integration test for toolbar link
2025-03-24 09:55:23 +08:00
Morn 44c9d572c8 fix: using date picker with @ menu with some errors (#7580) 2025-03-24 09:54:45 +08:00
Nathan 05949d2f87 chore: support switch ai model in chat or ai writer 2025-03-23 21:53:05 +08:00
Nathan.fooo ad695e43b9 Merge pull request #7575 from AppFlowy-IO/completion_stream_v2
chore: completion stream v2
2025-03-21 11:47:28 +08:00
Nathan 87015f7133 chore: upgrade lai commit 2025-03-21 11:47:05 +08:00
Richard Shiue deb019aa4a chore: don't allow double register two ai nodes 2025-03-21 11:14:49 +08:00
Richard Shiue c79d014305 chore: revert podfile changes and update error 2025-03-21 10:49:41 +08:00
Richard Shiue 182101023b chore: remove actions in explanation when not explain 2025-03-21 10:37:10 +08:00
Richard Shiue f1b2f51a06 chore: fix test 2025-03-21 10:20:47 +08:00
Nathan a5c0ad5998 chore: fix test 2025-03-21 10:07:27 +08:00
Nathan 6fd250d4d1 chore: update client api 2025-03-21 10:04:51 +08:00
Nathan db2270c8d8 chore: update local ai commit 2025-03-20 15:13:25 +08:00
Richard Shiue 10f19069c6 chore: implement ui 2025-03-20 13:30:42 +08:00
Richard Shiue 13a7ea07a8 chore: merge remote-tracking branch 'upstream/main' into this one 2025-03-20 13:29:03 +08:00
Richard Shiue aacd795ae0 chore: ai writer more actions (#7576)
* feat: add more button to ai writer input box

* chore: adjust button padding

* chore: adjust icon color
2025-03-20 12:33:51 +08:00
Richard Shiue 566e7b2f40 feat: allow user scroll during generation (#7559)
* chore: add keep alive to ai writer block component

* chore: allow user scrolling during ai writer generation

* chore: pull ai writer cubit upwards

* test: fix unit tests

* chore: clear selection
2025-03-20 11:50:25 +08:00
Nathan f413b9e070 chore: callback 2025-03-20 11:44:02 +08:00
Nathan 6e4206a8e2 chore: completion stream v2 2025-03-20 11:41:49 +08:00
173 changed files with 7944 additions and 2586 deletions

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true
CARGO_MAKE_CRATE_FS_NAME = "dart_ffi"
CARGO_MAKE_CRATE_NAME = "dart-ffi"
LIB_NAME = "dart_ffi"
APPFLOWY_VERSION = "0.8.7"
APPFLOWY_VERSION = "0.8.8"
FLUTTER_DESKTOP_FEATURES = "dart"
PRODUCT_NAME = "AppFlowy"
MACOSX_DEPLOYMENT_TARGET = "11.0"
@@ -1,10 +1,19 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/desktop_floating_toolbar.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_create_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_edit_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/custom_link_toolbar_item.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/more_option_toolbar_item.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/text_suggestions_toolbar_item.dart';
import 'package:appflowy/startup/startup.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_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
@@ -176,4 +185,146 @@ void main() {
);
});
});
group('document toolbar: link', () {
String? getLinkFromNode(Node node) {
for (final insert in node.delta!) {
final link = insert.attributes?.href;
if (link != null) return link;
}
return null;
}
bool isPageLink(Node node) {
for (final insert in node.delta!) {
final isPage = insert.attributes?.isPage;
if (isPage == true) return true;
}
return false;
}
String getNodeText(Node node) {
for (final insert in node.delta!) {
if (insert is TextInsert) return insert.text;
}
return '';
}
testWidgets('insert link and remove link', (tester) async {
const text = 'insert link', link = 'https://test.appflowy.cloud';
await prepareForToolbar(tester, text);
final toolbar = find.byType(DesktopFloatingToolbar);
expect(toolbar, findsOneWidget);
/// tap link button to show CreateLinkMenu
final linkButton = find.byFlowySvg(FlowySvgs.toolbar_link_m);
await tester.tapButton(linkButton);
final createLinkMenu = find.byType(LinkCreateMenu);
expect(createLinkMenu, findsOneWidget);
/// test esc to close
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
expect(toolbar, findsNothing);
/// show toolbar again
await selectText(tester, text);
await tester.tapButton(linkButton);
/// insert link
final textField = find.descendant(
of: createLinkMenu,
matching: find.byType(TextFormField),
);
await tester.enterText(textField, link);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
Node node = tester.editor.getNodeAtPath([0]);
expect(getLinkFromNode(node), link);
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
/// hover link
await tester.hoverOnWidget(find.byType(LinkHoverTrigger));
final hoverMenu = find.byType(LinkHoverMenu);
expect(hoverMenu, findsOneWidget);
/// copy link
final copyButton = find.descendant(
of: hoverMenu,
matching: find.byFlowySvg(FlowySvgs.toolbar_link_m),
);
await tester.tapButton(copyButton);
final clipboardContent = await getIt<ClipboardService>().getData();
final plainText = clipboardContent.plainText;
expect(plainText, link);
/// remove link
await tester.hoverOnWidget(find.byType(LinkHoverTrigger));
await tester.tapButton(find.byFlowySvg(FlowySvgs.toolbar_link_unlink_m));
node = tester.editor.getNodeAtPath([0]);
expect(getLinkFromNode(node), null);
});
testWidgets('insert link and edit link', (tester) async {
const text = 'edit link',
link = 'https://test.appflowy.cloud',
afterText = '$text after';
await prepareForToolbar(tester, text);
/// tap link button to show CreateLinkMenu
final linkButton = find.byFlowySvg(FlowySvgs.toolbar_link_m);
await tester.tapButton(linkButton);
/// search for page and select it
final textField = find.descendant(
of: find.byType(LinkCreateMenu),
matching: find.byType(TextFormField),
);
await tester.enterText(textField, gettingStarted);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
Node node = tester.editor.getNodeAtPath([0]);
expect(isPageLink(node), true);
expect(getLinkFromNode(node) == link, false);
/// hover link
await tester.hoverOnWidget(find.byType(LinkHoverTrigger));
/// click edit button to show LinkEditMenu
final editButton = find.byFlowySvg(FlowySvgs.toolbar_link_edit_m);
await tester.tapButton(editButton);
final linkEditMenu = find.byType(LinkEditMenu);
expect(linkEditMenu, findsOneWidget);
/// change the link text
final titleField = find.descendant(
of: linkEditMenu,
matching: find.byType(TextFormField),
);
await tester.enterText(titleField, afterText);
await tester.pumpAndSettle();
await tester.tapButton(
find.descendant(of: linkEditMenu, matching: find.text(gettingStarted)),
);
final linkField = find.ancestor(
of: find.text(LocaleKeys.document_toolbar_linkInputHint.tr()),
matching: find.byType(TextFormField),
);
await tester.enterText(linkField, link);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
/// apply the change
final applyButton =
find.text(LocaleKeys.settings_appearance_documentSettings_apply.tr());
await tester.tapButton(applyButton);
node = tester.editor.getNodeAtPath([0]);
expect(isPageLink(node), false);
expect(getLinkFromNode(node), link);
expect(getNodeText(node), afterText);
});
});
}
@@ -1,8 +1,10 @@
import 'dart:io';
import 'package:appflowy/plugins/emoji/emoji_handler.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/emoji_picker/emoji_picker.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor/src/editor/editor_component/service/editor.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
@@ -39,4 +41,114 @@ void main() {
expect(find.byType(EmojiSelectionMenu), findsOneWidget);
});
});
group('insert emoji by colon', () {
Future<void> createNewDocumentAndShowEmojiList(WidgetTester tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent();
await tester.editor.tapLineOfEditorAt(0);
await tester.ime.insertText(':');
await tester.pumpAndSettle(Duration(seconds: 1));
}
testWidgets('insert with click', (tester) async {
await createNewDocumentAndShowEmojiList(tester);
/// emoji list is showing
final emojiHandler = find.byType(EmojiHandler);
expect(emojiHandler, findsOneWidget);
final emojiButtons =
find.descendant(of: emojiHandler, matching: find.byType(FlowyButton));
final firstTextFinder = find.descendant(
of: emojiButtons.first,
matching: find.byType(FlowyText),
);
final emojiText =
(firstTextFinder.evaluate().first.widget as FlowyText).text;
/// click first emoji item
await tester.tapButton(emojiButtons.first);
final firstNode =
tester.editor.getCurrentEditorState().getNodeAtPath([0])!;
/// except the emoji is in document
expect(emojiText.contains(firstNode.delta!.toPlainText()), true);
});
testWidgets('insert with arrow and enter', (tester) async {
await createNewDocumentAndShowEmojiList(tester);
/// emoji list is showing
final emojiHandler = find.byType(EmojiHandler);
expect(emojiHandler, findsOneWidget);
final emojiButtons =
find.descendant(of: emojiHandler, matching: find.byType(FlowyButton));
/// tap arrow down and arrow up
await tester.simulateKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.simulateKeyEvent(LogicalKeyboardKey.arrowDown);
final firstTextFinder = find.descendant(
of: emojiButtons.first,
matching: find.byType(FlowyText),
);
final emojiText =
(firstTextFinder.evaluate().first.widget as FlowyText).text;
/// tap enter
await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
final firstNode =
tester.editor.getCurrentEditorState().getNodeAtPath([0])!;
/// except the emoji is in document
expect(emojiText.contains(firstNode.delta!.toPlainText()), true);
});
testWidgets('insert with searching', (tester) async {
await createNewDocumentAndShowEmojiList(tester);
/// search for `smiling eyes`, IME is not working, use keyboard input
final searchText = [
LogicalKeyboardKey.keyS,
LogicalKeyboardKey.keyM,
LogicalKeyboardKey.keyI,
LogicalKeyboardKey.keyL,
LogicalKeyboardKey.keyI,
LogicalKeyboardKey.keyN,
LogicalKeyboardKey.keyG,
LogicalKeyboardKey.space,
LogicalKeyboardKey.keyE,
LogicalKeyboardKey.keyY,
LogicalKeyboardKey.keyE,
LogicalKeyboardKey.keyS,
];
for (final key in searchText) {
await tester.simulateKeyEvent(key);
}
/// tap enter
await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
final firstNode =
tester.editor.getCurrentEditorState().getNodeAtPath([0])!;
/// except the emoji is in document
expect(firstNode.delta!.toPlainText().contains('😄'), true);
});
testWidgets('start searching with sapce', (tester) async {
await createNewDocumentAndShowEmojiList(tester);
/// emoji list is showing
final emojiHandler = find.byType(EmojiHandler);
expect(emojiHandler, findsOneWidget);
/// input space
await tester.simulateKeyEvent(LogicalKeyboardKey.space);
/// emoji list is dismissed
expect(emojiHandler, findsNothing);
});
});
}
@@ -13,7 +13,6 @@ void main() {
hotkeys_test.main();
emoji_shortcut_test.main();
hotkeys_test.main();
emoji_shortcut_test.main();
share_markdown_test.main();
import_files_test.main();
zoom_in_out_test.main();
+3
View File
@@ -2,6 +2,8 @@ export 'service/ai_entities.dart';
export 'service/ai_prompt_input_bloc.dart';
export 'service/appflowy_ai_service.dart';
export 'service/error.dart';
export 'service/ai_model_state_notifier.dart';
export 'service/select_model_bloc.dart';
export 'widgets/loading_indicator.dart';
export 'widgets/prompt_input/action_buttons.dart';
export 'widgets/prompt_input/desktop_prompt_text_field.dart';
@@ -13,4 +15,5 @@ export 'widgets/prompt_input/mentioned_page_text_span.dart';
export 'widgets/prompt_input/predefined_format_buttons.dart';
export 'widgets/prompt_input/select_sources_bottom_sheet.dart';
export 'widgets/prompt_input/select_sources_menu.dart';
export 'widgets/prompt_input/select_model_menu.dart';
export 'widgets/prompt_input/send_button.dart';
@@ -4,6 +4,28 @@ import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:equatable/equatable.dart';
class AIStreamEventPrefix {
static const data = 'data:';
static const error = 'error:';
static const metadata = 'metadata:';
static const start = 'start:';
static const finish = 'finish:';
static const comment = 'comment:';
static const aiResponseLimit = 'AI_RESPONSE_LIMIT';
static const aiImageResponseLimit = 'AI_IMAGE_RESPONSE_LIMIT';
static const aiMaxRequired = 'AI_MAX_REQUIRED:';
static const localAINotReady = 'LOCAL_AI_NOT_READY';
static const localAIDisabled = 'LOCAL_AI_DISABLED';
}
enum AiType {
cloud,
local;
bool get isCloud => this == cloud;
bool get isLocal => this == local;
}
class PredefinedFormat extends Equatable {
const PredefinedFormat({
required this.imageFormat,
@@ -0,0 +1,181 @@
import 'package:appflowy/ai/ai.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/ai_model_switch_listener.dart';
import 'package:appflowy/workspace/application/settings/ai/local_llm_listener.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:protobuf/protobuf.dart';
import 'package:universal_platform/universal_platform.dart';
typedef OnModelStateChangedCallback = void Function(AiType, bool, String);
typedef OnAvailableModelsChangedCallback = void Function(
List<AIModelPB>,
AIModelPB?,
);
class AIModelStateNotifier {
AIModelStateNotifier({required this.objectId})
: _localAIListener =
UniversalPlatform.isDesktop ? LocalAIStateListener() : null,
_aiModelSwitchListener = AIModelSwitchListener(objectId: objectId) {
_startListening();
_init();
}
final String objectId;
final LocalAIStateListener? _localAIListener;
final AIModelSwitchListener _aiModelSwitchListener;
LocalAIPB? _localAIState;
AvailableModelsPB? _availableModels;
// callbacks
final List<OnModelStateChangedCallback> _stateChangedCallbacks = [];
final List<OnAvailableModelsChangedCallback>
_availableModelsChangedCallbacks = [];
void _startListening() {
if (UniversalPlatform.isDesktop) {
_localAIListener?.start(
stateCallback: (state) async {
_localAIState = state;
_notifyStateChanged();
if (state.state == RunningStatePB.Running ||
state.state == RunningStatePB.Stopped) {
await _loadAvailableModels();
_notifyAvailableModelsChanged();
}
},
);
}
_aiModelSwitchListener.start(
onUpdateSelectedModel: (model) async {
final updatedModels = _availableModels?.deepCopy()
?..selectedModel = model;
_availableModels = updatedModels;
_notifyAvailableModelsChanged();
if (model.isLocal && UniversalPlatform.isDesktop) {
await _loadLocalAiState();
}
_notifyStateChanged();
},
);
}
void _init() async {
await Future.wait([_loadLocalAiState(), _loadAvailableModels()]);
_notifyStateChanged();
_notifyAvailableModelsChanged();
}
void addListener({
OnModelStateChangedCallback? onStateChanged,
OnAvailableModelsChangedCallback? onAvailableModelsChanged,
}) {
if (onStateChanged != null) {
_stateChangedCallbacks.add(onStateChanged);
}
if (onAvailableModelsChanged != null) {
_availableModelsChangedCallbacks.add(onAvailableModelsChanged);
}
}
void removeListener({
OnModelStateChangedCallback? onStateChanged,
OnAvailableModelsChangedCallback? onAvailableModelsChanged,
}) {
if (onStateChanged != null) {
_stateChangedCallbacks.remove(onStateChanged);
}
if (onAvailableModelsChanged != null) {
_availableModelsChangedCallbacks.remove(onAvailableModelsChanged);
}
}
Future<void> dispose() async {
_stateChangedCallbacks.clear();
_availableModelsChangedCallbacks.clear();
await _localAIListener?.stop();
await _aiModelSwitchListener.stop();
}
(AiType, String, bool) getState() {
if (UniversalPlatform.isMobile) {
return (AiType.cloud, LocaleKeys.chat_inputMessageHint.tr(), true);
}
final availableModels = _availableModels;
final localAiState = _localAIState;
if (availableModels == null) {
return (AiType.cloud, LocaleKeys.chat_inputMessageHint.tr(), true);
}
if (localAiState == null) {
Log.warn("Cannot get local AI state");
return (AiType.cloud, LocaleKeys.chat_inputMessageHint.tr(), true);
}
if (!availableModels.selectedModel.isLocal) {
return (AiType.cloud, LocaleKeys.chat_inputMessageHint.tr(), true);
}
final editable = localAiState.state == RunningStatePB.Running;
final hintText = editable
? LocaleKeys.chat_inputLocalAIMessageHint.tr()
: LocaleKeys.settings_aiPage_keys_localAIInitializing.tr();
return (AiType.local, hintText, editable);
}
(List<AIModelPB>, AIModelPB?) getAvailableModels() {
final availableModels = _availableModels;
if (availableModels == null) {
return ([], null);
}
return (availableModels.models, availableModels.selectedModel);
}
void _notifyAvailableModelsChanged() {
final (models, selectedModel) = getAvailableModels();
for (final callback in _availableModelsChangedCallbacks) {
callback(models, selectedModel);
}
}
void _notifyStateChanged() {
final (type, hintText, isEditable) = getState();
for (final callback in _stateChangedCallbacks) {
callback(type, isEditable, hintText);
}
}
Future<void> _loadAvailableModels() {
final payload = AvailableModelsQueryPB(source: objectId);
return AIEventGetAvailableModels(payload).send().fold(
(models) => _availableModels = models,
(err) => Log.error("Failed to get available models: $err"),
);
}
Future<void> _loadLocalAiState() {
return AIEventGetLocalAIState().send().fold(
(localAIState) => _localAIState = localAIState,
(error) => Log.error("Failed to get local AI state: $error"),
);
}
}
extension AiModelExtension on AIModelPB {
bool get isDefault {
return name == "Auto";
}
String get i18n {
return isDefault ? LocaleKeys.chat_switchModel_autoModel.tr() : name;
}
}
@@ -1,14 +1,8 @@
import 'dart:async';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/ai/service/ai_model_state_notifier.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/workspace/application/settings/ai/local_llm_listener.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
@@ -18,19 +12,20 @@ part 'ai_prompt_input_bloc.freezed.dart';
class AIPromptInputBloc extends Bloc<AIPromptInputEvent, AIPromptInputState> {
AIPromptInputBloc({
required String objectId,
required PredefinedFormat? predefinedFormat,
}) : _listener = LocalAIStateListener(),
}) : aiModelStateNotifier = AIModelStateNotifier(objectId: objectId),
super(AIPromptInputState.initial(predefinedFormat)) {
_dispatch();
_startListening();
_init();
}
final LocalAIStateListener _listener;
final AIModelStateNotifier aiModelStateNotifier;
@override
Future<void> close() async {
await _listener.stop();
await aiModelStateNotifier.dispose();
return super.close();
}
@@ -38,29 +33,10 @@ class AIPromptInputBloc extends Bloc<AIPromptInputEvent, AIPromptInputState> {
on<AIPromptInputEvent>(
(event, emit) {
event.when(
updateAIState: (localAIState) {
final aiType = localAIState.enabled ? AiType.local : AiType.cloud;
// final supportChatWithFile =
// aiType.isLocal && localAIState.state == RunningStatePB.Running;
// If local ai is enabled, user can only send messages when the AI is running
final editable = localAIState.enabled
? localAIState.state == RunningStatePB.Running
: true;
var hintText = aiType.isLocal
? LocaleKeys.chat_inputLocalAIMessageHint.tr()
: LocaleKeys.chat_inputMessageHint.tr();
if (editable == false && aiType.isLocal) {
hintText =
LocaleKeys.settings_aiPage_keys_localAIInitializing.tr();
}
updateAIState: (aiType, editable, hintText) {
emit(
state.copyWith(
aiType: aiType,
supportChatWithFile: false,
localAIState: localAIState,
editable: editable,
hintText: hintText,
),
@@ -128,24 +104,16 @@ class AIPromptInputBloc extends Bloc<AIPromptInputEvent, AIPromptInputState> {
}
void _startListening() {
_listener.start(
stateCallback: (pluginState) {
if (!isClosed) {
add(AIPromptInputEvent.updateAIState(pluginState));
}
aiModelStateNotifier.addListener(
onStateChanged: (aiType, editable, hintText) {
add(AIPromptInputEvent.updateAIState(aiType, editable, hintText));
},
);
}
void _init() {
AIEventGetLocalAIState().send().fold(
(localAIState) {
if (!isClosed) {
add(AIPromptInputEvent.updateAIState(localAIState));
}
},
Log.error,
);
final (aiType, hintText, isEditable) = aiModelStateNotifier.getState();
add(AIPromptInputEvent.updateAIState(aiType, isEditable, hintText));
}
Map<String, dynamic> consumeMetadata() {
@@ -164,8 +132,12 @@ class AIPromptInputBloc extends Bloc<AIPromptInputEvent, AIPromptInputState> {
@freezed
class AIPromptInputEvent with _$AIPromptInputEvent {
const factory AIPromptInputEvent.updateAIState(LocalAIPB localAIState) =
_UpdateAIState;
const factory AIPromptInputEvent.updateAIState(
AiType aiType,
bool editable,
String hintText,
) = _UpdateAIState;
const factory AIPromptInputEvent.toggleShowPredefinedFormat() =
_ToggleShowPredefinedFormat;
const factory AIPromptInputEvent.updatePredefinedFormat(
@@ -188,7 +160,6 @@ class AIPromptInputState with _$AIPromptInputState {
required bool supportChatWithFile,
required bool showPredefinedFormats,
required PredefinedFormat? predefinedFormat,
required LocalAIPB? localAIState,
required List<ChatFile> attachedFiles,
required List<ViewPB> mentionedPages,
required bool editable,
@@ -201,18 +172,9 @@ class AIPromptInputState with _$AIPromptInputState {
supportChatWithFile: false,
showPredefinedFormats: format != null,
predefinedFormat: format,
localAIState: null,
attachedFiles: [],
mentionedPages: [],
editable: true,
hintText: '',
);
}
enum AiType {
cloud,
local;
bool get isCloud => this == cloud;
bool get isLocal => this == local;
}
@@ -15,6 +15,11 @@ import 'package:fixnum/fixnum.dart' as fixnum;
import 'ai_entities.dart';
import 'error.dart';
enum LocalAIStreamingState {
notReady,
disabled,
}
abstract class AIRepository {
Future<void> streamCompletion({
String? objectId,
@@ -24,9 +29,12 @@ abstract class AIRepository {
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
required Future<void> Function(String text) processMessage,
required Future<void> Function(String text) processAssistMessage,
required Future<void> Function() onEnd,
required void Function(AIError error) onError,
required void Function(LocalAIStreamingState state)
onLocalAIStreamingStateChange,
});
}
@@ -40,15 +48,20 @@ class AppFlowyAIService implements AIRepository {
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
required Future<void> Function(String text) processMessage,
required Future<void> Function(String text) processAssistMessage,
required Future<void> Function() onEnd,
required void Function(AIError error) onError,
required void Function(LocalAIStreamingState state)
onLocalAIStreamingStateChange,
}) async {
final stream = AppFlowyCompletionStream(
onStart: onStart,
onProcess: onProcess,
processMessage: processMessage,
processAssistMessage: processAssistMessage,
processError: onError,
onLocalAIStreamingStateChange: onLocalAIStreamingStateChange,
onEnd: onEnd,
onError: onError,
);
final records = history.map((record) => record.toPB()).toList();
@@ -79,23 +92,30 @@ class AppFlowyAIService implements AIRepository {
abstract class CompletionStream {
CompletionStream({
required this.onStart,
required this.onProcess,
required this.processMessage,
required this.processAssistMessage,
required this.processError,
required this.onLocalAIStreamingStateChange,
required this.onEnd,
required this.onError,
});
final Future<void> Function() onStart;
final Future<void> Function(String text) onProcess;
final Future<void> Function(String text) processMessage;
final Future<void> Function(String text) processAssistMessage;
final void Function(AIError error) processError;
final void Function(LocalAIStreamingState state)
onLocalAIStreamingStateChange;
final Future<void> Function() onEnd;
final void Function(AIError error) onError;
}
class AppFlowyCompletionStream extends CompletionStream {
AppFlowyCompletionStream({
required super.onStart,
required super.onProcess,
required super.processMessage,
required super.processAssistMessage,
required super.processError,
required super.onEnd,
required super.onError,
required super.onLocalAIStreamingStateChange,
}) {
_startListening();
}
@@ -109,51 +129,7 @@ class AppFlowyCompletionStream extends CompletionStream {
_port.handler = _controller.add;
_subscription = _controller.stream.listen(
(event) async {
if (event == "AI_RESPONSE_LIMIT") {
onError(
AIError(
message: LocaleKeys.ai_textLimitReachedDescription.tr(),
code: AIErrorCode.aiResponseLimitExceeded,
),
);
}
if (event == "AI_IMAGE_RESPONSE_LIMIT") {
onError(
AIError(
message: LocaleKeys.ai_imageLimitReachedDescription.tr(),
code: AIErrorCode.aiImageResponseLimitExceeded,
),
);
}
if (event.startsWith("AI_MAX_REQUIRED:")) {
final msg = event.substring(16);
onError(
AIError(
message: msg,
code: AIErrorCode.other,
),
);
}
if (event.startsWith("start:")) {
await onStart();
}
if (event.startsWith("data:")) {
await onProcess(event.substring(5));
}
if (event.startsWith("finish:")) {
await onEnd();
}
if (event.startsWith("error:")) {
onError(
AIError(message: event.substring(6), code: AIErrorCode.other),
);
}
await _handleEvent(event);
},
);
}
@@ -163,4 +139,66 @@ class AppFlowyCompletionStream extends CompletionStream {
await _subscription.cancel();
_port.close();
}
Future<void> _handleEvent(String event) async {
// Check simple matches first
if (event == AIStreamEventPrefix.aiResponseLimit) {
processError(
AIError(
message: LocaleKeys.ai_textLimitReachedDescription.tr(),
code: AIErrorCode.aiResponseLimitExceeded,
),
);
return;
}
if (event == AIStreamEventPrefix.aiImageResponseLimit) {
processError(
AIError(
message: LocaleKeys.ai_imageLimitReachedDescription.tr(),
code: AIErrorCode.aiImageResponseLimitExceeded,
),
);
return;
}
// Otherwise, parse out prefix:content
if (event.startsWith(AIStreamEventPrefix.aiMaxRequired)) {
processError(
AIError(
message: event.substring(AIStreamEventPrefix.aiMaxRequired.length),
code: AIErrorCode.other,
),
);
} else if (event.startsWith(AIStreamEventPrefix.start)) {
await onStart();
} else if (event.startsWith(AIStreamEventPrefix.data)) {
await processMessage(
event.substring(AIStreamEventPrefix.data.length),
);
} else if (event.startsWith(AIStreamEventPrefix.comment)) {
await processAssistMessage(
event.substring(AIStreamEventPrefix.comment.length),
);
} else if (event.startsWith(AIStreamEventPrefix.finish)) {
await onEnd();
} else if (event.startsWith(AIStreamEventPrefix.localAIDisabled)) {
onLocalAIStreamingStateChange(
LocalAIStreamingState.disabled,
);
} else if (event.startsWith(AIStreamEventPrefix.localAINotReady)) {
onLocalAIStreamingStateChange(
LocalAIStreamingState.notReady,
);
} else if (event.startsWith(AIStreamEventPrefix.error)) {
processError(
AIError(
message: event.substring(AIStreamEventPrefix.error.length),
code: AIErrorCode.other,
),
);
} else {
Log.debug('Unknown AI event: $event');
}
}
}
@@ -0,0 +1,92 @@
import 'dart:async';
import 'package:appflowy/ai/service/ai_model_state_notifier.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pbserver.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'select_model_bloc.freezed.dart';
class SelectModelBloc extends Bloc<SelectModelEvent, SelectModelState> {
SelectModelBloc({
required AIModelStateNotifier aiModelStateNotifier,
}) : _aiModelStateNotifier = aiModelStateNotifier,
super(SelectModelState.initial(aiModelStateNotifier)) {
on<SelectModelEvent>(
(event, emit) {
event.when(
selectModel: (model) {
AIEventUpdateSelectedModel(
UpdateSelectedModelPB(
source: _aiModelStateNotifier.objectId,
selectedModel: model,
),
).send();
emit(state.copyWith(selectedModel: model));
},
didLoadModels: (models, selectedModel) {
emit(
SelectModelState(
models: models,
selectedModel: selectedModel,
),
);
},
);
},
);
_aiModelStateNotifier.addListener(
onAvailableModelsChanged: _onAvailableModelsChanged,
);
}
final AIModelStateNotifier _aiModelStateNotifier;
@override
Future<void> close() async {
_aiModelStateNotifier.removeListener(
onAvailableModelsChanged: _onAvailableModelsChanged,
);
await super.close();
}
void _onAvailableModelsChanged(
List<AIModelPB> models,
AIModelPB? selectedModel,
) {
if (!isClosed) {
add(SelectModelEvent.didLoadModels(models, selectedModel));
}
}
}
@freezed
class SelectModelEvent with _$SelectModelEvent {
const factory SelectModelEvent.selectModel(
AIModelPB model,
) = _SelectModel;
const factory SelectModelEvent.didLoadModels(
List<AIModelPB> models,
AIModelPB? selectedModel,
) = _DidLoadModels;
}
@freezed
class SelectModelState with _$SelectModelState {
const factory SelectModelState({
required List<AIModelPB> models,
required AIModelPB? selectedModel,
}) = _SelectModelState;
factory SelectModelState.initial(AIModelStateNotifier notifier) {
final (models, selectedModel) = notifier.getAvailableModels();
return SelectModelState(
models: models,
selectedModel: selectedModel,
);
}
}
@@ -17,20 +17,24 @@ class DesktopPromptInput extends StatefulWidget {
const DesktopPromptInput({
super.key,
required this.isStreaming,
required this.textController,
required this.onStopStreaming,
required this.onSubmitted,
required this.selectedSourcesNotifier,
required this.onUpdateSelectedSources,
this.hideDecoration = false,
this.extraBottomActionButton,
});
final bool isStreaming;
final TextEditingController textController;
final void Function() onStopStreaming;
final void Function(String, PredefinedFormat?, Map<String, dynamic>)
onSubmitted;
final ValueNotifier<List<String>> selectedSourcesNotifier;
final void Function(List<String>) onUpdateSelectedSources;
final bool hideDecoration;
final Widget? extraBottomActionButton;
@override
State<DesktopPromptInput> createState() => _DesktopPromptInputState();
@@ -42,7 +46,6 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
final overlayController = OverlayPortalController();
final inputControlCubit = ChatInputControlCubit();
final focusNode = FocusNode();
final textController = TextEditingController();
late SendButtonState sendButtonState;
bool isComposing = false;
@@ -51,17 +54,19 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
void initState() {
super.initState();
textController.addListener(handleTextControllerChanged);
focusNode.addListener(
() {
if (!widget.hideDecoration) {
setState(() {}); // refresh border color
}
if (!focusNode.hasFocus) {
cancelMentionPage(); // hide menu when lost focus
}
},
);
widget.textController.addListener(handleTextControllerChanged);
focusNode
..addListener(
() {
if (!widget.hideDecoration) {
setState(() {}); // refresh border color
}
if (!focusNode.hasFocus) {
cancelMentionPage(); // hide menu when lost focus
}
},
)
..onKeyEvent = handleKeyEvent;
updateSendButtonState();
@@ -79,7 +84,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
@override
void dispose() {
focusNode.dispose();
textController.dispose();
widget.textController.removeListener(handleTextControllerChanged);
inputControlCubit.close();
super.dispose();
}
@@ -104,7 +109,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
overlayChildBuilder: (context) {
return PromptInputMentionPageMenu(
anchor: PromptInputAnchor(textFieldKey, layerLink),
textController: textController,
textController: widget.textController,
onPageSelected: handlePageSelected,
);
},
@@ -178,6 +183,8 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
widget.selectedSourcesNotifier,
onUpdateSelectedSources:
widget.onUpdateSelectedSources,
extraBottomActionButton:
widget.extraBottomActionButton,
),
),
),
@@ -216,12 +223,12 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
if (!focusNode.hasFocus) {
focusNode.requestFocus();
}
textController.text += '@';
widget.textController.text += '@';
WidgetsBinding.instance.addPostFrameCallback((_) {
if (context.mounted) {
context
.read<ChatInputControlCubit>()
.startSearching(textController.value);
.startSearching(widget.textController.value);
overlayController.show();
}
});
@@ -237,7 +244,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
void updateSendButtonState() {
if (widget.isStreaming) {
sendButtonState = SendButtonState.streaming;
} else if (textController.text.trim().isEmpty) {
} else if (widget.textController.text.trim().isEmpty) {
sendButtonState = SendButtonState.disabled;
} else {
sendButtonState = SendButtonState.enabled;
@@ -249,9 +256,9 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
return;
}
final trimmedText = inputControlCubit.formatIntputText(
textController.text.trim(),
widget.textController.text.trim(),
);
textController.clear();
widget.textController.clear();
if (trimmedText.isEmpty) {
return;
}
@@ -274,7 +281,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
setState(() {
// update whether send button is clickable
updateSendButtonState();
isComposing = !textController.value.composing.isCollapsed;
isComposing = !widget.textController.value.composing.isCollapsed;
});
if (isComposing) {
@@ -292,6 +299,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
}
// handle cases where mention a page is cancelled
final textController = widget.textController;
final textSelection = textController.value.selection;
final isSelectingMultipleCharacters = !textSelection.isCollapsed;
final isCaretBeforeStartOfRange =
@@ -338,22 +346,27 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
}
KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
if (event.character == '@') {
WidgetsBinding.instance.addPostFrameCallback((_) {
inputControlCubit.startSearching(textController.value);
overlayController.show();
});
// if (event.character == '@') {
// WidgetsBinding.instance.addPostFrameCallback((_) {
// inputControlCubit.startSearching(widget.textController.value);
// overlayController.show();
// });
// }
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
node.unfocus();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
void handlePageSelected(ViewPB view) {
final newText = textController.text.replaceRange(
final newText = widget.textController.text.replaceRange(
inputControlCubit.filterStartPosition,
inputControlCubit.filterEndPosition,
view.id,
);
textController.value = TextEditingValue(
widget.textController.value = TextEditingValue(
text: newText,
selection: TextSelection.collapsed(
offset: inputControlCubit.filterStartPosition + view.id.length,
@@ -378,7 +391,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
key: textFieldKey,
editable: state.editable,
cubit: inputControlCubit,
textController: textController,
textController: widget.textController,
textFieldFocusNode: focusNode,
contentPadding:
calculateContentPadding(state.showPredefinedFormats),
@@ -565,6 +578,7 @@ class _PromptBottomActions extends StatelessWidget {
required this.onStopStreaming,
required this.selectedSourcesNotifier,
required this.onUpdateSelectedSources,
this.extraBottomActionButton,
});
final bool showPredefinedFormats;
@@ -575,6 +589,7 @@ class _PromptBottomActions extends StatelessWidget {
final void Function() onStopStreaming;
final ValueNotifier<List<String>> selectedSourcesNotifier;
final void Function(List<String>) onUpdateSelectedSources;
final Widget? extraBottomActionButton;
@override
Widget build(BuildContext context) {
@@ -583,18 +598,25 @@ class _PromptBottomActions extends StatelessWidget {
margin: DesktopAIChatSizes.inputActionBarMargin,
child: BlocBuilder<AIPromptInputBloc, AIPromptInputState>(
builder: (context, state) {
if (state.localAIState == null) {
return Align(
alignment: AlignmentDirectional.centerEnd,
child: _sendButton(),
);
}
return Row(
children: [
_predefinedFormatButton(),
const HSpace(
DesktopAIChatSizes.inputActionBarButtonSpacing,
),
SelectModelMenu(
aiModelStateNotifier:
context.read<AIPromptInputBloc>().aiModelStateNotifier,
),
const Spacer(),
if (state.aiType.isCloud) ...[
_selectSourcesButton(context),
_selectSourcesButton(),
const HSpace(
DesktopAIChatSizes.inputActionBarButtonSpacing,
),
],
if (extraBottomActionButton != null) ...[
extraBottomActionButton!,
const HSpace(
DesktopAIChatSizes.inputActionBarButtonSpacing,
),
@@ -624,7 +646,7 @@ class _PromptBottomActions extends StatelessWidget {
);
}
Widget _selectSourcesButton(BuildContext context) {
Widget _selectSourcesButton() {
return PromptInputDesktopSelectSourcesButton(
onUpdateSelectedSources: onUpdateSelectedSources,
selectedSourcesNotifier: selectedSourcesNotifier,
@@ -104,6 +104,7 @@ class ChangeFormatBar extends StatelessWidget {
},
child: FlowyTooltip(
message: format.i18n,
preferBelow: false,
child: SizedBox.square(
dimension: _buttonSize,
child: FlowyHover(
@@ -150,6 +151,7 @@ class ChangeFormatBar extends StatelessWidget {
},
child: FlowyTooltip(
message: format.i18n,
preferBelow: false,
child: SizedBox.square(
dimension: _buttonSize,
child: FlowyHover(
@@ -0,0 +1,259 @@
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_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SelectModelMenu extends StatefulWidget {
const SelectModelMenu({
super.key,
required this.aiModelStateNotifier,
});
final AIModelStateNotifier aiModelStateNotifier;
@override
State<SelectModelMenu> createState() => _SelectModelMenuState();
}
class _SelectModelMenuState extends State<SelectModelMenu> {
final popoverController = PopoverController();
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SelectModelBloc(
aiModelStateNotifier: widget.aiModelStateNotifier,
),
child: BlocBuilder<SelectModelBloc, SelectModelState>(
builder: (context, state) {
if (state.selectedModel == null) {
return const SizedBox.shrink();
}
return AppFlowyPopover(
offset: Offset(-12.0, 0.0),
constraints: BoxConstraints(maxWidth: 250, maxHeight: 600),
direction: PopoverDirection.topWithLeftAligned,
margin: EdgeInsets.zero,
controller: popoverController,
popupBuilder: (popoverContext) {
return SelectModelPopoverContent(
models: state.models,
selectedModel: state.selectedModel,
onSelectModel: (model) {
if (model != state.selectedModel) {
context
.read<SelectModelBloc>()
.add(SelectModelEvent.selectModel(model));
}
popoverController.close();
},
);
},
child: _CurrentModelButton(
model: state.selectedModel!,
onTap: () => popoverController.show(),
),
);
},
),
);
}
}
class SelectModelPopoverContent extends StatelessWidget {
const SelectModelPopoverContent({
super.key,
required this.models,
required this.selectedModel,
this.onSelectModel,
});
final List<AIModelPB> models;
final AIModelPB? selectedModel;
final void Function(AIModelPB)? onSelectModel;
@override
Widget build(BuildContext context) {
if (models.isEmpty) {
return const SizedBox.shrink();
}
// separate models into local and cloud models
final localModels = models.where((model) => model.isLocal).toList();
final cloudModels = models.where((model) => !model.isLocal).toList();
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (localModels.isNotEmpty) ...[
_ModelSectionHeader(
title: LocaleKeys.chat_switchModel_localModel.tr(),
),
const VSpace(4.0),
],
...localModels.map(
(model) => _ModelItem(
model: model,
isSelected: model == selectedModel,
onTap: () => onSelectModel?.call(model),
),
),
if (cloudModels.isNotEmpty && localModels.isNotEmpty) ...[
const VSpace(8.0),
_ModelSectionHeader(
title: LocaleKeys.chat_switchModel_cloudModel.tr(),
),
const VSpace(4.0),
],
...cloudModels.map(
(model) => _ModelItem(
model: model,
isSelected: model == selectedModel,
onTap: () => onSelectModel?.call(model),
),
),
],
),
);
}
}
class _ModelSectionHeader extends StatelessWidget {
const _ModelSectionHeader({
required this.title,
});
final String title;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 4, bottom: 2),
child: FlowyText(
title,
fontSize: 12,
figmaLineHeight: 16,
color: Theme.of(context).hintColor,
fontWeight: FontWeight.w500,
),
);
}
}
class _ModelItem extends StatelessWidget {
const _ModelItem({
required this.model,
required this.isSelected,
required this.onTap,
});
final AIModelPB model;
final bool isSelected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: const BoxConstraints(minHeight: 32),
child: FlowyButton(
onTap: onTap,
margin: EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0),
text: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText(
model.i18n,
figmaLineHeight: 20,
overflow: TextOverflow.ellipsis,
color: isSelected ? Theme.of(context).colorScheme.primary : null,
),
if (model.desc.isNotEmpty)
FlowyText(
model.desc,
fontSize: 12,
figmaLineHeight: 16,
color: Theme.of(context).hintColor,
overflow: TextOverflow.ellipsis,
),
],
),
rightIcon: isSelected
? FlowySvg(
FlowySvgs.check_s,
size: const Size.square(20),
color: Theme.of(context).colorScheme.primary,
)
: null,
),
);
}
}
class _CurrentModelButton extends StatelessWidget {
const _CurrentModelButton({
required this.model,
required this.onTap,
});
final AIModelPB model;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return FlowyTooltip(
message: LocaleKeys.chat_switchModel_label.tr(),
child: GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: SizedBox(
height: DesktopAIPromptSizes.actionBarButtonSize,
child: FlowyHover(
style: const HoverStyle(
borderRadius: BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: const EdgeInsetsDirectional.all(4.0),
child: Row(
children: [
Padding(
// TODO: remove this after change icon to 20px
padding: EdgeInsets.all(2),
child: FlowySvg(
FlowySvgs.ai_sparks_s,
color: Theme.of(context).hintColor,
size: Size.square(16),
),
),
if (!model.isDefault)
Padding(
padding: EdgeInsetsDirectional.only(end: 2.0),
child: FlowyText(
model.i18n,
fontSize: 12,
figmaLineHeight: 16,
color: Theme.of(context).hintColor,
overflow: TextOverflow.ellipsis,
),
),
FlowySvg(
FlowySvgs.ai_source_drop_down_s,
color: Theme.of(context).hintColor,
size: const Size.square(8),
),
],
),
),
),
),
),
);
}
}
@@ -145,7 +145,7 @@ class _IndicatorButton extends StatelessWidget {
children: [
FlowySvg(
FlowySvgs.ai_page_s,
color: Theme.of(context).iconTheme.color,
color: Theme.of(context).hintColor,
),
const HSpace(2.0),
ValueListenableBuilder(
@@ -170,7 +170,7 @@ class _IndicatorButton extends StatelessWidget {
FlowySvg(
FlowySvgs.ai_source_drop_down_s,
color: Theme.of(context).hintColor,
size: const Size.square(10),
size: const Size.square(8),
),
],
),
@@ -100,7 +100,6 @@ class _MobileHomeSettingPageState extends State<MobileHomeSettingPage> {
key: ValueKey(currentWorkspaceId),
userProfile: userProfile,
workspaceId: currentWorkspaceId,
currentWorkspaceMemberRole: state.currentWorkspace?.role,
),
const SupportSettingGroup(),
const AboutSettingGroup(),
@@ -5,8 +5,6 @@ import 'package:appflowy/mobile/presentation/setting/widgets/mobile_setting_item
import 'package:appflowy/mobile/presentation/widgets/flowy_option_tile.dart';
import 'package:appflowy/workspace/application/settings/ai/settings_ai_bloc.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/workspace.pbenum.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
@@ -18,12 +16,10 @@ class AiSettingsGroup extends StatelessWidget {
super.key,
required this.userProfile,
required this.workspaceId,
this.currentWorkspaceMemberRole,
});
final UserProfilePB userProfile;
final String workspaceId;
final AFRolePB? currentWorkspaceMemberRole;
@override
Widget build(BuildContext context) {
@@ -32,7 +28,6 @@ class AiSettingsGroup extends StatelessWidget {
create: (context) => SettingsAIBloc(
userProfile,
workspaceId,
currentWorkspaceMemberRole,
)..add(const SettingsAIEvent.started()),
child: BlocBuilder<SettingsAIBloc, SettingsAIState>(
builder: (context, state) {
@@ -48,7 +43,7 @@ class AiSettingsGroup extends StatelessWidget {
children: [
Flexible(
child: FlowyText(
state.selectedAIModel,
state.availableModels?.selectedModel.name ?? "",
color: theme.colorScheme.onSurface,
overflow: TextOverflow.ellipsis,
),
@@ -84,16 +79,19 @@ class AiSettingsGroup extends StatelessWidget {
title: LocaleKeys.settings_aiPage_keys_llmModelType.tr(),
builder: (_) {
return Column(
children: availableModels
.mapIndexed(
(index, model) => FlowyOptionTile.checkbox(
text: model,
showTopBorder: index == 0,
isSelected: state.selectedAIModel == model,
children: (availableModels?.models ?? [])
.asMap()
.entries
.map(
(entry) => FlowyOptionTile.checkbox(
text: entry.value.name,
showTopBorder: entry.key == 0,
isSelected:
availableModels?.selectedModel.name == entry.value.name,
onTap: () {
context
.read<SettingsAIBloc>()
.add(SettingsAIEvent.selectModel(model));
.add(SettingsAIEvent.selectModel(entry.value));
context.pop();
},
),
@@ -0,0 +1,53 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/plugins/ai_chat/application/chat_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
typedef OnUpdateSelectedModel = void Function(AIModelPB model);
class AIModelSwitchListener {
AIModelSwitchListener({required this.objectId}) {
_parser = ChatNotificationParser(id: objectId, callback: _callback);
_subscription = RustStreamReceiver.listen(
(observable) => _parser?.parse(observable),
);
}
final String objectId;
StreamSubscription<SubscribeObject>? _subscription;
ChatNotificationParser? _parser;
void start({
OnUpdateSelectedModel? onUpdateSelectedModel,
}) {
this.onUpdateSelectedModel = onUpdateSelectedModel;
}
OnUpdateSelectedModel? onUpdateSelectedModel;
void _callback(
ChatNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
result.map((r) {
switch (ty) {
case ChatNotification.DidUpdateSelectedModel:
onUpdateSelectedModel?.call(AIModelPB.fromBuffer(r));
break;
default:
break;
}
});
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}
@@ -239,9 +239,9 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
),
);
},
regenerateAnswer: (id, format) {
regenerateAnswer: (id, format, model) {
_clearRelatedQuestions();
_regenerateAnswer(id, format);
_regenerateAnswer(id, format, model);
lastSentMessage = null;
isFetchingRelatedQuestions = false;
@@ -483,6 +483,7 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
void _regenerateAnswer(
String answerMessageIdString,
PredefinedFormat? format,
AIModelPB? model,
) async {
final id = temporaryMessageIDMap.entries
.firstWhereOrNull((e) => e.value == answerMessageIdString)
@@ -505,6 +506,9 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
if (format != null) {
payload.format = format.toPB();
}
if (model != null) {
payload.model = model;
}
await AIEventRegenerateResponse(payload).send().fold(
(success) {
@@ -637,6 +641,7 @@ class ChatEvent with _$ChatEvent {
const factory ChatEvent.regenerateAnswer(
String id,
PredefinedFormat? format,
AIModelPB? model,
) = _RegenerateAnswer;
// streaming answer
@@ -2,19 +2,9 @@ import 'dart:async';
import 'dart:ffi';
import 'dart:isolate';
import 'package:appflowy/ai/service/ai_entities.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_service.dart';
/// Constants for event prefixes.
class AnswerEventPrefix {
static const data = 'data:';
static const error = 'error:';
static const metadata = 'metadata:';
static const aiResponseLimit = 'AI_RESPONSE_LIMIT';
static const aiImageResponseLimit = 'AI_IMAGE_RESPONSE_LIMIT';
static const aiMaxRequired = 'AI_MAX_REQUIRED:';
static const localAINotReady = 'LOCAL_AI_NOT_READY';
}
/// A stream that receives answer events from an isolate or external process.
/// It caches events that might occur before a listener is attached.
class AnswerStream {
@@ -68,31 +58,31 @@ class AnswerStream {
/// Handles incoming events from the underlying stream.
void _handleEvent(String event) {
if (event.startsWith(AnswerEventPrefix.data)) {
if (event.startsWith(AIStreamEventPrefix.data)) {
_hasStarted = true;
final newText = event.substring(AnswerEventPrefix.data.length);
final newText = event.substring(AIStreamEventPrefix.data.length);
_text += newText;
_onData?.call(_text);
} else if (event.startsWith(AnswerEventPrefix.error)) {
_error = event.substring(AnswerEventPrefix.error.length);
} else if (event.startsWith(AIStreamEventPrefix.error)) {
_error = event.substring(AIStreamEventPrefix.error.length);
_onError?.call(_error!);
} else if (event.startsWith(AnswerEventPrefix.metadata)) {
final s = event.substring(AnswerEventPrefix.metadata.length);
} else if (event.startsWith(AIStreamEventPrefix.metadata)) {
final s = event.substring(AIStreamEventPrefix.metadata.length);
_onMetadata?.call(parseMetadata(s));
} else if (event == AnswerEventPrefix.aiResponseLimit) {
} else if (event == AIStreamEventPrefix.aiResponseLimit) {
_aiLimitReached = true;
_onAIResponseLimit?.call();
} else if (event == AnswerEventPrefix.aiImageResponseLimit) {
} else if (event == AIStreamEventPrefix.aiImageResponseLimit) {
_aiImageLimitReached = true;
_onAIImageResponseLimit?.call();
} else if (event.startsWith(AnswerEventPrefix.aiMaxRequired)) {
final msg = event.substring(AnswerEventPrefix.aiMaxRequired.length);
} else if (event.startsWith(AIStreamEventPrefix.aiMaxRequired)) {
final msg = event.substring(AIStreamEventPrefix.aiMaxRequired.length);
if (_onAIMaxRequired != null) {
_onAIMaxRequired!(msg);
} else {
_pendingAIMaxRequiredEvents.add(msg);
}
} else if (event.startsWith(AnswerEventPrefix.localAINotReady)) {
} else if (event.startsWith(AIStreamEventPrefix.localAINotReady)) {
if (_onLocalAIInitializing != null) {
_onLocalAIInitializing!();
} else {
@@ -73,6 +73,7 @@ class AIChatPage extends StatelessWidget {
/// [AIPromptInputBloc] is used to handle the user prompt
BlocProvider(
create: (_) => AIPromptInputBloc(
objectId: view.id,
predefinedFormat: PredefinedFormat(
imageFormat: ImageFormat.text,
textFormat: TextFormat.bulletList,
@@ -264,10 +265,13 @@ class _ChatContentPage extends StatelessWidget {
_onSelectMetadata(context, metadata),
onRegenerate: () => context
.read<ChatBloc>()
.add(ChatEvent.regenerateAnswer(message.id, null)),
.add(ChatEvent.regenerateAnswer(message.id, null, null)),
onChangeFormat: (format) => context
.read<ChatBloc>()
.add(ChatEvent.regenerateAnswer(message.id, format)),
.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(),
),
@@ -384,13 +388,26 @@ class _ChatContentPage extends StatelessWidget {
}
}
class _Input extends StatelessWidget {
class _Input extends StatefulWidget {
const _Input({
required this.view,
});
final ViewPB view;
@override
State<_Input> createState() => _InputState();
}
class _InputState extends State<_Input> {
final textController = TextEditingController();
@override
void dispose() {
textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
@@ -420,6 +437,7 @@ class _Input extends StatelessWidget {
return UniversalPlatform.isDesktop
? DesktopPromptInput(
isStreaming: !canSendMessage,
textController: textController,
onStopStreaming: () {
chatBloc.add(const ChatEvent.stopStream());
},
@@ -41,7 +41,7 @@ class _MobileChatInputState extends State<MobileChatInput> {
void initState() {
super.initState();
textController.addListener(handleTextControllerChange);
textController.addListener(handleTextControllerChanged);
// focusNode.onKeyEvent = handleKeyEvent;
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -197,7 +197,7 @@ class _MobileChatInputState extends State<MobileChatInput> {
);
}
void handleTextControllerChange() {
void handleTextControllerChanged() {
if (textController.value.isComposingRangeValid) {
return;
}
@@ -0,0 +1,145 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/base/app_bar/app_bar_actions.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/widgets.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
Future<AIModelPB?> showChangeModelBottomSheet(
BuildContext context,
List<AIModelPB> models,
) {
return showMobileBottomSheet<AIModelPB?>(
context,
showDragHandle: true,
builder: (context) => _ChangeModelBottomSheetContent(models: models),
);
}
class _ChangeModelBottomSheetContent extends StatefulWidget {
const _ChangeModelBottomSheetContent({
required this.models,
});
final List<AIModelPB> models;
@override
State<_ChangeModelBottomSheetContent> createState() =>
_ChangeModelBottomSheetContentState();
}
class _ChangeModelBottomSheetContentState
extends State<_ChangeModelBottomSheetContent> {
AIModelPB? model;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
_Header(
onCancel: () => Navigator.of(context).pop(),
onDone: () => Navigator.of(context).pop(model),
),
const VSpace(4.0),
_Body(
models: widget.models,
selectedModel: model,
onSelectModel: (format) {
setState(() => model = format);
},
),
const VSpace(16.0),
],
);
}
}
class _Header extends StatelessWidget {
const _Header({
required this.onCancel,
required this.onDone,
});
final VoidCallback onCancel;
final VoidCallback onDone;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 44.0,
child: Stack(
children: [
Align(
alignment: Alignment.centerLeft,
child: AppBarBackButton(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 16,
),
onTap: onCancel,
),
),
Align(
child: Container(
constraints: const BoxConstraints(maxWidth: 250),
child: FlowyText(
LocaleKeys.chat_switchModel_label.tr(),
fontSize: 17.0,
fontWeight: FontWeight.w500,
overflow: TextOverflow.ellipsis,
),
),
),
Align(
alignment: Alignment.centerRight,
child: AppBarDoneButton(
onTap: onDone,
),
),
],
),
);
}
}
class _Body extends StatelessWidget {
const _Body({
required this.models,
required this.selectedModel,
required this.onSelectModel,
});
final List<AIModelPB> models;
final AIModelPB? selectedModel;
final void Function(AIModelPB) onSelectModel;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: models
.mapIndexed(
(index, model) => _buildModelButton(model, index == 0),
)
.toList(),
);
}
Widget _buildModelButton(
AIModelPB model, [
bool isFirst = false,
]) {
return FlowyOptionTile.checkbox(
text: model.name,
isSelected: model == selectedModel,
showTopBorder: isFirst,
onTap: () {
onSelectModel(model);
},
);
}
}
@@ -21,6 +21,7 @@ import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/space/shared_widget.dart';
import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_result/appflowy_result.dart';
@@ -41,6 +42,7 @@ class AIMessageActionBar extends StatefulWidget {
required this.showDecoration,
this.onRegenerate,
this.onChangeFormat,
this.onChangeModel,
this.onOverrideVisibility,
});
@@ -48,6 +50,7 @@ class AIMessageActionBar extends StatefulWidget {
final bool showDecoration;
final void Function()? onRegenerate;
final void Function(PredefinedFormat)? onChangeFormat;
final void Function(AIModelPB)? onChangeModel;
final void Function(bool)? onOverrideVisibility;
@override
@@ -126,6 +129,12 @@ class _AIMessageActionBarState extends State<AIMessageActionBar> {
popoverMutex: popoverMutex,
onOverrideVisibility: widget.onOverrideVisibility,
),
ChangeModelButton(
isInHoverBar: widget.showDecoration,
onRegenerate: widget.onChangeModel,
popoverMutex: popoverMutex,
onOverrideVisibility: widget.onOverrideVisibility,
),
SaveToPageButton(
textMessage: widget.message as TextMessage,
isInHoverBar: widget.showDecoration,
@@ -405,6 +414,85 @@ class _ChangeFormatPopoverContentState
}
}
class ChangeModelButton extends StatefulWidget {
const ChangeModelButton({
super.key,
required this.isInHoverBar,
this.popoverMutex,
this.onRegenerate,
this.onOverrideVisibility,
});
final bool isInHoverBar;
final PopoverMutex? popoverMutex;
final void Function(AIModelPB)? onRegenerate;
final void Function(bool)? onOverrideVisibility;
@override
State<ChangeModelButton> createState() => _ChangeModelButtonState();
}
class _ChangeModelButtonState extends State<ChangeModelButton> {
final popoverController = PopoverController();
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
controller: popoverController,
mutex: widget.popoverMutex,
triggerActions: PopoverTriggerFlags.none,
margin: EdgeInsets.zero,
offset: Offset(8, 0),
direction: PopoverDirection.rightWithBottomAligned,
constraints: BoxConstraints(maxWidth: 250, maxHeight: 600),
onClose: () => widget.onOverrideVisibility?.call(false),
child: buildButton(context),
popupBuilder: (_) {
final bloc = context.read<AIPromptInputBloc>();
final (models, _) = bloc.aiModelStateNotifier.getAvailableModels();
return SelectModelPopoverContent(
models: models,
selectedModel: null,
onSelectModel: widget.onRegenerate,
);
},
);
}
Widget buildButton(BuildContext context) {
return FlowyTooltip(
message: LocaleKeys.chat_switchModel_label.tr(),
child: FlowyIconButton(
width: 32.0,
height: DesktopAIChatSizes.messageActionBarIconSize,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
radius: widget.isInHoverBar
? DesktopAIChatSizes.messageHoverActionBarIconRadius
: DesktopAIChatSizes.messageActionBarIconRadius,
icon: Row(
mainAxisSize: MainAxisSize.min,
children: [
FlowySvg(
FlowySvgs.ai_sparks_s,
color: Theme.of(context).hintColor,
size: const Size.square(16),
),
FlowySvg(
FlowySvgs.ai_source_drop_down_s,
color: Theme.of(context).hintColor,
size: const Size.square(8),
),
],
),
onPressed: () {
widget.onOverrideVisibility?.call(true);
popoverController.show();
},
),
);
}
}
class SaveToPageButton extends StatefulWidget {
const SaveToPageButton({
super.key,
@@ -12,6 +12,7 @@ import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@@ -23,6 +24,7 @@ import 'package:universal_platform/universal_platform.dart';
import '../chat_avatar.dart';
import '../layout_define.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';
@@ -41,6 +43,7 @@ class ChatAIMessageBubble extends StatelessWidget {
this.isSelectingMessages = false,
this.onRegenerate,
this.onChangeFormat,
this.onChangeModel,
});
final Message message;
@@ -50,6 +53,7 @@ class ChatAIMessageBubble extends StatelessWidget {
final bool isSelectingMessages;
final void Function()? onRegenerate;
final void Function(PredefinedFormat)? onChangeFormat;
final void Function(AIModelPB)? onChangeModel;
@override
Widget build(BuildContext context) {
@@ -73,6 +77,7 @@ class ChatAIMessageBubble extends StatelessWidget {
message: message,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
child: child,
);
}
@@ -82,6 +87,7 @@ class ChatAIMessageBubble extends StatelessWidget {
message: message,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
child: child,
);
}
@@ -91,6 +97,7 @@ class ChatAIMessageBubble extends StatelessWidget {
message: message,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
child: child,
);
}
@@ -103,12 +110,14 @@ class ChatAIBottomInlineActions extends StatelessWidget {
required this.message,
this.onRegenerate,
this.onChangeFormat,
this.onChangeModel,
});
final Widget child;
final Message message;
final void Function()? onRegenerate;
final void Function(PredefinedFormat)? onChangeFormat;
final void Function(AIModelPB)? onChangeModel;
@override
Widget build(BuildContext context) {
@@ -127,6 +136,7 @@ class ChatAIBottomInlineActions extends StatelessWidget {
showDecoration: false,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
),
),
const VSpace(32.0),
@@ -142,12 +152,14 @@ class ChatAIMessageHover extends StatefulWidget {
required this.message,
this.onRegenerate,
this.onChangeFormat,
this.onChangeModel,
});
final Widget child;
final Message message;
final void Function()? onRegenerate;
final void Function(PredefinedFormat)? onChangeFormat;
final void Function(AIModelPB)? onChangeModel;
@override
State<ChatAIMessageHover> createState() => _ChatAIMessageHoverState();
@@ -229,6 +241,7 @@ class _ChatAIMessageHoverState extends State<ChatAIMessageHover> {
showDecoration: true,
onRegenerate: widget.onRegenerate,
onChangeFormat: widget.onChangeFormat,
onChangeModel: widget.onChangeModel,
onOverrideVisibility: (visibility) {
overrideVisibility = visibility;
},
@@ -302,12 +315,14 @@ class ChatAIMessagePopup extends StatelessWidget {
required this.message,
this.onRegenerate,
this.onChangeFormat,
this.onChangeModel,
});
final Widget child;
final Message message;
final void Function()? onRegenerate;
final void Function(PredefinedFormat)? onChangeFormat;
final void Function(AIModelPB)? onChangeModel;
@override
Widget build(BuildContext context) {
@@ -328,6 +343,8 @@ class ChatAIMessagePopup extends StatelessWidget {
_divider(),
_changeFormatButton(context),
_divider(),
_changeModelButton(context),
_divider(),
_saveToPageButton(context),
],
);
@@ -399,6 +416,25 @@ class ChatAIMessagePopup extends StatelessWidget {
);
}
Widget _changeModelButton(BuildContext context) {
return MobileQuickActionButton(
onTap: () async {
final bloc = context.read<AIPromptInputBloc>();
final (models, _) = bloc.aiModelStateNotifier.getAvailableModels();
final result = await showChangeModelBottomSheet(context, models);
if (result != null) {
onChangeModel?.call(result);
if (context.mounted) {
Navigator.of(context).pop();
}
}
},
icon: FlowySvgs.ai_sparks_s,
iconSize: const Size.square(20),
text: LocaleKeys.chat_switchModel_label.tr(),
);
}
Widget _saveToPageButton(BuildContext context) {
return MobileQuickActionButton(
onTap: () async {
@@ -4,6 +4,7 @@ import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@@ -36,6 +37,7 @@ class ChatAIMessageWidget extends StatelessWidget {
this.onSelectedMetadata,
this.onRegenerate,
this.onChangeFormat,
this.onChangeModel,
this.isLastMessage = false,
this.isStreaming = false,
this.isSelectingMessages = false,
@@ -53,6 +55,7 @@ class ChatAIMessageWidget extends StatelessWidget {
final void Function()? onRegenerate;
final void Function() onStopStream;
final void Function(PredefinedFormat)? onChangeFormat;
final void Function(AIModelPB)? onChangeModel;
final bool isStreaming;
final bool isLastMessage;
final bool isSelectingMessages;
@@ -110,6 +113,7 @@ class ChatAIMessageWidget extends StatelessWidget {
isSelectingMessages: isSelectingMessages,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
onChangeModel: onChangeModel,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -47,15 +47,6 @@ class NumberCellBloc extends Bloc<NumberCellEvent, NumberCellState> {
if (state.content != text) {
emit(state.copyWith(content: text));
await cellController.saveCellData(text);
// If the input content is "abc" that can't parsered as number then the data stored in the backend will be an empty string.
// So for every cell data that will be formatted in the backend.
// It needs to get the formatted data after saving.
add(
NumberCellEvent.didReceiveCellUpdate(
cellController.getCellData(),
),
);
}
},
);
@@ -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),
),
);
@@ -22,6 +22,7 @@ import 'package:appflowy/workspace/presentation/home/af_focus_manager.dart';
import 'package:appflowy_editor/appflowy_editor.dart' hide QuoteBlockKeys;
import 'package:collection/collection.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -350,6 +351,8 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
final isViewDeleted = context.read<DocumentBloc>().state.isDeleted;
final isLocked =
context.read<ViewLockStatusBloc?>()?.state.isLocked ?? false;
final themeV2 = AFThemeExtensionV2.of(context);
final editor = Directionality(
textDirection: textDirection,
child: AppFlowyEditor(
@@ -393,7 +396,7 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
},
child: SizedBox(
width: double.infinity,
height: UniversalPlatform.isDesktopOrWeb ? 300 : 400,
height: UniversalPlatform.isDesktopOrWeb ? 600 : 400,
),
),
dropTargetStyle: AppFlowyDropTargetStyle(
@@ -428,7 +431,6 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
),
);
}
return Center(
child: FloatingToolbar(
floatingToolbarHeight: 40,
@@ -436,15 +438,24 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
style: FloatingToolbarStyle(
backgroundColor: Theme.of(context).cardColor,
toolbarActiveColor: Color(0xffe0f8fd),
toolbarElevation: 10,
),
items: toolbarItems,
decoration: ShapeDecoration(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Theme.of(context).cardColor,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
boxShadow: [
BoxShadow(
offset: Offset(0, 4),
blurRadius: 24,
color: themeV2.shadow_medium,
),
],
),
toolbarBuilder: (context, child) => DesktopFloatingToolbar(
toolbarBuilder: (context, child, onDismiss, isMetricsChanged) =>
DesktopFloatingToolbar(
editorState: editorState,
onDismiss: onDismiss,
enableAnimation: !isMetricsChanged,
child: child,
),
placeHolderBuilder: (_) => customPlaceholderItem,
@@ -469,7 +469,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
blockComponentDelta: newDelta.toJson(),
},
children: [
...node.children,
...node.children.map((e) => e.deepCopy()),
...insertedNodes.map((e) => e.deepCopy()),
],
);
@@ -2,8 +2,7 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/home/menu/menu_shared_state.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/text_suggestions_toolbar_item.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
hide QuoteBlockKeys, quoteNode;
@@ -149,214 +148,134 @@ class TurnIntoOptionMenu extends StatelessWidget {
@override
Widget build(BuildContext context) {
if (hasNonSupportedTypes) {
return buildItem(
pateItem,
textSuggestionItem,
context.read<BlockActionOptionCubit>().editorState,
);
}
return _buildTurnIntoOptions(context, node);
}
Widget _buildTurnIntoOptions(BuildContext context, Node node) {
final editorState = context.read<BlockActionOptionCubit>().editorState;
SuggestionItem currentSuggestionItem = textSuggestionItem;
final List<SuggestionItem> suggestionItems = suggestions.sublist(0, 4);
final List<SuggestionItem> turnIntoItems =
suggestions.sublist(4, suggestions.length);
final textColor = Color(0xff99A1A8);
void refreshSuggestions() {
final selection = editorState.selection;
if (selection == null || !selection.isSingle) return;
final node = editorState.getNodeAtPath(selection.start.path);
if (node == null || node.delta == null) return;
final nodeType = node.type;
SuggestionType? suggestionType;
if (nodeType == HeadingBlockKeys.type) {
final level = node.attributes[HeadingBlockKeys.level] ?? 1;
if (level == 1) {
suggestionType = SuggestionType.h1;
} else if (level == 2) {
suggestionType = SuggestionType.h2;
} else if (level == 3) {
suggestionType = SuggestionType.h3;
}
} else if (nodeType == ToggleListBlockKeys.type) {
final level = node.attributes[ToggleListBlockKeys.level];
if (level == null) {
suggestionType = SuggestionType.toggle;
} else if (level == 1) {
suggestionType = SuggestionType.toggleH1;
} else if (level == 2) {
suggestionType = SuggestionType.toggleH2;
} else if (level == 3) {
suggestionType = SuggestionType.toggleH3;
}
} else {
suggestionType = nodeType2SuggestionType[nodeType];
}
if (suggestionType == null) return;
suggestionItems.clear();
turnIntoItems.clear();
for (final item in suggestions) {
if (item.type.group == suggestionType.group &&
item.type != suggestionType) {
suggestionItems.add(item);
} else {
turnIntoItems.add(item);
}
}
currentSuggestionItem =
suggestions.where((item) => item.type == suggestionType).first;
}
refreshSuggestions();
return Column(
mainAxisSize: MainAxisSize.min,
children: _buildTurnIntoOptions(context, node),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
buildSubTitle(
LocaleKeys.document_toolbar_suggestions.tr(),
textColor,
),
...List.generate(suggestionItems.length, (index) {
return buildItem(
suggestionItems[index],
currentSuggestionItem,
editorState,
);
}),
buildSubTitle(LocaleKeys.document_toolbar_turnInto.tr(), textColor),
...List.generate(turnIntoItems.length, (index) {
return buildItem(
turnIntoItems[index],
currentSuggestionItem,
editorState,
);
}),
],
);
}
List<Widget> _buildTurnIntoOptions(BuildContext context, Node node) {
final children = <Widget>[];
if (hasNonSupportedTypes) {
return children
..add(
_TurnInfoButton(
type: SubPageBlockKeys.type,
node: node,
),
);
}
for (final type in EditorOptionActionType.turnInto.supportTypes) {
if (type == ToggleListBlockKeys.type) {
// toggle list block and toggle heading block are the same type,
// but they have different attributes.
// toggle list block
children.add(
_TurnInfoButton(
type: type,
node: node,
),
);
// toggle heading block
for (final i in [1, 2, 3]) {
children.add(
_TurnInfoButton(
type: type,
node: node,
level: i,
),
);
}
} else if (type != HeadingBlockKeys.type) {
children.add(
_TurnInfoButton(
type: type,
node: node,
),
);
} else {
for (final i in [1, 2, 3]) {
children.add(
_TurnInfoButton(
type: type,
node: node,
level: i,
),
);
}
}
}
return children;
}
}
class _TurnInfoButton extends StatelessWidget {
const _TurnInfoButton({
required this.type,
required this.node,
this.level,
});
final String type;
final Node node;
final int? level;
@override
Widget build(BuildContext context) {
final name = _buildLocalization(type, level: level);
final leftIcon = _buildLeftIcon(type, level: level);
final rightIcon = _buildRightIcon(type, node, level: level);
return HoverButton(
name: name,
leftIcon: FlowySvg(leftIcon),
rightIcon: rightIcon,
itemHeight: ActionListSizes.itemHeight,
onTap: () => BlockActionOptionCubit.turnIntoBlock(
type,
node,
context.read<BlockActionOptionCubit>().editorState,
level: level,
currentViewId: getIt<MenuSharedState>().latestOpenView?.id,
Widget buildSubTitle(String text, Color color) {
return Container(
height: 32,
margin: EdgeInsets.symmetric(horizontal: 8),
child: Align(
alignment: Alignment.centerLeft,
child: FlowyText.semibold(
text,
color: color,
figmaLineHeight: 16,
),
),
);
}
Widget? _buildRightIcon(String type, Node node, {int? level}) {
if (type != node.type) {
return null;
}
if (node.type == HeadingBlockKeys.type) {
final nodeLevel = node.attributes[HeadingBlockKeys.level] ?? 1;
if (level != nodeLevel) {
return null;
}
}
if (node.type == ToggleListBlockKeys.type) {
final nodeLevel = node.attributes[ToggleListBlockKeys.level];
if (level != nodeLevel) {
return null;
}
}
return const FlowySvg(
FlowySvgs.workspace_selected_s,
blendMode: null,
Widget buildItem(
SuggestionItem item,
SuggestionItem currentSuggestionItem,
EditorState state,
) {
final isSelected = item.type == currentSuggestionItem.type;
return SizedBox(
height: 36,
child: FlowyButton(
leftIconSize: const Size.square(20),
leftIcon: FlowySvg(item.svg),
iconPadding: 12,
text: FlowyText(
item.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
rightIcon: isSelected ? FlowySvg(FlowySvgs.toolbar_check_m) : null,
onTap: () => item.onTap.call(state, false),
),
);
}
FlowySvgData _buildLeftIcon(String type, {int? level}) {
if (type == ParagraphBlockKeys.type) {
return FlowySvgs.type_text_m;
} else if (type == HeadingBlockKeys.type) {
switch (level) {
case 1:
return FlowySvgs.type_h1_m;
case 2:
return FlowySvgs.type_h2_m;
case 3:
return FlowySvgs.type_h3_m;
default:
return FlowySvgs.type_text_m;
}
} else if (type == QuoteBlockKeys.type) {
return FlowySvgs.type_quote_m;
} else if (type == BulletedListBlockKeys.type) {
return FlowySvgs.type_bulleted_list_m;
} else if (type == NumberedListBlockKeys.type) {
return FlowySvgs.type_numbered_list_m;
} else if (type == TodoListBlockKeys.type) {
return FlowySvgs.type_todo_m;
} else if (type == CalloutBlockKeys.type) {
return FlowySvgs.type_callout_m;
} else if (type == SubPageBlockKeys.type) {
return FlowySvgs.icon_document_s;
} else if (type == ToggleListBlockKeys.type) {
switch (level) {
case 1:
return FlowySvgs.type_toggle_h1_m;
case 2:
return FlowySvgs.type_toggle_h2_m;
case 3:
return FlowySvgs.type_toggle_h3_m;
default:
return FlowySvgs.type_toggle_list_m;
}
}
throw UnimplementedError('Unsupported block type: $type');
}
String _buildLocalization(
String type, {
int? level,
}) {
switch (type) {
case ParagraphBlockKeys.type:
return LocaleKeys.document_slashMenu_name_text.tr();
case HeadingBlockKeys.type:
switch (level) {
case 1:
return LocaleKeys.document_slashMenu_name_heading1.tr();
case 2:
return LocaleKeys.document_slashMenu_name_heading2.tr();
case 3:
return LocaleKeys.document_slashMenu_name_heading3.tr();
default:
return LocaleKeys.document_slashMenu_name_text.tr();
}
case QuoteBlockKeys.type:
return LocaleKeys.document_slashMenu_name_quote.tr();
case BulletedListBlockKeys.type:
return LocaleKeys.editor_bulletedListShortForm.tr();
case NumberedListBlockKeys.type:
return LocaleKeys.editor_numberedListShortForm.tr();
case TodoListBlockKeys.type:
return LocaleKeys.editor_checkbox.tr();
case CalloutBlockKeys.type:
return LocaleKeys.document_slashMenu_name_callout.tr();
case SubPageBlockKeys.type:
return LocaleKeys.editor_page.tr();
case ToggleListBlockKeys.type:
switch (level) {
case 1:
return LocaleKeys.editor_toggleHeading1ShortForm.tr();
case 2:
return LocaleKeys.editor_toggleHeading2ShortForm.tr();
case 3:
return LocaleKeys.editor_toggleHeading3ShortForm.tr();
default:
return LocaleKeys.editor_toggleListShortForm.tr();
}
}
throw UnimplementedError('Unsupported block type: $type');
}
}
@@ -2,14 +2,11 @@ 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/plugins/document/application/document_bloc.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';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -18,8 +15,8 @@ import 'package:universal_platform/universal_platform.dart';
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';
import 'widgets/ai_writer_suggestion_actions.dart';
import 'widgets/ai_writer_prompt_input_more_button.dart';
class AiWriterBlockKeys {
const AiWriterBlockKeys._();
@@ -98,18 +95,12 @@ class AiWriterBlockComponent extends BlockComponentStatefulWidget {
}
class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
final key = GlobalKey();
final textController = TextEditingController();
final overlayController = OverlayPortalController();
final layerLink = LayerLink();
final focusNode = FocusNode();
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() {
@@ -117,16 +108,14 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
WidgetsBinding.instance.addPostFrameCallback((_) {
overlayController.show();
if (!widget.node.isAiWriterInitialized) {
aiWriterCubit.init();
}
context.read<AiWriterCubit>().register(widget.node);
});
}
@override
void dispose() {
textController.dispose();
aiWriterCubit.close();
focusNode.dispose();
super.dispose();
}
@@ -136,85 +125,49 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
return const SizedBox.shrink();
}
return MultiBlocProvider(
providers: [
BlocProvider.value(
value: aiWriterCubit,
),
BlocProvider(
create: (_) => AIPromptInputBloc(
predefinedFormat: null,
),
),
],
final documentId = context.read<DocumentBloc?>()?.documentId;
return BlocProvider(
create: (_) => AIPromptInputBloc(
predefinedFormat: null,
objectId: documentId ?? editorState.document.root.id,
),
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: Focus(
focusNode: focusNode,
child: OverlayContent(
editorState: editorState,
node: widget.node,
textController: textController,
),
),
],
);
},
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,80 +175,84 @@ 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 {
class OverlayContent extends StatefulWidget {
const OverlayContent({
super.key,
required this.editorState,
required this.node,
required this.textController,
});
final EditorState editorState;
final Node node;
final TextEditingController textController;
@override
State<OverlayContent> createState() => _OverlayContentState();
}
class _OverlayContentState extends State<OverlayContent> {
final showCommandsToggle = ValueNotifier(false);
@override
void dispose() {
showCommandsToggle.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<AiWriterCubit, AiWriterState>(
builder: (context, state) {
final selection = node.aiWriterSelection;
final showSuggestionPopup =
state is ReadyAiWriterState && !state.isFirstRun;
final showActionPopup = state is ReadyAiWriterState && state.isFirstRun;
if (state is IdleAiWriterState ||
state is DocumentContentEmptyAiWriterState) {
return const SizedBox.shrink();
}
final command = (state as RegisteredAiWriter).command;
final selection = widget.node.aiWriterSelection;
final hasSelection = selection != null && !selection.isCollapsed;
final markdownText = switch (state) {
final ReadyAiWriterState ready => ready.markdownText,
final GeneratingAiWriterState generating => generating.markdownText,
_ => '',
};
final hasSelection = selection != null && !selection.isCollapsed;
final isLightMode = Theme.of(context).isLightMode;
final darkBorderColor =
isLightMode ? Color(0x1F1F2329) : Color(0xFF505469);
final lightBorderColor =
Theme.of(context).brightness == Brightness.light
? ColorSchemeConstants.lightBorderColor
: ColorSchemeConstants.darkBorderColor;
final showSuggestedActions =
state is ReadyAiWriterState && !state.isFirstRun;
final isInitialReadyState =
state is ReadyAiWriterState && state.isFirstRun;
final showSuggestedActionsPopup =
showSuggestedActions && markdownText.isEmpty ||
(markdownText.isNotEmpty && command != AiWriterCommand.explain);
final showSuggestedActionsWithin = showSuggestedActions &&
markdownText.isNotEmpty &&
command == AiWriterCommand.explain;
final borderColor = Theme.of(context).isLightMode
? Color(0x1F1F2329)
: Color(0xFF505469);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (showSuggestionPopup &&
state.command != AiWriterCommand.explain) ...[
if (showSuggestedActionsPopup) ...[
Container(
padding: EdgeInsets.all(4.0),
decoration: _getModalDecoration(
context,
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderColor: darkBorderColor,
borderColor: borderColor,
),
child: SuggestionActionBar(
actions: _getSuggestedActions(
currentCommand: state.command,
hasSelection: hasSelection,
),
currentCommand: command,
hasSelection: hasSelection,
onTap: (action) {
_onSelectSuggestionAction(context, action);
},
@@ -303,93 +260,74 @@ class OverlayContent extends StatelessWidget {
),
const VSpace(4.0 + 1.0),
],
DecoratedBox(
Container(
decoration: _getModalDecoration(
context,
color: null,
borderColor: darkBorderColor,
borderColor: borderColor,
borderRadius: BorderRadius.all(Radius.circular(12.0)),
),
constraints: BoxConstraints(maxHeight: 400),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (markdownText.isNotEmpty) ...[
DecoratedBox(
decoration: _getHelperChildDecoration(context),
child: Container(
constraints: BoxConstraints(maxHeight: 140),
width: double.infinity,
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: SingleChildScrollView(
physics: ClampingScrollPhysics(),
padding: EdgeInsets.only(top: 8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
height: 24.0,
padding:
EdgeInsets.symmetric(horizontal: 6.0),
alignment:
AlignmentDirectional.centerStart,
child: FlowyText(
state.command.i18n,
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF666D76),
),
),
const VSpace(4.0),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 6.0),
child: AIMarkdownText(
markdown: markdownText,
),
),
],
),
),
),
if (showSuggestionPopup) ...[
const VSpace(4.0),
SuggestionActionBar(
actions: _getSuggestedActions(
currentCommand: state.command,
hasSelection: hasSelection,
),
onTap: (action) {
_onSelectSuggestionAction(context, action);
},
),
],
const VSpace(8.0),
],
Flexible(
child: DecoratedBox(
decoration: _secondaryContentDecoration(context),
child: SecondaryContentArea(
markdownText: markdownText,
onSelectSuggestionAction: (action) {
_onSelectSuggestionAction(context, action);
},
command: command,
showSuggestionActions: showSuggestedActionsWithin,
hasSelection: hasSelection,
),
),
),
Divider(
height: 1.0,
),
Divider(height: 1.0),
],
DecoratedBox(
decoration: markdownText.isNotEmpty
? _getInputChildDecoration(context)
? _mainContentDecoration(context)
: _getSingleChildDeocoration(context),
child: MainContentArea(),
child: MainContentArea(
textController: widget.textController,
isDocumentEmpty: _isDocumentEmpty(),
isInitialReadyState: isInitialReadyState,
showCommandsToggle: showCommandsToggle,
),
),
],
),
),
..._bottomActions(
context,
showActionPopup,
hasSelection,
lightBorderColor,
ValueListenableBuilder(
valueListenable: showCommandsToggle,
builder: (context, value, child) {
if (!value || !isInitialReadyState) {
return const SizedBox.shrink();
}
return Align(
alignment: AlignmentDirectional.centerEnd,
child: MoreAiWriterCommands(
hasSelection: hasSelection,
editorState: widget.editorState,
onSelectCommand: (command) {
final state = context.read<AIPromptInputBloc>().state;
final showPredefinedFormats = state.showPredefinedFormats;
final predefinedFormat = state.predefinedFormat;
final text = widget.textController.text;
context.read<AiWriterCubit>().runCommand(
command,
text,
showPredefinedFormats ? predefinedFormat : null,
);
},
),
);
},
),
],
);
@@ -397,39 +335,6 @@ class OverlayContent extends StatelessWidget {
);
}
Widget _bottomButton(AiWriterCommand command) {
return Builder(
builder: (context) {
return SizedBox(
height: 30.0,
child: FlowyButton(
leftIcon: FlowySvg(
command.icon,
size: const Size.square(16),
color: Theme.of(context).iconTheme.color,
),
margin: const EdgeInsets.all(6.0),
text: FlowyText(
command.i18n,
figmaLineHeight: 20,
),
onTap: () {
final aiInputBloc = context.read<AIPromptInputBloc>();
final showPredefinedFormats =
aiInputBloc.state.showPredefinedFormats;
final predefinedFormat = aiInputBloc.state.predefinedFormat;
context.read<AiWriterCubit>().runCommand(
command,
showPredefinedFormats ? predefinedFormat : null,
);
},
),
);
},
);
}
BoxDecoration _getModalDecoration(
BuildContext context, {
required Color? color,
@@ -443,13 +348,9 @@ class OverlayContent extends StatelessWidget {
strokeAlign: BorderSide.strokeAlignOutside,
),
borderRadius: borderRadius,
boxShadow: const [
BoxShadow(
offset: Offset(0, 4),
blurRadius: 20,
color: Color(0x1A1F2329),
),
],
boxShadow: Theme.of(context).isLightMode
? ShadowConstants.lightSmall
: ShadowConstants.darkSmall,
);
}
@@ -460,133 +361,20 @@ class OverlayContent extends StatelessWidget {
);
}
BoxDecoration _getHelperChildDecoration(BuildContext context) {
BoxDecoration _secondaryContentDecoration(BuildContext context) {
return BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.vertical(top: Radius.circular(12.0)),
);
}
BoxDecoration _getInputChildDecoration(BuildContext context) {
BoxDecoration _mainContentDecoration(BuildContext context) {
return BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.vertical(bottom: Radius.circular(12.0)),
);
}
List<Widget> _bottomActions(
BuildContext context,
bool showActionPopup,
bool hasSelection,
Color borderColor,
) {
if (!showActionPopup) {
return [];
}
if (editorState.isEmptyForContinueWriting()) {
final documentContext = editorState.document.root.context;
if (documentContext == null) {
return [];
}
final view = documentContext.read<ViewBloc>().state.view;
if (view.name.isEmpty) {
return [];
}
}
return [
// add one here to take into account the border of the main message box.
// It is configured to be on the outside to hide some graphical
// artifacts.
const VSpace(4.0 + 1.0),
Container(
padding: EdgeInsets.all(8.0),
constraints: BoxConstraints(minWidth: 240.0),
decoration: _getModalDecoration(
context,
color: Theme.of(context).colorScheme.surface,
borderColor: borderColor,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
child: IntrinsicWidth(
child: SeparatedColumn(
separatorBuilder: () => const VSpace(4.0),
crossAxisAlignment: CrossAxisAlignment.start,
children: _getCommands(
hasSelection: hasSelection,
),
),
),
),
];
}
List<Widget> _getCommands({required bool hasSelection}) {
if (hasSelection) {
return [
_bottomButton(AiWriterCommand.improveWriting),
_bottomButton(AiWriterCommand.fixSpellingAndGrammar),
_bottomButton(AiWriterCommand.explain),
const Divider(height: 1.0, thickness: 1.0),
_bottomButton(AiWriterCommand.makeLonger),
_bottomButton(AiWriterCommand.makeShorter),
];
} else {
return [
_bottomButton(AiWriterCommand.continueWriting),
];
}
}
List<SuggestionAction> _getSuggestedActions({
required AiWriterCommand currentCommand,
required bool hasSelection,
}) {
if (hasSelection) {
return switch (currentCommand) {
AiWriterCommand.userQuestion || AiWriterCommand.continueWriting => [
SuggestionAction.keep,
SuggestionAction.discard,
SuggestionAction.rewrite,
],
AiWriterCommand.explain => [
SuggestionAction.insertBelow,
SuggestionAction.tryAgain,
SuggestionAction.close,
],
AiWriterCommand.fixSpellingAndGrammar ||
AiWriterCommand.improveWriting ||
AiWriterCommand.makeShorter ||
AiWriterCommand.makeLonger =>
[
SuggestionAction.accept,
SuggestionAction.discard,
SuggestionAction.insertBelow,
SuggestionAction.rewrite,
],
};
} else {
return switch (currentCommand) {
AiWriterCommand.userQuestion || AiWriterCommand.continueWriting => [
SuggestionAction.keep,
SuggestionAction.discard,
SuggestionAction.rewrite,
],
AiWriterCommand.explain => [
SuggestionAction.insertBelow,
SuggestionAction.tryAgain,
SuggestionAction.close,
],
_ => [
SuggestionAction.keep,
SuggestionAction.discard,
SuggestionAction.rewrite,
],
};
}
}
void _onSelectSuggestionAction(
BuildContext context,
SuggestionAction action,
@@ -598,10 +386,99 @@ class OverlayContent extends StatelessWidget {
predefinedFormat,
);
}
bool _isDocumentEmpty() {
if (widget.editorState.isEmptyForContinueWriting()) {
final documentContext = widget.editorState.document.root.context;
if (documentContext == null) {
return true;
}
final view = documentContext.read<ViewBloc>().state.view;
if (view.name.isEmpty) {
return true;
}
}
return false;
}
}
class SecondaryContentArea extends StatelessWidget {
const SecondaryContentArea({
super.key,
required this.command,
required this.markdownText,
required this.showSuggestionActions,
required this.hasSelection,
required this.onSelectSuggestionAction,
});
final AiWriterCommand command;
final String markdownText;
final bool showSuggestionActions;
final bool hasSelection;
final void Function(SuggestionAction) onSelectSuggestionAction;
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const VSpace(8.0),
Container(
height: 24.0,
padding: EdgeInsets.symmetric(horizontal: 14.0),
alignment: AlignmentDirectional.centerStart,
child: FlowyText(
command.i18n,
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF666D76),
),
),
const VSpace(4.0),
Flexible(
child: SingleChildScrollView(
physics: ClampingScrollPhysics(),
padding: EdgeInsets.symmetric(horizontal: 14.0),
child: AIMarkdownText(
markdown: markdownText,
),
),
),
if (showSuggestionActions) ...[
const VSpace(4.0),
Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: SuggestionActionBar(
currentCommand: command,
hasSelection: hasSelection,
onTap: onSelectSuggestionAction,
),
),
],
const VSpace(8.0),
],
),
);
}
}
class MainContentArea extends StatelessWidget {
const MainContentArea({super.key});
const MainContentArea({
super.key,
required this.textController,
required this.isInitialReadyState,
required this.isDocumentEmpty,
required this.showCommandsToggle,
});
final TextEditingController textController;
final bool isInitialReadyState;
final bool isDocumentEmpty;
final ValueNotifier<bool> showCommandsToggle;
@override
Widget build(BuildContext context) {
@@ -613,7 +490,10 @@ class MainContentArea extends StatelessWidget {
return DesktopPromptInput(
isStreaming: false,
hideDecoration: true,
onSubmitted: (message, format, _) => cubit.submit(message, format),
textController: textController,
onSubmitted: (message, format, _) {
cubit.runCommand(state.command, message, format);
},
onStopStreaming: () => cubit.stopStream(),
selectedSourcesNotifier: cubit.selectedSourcesNotifier,
onUpdateSelectedSources: (sources) {
@@ -621,6 +501,18 @@ class MainContentArea extends StatelessWidget {
...sources,
];
},
extraBottomActionButton: isInitialReadyState
? ValueListenableBuilder(
valueListenable: showCommandsToggle,
builder: (context, value, _) {
return AiWriterPromptMoreButton(
isEnabled: !isDocumentEmpty,
isSelected: value,
onTap: () => showCommandsToggle.value = !value,
);
},
)
: null,
);
}
if (state is GeneratingAiWriterState) {
@@ -676,6 +568,26 @@ class MainContentArea extends StatelessWidget {
),
);
}
if (state is LocalAIStreamingAiWriterState) {
final text = switch (state.state) {
LocalAIStreamingState.notReady =>
LocaleKeys.settings_aiPage_keys_localAINotReadyRetryLater.tr(),
LocalAIStreamingState.disabled =>
LocaleKeys.settings_aiPage_keys_localAIDisabled.tr(),
};
return Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: [
const HSpace(8.0),
Opacity(
opacity: 0.5,
child: FlowyText(text),
),
],
),
);
}
return const SizedBox.shrink();
},
);
@@ -6,6 +6,7 @@ import 'package:appflowy/plugins/document/presentation/editor_style.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/theme_extension_v2.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -118,7 +119,7 @@ class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {
}
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final themeV2 = AFThemeExtensionV2.of(context);
final child = FlowyIconButton(
width: 48,
height: 32,
@@ -130,13 +131,13 @@ class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {
FlowySvg(
FlowySvgs.toolbar_ai_writer_m,
size: Size.square(20),
color: iconColor,
color: themeV2.icon_primary,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size(12, 20),
color: iconColor,
color: themeV2.icon_tertiary,
),
],
),
@@ -187,7 +188,7 @@ class ImproveWritingButton extends StatelessWidget {
icon: FlowySvg(
FlowySvgs.toolbar_ai_improve_writing_m,
size: Size.square(20.0),
color: Theme.of(context).iconTheme.color,
color: AFThemeExtensionV2.of(context).icon_primary,
),
onPressed: () {
if (_isAIEnabled(editorState)) {
@@ -1,10 +1,45 @@
import 'dart:async';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import '../ai_writer_block_component.dart';
import 'ai_writer_entities.dart';
import 'ai_writer_node_extension.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,
});
await editorState.apply(
transaction,
options: const ApplyOptions(
recordUndo: false,
inMemoryUpdate: true,
),
withUpdateSelection: false,
);
final selection = node.aiWriterSelection;
if (selection != null && !selection.isCollapsed) {
unawaited(
editorState.updateSelectionWithReason(
selection,
extraInfo: {selectionExtraInfoDisableToolbar: true},
),
);
}
}
Future<void> removeAiWriterNode(
EditorState editorState,
Node node,
) async {
final transaction = editorState.transaction..deleteNode(node);
await editorState.apply(
transaction,
@@ -13,16 +48,16 @@ Future<void> removeAiWriterNode(EditorState editorState, Node node) async {
);
}
void formatSelection(
Future<void> formatSelection(
EditorState editorState,
Selection selection,
Transaction transaction,
ApplySuggestionFormatType formatType,
) {
) async {
final nodes = editorState.getNodesInSelection(selection).toList();
if (nodes.isEmpty) {
return;
}
final transaction = editorState.transaction;
if (nodes.length == 1) {
final node = nodes.removeAt(0);
@@ -68,29 +103,43 @@ void formatSelection(
}
transaction.compose();
await editorState.apply(
transaction,
options: ApplyOptions(
inMemoryUpdate: true,
recordUndo: false,
),
withUpdateSelection: false,
);
}
Position ensurePreviousNodeIsEmptyParagraph(
Future<Position> ensurePreviousNodeIsEmptyParagraph(
EditorState editorState,
Node aiWriterNode,
Transaction transaction,
) {
) async {
final previous = aiWriterNode.previous;
final needsEmptyParagraphNode = previous == null ||
previous.type != ParagraphBlockKeys.type ||
(previous.delta?.toPlainText().isNotEmpty ?? false);
final Position position;
final transaction = editorState.transaction;
if (needsEmptyParagraphNode) {
position = Position(path: aiWriterNode.path);
transaction.insertNode(aiWriterNode.path, paragraphNode());
} else {
position = Position(path: previous.path);
}
transaction.afterSelection = Selection.collapsed(position);
transaction.updateNode(aiWriterNode, {
AiWriterBlockKeys.isInitialized: true,
});
await editorState.apply(
transaction,
options: ApplyOptions(
inMemoryUpdate: true,
recordUndo: false,
),
);
return position;
}
@@ -1,3 +1,4 @@
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_backend/protobuf/flowy-ai/protobuf.dart';
@@ -129,24 +130,22 @@ enum AiRole {
}
class AiWriterRecord extends Equatable {
const AiWriterRecord({
required this.role,
required this.content,
});
const AiWriterRecord.user({
required this.content,
required this.format,
}) : role = AiRole.user;
const AiWriterRecord.ai({
required this.content,
}) : role = AiRole.ai;
}) : role = AiRole.ai,
format = null;
final AiRole role;
final String content;
final PredefinedFormat? format;
@override
List<Object> get props => [role, content];
List<Object?> get props => [role, content, format];
CompletionRecordPB toPB() {
return CompletionRecordPB(
@@ -104,7 +104,7 @@ extension AiWriterNodeExtension on EditorState {
start: Position(path: [0]),
end: selection?.normalized.end ??
this.selection?.normalized.end ??
Position(path: [0]),
Position(path: getLastSelectable()?.$1.path ?? [0]),
);
// if the selected nodes are not entirely selected, slice the nodes
@@ -1,63 +0,0 @@
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'operations/ai_writer_entities.dart';
class SuggestionActionBar extends StatelessWidget {
const SuggestionActionBar({
super.key,
required this.actions,
required this.onTap,
});
final List<SuggestionAction> actions;
final void Function(SuggestionAction) onTap;
@override
Widget build(BuildContext context) {
return SeparatedRow(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const HSpace(4.0),
children: actions
.map(
(action) => SuggestionActionButton(
action: action,
onTap: () => onTap(action),
),
)
.toList(),
);
}
}
class SuggestionActionButton extends StatelessWidget {
const SuggestionActionButton({
super.key,
required this.action,
required this.onTap,
});
final SuggestionAction action;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 28,
child: FlowyButton(
text: FlowyText(
action.i18n,
figmaLineHeight: 20,
),
leftIcon: action.buildIcon(context),
iconPadding: 4.0,
margin: const EdgeInsets.symmetric(
horizontal: 6.0,
vertical: 4.0,
),
onTap: onTap,
useIntrinsicWidth: true,
),
);
}
}
@@ -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<
@@ -0,0 +1,151 @@
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/util/theme_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/colorscheme/default_colorscheme.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import '../operations/ai_writer_entities.dart';
class AiWriterPromptMoreButton extends StatelessWidget {
const AiWriterPromptMoreButton({
super.key,
required this.isEnabled,
required this.isSelected,
required this.onTap,
});
final bool isEnabled;
final bool isSelected;
final void Function() onTap;
@override
Widget build(BuildContext context) {
return IgnorePointer(
ignoring: !isEnabled,
child: GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: SizedBox(
height: DesktopAIPromptSizes.actionBarButtonSize,
child: FlowyHover(
style: const HoverStyle(
borderRadius: BorderRadius.all(Radius.circular(8)),
),
isSelected: () => isSelected,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(6, 6, 4, 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
FlowyText(
LocaleKeys.ai_more.tr(),
fontSize: 12,
figmaLineHeight: 16,
color: isEnabled
? Theme.of(context).hintColor
: Theme.of(context).disabledColor,
),
const HSpace(2.0),
FlowySvg(
FlowySvgs.ai_source_drop_down_s,
color: Theme.of(context).hintColor,
size: const Size.square(8),
),
],
),
),
),
),
),
);
}
}
class MoreAiWriterCommands extends StatelessWidget {
const MoreAiWriterCommands({
super.key,
required this.hasSelection,
required this.editorState,
required this.onSelectCommand,
});
final EditorState editorState;
final bool hasSelection;
final void Function(AiWriterCommand) onSelectCommand;
@override
Widget build(BuildContext context) {
return Container(
// add one here to take into account the border of the main message box.
// It is configured to be on the outside to hide some graphical
// artifacts.
margin: EdgeInsets.only(top: 4.0 + 1.0),
padding: EdgeInsets.all(8.0),
constraints: BoxConstraints(minWidth: 240.0),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
border: Border.all(
color: Theme.of(context).brightness == Brightness.light
? ColorSchemeConstants.lightBorderColor
: ColorSchemeConstants.darkBorderColor,
strokeAlign: BorderSide.strokeAlignOutside,
),
borderRadius: BorderRadius.all(Radius.circular(8.0)),
boxShadow: Theme.of(context).isLightMode
? ShadowConstants.lightSmall
: ShadowConstants.darkSmall,
),
child: IntrinsicWidth(
child: Column(
spacing: 4.0,
crossAxisAlignment: CrossAxisAlignment.start,
children: _getCommands(
hasSelection: hasSelection,
),
),
),
);
}
List<Widget> _getCommands({required bool hasSelection}) {
if (hasSelection) {
return [
_bottomButton(AiWriterCommand.improveWriting),
_bottomButton(AiWriterCommand.fixSpellingAndGrammar),
_bottomButton(AiWriterCommand.explain),
const Divider(height: 1.0, thickness: 1.0),
_bottomButton(AiWriterCommand.makeLonger),
_bottomButton(AiWriterCommand.makeShorter),
];
} else {
return [
_bottomButton(AiWriterCommand.continueWriting),
];
}
}
Widget _bottomButton(AiWriterCommand command) {
return Builder(
builder: (context) {
return FlowyButton(
leftIcon: FlowySvg(
command.icon,
color: Theme.of(context).iconTheme.color,
),
leftIconSize: const Size.square(20),
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0),
text: FlowyText(
command.i18n,
figmaLineHeight: 20,
),
onTap: () => onSelectCommand(command),
);
},
);
}
}
@@ -0,0 +1,226 @@
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();
},
onRemoveNode: () {
aiWriterRegistered = false;
widget.editorState.service.keyboardService?.enableShortcuts();
},
onAppendToDocument: onAppendToDocument,
);
bool userHasScrolled = false;
bool aiWriterRegistered = false;
bool dialogShown = 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: Focus(
autofocus: true,
onKeyEvent: handleKeyEvent,
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: stopAndExit,
onCancel: () {},
);
} else {
stopAndExit();
}
}
KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
if (!aiWriterRegistered) {
return KeyEventResult.ignored;
}
if (dialogShown) {
return KeyEventResult.handled;
}
if (event is! KeyDownEvent) {
return KeyEventResult.ignored;
}
switch (event.logicalKey) {
case LogicalKeyboardKey.escape:
if (aiWriterCubit.state case GeneratingAiWriterState _) {
aiWriterCubit.stopStream();
} else if (aiWriterCubit.hasUnusedResponse()) {
dialogShown = true;
showConfirmDialog(
context: context,
title: LocaleKeys.button_discard.tr(),
description: LocaleKeys.document_plugins_discardResponse.tr(),
confirmLabel: LocaleKeys.button_discard.tr(),
style: ConfirmPopupStyle.cancelAndOk,
onConfirm: stopAndExit,
onCancel: () {},
).then((_) => dialogShown = false);
} else {
stopAndExit();
}
return KeyEventResult.handled;
case LogicalKeyboardKey.keyC
when HardwareKeyboard.instance.isControlPressed:
if (aiWriterCubit.state case GeneratingAiWriterState _) {
aiWriterCubit.stopStream();
}
return KeyEventResult.handled;
default:
break;
}
return KeyEventResult.ignored;
}
void onAppendToDocument() {
if (!aiWriterRegistered || userHasScrolled) {
return;
}
throttler.call(() {
if (aiWriterCubit.aiWriterNode != null) {
final path = aiWriterCubit.aiWriterNode!.path;
if (path.isNotEmpty) {
widget.editorState.updateSelectionWithReason(
Selection.collapsed(Position(path: path)),
);
}
}
});
}
void stopAndExit() {
Future(() async {
await aiWriterCubit.stopStream();
await aiWriterCubit.exit();
});
}
}
@@ -0,0 +1,110 @@
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import '../operations/ai_writer_entities.dart';
class SuggestionActionBar extends StatelessWidget {
const SuggestionActionBar({
super.key,
required this.currentCommand,
required this.hasSelection,
required this.onTap,
});
final AiWriterCommand currentCommand;
final bool hasSelection;
final void Function(SuggestionAction) onTap;
@override
Widget build(BuildContext context) {
return SeparatedRow(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const HSpace(4.0),
children: _getSuggestedActions()
.map(
(action) => SuggestionActionButton(
action: action,
onTap: () => onTap(action),
),
)
.toList(),
);
}
List<SuggestionAction> _getSuggestedActions() {
if (hasSelection) {
return switch (currentCommand) {
AiWriterCommand.userQuestion || AiWriterCommand.continueWriting => [
SuggestionAction.keep,
SuggestionAction.discard,
SuggestionAction.rewrite,
],
AiWriterCommand.explain => [
SuggestionAction.insertBelow,
SuggestionAction.tryAgain,
SuggestionAction.close,
],
AiWriterCommand.fixSpellingAndGrammar ||
AiWriterCommand.improveWriting ||
AiWriterCommand.makeShorter ||
AiWriterCommand.makeLonger =>
[
SuggestionAction.accept,
SuggestionAction.discard,
SuggestionAction.insertBelow,
SuggestionAction.rewrite,
],
};
} else {
return switch (currentCommand) {
AiWriterCommand.userQuestion || AiWriterCommand.continueWriting => [
SuggestionAction.keep,
SuggestionAction.discard,
SuggestionAction.rewrite,
],
AiWriterCommand.explain => [
SuggestionAction.insertBelow,
SuggestionAction.tryAgain,
SuggestionAction.close,
],
_ => [
SuggestionAction.keep,
SuggestionAction.discard,
SuggestionAction.rewrite,
],
};
}
}
}
class SuggestionActionButton extends StatelessWidget {
const SuggestionActionButton({
super.key,
required this.action,
required this.onTap,
});
final SuggestionAction action;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 28,
child: FlowyButton(
text: FlowyText(
action.i18n,
figmaLineHeight: 20,
),
leftIcon: action.buildIcon(context),
iconPadding: 4.0,
margin: const EdgeInsets.symmetric(
horizontal: 6.0,
vertical: 4.0,
),
onTap: onTap,
useIntrinsicWidth: true,
),
);
}
}
@@ -1,8 +1,10 @@
import 'dart:convert';
import 'package:appflowy/plugins/document/presentation/editor_plugins/numbered_list/numbered_list_icon.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:collection/collection.dart';
import 'package:synchronized/synchronized.dart';
const _enableDebug = false;
@@ -28,6 +30,9 @@ class MarkdownTextRobot {
/// Only for debug via [_enableDebug].
final List<String> _debugMarkdownTexts = [];
/// Selection before the refresh.
Selection? _previousSelection;
bool get hasAnyResult => _markdownText.isNotEmpty;
String get markdownText => _markdownText;
@@ -56,9 +61,11 @@ class MarkdownTextRobot {
}
void start({
Selection? previousSelection,
Position? position,
}) {
_insertPosition ??= position ?? editorState.selection?.start;
_insertPosition = position ?? editorState.selection?.start;
_previousSelection = previousSelection ?? editorState.selection;
if (_enableDebug) {
Log.info(
@@ -70,6 +77,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 +85,7 @@ class MarkdownTextRobot {
await _lock.synchronized(() async {
await _refresh(
inMemoryUpdate: true,
updateSelection: updateSelection,
attributes: attributes,
);
});
@@ -95,7 +104,6 @@ class MarkdownTextRobot {
await _lock.synchronized(() async {
await _refresh(
inMemoryUpdate: true,
updateSelection: false,
attributes: attributes,
);
});
@@ -139,7 +147,7 @@ class MarkdownTextRobot {
await editorState.apply(
transaction,
options: const ApplyOptions(recordUndo: false),
options: const ApplyOptions(recordUndo: false, inMemoryUpdate: true),
);
if (_enableDebug) {
@@ -147,15 +155,18 @@ class MarkdownTextRobot {
}
}
void reset() {
void clear() {
_markdownText = '';
_insertedNodes = [];
}
void reset() {
_insertPosition = null;
}
Future<void> _refresh({
required bool inMemoryUpdate,
bool updateSelection = true,
bool updateSelection = false,
Map<String, dynamic>? attributes,
}) async {
final position = _insertPosition;
@@ -171,11 +182,40 @@ class MarkdownTextRobot {
tableWidth: 250.0,
).root.children;
// check if the first selected node before the refresh is a numbered list node
final previousSelection = _previousSelection;
final previousSelectedNode = previousSelection == null
? null
: editorState.getNodeAtPath(previousSelection.start.path);
final firstNodeIsNumberedList = previousSelectedNode != null &&
previousSelectedNode.type == NumberedListBlockKeys.type;
final newNodes = attributes == null
? documentNodes
: documentNodes
.map((node) => _styleDelta(node: node, attributes: attributes))
.toList();
: documentNodes.mapIndexed((index, node) {
final n = _styleDelta(node: node, attributes: attributes);
n.externalValues = AINodeExternalValues(
isAINode: true,
);
if (index == 0 && n.type == NumberedListBlockKeys.type) {
if (firstNodeIsNumberedList) {
final builder = NumberedListIndexBuilder(
editorState: editorState,
node: previousSelectedNode,
);
final firstIndex = builder.indexInSameLevel;
n.updateAttributes({
NumberedListBlockKeys.number: firstIndex,
});
}
n.externalValues = AINodeExternalValues(
isAINode: true,
isFirstNumberedListNode: true,
);
}
return n;
}).toList();
if (newNodes.isEmpty) {
return;
@@ -203,10 +243,6 @@ class MarkdownTextRobot {
offset: lastDelta.length,
),
);
if (!updateSelection) {
insertTransaction.afterSelection = null;
}
}
await editorState.apply(
@@ -215,6 +251,7 @@ class MarkdownTextRobot {
inMemoryUpdate: inMemoryUpdate,
recordUndo: !inMemoryUpdate,
),
withUpdateSelection: updateSelection,
);
_insertedNodes = newNodes;
@@ -246,3 +283,13 @@ class MarkdownTextRobot {
);
}
}
class AINodeExternalValues extends NodeExternalValues {
const AINodeExternalValues({
this.isAINode = false,
this.isFirstNumberedListNode = false,
});
final bool isAINode;
final bool isFirstNumberedListNode;
}
@@ -1,3 +1,5 @@
import 'dart:ui';
import 'package:appflowy/plugins/document/presentation/editor_plugins/callout/callout_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toggle/toggle_block_component.dart';
@@ -35,9 +37,7 @@ bool onlyShowInSingleTextTypeSelectionAndExcludeTable(
notShowInTable(editorState);
}
bool enableSuggestions(
EditorState editorState,
) {
bool enableSuggestions(EditorState editorState) {
final selection = editorState.selection;
if (selection == null || !selection.isSingle) {
return false;
@@ -46,10 +46,18 @@ bool enableSuggestions(
if (node == null) {
return false;
}
if (isNarrowWindow(editorState)) return false;
return (node.delta != null && suggestionsItemTypes.contains(node.type)) &&
notShowInTable(editorState);
}
bool isNarrowWindow(EditorState editorState) {
final editorSize = editorState.renderBox?.size ?? Size.zero;
if (editorSize.width < 650) return true;
return false;
}
final Set<String> suggestionsItemTypes = {
...toolbarItemWhiteList,
ToggleListBlockKeys.type,
@@ -3,7 +3,6 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart'
show StringTranslateExtension;
@@ -176,12 +175,7 @@ class _CalloutBlockComponentWidgetState
EmojiIconData result = EmojiIconData.emoji('📌');
try {
result = EmojiIconData(FlowyIconType.values.byName(type), icon);
} catch (e) {
Log.info(
'get emoji error with icon:[$icon], type:[$type] within calloutBlockComponentWidget',
e,
);
}
} catch (_) {}
return result;
}
@@ -1,15 +1,24 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/toolbar_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'toolbar_animation.dart';
import 'toolbar_cubit.dart';
class DesktopFloatingToolbar extends StatefulWidget {
const DesktopFloatingToolbar({
super.key,
required this.editorState,
required this.child,
required this.onDismiss,
this.enableAnimation = true,
});
final EditorState editorState;
final Widget child;
final VoidCallback onDismiss;
final bool enableAnimation;
@override
State<DesktopFloatingToolbar> createState() => _DesktopFloatingToolbarState();
@@ -35,11 +44,16 @@ class _DesktopFloatingToolbarState extends State<DesktopFloatingToolbar> {
@override
Widget build(BuildContext context) {
if (position == null) return Container();
return Positioned(
left: position!.left,
top: position!.top,
right: position!.right,
child: widget.child,
return BlocProvider<ToolbarCubit>(
create: (_) => ToolbarCubit(widget.onDismiss),
child: Positioned(
left: position!.left,
top: position!.top,
right: position!.right,
child: widget.enableAnimation
? ToolbarAnimationWidget(child: widget.child)
: widget.child,
),
);
}
@@ -48,10 +62,11 @@ class _DesktopFloatingToolbarState extends State<DesktopFloatingToolbar> {
) {
const toolbarHeight = 40, topLimit = toolbarHeight + 8;
final bool isLongMenu = onlyShowInSingleSelectionAndTextType(editorState);
final menuWidth = isLongMenu ? 650.0 : 420.0;
final editorOffset =
editorState.renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final editorSize = editorState.renderBox?.size ?? Size.zero;
final menuWidth =
isLongMenu ? (isNarrowWindow(editorState) ? 490.0 : 660.0) : 420.0;
final editorRect = editorOffset & editorSize;
final left = rect.left, leftStart = 50;
final top =
@@ -0,0 +1,273 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_styles.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/custom_link_toolbar_item.dart';
import 'package:appflowy/plugins/shared/share/constants.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'link_search_text_field.dart';
class LinkCreateMenu extends StatefulWidget {
const LinkCreateMenu({
super.key,
required this.editorState,
required this.onSubmitted,
required this.onDismiss,
required this.alignment,
});
final EditorState editorState;
final void Function(String link, bool isPage) onSubmitted;
final VoidCallback onDismiss;
final LinkMenuAlignment alignment;
@override
State<LinkCreateMenu> createState() => _LinkCreateMenuState();
}
class _LinkCreateMenuState extends State<LinkCreateMenu> {
late LinkSearchTextField searchTextField = LinkSearchTextField(
onEnter: () {
searchTextField.onSearchResult(
onLink: () => onSubmittedLink(),
onRecentViews: () =>
onSubmittedPageLink(searchTextField.currentRecentView),
onSearchViews: () =>
onSubmittedPageLink(searchTextField.currentSearchedView),
onEmpty: () {},
);
},
onEscape: widget.onDismiss,
onDataRefresh: () {
if (mounted) setState(() {});
},
);
bool get isButtonEnable => searchText.isNotEmpty;
String get searchText => searchTextField.searchText;
bool get showAtTop => widget.alignment.isTop;
@override
void initState() {
super.initState();
searchTextField.requestFocus();
searchTextField.searchRecentViews();
}
@override
void dispose() {
searchTextField.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SizedBox(
width: 320,
child: Column(
children: showAtTop
? [
searchTextField.buildResultContainer(
margin: EdgeInsets.only(bottom: 2),
context: context,
onLinkSelected: onSubmittedLink,
onPageLinkSelected: onSubmittedPageLink,
),
buildSearchContainer(),
]
: [
buildSearchContainer(),
searchTextField.buildResultContainer(
margin: EdgeInsets.only(top: 2),
context: context,
onLinkSelected: onSubmittedLink,
onPageLinkSelected: onSubmittedPageLink,
),
],
),
);
}
Widget buildSearchContainer() {
return Container(
width: 320,
height: 48,
decoration: buildToolbarLinkDecoration(context),
padding: EdgeInsets.all(8),
child: ValueListenableBuilder(
valueListenable: searchTextField.textEditingController,
builder: (context, _, __) {
return Row(
children: [
Expanded(child: searchTextField.buildTextField()),
HSpace(8),
FlowyTextButton(
LocaleKeys.document_toolbar_insert.tr(),
mainAxisAlignment: MainAxisAlignment.center,
padding: EdgeInsets.zero,
constraints: BoxConstraints(maxWidth: 72, minHeight: 32),
fontSize: 14,
fontColor:
isButtonEnable ? Colors.white : LinkStyle.textTertiary,
fillColor: isButtonEnable
? LinkStyle.fillThemeThick
: LinkStyle.borderColor,
hoverColor: LinkStyle.fillThemeThick,
lineHeight: 20 / 14,
fontWeight: FontWeight.w600,
onPressed: isButtonEnable ? () => onSubmittedLink() : null,
),
],
);
},
),
);
}
void onSubmittedLink() => widget.onSubmitted(searchText, false);
void onSubmittedPageLink(ViewPB view) async {
final workspaceId = context
.read<UserWorkspaceBloc?>()
?.state
.currentWorkspace
?.workspaceId ??
'';
final link = ShareConstants.buildShareUrl(
workspaceId: workspaceId,
viewId: view.id,
);
widget.onSubmitted(link, true);
}
}
void showLinkCreateMenu(
BuildContext context,
EditorState editorState,
Selection selection,
) {
final (left, top, right, bottom, alignment) = _getPosition(editorState);
final node = editorState.getNodeAtPath(selection.end.path);
if (node == null) {
return;
}
OverlayEntry? overlay;
void dismissOverlay() {
keepEditorFocusNotifier.decrease();
overlay?.remove();
overlay = null;
}
keepEditorFocusNotifier.increase();
overlay = FullScreenOverlayEntry(
top: top,
bottom: bottom,
left: left,
right: right,
dismissCallback: () => keepEditorFocusNotifier.decrease(),
builder: (context) {
return LinkCreateMenu(
alignment: alignment,
editorState: editorState,
onSubmitted: (link, isPage) async {
await editorState.formatDelta(selection, {
BuiltInAttributeKey.href: link,
kIsPageLink: isPage,
});
dismissOverlay();
},
onDismiss: dismissOverlay,
);
},
).build();
Overlay.of(context, rootOverlay: true).insert(overlay!);
}
// get a proper position for link menu
(
double? left,
double? top,
double? right,
double? bottom,
LinkMenuAlignment alignment,
) _getPosition(
EditorState editorState,
) {
final rect = editorState.selectionRects().first;
const menuHeight = 222.0, menuWidth = 320.0;
double? left, right, top, bottom;
LinkMenuAlignment alignment = LinkMenuAlignment.topLeft;
final editorOffset = editorState.renderBox!.localToGlobal(Offset.zero),
editorSize = editorState.renderBox!.size;
final editorBottom = editorSize.height + editorOffset.dy,
editorRight = editorSize.width + editorOffset.dx;
final overflowBottom = rect.bottom + menuHeight > editorBottom,
overflowTop = rect.top - menuHeight < 0,
overflowLeft = rect.left - menuWidth < 0,
overflowRight = rect.right + menuWidth > editorRight;
if (overflowTop && !overflowBottom) {
/// show at bottom
top = rect.bottom;
} else if (overflowBottom && !overflowTop) {
/// show at top
bottom = editorBottom - rect.top;
} else if (!overflowTop && !overflowBottom) {
/// show at bottom
top = rect.bottom;
} else {
top = 0;
}
if (overflowLeft && !overflowRight) {
/// show at right
left = rect.left;
} else if (overflowRight && !overflowLeft) {
/// show at left
right = editorRight - rect.right;
} else if (!overflowLeft && !overflowRight) {
/// show at right
left = rect.left;
} else {
left = 0;
}
if (left != null && top != null) {
alignment = LinkMenuAlignment.bottomRight;
} else if (left != null && bottom != null) {
alignment = LinkMenuAlignment.topRight;
} else if (right != null && top != null) {
alignment = LinkMenuAlignment.bottomLeft;
} else if (right != null && bottom != null) {
alignment = LinkMenuAlignment.topLeft;
}
return (left, top, right, bottom, alignment);
}
ShapeDecoration buildToolbarLinkDecoration(BuildContext context) =>
ShapeDecoration(
color: Theme.of(context).cardColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
shadows: [
const BoxShadow(
color: LinkStyle.shadowMedium,
blurRadius: 24,
offset: Offset(0, 4),
),
],
);
@@ -0,0 +1,429 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/custom_link_toolbar_item.dart';
import 'package:appflowy/plugins/shared/share/constants.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'link_create_menu.dart';
import 'link_search_text_field.dart';
import 'link_styles.dart';
class LinkEditMenu extends StatefulWidget {
const LinkEditMenu({
super.key,
required this.linkInfo,
required this.onDismiss,
required this.onApply,
required this.onRemoveLink,
});
final LinkInfo linkInfo;
final ValueChanged<LinkInfo> onApply;
final VoidCallback onRemoveLink;
final VoidCallback onDismiss;
@override
State<LinkEditMenu> createState() => _LinkEditMenuState();
}
class _LinkEditMenuState extends State<LinkEditMenu> {
ValueChanged<LinkInfo> get onApply => widget.onApply;
VoidCallback get onRemoveLink => widget.onRemoveLink;
VoidCallback get onDismiss => widget.onDismiss;
late TextEditingController linkNameController =
TextEditingController(text: linkInfo.name);
final textFocusNode = FocusNode();
late LinkInfo linkInfo = widget.linkInfo;
late LinkSearchTextField searchTextField;
bool isShowingSearchResult = false;
ViewPB? currentView;
bool get enableApply =>
linkInfo.link.isNotEmpty && linkNameController.text.isNotEmpty;
@override
void initState() {
super.initState();
final isPageLink = linkInfo.isPage;
if (isPageLink) getPageView();
searchTextField = LinkSearchTextField(
initialSearchText: isPageLink ? '' : linkInfo.link,
onEnter: () {
searchTextField.onSearchResult(
onLink: onLinkSelected,
onRecentViews: () =>
onPageSelected(searchTextField.currentRecentView),
onSearchViews: () =>
onPageSelected(searchTextField.currentSearchedView),
onEmpty: () {
searchTextField.unfocus();
},
);
},
onEscape: () {
if (isShowingSearchResult) {
hideSearchResult();
} else {
onDismiss();
}
},
onDataRefresh: () {
if (mounted) setState(() {});
},
)..searchRecentViews();
}
@override
void dispose() {
linkNameController.dispose();
textFocusNode.dispose();
searchTextField.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final showingRecent =
searchTextField.showingRecent && isShowingSearchResult;
return GestureDetector(
onTap: onDismiss,
child: Container(
width: 400,
height: 250 + (showingRecent ? 32 : 0),
color: Colors.white.withAlpha(1),
child: Stack(
children: [
GestureDetector(
onTap: hideSearchResult,
child: Container(
width: 400,
height: 192,
decoration: buildToolbarLinkDecoration(context),
padding: EdgeInsets.fromLTRB(20, 16, 20, 16),
),
),
Positioned(
top: 16,
left: 20,
child: FlowyText.semibold(
LocaleKeys.document_toolbar_pageOrURL.tr(),
color: LinkStyle.textTertiary,
fontSize: 12,
figmaLineHeight: 16,
),
),
Positioned(
top: 80,
left: 20,
child: FlowyText.semibold(
LocaleKeys.document_toolbar_linkName.tr(),
color: LinkStyle.textTertiary,
fontSize: 12,
figmaLineHeight: 16,
),
),
Positioned(
top: 152,
left: 20,
child: buildButtons(),
),
Positioned(
top: 108,
left: 20,
child: buildNameTextField(),
),
Positioned(
top: 36,
left: 20,
child: buildLinkField(),
),
],
),
),
);
}
Widget buildLinkField() {
final showPageView = linkInfo.isPage && !isShowingSearchResult;
if (showPageView) return buildPageView();
if (!isShowingSearchResult) return buildLinkView();
return SizedBox(
width: 360,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 360,
height: 32,
child: searchTextField.buildTextField(
autofocus: true,
),
),
VSpace(6),
searchTextField.buildResultContainer(
context: context,
width: 360,
onPageLinkSelected: onPageSelected,
onLinkSelected: onLinkSelected,
),
],
),
);
}
Widget buildButtons() {
return GestureDetector(
onTap: hideSearchResult,
child: SizedBox(
width: 360,
height: 32,
child: Row(
children: [
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_unlink_m),
width: 32,
height: 32,
tooltipText: LocaleKeys.editor_removeLink.tr(),
preferBelow: false,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8)),
border: Border.all(color: LinkStyle.borderColor),
),
onPressed: onRemoveLink,
),
Spacer(),
DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8)),
border: Border.all(color: LinkStyle.borderColor),
),
child: FlowyTextButton(
LocaleKeys.button_cancel.tr(),
padding: EdgeInsets.zero,
mainAxisAlignment: MainAxisAlignment.center,
constraints: BoxConstraints(maxWidth: 78, minHeight: 32),
fontSize: 14,
lineHeight: 20 / 14,
fontColor: LinkStyle.textPrimary,
fillColor: Colors.transparent,
fontWeight: FontWeight.w400,
onPressed: onDismiss,
),
),
HSpace(12),
ValueListenableBuilder(
valueListenable: linkNameController,
builder: (context, _, __) {
return FlowyTextButton(
LocaleKeys.settings_appearance_documentSettings_apply.tr(),
padding: EdgeInsets.zero,
mainAxisAlignment: MainAxisAlignment.center,
constraints: BoxConstraints(maxWidth: 78, minHeight: 32),
fontSize: 14,
lineHeight: 20 / 14,
hoverColor: LinkStyle.fillThemeThick.withAlpha(200),
fontColor:
enableApply ? Colors.white : LinkStyle.textTertiary,
fillColor: enableApply
? LinkStyle.fillThemeThick
: LinkStyle.borderColor,
fontWeight: FontWeight.w400,
onPressed:
enableApply ? () => widget.onApply.call(linkInfo) : null,
);
},
),
],
),
),
);
}
Widget buildNameTextField() {
return SizedBox(
width: 360,
height: 32,
child: TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
focusNode: textFocusNode,
textAlign: TextAlign.left,
controller: linkNameController,
style: TextStyle(
fontSize: 14,
height: 20 / 14,
fontWeight: FontWeight.w400,
),
onChanged: (text) {
linkInfo = LinkInfo(
name: text,
link: linkInfo.link,
isPage: linkInfo.isPage,
);
},
decoration: LinkStyle.buildLinkTextFieldInputDecoration(
LocaleKeys.document_toolbar_linkNameHint.tr(),
),
),
);
}
Widget buildPageView() {
late Widget child;
final view = currentView;
if (view == null) {
child = Center(
child: SizedBox.fromSize(
size: Size(10, 10),
child: CircularProgressIndicator(),
),
);
} else {
child = GestureDetector(
onTap: showSearchResult,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: Container(
height: 32,
padding: EdgeInsets.fromLTRB(8, 6, 8, 6),
child: Row(
children: [
searchTextField.buildIcon(view),
HSpace(8),
Flexible(
child: FlowyText.regular(
view.name,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
);
}
return Container(
width: 360,
height: 32,
decoration: buildDecoration(),
child: child,
);
}
Widget buildLinkView() {
return Container(
width: 360,
height: 32,
decoration: buildDecoration(),
child: GestureDetector(
onTap: showSearchResult,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: Padding(
padding: EdgeInsets.fromLTRB(8, 6, 8, 6),
child: Row(
children: [
FlowySvg(FlowySvgs.toolbar_link_earth_m),
HSpace(8),
Flexible(
child: FlowyText.regular(
linkInfo.link,
overflow: TextOverflow.ellipsis,
figmaLineHeight: 20,
),
),
],
),
),
),
),
);
}
Future<void> getPageView() async {
if (!linkInfo.isPage) return;
final link = linkInfo.link;
final viewId = link.split('/').lastOrNull ?? '';
final (view, isInTrash, isDeleted) =
await ViewBackendService.getMentionPageStatus(viewId);
if (mounted) {
setState(() {
currentView = view;
});
}
}
void showSearchResult() {
setState(() {
if (linkInfo.isPage) searchTextField.updateText('');
isShowingSearchResult = true;
searchTextField.requestFocus();
});
}
void hideSearchResult() {
setState(() {
isShowingSearchResult = false;
searchTextField.unfocus();
textFocusNode.unfocus();
});
}
void onLinkSelected() {
if (mounted) {
linkInfo = LinkInfo(
name: linkInfo.name,
link: searchTextField.searchText,
);
hideSearchResult();
}
}
Future<void> onPageSelected(ViewPB view) async {
currentView = view;
final link = ShareConstants.buildShareUrl(
workspaceId: await UserBackendService.getCurrentWorkspace().fold(
(s) => s.id,
(f) => '',
),
viewId: view.id,
);
linkInfo = LinkInfo(
name: linkInfo.name,
link: link,
isPage: true,
);
searchTextField.updateText(linkInfo.link);
if (mounted) {
setState(() {
isShowingSearchResult = false;
searchTextField.unfocus();
});
}
}
BoxDecoration buildDecoration() => BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(color: LinkStyle.borderColor),
);
}
class LinkInfo {
LinkInfo({this.isPage = false, required this.name, required this.link});
final bool isPage;
final String name;
final String link;
Attributes toAttribute() =>
{AppFlowyRichTextKeys.href: link, kIsPageLink: isPage};
}
@@ -0,0 +1,397 @@
import 'dart:math';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/custom_link_toolbar_item.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'link_create_menu.dart';
import 'link_edit_menu.dart';
import 'link_styles.dart';
class LinkHoverTrigger extends StatefulWidget {
const LinkHoverTrigger({
super.key,
required this.editorState,
required this.selection,
required this.node,
required this.attribute,
required this.size,
this.delayToShow = const Duration(milliseconds: 50),
this.delayToHide = const Duration(milliseconds: 300),
});
final EditorState editorState;
final Selection selection;
final Node node;
final Attributes attribute;
final Size size;
final Duration delayToShow;
final Duration delayToHide;
@override
State<LinkHoverTrigger> createState() => _LinkHoverTriggerState();
}
class _LinkHoverTriggerState extends State<LinkHoverTrigger> {
final hoverMenuController = PopoverController();
final editMenuController = PopoverController();
bool isHoverMenuShowing = false;
bool isHoverMenuHovering = false;
bool isHoverTriggerHovering = false;
Size get size => widget.size;
EditorState get editorState => widget.editorState;
Selection get selection => widget.selection;
Attributes get attribute => widget.attribute;
HoverTriggerKey get triggerKey => HoverTriggerKey(widget.node.id, selection);
@override
void initState() {
super.initState();
getIt<LinkHoverTriggers>()._add(triggerKey, showLinkHoverMenu);
}
@override
void dispose() {
hoverMenuController.close();
editMenuController.close();
getIt<LinkHoverTriggers>()._remove(triggerKey, showLinkHoverMenu);
super.dispose();
}
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (v) {
isHoverTriggerHovering = true;
Future.delayed(widget.delayToShow, () {
if (isHoverTriggerHovering && !isHoverMenuShowing) {
showLinkHoverMenu();
}
});
},
onExit: (v) {
isHoverTriggerHovering = false;
tryToDismissLinkHoverMenu();
},
child: buildHoverPopover(
buildEditPopover(
Container(
color: Colors.black.withAlpha(1),
width: size.width,
height: size.height,
),
),
),
);
}
Widget buildHoverPopover(Widget child) {
return AppFlowyPopover(
controller: hoverMenuController,
direction: PopoverDirection.topWithLeftAligned,
offset: Offset(0, size.height),
onOpen: () {
keepEditorFocusNotifier.increase();
isHoverMenuShowing = true;
},
onClose: () {
keepEditorFocusNotifier.decrease();
isHoverMenuShowing = false;
},
margin: EdgeInsets.zero,
constraints: BoxConstraints(
maxWidth: max(320, size.width),
maxHeight: 48 + size.height,
),
decorationColor: Colors.transparent,
popoverDecoration: BoxDecoration(),
popupBuilder: (context) => LinkHoverMenu(
attribute: widget.attribute,
triggerSize: size,
onEnter: (_) {
isHoverMenuHovering = true;
},
onExit: (_) {
isHoverMenuHovering = false;
tryToDismissLinkHoverMenu();
},
onOpenLink: openLink,
onCopyLink: copyLink,
onEditLink: showLinkEditMenu,
onRemoveLink: () => removeLink(editorState, selection, true),
),
child: child,
);
}
Widget buildEditPopover(Widget child) {
final href = attribute.href ?? '',
isPage = attribute.isPage,
title = editorState.getTextInSelection(selection).join();
return AppFlowyPopover(
controller: editMenuController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: Offset(0, 0),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () => keepEditorFocusNotifier.decrease(),
margin: EdgeInsets.zero,
asBarrier: true,
decorationColor: Colors.transparent,
popoverDecoration: BoxDecoration(),
constraints: BoxConstraints(
maxWidth: 400,
minHeight: 282,
),
popupBuilder: (context) => LinkEditMenu(
linkInfo: LinkInfo(name: title, link: href, isPage: isPage),
onDismiss: () => editMenuController.close(),
onApply: (info) async {
final transaction = editorState.transaction;
transaction.replaceText(
widget.node,
selection.startIndex,
selection.length,
info.name,
attributes: info.toAttribute(),
);
editMenuController.close();
await editorState.apply(transaction);
},
onRemoveLink: () => removeLink(editorState, selection, true),
),
child: child,
);
}
void showLinkHoverMenu() {
if (isHoverMenuShowing) return;
keepEditorFocusNotifier.increase();
hoverMenuController.show();
}
void showLinkEditMenu() {
keepEditorFocusNotifier.increase();
hoverMenuController.close();
editMenuController.show();
}
void tryToDismissLinkHoverMenu() {
Future.delayed(widget.delayToHide, () {
if (isHoverMenuHovering || isHoverTriggerHovering) {
return;
}
hoverMenuController.close();
});
}
Future<void> openLink() async {
final href = widget.attribute.href ?? '', isPage = widget.attribute.isPage;
if (isPage) {
final viewId = href.split('/').lastOrNull ?? '';
if (viewId.isEmpty) {
await afLaunchUrlString(href);
} else {
final (view, isInTrash, isDeleted) =
await ViewBackendService.getMentionPageStatus(viewId);
if (view != null) {
await handleMentionBlockTap(context, widget.editorState, view);
}
}
} else {
await afLaunchUrlString(href);
}
}
Future<void> copyLink() async {
final href = widget.attribute.href ?? '';
if (href.isEmpty) return;
await getIt<ClipboardService>()
.setData(ClipboardServiceData(plainText: href));
hoverMenuController.close();
}
void removeLink(
EditorState editorState,
Selection selection,
bool isHref,
) {
if (!isHref) return;
final node = editorState.getNodeAtPath(selection.end.path);
if (node == null) {
return;
}
final index = selection.normalized.startIndex;
final length = selection.length;
final transaction = editorState.transaction
..formatText(
node,
index,
length,
{
BuiltInAttributeKey.href: null,
kIsPageLink: null,
},
);
editorState.apply(transaction);
}
}
class LinkHoverMenu extends StatelessWidget {
const LinkHoverMenu({
super.key,
required this.attribute,
required this.onEnter,
required this.onExit,
required this.triggerSize,
required this.onCopyLink,
required this.onOpenLink,
required this.onEditLink,
required this.onRemoveLink,
});
final Attributes attribute;
final PointerEnterEventListener onEnter;
final PointerExitEventListener onExit;
final Size triggerSize;
final VoidCallback onCopyLink;
final VoidCallback onOpenLink;
final VoidCallback onEditLink;
final VoidCallback onRemoveLink;
@override
Widget build(BuildContext context) {
final href = attribute.href ?? '';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MouseRegion(
onEnter: onEnter,
onExit: onExit,
child: SizedBox(
width: max(320, triggerSize.width),
height: 48,
child: Align(
alignment: Alignment.centerLeft,
child: Container(
width: 320,
height: 48,
decoration: buildToolbarLinkDecoration(context),
padding: EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: FlowyText.regular(
href,
fontSize: 14,
figmaLineHeight: 20,
overflow: TextOverflow.ellipsis,
),
),
Container(
height: 20,
width: 1,
color: LinkStyle.borderColor,
margin: EdgeInsets.symmetric(horizontal: 6),
),
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_m),
tooltipText: LocaleKeys.editor_copyLink.tr(),
width: 36,
height: 32,
onPressed: onCopyLink,
),
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_edit_m),
tooltipText: LocaleKeys.editor_editLink.tr(),
width: 36,
height: 32,
onPressed: onEditLink,
),
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_unlink_m),
tooltipText: LocaleKeys.editor_removeLink.tr(),
width: 36,
height: 32,
onPressed: onRemoveLink,
),
],
),
),
),
),
),
MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: onEnter,
onExit: onExit,
child: GestureDetector(
onTap: onOpenLink,
child: Container(
width: triggerSize.width,
height: triggerSize.height,
color: Colors.black.withAlpha(1),
),
),
),
],
);
}
}
class HoverTriggerKey {
HoverTriggerKey(this.nodeId, this.selection);
final String nodeId;
final Selection selection;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HoverTriggerKey &&
runtimeType == other.runtimeType &&
nodeId == other.nodeId &&
selection == other.selection;
@override
int get hashCode => nodeId.hashCode ^ selection.hashCode;
}
class LinkHoverTriggers {
final Map<HoverTriggerKey, Set<VoidCallback>> _map = {};
void _add(HoverTriggerKey key, VoidCallback callback) {
final callbacks = _map[key] ?? {};
callbacks.add(callback);
_map[key] = callbacks;
}
void _remove(HoverTriggerKey key, VoidCallback callback) {
final callbacks = _map[key] ?? {};
callbacks.remove(callback);
_map[key] = callbacks;
}
void call(HoverTriggerKey key) {
final callbacks = _map[key] ?? {};
for (final callback in callbacks) {
callback.call();
}
}
}
@@ -0,0 +1,326 @@
import 'dart:math';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart';
import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';
import 'package:appflowy/shared/list_extension.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/recent/cached_recent_service.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
// ignore: implementation_imports
import 'package:appflowy_editor/src/flutter/scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'link_create_menu.dart';
import 'link_styles.dart';
class LinkSearchTextField {
LinkSearchTextField({
this.onEscape,
this.onEnter,
this.onDataRefresh,
String? initialSearchText,
}) : textEditingController = TextEditingController(
text: initialSearchText ?? '',
);
final TextEditingController textEditingController;
final ItemScrollController searchController = ItemScrollController();
late FocusNode focusNode = FocusNode(onKeyEvent: onKeyEvent);
final List<ViewPB> searchedViews = [];
final List<ViewPB> recentViews = [];
int selectedIndex = 0;
final VoidCallback? onEscape;
final VoidCallback? onEnter;
final VoidCallback? onDataRefresh;
String get searchText => textEditingController.text;
bool get isButtonEnable => searchText.isNotEmpty;
bool get showingRecent => searchText.isEmpty && recentViews.isNotEmpty;
ViewPB get currentSearchedView => searchedViews[selectedIndex];
ViewPB get currentRecentView => recentViews[selectedIndex];
void dispose() {
textEditingController.dispose();
focusNode.dispose();
searchedViews.clear();
recentViews.clear();
}
Widget buildTextField({bool autofocus = false}) {
return TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
autofocus: autofocus,
focusNode: focusNode,
textAlign: TextAlign.left,
controller: textEditingController,
style: TextStyle(
fontSize: 14,
height: 20 / 14,
fontWeight: FontWeight.w400,
),
onChanged: (text) {
if (text.isEmpty) {
searchedViews.clear();
selectedIndex = 0;
onDataRefresh?.call();
} else {
searchViews(text);
}
},
decoration: LinkStyle.buildLinkTextFieldInputDecoration(
LocaleKeys.document_toolbar_linkInputHint.tr(),
),
);
}
Widget buildResultContainer({
EdgeInsetsGeometry? margin,
required BuildContext context,
VoidCallback? onLinkSelected,
ValueChanged<ViewPB>? onPageLinkSelected,
double width = 320.0,
}) {
return onSearchResult<Widget>(
onEmpty: () => SizedBox.shrink(),
onLink: () => Container(
height: 48,
width: width,
padding: EdgeInsets.all(8),
margin: margin,
decoration: buildToolbarLinkDecoration(context),
child: FlowyButton(
leftIcon: FlowySvg(FlowySvgs.toolbar_link_earth_m),
isSelected: true,
text: FlowyText.regular(
searchText,
overflow: TextOverflow.ellipsis,
fontSize: 14,
figmaLineHeight: 20,
),
onTap: onLinkSelected,
),
),
onRecentViews: () => Container(
width: width,
height: recentViews.length.clamp(1, 5) * 32.0 + 48,
margin: margin,
padding: EdgeInsets.all(8),
decoration: buildToolbarLinkDecoration(context),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 32,
padding: EdgeInsets.all(8),
child: FlowyText.semibold(
LocaleKeys.inlineActions_recentPages.tr(),
color: LinkStyle.textTertiary,
fontSize: 12,
figmaLineHeight: 16,
),
),
Flexible(
child: ListView.builder(
itemBuilder: (context, index) {
final currentView = recentViews[index];
return buildPageItem(
currentView,
index == selectedIndex,
onPageLinkSelected,
);
},
itemCount: recentViews.length,
),
),
],
),
),
onSearchViews: () => Container(
width: width,
height: searchedViews.length.clamp(1, 5) * 32.0 + 16,
margin: margin,
decoration: buildToolbarLinkDecoration(context),
child: ScrollablePositionedList.builder(
padding: EdgeInsets.all(8),
physics: const ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: searchedViews.length,
itemScrollController: searchController,
initialScrollIndex: max(0, selectedIndex),
itemBuilder: (context, index) {
final currentView = searchedViews[index];
return buildPageItem(
currentView,
index == selectedIndex,
onPageLinkSelected,
);
},
),
),
);
}
Widget buildPageItem(
ViewPB view,
bool isSelected,
ValueChanged<ViewPB>? onSubmittedPageLink,
) {
return SizedBox(
height: 32,
child: FlowyButton(
isSelected: isSelected,
leftIcon: buildIcon(view),
text: FlowyText.regular(
view.name,
overflow: TextOverflow.ellipsis,
fontSize: 14,
figmaLineHeight: 20,
),
onTap: () => onSubmittedPageLink?.call(view),
),
);
}
Widget buildIcon(ViewPB view) {
if (view.icon.value.isEmpty) return view.defaultIcon(size: Size(20, 20));
final iconData = view.icon.toEmojiIconData();
return RawEmojiIconWidget(
emoji: iconData,
emojiSize: iconData.type == FlowyIconType.emoji ? 16 : 20,
lineHeight: 1,
);
}
void requestFocus() => focusNode.requestFocus();
void unfocus() => focusNode.unfocus();
void updateText(String text) => textEditingController.text = text;
T onSearchResult<T>({
required ValueGetter<T> onLink,
required ValueGetter<T> onRecentViews,
required ValueGetter<T> onSearchViews,
required ValueGetter<T> onEmpty,
}) {
if (searchedViews.isEmpty && recentViews.isEmpty && searchText.isEmpty) {
return onEmpty.call();
}
if (searchedViews.isEmpty && searchText.isNotEmpty) {
return onLink.call();
}
if (searchedViews.isEmpty) return onRecentViews.call();
return onSearchViews.call();
}
KeyEventResult onKeyEvent(FocusNode node, KeyEvent key) {
if (key is! KeyDownEvent) return KeyEventResult.ignored;
int index = selectedIndex;
if (key.logicalKey == LogicalKeyboardKey.escape) {
onEscape?.call();
return KeyEventResult.handled;
} else if (key.logicalKey == LogicalKeyboardKey.arrowUp) {
index = onSearchResult(
onLink: () => 0,
onRecentViews: () {
int result = index - 1;
if (result < 0) result = recentViews.length - 1;
return result;
},
onSearchViews: () {
int result = index - 1;
if (result < 0) result = searchedViews.length - 1;
searchController.scrollTo(
index: result,
alignment: 0.5,
duration: const Duration(milliseconds: 300),
);
return result;
},
onEmpty: () => 0,
);
refreshIndex(index);
return KeyEventResult.handled;
} else if (key.logicalKey == LogicalKeyboardKey.arrowDown) {
index = onSearchResult(
onLink: () => 0,
onRecentViews: () {
int result = index + 1;
if (result >= recentViews.length) result = 0;
return result;
},
onSearchViews: () {
int result = index + 1;
if (result >= searchedViews.length) result = 0;
searchController.scrollTo(
index: result,
alignment: 0.5,
duration: const Duration(milliseconds: 300),
);
return result;
},
onEmpty: () => 0,
);
refreshIndex(index);
return KeyEventResult.handled;
} else if (key.logicalKey == LogicalKeyboardKey.enter) {
onEnter?.call();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
Future<void> searchRecentViews() async {
final recentService = getIt<CachedRecentService>();
final sectionViews = await recentService.recentViews();
final views = sectionViews
.unique((e) => e.item.id)
.map((e) => e.item)
.take(5)
.toList();
recentViews.clear();
recentViews.addAll(views);
selectedIndex = 0;
onDataRefresh?.call();
}
Future<void> searchViews(String search) async {
final viewResult = await ViewBackendService.getAllViews();
final allViews = viewResult
.toNullable()
?.items
.where(
(view) =>
view.name.toLowerCase().contains(search.toLowerCase()) ||
(view.name.isEmpty && search.isEmpty) ||
(view.name.isEmpty &&
LocaleKeys.menuAppHeader_defaultNewPageName
.tr()
.toLowerCase()
.contains(search.toLowerCase())),
)
.take(10)
.toList();
searchedViews.clear();
searchedViews.addAll(allViews ?? []);
selectedIndex = 0;
onDataRefresh?.call();
}
void refreshIndex(int index) {
selectedIndex = index;
onDataRefresh?.call();
}
}
@@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
class LinkStyle {
static const borderColor = Color(0xFFE8ECF3);
static const textTertiary = Color(0xFF99A1A8);
static const fillThemeThick = Color(0xFF00B5FF);
static const shadowMedium = Color(0x1F22251F);
static const textPrimary = Color(0xFF1F2329);
static InputDecoration buildLinkTextFieldInputDecoration(String hintText) {
const border = OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: LinkStyle.borderColor),
);
final enableBorder = border.copyWith(
borderSide: BorderSide(color: LinkStyle.fillThemeThick),
);
const hintStyle = TextStyle(
fontSize: 14,
height: 20 / 14,
fontWeight: FontWeight.w400,
color: LinkStyle.textTertiary,
);
return InputDecoration(
hintText: hintText,
hintStyle: hintStyle,
contentPadding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
isDense: true,
border: border,
enabledBorder: border,
focusedBorder: enableBorder,
);
}
}
@@ -0,0 +1,17 @@
import 'dart:ui';
import 'package:bloc/bloc.dart';
class ToolbarCubit extends Cubit<ToolbarState> {
ToolbarCubit(this.onDismissCallback) : super(ToolbarState._());
final VoidCallback onDismissCallback;
void dismiss() {
onDismissCallback.call();
}
}
class ToolbarState {
const ToolbarState._();
}
@@ -71,11 +71,13 @@ class RawEmojiIconWidget extends StatefulWidget {
required this.emoji,
required this.emojiSize,
this.enableColor = true,
this.lineHeight,
});
final EmojiIconData emoji;
final double emojiSize;
final bool enableColor;
final double? lineHeight;
@override
State<RawEmojiIconWidget> createState() => _RawEmojiIconWidgetState();
@@ -115,6 +117,7 @@ class _RawEmojiIconWidgetState extends State<RawEmojiIconWidget> {
emoji: widget.emoji.emoji,
fontSize: widget.emojiSize,
textAlign: TextAlign.justify,
lineHeight: widget.lineHeight,
);
case FlowyIconType.icon:
IconsData iconData =
@@ -60,8 +60,6 @@ class MentionDateBlock extends StatefulWidget {
}
class _MentionDateBlockState extends State<MentionDateBlock> {
final PopoverMutex mutex = PopoverMutex();
late bool _includeTime = widget.includeTime;
late DateTime? parsedDate = DateTime.tryParse(widget.date);
@@ -71,12 +69,6 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
mutex.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (parsedDate == null) {
@@ -105,7 +97,6 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
final options = DatePickerOptions(
focusedDay: parsedDate,
popoverMutex: mutex,
selectedDay: parsedDate,
includeTime: _includeTime,
dateFormat: appearance.dateFormat,
@@ -118,7 +118,7 @@ class _MentionPageBlockState extends State<MentionPageBlock> {
view: view,
content: state.blockContent,
textStyle: widget.textStyle,
handleTap: () => _handleTap(
handleTap: () => handleMentionBlockTap(
context,
widget.editorState,
view,
@@ -138,7 +138,7 @@ class _MentionPageBlockState extends State<MentionPageBlock> {
content: state.blockContent,
textStyle: widget.textStyle,
showTrashHint: state.isInTrash,
handleTap: () => _handleTap(
handleTap: () => handleMentionBlockTap(
context,
widget.editorState,
view,
@@ -221,7 +221,8 @@ class _MentionSubPageBlockState extends State<MentionSubPageBlock> {
view: view,
showTrashHint: state.isInTrash,
textStyle: widget.textStyle,
handleTap: () => _handleTap(context, widget.editorState, view),
handleTap: () =>
handleMentionBlockTap(context, widget.editorState, view),
isChildPage: true,
content: '',
handleDoubleTap: () => _handleDoubleTap(
@@ -239,7 +240,8 @@ class _MentionSubPageBlockState extends State<MentionSubPageBlock> {
content: null,
textStyle: widget.textStyle,
isChildPage: true,
handleTap: () => _handleTap(context, widget.editorState, view),
handleTap: () =>
handleMentionBlockTap(context, widget.editorState, view),
);
}
},
@@ -321,7 +323,7 @@ Path? _findNodePathByBlockId(EditorState editorState, String blockId) {
return null;
}
Future<void> _handleTap(
Future<void> handleMentionBlockTap(
BuildContext context,
EditorState editorState,
ViewPB view, {
@@ -1,3 +1,4 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -31,7 +32,7 @@ class NumberedListIcon extends StatelessWidget {
return Padding(
padding: const EdgeInsets.only(left: 6.0, right: 10.0),
child: Text(
node.levelString,
node.buildLevelString(context),
style: adjustedTextStyle,
strutStyle: StrutStyle.fromTextStyle(combinedTextStyle),
textHeightBehavior: TextHeightBehavior(
@@ -47,9 +48,12 @@ class NumberedListIcon extends StatelessWidget {
}
}
extension on Node {
String get levelString {
final builder = _NumberedListIconBuilder(node: this);
extension NumberedListNodeIndex on Node {
String buildLevelString(BuildContext context) {
final builder = NumberedListIndexBuilder(
editorState: context.read<EditorState>(),
node: this,
);
final indexInRootLevel = builder.indexInRootLevel;
final indexInSameLevel = builder.indexInSameLevel;
final level = indexInRootLevel % 3;
@@ -62,11 +66,13 @@ extension on Node {
}
}
class _NumberedListIconBuilder {
_NumberedListIconBuilder({
class NumberedListIndexBuilder {
NumberedListIndexBuilder({
required this.editorState,
required this.node,
});
final EditorState editorState;
final Node node;
// the level of the current node
@@ -88,7 +94,13 @@ class _NumberedListIconBuilder {
Node? previous = node.previous;
// if the previous one is not a numbered list, then it is the first one
if (previous == null || previous.type != NumberedListBlockKeys.type) {
final aiNodeExternalValues =
node.externalValues?.unwrapOrNull<AINodeExternalValues>();
if (previous == null ||
previous.type != NumberedListBlockKeys.type ||
(aiNodeExternalValues != null &&
aiNodeExternalValues.isFirstNumberedListNode)) {
return node.attributes[NumberedListBlockKeys.number] ?? level;
}
@@ -97,10 +109,17 @@ class _NumberedListIconBuilder {
startNumber = previous.attributes[NumberedListBlockKeys.number] as int?;
level++;
previous = previous.previous;
// break the loop if the start number is found when the current node is an AI node
if (aiNodeExternalValues != null && startNumber != null) {
return startNumber + level - 1;
}
}
if (startNumber != null) {
return startNumber + level - 1;
level = startNumber + level - 1;
}
return level;
}
}
@@ -7,6 +7,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.da
import 'package:appflowy/plugins/document/presentation/editor_plugins/shortcuts/heading_block_shortcuts.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/shortcuts/numbered_list_block_shortcuts.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy/plugins/emoji/emoji_actions_command.dart';
import 'package:appflowy/plugins/inline_actions/inline_actions_command.dart';
import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -82,5 +83,9 @@ List<CharacterShortcutEvent> buildCharacterShortcutEvents(
documentBloc.documentId,
styleCustomizer.inlineActionsMenuStyleBuilder(),
),
/// show emoji list
/// - Using `:`
emojiCommand(context),
];
}
@@ -238,8 +238,13 @@ extension TableNodeExtension on Node {
try {
final columnWidths =
parentTableNode.attributes[SimpleTableBlockKeys.columnWidths];
final width = columnWidths?[columnIndex.toString()];
return width ?? SimpleTableConstants.defaultColumnWidth;
final width = columnWidths?[columnIndex.toString()] as Object?;
if (width == null) {
return SimpleTableConstants.defaultColumnWidth;
}
return width.toDouble(
defaultValue: SimpleTableConstants.defaultColumnWidth,
);
} catch (e) {
Log.warn('get column width: $e');
return SimpleTableConstants.defaultColumnWidth;
@@ -856,3 +861,18 @@ extension TableNodeExtension on Node {
return TableAlign.left;
}
}
extension on Object {
double toDouble({double defaultValue = 0}) {
if (this is double) {
return this as double;
}
if (this is String) {
return double.tryParse(this as String) ?? defaultValue;
}
if (this is int) {
return (this as int).toDouble();
}
return defaultValue;
}
}
@@ -17,17 +17,20 @@ final _keywords = [
];
/// Image menu item
final imageSlashMenuItem = SelectionMenuItem(
getName: () => LocaleKeys.document_slashMenu_name_image.tr(),
keywords: _keywords,
handler: (editorState, _, __) async => editorState.insertImageBlock(),
nameBuilder: slashMenuItemNameBuilder,
icon: (editorState, isSelected, style) => SelectableSvgWidget(
data: FlowySvgs.slash_menu_icon_image_s,
isSelected: isSelected,
style: style,
),
);
final imageSlashMenuItem = buildImageSlashMenuItem();
SelectionMenuItem buildImageSlashMenuItem({FlowySvgData? svg}) =>
SelectionMenuItem(
getName: () => LocaleKeys.document_slashMenu_name_image.tr(),
keywords: _keywords,
handler: (editorState, _, __) async => editorState.insertImageBlock(),
nameBuilder: slashMenuItemNameBuilder,
icon: (editorState, isSelected, style) => SelectableSvgWidget(
data: svg ?? FlowySvgs.slash_menu_icon_image_s,
isSelected: isSelected,
style: style,
),
);
extension on EditorState {
Future<void> insertImageBlock() async {
@@ -15,7 +15,7 @@ final List<SelectionMenuItem> mobileItems = [
mobileTableSlashMenuItem,
visualsMobileSlashMenuItem,
dateOrReminderSlashMenuItem,
subPageSlashMenuItem,
buildSubpageSlashMenuItem(svg: FlowySvgs.type_page_m),
advancedMobileSlashMenuItem,
];
@@ -26,7 +26,7 @@ final List<SelectionMenuItem> mobileItemsInTale = [
fileAndMediaMobileSlashMenuItem,
visualsMobileSlashMenuItem,
dateOrReminderSlashMenuItem,
subPageSlashMenuItem,
buildSubpageSlashMenuItem(svg: FlowySvgs.type_page_m),
advancedMobileSlashMenuItem,
];
@@ -93,7 +93,7 @@ MobileSelectionMenuItem fileAndMediaMobileSlashMenuItem =
),
nameBuilder: slashMenuItemNameBuilder,
children: [
imageSlashMenuItem,
buildImageSlashMenuItem(svg: FlowySvgs.slash_menu_image_m),
photoGallerySlashMenuItem,
fileSlashMenuItem,
],
@@ -22,26 +22,29 @@ final _keywords = [
];
// Sub-page menu item
SelectionMenuItem subPageSlashMenuItem = SelectionMenuItem.node(
getName: () => LocaleKeys.document_slashMenu_subPage_name.tr(),
keywords: _keywords,
updateSelection: (editorState, path, __, ___) {
final context = editorState.document.root.context;
if (context != null) {
final isInDatabase =
context.read<SharedEditorContext>().isInDatabaseRowPage;
if (isInDatabase) {
Navigator.of(context).pop();
}
}
return Selection.collapsed(Position(path: path));
},
replace: (_, node) => node.delta?.isEmpty ?? false,
nodeBuilder: (_, __) => subPageNode(),
nameBuilder: slashMenuItemNameBuilder,
iconBuilder: (_, isSelected, style) => SelectableSvgWidget(
data: FlowySvgs.insert_document_s,
isSelected: isSelected,
style: style,
),
);
SelectionMenuItem subPageSlashMenuItem = buildSubpageSlashMenuItem();
SelectionMenuItem buildSubpageSlashMenuItem({FlowySvgData? svg}) =>
SelectionMenuItem.node(
getName: () => LocaleKeys.document_slashMenu_subPage_name.tr(),
keywords: _keywords,
updateSelection: (editorState, path, __, ___) {
final context = editorState.document.root.context;
if (context != null) {
final isInDatabase =
context.read<SharedEditorContext>().isInDatabaseRowPage;
if (isInDatabase) {
Navigator.of(context).pop();
}
}
return Selection.collapsed(Position(path: path));
},
replace: (_, node) => node.delta?.isEmpty ?? false,
nodeBuilder: (_, __) => subPageNode(),
nameBuilder: slashMenuItemNameBuilder,
iconBuilder: (_, isSelected, style) => SelectableSvgWidget(
data: svg ?? FlowySvgs.insert_document_s,
isSelected: isSelected,
style: style,
),
);
@@ -6,6 +6,7 @@ import 'package:appflowy_editor/appflowy_editor.dart';
// ignore: implementation_imports
import 'package:appflowy_editor/src/editor/toolbar/desktop/items/utils/tooltip_util.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:flutter/material.dart';
@@ -79,7 +80,7 @@ class _FormatToolbarItem extends ToolbarItem {
size: Size.square(20.0),
color: (isDark && isHighlight)
? Color(0xFF282E3A)
: Theme.of(context).iconTheme.color,
: AFThemeExtensionV2.of(context).icon_primary,
),
onPressed: () => editorState.toggleAttribute(
name,
@@ -1,15 +1,24 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/toolbar_extension.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_create_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/toolbar_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'toolbar_id_enum.dart';
const kIsPageLink = 'is_page_link';
final customLinkItem = ToolbarItem(
id: ToolbarId.link.id,
group: 4,
isActive: onlyShowInSingleSelectionAndTextType,
isActive: (state) =>
!isNarrowWindow(state) && onlyShowInSingleSelectionAndTextType(state),
builder: (context, editorState, highlightColor, iconColor, tooltipBuilder) {
final selection = editorState.selection!;
final nodes = editorState.getNodesInSelection(selection);
@@ -22,6 +31,7 @@ final customLinkItem = ToolbarItem(
final hoverColor = isHref
? highlightColor
: EditorStyleCustomizer.toolbarHoverColor(context);
final toolbarCubit = context.read<ToolbarCubit?>();
final child = FlowyIconButton(
width: 36,
@@ -33,7 +43,16 @@ final customLinkItem = ToolbarItem(
size: Size.square(20.0),
color: Theme.of(context).iconTheme.color,
),
onPressed: () => showLinkMenu(context, editorState, selection, isHref),
onPressed: () {
toolbarCubit?.dismiss();
if (isHref) {
getIt<LinkHoverTriggers>().call(
HoverTriggerKey(nodes.first.id, selection),
);
} else {
showLinkCreateMenu(context, editorState, selection);
}
},
);
if (tooltipBuilder != null) {
@@ -48,3 +67,24 @@ final customLinkItem = ToolbarItem(
return child;
},
);
extension AttributeExtension on Attributes {
bool get isPage {
if (this[kIsPageLink] is bool) {
return this[kIsPageLink];
}
return false;
}
}
enum LinkMenuAlignment {
topLeft,
topRight,
bottomLeft,
bottomRight,
}
extension LinkMenuAlignmentExtension on LinkMenuAlignment {
bool get isTop =>
this == LinkMenuAlignment.topLeft || this == LinkMenuAlignment.topRight;
}
@@ -1,5 +1,6 @@
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/ai_writer_toolbar_item.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/toolbar_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
@@ -43,5 +44,6 @@ ToolbarItem group1PaddingItem =
ToolbarItem group4PaddingItem = buildPaddingPlaceholderItem(
4,
isActive: onlyShowInSingleSelectionAndTextType,
isActive: (state) =>
!isNarrowWindow(state) && onlyShowInSingleSelectionAndTextType(state),
);
@@ -1,8 +1,10 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/toolbar_extension.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
@@ -11,7 +13,8 @@ import 'toolbar_id_enum.dart';
final ToolbarItem customTextAlignItem = ToolbarItem(
id: ToolbarId.textAlign.id,
group: 4,
isActive: onlyShowInSingleSelectionAndTextType,
isActive: (state) =>
!isNarrowWindow(state) && onlyShowInSingleSelectionAndTextType(state),
builder: (
context,
editorState,
@@ -33,18 +36,29 @@ class TextAlignActionList extends StatefulWidget {
required this.editorState,
required this.highlightColor,
this.tooltipBuilder,
this.child,
this.onSelect,
this.popoverController,
this.popoverDirection = PopoverDirection.bottomWithLeftAligned,
this.showOffset = const Offset(0, 2),
});
final EditorState editorState;
final ToolbarTooltipBuilder? tooltipBuilder;
final Color highlightColor;
final Widget? child;
final VoidCallback? onSelect;
final PopoverController? popoverController;
final PopoverDirection popoverDirection;
final Offset showOffset;
@override
State<TextAlignActionList> createState() => _TextAlignActionListState();
}
class _TextAlignActionListState extends State<TextAlignActionList> {
final popoverController = PopoverController();
late PopoverController popoverController =
widget.popoverController ?? PopoverController();
bool isSelected = false;
@@ -62,8 +76,8 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
Widget build(BuildContext context) {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(0, 2.0),
direction: widget.popoverDirection,
offset: widget.showOffset,
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -72,7 +86,7 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
keepEditorFocusNotifier.decrease();
},
popupBuilder: (context) => buildPopoverContent(),
child: buildChild(context),
child: widget.child ?? buildChild(context),
);
}
@@ -82,7 +96,7 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
}
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final themeV2 = AFThemeExtensionV2.of(context);
final child = FlowyIconButton(
width: 48,
height: 32,
@@ -94,13 +108,13 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
FlowySvg(
FlowySvgs.toolbar_alignment_m,
size: Size.square(20),
color: iconColor,
color: themeV2.icon_primary,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size(12, 20),
color: iconColor,
color: themeV2.icon_tertiary,
),
],
),
@@ -149,6 +163,7 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
isHighlight ? FlowySvg(FlowySvgs.toolbar_check_m) : null,
onTap: () {
command.onAlignChanged(editorState);
widget.onSelect?.call();
popoverController.close();
},
),
@@ -1,8 +1,12 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_create_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/toolbar_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
// ignore: implementation_imports
@@ -10,6 +14,10 @@ import 'package:appflowy_editor/src/editor/toolbar/desktop/items/utils/tooltip_u
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'custom_text_align_toolbar_item.dart';
import 'text_suggestions_toolbar_item.dart';
const _kMoreOptionItemId = 'editor.more_option';
const kFontToolbarItemId = 'editor.font';
@@ -54,7 +62,9 @@ class MoreOptionActionList extends StatefulWidget {
class _MoreOptionActionListState extends State<MoreOptionActionList> {
final popoverController = PopoverController();
final fontPopoverController = PopoverController();
PopoverController fontPopoverController = PopoverController();
PopoverController suggestionsPopoverController = PopoverController();
PopoverController textAlignPopoverController = PopoverController();
bool isSelected = false;
@@ -62,11 +72,15 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
Color get highlightColor => widget.highlightColor;
MoreOptionCommand? tappedCommand;
@override
void dispose() {
super.dispose();
popoverController.close();
fontPopoverController.close();
suggestionsPopoverController.close();
textAlignPopoverController.close();
}
@override
@@ -154,11 +168,17 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
Widget buildPopoverContent() {
final showFormula = onlyShowInSingleSelectionAndTextType(editorState);
const fontColor = Color(0xff99A1A8);
final isNarrow = isNarrowWindow(editorState);
return MouseRegion(
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(4.0),
children: [
if (isNarrow) ...[
buildTurnIntoSelector(),
buildCommandItem(MoreOptionCommand.link),
buildTextAlignSelector(),
],
buildFontSelector(),
buildCommandItem(
MoreOptionCommand.strikethrough,
@@ -197,6 +217,7 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
Widget buildCommandItem(
MoreOptionCommand command, {
Widget? rightIcon,
VoidCallback? onTap,
}) {
final isFontCommand = command == MoreOptionCommand.font;
return SizedBox(
@@ -212,12 +233,14 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
figmaLineHeight: 20,
fontWeight: FontWeight.w400,
),
onTap: () {
command.onExecute(editorState);
if (command != MoreOptionCommand.font) {
popoverController.close();
}
},
onTap: onTap ??
() {
command.onExecute(editorState, context);
hideOtherPopovers(command);
if (command != MoreOptionCommand.font) {
popoverController.close();
}
},
),
);
}
@@ -255,9 +278,73 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
),
);
}
Widget buildTurnIntoSelector() {
final selectionRects = editorState.selectionRects();
double height = -6;
if (selectionRects.isNotEmpty) height = selectionRects.first.height;
return SuggestionsActionList(
editorState: editorState,
popoverController: suggestionsPopoverController,
popoverDirection: PopoverDirection.leftWithTopAligned,
showOffset: Offset(-8, height),
onSelect: () => context.read<ToolbarCubit?>()?.dismiss(),
child: buildCommandItem(
MoreOptionCommand.suggestions,
rightIcon: FlowySvg(FlowySvgs.toolbar_arrow_right_m),
onTap: () {
if (tappedCommand == MoreOptionCommand.suggestions) return;
hideOtherPopovers(MoreOptionCommand.suggestions);
keepEditorFocusNotifier.increase();
suggestionsPopoverController.show();
},
),
);
}
Widget buildTextAlignSelector() {
return TextAlignActionList(
editorState: editorState,
popoverController: textAlignPopoverController,
popoverDirection: PopoverDirection.leftWithTopAligned,
showOffset: Offset(-8, 0),
onSelect: () => context.read<ToolbarCubit?>()?.dismiss(),
highlightColor: highlightColor,
child: buildCommandItem(
MoreOptionCommand.textAlign,
rightIcon: FlowySvg(FlowySvgs.toolbar_arrow_right_m),
onTap: () {
if (tappedCommand == MoreOptionCommand.textAlign) return;
hideOtherPopovers(MoreOptionCommand.textAlign);
keepEditorFocusNotifier.increase();
textAlignPopoverController.show();
},
),
);
}
void hideOtherPopovers(MoreOptionCommand currentCommand) {
if (tappedCommand == currentCommand) return;
if (tappedCommand == MoreOptionCommand.font) {
fontPopoverController.close();
fontPopoverController = PopoverController();
} else if (tappedCommand == MoreOptionCommand.suggestions) {
suggestionsPopoverController.close();
suggestionsPopoverController = PopoverController();
} else if (tappedCommand == MoreOptionCommand.textAlign) {
textAlignPopoverController.close();
textAlignPopoverController = PopoverController();
}
tappedCommand = currentCommand;
}
}
enum MoreOptionCommand {
suggestions(FlowySvgs.turninto_s),
link(FlowySvgs.toolbar_link_m),
textAlign(
FlowySvgs.toolbar_alignment_m,
),
font(FlowySvgs.type_font_m),
strikethrough(FlowySvgs.type_strikethrough_m),
formula(FlowySvgs.type_formula_m);
@@ -268,6 +355,12 @@ enum MoreOptionCommand {
String get title {
switch (this) {
case suggestions:
return LocaleKeys.document_toolbar_turnInto.tr();
case link:
return LocaleKeys.document_toolbar_link.tr();
case textAlign:
return LocaleKeys.button_align.tr();
case font:
return LocaleKeys.document_toolbar_font.tr();
case strikethrough:
@@ -277,14 +370,26 @@ enum MoreOptionCommand {
}
}
Future<void> onExecute(EditorState editorState) async {
if (this == strikethrough) {
Future<void> onExecute(EditorState editorState, BuildContext context) async {
final selection = editorState.selection!;
if (this == link) {
final nodes = editorState.getNodesInSelection(selection);
final isHref = nodes.allSatisfyInSelection(selection, (delta) {
return delta.everyAttributes(
(attributes) => attributes[AppFlowyRichTextKeys.href] != null,
);
});
context.read<ToolbarCubit?>()?.dismiss();
if (isHref) {
getIt<LinkHoverTriggers>().call(
HoverTriggerKey(nodes.first.id, selection),
);
} else {
showLinkCreateMenu(context, editorState, selection);
}
} else if (this == strikethrough) {
await editorState.toggleAttribute(name);
} else if (this == formula) {
final selection = editorState.selection;
if (selection == null || selection.isCollapsed) {
return;
}
final node = editorState.getNodeAtPath(selection.start.path);
final delta = node?.delta;
if (node == null || delta == null) {
@@ -5,6 +5,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.da
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
@@ -77,7 +78,7 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
}
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final themeV2 = AFThemeExtensionV2.of(context);
final child = FlowyIconButton(
width: 48,
height: 32,
@@ -89,13 +90,13 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
FlowySvg(
FlowySvgs.toolbar_text_format_m,
size: Size.square(20),
color: iconColor,
color: themeV2.icon_primary,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size(12, 20),
color: iconColor,
color: themeV2.icon_tertiary,
),
],
),
@@ -1,14 +1,16 @@
import 'dart:collection';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/home/menu/menu_shared_state.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
hide QuoteBlockComponentBuilder, quoteNode, QuoteBlockKeys;
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
@@ -45,17 +47,28 @@ class SuggestionsActionList extends StatefulWidget {
super.key,
required this.editorState,
this.tooltipBuilder,
this.child,
this.onSelect,
this.popoverController,
this.popoverDirection = PopoverDirection.bottomWithLeftAligned,
this.showOffset = const Offset(0, 2),
});
final EditorState editorState;
final ToolbarTooltipBuilder? tooltipBuilder;
final Widget? child;
final VoidCallback? onSelect;
final PopoverController? popoverController;
final PopoverDirection popoverDirection;
final Offset showOffset;
@override
State<SuggestionsActionList> createState() => _SuggestionsActionListState();
}
class _SuggestionsActionListState extends State<SuggestionsActionList> {
final popoverController = PopoverController();
late PopoverController popoverController =
widget.popoverController ?? PopoverController();
bool isSelected = false;
@@ -83,8 +96,8 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
Widget build(BuildContext context) {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(0, 2.0),
direction: widget.popoverDirection,
offset: widget.showOffset,
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -94,7 +107,7 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
},
constraints: const BoxConstraints(maxWidth: 240, maxHeight: 400),
popupBuilder: (context) => buildPopoverContent(context),
child: buildChild(context),
child: widget.child ?? buildChild(context),
);
}
@@ -104,7 +117,8 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
}
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final themeV2 = AFThemeExtensionV2.of(context);
final child = FlowyHover(
isSelected: () => isSelected,
style: HoverStyle(
@@ -147,7 +161,7 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size(12, 20),
color: iconColor,
color: themeV2.icon_tertiary,
),
],
),
@@ -206,7 +220,8 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
),
rightIcon: isSelected ? FlowySvg(FlowySvgs.toolbar_check_m) : null,
onTap: () {
item.onTap(widget.editorState);
item.onTap(widget.editorState, true);
widget.onSelect?.call();
popoverController.close();
},
),
@@ -289,10 +304,10 @@ class SuggestionItem {
final SuggestionType type;
final String title;
final FlowySvgData svg;
final ValueChanged<EditorState> onTap;
final Function(EditorState state, bool keepSelection) onTap;
}
enum SuggestionGroup { textHeading, list, toggle, quote }
enum SuggestionGroup { textHeading, list, toggle, quote, page }
enum SuggestionType {
text(SuggestionGroup.textHeading),
@@ -307,7 +322,8 @@ enum SuggestionType {
toggleH2(SuggestionGroup.toggle),
toggleH3(SuggestionGroup.toggle),
callOut(SuggestionGroup.quote),
quote(SuggestionGroup.quote);
quote(SuggestionGroup.quote),
page(SuggestionGroup.page);
const SuggestionType(this.group);
@@ -318,94 +334,166 @@ final textSuggestionItem = SuggestionItem(
type: SuggestionType.text,
title: AppFlowyEditorL10n.current.text,
svg: FlowySvgs.type_text_m,
onTap: (state) => formatNodeToText(state),
onTap: (state, _) => formatNodeToText(state),
);
final h1SuggestionItem = SuggestionItem(
type: SuggestionType.h1,
title: LocaleKeys.document_toolbar_h1.tr(),
svg: FlowySvgs.type_h1_m,
onTap: (state) => _turnInto(state, HeadingBlockKeys.type, level: 1),
onTap: (state, keepSelection) => _turnInto(
state,
HeadingBlockKeys.type,
level: 1,
keepSelection: keepSelection,
),
);
final h2SuggestionItem = SuggestionItem(
type: SuggestionType.h2,
title: LocaleKeys.document_toolbar_h2.tr(),
svg: FlowySvgs.type_h2_m,
onTap: (state) => _turnInto(state, HeadingBlockKeys.type, level: 2),
onTap: (state, keepSelection) => _turnInto(
state,
HeadingBlockKeys.type,
level: 2,
keepSelection: keepSelection,
),
);
final h3SuggestionItem = SuggestionItem(
type: SuggestionType.h3,
title: LocaleKeys.document_toolbar_h3.tr(),
svg: FlowySvgs.type_h3_m,
onTap: (state) => _turnInto(state, HeadingBlockKeys.type, level: 3),
onTap: (state, keepSelection) => _turnInto(
state,
HeadingBlockKeys.type,
level: 3,
keepSelection: keepSelection,
),
);
final checkboxSuggestionItem = SuggestionItem(
type: SuggestionType.checkbox,
title: LocaleKeys.editor_checkbox.tr(),
svg: FlowySvgs.type_todo_m,
onTap: (state) => _turnInto(state, TodoListBlockKeys.type),
onTap: (state, keepSelection) => _turnInto(
state,
TodoListBlockKeys.type,
keepSelection: keepSelection,
),
);
final bulletedSuggestionItem = SuggestionItem(
type: SuggestionType.bulleted,
title: LocaleKeys.editor_bulletedListShortForm.tr(),
svg: FlowySvgs.type_bulleted_list_m,
onTap: (state) => _turnInto(state, BulletedListBlockKeys.type),
onTap: (state, keepSelection) => _turnInto(
state,
BulletedListBlockKeys.type,
keepSelection: keepSelection,
),
);
final numberedSuggestionItem = SuggestionItem(
type: SuggestionType.numbered,
title: LocaleKeys.editor_numberedListShortForm.tr(),
svg: FlowySvgs.type_numbered_list_m,
onTap: (state) => _turnInto(state, NumberedListBlockKeys.type),
onTap: (state, keepSelection) => _turnInto(
state,
NumberedListBlockKeys.type,
keepSelection: keepSelection,
),
);
final toggleSuggestionItem = SuggestionItem(
type: SuggestionType.toggle,
title: LocaleKeys.editor_toggleListShortForm.tr(),
svg: FlowySvgs.type_toggle_list_m,
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type),
onTap: (state, keepSelection) => _turnInto(
state,
ToggleListBlockKeys.type,
keepSelection: keepSelection,
),
);
final toggleH1SuggestionItem = SuggestionItem(
type: SuggestionType.toggleH1,
title: LocaleKeys.editor_toggleHeading1ShortForm.tr(),
svg: FlowySvgs.type_toggle_h1_m,
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type, level: 1),
onTap: (state, keepSelection) => _turnInto(
state,
ToggleListBlockKeys.type,
level: 1,
keepSelection: keepSelection,
),
);
final toggleH2SuggestionItem = SuggestionItem(
type: SuggestionType.toggleH2,
title: LocaleKeys.editor_toggleHeading2ShortForm.tr(),
svg: FlowySvgs.type_toggle_h2_m,
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type, level: 2),
onTap: (state, keepSelection) => _turnInto(
state,
ToggleListBlockKeys.type,
level: 2,
keepSelection: keepSelection,
),
);
final toggleH3SuggestionItem = SuggestionItem(
type: SuggestionType.toggleH3,
title: LocaleKeys.editor_toggleHeading3ShortForm.tr(),
svg: FlowySvgs.type_toggle_h3_m,
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type, level: 3),
onTap: (state, keepSelection) => _turnInto(
state,
ToggleListBlockKeys.type,
level: 3,
keepSelection: keepSelection,
),
);
final callOutSuggestionItem = SuggestionItem(
type: SuggestionType.callOut,
title: LocaleKeys.document_plugins_callout.tr(),
svg: FlowySvgs.type_callout_m,
onTap: (state) => _turnInto(state, CalloutBlockKeys.type),
onTap: (state, keepSelection) => _turnInto(
state,
CalloutBlockKeys.type,
keepSelection: keepSelection,
),
);
final quoteSuggestionItem = SuggestionItem(
type: SuggestionType.quote,
title: LocaleKeys.editor_quote.tr(),
svg: FlowySvgs.type_quote_m,
onTap: (state) => _turnInto(state, QuoteBlockKeys.type),
onTap: (state, keepSelection) => _turnInto(
state,
QuoteBlockKeys.type,
keepSelection: keepSelection,
),
);
Future<void> _turnInto(EditorState state, String type, {int? level}) async {
final pateItem = SuggestionItem(
type: SuggestionType.page,
title: LocaleKeys.editor_page.tr(),
svg: FlowySvgs.icon_document_s,
onTap: (state, keepSelection) => _turnInto(
state,
SubPageBlockKeys.type,
viewId: getIt<MenuSharedState>().latestOpenView?.id,
keepSelection: keepSelection,
),
);
Future<void> _turnInto(
EditorState state,
String type, {
int? level,
String? viewId,
bool keepSelection = true,
}) async {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
await BlockActionOptionCubit.turnIntoBlock(
@@ -413,7 +501,8 @@ Future<void> _turnInto(EditorState state, String type, {int? level}) async {
node,
state,
level: level,
keepSelection: true,
currentViewId: viewId,
keepSelection: keepSelection,
);
}
@@ -431,6 +520,7 @@ final suggestions = UnmodifiableListView([
toggleH3SuggestionItem,
callOutSuggestionItem,
quoteSuggestionItem,
pateItem,
]);
final nodeType2SuggestionType = UnmodifiableMapView({
@@ -28,6 +28,7 @@ import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:universal_platform/universal_platform.dart';
import 'editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'editor_plugins/toolbar_item/more_option_toolbar_item.dart';
class EditorStyleCustomizer {
@@ -134,6 +135,7 @@ class EditorStyleCustomizer {
textSpanDecorator: customizeAttributeDecorator,
textScaleFactor:
context.watch<AppearanceSettingsCubit>().state.textScaleFactor,
textSpanOverlayBuilder: _buildTextSpanOverlay,
);
}
@@ -468,14 +470,15 @@ class EditorStyleCustomizer {
);
}
return defaultTextSpanDecoratorForAttribute(
context,
node,
index,
text,
before,
after,
);
if (href != null) {
return TextSpan(
style: before.style,
text: text.text,
mouseCursor: SystemMouseCursors.click,
);
} else {
return before;
}
}
Widget buildToolbarItemTooltip(
@@ -590,4 +593,54 @@ class EditorStyleCustomizer {
_ => style,
};
}
List<Widget> _buildTextSpanOverlay(
BuildContext context,
Node node,
SelectableMixin delegate,
) {
final delta = node.delta;
if (delta == null) {
return [];
}
final widgets = <Widget>[];
final textInserts = delta.whereType<TextInsert>();
int index = 0;
final editorState = context.read<EditorState>();
for (final textInsert in textInserts) {
if (textInsert.attributes?.href != null) {
final nodeSelection = Selection(
start: Position(path: node.path, offset: index),
end: Position(
path: node.path,
offset: index + textInsert.length,
),
);
final rectList = delegate.getRectsInSelection(nodeSelection);
if (rectList.isNotEmpty) {
for (final rect in rectList) {
widgets.add(
Positioned(
left: rect.left,
top: rect.top,
child: SizedBox(
width: rect.width,
height: rect.height,
child: LinkHoverTrigger(
editorState: editorState,
selection: nodeSelection,
attribute: textInsert.attributes!,
node: node,
size: rect.size,
),
),
),
);
}
}
}
index += textInsert.length;
}
return widgets;
}
}
@@ -0,0 +1,44 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/cupertino.dart';
import 'package:universal_platform/universal_platform.dart';
import 'emoji_menu.dart';
const emojiCharacter = ':';
CharacterShortcutEvent emojiCommand(BuildContext context) =>
CharacterShortcutEvent(
key: 'Opens Emoji Menu',
character: emojiCharacter,
handler: (editorState) {
emojiMenuService ??= EmojiMenu(
context: context,
editorState: editorState,
);
return emojiCommandHandler(editorState, context);
},
);
EmojiMenuService? emojiMenuService;
Future<bool> emojiCommandHandler(
EditorState editorState,
BuildContext context,
) async {
final selection = editorState.selection;
if (UniversalPlatform.isMobile || selection == null) {
return false;
}
if (!selection.isCollapsed) {
await editorState.deleteSelection(selection);
}
await editorState.insertTextAtPosition(
emojiCharacter,
position: selection.start,
);
emojiMenuService?.show();
return true;
}
@@ -0,0 +1,382 @@
import 'dart:async';
import 'dart:math';
import 'package:appflowy/plugins/base/emoji/emoji_picker.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_emoji_mart/flutter_emoji_mart.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'emoji_menu.dart';
class EmojiHandler extends StatefulWidget {
const EmojiHandler({
super.key,
required this.editorState,
required this.menuService,
required this.onDismiss,
required this.onSelectionUpdate,
required this.onEmojiSelect,
this.startCharAmount = 1,
this.cancelBySpaceHandler,
});
final EditorState editorState;
final EmojiMenuService menuService;
final VoidCallback onDismiss;
final VoidCallback onSelectionUpdate;
final SelectEmojiItemHandler onEmojiSelect;
final int startCharAmount;
final bool Function()? cancelBySpaceHandler;
@override
State<EmojiHandler> createState() => _EmojiHandlerState();
}
class _EmojiHandlerState extends State<EmojiHandler> {
final _focusNode = FocusNode(debugLabel: 'emoji_menu_handler');
final ItemScrollController controller = ItemScrollController();
late EmojiData emojiData;
final List<Emoji> searchedEmojis = [];
bool loaded = false;
int invalidCounter = 0;
late int startOffset;
String _search = '';
set search(String search) {
_search = search;
_doSearch();
}
final ValueNotifier<int> _selectedIndexNotifier = ValueNotifier(0);
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => _focusNode.requestFocus(),
);
startOffset = widget.editorState.selection?.endIndex ?? 0;
if (kCachedEmojiData != null) {
loadEmojis(kCachedEmojiData!);
} else {
EmojiData.builtIn().then(
(value) {
kCachedEmojiData = value;
loadEmojis(value);
},
);
}
}
@override
void dispose() {
_focusNode.dispose();
_selectedIndexNotifier.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final noEmojis = searchedEmojis.isEmpty;
return Focus(
focusNode: _focusNode,
onKeyEvent: onKeyEvent,
child: Container(
constraints: const BoxConstraints(maxHeight: 400, maxWidth: 300),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6.0),
color: Theme.of(context).cardColor,
boxShadow: [
BoxShadow(
blurRadius: 5,
spreadRadius: 1,
color: Colors.black.withAlpha(25),
),
],
),
child: noEmojis
? SizedBox(
width: 400,
height: 40,
child: Center(
child: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(),
),
),
)
: ScrollablePositionedList.builder(
itemCount: searchedEmojis.length,
itemScrollController: controller,
padding: EdgeInsets.all(8),
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
itemBuilder: (ctx, index) {
return ValueListenableBuilder(
valueListenable: _selectedIndexNotifier,
builder: (context, value, __) {
final selectedEmoji = searchedEmojis[index];
final displayedEmoji =
emojiData.getEmojiById(selectedEmoji.id);
final isSelected = value == index;
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(
'$displayedEmoji ${selectedEmoji.name}',
lineHeight: 1.0,
overflow: TextOverflow.ellipsis,
),
isSelected: isSelected,
onTap: () => onSelect(index),
),
);
},
);
},
),
),
);
}
void changeSelectedIndex(int index) => _selectedIndexNotifier.value = index;
void loadEmojis(EmojiData data) {
emojiData = data;
searchedEmojis.clear();
searchedEmojis.addAll(emojiData.emojis.values);
if (mounted) {
setState(() {
loaded = true;
});
}
}
Future<void> _doSearch() async {
if (!loaded) return;
if (_search.startsWith(' ')) {
widget.onDismiss.call();
return;
}
final searchEmojiData = emojiData.filterByKeyword(_search);
setState(() {
searchedEmojis.clear();
searchedEmojis.addAll(searchEmojiData.emojis.values);
changeSelectedIndex(0);
});
if (searchedEmojis.isEmpty) {
widget.onDismiss.call();
}
}
KeyEventResult onKeyEvent(focus, KeyEvent event) {
if (event is! KeyDownEvent) {
return KeyEventResult.ignored;
}
const moveKeys = [
LogicalKeyboardKey.arrowUp,
LogicalKeyboardKey.arrowDown,
];
if (event.logicalKey == LogicalKeyboardKey.enter) {
onSelect(_selectedIndexNotifier.value);
return KeyEventResult.handled;
} else if (event.logicalKey == LogicalKeyboardKey.escape) {
// Workaround to bring focus back to editor
widget.editorState
.updateSelectionWithReason(widget.editorState.selection);
widget.onDismiss.call();
} else if (event.logicalKey == LogicalKeyboardKey.backspace) {
if (_search.isEmpty) {
if (_canDeleteLastCharacter()) {
widget.editorState.deleteBackward();
} else {
// Workaround for editor regaining focus
widget.editorState.apply(
widget.editorState.transaction
..afterSelection = widget.editorState.selection,
);
}
widget.onDismiss.call();
} else {
widget.onSelectionUpdate();
widget.editorState.deleteBackward();
_deleteCharacterAtSelection();
}
return KeyEventResult.handled;
} else if (event.character != null &&
![
...moveKeys,
LogicalKeyboardKey.arrowLeft,
LogicalKeyboardKey.arrowRight,
].contains(event.logicalKey)) {
/// Prevents dismissal of context menu by notifying the parent
/// that the selection change occurred from the handler.
widget.onSelectionUpdate();
if (event.logicalKey == LogicalKeyboardKey.space) {
final cancelBySpaceHandler = widget.cancelBySpaceHandler;
if (cancelBySpaceHandler != null && cancelBySpaceHandler()) {
return KeyEventResult.handled;
}
}
// Interpolation to avoid having a getter for private variable
_insertCharacter(event.character!);
return KeyEventResult.handled;
} else if (moveKeys.contains(event.logicalKey)) {
_moveSelection(event.logicalKey);
return KeyEventResult.handled;
}
if ([LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowRight]
.contains(event.logicalKey)) {
widget.onSelectionUpdate();
event.logicalKey == LogicalKeyboardKey.arrowLeft
? widget.editorState.moveCursorForward()
: widget.editorState.moveCursorBackward(SelectionMoveRange.character);
/// If cursor moves before @ then dismiss menu
/// If cursor moves after @search.length then dismiss menu
final selection = widget.editorState.selection;
if (selection != null &&
(selection.endIndex < startOffset ||
selection.endIndex > (startOffset + _search.length))) {
widget.onDismiss.call();
}
/// Workaround: When using the move cursor methods, it seems the
/// focus goes back to the editor, this makes sure this handler
/// receives the next keypress.
///
_focusNode.requestFocus();
return KeyEventResult.handled;
}
return KeyEventResult.handled;
}
void onSelect(int index) {
widget.onEmojiSelect.call(
context,
(
startOffset - widget.startCharAmount,
_search.length + widget.startCharAmount
),
emojiData.getEmojiById(searchedEmojis[index].id),
);
widget.onDismiss.call();
}
void _insertCharacter(String character) {
widget.editorState.insertTextAtCurrentSelection(character);
final selection = widget.editorState.selection;
if (selection == null || !selection.isCollapsed) {
return;
}
final delta = widget.editorState.getNodeAtPath(selection.end.path)?.delta;
if (delta == null) {
return;
}
search = widget.editorState
.getTextInSelection(
selection.copyWith(
start: selection.start.copyWith(offset: startOffset),
end: selection.start
.copyWith(offset: startOffset + _search.length + 1),
),
)
.join();
}
void _moveSelection(LogicalKeyboardKey key) {
bool didChange = false;
final index = _selectedIndexNotifier.value;
if (key == LogicalKeyboardKey.arrowUp ||
(key == LogicalKeyboardKey.tab &&
HardwareKeyboard.instance.isShiftPressed)) {
if (index == 0) {
changeSelectedIndex(max(0, searchedEmojis.length - 1));
didChange = true;
} else if (index > 0) {
changeSelectedIndex(index - 1);
didChange = true;
}
} else if ([LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.tab]
.contains(key)) {
if (index < searchedEmojis.length - 1) {
changeSelectedIndex(index + 1);
didChange = true;
} else if (index == searchedEmojis.length - 1) {
changeSelectedIndex(0);
didChange = true;
}
}
if (mounted && didChange) {
_scrollToItem();
}
}
void _scrollToItem() {
final noEmojis = searchedEmojis.isEmpty;
if (noEmojis) return;
controller.scrollTo(
index: _selectedIndexNotifier.value,
duration: const Duration(milliseconds: 200),
alignment: 0.5,
);
}
void _deleteCharacterAtSelection() {
final selection = widget.editorState.selection;
if (selection == null || !selection.isCollapsed) {
return;
}
final node = widget.editorState.getNodeAtPath(selection.end.path);
final delta = node?.delta;
if (node == null || delta == null) {
return;
}
search = delta.toPlainText().substring(
startOffset,
startOffset - 1 + _search.length,
);
}
bool _canDeleteLastCharacter() {
final selection = widget.editorState.selection;
if (selection == null || !selection.isCollapsed) {
return false;
}
final delta = widget.editorState.getNodeAtPath(selection.start.path)?.delta;
if (delta == null) {
return false;
}
return delta.isNotEmpty;
}
}
typedef SelectEmojiItemHandler = void Function(
BuildContext context,
(int start, int end) replacement,
String emoji,
);
@@ -0,0 +1,204 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'emoji_actions_command.dart';
import 'emoji_handler.dart';
abstract class EmojiMenuService {
void show();
void dismiss();
}
class EmojiMenu extends EmojiMenuService {
EmojiMenu({
required this.context,
required this.editorState,
this.startCharAmount = 1,
this.cancelBySpaceHandler,
});
final BuildContext context;
final EditorState editorState;
final bool Function()? cancelBySpaceHandler;
final int startCharAmount;
OverlayEntry? _menuEntry;
bool selectionChangedByMenu = false;
@override
void dismiss() {
if (_menuEntry != null) {
editorState.service.keyboardService?.enable();
editorState.service.scrollService?.enable();
keepEditorFocusNotifier.decrease();
}
_menuEntry?.remove();
_menuEntry = null;
// workaround: SelectionService has been released after hot reload.
final isSelectionDisposed =
editorState.service.selectionServiceKey.currentState == null;
if (!isSelectionDisposed) {
final selectionService = editorState.service.selectionService;
selectionService.currentSelection.removeListener(_onSelectionChange);
}
emojiMenuService = null;
}
void _onSelectionUpdate() => selectionChangedByMenu = true;
@override
void show() {
WidgetsBinding.instance.addPostFrameCallback((_) => _show());
}
void _show() {
final selectionService = editorState.service.selectionService;
final selectionRects = selectionService.selectionRects;
if (selectionRects.isEmpty) {
return;
}
const menuHeight = 400.0, menuWidth = 300.0;
const Offset menuOffset = Offset(0, 10);
final Offset editorOffset =
editorState.renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final Size editorSize = editorState.renderBox!.size;
final editorHeight = editorSize.height, editorWidth = editorSize.width;
// Default to opening the overlay below
Alignment alignment = Alignment.topLeft;
final firstRect = selectionRects.first;
Offset offset = firstRect.bottomRight + menuOffset;
// Show above
if (offset.dy + menuHeight >= editorOffset.dy + editorSize.height) {
offset = firstRect.topRight - menuOffset;
alignment = Alignment.bottomLeft;
offset = Offset(
offset.dx,
editorHeight - offset.dy,
);
}
// Show on the left
if (offset.dx > (editorWidth - menuWidth)) {
alignment = alignment == Alignment.topLeft
? Alignment.topRight
: Alignment.bottomRight;
offset = Offset(
editorWidth - offset.dx,
offset.dy,
);
}
final (left, top, right, bottom) = _getPosition(alignment, offset);
_menuEntry = OverlayEntry(
builder: (context) => SizedBox(
height: editorSize.height,
width: editorSize.width,
// GestureDetector handles clicks outside of the context menu,
// to dismiss the context menu.
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: dismiss,
child: Stack(
children: [
Positioned(
top: top,
bottom: bottom,
left: left,
right: right,
child: EmojiHandler(
editorState: editorState,
menuService: this,
onDismiss: dismiss,
onSelectionUpdate: _onSelectionUpdate,
startCharAmount: startCharAmount,
cancelBySpaceHandler: cancelBySpaceHandler,
onEmojiSelect: (
BuildContext context,
(int, int) replacement,
String emoji,
) async {
final selection = editorState.selection;
if (selection == null) return;
final node =
editorState.document.nodeAtPath(selection.end.path);
if (node == null) return;
final transaction = editorState.transaction
..replaceText(
node,
replacement.$1,
replacement.$2,
emoji,
);
await editorState.apply(transaction);
},
),
),
],
),
),
),
);
Overlay.of(context).insert(_menuEntry!);
editorState.service.keyboardService?.disable(showCursor: true);
editorState.service.scrollService?.disable();
selectionService.currentSelection.addListener(_onSelectionChange);
}
void _onSelectionChange() {
// workaround: SelectionService has been released after hot reload.
final isSelectionDisposed =
editorState.service.selectionServiceKey.currentState == null;
if (!isSelectionDisposed) {
final selectionService = editorState.service.selectionService;
if (selectionService.currentSelection.value == null) {
return;
}
}
if (!selectionChangedByMenu) {
return dismiss();
}
selectionChangedByMenu = false;
}
(double? left, double? top, double? right, double? bottom) _getPosition(
Alignment alignment,
Offset offset,
) {
double? left, top, right, bottom;
switch (alignment) {
case Alignment.topLeft:
left = offset.dx;
top = offset.dy;
break;
case Alignment.bottomLeft:
left = offset.dx;
bottom = offset.dy;
break;
case Alignment.topRight:
right = offset.dx;
top = offset.dy;
break;
case Alignment.bottomRight:
right = offset.dx;
bottom = offset.dy;
break;
}
return (left, top, right, bottom);
}
}
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:io';
import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/util/expand_views.dart';
import 'package:appflowy/workspace/application/settings/prelude.dart';
import 'package:appflowy_backend/appflowy_backend.dart';
@@ -119,7 +120,7 @@ class FlowyRunner {
// this task should be second task, for handling memory leak.
// there's a flag named _enable in memory_leak_detector.dart. If it's false, the task will be ignored.
MemoryLeakDetectorTask(),
const DebugTask(),
DebugTask(),
const FeatureFlagTask(),
// localization
@@ -185,6 +186,7 @@ Future<void> initGetIt(
);
getIt.registerSingleton<PluginSandbox>(PluginSandbox());
getIt.registerSingleton<ViewExpanderRegistry>(ViewExpanderRegistry());
getIt.registerSingleton<LinkHoverTriggers>(LinkHoverTriggers());
await DependencyResolver.resolve(getIt, mode);
}
@@ -17,7 +17,6 @@ import 'package:appflowy/workspace/application/sidebar/rename_view/rename_view_b
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/presentation/command_palette/command_palette.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:easy_localization/easy_localization.dart';
@@ -64,7 +63,6 @@ class InitAppWidgetTask extends LaunchTask {
child: widget,
);
Bloc.observer = ApplicationBlocObserver();
runApp(
EasyLocalization(
supportedLocales: const [
@@ -283,14 +281,6 @@ class AppGlobals {
static BuildContext get context => rootNavKey.currentContext!;
}
class ApplicationBlocObserver extends BlocObserver {
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
Log.debug(error);
super.onError(bloc, error, stackTrace);
}
}
Future<AppTheme> appTheme(String themeName) async {
if (themeName.isEmpty) {
return AppTheme.fallback;
@@ -1,18 +1,45 @@
import 'package:appflowy/startup/startup.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:talker/talker.dart';
import 'package:talker_bloc_logger/talker_bloc_logger.dart';
import 'package:universal_platform/universal_platform.dart';
import '../startup.dart';
class DebugTask extends LaunchTask {
const DebugTask();
DebugTask();
final Talker talker = Talker();
@override
Future<void> initialize(LaunchContext context) async {
// the hotkey manager is not supported on mobile
// hide the keyboard on mobile
if (UniversalPlatform.isMobile && kDebugMode) {
await SystemChannels.textInput.invokeMethod('TextInput.hide');
}
// log the bloc events
if (kDebugMode) {
Bloc.observer = TalkerBlocObserver(
talker: talker,
settings: TalkerBlocLoggerSettings(
// Disabled by default to prevent mixing with AppFlowy logs
// Enable to observe all bloc events
enabled: false,
printEventFullData: false,
printStateFullData: false,
printChanges: true,
printClosings: true,
printCreations: true,
transitionFilter: (_, transition) {
// By default, observe all transitions
// You can add your own filter here if needed
// when you want to observer a specific bloc
return true;
},
),
);
}
}
@override
@@ -29,6 +29,9 @@ class ApplicationInfo {
// If the latest version is greater than the current version, it means there is an update available
static bool get isUpdateAvailable {
try {
if (latestVersion.isEmpty) {
return false;
}
return Version.parse(latestVersion) > Version.parse(applicationVersion);
} catch (e) {
return false;
@@ -16,6 +16,10 @@ class Throttler {
});
}
void cancel() {
_timer?.cancel();
}
void dispose() {
_timer?.cancel();
_timer = null;
@@ -1,41 +0,0 @@
import 'dart:async';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:url_launcher/url_launcher.dart' show launchUrl;
part 'download_offline_ai_app_bloc.freezed.dart';
class DownloadOfflineAIBloc
extends Bloc<DownloadOfflineAIEvent, DownloadOfflineAIState> {
DownloadOfflineAIBloc() : super(const DownloadOfflineAIState()) {
on<DownloadOfflineAIEvent>(_handleEvent);
}
Future<void> _handleEvent(
DownloadOfflineAIEvent event,
Emitter<DownloadOfflineAIState> emit,
) async {
await event.when(
started: () async {
final result = await AIEventGetLocalAIDownloadLink().send();
await result.fold(
(app) async {
await launchUrl(Uri.parse(app.link));
},
(err) {},
);
},
);
}
}
@freezed
class DownloadOfflineAIEvent with _$DownloadOfflineAIEvent {
const factory DownloadOfflineAIEvent.started() = _Started;
}
@freezed
class DownloadOfflineAIState with _$DownloadOfflineAIState {
const factory DownloadOfflineAIState() = _DownloadOfflineAIState;
}
@@ -44,7 +44,7 @@ class LocalAISettingPanelBloc
) async {
event.when(
updateAIState: (LocalAIPB pluginState) {
if (pluginState.isPluginExecutableReady) {
if (pluginState.pluginDownloaded) {
emit(
state.copyWith(
runningState: pluginState.state,
@@ -91,7 +91,11 @@ class PluginStateBloc extends Bloc<PluginStateEvent, PluginStateState> {
);
break;
case RunningStatePB.Running:
emit(const PluginStateState(action: PluginStateAction.running()));
emit(
PluginStateState(
action: PluginStateAction.running(aiState.pluginVersion),
),
);
break;
case RunningStatePB.Stopped:
emit(
@@ -140,7 +144,7 @@ class PluginStateAction with _$PluginStateAction {
const factory PluginStateAction.unknown() = _Unknown;
const factory PluginStateAction.readToRun() = _ReadyToRun;
const factory PluginStateAction.initializingPlugin() = _InitializingPlugin;
const factory PluginStateAction.running() = _PluginRunning;
const factory PluginStateAction.running(String version) = _PluginRunning;
const factory PluginStateAction.restartPlugin() = _RestartPlugin;
const factory PluginStateAction.lackOfResource(String desc) = _LackOfResource;
}
@@ -1,9 +1,8 @@
import 'dart:convert';
import 'package:appflowy/plugins/ai_chat/application/ai_model_switch_listener.dart';
import 'package:appflowy/user/application/user_listener.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
@@ -11,48 +10,40 @@ import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'settings_ai_bloc.freezed.dart';
part 'settings_ai_bloc.g.dart';
const String aiModelsGlobalActiveModel = "ai_models_global_active_model";
class SettingsAIBloc extends Bloc<SettingsAIEvent, SettingsAIState> {
SettingsAIBloc(
this.userProfile,
this.workspaceId,
AFRolePB? currentWorkspaceMemberRole,
) : _userListener = UserListener(userProfile: userProfile),
_userService = UserBackendService(userId: userProfile.id),
_aiModelSwitchListener =
AIModelSwitchListener(objectId: aiModelsGlobalActiveModel),
super(
SettingsAIState(
selectedAIModel: userProfile.aiModel,
userProfile: userProfile,
currentWorkspaceMemberRole: currentWorkspaceMemberRole,
),
) {
_aiModelSwitchListener.start(
onUpdateSelectedModel: (model) {
if (!isClosed) {
_loadModelList();
}
},
);
_dispatch();
if (currentWorkspaceMemberRole == null) {
_userService.getWorkspaceMember().then((result) {
result.fold(
(member) {
if (!isClosed) {
add(SettingsAIEvent.refreshMember(member));
}
},
(err) {
Log.error(err);
},
);
});
}
}
final UserListener _userListener;
final UserProfilePB userProfile;
final UserBackendService _userService;
final String workspaceId;
final AIModelSwitchListener _aiModelSwitchListener;
@override
Future<void> close() async {
await _userListener.stop();
await _aiModelSwitchListener.stop();
return super.close();
}
@@ -68,8 +59,8 @@ class SettingsAIBloc extends Bloc<SettingsAIEvent, SettingsAIState> {
}
},
);
_loadUserWorkspaceSetting();
_loadModelList();
_loadUserWorkspaceSetting();
},
didReceiveUserProfile: (userProfile) {
emit(state.copyWith(userProfile: userProfile));
@@ -83,48 +74,31 @@ class SettingsAIBloc extends Bloc<SettingsAIEvent, SettingsAIState> {
!(state.aiSettings?.disableSearchIndexing ?? false),
);
},
selectModel: (String model) async {
await _updateUserWorkspaceSetting(model: model);
selectModel: (AIModelPB model) async {
if (!model.isLocal) {
await _updateUserWorkspaceSetting(model: model.name);
}
await AIEventUpdateSelectedModel(
UpdateSelectedModelPB(
source: aiModelsGlobalActiveModel,
selectedModel: model,
),
).send();
},
didLoadAISetting: (UseAISettingPB settings) {
emit(
state.copyWith(
aiSettings: settings,
selectedAIModel: settings.aiModel,
enableSearchIndexing: !settings.disableSearchIndexing,
),
);
},
didLoadAvailableModels: (String models) {
final dynamic decodedJson = jsonDecode(models);
Log.info("Available models: $decodedJson");
if (decodedJson is Map<String, dynamic>) {
final models = ModelList.fromJson(decodedJson).models;
if (models.isEmpty) {
// If available models is empty, then we just show the
// Default
emit(state.copyWith(availableModels: ["Default"]));
return;
}
if (!models.contains(state.selectedAIModel)) {
// Use first model as default model if current selected model
// is not available
final selectedModel = models[0];
_updateUserWorkspaceSetting(model: selectedModel);
emit(
state.copyWith(
availableModels: models,
selectedAIModel: selectedModel,
),
);
} else {
emit(state.copyWith(availableModels: models));
}
}
},
refreshMember: (member) {
emit(state.copyWith(currentWorkspaceMemberRole: member.role));
didLoadAvailableModels: (AvailableModelsPB models) {
emit(
state.copyWith(
availableModels: models,
),
);
},
);
});
@@ -159,12 +133,11 @@ class SettingsAIBloc extends Bloc<SettingsAIEvent, SettingsAIState> {
(err) => Log.error(err),
);
void _loadUserWorkspaceSetting() {
final payload = UserWorkspaceIdPB(workspaceId: workspaceId);
UserEventGetWorkspaceSetting(payload).send().then((result) {
result.fold((settings) {
void _loadModelList() {
AIEventGetServerAvailableModels().send().then((result) {
result.fold((models) {
if (!isClosed) {
add(SettingsAIEvent.didLoadAISetting(settings));
add(SettingsAIEvent.didLoadAvailableModels(models));
}
}, (err) {
Log.error(err);
@@ -172,11 +145,12 @@ class SettingsAIBloc extends Bloc<SettingsAIEvent, SettingsAIState> {
});
}
void _loadModelList() {
AIEventGetAvailableModels().send().then((result) {
result.fold((config) {
void _loadUserWorkspaceSetting() {
final payload = UserWorkspaceIdPB(workspaceId: workspaceId);
UserEventGetWorkspaceSetting(payload).send().then((result) {
result.fold((settings) {
if (!isClosed) {
add(SettingsAIEvent.didLoadAvailableModels(config.models));
add(SettingsAIEvent.didLoadAISetting(settings));
}
}, (err) {
Log.error(err);
@@ -193,17 +167,15 @@ class SettingsAIEvent with _$SettingsAIEvent {
) = _DidLoadWorkspaceSetting;
const factory SettingsAIEvent.toggleAISearch() = _toggleAISearch;
const factory SettingsAIEvent.refreshMember(WorkspaceMemberPB member) =
_RefreshMember;
const factory SettingsAIEvent.selectModel(String model) = _SelectAIModel;
const factory SettingsAIEvent.selectModel(AIModelPB model) = _SelectAIModel;
const factory SettingsAIEvent.didReceiveUserProfile(
UserProfilePB newUserProfile,
) = _DidReceiveUserProfile;
const factory SettingsAIEvent.didLoadAvailableModels(
String models,
AvailableModelsPB models,
) = _DidLoadAvailableModels;
}
@@ -212,23 +184,7 @@ class SettingsAIState with _$SettingsAIState {
const factory SettingsAIState({
required UserProfilePB userProfile,
UseAISettingPB? aiSettings,
@Default("Default") String selectedAIModel,
AFRolePB? currentWorkspaceMemberRole,
@Default(["Default"]) List<String> availableModels,
AvailableModelsPB? availableModels,
@Default(true) bool enableSearchIndexing,
}) = _SettingsAIState;
}
@JsonSerializable()
class ModelList {
ModelList({
required this.models,
});
factory ModelList.fromJson(Map<String, dynamic> json) =>
_$ModelListFromJson(json);
final List<String> models;
Map<String, dynamic> toJson() => _$ModelListToJson(this);
}
@@ -2,6 +2,7 @@ import 'package:appflowy/workspace/application/settings/appearance/base_appearan
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flutter/material.dart';
class DesktopAppearance extends BaseAppearance {
@@ -14,9 +15,8 @@ class DesktopAppearance extends BaseAppearance {
) {
assert(codeFontFamily.isNotEmpty);
final theme = brightness == Brightness.light
? appTheme.lightTheme
: appTheme.darkTheme;
final isLight = brightness == Brightness.light;
final theme = isLight ? appTheme.lightTheme : appTheme.darkTheme;
final colorScheme = ColorScheme(
brightness: brightness,
@@ -152,6 +152,11 @@ class DesktopAppearance extends BaseAppearance {
lightIconColor: theme.lightIconColor,
toolbarHoverColor: theme.toolbarHoverColor,
),
isLight
? lightAFThemeV2
: darkAFThemeV2.copyWith(
icon_primary: theme.icon,
),
],
);
}
@@ -331,16 +331,6 @@ class SpaceBloc extends Bloc<SpaceEvent, SpaceState> {
final (spaces, _, _) = await _getSpaces();
final currentSpace = await _getLastOpenedSpace(spaces);
Log.info(
'receive space update, current space: ${currentSpace?.name}(${currentSpace?.id})',
);
for (var i = 0; i < spaces.length; i++) {
Log.info(
'receive space update[$i]: ${spaces[i].name}(${spaces[i].id})',
);
}
emit(
state.copyWith(
spaces: spaces,
@@ -496,7 +486,6 @@ class SpaceBloc extends Bloc<SpaceEvent, SpaceState> {
}
void _initial(UserProfilePB userProfile, String workspaceId) {
Log.info('initial(or reset) space bloc: $workspaceId, ${userProfile.id}');
_workspaceService = WorkspaceService(workspaceId: workspaceId);
this.userProfile = userProfile;
@@ -507,7 +496,6 @@ class SpaceBloc extends Bloc<SpaceEvent, SpaceState> {
workspaceId: workspaceId,
)..start(
sectionChanged: (result) async {
Log.info('did receive section views changed');
if (isClosed) {
return;
}
@@ -84,7 +84,7 @@ class LocalAISettingHeader extends StatelessWidget {
children: [
Row(
children: [
FlowyText(
FlowyText.medium(
LocaleKeys.settings_aiPage_keys_localAIToggleTitle.tr(),
),
const Spacer(),
@@ -1,3 +1,5 @@
import 'package:appflowy/ai/ai.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
@@ -10,11 +12,21 @@ import 'package:flutter_bloc/flutter_bloc.dart';
class AIModelSelection extends StatelessWidget {
const AIModelSelection({super.key});
static const double height = 49;
@override
Widget build(BuildContext context) {
return BlocBuilder<SettingsAIBloc, SettingsAIState>(
buildWhen: (previous, current) =>
previous.availableModels != current.availableModels,
builder: (context, state) {
if (state.availableModels == null) {
return const SizedBox(
// Using same height as SettingsDropdown to avoid layout shift
height: height,
);
}
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
@@ -28,18 +40,20 @@ class AIModelSelection extends StatelessWidget {
),
const Spacer(),
Flexible(
child: SettingsDropdown<String>(
child: SettingsDropdown<AIModelPB>(
key: const Key('_AIModelSelection'),
onChanged: (model) => context
.read<SettingsAIBloc>()
.add(SettingsAIEvent.selectModel(model)),
selectedOption: state.selectedAIModel,
options: state.availableModels
selectedOption: state.availableModels!.selectedModel,
options: state.availableModels!.models
.map(
(model) => buildDropdownMenuEntry<String>(
(model) => buildDropdownMenuEntry<AIModelPB>(
context,
value: model,
label: model,
label: model.i18n,
subLabel: model.desc,
maximumHeight: height,
),
)
.toList(),
@@ -1,15 +1,11 @@
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/ai/download_offline_ai_app_bloc.dart';
import 'package:appflowy/workspace/application/settings/ai/plugin_state_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/pages/setting_ai_view/init_local_ai.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -27,7 +23,10 @@ class PluginStateIndicator extends StatelessWidget {
unknown: () => const SizedBox.shrink(),
readToRun: () => const _PrepareRunning(),
initializingPlugin: () => const InitLocalAIIndicator(),
running: () => const _LocalAIRunning(),
running: (version) => _LocalAIRunning(
key: ValueKey(version),
version: version,
),
restartPlugin: () => const _RestartPluginButton(),
lackOfResource: (desc) => _LackOfResource(desc: desc),
);
@@ -88,7 +87,9 @@ class _RestartPluginButton extends StatelessWidget {
}
class _LocalAIRunning extends StatelessWidget {
const _LocalAIRunning();
const _LocalAIRunning({required this.version, super.key});
final String version;
@override
Widget build(BuildContext context) {
@@ -113,6 +114,14 @@ class _LocalAIRunning extends StatelessWidget {
color: Color(0xFF2E7D32),
),
const HSpace(6),
if (version.isNotEmpty)
Flexible(
child: FlowyText(
"($version) ",
fontSize: 11,
color: const Color(0xFF1E4620),
),
),
Flexible(
child: FlowyText(
LocaleKeys.settings_aiPage_keys_localAIRunning.tr(),
@@ -131,95 +140,6 @@ class _LocalAIRunning extends StatelessWidget {
}
}
class OpenOrDownloadOfflineAIApp extends StatelessWidget {
const OpenOrDownloadOfflineAIApp({required this.onRetry, super.key});
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => DownloadOfflineAIBloc(),
child: BlocBuilder<DownloadOfflineAIBloc, DownloadOfflineAIState>(
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
maxLines: 3,
textAlign: TextAlign.left,
text: TextSpan(
children: <TextSpan>[
TextSpan(
text:
"${LocaleKeys.settings_aiPage_keys_offlineAIInstruction1.tr()} ",
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(height: 1.5),
),
TextSpan(
text:
" ${LocaleKeys.settings_aiPage_keys_offlineAIInstruction2.tr()} ",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: FontSizes.s14,
color: Theme.of(context).colorScheme.primary,
height: 1.5,
),
recognizer: TapGestureRecognizer()
..onTap = () => afLaunchUrlString(
"https://docs.appflowy.io/docs/appflowy/product/appflowy-ai-offline",
),
),
TextSpan(
text:
" ${LocaleKeys.settings_aiPage_keys_offlineAIInstruction3.tr()} ",
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(height: 1.5),
),
TextSpan(
text:
"${LocaleKeys.settings_aiPage_keys_offlineAIDownload1.tr()} ",
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(height: 1.5),
),
TextSpan(
text:
" ${LocaleKeys.settings_aiPage_keys_offlineAIDownload2.tr()} ",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: FontSizes.s14,
color: Theme.of(context).colorScheme.primary,
height: 1.5,
),
recognizer: TapGestureRecognizer()
..onTap =
() => context.read<DownloadOfflineAIBloc>().add(
const DownloadOfflineAIEvent.started(),
),
),
TextSpan(
text:
" ${LocaleKeys.settings_aiPage_keys_offlineAIDownload3.tr()} ",
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(height: 1.5),
),
],
),
),
],
);
},
),
);
}
}
class _LackOfResource extends StatelessWidget {
const _LackOfResource({required this.desc});
@@ -42,25 +42,16 @@ class SettingsAIView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider<SettingsAIBloc>(
create: (_) =>
SettingsAIBloc(userProfile, workspaceId, currentWorkspaceMemberRole)
..add(const SettingsAIEvent.started()),
child: BlocBuilder<SettingsAIBloc, SettingsAIState>(
builder: (context, state) {
final children = <Widget>[
const AIModelSelection(),
];
children.add(const _AISearchToggle(value: false));
children.add(const LocalAISetting());
return SettingsBody(
title: LocaleKeys.settings_aiPage_title.tr(),
description:
LocaleKeys.settings_aiPage_keys_aiSettingsDescription.tr(),
children: children,
);
},
create: (_) => SettingsAIBloc(userProfile, workspaceId)
..add(const SettingsAIEvent.started()),
child: SettingsBody(
title: LocaleKeys.settings_aiPage_title.tr(),
description: LocaleKeys.settings_aiPage_keys_aiSettingsDescription.tr(),
children: [
const AIModelSelection(),
const _AISearchToggle(value: false),
const LocalAISetting(),
],
),
);
}
@@ -141,7 +141,7 @@ class SettingsDialog extends StatelessWidget {
case SettingsPage.ai:
if (user.authenticator == AuthenticatorPB.AppFlowyCloud) {
return SettingsAIView(
key: ValueKey(user.hashCode),
key: ValueKey(workspaceId),
userProfile: user,
currentWorkspaceMemberRole: currentWorkspaceMemberRole,
workspaceId: workspaceId,
@@ -9,14 +9,40 @@ DropdownMenuEntry<T> buildDropdownMenuEntry<T>(
BuildContext context, {
required T value,
required String label,
String subLabel = '',
T? selectedValue,
Widget? leadingWidget,
Widget? trailingWidget,
String? fontFamily,
double maximumHeight = 29,
}) {
final fontFamilyUsed = fontFamily != null
? getGoogleFontSafely(fontFamily).fontFamily ?? defaultFontFamily
: defaultFontFamily;
Widget? labelWidget;
if (subLabel.isNotEmpty) {
labelWidget = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.regular(
label,
fontSize: 14,
),
const VSpace(4),
FlowyText.regular(
subLabel,
fontSize: 10,
),
],
);
} else {
labelWidget = FlowyText.regular(
label,
fontSize: 14,
textAlign: TextAlign.start,
fontFamily: fontFamilyUsed,
);
}
return DropdownMenuEntry<T>(
style: ButtonStyle(
@@ -26,17 +52,12 @@ DropdownMenuEntry<T> buildDropdownMenuEntry<T>(
const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
),
minimumSize: const WidgetStatePropertyAll(Size(double.infinity, 29)),
maximumSize: const WidgetStatePropertyAll(Size(double.infinity, 29)),
maximumSize: WidgetStatePropertyAll(Size(double.infinity, maximumHeight)),
),
value: value,
label: label,
leadingIcon: leadingWidget,
labelWidget: FlowyText.regular(
label,
fontSize: 14,
textAlign: TextAlign.start,
fontFamily: fontFamilyUsed,
),
labelWidget: labelWidget,
trailingIcon: Row(
children: [
if (trailingWidget != null) ...[
@@ -23,6 +23,7 @@ abstract class AppFlowyDatePicker extends StatefulWidget {
this.onIncludeTimeChanged,
this.onIsRangeChanged,
this.onReminderSelected,
this.enableDidUpdate = true,
});
final DateTime? dateTime;
@@ -55,6 +56,7 @@ abstract class AppFlowyDatePicker extends StatefulWidget {
final ReminderOption reminderOption;
final OnReminderSelected? onReminderSelected;
final bool enableDidUpdate;
}
abstract class AppFlowyDatePickerState<T extends AppFlowyDatePicker>
@@ -75,34 +77,31 @@ abstract class AppFlowyDatePickerState<T extends AppFlowyDatePicker>
@override
void initState() {
super.initState();
dateTime = widget.dateTime;
startDateTime = widget.isRange ? widget.dateTime : null;
endDateTime = widget.isRange ? widget.endDateTime : null;
includeTime = widget.includeTime;
isRange = widget.isRange;
reminderOption = widget.reminderOption;
initData();
focusedDateTime = widget.dateTime ?? DateTime.now();
}
@override
void didUpdateWidget(covariant oldWidget) {
dateTime = widget.dateTime;
if (widget.isRange) {
startDateTime = widget.dateTime;
endDateTime = widget.endDateTime;
} else {
startDateTime = endDateTime = null;
if (widget.enableDidUpdate) {
initData();
}
includeTime = widget.includeTime;
isRange = widget.isRange;
if (oldWidget.reminderOption != widget.reminderOption) {
reminderOption = widget.reminderOption;
}
super.didUpdateWidget(oldWidget);
}
void initData() {
dateTime = widget.dateTime;
startDateTime = widget.isRange ? widget.dateTime : null;
endDateTime = widget.isRange ? widget.endDateTime : null;
includeTime = widget.includeTime;
isRange = widget.isRange;
reminderOption = widget.reminderOption;
}
void onDateSelectedFromDatePicker(
DateTime? newStartDateTime,
DateTime? newEndDateTime,
@@ -32,6 +32,7 @@ class DesktopAppFlowyDatePicker extends AppFlowyDatePicker {
super.onIncludeTimeChanged,
super.onIsRangeChanged,
super.onReminderSelected,
super.enableDidUpdate,
this.popoverMutex,
this.options = const [],
});
@@ -16,7 +16,6 @@ import 'package:flutter/services.dart';
class DatePickerOptions {
DatePickerOptions({
DateTime? focusedDay,
this.popoverMutex,
this.selectedDay,
this.includeTime = false,
this.isRange = false,
@@ -31,7 +30,6 @@ class DatePickerOptions {
}) : focusedDay = focusedDay ?? DateTime.now();
final DateTime focusedDay;
final PopoverMutex? popoverMutex;
final DateTime? selectedDay;
final bool includeTime;
final bool isRange;
@@ -48,6 +46,7 @@ class DatePickerOptions {
abstract class DatePickerService {
void show(Offset offset, {required DatePickerOptions options});
void dismiss();
}
@@ -60,6 +59,7 @@ class DatePickerMenu extends DatePickerService {
final BuildContext context;
final EditorState editorState;
PopoverMutex? popoverMutex;
OverlayEntry? _menuEntry;
@@ -67,6 +67,9 @@ class DatePickerMenu extends DatePickerService {
void dismiss() {
_menuEntry?.remove();
_menuEntry = null;
popoverMutex?.close();
popoverMutex?.dispose();
popoverMutex = null;
}
@override
@@ -97,6 +100,7 @@ class DatePickerMenu extends DatePickerService {
}
}
popoverMutex = PopoverMutex();
_menuEntry = OverlayEntry(
builder: (_) => Material(
type: MaterialType.transparency,
@@ -119,6 +123,7 @@ class DatePickerMenu extends DatePickerService {
offset: Offset(offsetX, offsetY),
showBelow: showBelow,
options: options,
popoverMutex: popoverMutex,
),
],
),
@@ -137,11 +142,13 @@ class _AnimatedDatePicker extends StatelessWidget {
required this.offset,
required this.showBelow,
required this.options,
this.popoverMutex,
});
final Offset offset;
final bool showBelow;
final DatePickerOptions options;
final PopoverMutex? popoverMutex;
@override
Widget build(BuildContext context) {
@@ -165,11 +172,12 @@ class _AnimatedDatePicker extends StatelessWidget {
dateFormat: options.dateFormat.simplified,
timeFormat: options.timeFormat.simplified,
dateTime: options.selectedDay,
popoverMutex: options.popoverMutex,
popoverMutex: popoverMutex,
reminderOption: options.selectedReminderOption ?? ReminderOption.none,
onDaySelected: options.onDaySelected,
onRangeSelected: options.onRangeSelected,
onReminderSelected: options.onReminderSelected,
enableDidUpdate: false,
),
),
);
@@ -1,9 +1,13 @@
import Cocoa
import FlutterMacOS
@NSApplicationMain
@main
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}
@@ -4,11 +4,11 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:ffi/ffi.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'ffi.dart' as ffi;
@@ -62,28 +62,15 @@ class RustLogStreamReceiver {
late StreamController<Uint8List> _streamController;
late StreamSubscription<Uint8List> _subscription;
int get port => _ffiPort.sendPort.nativePort;
late Logger _logger;
RustLogStreamReceiver._internal() {
_ffiPort = RawReceivePort();
_streamController = StreamController();
_ffiPort.handler = _streamController.add;
_logger = Logger(
printer: PrettyPrinter(
methodCount: 0, // number of method calls to be displayed
errorMethodCount: 8, // number of method calls if stacktrace is provided
lineLength: 120, // width of the output
colors: false, // Colorful log messages
printEmojis: false, // Print an emoji for each log message
dateTimeFormat:
DateTimeFormat.none, // Should each log print contain a timestamp
),
level: kDebugMode ? Level.trace : Level.info,
);
_subscription = _streamController.stream.listen((data) {
String decodedString = utf8.decode(data);
_logger.i(decodedString);
Log.info(decodedString);
});
}
@@ -3,64 +3,43 @@ import 'dart:ffi';
import 'package:ffi/ffi.dart' as ffi;
import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
import 'package:talker/talker.dart';
import 'ffi.dart';
class Log {
static final shared = Log();
// ignore: unused_field
late Logger _logger;
bool _enabled = false;
late Talker _logger;
bool enableFlutterLog = true;
// used to disable log in tests
@visibleForTesting
bool disableLog = false;
Log() {
_logger = Logger(
printer: PrettyPrinter(
methodCount: 2, // Number of method calls to be displayed
errorMethodCount: 8, // Number of method calls if stacktrace is provided
lineLength: 120, // Width of the output
colors: true, // Colorful log messages
printEmojis: true, // Print an emoji for each log message
),
level: kDebugMode ? Level.trace : Level.info,
_logger = Talker(
filter: LogLevelTalkerFilter(),
);
}
static void enableFlutterLog() {
shared._enabled = true;
}
// Generic internal logging function to reduce code duplication
static void _log(Level level, int rustLevel, dynamic msg,
[dynamic error, StackTrace? stackTrace]) {
if (shared._enabled) {
switch (level) {
case Level.info:
shared._logger.i(msg, stackTrace: stackTrace);
break;
case Level.debug:
shared._logger.d(msg, stackTrace: stackTrace);
break;
case Level.warning:
shared._logger.w(msg, stackTrace: stackTrace);
break;
case Level.error:
shared._logger.e(msg, stackTrace: stackTrace);
break;
case Level.trace:
shared._logger.t(msg, stackTrace: stackTrace);
break;
default:
shared._logger.log(level, msg, stackTrace: stackTrace);
}
static void _log(
LogLevel level,
int rustLevel,
dynamic msg, [
dynamic error,
StackTrace? stackTrace,
]) {
// only forward logs to flutter in debug mode, otherwise log to rust to
// persist logs in the file system
if (shared.enableFlutterLog && kDebugMode) {
shared._logger.log(msg, logLevel: level, stackTrace: stackTrace);
} else {
String formattedMessage = _formatMessageWithStackTrace(msg, stackTrace);
rust_log(rustLevel, toNativeUtf8(formattedMessage));
}
String formattedMessage = _formatMessageWithStackTrace(msg, stackTrace);
rust_log(rustLevel, toNativeUtf8(formattedMessage));
}
static void info(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
@@ -68,7 +47,7 @@ class Log {
return;
}
_log(Level.info, 0, msg, error, stackTrace);
_log(LogLevel.info, 0, msg, error, stackTrace);
}
static void debug(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
@@ -76,7 +55,7 @@ class Log {
return;
}
_log(Level.debug, 1, msg, error, stackTrace);
_log(LogLevel.debug, 1, msg, error, stackTrace);
}
static void warn(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
@@ -84,7 +63,7 @@ class Log {
return;
}
_log(Level.warning, 3, msg, error, stackTrace);
_log(LogLevel.warning, 3, msg, error, stackTrace);
}
static void trace(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
@@ -92,7 +71,7 @@ class Log {
return;
}
_log(Level.trace, 2, msg, error, stackTrace);
_log(LogLevel.verbose, 2, msg, error, stackTrace);
}
static void error(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
@@ -100,7 +79,7 @@ class Log {
return;
}
_log(Level.error, 4, msg, error, stackTrace);
_log(LogLevel.error, 4, msg, error, stackTrace);
}
}
@@ -119,3 +98,11 @@ String _formatMessageWithStackTrace(dynamic msg, StackTrace? stackTrace) {
}
return msg.toString();
}
class LogLevelTalkerFilter implements TalkerFilter {
@override
bool filter(TalkerData data) {
// filter out the debug logs in release mode
return kDebugMode ? true : data.logLevel != LogLevel.debug;
}
}
@@ -14,7 +14,7 @@ dependencies:
ffi: ^2.0.2
isolates: ^3.0.3+8
protobuf: ^3.1.0
logger: ^2.4.0
talker: ^4.7.1
plugin_platform_interface: ^2.1.3
appflowy_result:
path: ../appflowy_result
@@ -1,7 +1,7 @@
name: appflowy_result
description: "A new Flutter package project."
version: 0.0.1
homepage:
homepage: https://github.com/appflowy-io/appflowy
environment:
sdk: ">=3.3.0 <4.0.0"
@@ -9,40 +9,3 @@ environment:
dev_dependencies:
flutter_lints: ^3.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# To add assets to your package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# To add custom fonts to your package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
@@ -0,0 +1,91 @@
// ignore_for_file: non_constant_identifier_names
import 'package:flutter/material.dart';
@immutable
class AFThemeExtensionV2 extends ThemeExtension<AFThemeExtensionV2> {
static AFThemeExtensionV2 of(BuildContext context) =>
Theme.of(context).extension<AFThemeExtensionV2>()!;
static AFThemeExtensionV2? maybeOf(BuildContext context) =>
Theme.of(context).extension<AFThemeExtensionV2>();
const AFThemeExtensionV2({
required this.icon_primary,
required this.icon_tertiary,
required this.border_grey_quaternary,
required this.fill_theme_select,
required this.fill_grey_thick_alpha_1,
required this.shadow_medium,
});
final Color icon_primary;
final Color icon_tertiary;
final Color border_grey_quaternary;
final Color fill_theme_select;
final Color fill_grey_thick_alpha_1;
final Color shadow_medium;
@override
AFThemeExtensionV2 copyWith({
Color? icon_primary,
Color? icon_tertiary,
Color? border_grey_quaternary,
Color? fill_theme_select,
Color? fill_grey_thick_alpha_1,
Color? shadow_medium,
}) =>
AFThemeExtensionV2(
icon_primary: icon_primary ?? this.icon_primary,
icon_tertiary: icon_tertiary ?? this.icon_tertiary,
border_grey_quaternary:
border_grey_quaternary ?? this.border_grey_quaternary,
fill_theme_select: fill_theme_select ?? this.fill_theme_select,
fill_grey_thick_alpha_1:
fill_grey_thick_alpha_1 ?? this.fill_grey_thick_alpha_1,
shadow_medium: shadow_medium ?? this.shadow_medium,
);
@override
ThemeExtension<AFThemeExtensionV2> lerp(
ThemeExtension<AFThemeExtensionV2>? other, double t) {
if (other is! AFThemeExtensionV2) {
return this;
}
return AFThemeExtensionV2(
icon_primary:
Color.lerp(icon_primary, other.icon_primary, t) ?? icon_primary,
icon_tertiary:
Color.lerp(icon_tertiary, other.icon_tertiary, t) ?? icon_tertiary,
border_grey_quaternary:
Color.lerp(border_grey_quaternary, other.border_grey_quaternary, t) ??
border_grey_quaternary,
fill_theme_select:
Color.lerp(fill_theme_select, other.fill_theme_select, t) ??
fill_theme_select,
fill_grey_thick_alpha_1: Color.lerp(
fill_grey_thick_alpha_1, other.fill_grey_thick_alpha_1, t) ??
fill_grey_thick_alpha_1,
shadow_medium:
Color.lerp(shadow_medium, other.shadow_medium, t) ?? shadow_medium,
);
}
}
const AFThemeExtensionV2 darkAFThemeV2 = AFThemeExtensionV2(
icon_primary: Color(0xFF1F2329),
icon_tertiary: Color(0xFF99A1A8),
border_grey_quaternary: Color(0xFFE8ECF3),
fill_theme_select: Color(0x00BCF01F),
fill_grey_thick_alpha_1: Color(0x1F23290F),
shadow_medium: Color(0x1F22251F),
);
const AFThemeExtensionV2 lightAFThemeV2 = AFThemeExtensionV2(
icon_primary: Color(0xFF1F2329),
icon_tertiary: Color(0xFF99A1A8),
border_grey_quaternary: Color(0xFFE8ECF3),
fill_theme_select: Color(0x00BCF01F),
fill_grey_thick_alpha_1: Color(0x1F23290F),
shadow_medium: Color(0x1F22251F),
);
@@ -1,5 +1,5 @@
name: flowy_infra
description: A new Flutter package project.
description: AppFlowy Infra.
version: 0.0.1
homepage: https://appflowy.io
@@ -15,7 +15,7 @@ dependencies:
path: ^1.8.2
time: ">=2.0.0"
uuid: ">=2.2.2"
bloc: ^8.1.2
bloc: ^9.0.0
freezed_annotation: ^2.1.0
file_picker: ^8.0.2
file: ^7.0.0
@@ -25,40 +25,3 @@ dev_dependencies:
flutter_lints: ^3.0.1
freezed: ^2.4.7
json_serializable: ^6.5.4
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# To add assets to your package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# To add custom fonts to your package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
@@ -1,7 +1,7 @@
name: flowy_infra_ui_platform_interface
description: A new Flutter package project.
version: 0.0.1
homepage:
homepage: https://github.com/appflowy-io/appflowy
environment:
sdk: ">=2.12.0 <3.0.0"
@@ -17,5 +17,3 @@ dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.1
flutter:
@@ -1,7 +1,7 @@
name: flowy_infra_ui_web
description: A new Flutter package project.
version: 0.0.1
homepage:
homepage: https://github.com/appflowy-io/appflowy
publish_to: none
environment:
@@ -25,4 +25,4 @@ flutter:
platforms:
web:
pluginClass: FlowyInfraUIPlugin
fileName: flowy_infra_ui_web.dart
fileName: flowy_infra_ui_web.dart
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more